text stringlengths 54 60.6k |
|---|
<commit_before>This is only for testing.<commit_msg>Update the test.cpp to reflect recent changes<commit_after>This is only for
Adding a second line.
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <opencv2/opencv.hpp>
#include "calib.hpp"
int main()
{
std::ifstream ifs("list_test");
std::string line;
libcv::CalibCam calib;
calib.load("save.xml");
while(std::getline(ifs, line)) {
std::istringstream iss(line);
std::string left, right;
iss >> left >> right;
std::cout << "Remapping " << left << " and " << right << std::endl;
IplImage* imgl = cvLoadImage(left.c_str());
IplImage* imgr = cvLoadImage(right.c_str());
cv::Mat imgml(imgl);
cv::Mat imgmr(imgr);
cv::cvtColor(imgml, imgml, CV_BGR2GRAY);
cv::cvtColor(imgmr, imgmr, CV_BGR2GRAY);
calib.transform(imgml, imgmr);
cv::cvtColor(imgml, imgml, CV_GRAY2BGR);
cv::cvtColor(imgmr, imgmr, CV_GRAY2BGR);
IplImage imgpl = imgml;
IplImage imgpr = imgmr;
for(size_t i = 0; i < 480; i += 16) {
cvLine(&imgpl, cv::Point(0, i),
cv::Point(640, i), CV_RGB(0, 255, 0));
cvLine(&imgpr, cv::Point(0, i),
cv::Point(640, i), CV_RGB(0, 255, 0));
}
cvShowImage("Left", &imgpl);
cvShowImage("Right", &imgpr);
// Saving
std::string path = "trans/" + left;
cvSaveImage(path.c_str(), (void*)&imgpl);
path = "trans/" + right;
cvSaveImage(path.c_str(), (void*)&imgpr);
cvRelease((void**)&imgl);
cvRelease((void**)&imgr);
while((char)cvWaitKey(0) != ' ');
}
return 0;
}
<commit_msg>Migrated the test to opencv2.<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <opencv2/opencv.hpp>
#include "calib.hpp"
int main()
{
std::ifstream ifs("list_test");
std::string line;
libcv::CalibCam calib;
calib.load("save.xml");
while(std::getline(ifs, line)) {
std::istringstream iss(line);
std::string left, right;
iss >> left >> right;
std::cout << "Remapping " << left << " and " << right << std::endl;
cv::Mat imgml = cv::imread(left, cv::IMREAD_GRAYSCALE);
cv::Mat imgmr = cv::imread(right, cv::IMREAD_GRAYSCALE);
calib.transform(imgml, imgmr);
cv::Mat imgpl, imgpr;
cv::cvtColor(imgml, imgpl, CV_GRAY2BGR);
cv::cvtColor(imgmr, imgpr, CV_GRAY2BGR);
for(size_t i = 0; i < 480; i += 16) {
cv::line(imgpl, cv::Point(0, i),
cv::Point(640, i), cv::Scalar(0, 255, 0));
cv::line(imgpr, cv::Point(0, i),
cv::Point(640, i), cv::Scalar(0, 255, 0));
}
cv::imshow("Left", imgpl);
cv::imshow("Right", imgpr);
// Saving
std::string path = "trans/" + left;
cv::imwrite(path, imgml);
path = "trans/" + right;
cv::imwrite(path, imgmr);
while((char)cv::waitKey() != ' ');
}
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <immintrin.h>
#include "input_data.cpp"
#include "quicksort.cpp"
bool is_sorted(uint32_t* array, size_t n) {
assert(n > 0);
for (size_t i=1; i < n; i++) {
if (array[i - 1] > array[i]) {
printf("mismatch at %lu\n", i);
return false;
}
}
return true;
}
bool test(InputData& data) {
//avx512_quicksort(data.pointer(), 0, data.count() - 1);
avx512_popcnt_quicksort(data.pointer(), 0, data.count() - 1);
return is_sorted(data.pointer(), data.count());
}
int main() {
const size_t AVX512_REGISTER_SIZE = 16;
puts("Please wait, it may take a while...");
for (size_t size=2*AVX512_REGISTER_SIZE; size < 100*AVX512_REGISTER_SIZE; size += 1) {
InputAscending asc(size);
InputDescending dsc(size);
InputRandom rnd(size);
if (!test(asc)) {
printf("failed for size %lu, intput ascending\n", size);
return EXIT_FAILURE;
}
if (!test(dsc)) {
printf("failed for size %lu, intput descending\n", size);
return EXIT_FAILURE;
}
if (!test(dsc)) {
printf("failed for size %lu, intput random\n", size);
return EXIT_FAILURE;
}
}
puts("All OK");
return EXIT_SUCCESS;
}
<commit_msg>AVX512 quicksort: plug the new method into tests<commit_after>#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <immintrin.h>
#include "input_data.cpp"
#include "quicksort.cpp"
bool is_sorted(uint32_t* array, size_t n) {
assert(n > 0);
for (size_t i=1; i < n; i++) {
if (array[i - 1] > array[i]) {
printf("mismatch at %lu\n", i);
return false;
}
}
return true;
}
const size_t AVX512_REGISTER_SIZE = 16;
class Test {
public:
template <typename SORT_FN>
bool run(SORT_FN sort) {
for (size_t size=2*AVX512_REGISTER_SIZE; size < 256*AVX512_REGISTER_SIZE; size += 1) {
InputAscending asc(size);
InputDescending dsc(size);
InputRandom rnd(size);
if (!test(sort, asc)) {
printf("failed for size %lu, intput ascending\n", size);
return false;
}
if (!test(sort, dsc)) {
printf("failed for size %lu, intput descending\n", size);
return false;
}
if (!test(sort, dsc)) {
printf("failed for size %lu, intput random\n", size);
return false;
}
} // for
return true;
}
private:
template <typename SORT_FN>
bool test(SORT_FN sort, InputData& data) {
sort(data.pointer(), 0, data.count() - 1);
return is_sorted(data.pointer(), data.count());
}
};
int main() {
puts("Please wait, it might take a while...");
puts("");
Test test;
int ret = EXIT_SUCCESS;
{
printf("AVX512 base version... "); fflush(stdout);
if (test.run(avx512_quicksort)) {
puts("OK");
} else {
puts("FAILED");
ret = EXIT_FAILURE;
}
}
{
printf("AVX512 + popcnt version... "); fflush(stdout);
if (test.run(avx512_popcnt_quicksort)) {
puts("OK");
} else {
puts("FAILED");
ret = EXIT_FAILURE;
}
}
return ret;
}
<|endoftext|> |
<commit_before>// -*- mode: c++; coding: utf-8 -*-
#include <iostream>
#include <chrono>
#include <random>
#include <thread>
#include <future>
#include <regex>
#include "algorithm.hpp"
#include "cow.hpp"
#include "debug.hpp"
#include "genetic.hpp"
//#include "getopt.hpp" // needs boost/program_options
//#include "grn.hpp" // needs boost/graph
//#include "gz.hpp" // needs boost/iostreams
#include "iostr.hpp"
#include "mixin.hpp"
#include "omp.hpp"
#include "os.hpp"
#include "demangle.hpp"
#include "prandom.hpp"
#include "multiprocessing.hpp"
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
class Cls: public Singleton<Cls> {
friend Singleton<Cls>;
public:
int get_x() const {return x_;}
void print_x() const {std::cout << x_ << std::endl;}
private:
Cls(const int x): x_(x) {HERE;};
int x_ = 42;
};
inline void test_integral() {HERE;
std::cerr << "y = 1: " << wtl::integrate([](const double x){return 1.0 + x*0;}, 0, 1) << std::endl;
std::cerr << "y = x: " << wtl::integrate([](const double x){return x;}, 0, 1) << std::endl;
std::cerr << "y = sin(x): "
<< wtl::integrate([](const double x){return std::sin(x);}, 0, M_PI) << std::endl;
std::cerr << "y = cos(x): "
<< wtl::integrate([](const double x){return std::cos(x);}, 0, M_PI) << std::endl;
std::cerr << "x^2 + y^2 = 1: "
<< wtl::integrate([](const double x){return std::sqrt(1 - x * x);}, 0, 1) * 4 << std::endl;
std::cerr << "y = exp(-x^2) / sqrt(pi): "
<< wtl::integrate([](const double x)
{return std::exp(- x * x);}, 0, 10, 100) * 2 / std::sqrt(M_PI) << std::endl;
}
inline void test_validity() {HERE;
auto& ref = Cls::instance(1);
ref.print_x();
Cls::instance(2).print_x();
}
inline void test_speed() {HERE;
constexpr size_t n = 2 * 1000 * 1000;
std::vector<size_t> x(n);
double mu = 8.0;
std::poisson_distribution<size_t> dist(mu);
wtl::benchmark([&](){
for (size_t j=0; j<n; ++j) {
x[j] = dist(wtl::sfmt());
}
});
std::cerr << wtl::mean(x) << std::endl;
wtl::benchmark([&](){
for (size_t j=0; j<n; ++j) {
x[j] = dist(wtl::mt());
}
});
std::cerr << wtl::mean(x) << std::endl;
wtl::benchmark([&](){
for (size_t j=0; j<n; ++j) {
x[j] = wtl::prandom().poisson(mu);
}
});
std::cerr << wtl::mean(x) << std::endl;
size_t k = n / 50;
size_t trash = 0;
wtl::benchmark([&](){
trash += wtl::sample(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
wtl::benchmark([&](){
trash += wtl::sample_set(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
wtl::benchmark([&](){
trash += wtl::sample_fisher(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
wtl::benchmark([&](){
trash += wtl::sample_knuth(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
x.resize(6);
std::cerr << x << std::endl;
}
inline void cxx11_regex() {HERE;
std::regex patt{"(\\w+)(file)"};
std::smatch match;
auto entries = wtl::ls(".");
for (const auto& entry: entries) {
if (std::regex_search(entry, match, patt)) {
for (const auto& sm: match) {
std::cerr << sm << std::endl;
}
}
}
}
inline void cxx11_thread() {HERE;
const size_t concurrency = std::thread::hardware_concurrency();
std::cerr << "std::thread::hardware_concurrency(): "
<< concurrency << std::endl;
std::mutex display_mutex;
constexpr size_t n = 4;
wtl::Pool pool(concurrency);
for (size_t i=0; i<n; ++i) {
pool.async_thread([&]()->void {
display_mutex.lock();
std::cerr << std::this_thread::get_id() << std::endl;
display_mutex.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
});
}
pool.join();
std::vector<std::thread> threads;
wtl::Semaphore sem(concurrency);
for (size_t i=0; i<n; ++i) {
sem.lock();
threads.emplace_back([&]()->void {
display_mutex.lock();
std::cerr << std::this_thread::get_id() << std::endl;
display_mutex.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
sem.unlock();
});
}
for (auto& x: threads) {
x.join();
}
auto dist = std::uniform_real_distribution<>();
auto gen = std::bind(dist, wtl::mt());
std::vector<std::future<double> > results;
for (size_t i=0; i<n; ++i) {
results.push_back(pool.async_future(gen));
}
for (size_t i=0; i<n; ++i) {
sem.lock();
results.push_back(std::async(std::launch::async, [&] {
auto x = gen();
sem.unlock();
return x;
}));
}
for (auto& x: results) {
std::cerr << x.get() << std::endl;
}
}
inline void test_function() {HERE;
const std::string homedir(std::getenv("HOME"));
const std::string tmpdir = homedir + "/tmp";
wtl::mkdir(tmpdir);
std::cerr << "hostname: " << wtl::gethostname() << std::endl;
std::cerr << "pid: " << ::getpid() << std::endl;
std::cerr << "pwd: " << wtl::pwd() << std::endl;
std::cerr << "--------------------------------------------------\n"
<< wtl::strftime() << "\n"
<< "--------------------------------------------------\n"
<< std::endl;
test_integral();
test_validity();
test_speed();
cxx11_regex();
cxx11_thread();
}
int main(int argc, char* argv[]) {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.precision(16);
std::cerr.precision(6);
try {
std::cerr << "argc: " << argc << std::endl;
std::cerr << "argv: " << wtl::str_join(argv, argv + argc, " ") << std::endl;
test_function();
std::cerr << "EXIT_SUCCESS" << std::endl;
return EXIT_SUCCESS;
}
catch (const std::exception& e) {
std::cerr << "\n" << wtl::typestr(e) << ": " << e.what() << std::endl;
}
catch (const char* const e) {std::cerr << "\nEXCEPTION:\n" << e << std::endl;}
catch (const char* e) {std::cerr << "\nEXCEPTION:\n" << e << std::endl;}
catch (const int e) {
std::cerr << "\nint " << e << " was thrown.\nIf it is errno: "
<< std::strerror(e) << std::endl;
}
catch (...) {
std::cerr << "\nUNKNOWN ERROR OCCURED!!\nerrno "
<< errno << ": " << std::strerror(errno) << std::endl;
}
return EXIT_FAILURE;
}
<commit_msg>Remove compiler warning<commit_after>// -*- mode: c++; coding: utf-8 -*-
#include <iostream>
#include <chrono>
#include <random>
#include <thread>
#include <future>
#include <regex>
#include "algorithm.hpp"
#include "cow.hpp"
#include "debug.hpp"
#include "genetic.hpp"
//#include "getopt.hpp" // needs boost/program_options
//#include "grn.hpp" // needs boost/graph
//#include "gz.hpp" // needs boost/iostreams
#include "iostr.hpp"
#include "mixin.hpp"
#include "omp.hpp"
#include "os.hpp"
#include "demangle.hpp"
#include "prandom.hpp"
#include "multiprocessing.hpp"
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
class Cls: public Singleton<Cls> {
friend Singleton<Cls>;
public:
int get_x() const {return x_;}
void print_x() const {std::cout << x_ << std::endl;}
private:
Cls(const int x): x_(x) {HERE;};
int x_ = 42;
};
inline void test_integral() {HERE;
std::cerr << "y = 1: " << wtl::integrate([](const double x){return 1.0 + x*0;}, 0, 1) << std::endl;
std::cerr << "y = x: " << wtl::integrate([](const double x){return x;}, 0, 1) << std::endl;
std::cerr << "y = sin(x): "
<< wtl::integrate([](const double x){return std::sin(x);}, 0, M_PI) << std::endl;
std::cerr << "y = cos(x): "
<< wtl::integrate([](const double x){return std::cos(x);}, 0, M_PI) << std::endl;
std::cerr << "x^2 + y^2 = 1: "
<< wtl::integrate([](const double x){return std::sqrt(1 - x * x);}, 0, 1) * 4 << std::endl;
std::cerr << "y = exp(-x^2) / sqrt(pi): "
<< wtl::integrate([](const double x)
{return std::exp(- x * x);}, 0, 10, 100) * 2 / std::sqrt(M_PI) << std::endl;
}
inline void test_validity() {HERE;
auto& ref = Cls::instance(1);
ref.print_x();
Cls::instance(2).print_x();
}
inline void test_speed() {HERE;
constexpr size_t n = 2 * 1000 * 1000;
std::vector<size_t> x(n);
double mu = 8.0;
std::poisson_distribution<size_t> dist(mu);
wtl::benchmark([&](){
for (size_t j=0; j<n; ++j) {
x[j] = dist(wtl::sfmt());
}
});
std::cerr << wtl::mean(x) << std::endl;
wtl::benchmark([&](){
for (size_t j=0; j<n; ++j) {
x[j] = dist(wtl::mt());
}
});
std::cerr << wtl::mean(x) << std::endl;
wtl::benchmark([&](){
for (size_t j=0; j<n; ++j) {
x[j] = wtl::prandom().poisson(mu);
}
});
std::cerr << wtl::mean(x) << std::endl;
size_t k = n / 50;
size_t trash = 0;
wtl::benchmark([&](){
trash += wtl::sample(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
wtl::benchmark([&](){
trash += wtl::sample_set(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
wtl::benchmark([&](){
trash += wtl::sample_fisher(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
wtl::benchmark([&](){
trash += wtl::sample_knuth(x, k, wtl::sfmt())[0];
});
std::cerr << trash << std::endl;
x.resize(6);
std::cerr << x << std::endl;
}
inline void cxx11_regex() {HERE;
std::regex patt{"(\\w+)(file)"};
std::smatch match;
auto entries = wtl::ls(".");
for (const auto& entry: entries) {
if (std::regex_search(entry, match, patt)) {
for (const auto& sm: match) {
std::cerr << sm << std::endl;
}
}
}
}
inline void cxx11_thread() {HERE;
const size_t concurrency = std::thread::hardware_concurrency();
std::cerr << "std::thread::hardware_concurrency(): "
<< concurrency << std::endl;
std::mutex display_mutex;
constexpr size_t n = 4;
wtl::Pool pool(concurrency);
for (size_t i=0; i<n; ++i) {
pool.async_thread([&]()->void {
display_mutex.lock();
std::cerr << std::this_thread::get_id() << std::endl;
display_mutex.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
});
}
pool.join();
std::vector<std::thread> threads;
wtl::Semaphore sem(concurrency);
for (size_t i=0; i<n; ++i) {
sem.lock();
threads.emplace_back([&]()->void {
display_mutex.lock();
std::cerr << std::this_thread::get_id() << std::endl;
display_mutex.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
sem.unlock();
});
}
for (auto& x: threads) {
x.join();
}
auto dist = std::uniform_real_distribution<>();
auto gen = std::bind(dist, wtl::mt());
std::vector<std::future<double> > results;
for (size_t i=0; i<n; ++i) {
results.push_back(pool.async_future(gen));
}
for (size_t i=0; i<n; ++i) {
sem.lock();
results.push_back(std::async(std::launch::async, [&] {
auto x = gen();
sem.unlock();
return x;
}));
}
for (auto& x: results) {
std::cerr << x.get() << std::endl;
}
}
inline void test_function() {HERE;
const std::string homedir(std::getenv("HOME"));
const std::string tmpdir = homedir + "/tmp";
wtl::mkdir(tmpdir);
std::cerr << "hostname: " << wtl::gethostname() << std::endl;
std::cerr << "pid: " << ::getpid() << std::endl;
std::cerr << "pwd: " << wtl::pwd() << std::endl;
std::cerr << "--------------------------------------------------\n"
<< wtl::strftime() << "\n"
<< "--------------------------------------------------\n"
<< std::endl;
test_integral();
test_validity();
test_speed();
cxx11_regex();
cxx11_thread();
}
int main(int argc, char* argv[]) {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.precision(16);
std::cerr.precision(6);
try {
std::cerr << "argc: " << argc << std::endl;
std::cerr << "argv: " << wtl::str_join(argv, argv + argc, " ") << std::endl;
test_function();
std::cerr << "EXIT_SUCCESS" << std::endl;
return EXIT_SUCCESS;
}
catch (const std::exception& e) {
std::cerr << "\n" << wtl::typestr(e) << ": " << e.what() << std::endl;
}
catch (const char* e) {std::cerr << "\nEXCEPTION:\n" << e << std::endl;}
catch (const int e) {
std::cerr << "\nint " << e << " was thrown.\nIf it is errno: "
<< std::strerror(e) << std::endl;
}
catch (...) {
std::cerr << "\nUNKNOWN ERROR OCCURED!!\nerrno "
<< errno << ": " << std::strerror(errno) << std::endl;
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include "lua/lua.hpp"
#include <type_traits>
#include <iostream>
int main(int argc, char const *argv[])
{
try {
lua::root["my_scope"] = {
{"my_string", "some text"},
{"my_table", {
{"nested_thing", "woohoo!"}
}},
{"my_data", 0.9234},
{"my_bool", true},
{"my_chunk", lua::chunk("local world = ...; print(\"Hello \"..world..\"!\")")}
};
lua::root["my_scope"]["my_chunk"]("Matt");
} catch (lua::exception e) {
std::cout << e.what() << std::endl;
}
return 0;
}<commit_msg>Integer ambiguous with bool...<commit_after>#include "lua/lua.hpp"
#include <type_traits>
#include <iostream>
int main(int argc, char const *argv[])
{
try {
lua::root["my_scope"] = {
{"my_string", "some text"},
{"my_table", {
{"nested_thing", "woohoo!"}
}},
{"my_data", 0.9234},
{"my_bool", true},
{"my_int", 1},
{"my_chunk", lua::chunk("local world = ...; print(\"Hello \"..world..\"!\")")}
};
lua::root["my_scope"]["my_chunk"]("Matt",1);
} catch (lua::exception e) {
std::cout << e.what() << std::endl;
}
return 0;
}<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <algorithm>
#include <initializer_list>
#include <iterator>
#include <memory>
#include <string>
#include "notch.hpp"
using namespace std;
/// FullyConnectedLayer_Test breaks encapsulation of FullyConnectedLayer to
/// explore its inner state.
class FullyConnectedLayer_Test : public FullyConnectedLayer {
public:
FullyConnectedLayer_Test(size_t in, size_t out, const ActivationFunction &af)
: FullyConnectedLayer(in, out, af) {}
Array &getWeights() { return weights; }
Array &getBias() { return bias; }
Array &getInducedLocalField() { return inducedLocalField; }
Array &getActivationGrad() { return activationGrad; }
Array &getLocalGrad() { return localGrad; }
shared_ptr<ALearningPolicy> getPolicy() { return policy->copy(); }
shared_ptr<Array> getLastInputs() { return lastInputs; }
shared_ptr<Array> getLastOutputs() { return lastOutputs; }
shared_ptr<BackpropResult> getThisBPR() { return thisBPR; };
shared_ptr<BackpropResult> getNextBPR() { return nextBPR; };
bool getBuffersReadyFlag() { return buffersAreReady; };
};
#define CHECK_ARRAY_IS_INITIALIZED(name, arr_expr, expected_size) do { \
Array &(name) = arr_expr; \
auto is_zero = [](float x) { return x == Approx(0.0); }; \
CHECK( (name).size() == (expected_size) ); \
CHECK( all_of(begin(name), end(name), is_zero) ); \
} while(0)
TEST_CASE( "FullyConnectedLayer construction", "[core]" ) {
size_t n_in = 3;
size_t n_out = 2;
FullyConnectedLayer_Test fc(n_in, n_out, linearActivation);
// initialization on construction:
CHECK_ARRAY_IS_INITIALIZED(weights, fc.getWeights(), n_in*n_out);
CHECK_ARRAY_IS_INITIALIZED(bias, fc.getBias(), n_out);
CHECK_ARRAY_IS_INITIALIZED(inducedLocalField, fc.getInducedLocalField(), n_out);
CHECK_ARRAY_IS_INITIALIZED(activationGrad, fc.getActivationGrad(), n_out);
CHECK_ARRAY_IS_INITIALIZED(localGrad, fc.getLocalGrad(), n_out);
CHECK_FALSE(fc.getLastInputs());
CHECK_FALSE(fc.getLastOutputs());
CHECK_FALSE(fc.getThisBPR());
CHECK_FALSE(fc.getNextBPR());
CHECK_FALSE(fc.getBuffersReadyFlag());
}
TEST_CASE( "FullyConnectedLayer shared buffers initialization", "[core]" ) {
size_t n_in = 3;
size_t n_out = 7;
size_t n_out_next = 4;
auto rng = newRNG();
FullyConnectedLayer_Test fc(n_in, n_out, linearActivation);
FullyConnectedLayer_Test fc2(n_out, n_out_next, linearActivation);
CHECK_FALSE(fc.getBuffersReadyFlag()); // not until connectTo()
fc.connectTo(fc2);
CHECK(fc.getBuffersReadyFlag()); // now ready
CHECK(fc.getNextBPR() == fc2.getThisBPR()); // buffers are shared
CHECK(fc.getLastOutputs() == fc2.getLastInputs());
// check dimensions of the dynamically allocated arrays
CHECK_ARRAY_IS_INITIALIZED(lastInputs, *fc.getLastInputs(), n_in);
CHECK_ARRAY_IS_INITIALIZED(lastOutputs, *fc.getLastOutputs(), n_out);
// check that dimensions of this layer's BackpropResult
// match layer's dimensions
shared_ptr<BackpropResult> bpr = fc.getThisBPR();
CHECK_ARRAY_IS_INITIALIZED(bpr_propagatedErrors,
bpr->propagatedErrors, n_in);
CHECK_ARRAY_IS_INITIALIZED(bpr_weightsSensitivity,
bpr->weightSensitivity, n_in * n_out);
CHECK_ARRAY_IS_INITIALIZED(bpr_biasSensitivity,
bpr->biasSensitivity, n_out);
// check that dimensions of the next layer's BackpropResult
// match layer's dimensions
shared_ptr<BackpropResult> next_bpr = fc.getNextBPR();
CHECK_ARRAY_IS_INITIALIZED(next_bpr_propagatedErrors,
next_bpr->propagatedErrors, n_out);
CHECK_ARRAY_IS_INITIALIZED(next_bpr_weightsSensitivity,
next_bpr->weightSensitivity, n_out * n_out_next);
CHECK_ARRAY_IS_INITIALIZED(next_bpr_biasSensitivity,
next_bpr->biasSensitivity, n_out_next);
fc.init(rng, normalXavier);
CHECK(fc.getNextBPR() == fc2.getThisBPR()); // buffers are still shared
CHECK(fc.getLastOutputs() == fc2.getLastInputs());
}
TEST_CASE( "FullyConnectedLayer from weights matrix (&&)", "[core]" ) {
/// three in, two out
FullyConnectedLayer fc({1, 10, 100, 0.1, 0.01, 0.001}, // weights, row-major
{2.5, 5.0}, // bias
defaultTanh);
auto out = *fc.output({1,1,1});
CHECK(out.size() == 2u);
CHECK(out[0] == Approx(tanh(111 + 2.5)));
CHECK(out[1] == Approx(tanh(0.111 + 5.0)));
}
TEST_CASE( "FullyConnectedLayer from weights matrix (const&)", "[core]" ) {
/// three in, two out
const Array w = {1, 10, 100, 0.1, 0.01, 0.001}; // weights, row-major
const Array bias = {2.5, 5.0}; // bias
FullyConnectedLayer fc(w, bias, linearActivation);
auto out = *fc.output({1,1,1});
CHECK(out.size() == 2);
CHECK(out[0] == Approx(111 + 2.5));
CHECK(out[1] == Approx(0.111 + 5.0));
}
TEST_CASE( "FullyConnectedLayer init(weights, bias)", "[core]" ) {
FullyConnectedLayer fc(2, 1, linearActivation);
auto out_before = *fc.output({1,1});
CHECK(out_before.size() == 1);
CHECK(out_before[0] == Approx(0));
// init using r-value references
fc.init({10, 100}, {2});
auto out1 = *fc.output({1,1});
CHECK(out1.size() == 1);
CHECK(out1[0] == Approx(112));
// init using const references
const Array ws = {0.1, 0.01};
const Array b = {0};
fc.init(ws, b);
auto out2 = *fc.output({1, 2});
CHECK(out2.size() == 1);
CHECK(out2[0] == Approx(0.1*1 + 0.01*2));
}
#include "test_notch_io.hpp"
<commit_msg>test case for FixedRate updating weights<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <algorithm>
#include <initializer_list>
#include <iterator>
#include <memory>
#include <string>
#include "notch.hpp"
using namespace std;
/// FullyConnectedLayer_Test breaks encapsulation of FullyConnectedLayer to
/// explore its inner state.
class FullyConnectedLayer_Test : public FullyConnectedLayer {
public:
FullyConnectedLayer_Test(size_t in, size_t out, const ActivationFunction &af)
: FullyConnectedLayer(in, out, af) {}
Array &getWeights() { return weights; }
Array &getBias() { return bias; }
Array &getInducedLocalField() { return inducedLocalField; }
Array &getActivationGrad() { return activationGrad; }
Array &getLocalGrad() { return localGrad; }
shared_ptr<ALearningPolicy> getPolicy() { return policy->copy(); }
shared_ptr<Array> getLastInputs() { return lastInputs; }
shared_ptr<Array> getLastOutputs() { return lastOutputs; }
shared_ptr<BackpropResult> getThisBPR() { return thisBPR; };
shared_ptr<BackpropResult> getNextBPR() { return nextBPR; };
bool getBuffersReadyFlag() { return buffersAreReady; };
};
#define CHECK_ARRAY_IS_INITIALIZED(name, arr_expr, expected_size) do { \
Array &(name) = arr_expr; \
auto is_zero = [](float x) { return x == Approx(0.0); }; \
CHECK( (name).size() == (expected_size) ); \
CHECK( all_of(begin(name), end(name), is_zero) ); \
} while(0)
TEST_CASE( "FullyConnectedLayer construction", "[core]" ) {
size_t n_in = 3;
size_t n_out = 2;
FullyConnectedLayer_Test fc(n_in, n_out, linearActivation);
// initialization on construction:
CHECK_ARRAY_IS_INITIALIZED(weights, fc.getWeights(), n_in*n_out);
CHECK_ARRAY_IS_INITIALIZED(bias, fc.getBias(), n_out);
CHECK_ARRAY_IS_INITIALIZED(inducedLocalField, fc.getInducedLocalField(), n_out);
CHECK_ARRAY_IS_INITIALIZED(activationGrad, fc.getActivationGrad(), n_out);
CHECK_ARRAY_IS_INITIALIZED(localGrad, fc.getLocalGrad(), n_out);
CHECK_FALSE(fc.getLastInputs());
CHECK_FALSE(fc.getLastOutputs());
CHECK_FALSE(fc.getThisBPR());
CHECK_FALSE(fc.getNextBPR());
CHECK_FALSE(fc.getBuffersReadyFlag());
}
TEST_CASE( "FullyConnectedLayer shared buffers initialization", "[core]" ) {
size_t n_in = 3;
size_t n_out = 7;
size_t n_out_next = 4;
auto rng = newRNG();
FullyConnectedLayer_Test fc(n_in, n_out, linearActivation);
FullyConnectedLayer_Test fc2(n_out, n_out_next, linearActivation);
CHECK_FALSE(fc.getBuffersReadyFlag()); // not until connectTo()
fc.connectTo(fc2);
CHECK(fc.getBuffersReadyFlag()); // now ready
CHECK(fc.getNextBPR() == fc2.getThisBPR()); // buffers are shared
CHECK(fc.getLastOutputs() == fc2.getLastInputs());
// check dimensions of the dynamically allocated arrays
CHECK_ARRAY_IS_INITIALIZED(lastInputs, *fc.getLastInputs(), n_in);
CHECK_ARRAY_IS_INITIALIZED(lastOutputs, *fc.getLastOutputs(), n_out);
// check that dimensions of this layer's BackpropResult
// match layer's dimensions
shared_ptr<BackpropResult> bpr = fc.getThisBPR();
CHECK_ARRAY_IS_INITIALIZED(bpr_propagatedErrors,
bpr->propagatedErrors, n_in);
CHECK_ARRAY_IS_INITIALIZED(bpr_weightsSensitivity,
bpr->weightSensitivity, n_in * n_out);
CHECK_ARRAY_IS_INITIALIZED(bpr_biasSensitivity,
bpr->biasSensitivity, n_out);
// check that dimensions of the next layer's BackpropResult
// match layer's dimensions
shared_ptr<BackpropResult> next_bpr = fc.getNextBPR();
CHECK_ARRAY_IS_INITIALIZED(next_bpr_propagatedErrors,
next_bpr->propagatedErrors, n_out);
CHECK_ARRAY_IS_INITIALIZED(next_bpr_weightsSensitivity,
next_bpr->weightSensitivity, n_out * n_out_next);
CHECK_ARRAY_IS_INITIALIZED(next_bpr_biasSensitivity,
next_bpr->biasSensitivity, n_out_next);
fc.init(rng, normalXavier);
CHECK(fc.getNextBPR() == fc2.getThisBPR()); // buffers are still shared
CHECK(fc.getLastOutputs() == fc2.getLastInputs());
}
TEST_CASE( "FullyConnectedLayer from weights matrix (&&)", "[core]" ) {
/// three in, two out
FullyConnectedLayer fc({1, 10, 100, 0.1, 0.01, 0.001}, // weights, row-major
{2.5, 5.0}, // bias
defaultTanh);
auto out = *fc.output({1,1,1});
CHECK(out.size() == 2u);
CHECK(out[0] == Approx(tanh(111 + 2.5)));
CHECK(out[1] == Approx(tanh(0.111 + 5.0)));
}
TEST_CASE( "FullyConnectedLayer from weights matrix (const&)", "[core]" ) {
/// three in, two out
const Array w = {1, 10, 100, 0.1, 0.01, 0.001}; // weights, row-major
const Array bias = {2.5, 5.0}; // bias
FullyConnectedLayer fc(w, bias, linearActivation);
auto out = *fc.output({1,1,1});
CHECK(out.size() == 2);
CHECK(out[0] == Approx(111 + 2.5));
CHECK(out[1] == Approx(0.111 + 5.0));
}
TEST_CASE( "FullyConnectedLayer init(weights, bias)", "[core]" ) {
FullyConnectedLayer fc(2, 1, linearActivation);
auto out_before = *fc.output({1,1});
CHECK(out_before.size() == 1);
CHECK(out_before[0] == Approx(0));
// init using r-value references
fc.init({10, 100}, {2});
auto out1 = *fc.output({1,1});
CHECK(out1.size() == 1);
CHECK(out1[0] == Approx(112));
// init using const references
const Array ws = {0.1, 0.01};
const Array b = {0};
fc.init(ws, b);
auto out2 = *fc.output({1, 2});
CHECK(out2.size() == 1);
CHECK(out2[0] == Approx(0.1*1 + 0.01*2));
}
TEST_CASE( "FixedRate (delta rule) policy", "[core][train]") {
float eta = 0.5;
FixedRate policy(eta);
// weight updates
Array dEdw { 10, 20, 40 };
Array weights { 100, 200, 400 };
Array oldWeights = weights;
policy.correctWeights(dEdw, weights);
for (size_t i = 0; i < weights.size(); ++i) {
CHECK(weights[i] == oldWeights[i] - eta*dEdw[i]);
}
// bias updates
Array dBdw { -20, -10 };
Array bias { 100, 200 };
Array oldBias = bias;
policy.correctBias(dBdw, bias);
for (size_t i = 0; i < bias.size(); ++i) {
CHECK(bias[i] == oldBias[i] - eta*dBdw[i]);
}
}
#include "test_notch_io.hpp"
<|endoftext|> |
<commit_before>#include "chainerx/routines/reduction.h"
#include <cmath>
#include <cstdint>
#include <numeric>
#include <utility>
#include <vector>
#include <absl/types/optional.h>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/kernels/reduction.h"
#include "chainerx/macro.h"
#include "chainerx/routines/arithmetic.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/explog.h"
#include "chainerx/routines/manipulation.h"
#include "chainerx/routines/routines_util.h"
#include "chainerx/routines/statistics.h"
#include "chainerx/routines/type_util.h"
#include "chainerx/shape.h"
namespace chainerx {
Array Sum(const Array& a, const OptionalAxes& axis, bool keepdims) {
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a.dtype();
}
Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<SumKernel>(a, sorted_axis, out);
}
BackwardBuilder bb{"sum", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));
if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
Shape out_shape_broadcastable = gout.shape();
for (auto axis : sorted_axis) {
out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
}
bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape);
} else {
bctx.input_grad() = gout.BroadcastTo(in_shape);
}
});
}
bb.Finalize();
return out;
}
Array Softmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis.has_value() ? axis : OptionalAxes{1}, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array exps = Exp(x_cast - xmax);
Array sums = Sum(exps, sorted_axis, true);
return exps * Reciprocal(sums);
}
Array LogSumExp(const Array& x, const OptionalAxes& axis, bool keepdims) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array logs = Log(Sum(Exp(x_cast - xmax), sorted_axis, keepdims));
return (keepdims ? xmax : Squeeze(xmax, axis)) + logs;
}
Array LogSoftmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
return x_cast - LogSumExp(x_cast, axis.has_value() ? axis : OptionalAxes{1}, true);
}
Array Cumsum(const Array& a, absl::optional<int8_t> axis) {
int8_t axis_norm;
Array a_reshaped{};
if (axis.has_value()) {
axis_norm = internal::NormalizeAxis(*axis, a.ndim());
a_reshaped = a;
} else {
axis_norm = 0;
// TODO(imanishi): Fix after chainerx::Ravel is supported.
a_reshaped = a.Reshape(Shape{a.GetTotalSize()});
}
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a_reshaped.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a_reshaped.dtype();
}
const Array& out = Empty(a_reshaped.shape(), out_dtype, a_reshaped.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<CumsumKernel>(a_reshaped, axis_norm, out);
}
BackwardBuilder bb{"cumsum", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([axis, axis_norm, in_shape = a.shape()](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
if (axis.has_value()) {
bctx.input_grad() = Flip(Cumsum(Flip(gout, axis_norm), axis_norm), axis_norm);
} else {
Array input_grad = Flip(Cumsum(Flip(gout, 0), 0), 0);
bctx.input_grad() = input_grad.Reshape(in_shape);
}
});
}
bb.Finalize();
return out;
}
} // namespace chainerx
<commit_msg>Modify backward<commit_after>#include "chainerx/routines/reduction.h"
#include <cmath>
#include <cstdint>
#include <numeric>
#include <utility>
#include <vector>
#include <absl/types/optional.h>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/kernels/reduction.h"
#include "chainerx/macro.h"
#include "chainerx/routines/arithmetic.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/explog.h"
#include "chainerx/routines/manipulation.h"
#include "chainerx/routines/routines_util.h"
#include "chainerx/routines/statistics.h"
#include "chainerx/routines/type_util.h"
#include "chainerx/shape.h"
namespace chainerx {
Array Sum(const Array& a, const OptionalAxes& axis, bool keepdims) {
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a.dtype();
}
Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<SumKernel>(a, sorted_axis, out);
}
BackwardBuilder bb{"sum", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));
if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
Shape out_shape_broadcastable = gout.shape();
for (auto axis : sorted_axis) {
out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
}
bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape);
} else {
bctx.input_grad() = gout.BroadcastTo(in_shape);
}
});
}
bb.Finalize();
return out;
}
Array Softmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis.has_value() ? axis : OptionalAxes{1}, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array exps = Exp(x_cast - xmax);
Array sums = Sum(exps, sorted_axis, true);
return exps * Reciprocal(sums);
}
Array LogSumExp(const Array& x, const OptionalAxes& axis, bool keepdims) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array logs = Log(Sum(Exp(x_cast - xmax), sorted_axis, keepdims));
return (keepdims ? xmax : Squeeze(xmax, axis)) + logs;
}
Array LogSoftmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
return x_cast - LogSumExp(x_cast, axis.has_value() ? axis : OptionalAxes{1}, true);
}
Array Cumsum(const Array& a, absl::optional<int8_t> axis) {
int8_t axis_norm;
Array a_reshaped{};
if (axis.has_value()) {
axis_norm = internal::NormalizeAxis(*axis, a.ndim());
a_reshaped = a;
} else {
axis_norm = 0;
// TODO(imanishi): Fix after chainerx::Ravel is supported.
a_reshaped = a.Reshape(Shape{a.GetTotalSize()});
}
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a_reshaped.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a_reshaped.dtype();
}
const Array& out = Empty(a_reshaped.shape(), out_dtype, a_reshaped.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<CumsumKernel>(a_reshaped, axis_norm, out);
}
BackwardBuilder bb{"cumsum", a_reshaped, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([axis, axis_norm, in_shape = a_reshaped.shape()](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
if (axis.has_value()) {
bctx.input_grad() = Flip(Cumsum(Flip(gout, axis_norm), axis_norm), axis_norm);
} else {
Array input_grad = Flip(Cumsum(Flip(gout, 0), 0), 0);
bctx.input_grad() = input_grad.Reshape(in_shape);
}
});
}
bb.Finalize();
return out;
}
} // namespace chainerx
<|endoftext|> |
<commit_before>/*
* ©LAAS-CNRS (2008-2009)
*
* contributor(s) : Séverin Lemaignan <severin.lemaignan@laas.fr>
*
* This software is a computer program whose purpose is to interface
* with an ontology server in a robotics context.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*
*/
#include <string>
#include <sstream>
#include "oro.h"
using namespace std;
namespace oro {
Statement::Statement(const Concept& _subject, const Property& _predicate, const Concept& _object):subject(_subject), predicate(_predicate), object(_object), literal_object(""), isObjectLiteral(false){
_originalStmt = subject.to_string() + " " + predicate.to_string() + " " + (isObjectLiteral?literal_object:object.to_string());
}
Statement::Statement(const Concept& _subject, const Property& _predicate, const std::string& _object):subject(_subject), predicate(_predicate), object(Concept::nothing), literal_object(_object), isObjectLiteral(true){
_originalStmt = subject.to_string() + " " + predicate.to_string() + " " + (isObjectLiteral?literal_object:object.to_string());
}
/**
* Creates a new statement from its literal string representation.
*/
Statement::Statement(const string& stmt) : subject(""), predicate(""), object(""), literal_object(""), isObjectLiteral(false){
_originalStmt = stmt;
string buf = stmt; // Have a buffer string
//stringstream ss(stmt); // Insert the string into a stream
vector<string> tokens; // Create vector to hold the parts of the statement
//while (ss >> buf) //nice and efficient to tokenize a string on the spaces
// tokens.push_back(buf);
//pas super élégant...
int cutAt;
//First token (subject)
cutAt = buf.find(" ");
tokens.push_back(buf.substr(0,cutAt));
//if(tokens[0].find(":") != string::npos){
// tokens[0] = tokens[0].substr(tokens[0].find(":"));
//}
subject = Concept(tokens[0]);
//Second token (predicate)
buf = buf.substr(cutAt+1);
cutAt = buf.find(" ");
tokens.push_back(buf.substr(0,cutAt));
predicate = Property(tokens[1]);
//Third token (object)
buf = buf.substr(cutAt+1);
tokens.push_back(buf);
//if (tokens.size() != 3)
// throw InvalidStatementException();
//TODO Ugly... if the last token simply contains a semicolon or the predicate is subClassOf, we assume it's a concept. Need to be improved!
if((tokens[2].find(":") != string::npos) || tokens[1] == "rdfs:subClassOf"){
tokens[2] = tokens[2].substr(tokens[2].find(":"));
object = Concept(tokens[2]);
isObjectLiteral = false;
}
else {
object = tokens[2];
isObjectLiteral = true;
}
}
/**
* Returns a computer-friendly string describing the statement.
*/
std::string Statement::to_string() const {
//return subject.to_string() + " " + predicate.to_string() + " " + (isObjectLiteral?literal_object:object.to_string());
return _originalStmt;
}
}
<commit_msg>Fixed a bad bug in the Statement factory. The code there is still in bad state.<commit_after>/*
* ©LAAS-CNRS (2008-2009)
*
* contributor(s) : Séverin Lemaignan <severin.lemaignan@laas.fr>
*
* This software is a computer program whose purpose is to interface
* with an ontology server in a robotics context.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*
*/
#include <string>
#include <sstream>
#include "oro.h"
using namespace std;
namespace oro {
Statement::Statement(const Concept& _subject, const Property& _predicate, const Concept& _object):subject(_subject), predicate(_predicate), object(_object), literal_object(""), isObjectLiteral(false){
_originalStmt = subject.to_string() + " " + predicate.to_string() + " " + (isObjectLiteral?literal_object:object.to_string());
}
Statement::Statement(const Concept& _subject, const Property& _predicate, const std::string& _object):subject(_subject), predicate(_predicate), object(Concept::nothing), literal_object(_object), isObjectLiteral(true){
_originalStmt = subject.to_string() + " " + predicate.to_string() + " " + (isObjectLiteral?literal_object:object.to_string());
}
/**
* Creates a new statement from its literal string representation.
*/
Statement::Statement(const string& stmt) : subject(""), predicate(""), object(""), literal_object(""), isObjectLiteral(false){
_originalStmt = stmt;
string buf = stmt; // Have a buffer string
//stringstream ss(stmt); // Insert the string into a stream
vector<string> tokens; // Create vector to hold the parts of the statement
//while (ss >> buf) //nice and efficient to tokenize a string on the spaces
// tokens.push_back(buf);
//pas super élégant...
int cutAt;
//First token (subject)
cutAt = buf.find(" ");
tokens.push_back(buf.substr(0,cutAt));
//if(tokens[0].find(":") != string::npos){
// tokens[0] = tokens[0].substr(tokens[0].find(":"));
//}
subject = Concept(tokens[0]);
//Second token (predicate)
buf = buf.substr(cutAt+1);
cutAt = buf.find(" ");
tokens.push_back(buf.substr(0,cutAt));
predicate = Property(tokens[1]);
//Third token (object)
buf = buf.substr(cutAt+1);
tokens.push_back(buf);
//Problem: the third argument may contain spaces
//if (tokens.size() != 3)
// throw InvalidStatementException();
//TODO Ugly... if the last token contains a semicolon or the predicate is subClassOf, we assume it's a concept. Need to be improved!
if(tokens[2].find(":") != string::npos){
tokens[2] = tokens[2].substr(tokens[2].find(":"));
object = Concept(tokens[2]);
isObjectLiteral = false;
}
else if (tokens[1] == "rdfs:subClassOf") {
object = Concept(tokens[2]);
isObjectLiteral = false;
}
else {
object = tokens[2];
isObjectLiteral = true;
}
}
/**
* Returns a computer-friendly string describing the statement.
*/
std::string Statement::to_string() const {
//return subject.to_string() + " " + predicate.to_string() + " " + (isObjectLiteral?literal_object:object.to_string());
return _originalStmt;
}
}
<|endoftext|> |
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rank_estimators.h"
#include "cf.h"
#include "cf_configuration.h"
#include "qprocess.h"
#include "query_capture.h"
#include "uri_capture.h"
#include "db_uri_record.h"
#include "urlmatch.h"
#include <assert.h>
#include <math.h>
#include <iostream>
using lsh::qprocess;
using sp::urlmatch;
namespace seeks_plugins
{
/*- rank_estimator -*/
void rank_estimator::fetch_user_db_record(const std::string &query,
std::vector<db_record*> &records)
{
static std::string qc_str = "query-capture";
// strip query.
std::string q = query_capture_element::no_command_query(query);
// generate query fragments.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(q,0,5,features); //TODO: from configuration (5).
// fetch records from the user DB.
hash_multimap<uint32_t,DHTKey,id_hash_uint>::const_iterator hit = features.begin();
while (hit!=features.end())
{
std::string key_str = (*hit).second.to_rstring();
db_record *dbr = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
if (dbr)
records.push_back(dbr);
++hit;
}
}
/*- simple_re -*/
simple_re::simple_re()
:rank_estimator()
{
}
simple_re::~simple_re()
{
}
void simple_re::extract_queries(const std::vector<db_record*> &records,
hash_map<const char*,query_data*,hash<const char*>,eqstr> &qdata)
{
static std::string qc_str = "query-capture";
// iterate records and gather queries and data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit;
std::vector<db_record*>::const_iterator vit = records.begin();
while (vit!=records.end())
{
db_query_record *dbqr = static_cast<db_query_record*>((*vit));
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit
= dbqr->_related_queries.begin();
while (qit!=dbqr->_related_queries.end())
{
query_data *qd = (*qit).second;
if ((hit=qdata.find(qd->_query.c_str()))==qdata.end())
{
if (qd->_radius == 0) // contains the data.
qdata.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),
new query_data(qd)));
else
{
// data are in lower radius records.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(qd->_query,0,0,features);
// XXX: when the query contains > 8 words there are many features generated
// for the same radius. The original query data can be fetched from any
// of the generated features, so we take the first one.
assert(features.size()>=1);
std::string key_str = (*features.begin()).second.to_rstring();
db_record *dbr_data = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
assert(dbr_data != NULL); // beware.
db_query_record *dbqr_data = static_cast<db_query_record*>(dbr_data);
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit2
= dbqr_data->_related_queries.begin();
while (qit2!=dbqr_data->_related_queries.end())
{
if ((*qit2).second->_radius == 0
&& (*qit2).second->_query == qd->_query)
{
query_data *dbqrc = new query_data((*qit2).second);
qdata.insert(std::pair<const char*,query_data*>(dbqrc->_query.c_str(),
dbqrc));
break;
}
++qit2;
}
delete dbqr_data;
}
}
++qit;
}
++vit;
}
}
void simple_re::estimate_ranks(const std::string &query,
std::vector<search_snippet*> &snippets)
{
// fetch records from user DB.
std::vector<db_record*> records;
fetch_user_db_record(query,records);
//std::cerr << "[estimate_ranks]: number of fetched records: " << records.size() << std::endl;
// extract queries.
hash_map<const char*,query_data*,hash<const char*>,eqstr> qdata;
extract_queries(records,qdata);
//std::cerr << "[estimate_ranks]: number of extracted queries: " << qdata.size() << std::endl;
// destroy records.
std::vector<db_record*>::iterator rit = records.begin();
while (rit!=records.end())
{
db_record *dbr = (*rit);
rit = records.erase(rit);
delete dbr;
}
// gather normalizing values.
int i = 0;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit
= qdata.begin();
float q_vurl_hits[qdata.size()];
while (hit!=qdata.end())
{
q_vurl_hits[i++] = (*hit).second->vurls_total_hits();
++hit;
}
float sum_se_ranks = 0.0;
std::vector<search_snippet*>::iterator vit = snippets.begin();
while (vit!=snippets.end())
{
sum_se_ranks += (*vit)->_seeks_rank;
++vit;
}
// get number of captured URIs.
uint64_t nuri = 0;
if (cf::_uc_plugin)
nuri = static_cast<uri_capture*>(cf::_uc_plugin)->_nr;
// estimate each URL's rank.
int j = 0;
size_t ns = snippets.size();
float posteriors[ns];
float sum_posteriors = 0.0;
vit = snippets.begin();
while (vit!=snippets.end())
{
std::string url = (*vit)->_url;
std::transform(url.begin(),url.end(),url.begin(),tolower);
//std::string surl = urlmatch::strip_url(url);
std::string host, path;
urlmatch::parse_url_host_and_path(url,host,path);
host = urlmatch::strip_url(host);
i = 0;
posteriors[j] = 0.0;
hit = qdata.begin();
while (hit!=qdata.end())
{
float qpost = estimate_rank((*vit),ns,(*hit).second,q_vurl_hits[i++],
url,host,path);
//qpost *= (*vit)->_seeks_rank / sum_se_ranks; // account for URL rank in results from search engines.
qpost *= 1.0/static_cast<float>(((*hit).second->_radius + 1.0)); // account for distance to original query.
posteriors[j] += qpost; // boosting over similar queries.
//std::cerr << "url: " << (*vit)->_url << " -- qpost: " << qpost << std::endl;
++hit;
}
// estimate the url prior.
bool personalized = false;
float prior = 1.0;
if (nuri != 0 && (*vit)->_doc_type != VIDEO_THUMB && (*vit)->_doc_type != TWEET) // not empty or not type with not enought competition on domains.
prior = estimate_prior(url,host,nuri,personalized);
if (personalized)
(*vit)->_personalized = true;
posteriors[j] *= prior;
//std::cerr << "url: " << (*vit)->_url << " -- prior: " << prior << " -- posterior: " << posteriors[j] << std::endl;
sum_posteriors += posteriors[j++];
++vit;
}
// wrapup.
if (sum_posteriors > 0.0)
{
for (size_t k=0; k<ns; k++)
{
posteriors[k] /= sum_posteriors; // normalize.
snippets.at(k)->_seeks_rank = posteriors[k];
//std::cerr << "url: " << snippets.at(k)->_url << " -- seeks_rank: " << snippets.at(k)->_seeks_rank << std::endl;
}
}
// destroy query data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator hit2;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator chit;
hit2 = qdata.begin();
while (hit2!=qdata.end())
{
query_data *qd = (*hit2).second;
chit = hit2;
++hit2;
delete qd;
}
}
float simple_re::estimate_rank(search_snippet *s, const int &ns,
const query_data *qd,
const float &total_hits,
const std::string &surl,
const std::string &host, const std::string &path)
{
float posterior = 0.0;
// URL.
vurl_data *vd = qd->find_vurl(surl);
if (!vd)
//posterior = 1.0 / (log(static_cast<float>(ns) + 1.0) + 1.0); // XXX: may replace ns with a less discriminative value.
posterior = 1.0 / (log(total_hits + 1.0) + ns);
else
{
posterior = (log(vd->_hits + 1.0) + 1.0)/ (log(total_hits + 1.0) + ns);
s->_personalized = true;
}
// host.
vd = qd->find_vurl(host);
if (!vd || s->_doc_type == VIDEO_THUMB || s->_doc_type == TWEET) // empty or type with not enough competition on domains.
posterior *= cf_configuration::_config->_domain_name_weight
/ static_cast<float>(ns); // XXX: may replace ns with a less discriminative value.
else
{
posterior *= cf_configuration::_config->_domain_name_weight
* (log(vd->_hits + 1.0) + 1.0)
/ (log(total_hits + 1.0) + ns); // with domain-name weight factor.
s->_personalized = true;
}
//std::cerr << "posterior: " << posterior << std::endl;
return posterior;
}
float simple_re::estimate_prior(const std::string &surl,
const std::string &host,
const uint64_t &nuri,
bool &personalized)
{
static std::string uc_str = "uri-capture";
float prior = 0.0;
float furi = static_cast<float>(nuri);
db_record *dbr = seeks_proxy::_user_db->find_dbr(surl,uc_str);
if (!dbr)
prior = 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior = (log(uc_dbr->_hits + 1.0) + 1.0)/ log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
dbr = seeks_proxy::_user_db->find_dbr(host,uc_str);
if (!dbr)
prior *= 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior *= (log(uc_dbr->_hits + 1.0) + 1.0) / log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
return prior;
}
} /* end of namespace. */
<commit_msg>cancel the cf prior on images as there is not enough competition among domains<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rank_estimators.h"
#include "cf.h"
#include "cf_configuration.h"
#include "qprocess.h"
#include "query_capture.h"
#include "uri_capture.h"
#include "db_uri_record.h"
#include "urlmatch.h"
#include <assert.h>
#include <math.h>
#include <iostream>
using lsh::qprocess;
using sp::urlmatch;
namespace seeks_plugins
{
/*- rank_estimator -*/
void rank_estimator::fetch_user_db_record(const std::string &query,
std::vector<db_record*> &records)
{
static std::string qc_str = "query-capture";
// strip query.
std::string q = query_capture_element::no_command_query(query);
// generate query fragments.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(q,0,5,features); //TODO: from configuration (5).
// fetch records from the user DB.
hash_multimap<uint32_t,DHTKey,id_hash_uint>::const_iterator hit = features.begin();
while (hit!=features.end())
{
std::string key_str = (*hit).second.to_rstring();
db_record *dbr = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
if (dbr)
records.push_back(dbr);
++hit;
}
}
/*- simple_re -*/
simple_re::simple_re()
:rank_estimator()
{
}
simple_re::~simple_re()
{
}
void simple_re::extract_queries(const std::vector<db_record*> &records,
hash_map<const char*,query_data*,hash<const char*>,eqstr> &qdata)
{
static std::string qc_str = "query-capture";
// iterate records and gather queries and data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit;
std::vector<db_record*>::const_iterator vit = records.begin();
while (vit!=records.end())
{
db_query_record *dbqr = static_cast<db_query_record*>((*vit));
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit
= dbqr->_related_queries.begin();
while (qit!=dbqr->_related_queries.end())
{
query_data *qd = (*qit).second;
if ((hit=qdata.find(qd->_query.c_str()))==qdata.end())
{
if (qd->_radius == 0) // contains the data.
qdata.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),
new query_data(qd)));
else
{
// data are in lower radius records.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(qd->_query,0,0,features);
// XXX: when the query contains > 8 words there are many features generated
// for the same radius. The original query data can be fetched from any
// of the generated features, so we take the first one.
assert(features.size()>=1);
std::string key_str = (*features.begin()).second.to_rstring();
db_record *dbr_data = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
assert(dbr_data != NULL); // beware.
db_query_record *dbqr_data = static_cast<db_query_record*>(dbr_data);
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit2
= dbqr_data->_related_queries.begin();
while (qit2!=dbqr_data->_related_queries.end())
{
if ((*qit2).second->_radius == 0
&& (*qit2).second->_query == qd->_query)
{
query_data *dbqrc = new query_data((*qit2).second);
qdata.insert(std::pair<const char*,query_data*>(dbqrc->_query.c_str(),
dbqrc));
break;
}
++qit2;
}
delete dbqr_data;
}
}
++qit;
}
++vit;
}
}
void simple_re::estimate_ranks(const std::string &query,
std::vector<search_snippet*> &snippets)
{
// fetch records from user DB.
std::vector<db_record*> records;
fetch_user_db_record(query,records);
//std::cerr << "[estimate_ranks]: number of fetched records: " << records.size() << std::endl;
// extract queries.
hash_map<const char*,query_data*,hash<const char*>,eqstr> qdata;
extract_queries(records,qdata);
//std::cerr << "[estimate_ranks]: number of extracted queries: " << qdata.size() << std::endl;
// destroy records.
std::vector<db_record*>::iterator rit = records.begin();
while (rit!=records.end())
{
db_record *dbr = (*rit);
rit = records.erase(rit);
delete dbr;
}
// gather normalizing values.
int i = 0;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit
= qdata.begin();
float q_vurl_hits[qdata.size()];
while (hit!=qdata.end())
{
q_vurl_hits[i++] = (*hit).second->vurls_total_hits();
++hit;
}
float sum_se_ranks = 0.0;
std::vector<search_snippet*>::iterator vit = snippets.begin();
while (vit!=snippets.end())
{
sum_se_ranks += (*vit)->_seeks_rank;
++vit;
}
// get number of captured URIs.
uint64_t nuri = 0;
if (cf::_uc_plugin)
nuri = static_cast<uri_capture*>(cf::_uc_plugin)->_nr;
// estimate each URL's rank.
int j = 0;
size_t ns = snippets.size();
float posteriors[ns];
float sum_posteriors = 0.0;
vit = snippets.begin();
while (vit!=snippets.end())
{
std::string url = (*vit)->_url;
std::transform(url.begin(),url.end(),url.begin(),tolower);
//std::string surl = urlmatch::strip_url(url);
std::string host, path;
urlmatch::parse_url_host_and_path(url,host,path);
host = urlmatch::strip_url(host);
i = 0;
posteriors[j] = 0.0;
hit = qdata.begin();
while (hit!=qdata.end())
{
float qpost = estimate_rank((*vit),ns,(*hit).second,q_vurl_hits[i++],
url,host,path);
//qpost *= (*vit)->_seeks_rank / sum_se_ranks; // account for URL rank in results from search engines.
qpost *= 1.0/static_cast<float>(((*hit).second->_radius + 1.0)); // account for distance to original query.
posteriors[j] += qpost; // boosting over similar queries.
//std::cerr << "url: " << (*vit)->_url << " -- qpost: " << qpost << std::endl;
++hit;
}
// estimate the url prior.
bool personalized = false;
float prior = 1.0;
if (nuri != 0 && (*vit)->_doc_type != VIDEO_THUMB
&& (*vit)->_doc_type != TWEET && (*vit)->_doc_type != IMAGE) // not empty or type with not enought competition on domains.
prior = estimate_prior(url,host,nuri,personalized);
if (personalized)
(*vit)->_personalized = true;
posteriors[j] *= prior;
//std::cerr << "url: " << (*vit)->_url << " -- prior: " << prior << " -- posterior: " << posteriors[j] << std::endl;
sum_posteriors += posteriors[j++];
++vit;
}
// wrapup.
if (sum_posteriors > 0.0)
{
for (size_t k=0; k<ns; k++)
{
posteriors[k] /= sum_posteriors; // normalize.
snippets.at(k)->_seeks_rank = posteriors[k];
//std::cerr << "url: " << snippets.at(k)->_url << " -- seeks_rank: " << snippets.at(k)->_seeks_rank << std::endl;
}
}
// destroy query data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator hit2;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator chit;
hit2 = qdata.begin();
while (hit2!=qdata.end())
{
query_data *qd = (*hit2).second;
chit = hit2;
++hit2;
delete qd;
}
}
float simple_re::estimate_rank(search_snippet *s, const int &ns,
const query_data *qd,
const float &total_hits,
const std::string &surl,
const std::string &host, const std::string &path)
{
float posterior = 0.0;
// URL.
vurl_data *vd = qd->find_vurl(surl);
if (!vd)
//posterior = 1.0 / (log(static_cast<float>(ns) + 1.0) + 1.0); // XXX: may replace ns with a less discriminative value.
posterior = 1.0 / (log(total_hits + 1.0) + ns);
else
{
posterior = (log(vd->_hits + 1.0) + 1.0)/ (log(total_hits + 1.0) + ns);
s->_personalized = true;
}
// host.
vd = qd->find_vurl(host);
if (!vd || s->_doc_type == VIDEO_THUMB || s->_doc_type == TWEET) // empty or type with not enough competition on domains.
posterior *= cf_configuration::_config->_domain_name_weight
/ static_cast<float>(ns); // XXX: may replace ns with a less discriminative value.
else
{
posterior *= cf_configuration::_config->_domain_name_weight
* (log(vd->_hits + 1.0) + 1.0)
/ (log(total_hits + 1.0) + ns); // with domain-name weight factor.
s->_personalized = true;
}
//std::cerr << "posterior: " << posterior << std::endl;
return posterior;
}
float simple_re::estimate_prior(const std::string &surl,
const std::string &host,
const uint64_t &nuri,
bool &personalized)
{
static std::string uc_str = "uri-capture";
float prior = 0.0;
float furi = static_cast<float>(nuri);
db_record *dbr = seeks_proxy::_user_db->find_dbr(surl,uc_str);
if (!dbr)
prior = 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior = (log(uc_dbr->_hits + 1.0) + 1.0)/ log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
dbr = seeks_proxy::_user_db->find_dbr(host,uc_str);
if (!dbr)
prior *= 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior *= (log(uc_dbr->_hits + 1.0) + 1.0) / log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
return prior;
}
} /* end of namespace. */
<|endoftext|> |
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rank_estimators.h"
#include "cf.h"
#include "cf_configuration.h"
#include "qprocess.h"
#include "query_capture.h"
#include "uri_capture.h"
#include "db_uri_record.h"
#include "urlmatch.h"
#include <assert.h>
#include <math.h>
#include <iostream>
using lsh::qprocess;
using sp::urlmatch;
namespace seeks_plugins
{
/*- rank_estimator -*/
void rank_estimator::fetch_user_db_record(const std::string &query,
std::vector<db_record*> &records)
{
static std::string qc_str = "query-capture";
// strip query.
std::string q = query_capture_element::no_command_query(query);
// generate query fragments.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(q,0,5,features); //TODO: from configuration (5).
// fetch records from the user DB.
hash_multimap<uint32_t,DHTKey,id_hash_uint>::const_iterator hit = features.begin();
while (hit!=features.end())
{
std::string key_str = (*hit).second.to_rstring();
db_record *dbr = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
if (dbr)
records.push_back(dbr);
++hit;
}
}
void rank_estimator::extract_queries(const std::vector<db_record*> &records,
hash_map<const char*,query_data*,hash<const char*>,eqstr> &qdata)
{
static std::string qc_str = "query-capture";
// iterate records and gather queries and data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit;
std::vector<db_record*>::const_iterator vit = records.begin();
while (vit!=records.end())
{
db_query_record *dbqr = static_cast<db_query_record*>((*vit));
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit
= dbqr->_related_queries.begin();
while (qit!=dbqr->_related_queries.end())
{
query_data *qd = (*qit).second;
if ((hit=qdata.find(qd->_query.c_str()))==qdata.end())
{
if (qd->_radius == 0) // contains the data.
qdata.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),
new query_data(qd)));
else
{
// data are in lower radius records.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(qd->_query,0,0,features);
// XXX: when the query contains > 8 words there are many features generated
// for the same radius. The original query data can be fetched from any
// of the generated features, so we take the first one.
if (features.empty()) // this should never happen.
{
++qit;
continue;
}
std::string key_str = (*features.begin()).second.to_rstring();
db_record *dbr_data = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
if (!dbr_data) // this should never happen.
{
++qit;
continue;
}
db_query_record *dbqr_data = static_cast<db_query_record*>(dbr_data);
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit2
= dbqr_data->_related_queries.begin();
while (qit2!=dbqr_data->_related_queries.end())
{
if ((*qit2).second->_radius == 0
&& (*qit2).second->_query == qd->_query)
{
query_data *dbqrc = new query_data((*qit2).second);
dbqrc->_radius = qd->_radius; // update radius relatively to original query.
qdata.insert(std::pair<const char*,query_data*>(dbqrc->_query.c_str(),
dbqrc));
break;
}
++qit2;
}
delete dbqr_data;
}
}
++qit;
}
++vit;
}
}
/*- simple_re -*/
simple_re::simple_re()
:rank_estimator()
{
}
simple_re::~simple_re()
{
}
void simple_re::estimate_ranks(const std::string &query,
std::vector<search_snippet*> &snippets)
{
// fetch records from user DB.
std::vector<db_record*> records;
rank_estimator::fetch_user_db_record(query,records);
//std::cerr << "[estimate_ranks]: number of fetched records: " << records.size() << std::endl;
// extract queries.
hash_map<const char*,query_data*,hash<const char*>,eqstr> qdata;
rank_estimator::extract_queries(records,qdata);
//std::cerr << "[estimate_ranks]: number of extracted queries: " << qdata.size() << std::endl;
// destroy records.
std::vector<db_record*>::iterator rit = records.begin();
while (rit!=records.end())
{
db_record *dbr = (*rit);
rit = records.erase(rit);
delete dbr;
}
// gather normalizing values.
int i = 0;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit
= qdata.begin();
float q_vurl_hits[qdata.size()];
while (hit!=qdata.end())
{
q_vurl_hits[i++] = (*hit).second->vurls_total_hits();
++hit;
}
float sum_se_ranks = 0.0;
std::vector<search_snippet*>::iterator vit = snippets.begin();
while (vit!=snippets.end())
{
sum_se_ranks += (*vit)->_seeks_rank;
++vit;
}
// get number of captured URIs.
uint64_t nuri = 0;
if (cf::_uc_plugin)
nuri = static_cast<uri_capture*>(cf::_uc_plugin)->_nr;
// estimate each URL's rank.
int j = 0;
size_t ns = snippets.size();
float posteriors[ns];
float sum_posteriors = 0.0;
vit = snippets.begin();
while (vit!=snippets.end())
{
std::string url = (*vit)->_url;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string host, path;
urlmatch::parse_url_host_and_path(url,host,path);
host = urlmatch::strip_url(host);
i = 0;
posteriors[j] = 0.0;
hit = qdata.begin();
while (hit!=qdata.end())
{
float qpost = estimate_rank((*vit),ns,(*hit).second,q_vurl_hits[i++],
url,host,path);
//qpost *= (*vit)->_seeks_rank / sum_se_ranks; // account for URL rank in results from search engines.
qpost *= 1.0/static_cast<float>(((*hit).second->_radius + 1.0)); // account for distance to original query.
posteriors[j] += qpost; // boosting over similar queries.
//std::cerr << "url: " << (*vit)->_url << " -- qpost: " << qpost << std::endl;
++hit;
}
// estimate the url prior.
bool personalized = false;
float prior = 1.0;
if (nuri != 0 && (*vit)->_doc_type != VIDEO_THUMB
&& (*vit)->_doc_type != TWEET && (*vit)->_doc_type != IMAGE) // not empty or type with not enought competition on domains.
prior = estimate_prior(url,host,nuri,personalized);
if (personalized)
(*vit)->_personalized = true;
posteriors[j] *= prior;
//std::cerr << "url: " << (*vit)->_url << " -- prior: " << prior << " -- posterior: " << posteriors[j] << std::endl;
sum_posteriors += posteriors[j++];
++vit;
}
// wrapup.
if (sum_posteriors > 0.0)
{
for (size_t k=0; k<ns; k++)
{
posteriors[k] /= sum_posteriors; // normalize.
snippets.at(k)->_seeks_rank = posteriors[k];
//std::cerr << "url: " << snippets.at(k)->_url << " -- seeks_rank: " << snippets.at(k)->_seeks_rank << std::endl;
}
}
// destroy query data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator hit2;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator chit;
hit2 = qdata.begin();
while (hit2!=qdata.end())
{
query_data *qd = (*hit2).second;
chit = hit2;
++hit2;
delete qd;
}
}
float simple_re::estimate_rank(search_snippet *s, const int &ns,
const query_data *qd,
const float &total_hits,
const std::string &surl,
const std::string &host, const std::string &path)
{
float posterior = 0.0;
// URL.
vurl_data *vd = qd->find_vurl(surl);
if (!vd)
//posterior = 1.0 / (log(static_cast<float>(ns) + 1.0) + 1.0); // XXX: may replace ns with a less discriminative value.
posterior = 1.0 / (log(total_hits + 1.0) + ns);
else
{
posterior = (log(vd->_hits + 1.0) + 1.0)/ (log(total_hits + 1.0) + ns);
s->_personalized = true;
}
// host.
vd = qd->find_vurl(host);
if (!vd || s->_doc_type == VIDEO_THUMB || s->_doc_type == TWEET) // empty or type with not enough competition on domains.
posterior *= cf_configuration::_config->_domain_name_weight
/ static_cast<float>(ns); // XXX: may replace ns with a less discriminative value.
else
{
posterior *= cf_configuration::_config->_domain_name_weight
* (log(vd->_hits + 1.0) + 1.0)
/ (log(total_hits + 1.0) + ns); // with domain-name weight factor.
s->_personalized = true;
}
//std::cerr << "posterior: " << posterior << std::endl;
return posterior;
}
float simple_re::estimate_prior(const std::string &surl,
const std::string &host,
const uint64_t &nuri,
bool &personalized)
{
static std::string uc_str = "uri-capture";
float prior = 0.0;
float furi = static_cast<float>(nuri);
db_record *dbr = seeks_proxy::_user_db->find_dbr(surl,uc_str);
if (!dbr)
prior = 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior = (log(uc_dbr->_hits + 1.0) + 1.0)/ log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
dbr = seeks_proxy::_user_db->find_dbr(host,uc_str);
if (!dbr)
prior *= 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior *= (log(uc_dbr->_hits + 1.0) + 1.0) / log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
return prior;
}
} /* end of namespace. */
<commit_msg>remove impact of domain hosts on image personalization because of the lack of competition among domains<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rank_estimators.h"
#include "cf.h"
#include "cf_configuration.h"
#include "qprocess.h"
#include "query_capture.h"
#include "uri_capture.h"
#include "db_uri_record.h"
#include "urlmatch.h"
#include <assert.h>
#include <math.h>
#include <iostream>
using lsh::qprocess;
using sp::urlmatch;
namespace seeks_plugins
{
/*- rank_estimator -*/
void rank_estimator::fetch_user_db_record(const std::string &query,
std::vector<db_record*> &records)
{
static std::string qc_str = "query-capture";
// strip query.
std::string q = query_capture_element::no_command_query(query);
// generate query fragments.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(q,0,5,features); //TODO: from configuration (5).
// fetch records from the user DB.
hash_multimap<uint32_t,DHTKey,id_hash_uint>::const_iterator hit = features.begin();
while (hit!=features.end())
{
std::string key_str = (*hit).second.to_rstring();
db_record *dbr = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
if (dbr)
records.push_back(dbr);
++hit;
}
}
void rank_estimator::extract_queries(const std::vector<db_record*> &records,
hash_map<const char*,query_data*,hash<const char*>,eqstr> &qdata)
{
static std::string qc_str = "query-capture";
// iterate records and gather queries and data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit;
std::vector<db_record*>::const_iterator vit = records.begin();
while (vit!=records.end())
{
db_query_record *dbqr = static_cast<db_query_record*>((*vit));
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit
= dbqr->_related_queries.begin();
while (qit!=dbqr->_related_queries.end())
{
query_data *qd = (*qit).second;
if ((hit=qdata.find(qd->_query.c_str()))==qdata.end())
{
if (qd->_radius == 0) // contains the data.
qdata.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),
new query_data(qd)));
else
{
// data are in lower radius records.
hash_multimap<uint32_t,DHTKey,id_hash_uint> features;
qprocess::generate_query_hashes(qd->_query,0,0,features);
// XXX: when the query contains > 8 words there are many features generated
// for the same radius. The original query data can be fetched from any
// of the generated features, so we take the first one.
if (features.empty()) // this should never happen.
{
++qit;
continue;
}
std::string key_str = (*features.begin()).second.to_rstring();
db_record *dbr_data = seeks_proxy::_user_db->find_dbr(key_str,qc_str);
if (!dbr_data) // this should never happen.
{
++qit;
continue;
}
db_query_record *dbqr_data = static_cast<db_query_record*>(dbr_data);
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator qit2
= dbqr_data->_related_queries.begin();
while (qit2!=dbqr_data->_related_queries.end())
{
if ((*qit2).second->_radius == 0
&& (*qit2).second->_query == qd->_query)
{
query_data *dbqrc = new query_data((*qit2).second);
dbqrc->_radius = qd->_radius; // update radius relatively to original query.
qdata.insert(std::pair<const char*,query_data*>(dbqrc->_query.c_str(),
dbqrc));
break;
}
++qit2;
}
delete dbqr_data;
}
}
++qit;
}
++vit;
}
}
/*- simple_re -*/
simple_re::simple_re()
:rank_estimator()
{
}
simple_re::~simple_re()
{
}
void simple_re::estimate_ranks(const std::string &query,
std::vector<search_snippet*> &snippets)
{
// fetch records from user DB.
std::vector<db_record*> records;
rank_estimator::fetch_user_db_record(query,records);
//std::cerr << "[estimate_ranks]: number of fetched records: " << records.size() << std::endl;
// extract queries.
hash_map<const char*,query_data*,hash<const char*>,eqstr> qdata;
rank_estimator::extract_queries(records,qdata);
//std::cerr << "[estimate_ranks]: number of extracted queries: " << qdata.size() << std::endl;
// destroy records.
std::vector<db_record*>::iterator rit = records.begin();
while (rit!=records.end())
{
db_record *dbr = (*rit);
rit = records.erase(rit);
delete dbr;
}
// gather normalizing values.
int i = 0;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit
= qdata.begin();
float q_vurl_hits[qdata.size()];
while (hit!=qdata.end())
{
q_vurl_hits[i++] = (*hit).second->vurls_total_hits();
++hit;
}
float sum_se_ranks = 0.0;
std::vector<search_snippet*>::iterator vit = snippets.begin();
while (vit!=snippets.end())
{
sum_se_ranks += (*vit)->_seeks_rank;
++vit;
}
// get number of captured URIs.
uint64_t nuri = 0;
if (cf::_uc_plugin)
nuri = static_cast<uri_capture*>(cf::_uc_plugin)->_nr;
// estimate each URL's rank.
int j = 0;
size_t ns = snippets.size();
float posteriors[ns];
float sum_posteriors = 0.0;
vit = snippets.begin();
while (vit!=snippets.end())
{
std::string url = (*vit)->_url;
std::transform(url.begin(),url.end(),url.begin(),tolower);
std::string host, path;
urlmatch::parse_url_host_and_path(url,host,path);
host = urlmatch::strip_url(host);
i = 0;
posteriors[j] = 0.0;
hit = qdata.begin();
while (hit!=qdata.end())
{
float qpost = estimate_rank((*vit),ns,(*hit).second,q_vurl_hits[i++],
url,host,path);
//qpost *= (*vit)->_seeks_rank / sum_se_ranks; // account for URL rank in results from search engines.
qpost *= 1.0/static_cast<float>(((*hit).second->_radius + 1.0)); // account for distance to original query.
posteriors[j] += qpost; // boosting over similar queries.
//std::cerr << "url: " << (*vit)->_url << " -- qpost: " << qpost << std::endl;
++hit;
}
// estimate the url prior.
bool personalized = false;
float prior = 1.0;
if (nuri != 0 && (*vit)->_doc_type != VIDEO_THUMB
&& (*vit)->_doc_type != TWEET && (*vit)->_doc_type != IMAGE) // not empty or type with not enought competition on domains.
prior = estimate_prior(url,host,nuri,personalized);
if (personalized)
(*vit)->_personalized = true;
posteriors[j] *= prior;
//std::cerr << "url: " << (*vit)->_url << " -- prior: " << prior << " -- posterior: " << posteriors[j] << std::endl;
sum_posteriors += posteriors[j++];
++vit;
}
// wrapup.
if (sum_posteriors > 0.0)
{
for (size_t k=0; k<ns; k++)
{
posteriors[k] /= sum_posteriors; // normalize.
snippets.at(k)->_seeks_rank = posteriors[k];
//std::cerr << "url: " << snippets.at(k)->_url << " -- seeks_rank: " << snippets.at(k)->_seeks_rank << std::endl;
}
}
// destroy query data.
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator hit2;
hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator chit;
hit2 = qdata.begin();
while (hit2!=qdata.end())
{
query_data *qd = (*hit2).second;
chit = hit2;
++hit2;
delete qd;
}
}
float simple_re::estimate_rank(search_snippet *s, const int &ns,
const query_data *qd,
const float &total_hits,
const std::string &surl,
const std::string &host, const std::string &path)
{
float posterior = 0.0;
// URL.
vurl_data *vd = qd->find_vurl(surl);
if (!vd)
//posterior = 1.0 / (log(static_cast<float>(ns) + 1.0) + 1.0); // XXX: may replace ns with a less discriminative value.
posterior = 1.0 / (log(total_hits + 1.0) + ns);
else
{
posterior = (log(vd->_hits + 1.0) + 1.0)/ (log(total_hits + 1.0) + ns);
s->_personalized = true;
}
// host.
vd = qd->find_vurl(host);
if (!vd || s->_doc_type == VIDEO_THUMB || s->_doc_type == TWEET
|| s->_doc_type == IMAGE) // empty or type with not enough competition on domains.
posterior *= cf_configuration::_config->_domain_name_weight
/ static_cast<float>(ns); // XXX: may replace ns with a less discriminative value.
else
{
posterior *= cf_configuration::_config->_domain_name_weight
* (log(vd->_hits + 1.0) + 1.0)
/ (log(total_hits + 1.0) + ns); // with domain-name weight factor.
s->_personalized = true;
}
//std::cerr << "posterior: " << posterior << std::endl;
return posterior;
}
float simple_re::estimate_prior(const std::string &surl,
const std::string &host,
const uint64_t &nuri,
bool &personalized)
{
static std::string uc_str = "uri-capture";
float prior = 0.0;
float furi = static_cast<float>(nuri);
db_record *dbr = seeks_proxy::_user_db->find_dbr(surl,uc_str);
if (!dbr)
prior = 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior = (log(uc_dbr->_hits + 1.0) + 1.0)/ log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
dbr = seeks_proxy::_user_db->find_dbr(host,uc_str);
if (!dbr)
prior *= 1.0 / log(furi + 1.0);
else
{
db_uri_record *uc_dbr = static_cast<db_uri_record*>(dbr);
prior *= (log(uc_dbr->_hits + 1.0) + 1.0) / log(furi + 1.0);
delete uc_dbr;
personalized = true;
}
return prior;
}
} /* end of namespace. */
<|endoftext|> |
<commit_before>// Copyright 2013 The Flutter 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 "impeller/renderer/backend/gles/surface_gles.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/config.h"
#include "impeller/renderer/backend/gles/context_gles.h"
#include "impeller/renderer/backend/gles/texture_gles.h"
namespace impeller {
std::unique_ptr<Surface> SurfaceGLES::WrapFBO(std::shared_ptr<Context> context,
SwapCallback swap_callback,
GLuint fbo,
PixelFormat color_format,
ISize fbo_size) {
TRACE_EVENT0("impeller", "SurfaceGLES::WrapOnScreenFBO");
if (context == nullptr || !context->IsValid() || !swap_callback) {
return nullptr;
}
const auto& gl_context = ContextGLES::Cast(*context);
TextureDescriptor color0_tex;
color0_tex.type = TextureType::kTexture2D;
color0_tex.format = color_format;
color0_tex.size = fbo_size;
color0_tex.usage = static_cast<TextureUsageMask>(TextureUsage::kRenderTarget);
color0_tex.sample_count = SampleCount::kCount1;
ColorAttachment color0;
color0.texture = std::make_shared<TextureGLES>(
gl_context.GetReactor(), std::move(color0_tex),
TextureGLES::IsWrapped::kWrapped);
color0.clear_color = Color::DarkSlateGray();
color0.load_action = LoadAction::kClear;
color0.store_action = StoreAction::kStore;
TextureDescriptor stencil0_tex;
stencil0_tex.type = TextureType::kTexture2D;
stencil0_tex.format = color_format;
stencil0_tex.size = fbo_size;
stencil0_tex.usage =
static_cast<TextureUsageMask>(TextureUsage::kRenderTarget);
stencil0_tex.sample_count = SampleCount::kCount1;
StencilAttachment stencil0;
stencil0.clear_stencil = 0;
stencil0.texture = std::make_shared<TextureGLES>(
gl_context.GetReactor(), std::move(stencil0_tex),
TextureGLES::IsWrapped::kWrapped);
stencil0.load_action = LoadAction::kClear;
stencil0.store_action = StoreAction::kDontCare;
RenderTarget render_target_desc;
render_target_desc.SetColorAttachment(color0, 0u);
render_target_desc.SetStencilAttachment(stencil0);
return std::unique_ptr<SurfaceGLES>(
new SurfaceGLES(std::move(swap_callback), std::move(render_target_desc)));
}
SurfaceGLES::SurfaceGLES(SwapCallback swap_callback, RenderTarget target_desc)
: Surface(std::move(target_desc)),
swap_callback_(std::move(swap_callback)) {}
// |Surface|
SurfaceGLES::~SurfaceGLES() = default;
// |Surface|
bool SurfaceGLES::Present() const {
return swap_callback_ ? swap_callback_() : false;
}
} // namespace impeller
<commit_msg>[Impeller] Make 'SurfaceGLES::WrapFBO' pass attachment validation (#35881)<commit_after>// Copyright 2013 The Flutter 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 "impeller/renderer/backend/gles/surface_gles.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/config.h"
#include "impeller/renderer/backend/gles/context_gles.h"
#include "impeller/renderer/backend/gles/texture_gles.h"
namespace impeller {
std::unique_ptr<Surface> SurfaceGLES::WrapFBO(std::shared_ptr<Context> context,
SwapCallback swap_callback,
GLuint fbo,
PixelFormat color_format,
ISize fbo_size) {
TRACE_EVENT0("impeller", "SurfaceGLES::WrapOnScreenFBO");
if (context == nullptr || !context->IsValid() || !swap_callback) {
return nullptr;
}
const auto& gl_context = ContextGLES::Cast(*context);
TextureDescriptor color0_tex;
color0_tex.type = TextureType::kTexture2D;
color0_tex.format = color_format;
color0_tex.size = fbo_size;
color0_tex.usage = static_cast<TextureUsageMask>(TextureUsage::kRenderTarget);
color0_tex.sample_count = SampleCount::kCount1;
color0_tex.storage_mode = StorageMode::kDevicePrivate;
ColorAttachment color0;
color0.texture = std::make_shared<TextureGLES>(
gl_context.GetReactor(), std::move(color0_tex),
TextureGLES::IsWrapped::kWrapped);
color0.clear_color = Color::DarkSlateGray();
color0.load_action = LoadAction::kClear;
color0.store_action = StoreAction::kStore;
TextureDescriptor stencil0_tex;
stencil0_tex.type = TextureType::kTexture2D;
stencil0_tex.format = color_format;
stencil0_tex.size = fbo_size;
stencil0_tex.usage =
static_cast<TextureUsageMask>(TextureUsage::kRenderTarget);
stencil0_tex.sample_count = SampleCount::kCount1;
StencilAttachment stencil0;
stencil0.clear_stencil = 0;
stencil0.texture = std::make_shared<TextureGLES>(
gl_context.GetReactor(), std::move(stencil0_tex),
TextureGLES::IsWrapped::kWrapped);
stencil0.load_action = LoadAction::kClear;
stencil0.store_action = StoreAction::kDontCare;
RenderTarget render_target_desc;
render_target_desc.SetColorAttachment(color0, 0u);
render_target_desc.SetStencilAttachment(stencil0);
return std::unique_ptr<SurfaceGLES>(
new SurfaceGLES(std::move(swap_callback), std::move(render_target_desc)));
}
SurfaceGLES::SurfaceGLES(SwapCallback swap_callback, RenderTarget target_desc)
: Surface(std::move(target_desc)),
swap_callback_(std::move(swap_callback)) {}
// |Surface|
SurfaceGLES::~SurfaceGLES() = default;
// |Surface|
bool SurfaceGLES::Present() const {
return swap_callback_ ? swap_callback_() : false;
}
} // namespace impeller
<|endoftext|> |
<commit_before><commit_msg>Initialize variable<commit_after><|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "FrameworkQtApplication.h"
#include "Framework.h"
#include "ConfigurationManager.h"
#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include "MemoryLeakCheck.h"
namespace Foundation
{
FrameworkQtApplication::FrameworkQtApplication(Framework *framework, int &argc, char **argv) :
QApplication(argc, argv), framework_(framework), app_activated_(true), native_translator_(new QTranslator), app_translator_(new QTranslator)
{
#ifdef Q_WS_WIN
// If under windows, add run_dir/plugins as library path
// unix users will get plugins from their OS Qt installation folder automatically
QString run_directory = applicationDirPath();
run_directory += "/qtplugins";
addLibraryPath(run_directory);
#endif
QDir dir("data/translations/qt_native_translations");
QStringList qmFiles = GetQmFiles(dir);
// Search then that is there corresponding native translations for system locals.
QString loc = QLocale::system().name();
loc.chop(3);
QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
QStringList lst = qmFiles.filter(name);
if (!lst.empty() )
native_translator_->load(lst[0]);
this->installTranslator(native_translator_);
std::string default_language = framework_->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(), "language", std::string("data/translations/naali_fi"));
ChangeLanguage(QString::fromStdString(default_language));
}
FrameworkQtApplication::~FrameworkQtApplication()
{
SAFE_DELETE(native_translator_);
SAFE_DELETE(app_translator_);
}
QGraphicsView *FrameworkQtApplication::GetUIView() const
{
return view_.get();
}
void FrameworkQtApplication::SetUIView(std::auto_ptr <QGraphicsView> view)
{
view_ = view;
}
QStringList FrameworkQtApplication::GetQmFiles(const QDir& dir)
{
QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
QMutableStringListIterator i(fileNames);
while (i.hasNext())
{
i.next();
i.setValue(dir.filePath(i.value()));
}
return fileNames;
}
void FrameworkQtApplication::Go()
{
installEventFilter(this);
QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
frame_update_timer_.setSingleShot (true);
frame_update_timer_.start (0);
try
{
exec ();
}
catch(const std::exception &e)
{
RootLogCritical(std::string("FrameworkQtApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
RootLogCritical(std::string("FrameworkQtApplication::Go caught an unknown exception!"));
throw;
}
}
bool FrameworkQtApplication::eventFilter(QObject *obj, QEvent *event)
{
try
{
if (obj == this)
{
if (event->type() == QEvent::ApplicationActivate)
app_activated_ = true;
if (event->type() == QEvent::ApplicationDeactivate)
app_activated_ = false;
/*
if (event->type() == QEvent::LanguageChange)
{
// Now if exist remove our default translation engine.
if (translator_ != 0)
this->removeTranslator(translator_);
}
*/
}
return QObject::eventFilter(obj, event);
}
catch(const std::exception &e)
{
std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
throw;
}
return true;
}
void FrameworkQtApplication::ChangeLanguage(const QString& file)
{
QString filename = file;
if (!filename.endsWith(".qm", Qt::CaseInsensitive))
filename.append(".qm");
QString tmp = filename;
tmp.chop(3);
QString str = tmp.right(2);
QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";
// Remove old translators then change them to new.
removeTranslator(native_translator_);
if ( QFile::exists(name) )
{
if ( native_translator_ != 0)
{
native_translator_->load(name);
installTranslator(native_translator_);
}
}
else
{
if (native_translator_ != 0 && native_translator_->isEmpty())
{
installTranslator(native_translator_);
}
else
{
SAFE_DELETE(native_translator_);
native_translator_ = new QTranslator;
installTranslator(native_translator_);
}
}
// Remove old translators then change them to new.
removeTranslator(app_translator_);
if (app_translator_->load(filename))
{
installTranslator(app_translator_);
framework_->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
}
emit LanguageChanged();
}
bool FrameworkQtApplication::notify(QObject *receiver, QEvent *event)
{
try
{
return QApplication::notify(receiver, event);
} catch(const std::exception &e)
{
std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
throw;
}
return true;
}
void FrameworkQtApplication::UpdateFrame()
{
try
{
QApplication::processEvents (QEventLoop::AllEvents, 1);
QApplication::sendPostedEvents ();
framework_-> ProcessOneFrame();
// Reduce framerate when unfocused
if (app_activated_)
frame_update_timer_.start(0);
else
frame_update_timer_.start(5);
}
catch(const std::exception &e)
{
std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
throw;
}
}
void FrameworkQtApplication::AboutToExit()
{
emit ExitRequested();
// If no-one canceled the exit as a response to the signal, exit
if (framework_->IsExiting())
quit();
}
}
<commit_msg>Reverted back to English as default.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "FrameworkQtApplication.h"
#include "Framework.h"
#include "ConfigurationManager.h"
#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include "MemoryLeakCheck.h"
namespace Foundation
{
FrameworkQtApplication::FrameworkQtApplication(Framework *framework, int &argc, char **argv) :
QApplication(argc, argv), framework_(framework), app_activated_(true), native_translator_(new QTranslator), app_translator_(new QTranslator)
{
#ifdef Q_WS_WIN
// If under windows, add run_dir/plugins as library path
// unix users will get plugins from their OS Qt installation folder automatically
QString run_directory = applicationDirPath();
run_directory += "/qtplugins";
addLibraryPath(run_directory);
#endif
QDir dir("data/translations/qt_native_translations");
QStringList qmFiles = GetQmFiles(dir);
// Search then that is there corresponding native translations for system locals.
QString loc = QLocale::system().name();
loc.chop(3);
QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
QStringList lst = qmFiles.filter(name);
if (!lst.empty() )
native_translator_->load(lst[0]);
this->installTranslator(native_translator_);
std::string default_language = framework_->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(), "language", std::string("data/translations/naali_en"));
ChangeLanguage(QString::fromStdString(default_language));
}
FrameworkQtApplication::~FrameworkQtApplication()
{
SAFE_DELETE(native_translator_);
SAFE_DELETE(app_translator_);
}
QGraphicsView *FrameworkQtApplication::GetUIView() const
{
return view_.get();
}
void FrameworkQtApplication::SetUIView(std::auto_ptr <QGraphicsView> view)
{
view_ = view;
}
QStringList FrameworkQtApplication::GetQmFiles(const QDir& dir)
{
QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
QMutableStringListIterator i(fileNames);
while (i.hasNext())
{
i.next();
i.setValue(dir.filePath(i.value()));
}
return fileNames;
}
void FrameworkQtApplication::Go()
{
installEventFilter(this);
QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
frame_update_timer_.setSingleShot (true);
frame_update_timer_.start (0);
try
{
exec ();
}
catch(const std::exception &e)
{
RootLogCritical(std::string("FrameworkQtApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
RootLogCritical(std::string("FrameworkQtApplication::Go caught an unknown exception!"));
throw;
}
}
bool FrameworkQtApplication::eventFilter(QObject *obj, QEvent *event)
{
try
{
if (obj == this)
{
if (event->type() == QEvent::ApplicationActivate)
app_activated_ = true;
if (event->type() == QEvent::ApplicationDeactivate)
app_activated_ = false;
/*
if (event->type() == QEvent::LanguageChange)
{
// Now if exist remove our default translation engine.
if (translator_ != 0)
this->removeTranslator(translator_);
}
*/
}
return QObject::eventFilter(obj, event);
}
catch(const std::exception &e)
{
std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
throw;
}
return true;
}
void FrameworkQtApplication::ChangeLanguage(const QString& file)
{
QString filename = file;
if (!filename.endsWith(".qm", Qt::CaseInsensitive))
filename.append(".qm");
QString tmp = filename;
tmp.chop(3);
QString str = tmp.right(2);
QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";
// Remove old translators then change them to new.
removeTranslator(native_translator_);
if ( QFile::exists(name) )
{
if ( native_translator_ != 0)
{
native_translator_->load(name);
installTranslator(native_translator_);
}
}
else
{
if (native_translator_ != 0 && native_translator_->isEmpty())
{
installTranslator(native_translator_);
}
else
{
SAFE_DELETE(native_translator_);
native_translator_ = new QTranslator;
installTranslator(native_translator_);
}
}
// Remove old translators then change them to new.
removeTranslator(app_translator_);
if (app_translator_->load(filename))
{
installTranslator(app_translator_);
framework_->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
}
emit LanguageChanged();
}
bool FrameworkQtApplication::notify(QObject *receiver, QEvent *event)
{
try
{
return QApplication::notify(receiver, event);
} catch(const std::exception &e)
{
std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
throw;
}
return true;
}
void FrameworkQtApplication::UpdateFrame()
{
try
{
QApplication::processEvents (QEventLoop::AllEvents, 1);
QApplication::sendPostedEvents ();
framework_-> ProcessOneFrame();
// Reduce framerate when unfocused
if (app_activated_)
frame_update_timer_.start(0);
else
frame_update_timer_.start(5);
}
catch(const std::exception &e)
{
std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
throw;
}
}
void FrameworkQtApplication::AboutToExit()
{
emit ExitRequested();
// If no-one canceled the exit as a response to the signal, exit
if (framework_->IsExiting())
quit();
}
}
<|endoftext|> |
<commit_before>#include "GatewayServiceHandler.h"
#include "GatewayCore.h"
#include "protocol/GatewayPrivateMessages.pb.h"
#include <iostream>
#include "log.h"
#include "ace/OS_NS_errno.h"
/* GatewayServiceHandler::GatewayServiceHandler(ACE_Thread_Manager *tm = 0, ACE_Message_Queue<ACE_NULL_SYNCH> *mq = 0, ACE_Reactor *reactor = ACE_Reactor::instance())
: ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_NULL_SYNCH>(tm, mq, reactor)
{
} */
int GatewayServiceHandler::open(void *ptr) {
if(super::open(ptr) == -1) {
return -1;
}
state = READING_SIZE;
dataSize = 0;
checksum = 0;
collectedData = NULL;
position = 0;
username = "";
usernameAuthenticated = false;
this->peer().enable(ACE_NONBLOCK);
return 0;
}
int GatewayServiceHandler::handle_input(ACE_HANDLE fd) {
//LOG_TRACE("In handle_input");
int count = 0;
if(state == READING_SIZE) {
count = this->peer().recv_n(&dataSize, sizeof(dataSize));
//LOG_TRACE("SIZE Read " << count << " bytes");
} else if(state == READING_CHECKSUM) {
count = this->peer().recv_n(&checksum, sizeof(checksum));
//LOG_TRACE("SUM Read " << count << " bytes");
} else if(state == READING_DATA) {
count = this->peer().recv(collectedData + position, dataSize - position);
//LOG_TRACE("DATA Read " << count << " bytes");
} else {
LOG_ERROR("Invalid state!");
}
if(count > 0) {
if(state == READING_SIZE) {
collectedData = new char[dataSize];
position = 0;
//LOG_TRACE("Got data size (" << dataSize << ")");
state = READING_CHECKSUM;
} else if(state == READING_CHECKSUM) {
//LOG_TRACE("Got data checksum (" << checksum << ")");
state = READING_DATA;
} else if(state == READING_DATA) {
//LOG_TRACE("Got some data...");
position += count;
if(position == dataSize) {
//LOG_TRACE("Got all the data... processing");
processData(collectedData, dataSize, checksum);
//LOG_TRACE("Processsing complete. Deleting buffer.");
delete[] collectedData;
collectedData = NULL;
dataSize = 0;
position = 0;
state = READING_SIZE;
}
}
} else if(count == 0) {
LOG_INFO("Connection closed.");
return -1;
} else if(count == -1 && ACE_OS::last_error () != EWOULDBLOCK) {
LOG_ERROR("Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
//LOG_INFO("Leaving handle_input()");
return 0;
}
int GatewayServiceHandler::handle_output(ACE_HANDLE fd) {
int count = 0;
do {
if(dataToSend == NULL) {
ammo::gateway::protocol::GatewayWrapper *msg = getNextMessageToSend();
if(msg != NULL) {
LOG_TRACE("Getting a new message to send");
if(!msg->IsInitialized()) {
LOG_WARN(this << " Protocol Buffers message is missing a required element.");
}
unsigned int messageSize = msg->ByteSize();
sendBufferSize = messageSize + 2*sizeof(unsigned int);
dataToSend = new char[sendBufferSize];
unsigned int *size = (unsigned int *) dataToSend;
unsigned int *messageChecksum = (unsigned int *) (dataToSend + sizeof(unsigned int));
char *protobufSerializedMessage = dataToSend + 2*sizeof(unsigned int);
*size = messageSize;
msg->SerializeToArray(protobufSerializedMessage, messageSize);
*messageChecksum = ACE::crc32(protobufSerializedMessage, messageSize);
sendPosition = 0;
delete msg;
} else {
//don't wake up the reactor when there's no data that needs to be sent
//(wake-up will be rescheduled when data becomes available in sendMessage
//below)
this->reactor()->cancel_wakeup(this, ACE_Event_Handler::WRITE_MASK);
return 0;
}
}
//timeout after ten seconds when sending data (in case connection drops
//in the middle, we don't want to wait until the socket connection dies)
//ACE_Time_Value timeout(10);
count = this->peer().send(dataToSend + sendPosition, sendBufferSize - sendPosition);
if(count >= 0) {
sendPosition += count;
}
LOG_TRACE("Sent " << count << " bytes (current postition " << sendPosition << "/" << sendBufferSize);
if(sendPosition >= (sendBufferSize)) {
delete[] dataToSend;
dataToSend = NULL;
sendBufferSize = 0;
sendPosition = 0;
}
} while(count != -1);
if(count == -1 && ACE_OS::last_error () == EWOULDBLOCK) {
LOG_TRACE("Received EWOULDBLOCK");
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
} else {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
return 0;
}
void GatewayServiceHandler::sendData(ammo::gateway::protocol::GatewayWrapper *msg) {
sendQueue.push(msg);
LOG_TRACE(this << " Queued a message to send. " << sendQueue.size() << " messages in queue.");
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
}
ammo::gateway::protocol::GatewayWrapper *GatewayServiceHandler::getNextMessageToSend() {
ammo::gateway::protocol::GatewayWrapper *msg = NULL;
if(!sendQueue.empty()) {
msg = sendQueue.front();
sendQueue.pop();
}
int size = sendQueue.size();
LOG_TRACE(this << " Dequeued a message to send. " << size << " messages remain in queue.");
return msg;
}
int GatewayServiceHandler::processData(char *data, unsigned int messageSize, unsigned int messageChecksum) {
//Validate checksum
unsigned int calculatedChecksum = ACE::crc32(data, messageSize);
if(calculatedChecksum != messageChecksum) {
LOG_ERROR("Invalid checksum-- we've been sent bad data (perhaps a message size mismatch?)");
return -1;
}
//checksum is valid; parse the data
ammo::gateway::protocol::GatewayWrapper msg;
bool result = msg.ParseFromArray(data, messageSize);
if(result == false) {
LOG_ERROR("GatewayWrapper could not be deserialized.");
LOG_ERROR("Client must have sent something that isn't a protocol buffer (or the wrong type).");
return -1;
}
//LOG_TRACE("Message Received: " << msg.DebugString());
switch(msg.type()) {
case ammo::gateway::protocol::GatewayWrapper_MessageType_ASSOCIATE_DEVICE: {
LOG_DEBUG("Received Associate Device...");
//TODO: split out into a different function and do more here
ammo::gateway::protocol::GatewayWrapper *newMsg;
newMsg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_ASSOCIATE_RESULT);
newMsg->mutable_associate_result()->set_result(ammo::gateway::protocol::AssociateResult_Status_SUCCESS);
this->sendData(newMsg);
username = msg.associate_device().user();
usernameAuthenticated = true;
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_REGISTER_DATA_INTEREST: {
LOG_DEBUG("Received Register Data Interest...");
std::string mime_type = msg.register_data_interest().mime_type();
MessageScope scope;
if(msg.register_data_interest().scope() == ammo::gateway::protocol::GLOBAL) {
scope = SCOPE_GLOBAL;
} else {
scope = SCOPE_LOCAL;
}
bool result = GatewayCore::getInstance()->registerDataInterest(mime_type, scope, this);
if(result == true) {
registeredHandlers.push_back(mime_type);
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_UNREGISTER_DATA_INTEREST: {
LOG_DEBUG("Received Unregister Data Interest...");
std::string mime_type = msg.unregister_data_interest().mime_type();
MessageScope scope;
if(msg.unregister_data_interest().scope() == ammo::gateway::protocol::GLOBAL) {
scope = SCOPE_GLOBAL;
} else {
scope = SCOPE_LOCAL;
}
bool result = GatewayCore::getInstance()->unregisterDataInterest(mime_type, scope, this);
if(result == true) {
for(std::vector<std::string>::iterator it = registeredHandlers.begin(); it != registeredHandlers.end();) {
if((*it) == mime_type) {
it = registeredHandlers.erase(it); //erase returns the iterator to the next element
break;
} else {
it++;
}
}
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_PUSH_DATA: {
LOG_DEBUG("Received Push Data...");
MessageScope scope;
if(msg.push_data().scope() == ammo::gateway::protocol::GLOBAL) {
scope = SCOPE_GLOBAL;
} else {
scope = SCOPE_LOCAL;
}
GatewayCore::getInstance()->pushData(msg.push_data().uri(), msg.push_data().mime_type(), msg.push_data().data(), this->username, scope);
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_REQUEST: {
LOG_DEBUG("Received Pull Request...");
LOG_TRACE(" " << msg.DebugString());
ammo::gateway::protocol::PullRequest pullMsg = msg.pull_request();
bool result = GatewayCore::getInstance()->pullRequest(pullMsg.request_uid(), pullMsg.plugin_id(), pullMsg.mime_type(), pullMsg.query(),
pullMsg.projection(), pullMsg.max_results(), pullMsg.start_from_count(), pullMsg.live_query(), this);
if(result == true) {
registeredPullResponsePluginIds.insert(pullMsg.plugin_id());
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_RESPONSE: {
LOG_DEBUG("Received Pull Response...");
LOG_TRACE(" " << msg.DebugString());
ammo::gateway::protocol::PullResponse pullRsp = msg.pull_response();
GatewayCore::getInstance()->pullResponse( pullRsp.request_uid(), pullRsp.plugin_id(), pullRsp.mime_type(), pullRsp.uri(), pullRsp.data() );
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_REGISTER_PULL_INTEREST: {
LOG_DEBUG("Received Register Pull Interest...");
std::string mime_type = msg.register_pull_interest().mime_type();
bool result = GatewayCore::getInstance()->registerPullInterest(mime_type, this);
if(result == true) {
registeredPullRequestHandlers.push_back(mime_type);
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_UNREGISTER_PULL_INTEREST: {
LOG_DEBUG("Received Unregister Pull Interest...");
std::string mime_type = msg.unregister_pull_interest().mime_type();
bool result = GatewayCore::getInstance()->unregisterPullInterest(mime_type, this);
if(result == true) {
for(std::vector<std::string>::iterator it = registeredPullRequestHandlers.begin(); it != registeredPullRequestHandlers.end(); it++) {
if((*it) == mime_type) {
registeredPullRequestHandlers.erase(it);
break;
}
}
}
break;
}
default: {
LOG_ERROR("Received unsupported message:" << msg.DebugString());
break;
}
}
return 0;
}
bool GatewayServiceHandler::sendPushedData(std::string uri, std::string mimeType, const std::string &data, std::string originUser, MessageScope scope) {
ammo::gateway::protocol::GatewayWrapper *msg = new ammo::gateway::protocol::GatewayWrapper();
ammo::gateway::protocol::PushData *pushMsg = msg->mutable_push_data();
pushMsg->set_uri(uri);
pushMsg->set_mime_type(mimeType);
pushMsg->set_data(data);
pushMsg->set_origin_user(originUser);
msg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_PUSH_DATA);
LOG_DEBUG("Sending Data Push message to connected plugin");
this->sendData(msg);
return true;
}
bool GatewayServiceHandler::sendPullRequest(std::string requestUid, std::string pluginId, std::string mimeType,
std::string query, std::string projection, unsigned int maxResults,
unsigned int startFromCount, bool liveQuery) {
ammo::gateway::protocol::GatewayWrapper *msg = new ammo::gateway::protocol::GatewayWrapper();
ammo::gateway::protocol::PullRequest *pullMsg = msg->mutable_pull_request();
pullMsg->set_request_uid(requestUid);
pullMsg->set_plugin_id(pluginId);
pullMsg->set_mime_type(mimeType);
pullMsg->set_query(query);
pullMsg->set_projection(projection);
pullMsg->set_max_results(maxResults);
pullMsg->set_start_from_count(startFromCount);
pullMsg->set_live_query(liveQuery);
msg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_REQUEST);
LOG_DEBUG("Sending Pull Request message to connected plugin");
this->sendData(msg);
return true;
}
bool GatewayServiceHandler::sendPullResponse(std::string requestUid, std::string pluginId, std::string mimeType,
std::string uri, const std::string& data) {
ammo::gateway::protocol::GatewayWrapper *msg = new ammo::gateway::protocol::GatewayWrapper();
ammo::gateway::protocol::PullResponse *pullRsp = msg->mutable_pull_response();
pullRsp->set_request_uid(requestUid);
pullRsp->set_plugin_id(pluginId);
pullRsp->set_mime_type(mimeType);
pullRsp->set_uri(uri);
pullRsp->set_data(data);
msg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_RESPONSE);
LOG_DEBUG("Sending Pull Response message to connected plugin");
this->sendData(msg);
return true;
}
GatewayServiceHandler::~GatewayServiceHandler() {
LOG_DEBUG("GatewayServiceHandler being destroyed!");
LOG_DEBUG("Unregistering data handlers...");
for(std::vector<std::string>::iterator it = registeredHandlers.begin(); it != registeredHandlers.end(); it++) {
GatewayCore::getInstance()->unregisterDataInterest(*it, SCOPE_ALL, this);
}
LOG_DEBUG("Unregistering pull request handlers...");
for(std::vector<std::string>::iterator it = registeredPullRequestHandlers.begin(); it != registeredPullRequestHandlers.end(); it++) {
GatewayCore::getInstance()->unregisterPullInterest(*it, this);
}
LOG_DEBUG("Unregistering pull response plugin IDs...");
for(std::set<std::string>::iterator it = registeredPullResponsePluginIds.begin(); it != registeredPullResponsePluginIds.end(); it++) {
GatewayCore::getInstance()->unregisterPullResponsePluginId(*it, this);
}
}
std::ostream& operator<< (std::ostream& out, const GatewayServiceHandler& handler) {
out << &handler;
return out;
}
std::ostream& operator<< (std::ostream& out, const GatewayServiceHandler* handler) {
// Since operator<< is a friend of the GatewayServiceHandler class,
// we can access handler's members directly.
out << "(" << reinterpret_cast<void const *>(handler) << " " << handler->state << ", " << handler->username << ")";
return out;
}
<commit_msg>Fix crash due to uninitialized variable<commit_after>#include "GatewayServiceHandler.h"
#include "GatewayCore.h"
#include "protocol/GatewayPrivateMessages.pb.h"
#include <iostream>
#include "log.h"
#include "ace/OS_NS_errno.h"
/* GatewayServiceHandler::GatewayServiceHandler(ACE_Thread_Manager *tm = 0, ACE_Message_Queue<ACE_NULL_SYNCH> *mq = 0, ACE_Reactor *reactor = ACE_Reactor::instance())
: ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_NULL_SYNCH>(tm, mq, reactor)
{
} */
int GatewayServiceHandler::open(void *ptr) {
if(super::open(ptr) == -1) {
return -1;
}
state = READING_SIZE;
dataSize = 0;
checksum = 0;
collectedData = NULL;
position = 0;
username = "";
usernameAuthenticated = false;
this->peer().enable(ACE_NONBLOCK);
return 0;
}
int GatewayServiceHandler::handle_input(ACE_HANDLE fd) {
//LOG_TRACE("In handle_input");
int count = 0;
if(state == READING_SIZE) {
count = this->peer().recv_n(&dataSize, sizeof(dataSize));
//LOG_TRACE("SIZE Read " << count << " bytes");
} else if(state == READING_CHECKSUM) {
count = this->peer().recv_n(&checksum, sizeof(checksum));
//LOG_TRACE("SUM Read " << count << " bytes");
} else if(state == READING_DATA) {
count = this->peer().recv(collectedData + position, dataSize - position);
//LOG_TRACE("DATA Read " << count << " bytes");
} else {
LOG_ERROR("Invalid state!");
}
if(count > 0) {
if(state == READING_SIZE) {
collectedData = new char[dataSize];
position = 0;
//LOG_TRACE("Got data size (" << dataSize << ")");
state = READING_CHECKSUM;
} else if(state == READING_CHECKSUM) {
//LOG_TRACE("Got data checksum (" << checksum << ")");
state = READING_DATA;
} else if(state == READING_DATA) {
//LOG_TRACE("Got some data...");
position += count;
if(position == dataSize) {
//LOG_TRACE("Got all the data... processing");
processData(collectedData, dataSize, checksum);
//LOG_TRACE("Processsing complete. Deleting buffer.");
delete[] collectedData;
collectedData = NULL;
dataSize = 0;
position = 0;
state = READING_SIZE;
}
}
} else if(count == 0) {
LOG_INFO("Connection closed.");
return -1;
} else if(count == -1 && ACE_OS::last_error () != EWOULDBLOCK) {
LOG_ERROR("Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
//LOG_INFO("Leaving handle_input()");
return 0;
}
int GatewayServiceHandler::handle_output(ACE_HANDLE fd) {
int count = 0;
do {
if(dataToSend == NULL) {
ammo::gateway::protocol::GatewayWrapper *msg = getNextMessageToSend();
if(msg != NULL) {
LOG_TRACE("Getting a new message to send");
if(!msg->IsInitialized()) {
LOG_WARN(this << " Protocol Buffers message is missing a required element.");
}
unsigned int messageSize = msg->ByteSize();
sendBufferSize = messageSize + 2*sizeof(unsigned int);
dataToSend = new char[sendBufferSize];
unsigned int *size = (unsigned int *) dataToSend;
unsigned int *messageChecksum = (unsigned int *) (dataToSend + sizeof(unsigned int));
char *protobufSerializedMessage = dataToSend + 2*sizeof(unsigned int);
*size = messageSize;
msg->SerializeToArray(protobufSerializedMessage, messageSize);
*messageChecksum = ACE::crc32(protobufSerializedMessage, messageSize);
sendPosition = 0;
delete msg;
} else {
//don't wake up the reactor when there's no data that needs to be sent
//(wake-up will be rescheduled when data becomes available in sendMessage
//below)
this->reactor()->cancel_wakeup(this, ACE_Event_Handler::WRITE_MASK);
return 0;
}
}
//timeout after ten seconds when sending data (in case connection drops
//in the middle, we don't want to wait until the socket connection dies)
//ACE_Time_Value timeout(10);
count = this->peer().send(dataToSend + sendPosition, sendBufferSize - sendPosition);
if(count >= 0) {
sendPosition += count;
}
LOG_TRACE("Sent " << count << " bytes (current postition " << sendPosition << "/" << sendBufferSize);
if(sendPosition >= (sendBufferSize)) {
delete[] dataToSend;
dataToSend = NULL;
sendBufferSize = 0;
sendPosition = 0;
}
} while(count != -1);
if(count == -1 && ACE_OS::last_error () == EWOULDBLOCK) {
LOG_TRACE("Received EWOULDBLOCK");
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
} else {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
return 0;
}
void GatewayServiceHandler::sendData(ammo::gateway::protocol::GatewayWrapper *msg) {
sendQueue.push(msg);
LOG_TRACE(this << " Queued a message to send. " << sendQueue.size() << " messages in queue.");
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
}
ammo::gateway::protocol::GatewayWrapper *GatewayServiceHandler::getNextMessageToSend() {
ammo::gateway::protocol::GatewayWrapper *msg = NULL;
if(!sendQueue.empty()) {
msg = sendQueue.front();
sendQueue.pop();
}
int size = sendQueue.size();
LOG_TRACE(this << " Dequeued a message to send. " << size << " messages remain in queue.");
return msg;
}
int GatewayServiceHandler::processData(char *data, unsigned int messageSize, unsigned int messageChecksum) {
//Validate checksum
unsigned int calculatedChecksum = ACE::crc32(data, messageSize);
if(calculatedChecksum != messageChecksum) {
LOG_ERROR("Invalid checksum-- we've been sent bad data (perhaps a message size mismatch?)");
return -1;
}
//checksum is valid; parse the data
ammo::gateway::protocol::GatewayWrapper msg;
bool result = msg.ParseFromArray(data, messageSize);
if(result == false) {
LOG_ERROR("GatewayWrapper could not be deserialized.");
LOG_ERROR("Client must have sent something that isn't a protocol buffer (or the wrong type).");
return -1;
}
//LOG_TRACE("Message Received: " << msg.DebugString());
switch(msg.type()) {
case ammo::gateway::protocol::GatewayWrapper_MessageType_ASSOCIATE_DEVICE: {
LOG_DEBUG("Received Associate Device...");
//TODO: split out into a different function and do more here
ammo::gateway::protocol::GatewayWrapper *newMsg = new ammo::gateway::protocol::GatewayWrapper();
newMsg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_ASSOCIATE_RESULT);
newMsg->mutable_associate_result()->set_result(ammo::gateway::protocol::AssociateResult_Status_SUCCESS);
this->sendData(newMsg);
username = msg.associate_device().user();
usernameAuthenticated = true;
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_REGISTER_DATA_INTEREST: {
LOG_DEBUG("Received Register Data Interest...");
std::string mime_type = msg.register_data_interest().mime_type();
MessageScope scope;
if(msg.register_data_interest().scope() == ammo::gateway::protocol::GLOBAL) {
scope = SCOPE_GLOBAL;
} else {
scope = SCOPE_LOCAL;
}
bool result = GatewayCore::getInstance()->registerDataInterest(mime_type, scope, this);
if(result == true) {
registeredHandlers.push_back(mime_type);
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_UNREGISTER_DATA_INTEREST: {
LOG_DEBUG("Received Unregister Data Interest...");
std::string mime_type = msg.unregister_data_interest().mime_type();
MessageScope scope;
if(msg.unregister_data_interest().scope() == ammo::gateway::protocol::GLOBAL) {
scope = SCOPE_GLOBAL;
} else {
scope = SCOPE_LOCAL;
}
bool result = GatewayCore::getInstance()->unregisterDataInterest(mime_type, scope, this);
if(result == true) {
for(std::vector<std::string>::iterator it = registeredHandlers.begin(); it != registeredHandlers.end();) {
if((*it) == mime_type) {
it = registeredHandlers.erase(it); //erase returns the iterator to the next element
break;
} else {
it++;
}
}
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_PUSH_DATA: {
LOG_DEBUG("Received Push Data...");
MessageScope scope;
if(msg.push_data().scope() == ammo::gateway::protocol::GLOBAL) {
scope = SCOPE_GLOBAL;
} else {
scope = SCOPE_LOCAL;
}
GatewayCore::getInstance()->pushData(msg.push_data().uri(), msg.push_data().mime_type(), msg.push_data().data(), this->username, scope);
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_REQUEST: {
LOG_DEBUG("Received Pull Request...");
LOG_TRACE(" " << msg.DebugString());
ammo::gateway::protocol::PullRequest pullMsg = msg.pull_request();
bool result = GatewayCore::getInstance()->pullRequest(pullMsg.request_uid(), pullMsg.plugin_id(), pullMsg.mime_type(), pullMsg.query(),
pullMsg.projection(), pullMsg.max_results(), pullMsg.start_from_count(), pullMsg.live_query(), this);
if(result == true) {
registeredPullResponsePluginIds.insert(pullMsg.plugin_id());
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_RESPONSE: {
LOG_DEBUG("Received Pull Response...");
LOG_TRACE(" " << msg.DebugString());
ammo::gateway::protocol::PullResponse pullRsp = msg.pull_response();
GatewayCore::getInstance()->pullResponse( pullRsp.request_uid(), pullRsp.plugin_id(), pullRsp.mime_type(), pullRsp.uri(), pullRsp.data() );
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_REGISTER_PULL_INTEREST: {
LOG_DEBUG("Received Register Pull Interest...");
std::string mime_type = msg.register_pull_interest().mime_type();
bool result = GatewayCore::getInstance()->registerPullInterest(mime_type, this);
if(result == true) {
registeredPullRequestHandlers.push_back(mime_type);
}
break;
}
case ammo::gateway::protocol::GatewayWrapper_MessageType_UNREGISTER_PULL_INTEREST: {
LOG_DEBUG("Received Unregister Pull Interest...");
std::string mime_type = msg.unregister_pull_interest().mime_type();
bool result = GatewayCore::getInstance()->unregisterPullInterest(mime_type, this);
if(result == true) {
for(std::vector<std::string>::iterator it = registeredPullRequestHandlers.begin(); it != registeredPullRequestHandlers.end(); it++) {
if((*it) == mime_type) {
registeredPullRequestHandlers.erase(it);
break;
}
}
}
break;
}
default: {
LOG_ERROR("Received unsupported message:" << msg.DebugString());
break;
}
}
return 0;
}
bool GatewayServiceHandler::sendPushedData(std::string uri, std::string mimeType, const std::string &data, std::string originUser, MessageScope scope) {
ammo::gateway::protocol::GatewayWrapper *msg = new ammo::gateway::protocol::GatewayWrapper();
ammo::gateway::protocol::PushData *pushMsg = msg->mutable_push_data();
pushMsg->set_uri(uri);
pushMsg->set_mime_type(mimeType);
pushMsg->set_data(data);
pushMsg->set_origin_user(originUser);
msg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_PUSH_DATA);
LOG_DEBUG("Sending Data Push message to connected plugin");
this->sendData(msg);
return true;
}
bool GatewayServiceHandler::sendPullRequest(std::string requestUid, std::string pluginId, std::string mimeType,
std::string query, std::string projection, unsigned int maxResults,
unsigned int startFromCount, bool liveQuery) {
ammo::gateway::protocol::GatewayWrapper *msg = new ammo::gateway::protocol::GatewayWrapper();
ammo::gateway::protocol::PullRequest *pullMsg = msg->mutable_pull_request();
pullMsg->set_request_uid(requestUid);
pullMsg->set_plugin_id(pluginId);
pullMsg->set_mime_type(mimeType);
pullMsg->set_query(query);
pullMsg->set_projection(projection);
pullMsg->set_max_results(maxResults);
pullMsg->set_start_from_count(startFromCount);
pullMsg->set_live_query(liveQuery);
msg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_REQUEST);
LOG_DEBUG("Sending Pull Request message to connected plugin");
this->sendData(msg);
return true;
}
bool GatewayServiceHandler::sendPullResponse(std::string requestUid, std::string pluginId, std::string mimeType,
std::string uri, const std::string& data) {
ammo::gateway::protocol::GatewayWrapper *msg = new ammo::gateway::protocol::GatewayWrapper();
ammo::gateway::protocol::PullResponse *pullRsp = msg->mutable_pull_response();
pullRsp->set_request_uid(requestUid);
pullRsp->set_plugin_id(pluginId);
pullRsp->set_mime_type(mimeType);
pullRsp->set_uri(uri);
pullRsp->set_data(data);
msg->set_type(ammo::gateway::protocol::GatewayWrapper_MessageType_PULL_RESPONSE);
LOG_DEBUG("Sending Pull Response message to connected plugin");
this->sendData(msg);
return true;
}
GatewayServiceHandler::~GatewayServiceHandler() {
LOG_DEBUG("GatewayServiceHandler being destroyed!");
LOG_DEBUG("Unregistering data handlers...");
for(std::vector<std::string>::iterator it = registeredHandlers.begin(); it != registeredHandlers.end(); it++) {
GatewayCore::getInstance()->unregisterDataInterest(*it, SCOPE_ALL, this);
}
LOG_DEBUG("Unregistering pull request handlers...");
for(std::vector<std::string>::iterator it = registeredPullRequestHandlers.begin(); it != registeredPullRequestHandlers.end(); it++) {
GatewayCore::getInstance()->unregisterPullInterest(*it, this);
}
LOG_DEBUG("Unregistering pull response plugin IDs...");
for(std::set<std::string>::iterator it = registeredPullResponsePluginIds.begin(); it != registeredPullResponsePluginIds.end(); it++) {
GatewayCore::getInstance()->unregisterPullResponsePluginId(*it, this);
}
}
std::ostream& operator<< (std::ostream& out, const GatewayServiceHandler& handler) {
out << &handler;
return out;
}
std::ostream& operator<< (std::ostream& out, const GatewayServiceHandler* handler) {
// Since operator<< is a friend of the GatewayServiceHandler class,
// we can access handler's members directly.
out << "(" << reinterpret_cast<void const *>(handler) << " " << handler->state << ", " << handler->username << ")";
return out;
}
<|endoftext|> |
<commit_before>#include <QFile>
#include <quazip/quazip.h>
#include <quazip/quazipfile.h>
/* A simple test program. Requires "test.zip" and writable "out"
* directory to be present in the current directory.
*
* To test unicode-aware case sensitivity, see testCase() function.
*/
// test reading archive
bool testRead()
{
QuaZip zip("test.zip");
if(!zip.open(QuaZip::mdUnzip)) {
qWarning("testRead(): zip.open(): %d", zip.getZipError());
return false;
}
zip.setFileNameCodec("IBM866");
printf("%d entries\n", zip.getEntriesCount());
printf("Global comment: %s\n", zip.getComment().constData());
QuaZipFileInfo info;
printf("name\tcver\tnver\tflags\tmethod\tctime\tCRC\tcsize\tusize\tdisknum\tIA\tEA\tcomment\textra\n");
QuaZipFile file(&zip);
QFile out;
QString name;
char c;
for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
if(!zip.getCurrentFileInfo(&info)) {
qWarning("testRead(): getCurrentFileInfo(): %d\n", zip.getZipError());
return false;
}
printf("%s\t%hu\t%hu\t%hu\t%hu\t%s\t%u\t%u\t%u\t%hu\t%hu\t%u\t%s\t%s\n",
info.name.toLocal8Bit().constData(),
info.versionCreated, info.versionNeeded, info.flags, info.method,
info.dateTime.toString(Qt::ISODate).toLocal8Bit().constData(),
info.crc, info.compressedSize, info.uncompressedSize, info.diskNumberStart,
info.internalAttr, info.externalAttr,
info.comment.toLocal8Bit().constData(), info.extra.constData());
if(!file.open(QIODevice::ReadOnly)) {
qWarning("testRead(): file.open(): %d", file.getZipError());
return false;
}
name=file.getActualFileName();
if(file.getZipError()!=UNZ_OK) {
qWarning("testRead(): file.getFileName(): %d", file.getZipError());
return false;
}
out.setFileName("out/"+name);
// this will fail if "name" contains subdirectories, but we don't mind that
out.open(QIODevice::WriteOnly);
// Slow like hell (on GNU/Linux at least), but it is not my fault.
// Not ZIP/UNZIP package's fault either.
// The slowest thing here is out.putChar(c).
while(file.getChar(&c)) out.putChar(c);
out.close();
if(file.getZipError()!=UNZ_OK) {
qWarning("testRead(): file.getFileName(): %d", file.getZipError());
return false;
}
if(!file.atEnd()) {
qWarning("testRead(): read all but not EOF");
return false;
}
file.close();
if(file.getZipError()!=UNZ_OK) {
qWarning("testRead(): file.close(): %d", file.getZipError());
return false;
}
}
zip.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testRead(): zip.close(): %d", zip.getZipError());
return false;
}
return true;
}
// test pos(), size(), csize(), usize(), ungetChar(), bytesAvailable()
bool testPos()
{
QuaZip zip("test.zip");
if(!zip.open(QuaZip::mdUnzip)) {
qWarning("testPos(): zip.open(): %d", zip.getZipError());
return false;
}
if(!zip.goToFirstFile()) {
qWarning("testPos(): zip.goToFirstFile(): %d", zip.getZipError());
return false;
}
QuaZipFile file(&zip);
int method;
if(!file.open(QIODevice::ReadOnly, &method, NULL, true)) {
qWarning("testPos(): file.open(raw): %d", file.getZipError());
return false;
}
QByteArray array=file.readAll();
if(array.isEmpty()) {
qWarning("testPos(): file.readAll(): %d", file.getZipError());
return false;
}
qint64 pos=file.pos();
if(pos!=file.size()||file.size()!=file.csize()) {
qWarning("testPos(): pos=%Ld, file.size()=%Ld, file.csize()=%Ld", pos, file.size(), file.csize());
return false;
}
char last=array.at(array.size()-1);
file.ungetChar(last);
char next;
if(!file.getChar(&next)) {
qWarning("testPos(): file.getChar(): %d", file.getZipError());
return false;
}
if(last!=next) {
qWarning("testPos(): ungot %d, got %d", (int)(uchar)last, (int)(uchar)next);
return false;
}
if(file.pos()!=pos) { // position should not change
qWarning("testPos(): position changed: old pos=%Ld, new pos=%Ld", pos, file.pos());
return false;
}
file.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testPos(): file.close(raw): %d", file.getZipError());
return false;
}
if(!file.open(QIODevice::ReadOnly, &method, NULL, false)) {
qWarning("testPos(): file.open(): %d", file.getZipError());
return false;
}
array=file.readAll();
pos=file.pos();
if(pos!=file.size()||file.size()!=file.usize()) {
qWarning("testPos(): pos=%Ld, file.size()=%Ld, file.usize()=%Ld", pos, file.size(), file.usize());
return false;
}
file.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testPos(): file.close(): %d", file.getZipError());
return false;
}
zip.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testPos(): zip.close(): %d", zip.getZipError());
return false;
}
return true;
}
// test unicode-aware case sensitivity
// change the name and file name codec below before compiling
bool testCase()
{
QString name=QString::fromUtf8("01_КАФЕ НА ТРОТУАРЕ.OGG");
QuaZip zip("test.zip");
if(!zip.open(QuaZip::mdUnzip)) {
qWarning("testCase(): zip.open(): %d", zip.getZipError());
return false;
}
zip.setFileNameCodec("IBM866");
if(!zip.setCurrentFile(name, QuaZip::csInsensitive)) {
if(zip.getZipError()==UNZ_OK)
qWarning("testCase(): setCurrentFile(): check the file name");
else
qWarning("testCase(): setCurrentFile(): %d", zip.getZipError());
return false;
}
if(zip.setCurrentFile(name, QuaZip::csSensitive)) {
qWarning("testCase(): setCurrentFile(): sets even if the case is wrong");
return false;
}
zip.close();
return true;
}
int main()
{
if(!testRead()) return 1;
if(!testPos()) return 1;
if(!testCase()) return 1;
return 0;
}
<commit_msg>Fixed: comment encoding.<commit_after>#include <QFile>
#include <quazip/quazip.h>
#include <quazip/quazipfile.h>
/* A simple test program. Requires "test.zip" and writable "out"
* directory to be present in the current directory.
*
* To test unicode-aware case sensitivity, see testCase() function.
*/
// test reading archive
bool testRead()
{
QuaZip zip("test.zip");
if(!zip.open(QuaZip::mdUnzip)) {
qWarning("testRead(): zip.open(): %d", zip.getZipError());
return false;
}
zip.setFileNameCodec("IBM866");
printf("%d entries\n", zip.getEntriesCount());
printf("Global comment: %s\n", zip.getComment().toLocal8Bit().constData());
QuaZipFileInfo info;
printf("name\tcver\tnver\tflags\tmethod\tctime\tCRC\tcsize\tusize\tdisknum\tIA\tEA\tcomment\textra\n");
QuaZipFile file(&zip);
QFile out;
QString name;
char c;
for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
if(!zip.getCurrentFileInfo(&info)) {
qWarning("testRead(): getCurrentFileInfo(): %d\n", zip.getZipError());
return false;
}
printf("%s\t%hu\t%hu\t%hu\t%hu\t%s\t%u\t%u\t%u\t%hu\t%hu\t%u\t%s\t%s\n",
info.name.toLocal8Bit().constData(),
info.versionCreated, info.versionNeeded, info.flags, info.method,
info.dateTime.toString(Qt::ISODate).toLocal8Bit().constData(),
info.crc, info.compressedSize, info.uncompressedSize, info.diskNumberStart,
info.internalAttr, info.externalAttr,
info.comment.toLocal8Bit().constData(), info.extra.constData());
if(!file.open(QIODevice::ReadOnly)) {
qWarning("testRead(): file.open(): %d", file.getZipError());
return false;
}
name=file.getActualFileName();
if(file.getZipError()!=UNZ_OK) {
qWarning("testRead(): file.getFileName(): %d", file.getZipError());
return false;
}
out.setFileName("out/"+name);
// this will fail if "name" contains subdirectories, but we don't mind that
out.open(QIODevice::WriteOnly);
// Slow like hell (on GNU/Linux at least), but it is not my fault.
// Not ZIP/UNZIP package's fault either.
// The slowest thing here is out.putChar(c).
while(file.getChar(&c)) out.putChar(c);
out.close();
if(file.getZipError()!=UNZ_OK) {
qWarning("testRead(): file.getFileName(): %d", file.getZipError());
return false;
}
if(!file.atEnd()) {
qWarning("testRead(): read all but not EOF");
return false;
}
file.close();
if(file.getZipError()!=UNZ_OK) {
qWarning("testRead(): file.close(): %d", file.getZipError());
return false;
}
}
zip.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testRead(): zip.close(): %d", zip.getZipError());
return false;
}
return true;
}
// test pos(), size(), csize(), usize(), ungetChar(), bytesAvailable()
bool testPos()
{
QuaZip zip("test.zip");
if(!zip.open(QuaZip::mdUnzip)) {
qWarning("testPos(): zip.open(): %d", zip.getZipError());
return false;
}
if(!zip.goToFirstFile()) {
qWarning("testPos(): zip.goToFirstFile(): %d", zip.getZipError());
return false;
}
QuaZipFile file(&zip);
int method;
if(!file.open(QIODevice::ReadOnly, &method, NULL, true)) {
qWarning("testPos(): file.open(raw): %d", file.getZipError());
return false;
}
QByteArray array=file.readAll();
if(array.isEmpty()) {
qWarning("testPos(): file.readAll(): %d", file.getZipError());
return false;
}
qint64 pos=file.pos();
if(pos!=file.size()||file.size()!=file.csize()) {
qWarning("testPos(): pos=%Ld, file.size()=%Ld, file.csize()=%Ld", pos, file.size(), file.csize());
return false;
}
char last=array.at(array.size()-1);
file.ungetChar(last);
char next;
if(!file.getChar(&next)) {
qWarning("testPos(): file.getChar(): %d", file.getZipError());
return false;
}
if(last!=next) {
qWarning("testPos(): ungot %d, got %d", (int)(uchar)last, (int)(uchar)next);
return false;
}
if(file.pos()!=pos) { // position should not change
qWarning("testPos(): position changed: old pos=%Ld, new pos=%Ld", pos, file.pos());
return false;
}
file.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testPos(): file.close(raw): %d", file.getZipError());
return false;
}
if(!file.open(QIODevice::ReadOnly, &method, NULL, false)) {
qWarning("testPos(): file.open(): %d", file.getZipError());
return false;
}
array=file.readAll();
pos=file.pos();
if(pos!=file.size()||file.size()!=file.usize()) {
qWarning("testPos(): pos=%Ld, file.size()=%Ld, file.usize()=%Ld", pos, file.size(), file.usize());
return false;
}
file.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testPos(): file.close(): %d", file.getZipError());
return false;
}
zip.close();
if(zip.getZipError()!=UNZ_OK) {
qWarning("testPos(): zip.close(): %d", zip.getZipError());
return false;
}
return true;
}
// test unicode-aware case sensitivity
// change the name and file name codec below before compiling
bool testCase()
{
QString name=QString::fromUtf8("01_КАФЕ НА ТРОТУАРЕ.OGG");
QuaZip zip("test.zip");
if(!zip.open(QuaZip::mdUnzip)) {
qWarning("testCase(): zip.open(): %d", zip.getZipError());
return false;
}
zip.setFileNameCodec("IBM866");
if(!zip.setCurrentFile(name, QuaZip::csInsensitive)) {
if(zip.getZipError()==UNZ_OK)
qWarning("testCase(): setCurrentFile(): check the file name");
else
qWarning("testCase(): setCurrentFile(): %d", zip.getZipError());
return false;
}
if(zip.setCurrentFile(name, QuaZip::csSensitive)) {
qWarning("testCase(): setCurrentFile(): sets even if the case is wrong");
return false;
}
zip.close();
return true;
}
int main()
{
if(!testRead()) return 1;
if(!testPos()) return 1;
if(!testCase()) return 1;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_SUBSCRIBER_HPP
#define LIBBITCOIN_SUBSCRIBER_HPP
#include <functional>
#include <memory>
#include <stack>
#include <bitcoin/bitcoin/utility/assert.hpp>
#include <bitcoin/bitcoin/utility/async_strand.hpp>
#include <bitcoin/bitcoin/utility/threadpool.hpp>
namespace libbitcoin {
template <typename... Args>
class subscriber
: public std::enable_shared_from_this<subscriber<Args...>>
{
public:
typedef std::function<void (Args...)> handler_type;
typedef std::shared_ptr<subscriber<Args...>> ptr;
subscriber(threadpool& pool)
: strand_(pool)
{
}
void subscribe(handler_type handle)
{
auto dispatch_subscribe =
strand_.wrap(&subscriber<Args...>::do_subscribe,
shared_from_this(), handle);
dispatch_subscribe();
}
void relay(Args... params)
{
auto dispatch_relay =
strand_.wrap(&subscriber<Args...>::do_relay,
shared_from_this(), std::forward<Args>(params)...);
dispatch_relay();
}
private:
typedef std::stack<handler_type> registry_stack;
void do_subscribe(handler_type handle)
{
registry_.push(handle);
}
void do_relay(Args... params)
{
auto notify_copy = registry_;
registry_ = registry_stack();
while (!notify_copy.empty())
{
notify_copy.top()(params...);
notify_copy.pop();
}
BITCOIN_ASSERT(notify_copy.empty());
}
async_strand strand_;
registry_stack registry_;
};
// TODO: push into subscriber<Agrs...> (interface break).
template <typename... Args>
using subscriber_ptr = std::shared_ptr<subscriber<Args...>>;
} // namespace libbitcoin
#endif
<commit_msg>Use explicit this->shared_from_this().<commit_after>/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_SUBSCRIBER_HPP
#define LIBBITCOIN_SUBSCRIBER_HPP
#include <functional>
#include <memory>
#include <stack>
#include <bitcoin/bitcoin/utility/assert.hpp>
#include <bitcoin/bitcoin/utility/async_strand.hpp>
#include <bitcoin/bitcoin/utility/threadpool.hpp>
namespace libbitcoin {
template <typename... Args>
class subscriber
: public std::enable_shared_from_this<subscriber<Args...>>
{
public:
typedef std::function<void (Args...)> handler_type;
typedef std::shared_ptr<subscriber<Args...>> ptr;
subscriber(threadpool& pool)
: strand_(pool)
{
}
void subscribe(handler_type handle)
{
auto dispatch_subscribe =
strand_.wrap(&subscriber<Args...>::do_subscribe,
this->shared_from_this(), handle);
dispatch_subscribe();
}
void relay(Args... params)
{
auto dispatch_relay =
strand_.wrap(&subscriber<Args...>::do_relay,
this->shared_from_this(), std::forward<Args>(params)...);
dispatch_relay();
}
private:
typedef std::stack<handler_type> registry_stack;
void do_subscribe(handler_type handle)
{
registry_.push(handle);
}
void do_relay(Args... params)
{
auto notify_copy = registry_;
registry_ = registry_stack();
while (!notify_copy.empty())
{
notify_copy.top()(params...);
notify_copy.pop();
}
BITCOIN_ASSERT(notify_copy.empty());
}
async_strand strand_;
registry_stack registry_;
};
// TODO: push into subscriber<Agrs...> (interface break).
template <typename... Args>
using subscriber_ptr = std::shared_ptr<subscriber<Args...>>;
} // namespace libbitcoin
#endif
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// \file hardware_concurrency.hpp
/// ------------------------------
///
/// (c) Copyright Domagoj Saric 2016 - 2019.
///
/// Use, modification and distribution are subject to the
/// Boost Software License, Version 1.0. (See accompanying file
/// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See http://www.boost.org for most recent version.
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#ifndef hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#define hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#pragma once
//------------------------------------------------------------------------------
#ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
# if defined( __EMSCRIPTEN__ ) && !defined( __EMSCRIPTEN_PTHREADS__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 1
# elif defined( __ANDROID__ )
# if defined( __aarch64__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 32 // SGS6 8, Meizu PRO 6 10 cores
# elif defined( __arm__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8
# endif // arch
# elif defined( __APPLE__ )
# if defined( __aarch64__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 // iPad 2 Air 3, iPhone 8 6 cores
# elif defined( __arm__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 // desktop or simulator
# endif // arch
# elif defined(__WINDOWS_PHONE__)
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0
# endif // platform
#endif // BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
#ifdef __ANDROID__
# include <unistd.h>
#endif // __ANDROID__
#ifdef __EMSCRIPTEN_PTHREADS__
# include <emscripten/threading.h>
#endif // __EMSCRIPTEN_PTHREADS__
#ifdef __linux__
# include <sys/sysinfo.h>
#endif // __linux__
#if BOOST_SWEATER_DOCKER_LIMITS
# include <fcntl.h>
# include <sys/types.h>
#endif
#ifdef _MSC_VER
# include <yvals.h>
# pragma detect_mismatch( "BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY", _STRINGIZE( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY ) )
#endif // _MSC_VER
#include <cstdint>
#include <thread>
//------------------------------------------------------------------------------
#ifdef __ANDROID__
// https://android.googlesource.com/platform/bionic/+/HEAD/docs/status.md
__attribute__(( weak )) int get_nprocs () noexcept { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_ONLN ) ); }
__attribute__(( weak )) int get_nprocs_conf() noexcept { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_CONF ) ); }
#endif // __ANDROID__
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace sweater
{
//------------------------------------------------------------------------------
#if defined( __arm__ ) || defined( __aarch64__ ) || defined( __ANDROID__ ) || defined( __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ )
using hardware_concurrency_t = std::uint_fast8_t;
#else
using hardware_concurrency_t = std::uint_fast16_t; // e.g. Intel MIC
#endif
#if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY == 1
inline hardware_concurrency_t hardware_concurrency_current() noexcept { return 1; }
inline hardware_concurrency_t const hardware_concurrency_max{ 1 };
inline struct hardware_concurrency_max_t
{
hardware_concurrency_t const value = detail::get_hardware_concurrency_max();
operator hardware_concurrency_t() const noexcept { return value; }
} const hardware_concurrency_max __attribute__(( init_priority( 101 ) ));
#elif BOOST_SWEATER_DOCKER_LIMITS
namespace detail
{
int read_int( char const * const file_path ) noexcept
{
auto const fd( ::open( file_path, O_RDONLY, 0 ) );
if ( fd == -1 )
return -1;
char value[ 64 ];
BOOST_VERIFY( ::read( fd, value, sizeof( value ) ) < signed( sizeof( value ) ) );
return std::atoi( value );
}
inline auto const get_docker_limit() noexcept
{
// https://bugs.openjdk.java.net/browse/JDK-8146115
// http://hg.openjdk.java.net/jdk/hs/rev/7f22774a5f42
// RAM limit /sys/fs/cgroup/memory.limit_in_bytes
// swap limt /sys/fs/cgroup/memory.memsw.limit_in_bytes
auto const cfs_quota ( read_int( "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" ) );
auto const cfs_period( read_int( "/sys/fs/cgroup/cpu/cpu.cfs_period_us" ) );
if ( ( cfs_quota > 0 ) && ( cfs_period > 0 ) )
{
// Docker allows non-whole core quota assignments - use some sort of
// heurestical rounding.
return std::max( ( cfs_quota + cfs_period / 2 ) / cfs_period, 1 );
}
return -1;
}
} // namespace detail
inline struct hardware_concurrency_max_t
{
auto const docker_quota = detail::get_docker_limit();
auto const value = static_cast<hardware_concurrency_t>( ( docker_quota != -1 ) ? docker_quota : get_nprocs_conf() );
operator hardware_concurrency_t() const noexcept { return value; }
} const hardware_concurrency_max __attribute__(( init_priority( 101 ) ));
inline auto hardware_concurrency_current() noexcept { return static_cast<hardware_concurrency_t>( ( hardware_concurrency_max.docker_quota != -1 ) ? hardware_concurrency_max.docker_quota : get_nprocs() ); }
#else // generic/standard impl
namespace detail
{
inline auto get_hardware_concurrency_max() noexcept
{
return static_cast<hardware_concurrency_t>
(
# if defined( __EMSCRIPTEN_PTHREADS__ )
emscripten_has_threading_support() ? emscripten_num_logical_cores() : 1
# elif defined( __linux__ )
// libcpp std::thread::hardware_concurrency() returns the dynamic number of active cores.
get_nprocs_conf()
# else
std::thread::hardware_concurrency()
# endif
);
}
} // namespace detail
inline auto hardware_concurrency_current() noexcept
{
return static_cast<hardware_concurrency_t>
(
# if defined( __EMSCRIPTEN_PTHREADS__ )
detail::get_hardware_concurrency_max()
# elif defined( __linux__ )
get_nprocs()
# else
std::thread::hardware_concurrency()
# endif
);
}
#ifdef __GNUC__
// http://clang-developers.42468.n3.nabble.com/Clang-equivalent-to-attribute-init-priority-td4034229.html
// https://gcc.gnu.org/ml/gcc-help/2011-05/msg00221.html
// "can only use 'init_priority' attribute on file-scope definitions of objects of class type"
inline struct hardware_concurrency_max_t
{
hardware_concurrency_t const value = detail::get_hardware_concurrency_max();
operator hardware_concurrency_t() const noexcept { return value; }
} const hardware_concurrency_max __attribute__(( init_priority( 101 ) ));
#else
inline auto const hardware_concurrency_max( detail::get_hardware_concurrency_max() );
#endif // compiler
#endif // impl
//------------------------------------------------------------------------------
} // namespace sweater
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
#endif // hardware_concurrency_hpp
<commit_msg>fix compile and link errors<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// \file hardware_concurrency.hpp
/// ------------------------------
///
/// (c) Copyright Domagoj Saric 2016 - 2019.
///
/// Use, modification and distribution are subject to the
/// Boost Software License, Version 1.0. (See accompanying file
/// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See http://www.boost.org for most recent version.
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#ifndef hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#define hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8
#pragma once
//------------------------------------------------------------------------------
#ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
# if defined( __EMSCRIPTEN__ ) && !defined( __EMSCRIPTEN_PTHREADS__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 1
# elif defined( __ANDROID__ )
# if defined( __aarch64__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 32 // SGS6 8, Meizu PRO 6 10 cores
# elif defined( __arm__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8
# endif // arch
# elif defined( __APPLE__ )
# if defined( __aarch64__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 // iPad 2 Air 3, iPhone 8 6 cores
# elif defined( __arm__ )
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 // desktop or simulator
# endif // arch
# elif defined(__WINDOWS_PHONE__)
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2
# else
# define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0
# endif // platform
#endif // BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY
#ifdef __ANDROID__
# include <unistd.h>
#endif // __ANDROID__
#ifdef __EMSCRIPTEN_PTHREADS__
# include <emscripten/threading.h>
#endif // __EMSCRIPTEN_PTHREADS__
#ifdef __linux__
# include <sys/sysinfo.h>
#endif // __linux__
#if BOOST_SWEATER_DOCKER_LIMITS
# include <boost/assert.hpp>
# include <fcntl.h>
# include <sys/types.h>
# include <unistd.h>
#endif
#ifdef _MSC_VER
# include <yvals.h>
# pragma detect_mismatch( "BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY", _STRINGIZE( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY ) )
#endif // _MSC_VER
#include <cstdint>
#include <thread>
//------------------------------------------------------------------------------
#ifdef __ANDROID__
// https://android.googlesource.com/platform/bionic/+/HEAD/docs/status.md
__attribute__(( weak )) int get_nprocs () noexcept { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_ONLN ) ); }
__attribute__(( weak )) int get_nprocs_conf() noexcept { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_CONF ) ); }
#endif // __ANDROID__
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace sweater
{
//------------------------------------------------------------------------------
#if defined( __arm__ ) || defined( __aarch64__ ) || defined( __ANDROID__ ) || defined( __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ )
using hardware_concurrency_t = std::uint_fast8_t;
#else
using hardware_concurrency_t = std::uint_fast16_t; // e.g. Intel MIC
#endif
#if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY == 1
inline hardware_concurrency_t hardware_concurrency_current() noexcept { return 1; }
inline hardware_concurrency_t const hardware_concurrency_max{ 1 };
inline struct hardware_concurrency_max_t
{
hardware_concurrency_t const value = detail::get_hardware_concurrency_max();
operator hardware_concurrency_t() const noexcept { return value; }
} const hardware_concurrency_max __attribute__(( init_priority( 101 ) ));
#elif BOOST_SWEATER_DOCKER_LIMITS
namespace detail
{
inline int read_int( char const * const file_path ) noexcept
{
auto const fd( ::open( file_path, O_RDONLY, 0 ) );
if ( fd == -1 )
return -1;
char value[ 64 ];
BOOST_VERIFY( ::read( fd, value, sizeof( value ) ) < signed( sizeof( value ) ) );
return std::atoi( value );
}
inline auto const get_docker_limit() noexcept
{
// https://bugs.openjdk.java.net/browse/JDK-8146115
// http://hg.openjdk.java.net/jdk/hs/rev/7f22774a5f42
// RAM limit /sys/fs/cgroup/memory.limit_in_bytes
// swap limt /sys/fs/cgroup/memory.memsw.limit_in_bytes
auto const cfs_quota ( read_int( "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" ) );
auto const cfs_period( read_int( "/sys/fs/cgroup/cpu/cpu.cfs_period_us" ) );
if ( ( cfs_quota > 0 ) && ( cfs_period > 0 ) )
{
// Docker allows non-whole core quota assignments - use some sort of
// heurestical rounding.
return std::max( ( cfs_quota + cfs_period / 2 ) / cfs_period, 1 );
}
return -1;
}
} // namespace detail
inline struct hardware_concurrency_max_t
{
int const docker_quota = detail::get_docker_limit();
hardware_concurrency_t const value = static_cast<hardware_concurrency_t>( ( docker_quota != -1 ) ? docker_quota : get_nprocs_conf() );
operator hardware_concurrency_t() const noexcept { return value; }
} const hardware_concurrency_max __attribute__(( init_priority( 101 ) ));
inline auto hardware_concurrency_current() noexcept { return static_cast<hardware_concurrency_t>( ( hardware_concurrency_max.docker_quota != -1 ) ? hardware_concurrency_max.docker_quota : get_nprocs() ); }
#else // generic/standard impl
namespace detail
{
inline auto get_hardware_concurrency_max() noexcept
{
return static_cast<hardware_concurrency_t>
(
# if defined( __EMSCRIPTEN_PTHREADS__ )
emscripten_has_threading_support() ? emscripten_num_logical_cores() : 1
# elif defined( __linux__ )
// libcpp std::thread::hardware_concurrency() returns the dynamic number of active cores.
get_nprocs_conf()
# else
std::thread::hardware_concurrency()
# endif
);
}
} // namespace detail
inline auto hardware_concurrency_current() noexcept
{
return static_cast<hardware_concurrency_t>
(
# if defined( __EMSCRIPTEN_PTHREADS__ )
detail::get_hardware_concurrency_max()
# elif defined( __linux__ )
get_nprocs()
# else
std::thread::hardware_concurrency()
# endif
);
}
#ifdef __GNUC__
// http://clang-developers.42468.n3.nabble.com/Clang-equivalent-to-attribute-init-priority-td4034229.html
// https://gcc.gnu.org/ml/gcc-help/2011-05/msg00221.html
// "can only use 'init_priority' attribute on file-scope definitions of objects of class type"
inline struct hardware_concurrency_max_t
{
hardware_concurrency_t const value = detail::get_hardware_concurrency_max();
operator hardware_concurrency_t() const noexcept { return value; }
} const hardware_concurrency_max __attribute__(( init_priority( 101 ) ));
#else
inline auto const hardware_concurrency_max( detail::get_hardware_concurrency_max() );
#endif // compiler
#endif // impl
//------------------------------------------------------------------------------
} // namespace sweater
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
#endif // hardware_concurrency_hpp
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2002.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
//
// See http://www.boost.org for most recent version including documentation.
#ifndef BOOST_UNIT_TEST_CONFIG_HPP
#define BOOST_UNIT_TEST_CONFIG_HPP
// BOOST
#include <boost/config.hpp>
namespace boost {
namespace unit_test_framework {
typedef unsigned long unit_test_counter;
namespace detail {
#ifdef BOOST_NO_STD_DISTANCE
template <class T>
std::ptrdiff_t distance(const T& x, const T& y)
{
std::ptrdiff_t res = 0;
std::distance( x, y, res );
return res;
}
#else
using std::distance;
#endif
} // namespace detail
} // namespace unit_test_framework
} // namespace boost
// Revision History
// 8 Aug 02 Parameters definition separated (Gennadiy Rozental)
// 5 Oct 01 Initial version (Gennadiy Rozental)
#endif // BOOST_UNIT_TEST_CONFIG_HPP
<commit_msg>missing iterator added<commit_after>// (C) Copyright Gennadiy Rozental 2001-2002.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
//
// See http://www.boost.org for most recent version including documentation.
#ifndef BOOST_UNIT_TEST_CONFIG_HPP
#define BOOST_UNIT_TEST_CONFIG_HPP
// BOOST
#include <boost/config.hpp>
// STL
#include <iterator>
namespace boost {
namespace unit_test_framework {
typedef unsigned long unit_test_counter;
namespace detail {
#ifdef BOOST_NO_STD_DISTANCE
template <class T>
std::ptrdiff_t distance(const T& x, const T& y)
{
std::ptrdiff_t res = 0;
std::distance( x, y, res );
return res;
}
#else
using std::distance;
#endif
} // namespace detail
} // namespace unit_test_framework
} // namespace boost
// Revision History
// 8 Aug 02 Parameters definition separated (Gennadiy Rozental)
// 5 Oct 01 Initial version (Gennadiy Rozental)
#endif // BOOST_UNIT_TEST_CONFIG_HPP
<|endoftext|> |
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_SPRITE_SHEET_HPP
#define NOMLIB_SPRITE_SHEET_HPP
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>
#include <memory>
#include "nomlib/config.hpp"
#include "nomlib/version.hpp"
#include "nomlib/math/Coords.hpp"
#include "nomlib/json.hpp"
namespace nom {
extern const int NOM_SPRITE_SHEET_MAJOR_VERSION;
extern const int NOM_SPRITE_SHEET_MINOR_VERSION;
extern const int NOM_SPRITE_SHEET_PATCH_VERSION;
//#define NOM_DEBUG_SPRITE_SHEET
/// Not implemented; reserved for future usage
#define NOM_DEBUG_SPRITE_SHEET_JSON_SAVE
//#define NOM_DEBUG_SPRITE_SHEET_JSON_LOAD
/// \brief Specialized class container for the creation of sprite sheets via
/// RFC 4627 JSON-compliant file input
class SpriteSheet
{
public:
typedef std::shared_ptr<SpriteSheet> SharedPtr;
/// Default construct for initializing instance variables to their
/// respective defaults.
SpriteSheet ( void );
/// Destructor.
~SpriteSheet ( void );
/// Construct a sprite sheet from an existing sprite sheet file
SpriteSheet ( const std::string& filename );
/// Construct a sprite sheet from a given list of arguments. The total tile
/// count is used if the num_sprites argument is not initialized.
///
/// The filename specified is used only as meta-data.
///
/// Padding is applied on all four sides. Spacing is applied between each
/// tile.
///
/// \todo Re-order these arguments to match the order of instance variables
/// \todo Add additional sanity-check asserts for spacing, padding
/// and so on
SpriteSheet (
const std::string& filename,
int32 sheet_width, int32 sheet_height,
int32 sprite_width, int32 sprite_height,
int32 spacing, int32 padding, int32 num_sprites
);
/// Make a duplicate of this object's instance
SpriteSheet::SharedPtr clone ( void ) const;
/// Get the calculations made for a particular ID number.
const Coords& dimensions ( int32 index ) const;
/// Obtain the number of frames this object contains
int32 frames ( void ) const;
const std::string& sheet_filename ( void ) const;
/// Save the current sprite sheet data calculations to a file as a series
/// of RFC 4627 compliant JSON objects.
bool save ( const std::string& filename );
/// Load saved sprite sheet data from a file encoded as an RFC 4627
/// compliant JSON object.
bool load ( const std::string& filename );
/// Dump the state of this object instance
void dump ( void ) const;
private:
/// Our sprite sheet values container
std::vector<Coords> sheet;
/// Source filename used is saved with the output (meta-data)
std::string sheet_filename_;
/// Source number of sprites specified; this is saved with the resulting
/// output as meta-data
int32 sheet_sprites;
/// Source spacing used is saved with the output (meta-data)
int32 sheet_spacing;
/// Source padding used is saved with the output (meta-data)
int32 sheet_padding;
/// Source sheet_width used is saved with the output (meta-data)
int32 sheet_width;
/// Source sheet_height used is saved with the output (meta-data)
int32 sheet_height;
};
} // namespace nom
#endif // include guard defined
/// \class nom::SpriteSheet
/// \ingroup graphics
///
/// [DESCRIPTION STUB]
///
/// \code
///
/// Example of 4X4 Sheet
/// ________________
/// | 0 | 1 | 2 | 3 |
/// |===============|
/// | 0 | 1 | 2 | 3 |
/// |===============|
/// | 0 | 1 | 2 | 3 |
/// |===============|
/// | 0 | 1 | 2 | 3 |
/// |---------------|
///
/// \endcode
///
/// Usage example:
/// \code
///
/// #include <nomlib/graphics/SpriteSheet.hpp>
/// #include <nomlib/graphics/Sprite.hpp>
///
/// nom::SpriteSheet card_faces_sheet ( "faces.png", 256, 262, 64, 64, 0, 1, 16 );
/// card_faces_sheet.save( "faces.json" );
///
/// nom::Sprite card_face = nom::Sprite ( card_faces_sheet );
///
/// // ...or!
///
/// nom::Sprite card_face ( nom::SpriteSheet ( card_faces_sheet ( "faces.json" ) ) );
///
/// \endcode
///
///
/// \code
///
/// REFERENCES
///
/// 1. http://www.dreamincode.net/forums/topic/179429-sdl-sprite-sheet/
/// \endcode
///
/// \todo Re-design the JSON layout used, perhaps with something like:
/// { "metadata": { }, "<filename>": { "<ID>": { } } }
///
/// \todo Re-consider our sheet vector's data type (nom::Coords); we should
/// ideally be loading the object's ID into this vector
///
/// \todo Create structs for our instance vars
///
/// \todo Buffer the file meta-data like we do the other JSON objects inside
/// load method
<commit_msg>Update header files in usage example for SpriteSheet<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_SPRITE_SHEET_HPP
#define NOMLIB_SPRITE_SHEET_HPP
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>
#include <memory>
#include "nomlib/config.hpp"
#include "nomlib/version.hpp"
#include "nomlib/math/Coords.hpp"
#include "nomlib/json.hpp"
namespace nom {
extern const int NOM_SPRITE_SHEET_MAJOR_VERSION;
extern const int NOM_SPRITE_SHEET_MINOR_VERSION;
extern const int NOM_SPRITE_SHEET_PATCH_VERSION;
//#define NOM_DEBUG_SPRITE_SHEET
/// Not implemented; reserved for future usage
#define NOM_DEBUG_SPRITE_SHEET_JSON_SAVE
//#define NOM_DEBUG_SPRITE_SHEET_JSON_LOAD
/// \brief Specialized class container for the creation of sprite sheets via
/// RFC 4627 JSON-compliant file input
class SpriteSheet
{
public:
typedef std::shared_ptr<SpriteSheet> SharedPtr;
/// Default construct for initializing instance variables to their
/// respective defaults.
SpriteSheet ( void );
/// Destructor.
~SpriteSheet ( void );
/// Construct a sprite sheet from an existing sprite sheet file
SpriteSheet ( const std::string& filename );
/// Construct a sprite sheet from a given list of arguments. The total tile
/// count is used if the num_sprites argument is not initialized.
///
/// The filename specified is used only as meta-data.
///
/// Padding is applied on all four sides. Spacing is applied between each
/// tile.
///
/// \todo Re-order these arguments to match the order of instance variables
/// \todo Add additional sanity-check asserts for spacing, padding
/// and so on
SpriteSheet (
const std::string& filename,
int32 sheet_width, int32 sheet_height,
int32 sprite_width, int32 sprite_height,
int32 spacing, int32 padding, int32 num_sprites
);
/// Make a duplicate of this object's instance
SpriteSheet::SharedPtr clone ( void ) const;
/// Get the calculations made for a particular ID number.
const Coords& dimensions ( int32 index ) const;
/// Obtain the number of frames this object contains
int32 frames ( void ) const;
const std::string& sheet_filename ( void ) const;
/// Save the current sprite sheet data calculations to a file as a series
/// of RFC 4627 compliant JSON objects.
bool save ( const std::string& filename );
/// Load saved sprite sheet data from a file encoded as an RFC 4627
/// compliant JSON object.
bool load ( const std::string& filename );
/// Dump the state of this object instance
void dump ( void ) const;
private:
/// Our sprite sheet values container
std::vector<Coords> sheet;
/// Source filename used is saved with the output (meta-data)
std::string sheet_filename_;
/// Source number of sprites specified; this is saved with the resulting
/// output as meta-data
int32 sheet_sprites;
/// Source spacing used is saved with the output (meta-data)
int32 sheet_spacing;
/// Source padding used is saved with the output (meta-data)
int32 sheet_padding;
/// Source sheet_width used is saved with the output (meta-data)
int32 sheet_width;
/// Source sheet_height used is saved with the output (meta-data)
int32 sheet_height;
};
} // namespace nom
#endif // include guard defined
/// \class nom::SpriteSheet
/// \ingroup graphics
///
/// [DESCRIPTION STUB]
///
/// \code
///
/// Example of 4X4 Sheet
/// ________________
/// | 0 | 1 | 2 | 3 |
/// |===============|
/// | 0 | 1 | 2 | 3 |
/// |===============|
/// | 0 | 1 | 2 | 3 |
/// |===============|
/// | 0 | 1 | 2 | 3 |
/// |---------------|
///
/// \endcode
///
/// Usage example:
/// \code
///
/// #include <nomlib/graphics/graphics.hpp>
///
/// nom::SpriteSheet card_faces_sheet ( "faces.png", 256, 262, 64, 64, 0, 1, 16 );
/// card_faces_sheet.save( "faces.json" );
///
/// nom::Sprite card_face = nom::Sprite ( card_faces_sheet );
///
/// // ...or!
///
/// nom::Sprite card_face ( nom::SpriteSheet ( card_faces_sheet ( "faces.json" ) ) );
///
/// \endcode
///
///
/// \code
///
/// REFERENCES
///
/// 1. http://www.dreamincode.net/forums/topic/179429-sdl-sprite-sheet/
/// \endcode
///
/// \todo Re-design the JSON layout used, perhaps with something like:
/// { "metadata": { }, "<filename>": { "<ID>": { } } }
///
/// \todo Re-consider our sheet vector's data type (nom::Coords); we should
/// ideally be loading the object's ID into this vector
///
/// \todo Create structs for our instance vars
///
/// \todo Buffer the file meta-data like we do the other JSON objects inside
/// load method
<|endoftext|> |
<commit_before>#ifndef TABLE_PARAMETERS_GRAMMAR_HPP
#define TABLE_PARAMETERS_GRAMMAR_HPP
#include "engine/api/table_parameters.hpp"
#include "server/api/base_parameters_grammar.hpp"
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
namespace osrm
{
namespace server
{
namespace api
{
namespace qi = boost::spirit::qi;
struct TableParametersGrammar final : public BaseParametersGrammar
{
using Iterator = std::string::iterator;
using SourcesT = std::vector<std::size_t>;
using DestinationsT = std::vector<std::size_t>;
TableParametersGrammar() : BaseParametersGrammar(root_rule, parameters)
{
const auto set_destiantions = [this](DestinationsT dests) {
parameters.destinations = std::move(dests);
};
const auto set_sources = [this](SourcesT sources) {
parameters.sources = std::move(sources);
};
#ifdef BOOST_HAS_LONG_LONG
destinations_rule = (qi::lit("destinations=") > (qi::ulong_long % ";")[set_destiantions]) |
qi::lit("destinations=all");
sources_rule =
(qi::lit("sources=") > (qi::ulong_long % ";")[set_sources]) | qi::lit("sources=all");
#else
destinations_rule = (qi::lit("destinations=") > (qi::ulong_ % ";")[set_destiantions]) |
qi::lit("destinations=all");
sources_rule =
(qi::lit("sources=") > (qi::ulong_ % ";")[set_sources]) | qi::lit("sources=all");
#endif
table_rule = destinations_rule | sources_rule;
root_rule =
query_rule > -qi::lit(".json") > -(qi::lit("?") > (table_rule | base_rule) % '&');
}
engine::api::TableParameters parameters;
private:
qi::rule<Iterator> root_rule;
qi::rule<Iterator> table_rule;
qi::rule<Iterator> sources_rule;
qi::rule<Iterator> destinations_rule;
};
}
}
}
#endif
<commit_msg>Fixes regression introduced in 8ff8dc.<commit_after>#ifndef TABLE_PARAMETERS_GRAMMAR_HPP
#define TABLE_PARAMETERS_GRAMMAR_HPP
#include "engine/api/table_parameters.hpp"
#include "server/api/base_parameters_grammar.hpp"
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
namespace osrm
{
namespace server
{
namespace api
{
namespace qi = boost::spirit::qi;
struct TableParametersGrammar final : public BaseParametersGrammar
{
using Iterator = std::string::iterator;
using SourcesT = std::vector<std::size_t>;
using DestinationsT = std::vector<std::size_t>;
TableParametersGrammar() : BaseParametersGrammar(root_rule, parameters)
{
const auto set_destiantions = [this](DestinationsT dests) {
parameters.destinations = std::move(dests);
};
const auto set_sources = [this](SourcesT sources) {
parameters.sources = std::move(sources);
};
// TODO: ulonglong -> size_t not only on Windows but on all 32 bit platforms; unsupported anyway as of now
#ifdef WIN32
destinations_rule = (qi::lit("destinations=") > (qi::ulong_long % ";")[set_destiantions]) |
qi::lit("destinations=all");
sources_rule =
(qi::lit("sources=") > (qi::ulong_long % ";")[set_sources]) | qi::lit("sources=all");
#else
destinations_rule = (qi::lit("destinations=") > (qi::ulong_ % ";")[set_destiantions]) |
qi::lit("destinations=all");
sources_rule =
(qi::lit("sources=") > (qi::ulong_ % ";")[set_sources]) | qi::lit("sources=all");
#endif
table_rule = destinations_rule | sources_rule;
root_rule =
query_rule > -qi::lit(".json") > -(qi::lit("?") > (table_rule | base_rule) % '&');
}
engine::api::TableParameters parameters;
private:
qi::rule<Iterator> root_rule;
qi::rule<Iterator> table_rule;
qi::rule<Iterator> sources_rule;
qi::rule<Iterator> destinations_rule;
};
}
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_to_mobile_service.h"
#include "base/bind.h"
#include "base/json/json_writer.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/printing/cloud_print/cloud_print_url.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/token_service.h"
#include "chrome/browser/signin/token_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/cloud_print/cloud_print_helpers.h"
#include "chrome/common/guid.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "chrome/common/net/gaia/gaia_urls.h"
#include "chrome/common/net/gaia/oauth2_access_token_fetcher.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_fetcher.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
namespace {
// The maximum number of retries for the URLFetcher requests.
size_t kMaxRetries = 10;
// The number of seconds between automated URLFetcher requests.
size_t kRetryDelay = 300;
// The cloud print OAuth2 scope and 'printer' type of compatible mobile devices.
const char kOAuthScope[] = "https://www.googleapis.com/auth/cloudprint";
const char kTypeAndroidChromeSnapshot[] = "ANDROID_CHROME_SNAPSHOT";
// The types of Chrome To Mobile requests sent to the cloud print service.
const char kRequestTypeURL[] = "url";
const char kRequestTypeDelayedSnapshot[] = "url_with_delayed_snapshot";
const char kRequestTypeSnapshot[] = "snapshot";
// The snapshot path constants; used with a guid for each MHTML snapshot file.
const FilePath::CharType kSnapshotPath[] =
FILE_PATH_LITERAL("chrome_to_mobile_snapshot_.mht");
// Get the "__c2dm__job_data" tag JSON data for the cloud print job submission.
std::string GetJobString(const ChromeToMobileService::RequestData& data) {
scoped_ptr<DictionaryValue> job(new DictionaryValue());
job->SetString("url", data.url.spec());
if (data.type == ChromeToMobileService::URL) {
job->SetString("type", kRequestTypeURL);
} else {
job->SetString("snapID", data.snapshot_id);
job->SetString("type", (data.type == ChromeToMobileService::SNAPSHOT) ?
kRequestTypeSnapshot : kRequestTypeDelayedSnapshot);
}
std::string job_string;
base::JSONWriter::Write(job.get(), &job_string);
return job_string;
}
// Get the URL for cloud print job submission; appends query params if needed.
GURL GetSubmitURL(const GURL& service_url,
const ChromeToMobileService::RequestData& data) {
GURL submit_url = cloud_print::GetUrlForSubmit(service_url);
if (data.type == ChromeToMobileService::SNAPSHOT)
return submit_url;
// Append form data to the URL's query for |URL| and |DELAYED_SNAPSHOT| jobs.
static const bool kUsePlus = true;
std::string tag_string = net::EscapeQueryParamValue(
"__c2dm__job_data=" + GetJobString(data), kUsePlus);
GURL::Replacements replacements;
// Provide dummy content to workaround |errorCode| 412 'Document missing'.
std::string query = StringPrintf("printerid=%s&tag=%s&title=%s"
"&contentType=text/plain&content=dummy",
net::EscapeQueryParamValue(UTF16ToUTF8(data.mobile_id), kUsePlus).c_str(),
net::EscapeQueryParamValue(tag_string, kUsePlus).c_str(),
net::EscapeQueryParamValue(UTF16ToUTF8(data.title), kUsePlus).c_str());
replacements.SetQueryStr(query);
return submit_url.ReplaceComponents(replacements);
}
// Delete the specified file; called as a BlockingPoolTask.
void DeleteFilePath(const FilePath& file_path) {
bool success = file_util::Delete(file_path, false);
DCHECK(success);
}
// Construct POST data and submit the MHTML snapshot file; deletes the snapshot.
void SubmitSnapshot(content::URLFetcher* request,
const ChromeToMobileService::RequestData& data) {
std::string file;
if (file_util::ReadFileToString(data.snapshot_path, &file) && !file.empty()) {
std::string post_data, mime_boundary;
cloud_print::CreateMimeBoundaryForUpload(&mime_boundary);
cloud_print::AddMultipartValueForUpload("printerid",
UTF16ToUTF8(data.mobile_id), mime_boundary, std::string(), &post_data);
cloud_print::AddMultipartValueForUpload("tag", "__c2dm__job_data=" +
GetJobString(data), mime_boundary, std::string(), &post_data);
cloud_print::AddMultipartValueForUpload("title", UTF16ToUTF8(data.title),
mime_boundary, std::string(), &post_data);
cloud_print::AddMultipartValueForUpload("contentType", "multipart/related",
mime_boundary, std::string(), &post_data);
// Append the snapshot MHTML content and terminate the request body.
post_data.append("--" + mime_boundary + "\r\n"
"Content-Disposition: form-data; "
"name=\"content\"; filename=\"blob\"\r\n"
"Content-Type: text/mhtml\r\n"
"\r\n" + file + "\r\n" "--" + mime_boundary + "--\r\n");
std::string content_type = "multipart/form-data; boundary=" + mime_boundary;
request->SetUploadData(content_type, post_data);
request->Start();
}
content::BrowserThread::PostBlockingPoolTask(FROM_HERE,
base::Bind(&DeleteFilePath, data.snapshot_path));
}
} // namespace
ChromeToMobileService::Observer::~Observer() {}
ChromeToMobileService::RequestData::RequestData() {}
ChromeToMobileService::RequestData::~RequestData() {}
ChromeToMobileService::ChromeToMobileService(Profile* profile)
: profile_(profile),
cloud_print_url_(new CloudPrintURL(profile)) {
// Skip initialization if constructed without a profile.
if (profile_) {
content::BrowserThread::PostBlockingPoolTask(FROM_HERE,
base::Bind(&ChromeToMobileService::CreateUniqueTempDir,
base::Unretained(this)));
TokenService* service = TokenServiceFactory::GetForProfile(profile_);
registrar_.Add(this, chrome::NOTIFICATION_TOKEN_AVAILABLE,
content::Source<TokenService>(service));
if (service->HasOAuthLoginToken())
RefreshAccessToken();
}
}
ChromeToMobileService::~ChromeToMobileService() {}
void ChromeToMobileService::RequestMobileListUpdate() {
if (access_token_.empty())
RefreshAccessToken();
else
RequestSearch();
}
void ChromeToMobileService::GenerateSnapshot(base::WeakPtr<Observer> observer) {
FilePath path(temp_dir_.path().Append(kSnapshotPath));
BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents()->
GenerateMHTML(path.InsertBeforeExtensionASCII(guid::GenerateGUID()),
base::Bind(&Observer::SnapshotGenerated, observer));
}
void ChromeToMobileService::SendToMobile(const string16& mobile_id,
const FilePath& snapshot,
base::WeakPtr<Observer> observer) {
DCHECK(!access_token_.empty());
RequestData data;
data.mobile_id = mobile_id;
content::WebContents* web_contents =
BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents();
data.url = web_contents->GetURL();
data.title = web_contents->GetTitle();
data.snapshot_path = snapshot;
bool send_snapshot = !snapshot.empty();
data.snapshot_id = send_snapshot ? guid::GenerateGUID() : std::string();
data.type = send_snapshot ? DELAYED_SNAPSHOT : URL;
content::URLFetcher* submit_url = CreateRequest(data);
request_observer_map_[submit_url] = observer;
submit_url->Start();
if (send_snapshot) {
data.type = SNAPSHOT;
content::URLFetcher* submit_snapshot = CreateRequest(data);
request_observer_map_[submit_snapshot] = observer;
content::BrowserThread::PostBlockingPoolTask(FROM_HERE,
base::Bind(&SubmitSnapshot, submit_snapshot, data));
}
}
void ChromeToMobileService::OnURLFetchComplete(
const content::URLFetcher* source) {
if (source == search_request_.get())
HandleSearchResponse();
else
HandleSubmitResponse(source);
}
void ChromeToMobileService::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(type == chrome::NOTIFICATION_TOKEN_AVAILABLE);
TokenService::TokenAvailableDetails* token_details =
content::Details<TokenService::TokenAvailableDetails>(details).ptr();
if (token_details->service() == GaiaConstants::kGaiaOAuth2LoginRefreshToken)
RefreshAccessToken();
}
void ChromeToMobileService::OnGetTokenSuccess(
const std::string& access_token) {
DCHECK(!access_token.empty());
access_token_fetcher_.reset();
request_timer_.Stop();
access_token_ = access_token;
RequestMobileListUpdate();
}
void ChromeToMobileService::OnGetTokenFailure(
const GoogleServiceAuthError& error) {
access_token_fetcher_.reset();
request_timer_.Stop();
request_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kRetryDelay),
this, &ChromeToMobileService::RefreshAccessToken);
}
void ChromeToMobileService::CreateUniqueTempDir() {
bool success = temp_dir_.CreateUniqueTempDir();
DCHECK(success);
}
content::URLFetcher* ChromeToMobileService::CreateRequest(
const RequestData& data) {
bool get = data.type != SNAPSHOT;
GURL service_url(cloud_print_url_->GetCloudPrintServiceURL());
content::URLFetcher* request = content::URLFetcher::Create(
data.type == SEARCH ? cloud_print::GetUrlForSearch(service_url) :
GetSubmitURL(service_url, data),
get ? content::URLFetcher::GET : content::URLFetcher::POST, this);
request->SetRequestContext(profile_->GetRequestContext());
request->SetMaxRetries(kMaxRetries);
request->SetExtraRequestHeaders("Authorization: OAuth " +
access_token_ + "\r\n" + cloud_print::kChromeCloudPrintProxyHeader);
request->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
return request;
}
void ChromeToMobileService::RefreshAccessToken() {
if (access_token_fetcher_.get())
return;
std::string token = TokenServiceFactory::GetForProfile(profile_)->
GetOAuth2LoginRefreshToken();
if (token.empty())
return;
request_timer_.Stop();
access_token_fetcher_.reset(
new OAuth2AccessTokenFetcher(this, profile_->GetRequestContext()));
std::vector<std::string> scopes(1, kOAuthScope);
GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
access_token_fetcher_->Start(gaia_urls->oauth2_chrome_client_id(),
gaia_urls->oauth2_chrome_client_secret(), token, scopes);
}
void ChromeToMobileService::RequestSearch() {
DCHECK(!access_token_.empty());
if (search_request_.get())
return;
RequestData data;
data.type = SEARCH;
search_request_.reset(CreateRequest(data));
search_request_->Start();
}
void ChromeToMobileService::HandleSearchResponse() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
std::string data;
search_request_->GetResponseAsString(&data);
search_request_.reset();
DictionaryValue* json_data = NULL;
cloud_print::ParseResponseJSON(data, NULL, &json_data);
ListValue* list = NULL;
if (json_data && json_data->GetList(cloud_print::kPrinterListValue, &list)) {
std::vector<base::DictionaryValue*> mobiles;
for (size_t index = 0; index < list->GetSize(); index++) {
DictionaryValue* mobile_data = NULL;
if (list->GetDictionary(index, &mobile_data)) {
std::string mobile_type;
mobile_data->GetString("type", &mobile_type);
if (mobile_type.compare(kTypeAndroidChromeSnapshot) == 0)
mobiles.push_back(mobile_data);
}
}
mobiles_ = mobiles;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser && browser->command_updater())
browser->command_updater()->UpdateCommandEnabled(
IDC_CHROME_TO_MOBILE_PAGE, !mobiles_.empty());
}
request_timer_.Stop();
request_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kRetryDelay),
this, &ChromeToMobileService::RequestSearch);
}
void ChromeToMobileService::HandleSubmitResponse(
const content::URLFetcher* source) {
// Get the observer for this response; bail if there is none or it is NULL.
RequestObserverMap::iterator i = request_observer_map_.find(source);
if (i == request_observer_map_.end())
return;
base::WeakPtr<Observer> observer = i->second;
request_observer_map_.erase(i);
if (!observer.get())
return;
// Get the success value from the CloudPrint server response data.
std::string data;
source->GetResponseAsString(&data);
DictionaryValue* json_data = NULL;
cloud_print::ParseResponseJSON(data, NULL, &json_data);
bool success = false;
if (json_data)
json_data->GetBoolean("success", &success);
// Check if the observer is waiting on a second response (url and snapshot).
RequestObserverMap::iterator other = request_observer_map_.begin();
for (; other != request_observer_map_.end(); ++other) {
if (other->second == observer) {
// Do not call OnSendComplete for observers waiting on a second response.
if (success)
return;
// Ensure a second response is not sent after reporting failure below.
request_observer_map_.erase(other);
break;
}
}
observer->OnSendComplete(success);
}
<commit_msg>Add Chrome To Mobile requestor search query param. Add "requestor=chrome-to-mobile" cloud print search url query param. This may be used by the cloud print service for filtering requests. This change was requested by rltoscano@google.com<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_to_mobile_service.h"
#include "base/bind.h"
#include "base/json/json_writer.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/printing/cloud_print/cloud_print_url.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/token_service.h"
#include "chrome/browser/signin/token_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/cloud_print/cloud_print_helpers.h"
#include "chrome/common/guid.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "chrome/common/net/gaia/gaia_urls.h"
#include "chrome/common/net/gaia/oauth2_access_token_fetcher.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_fetcher.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
namespace {
// The maximum number of retries for the URLFetcher requests.
size_t kMaxRetries = 10;
// The number of seconds between automated URLFetcher requests.
size_t kRetryDelay = 300;
// The cloud print OAuth2 scope and 'printer' type of compatible mobile devices.
const char kOAuthScope[] = "https://www.googleapis.com/auth/cloudprint";
const char kTypeAndroidChromeSnapshot[] = "ANDROID_CHROME_SNAPSHOT";
// The Chrome To Mobile requestor type; used by the service for filtering.
const char kChromeToMobileRequestor[] = "requestor=chrome-to-mobile";
// The types of Chrome To Mobile requests sent to the cloud print service.
const char kRequestTypeURL[] = "url";
const char kRequestTypeDelayedSnapshot[] = "url_with_delayed_snapshot";
const char kRequestTypeSnapshot[] = "snapshot";
// The snapshot path constants; used with a guid for each MHTML snapshot file.
const FilePath::CharType kSnapshotPath[] =
FILE_PATH_LITERAL("chrome_to_mobile_snapshot_.mht");
// Get the "__c2dm__job_data" tag JSON data for the cloud print job submission.
std::string GetJobString(const ChromeToMobileService::RequestData& data) {
scoped_ptr<DictionaryValue> job(new DictionaryValue());
job->SetString("url", data.url.spec());
if (data.type == ChromeToMobileService::URL) {
job->SetString("type", kRequestTypeURL);
} else {
job->SetString("snapID", data.snapshot_id);
job->SetString("type", (data.type == ChromeToMobileService::SNAPSHOT) ?
kRequestTypeSnapshot : kRequestTypeDelayedSnapshot);
}
std::string job_string;
base::JSONWriter::Write(job.get(), &job_string);
return job_string;
}
// Get the URL for cloud print device search; appends a requestor query param.
GURL GetSearchURL(const GURL& service_url) {
GURL search_url = cloud_print::GetUrlForSearch(service_url);
GURL::Replacements replacements;
std::string query(kChromeToMobileRequestor);
replacements.SetQueryStr(query);
return search_url.ReplaceComponents(replacements);
}
// Get the URL for cloud print job submission; appends query params if needed.
GURL GetSubmitURL(const GURL& service_url,
const ChromeToMobileService::RequestData& data) {
GURL submit_url = cloud_print::GetUrlForSubmit(service_url);
if (data.type == ChromeToMobileService::SNAPSHOT)
return submit_url;
// Append form data to the URL's query for |URL| and |DELAYED_SNAPSHOT| jobs.
static const bool kUsePlus = true;
std::string tag_string = net::EscapeQueryParamValue(
"__c2dm__job_data=" + GetJobString(data), kUsePlus);
GURL::Replacements replacements;
// Provide dummy content to workaround |errorCode| 412 'Document missing'.
std::string query = StringPrintf("printerid=%s&tag=%s&title=%s"
"&contentType=text/plain&content=dummy",
net::EscapeQueryParamValue(UTF16ToUTF8(data.mobile_id), kUsePlus).c_str(),
net::EscapeQueryParamValue(tag_string, kUsePlus).c_str(),
net::EscapeQueryParamValue(UTF16ToUTF8(data.title), kUsePlus).c_str());
replacements.SetQueryStr(query);
return submit_url.ReplaceComponents(replacements);
}
// Delete the specified file; called as a BlockingPoolTask.
void DeleteFilePath(const FilePath& file_path) {
bool success = file_util::Delete(file_path, false);
DCHECK(success);
}
// Construct POST data and submit the MHTML snapshot file; deletes the snapshot.
void SubmitSnapshot(content::URLFetcher* request,
const ChromeToMobileService::RequestData& data) {
std::string file;
if (file_util::ReadFileToString(data.snapshot_path, &file) && !file.empty()) {
std::string post_data, mime_boundary;
cloud_print::CreateMimeBoundaryForUpload(&mime_boundary);
cloud_print::AddMultipartValueForUpload("printerid",
UTF16ToUTF8(data.mobile_id), mime_boundary, std::string(), &post_data);
cloud_print::AddMultipartValueForUpload("tag", "__c2dm__job_data=" +
GetJobString(data), mime_boundary, std::string(), &post_data);
cloud_print::AddMultipartValueForUpload("title", UTF16ToUTF8(data.title),
mime_boundary, std::string(), &post_data);
cloud_print::AddMultipartValueForUpload("contentType", "multipart/related",
mime_boundary, std::string(), &post_data);
// Append the snapshot MHTML content and terminate the request body.
post_data.append("--" + mime_boundary + "\r\n"
"Content-Disposition: form-data; "
"name=\"content\"; filename=\"blob\"\r\n"
"Content-Type: text/mhtml\r\n"
"\r\n" + file + "\r\n" "--" + mime_boundary + "--\r\n");
std::string content_type = "multipart/form-data; boundary=" + mime_boundary;
request->SetUploadData(content_type, post_data);
request->Start();
}
content::BrowserThread::PostBlockingPoolTask(FROM_HERE,
base::Bind(&DeleteFilePath, data.snapshot_path));
}
} // namespace
ChromeToMobileService::Observer::~Observer() {}
ChromeToMobileService::RequestData::RequestData() {}
ChromeToMobileService::RequestData::~RequestData() {}
ChromeToMobileService::ChromeToMobileService(Profile* profile)
: profile_(profile),
cloud_print_url_(new CloudPrintURL(profile)) {
// Skip initialization if constructed without a profile.
if (profile_) {
content::BrowserThread::PostBlockingPoolTask(FROM_HERE,
base::Bind(&ChromeToMobileService::CreateUniqueTempDir,
base::Unretained(this)));
TokenService* service = TokenServiceFactory::GetForProfile(profile_);
registrar_.Add(this, chrome::NOTIFICATION_TOKEN_AVAILABLE,
content::Source<TokenService>(service));
if (service->HasOAuthLoginToken())
RefreshAccessToken();
}
}
ChromeToMobileService::~ChromeToMobileService() {}
void ChromeToMobileService::RequestMobileListUpdate() {
if (access_token_.empty())
RefreshAccessToken();
else
RequestSearch();
}
void ChromeToMobileService::GenerateSnapshot(base::WeakPtr<Observer> observer) {
FilePath path(temp_dir_.path().Append(kSnapshotPath));
BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents()->
GenerateMHTML(path.InsertBeforeExtensionASCII(guid::GenerateGUID()),
base::Bind(&Observer::SnapshotGenerated, observer));
}
void ChromeToMobileService::SendToMobile(const string16& mobile_id,
const FilePath& snapshot,
base::WeakPtr<Observer> observer) {
DCHECK(!access_token_.empty());
RequestData data;
data.mobile_id = mobile_id;
content::WebContents* web_contents =
BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents();
data.url = web_contents->GetURL();
data.title = web_contents->GetTitle();
data.snapshot_path = snapshot;
bool send_snapshot = !snapshot.empty();
data.snapshot_id = send_snapshot ? guid::GenerateGUID() : std::string();
data.type = send_snapshot ? DELAYED_SNAPSHOT : URL;
content::URLFetcher* submit_url = CreateRequest(data);
request_observer_map_[submit_url] = observer;
submit_url->Start();
if (send_snapshot) {
data.type = SNAPSHOT;
content::URLFetcher* submit_snapshot = CreateRequest(data);
request_observer_map_[submit_snapshot] = observer;
content::BrowserThread::PostBlockingPoolTask(FROM_HERE,
base::Bind(&SubmitSnapshot, submit_snapshot, data));
}
}
void ChromeToMobileService::OnURLFetchComplete(
const content::URLFetcher* source) {
if (source == search_request_.get())
HandleSearchResponse();
else
HandleSubmitResponse(source);
}
void ChromeToMobileService::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(type == chrome::NOTIFICATION_TOKEN_AVAILABLE);
TokenService::TokenAvailableDetails* token_details =
content::Details<TokenService::TokenAvailableDetails>(details).ptr();
if (token_details->service() == GaiaConstants::kGaiaOAuth2LoginRefreshToken)
RefreshAccessToken();
}
void ChromeToMobileService::OnGetTokenSuccess(
const std::string& access_token) {
DCHECK(!access_token.empty());
access_token_fetcher_.reset();
request_timer_.Stop();
access_token_ = access_token;
RequestMobileListUpdate();
}
void ChromeToMobileService::OnGetTokenFailure(
const GoogleServiceAuthError& error) {
access_token_fetcher_.reset();
request_timer_.Stop();
request_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kRetryDelay),
this, &ChromeToMobileService::RefreshAccessToken);
}
void ChromeToMobileService::CreateUniqueTempDir() {
bool success = temp_dir_.CreateUniqueTempDir();
DCHECK(success);
}
content::URLFetcher* ChromeToMobileService::CreateRequest(
const RequestData& data) {
bool get = data.type != SNAPSHOT;
GURL service_url(cloud_print_url_->GetCloudPrintServiceURL());
content::URLFetcher* request = content::URLFetcher::Create(
data.type == SEARCH ? GetSearchURL(service_url) :
GetSubmitURL(service_url, data),
get ? content::URLFetcher::GET : content::URLFetcher::POST, this);
request->SetRequestContext(profile_->GetRequestContext());
request->SetMaxRetries(kMaxRetries);
request->SetExtraRequestHeaders("Authorization: OAuth " +
access_token_ + "\r\n" + cloud_print::kChromeCloudPrintProxyHeader);
request->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
return request;
}
void ChromeToMobileService::RefreshAccessToken() {
if (access_token_fetcher_.get())
return;
std::string token = TokenServiceFactory::GetForProfile(profile_)->
GetOAuth2LoginRefreshToken();
if (token.empty())
return;
request_timer_.Stop();
access_token_fetcher_.reset(
new OAuth2AccessTokenFetcher(this, profile_->GetRequestContext()));
std::vector<std::string> scopes(1, kOAuthScope);
GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
access_token_fetcher_->Start(gaia_urls->oauth2_chrome_client_id(),
gaia_urls->oauth2_chrome_client_secret(), token, scopes);
}
void ChromeToMobileService::RequestSearch() {
DCHECK(!access_token_.empty());
if (search_request_.get())
return;
RequestData data;
data.type = SEARCH;
search_request_.reset(CreateRequest(data));
search_request_->Start();
}
void ChromeToMobileService::HandleSearchResponse() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
std::string data;
search_request_->GetResponseAsString(&data);
search_request_.reset();
DictionaryValue* json_data = NULL;
cloud_print::ParseResponseJSON(data, NULL, &json_data);
ListValue* list = NULL;
if (json_data && json_data->GetList(cloud_print::kPrinterListValue, &list)) {
std::vector<base::DictionaryValue*> mobiles;
for (size_t index = 0; index < list->GetSize(); index++) {
DictionaryValue* mobile_data = NULL;
if (list->GetDictionary(index, &mobile_data)) {
std::string mobile_type;
mobile_data->GetString("type", &mobile_type);
if (mobile_type.compare(kTypeAndroidChromeSnapshot) == 0)
mobiles.push_back(mobile_data);
}
}
mobiles_ = mobiles;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser && browser->command_updater())
browser->command_updater()->UpdateCommandEnabled(
IDC_CHROME_TO_MOBILE_PAGE, !mobiles_.empty());
}
request_timer_.Stop();
request_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kRetryDelay),
this, &ChromeToMobileService::RequestSearch);
}
void ChromeToMobileService::HandleSubmitResponse(
const content::URLFetcher* source) {
// Get the observer for this response; bail if there is none or it is NULL.
RequestObserverMap::iterator i = request_observer_map_.find(source);
if (i == request_observer_map_.end())
return;
base::WeakPtr<Observer> observer = i->second;
request_observer_map_.erase(i);
if (!observer.get())
return;
// Get the success value from the CloudPrint server response data.
std::string data;
source->GetResponseAsString(&data);
DictionaryValue* json_data = NULL;
cloud_print::ParseResponseJSON(data, NULL, &json_data);
bool success = false;
if (json_data)
json_data->GetBoolean("success", &success);
// Check if the observer is waiting on a second response (url and snapshot).
RequestObserverMap::iterator other = request_observer_map_.begin();
for (; other != request_observer_map_.end(); ++other) {
if (other->second == observer) {
// Do not call OnSendComplete for observers waiting on a second response.
if (success)
return;
// Ensure a second response is not sent after reporting failure below.
request_observer_map_.erase(other);
break;
}
}
observer->OnSendComplete(success);
}
<|endoftext|> |
<commit_before>#include "socket.h"
#ifndef SOCKET_CPP
#define SOCKET_CPP
class Socket {
public:
Socket();
~Socket();
void connectServer(std::string address, unsigned short port);
bool sendData(std::string message);
std::string receive();
void closeConnection();
bool isConnected();
private:
int socketfd;
sockaddr_in socketAddr;
bool connected;
};
Socket::Socket() {
socketfd = socket(AF_INET, SOCK_STREAM, 0);
socketAddr.sin_family = AF_INET;
connected = false;
}
Socket::~Socket() {
closeConnection();
}
void Socket::connectServer(std::string address, unsigned short port) {
socketAddr.sin_port = htons(port);
inet_pton(AF_INET, address.c_str(), &socketAddr.sin_addr);
int status;
// TODO: resolve DNS
status = connect(socketfd, (sockaddr*) &socketAddr, sizeof(socketAddr));
if (status != 0) {
perror("Could not connect to server");
connected = false;
} else {
std::cout << "Successfully connected to " << address << std::endl;
connected = true;
}
}
void Socket::closeConnection() {
close(socketfd);
connected = false;
}
bool Socket::isConnected() {
return connected;
}
bool Socket::sendData(std::string message) {
message += "\r\n";
int status = send(socketfd, message.c_str(), message.size(), 0);
if ((unsigned) status == message.size())
return true;
perror("An error occurred sending a message");
return false;
}
std::string Socket::receive() {
std::string messageString = "";
char inputBuffer[2];
bool seenCR = false;
int status;
while (true) {
status = recv(socketfd, &inputBuffer, 1, 0);
if (status < 0) {
perror("An error occurred receiving a message");
closeConnection();
break;
}
if (inputBuffer[0] == '\0')
return messageString;
if (inputBuffer[0] == '\n' && seenCR)
return messageString;
if (inputBuffer[0] != '\n' && inputBuffer[0] != '\r')
messageString += inputBuffer[0];
seenCR = false;
if (inputBuffer[0] == '\r')
seenCR = true;
}
return "";
}
#endif<commit_msg>Remove comment reminding me to resolve DNS names. I have a TODO now.<commit_after>#include "socket.h"
#ifndef SOCKET_CPP
#define SOCKET_CPP
class Socket {
public:
Socket();
~Socket();
void connectServer(std::string address, unsigned short port);
bool sendData(std::string message);
std::string receive();
void closeConnection();
bool isConnected();
private:
int socketfd;
sockaddr_in socketAddr;
bool connected;
};
Socket::Socket() {
socketfd = socket(AF_INET, SOCK_STREAM, 0);
socketAddr.sin_family = AF_INET;
connected = false;
}
Socket::~Socket() {
closeConnection();
}
void Socket::connectServer(std::string address, unsigned short port) {
socketAddr.sin_port = htons(port);
inet_pton(AF_INET, address.c_str(), &socketAddr.sin_addr);
int status;
status = connect(socketfd, (sockaddr*) &socketAddr, sizeof(socketAddr));
if (status != 0) {
perror("Could not connect to server");
connected = false;
} else {
std::cout << "Successfully connected to " << address << std::endl;
connected = true;
}
}
void Socket::closeConnection() {
close(socketfd);
connected = false;
}
bool Socket::isConnected() {
return connected;
}
bool Socket::sendData(std::string message) {
message += "\r\n";
int status = send(socketfd, message.c_str(), message.size(), 0);
if ((unsigned) status == message.size())
return true;
perror("An error occurred sending a message");
return false;
}
std::string Socket::receive() {
std::string messageString = "";
char inputBuffer[2];
bool seenCR = false;
int status;
while (true) {
status = recv(socketfd, &inputBuffer, 1, 0);
if (status < 0) {
perror("An error occurred receiving a message");
closeConnection();
break;
}
if (inputBuffer[0] == '\0')
return messageString;
if (inputBuffer[0] == '\n' && seenCR)
return messageString;
if (inputBuffer[0] != '\n' && inputBuffer[0] != '\r')
messageString += inputBuffer[0];
seenCR = false;
if (inputBuffer[0] == '\r')
seenCR = true;
}
return "";
}
#endif<|endoftext|> |
<commit_before>#include "socket.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
IPV4Addr::IPV4Addr(int _addr, short _port){
addr = _addr;
port = _port;
}
IPV4Addr::IPV4Addr(unsigned char a, unsigned char b, unsigned char c, unsigned char d, short _port){
addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
port = htons(_port);
}
IPV4Addr::IPV4Addr(const char* hostName, int _port){
}
void IPV4Addr::WriteToString(char* buffer, int bufferSize){
int hostAddr = ntohl(addr);
short hostPort = ntohs(port);
snprintf(buffer, bufferSize, "%d.%d.%d.%d:%d", (hostAddr >> 24), (hostAddr >> 16) & 0xFF, (hostAddr >> 8) & 0xFF, hostAddr & 0xFF, hostPort);
}
sockaddr_in IPV4Addr::ToSockAddr(){
sockaddr_in ip = {};
ip.sin_addr.s_addr = addr;
ip.sin_port = port;
return ip;
}
/**
int handle;
SocketBlockingType blockingType;
SocketProtocol protocol;
IPV4Addr source;
IPV4Addr destination;
*/
bool Socket::Create(SocketProtocol _protocol, SocketBlockingType _blockingType){
protocol = _protocol;
blockingType = _blockingType;
if (protocol == SP_UDP){
handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
else if (protocol == SP_TCP){
handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
else{
}
if (handle <= 0){
}
if (_blockingType == SBT_NonBlocking){
int nonBlocking = 1;
if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
printf( "failed to set non-blocking\n" );
return false;
}
}
}
bool Socket::Bind(int _port /*= 0*/){
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons((unsigned short)_port);
source.addr = htonl((127 << 24) | 1);
source.port = htons(_port);
bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in));
if (source.port < 0 ){
printf( "failed to bind socket\n" );
return false;
}
}
bool Socket::Connect(IPV4Addr addr){
destination = addr;
source = IPV4Addr(127, 0, 0, 1, ntohs(source.port));
}
bool Socket::SendData(const void* buffer, int buffLength, int* bytesSent){
char srcAddr[256] = {};
char dstAddr[256] = {};
source.WriteToString(srcAddr, sizeof(srcAddr));
destination.WriteToString(dstAddr, sizeof(dstAddr));
printf("Sending %d bytes from '%s' to '%s'\n", buffLength, srcAddr, dstAddr);
sockaddr_in address = destination.ToSockAddr();
int sentBytes =
sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));
if (sentBytes != buffLength){
printf("failed to send packet\n");
return false;
}
*bytesSent = sentBytes;
return true;
}
bool Socket::ReceiveData(void* buffer, int buffLength, int* bytesReceived, IPV4Addr* outAddr){
sockaddr_in from;
socklen_t fromLen = sizeof(from);
int receivedBytes =
recvfrom(handle, buffer, buffLength, 0, (sockaddr*)&from, &fromLen);
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
*outAddr = addr;
*bytesReceived = receivedBytes;
return receivedBytes > 0;
}
bool Socket::Destroy(){
close(handle);
}
bool isSocketSystemInitialised = false;
bool StartUpSocketSystem(){
}
bool ShutdownSocketSystem(){
}
#if defined(SOCKET_TEST_MAIN)
int main(int argc, char** argv){
Socket sock1;
sock1.Create(SP_UDP, SBT_NonBlocking);
sock1.Bind(12245);
Socket sock2;
sock2.Create(SP_UDP, SBT_NonBlocking);
sock2.Bind(12243);
sock1.Connect(sock2.source);
const char* dataToSend = "Hello World";
int bytesSent = 0;
sock1.SendData(dataToSend, strlen(dataToSend)+1, &bytesSent);
usleep(1000);
char packet[256];
int bytesReceived = 0;
int timeout = 0;
while (bytesReceived <= 0){
IPV4Addr addr;
sock2.ReceiveData(packet, sizeof(packet), &bytesReceived, &addr);
usleep(1000);
timeout++;
if (timeout > 10){
break;
}
}
printf("Received '%s' from socket.\n", packet);
if (strcmp(packet, dataToSend) != 0){
return -1;
}
return 0;
}
#endif
<commit_msg>Fixed sockets for windows (builds, not supported though).<commit_after>#include "socket.h"
#if defined(_WIN32)
// TODO: headers for windows
#pragma comment( lib, "wsock32.lib" )
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <string.h>
IPV4Addr::IPV4Addr(int _addr, short _port){
addr = _addr;
port = _port;
}
IPV4Addr::IPV4Addr(unsigned char a, unsigned char b, unsigned char c, unsigned char d, short _port){
addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
port = htons(_port);
}
IPV4Addr::IPV4Addr(const char* hostName, int _port){
}
void IPV4Addr::WriteToString(char* buffer, int bufferSize){
int hostAddr = ntohl(addr);
short hostPort = ntohs(port);
snprintf(buffer, bufferSize, "%d.%d.%d.%d:%d", (hostAddr >> 24), (hostAddr >> 16) & 0xFF, (hostAddr >> 8) & 0xFF, hostAddr & 0xFF, hostPort);
}
sockaddr_in IPV4Addr::ToSockAddr(){
sockaddr_in ip = {};
ip.sin_addr.s_addr = addr;
ip.sin_port = port;
return ip;
}
/**
int handle;
SocketBlockingType blockingType;
SocketProtocol protocol;
IPV4Addr source;
IPV4Addr destination;
*/
bool Socket::Create(SocketProtocol _protocol, SocketBlockingType _blockingType){
protocol = _protocol;
blockingType = _blockingType;
#if defined(_WIN32)
// TODO: socket creation for windows
return false;
#else
if (protocol == SP_UDP){
handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
else if (protocol == SP_TCP){
handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
else{
}
if (handle <= 0){
}
if (_blockingType == SBT_NonBlocking){
int nonBlocking = 1;
if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
printf( "failed to set non-blocking\n" );
return false;
}
}
#endif
return true;
}
bool Socket::Bind(int _port /*= 0*/){
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons((unsigned short)_port);
source.addr = htonl((127 << 24) | 1);
source.port = htons(_port);
#if defined(_WIN32)
// TODO: bind for windows
#else
bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in));
#endif
if (source.port < 0 ){
printf( "failed to bind socket\n" );
return false;
}
return true;
}
bool Socket::Connect(IPV4Addr addr){
destination = addr;
source = IPV4Addr(127, 0, 0, 1, ntohs(source.port));
return true;
}
bool Socket::SendData(const void* buffer, int buffLength, int* bytesSent){
char srcAddr[256] = {};
char dstAddr[256] = {};
source.WriteToString(srcAddr, sizeof(srcAddr));
destination.WriteToString(dstAddr, sizeof(dstAddr));
printf("Sending %d bytes from '%s' to '%s'\n", buffLength, srcAddr, dstAddr);
sockaddr_in address = destination.ToSockAddr();
int sentBytes =
#if defined(_WIN32)
// TODO: headers for windows
0;
#else
sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));
#endif
if (sentBytes != buffLength){
printf("failed to send packet\n");
return false;
}
*bytesSent = sentBytes;
return true;
}
bool Socket::ReceiveData(void* buffer, int buffLength, int* bytesReceived, IPV4Addr* outAddr){
sockaddr_in from = {};
#if defined(_WIN32)
// TODO: headers for windows
int receivedBytes = 0;
#else
socklen_t fromLen = sizeof(from);
int receivedBytes =
recvfrom(handle, buffer, buffLength, 0, (sockaddr*)&from, &fromLen);
#endif
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
*outAddr = addr;
*bytesReceived = receivedBytes;
return receivedBytes > 0;
}
bool Socket::Destroy(){
#if defined(_WIN32)
// TODO: close for windows
return true;
#else
close(handle);
return true;
#endif
}
bool isSocketSystemInitialised = false;
bool StartUpSocketSystem(){
#if defined(_WIN32)
return true;
#else
return true;
#endif
}
bool ShutdownSocketSystem(){
#if defined(_WIN32)
return true;
#else
return true;
#endif
}
#if defined(SOCKET_TEST_MAIN)
int main(int argc, char** argv){
Socket sock1;
sock1.Create(SP_UDP, SBT_NonBlocking);
sock1.Bind(12245);
Socket sock2;
sock2.Create(SP_UDP, SBT_NonBlocking);
sock2.Bind(12243);
sock1.Connect(sock2.source);
const char* dataToSend = "Hello World";
int bytesSent = 0;
sock1.SendData(dataToSend, strlen(dataToSend)+1, &bytesSent);
usleep(1000);
char packet[256];
int bytesReceived = 0;
int timeout = 0;
while (bytesReceived <= 0){
IPV4Addr addr;
sock2.ReceiveData(packet, sizeof(packet), &bytesReceived, &addr);
usleep(1000);
timeout++;
if (timeout > 10){
break;
}
}
printf("Received '%s' from socket.\n", packet);
if (strcmp(packet, dataToSend) != 0){
return -1;
}
return 0;
}
#endif
<|endoftext|> |
<commit_before>
#include "library.h"
#include <gtest/gtest.h>
TEST(LibraryTest, libc_sprintf)
{
#if defined(__ANDROID__)
const auto path = "libc.so";
#elif defined(__gnu_linux__)
const auto path = "libc.so.6";
#else
#error "Unsupported Platform"
#endif
const auto library = platform::Library { path };
using sprintfType = int (*)(char* buffer, const char* format, ...);
const auto sprintfFunction = library.LoadSymbol<sprintfType>("sprintf");
char buffer[11] = { };
const auto result = sprintfFunction(buffer, "string %1d %c", 6, '$');
ASSERT_EQ(10, result);
ASSERT_STREQ("string 6 $", buffer);
}
<commit_msg>Dynamic Library -> Windows support yet not supported.<commit_after>
#include "library.h"
#include <gtest/gtest.h>
TEST(LibraryTest, libc_sprintf)
{
#if defined(__ANDROID__)
const auto path = "libc.so";
#elif defined(__gnu_linux__)
const auto path = "libc.so.6";
#elif defined(_WIN32) && false
// https://blogs.msdn.microsoft.com/oldnewthing/20140411-00/?p=1273
// The MSVCRT.dll is reserved for Windows applications only.
const auto path = "MSVCRT.dll";
#else
#error "Unsupported Platform"
#endif
const auto library = platform::Library { path };
using sprintfType = int (*)(char* buffer, const char* format, ...);
const auto sprintfFunction = library.LoadSymbol<sprintfType>("sprintf");
char buffer[11] = { };
const auto result = sprintfFunction(buffer, "string %1d %c", 6, '$');
ASSERT_EQ(10, result);
ASSERT_STREQ("string 6 $", buffer);
}
<|endoftext|> |
<commit_before>#pragma once
class Solver {
public:
// Check whether a half-filled grid has valid solution(s)
static int hasSolution(Grid &g) {
Grid dup(g);
return solve(dup, 0, 0);
}
// Assuming g is solvable, get a valid solution
static Grid getSolution(Grid &g) {
Grid dup(g);
solve(dup, 0, 0);
return dup;
}
static int verifyAnswer(Grid &g) {
//TODO: implement logic to check the validity of a fully filled grid
return 1;
}
static int isValidMove(int number, Grid &g, int row, int col) {
int sqRow = 3*(row/3);
int sqCol = 3*(col/3);
int row1 = (row+2)%3;
int row2 = (row+4)%3;
int col1 = (col+2)%3;
int col2 = (col+4)%3;
for (int i = 0; i < 9; i++) {
if (i != col && g[row][i] == number) return 0;
if (i != row && g[i][col] == number) return 0;
}
if (g[sqRow+row1][sqCol+col1] == number) return 0;
if (g[sqRow+row2][sqCol+col1] == number) return 0;
if (g[sqRow+row1][sqCol+col2] == number) return 0;
if (g[sqRow+row2][sqCol+col2] == number) return 0;
return 1;
}
private:
// Given a half-filled grid, solve the grid and return 0 if it is solvable.
// If not solvable, return 0.
static int solve(Grid &g, int row, int col) {
if (row == 9) return 1;
// if cell has already been set
if (g[row][col] != -10) {
if (col == 8) {
if (solve(g, row+1, 0)) return 1;
} else {
if (solve(g, row, col+1)) return 1;
}
return 0;
}
// find a valid value to fill the cell
for (int i = 1; i < 10; i++) {
if(isValidMove(i, g, row, col)) {
g.set(row, col, i);
if (col == 8) {
if (solve(g, row+1, 0)) return 1;
} else {
if (solve(g, row, col+1)) return 1;
}
g.set(row, col, -10);
}
}
return 0;
}
};
<commit_msg>Removed unused function from Solver class<commit_after>#pragma once
class Solver {
public:
// Check whether a half-filled grid has valid solution(s)
static int hasSolution(Grid &g) {
Grid dup(g);
return solve(dup, 0, 0);
}
// Assuming g is solvable, get a valid solution
static Grid getSolution(Grid &g) {
Grid dup(g);
solve(dup, 0, 0);
return dup;
}
static int isValidMove(int number, Grid &g, int row, int col) {
int sqRow = 3*(row/3);
int sqCol = 3*(col/3);
int row1 = (row+2)%3;
int row2 = (row+4)%3;
int col1 = (col+2)%3;
int col2 = (col+4)%3;
for (int i = 0; i < 9; i++) {
if (i != col && g[row][i] == number) return 0;
if (i != row && g[i][col] == number) return 0;
}
if (g[sqRow+row1][sqCol+col1] == number) return 0;
if (g[sqRow+row2][sqCol+col1] == number) return 0;
if (g[sqRow+row1][sqCol+col2] == number) return 0;
if (g[sqRow+row2][sqCol+col2] == number) return 0;
return 1;
}
private:
// Given a half-filled grid, solve the grid and return 0 if it is solvable.
// If not solvable, return 0.
static int solve(Grid &g, int row, int col) {
if (row == 9) return 1;
// if cell has already been set
if (g[row][col] != -10) {
if (col == 8) {
if (solve(g, row+1, 0)) return 1;
} else {
if (solve(g, row, col+1)) return 1;
}
return 0;
}
// find a valid value to fill the cell
for (int i = 1; i < 10; i++) {
if(isValidMove(i, g, row, col)) {
g.set(row, col, i);
if (col == 8) {
if (solve(g, row+1, 0)) return 1;
} else {
if (solve(g, row, col+1)) return 1;
}
g.set(row, col, -10);
}
}
return 0;
}
};
<|endoftext|> |
<commit_before>// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gmock/gmock.h"
#include "rcutils/error_handling.h"
#include "rmw/error_handling.h"
#include "rmw/names_and_types.h"
namespace
{
void *
bad_zero_allocator(size_t number, size_t size, void * state)
{
RCUTILS_UNUSED(number);
RCUTILS_UNUSED(size);
RCUTILS_UNUSED(state);
return nullptr;
}
} // namespace
TEST(rmw_names_and_types, get_zero_init)
{
rmw_names_and_types_t names_and_types = rmw_get_zero_initialized_names_and_types();
EXPECT_EQ(names_and_types.names.size, 0u);
EXPECT_EQ(names_and_types.names.data, nullptr);
EXPECT_EQ(names_and_types.names.allocator.allocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.deallocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.reallocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.zero_allocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.state, nullptr);
EXPECT_EQ(names_and_types.types, nullptr);
}
TEST(rmw_names_and_types, rmw_names_and_types_check_zero) {
EXPECT_EQ(rmw_names_and_types_check_zero(nullptr), RMW_RET_INVALID_ARGUMENT);
rmw_names_and_types_t names_and_types;
rmw_reset_error();
// Size is not 0
names_and_types.names.size = 1;
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_INVALID_ARGUMENT);
names_and_types.names.size = 0;
rmw_reset_error();
// data is not null
char s[20] = "I'm a string!";
char * data[2] = {&s[0], &s[1]};
names_and_types.names.data = &data[0];
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_INVALID_ARGUMENT);
names_and_types.names.data = nullptr;
rcutils_reset_error();
// types is not null
rcutils_string_array_t string_array;
names_and_types.types = &string_array;
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_INVALID_ARGUMENT);
names_and_types.types = nullptr;
rmw_reset_error();
// OK
names_and_types = rmw_get_zero_initialized_names_and_types();
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_OK);
}
TEST(rmw_names_and_types, rmw_names_and_types_init) {
rmw_names_and_types_t names_and_types;
rcutils_allocator_t allocator = rcutils_get_default_allocator();
size_t size = 100;
// allocator is null
rmw_ret_t result = rmw_names_and_types_init(&names_and_types, size, nullptr);
EXPECT_EQ(result, RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// names_and_types is null
result = rmw_names_and_types_init(nullptr, size, &allocator);
EXPECT_EQ(result, RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// allocator fails to allocate memory to names
allocator.zero_allocate = &bad_zero_allocator;
result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_BAD_ALLOC);
allocator = rcutils_get_default_allocator();
rmw_reset_error();
// Fails to deallocate after failing to zero allocate types
allocator.zero_allocate = &bad_zero_allocator;
allocator.deallocate = nullptr;
result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_BAD_ALLOC);
allocator = rcutils_get_default_allocator();
rmw_reset_error();
result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_OK);
}
TEST(rmw_names_and_types, rmw_names_and_types_fini) {
rmw_names_and_types_t names_and_types = rmw_get_zero_initialized_names_and_types();
rcutils_allocator_t allocator = rcutils_get_default_allocator();
size_t size = 100;
rmw_ret_t result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_OK);
// names_and_types is nullptr
EXPECT_EQ(rmw_names_and_types_fini(nullptr), RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// Ok
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_OK);
// Size != 0 and types is null
auto types_ptr = names_and_types.types;
names_and_types.types = nullptr;
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
names_and_types.types = types_ptr;
// bad allocator, rcutils fails to finalize string array
names_and_types.names.allocator.deallocate = nullptr;
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
}
<commit_msg>Fix rmw_names_and_types_fini test to address issue #234 (#235)<commit_after>// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gmock/gmock.h"
#include "rcutils/error_handling.h"
#include "rmw/error_handling.h"
#include "rmw/names_and_types.h"
namespace
{
void *
bad_zero_allocator(size_t number, size_t size, void * state)
{
RCUTILS_UNUSED(number);
RCUTILS_UNUSED(size);
RCUTILS_UNUSED(state);
return nullptr;
}
} // namespace
TEST(rmw_names_and_types, get_zero_init)
{
rmw_names_and_types_t names_and_types = rmw_get_zero_initialized_names_and_types();
EXPECT_EQ(names_and_types.names.size, 0u);
EXPECT_EQ(names_and_types.names.data, nullptr);
EXPECT_EQ(names_and_types.names.allocator.allocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.deallocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.reallocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.zero_allocate, nullptr);
EXPECT_EQ(names_and_types.names.allocator.state, nullptr);
EXPECT_EQ(names_and_types.types, nullptr);
}
TEST(rmw_names_and_types, rmw_names_and_types_check_zero) {
EXPECT_EQ(rmw_names_and_types_check_zero(nullptr), RMW_RET_INVALID_ARGUMENT);
rmw_names_and_types_t names_and_types;
rmw_reset_error();
// Size is not 0
names_and_types.names.size = 1;
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_INVALID_ARGUMENT);
names_and_types.names.size = 0;
rmw_reset_error();
// data is not null
char s[20] = "I'm a string!";
char * data[2] = {&s[0], &s[1]};
names_and_types.names.data = &data[0];
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_INVALID_ARGUMENT);
names_and_types.names.data = nullptr;
rcutils_reset_error();
// types is not null
rcutils_string_array_t string_array;
names_and_types.types = &string_array;
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_INVALID_ARGUMENT);
names_and_types.types = nullptr;
rmw_reset_error();
// OK
names_and_types = rmw_get_zero_initialized_names_and_types();
EXPECT_EQ(rmw_names_and_types_check_zero(&names_and_types), RMW_RET_OK);
}
TEST(rmw_names_and_types, rmw_names_and_types_init) {
rmw_names_and_types_t names_and_types;
rcutils_allocator_t allocator = rcutils_get_default_allocator();
size_t size = 100;
// allocator is null
rmw_ret_t result = rmw_names_and_types_init(&names_and_types, size, nullptr);
EXPECT_EQ(result, RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// names_and_types is null
result = rmw_names_and_types_init(nullptr, size, &allocator);
EXPECT_EQ(result, RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// allocator fails to allocate memory to names
allocator.zero_allocate = &bad_zero_allocator;
result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_BAD_ALLOC);
allocator = rcutils_get_default_allocator();
rmw_reset_error();
// Fails to deallocate after failing to zero allocate types
allocator.zero_allocate = &bad_zero_allocator;
allocator.deallocate = nullptr;
result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_BAD_ALLOC);
allocator = rcutils_get_default_allocator();
rmw_reset_error();
result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_OK);
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_OK);
}
TEST(rmw_names_and_types, rmw_names_and_types_fini) {
rmw_names_and_types_t names_and_types = rmw_get_zero_initialized_names_and_types();
rcutils_allocator_t allocator = rcutils_get_default_allocator();
size_t size = 100;
rmw_ret_t result = rmw_names_and_types_init(&names_and_types, size, &allocator);
EXPECT_EQ(result, RMW_RET_OK);
// Ok
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_OK);
result = rmw_names_and_types_init(&names_and_types, size, &allocator);
ASSERT_EQ(result, RMW_RET_OK);
// names_and_types is nullptr
EXPECT_EQ(rmw_names_and_types_fini(nullptr), RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// Size != 0 and types is null
auto types_ptr = names_and_types.types;
names_and_types.types = nullptr;
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// bad allocator, rcutils fails to finalize string array
names_and_types.names.allocator.deallocate = nullptr;
names_and_types.names.size = 0u;
names_and_types.types = nullptr;
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_INVALID_ARGUMENT);
rmw_reset_error();
// Restore back to nominal for proper finalizing
names_and_types.types = types_ptr;
names_and_types.names.size = size;
names_and_types.names.allocator = rcutils_get_default_allocator();
EXPECT_EQ(rmw_names_and_types_fini(&names_and_types), RMW_RET_OK);
}
<|endoftext|> |
<commit_before>#include <iostream.h>
#include <nlist.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string.h>
#include <sys/sysinfo.h>
#include "condor_debug.h"
#include "except.h"
#include "condor_sysparam.h"
// C definitions
static char *_FileName_ = __FILE__;
extern "C"
{
int set_root_euid();
int set_condor_euid();
int nlist();
}
class AixSpecific
{
public:
AixSpecific() { n_polls = 0; };
static struct nlist nl[]; // table for OS symbols
int* kd; // fd for kvm calls
const int AvgInterval = 60; // Calculate a one minute load average
int PrevInRunQ, PrevTicks, CurInRunQ, CurTicks;
time_t LastPoll;
float long_avg;
time_t now, elapsed_time;
int n_polls ;
void poll(int* queue, int* ticks, time_t* poll_time);
} specific;
enum { X_SYSINFO =0 };
struct nlist AixSpecific::nl[] =
{
{ "sysinfo" ,0,0,0,0,0},
{ "" ,0,0,0,0,0}
};
Aix::Aix()
{
set_root_euid();
// Open kmem for reading
if( (specific.kd=open("/dev/kmem",O_RDONLY,0)) < 0 )
{
set_condor_euid();
EXCEPT( "open(/dev/kmem,O_RDONLY,0)" );
}
// Get the kernel's name list
(void)nlist( "/vmunix", specific.nl );
set_condor_euid();
}
int
Aix::readSysParam(const SysParamName sys, char*& buffer, int& size,SysType& t)
{
set_root_euid();
switch ( sys )
{
case Arch: // get_arch()
struct utsname buf;
if( uname(&buf) < 0 ) return -1;
size = strlen(buf.machine) + 1;
t = String;
buffer = new char[size];
memcpy(buffer, buf.machine, size);
break;
case OpSys: // get_op_sys()
struct utsname buf1;
if( uname(&buf1) < 0 ) return -1;
size = strlen(buf1.sysname) + strlen(buf1.release) +1;
t = String;
buffer = new char[size];
strcpy( buffer, buf1.sysname );
strcat( buffer, buf1.release );
break;
case LoadAvg: // lookup_load_avg()
float short_avg;
float weighted_long, weighted_short;
specific.poll( &specific.CurInRunQ, &specific.CurTicks, &specific.now );
if( specific.n_polls == 0 )
{ /* first time through, just set things up */
specific.PrevInRunQ = specific.CurInRunQ;
specific.PrevTicks = specific.CurTicks;
specific.LastPoll = specific.now;
specific.n_polls = 1;
short_avg = 1.0;
specific.long_avg = 1.0;
dprintf( D_LOAD, "First Time, returning 1.0\n" );
t = Float;
size = sizeof(float);
buffer = (char *)new float[1];
*(float *)buffer = 1.0;
break;
}
if( specific.CurTicks == specific.PrevTicks )
{
dprintf( D_LOAD, "Too short of time to compute avg, returning
%5.2f\n", specific.long_avg );
t = Float;
size = sizeof(float);
buffer = (char *)new float[1];
*(float *)buffer = specific.long_avg;
break;
}
short_avg = (float)(specific.CurInRunQ - specific.PrevInRunQ) /
(float)(specific.CurTicks - specific.PrevTicks) - 1.0;
specific.elapsed_time = specific.now - specific.LastPoll;
if( specific.n_polls == 1 )
{ /* second time through, init long average */
specific.long_avg = short_avg;
specific.PrevInRunQ = specific.CurInRunQ;
specific.PrevTicks = specific.CurTicks;
specific.LastPoll = specific.now;
specific.n_polls = 2;
dprintf( D_LOAD, "Second time, returning %5.2f\n", specific.long_avg );
t = Float;
size = sizeof(float);
buffer = (char *)new float[1];
*(float *)buffer = specific.long_avg;
}
// after second time through, update long average with new info
weighted_short = short_avg * (float)specific.elapsed_time / (float)specific.AvgInterval;
weighted_long = specific.long_avg *
(float)(specific.AvgInterval - specific.elapsed_time) / (float)specific.AvgInterval;
specific.long_avg = weighted_long + weighted_short;
dprintf( D_LOAD, "ShortAvg = %5.2f LongAvg = %5.2f\n",
short_avg, specific.long_avg );
dprintf( D_LOAD, "\n" );
specific.PrevInRunQ = specific.CurInRunQ;
specific.PrevTicks = specific.CurTicks;
specific.LastPoll = specific.now;
t = Float;
size = sizeof(float);
buffer = (char *)new float[1];
*(float *)buffer = specific.long_avg;
break;
#if 0
case SwapSpace: // calc_virt_memory()
struct anoninfo a_info;
if (kvm_read (specific.kd, specific.nl[X_ANONINFO].n_value,
&a_info, sizeof (a_info)) != sizeof(a_info))
{
kvm_close( specific.kd );
specific.kd = NULL;
set_condor_euid();
dprintf (D_ALWAYS, "kvm_read error.\n");
return (-1);
}
size = sizeof(int);
t = Integer;
buffer = (char *)new int[1];
int page_to_k = getpagesize() / 1024;
*(int *)buffer = (int)(a_info.ani_max - a_info.ani_resv)* page_to_k;
break;
case PhyMem: // calc_phys_memory()
unsigned int phy;
if (kvm_read (specific.kd, SunOsSpecific::nl[X_PHYMEM].n_value,
&phy, sizeof (phy)) != sizeof(phy))
{
kvm_close( specific.kd );
specific.kd = NULL;
set_condor_euid();
dprintf (D_ALWAYS, "kvm_read error.\n");
return (-1);
}
phy *= getpagesize();
phy += 300000; /* add about 300K to offset for RAM that the
Sun PROM program gobbles at boot time (at
least I think that's where its going). If
we fail to do this the integer divide we do
next will incorrectly round down one meg. */
phy /= 1048576; /* convert from bytes to megabytes */
size = sizeof(int);
t = Integer;
buffer = (char *)new int[1];
*(int *)buffer = phy ;
break;
case CpuType:
dprintf(D_ALWAYS,"Cpu Type not implemented in this platform\n");
return -1;
#endif
default:
dprintf(D_ALWAYS, "readSysParam: default\n");
return -1;
}
set_condor_euid();
return 1;
}
void
AixSpecific::poll(int* queue, int* ticks, time_t* poll_time)
{
struct sysinfo info;
if( lseek(kd,nl[X_SYSINFO].n_value,L_SET) < 0 )
{
perror( "lseek" );
exit( 1 );
}
if( read(kd,(char *)&info,sizeof(struct sysinfo)) < sizeof(struct sysinfo))
{
perror( "read from kmem" );
exit( 1 );
}
*queue = info.runque;
*ticks = info.runocc;
(void)time( poll_time );
}
// Function to print out system parameter to log file
void
SunOs::disSysParam(const SysParamName sys, const char* buffer,
const int size, const SysType type)
{
if ( !buffer )
{
dprintf(D_ALWAYS, "display():Buffer pointer is null\n");
return;
}
switch ( sys )
{
case Arch:
if ( size == 0 ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != String ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New Arch = %s\n", buffer);
break;
case OpSys:
if ( size == 0 ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != String ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New OpSys = %s\n", buffer);
break;
case LoadAvg:
if ( size != sizeof(float) ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != Float ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New load = %f\n", *(float *)buffer);
break;
case SwapSpace:
if ( size != sizeof(int) ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != Integer ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New virt_mem = %i\n", *(int *)buffer);
break;
case PhyMem:
if ( size != sizeof(int) ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != Integer ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New phys_mem = %i\n", *(int *)buffer);
break;
case CpuType:
dprintf(D_ALWAYS, "disSysParam : CpuType not implemented\n");
break;
default:
dprintf(D_ALWAYS, "disSysParam : no match\n");
break;
}
}
// dummy stubs
Osf1:: Osf1() {}
int Osf1::readSysParam(const SysParamName, char*& buffer, int& size, SysType& type){}
void Osf1::disSysParam(const SysParamName sys, const char* buffer, const int size, const SysType type){}
Ultrix:: Ultrix() {}
int Ultrix::readSysParam(const SysParamName, char*& buffer, int& size, SysType& type){}
void Ultrix::disSysParam(const SysParamName sys, const char* buffer, const int size, const SysType type){}
Hpux:: Hpux() {}
int Hpux::readSysParam(const SysParamName, char*& buffer, int& size, SysType& type){}
void Hpux::disSysParam(const SysParamName sys, const char* buffer, const int size, const SysType type){}
<commit_msg>Compilation errors for AIX removed.<commit_after>#include <stdio.h>
#include <nlist.h>
#include <sys/types.h>
#include <sys/file.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string.h>
#include <malloc.h>
#include "condor_debug.h"
#include "except.h"
#include "condor_sysparam.h"
// C definitions
static char *_FileName_ = __FILE__;
extern "C"
{
int set_root_euid();
int set_condor_euid();
int knlist();
}
class AixSpecific
{
public:
AixSpecific();
~AixSpecific();
static struct nlist nl[]; // table for OS symbols
int kd; // fd for kvm calls
} specific;
enum { X_AVENRUN =0 };
struct nlist AixSpecific::nl[] =
{
{ { "avenrun"} },
};
Aix::Aix()
{
set_root_euid();
// Open kmem for reading
if( (specific.kd=open("/dev/kmem",O_RDONLY,0)) < 0 )
{
set_condor_euid();
EXCEPT( "open(/dev/kmem,O_RDONLY,0)" );
}
// Get the kernel's name list
if( knlist(specific.nl,1,sizeof(struct nlist)) < 0 )
{
set_condor_euid();
EXCEPT( "Can't get kernel name list" );
}
set_condor_euid();
}
int
Aix::readSysParam(const SysParamName sys, char*& buffer, int& size,SysType& t)
{
set_root_euid();
switch ( sys )
{
case Arch: // get_arch()
struct utsname buf;
if( uname(&buf) < 0 ) return -1;
size = strlen(buf.machine) + 1;
t = String;
buffer = new char[size];
memcpy(buffer, buf.machine, size);
break;
case OpSys: // get_op_sys()
struct utsname buf1;
if( uname(&buf1) < 0 ) return -1;
size = strlen(buf1.sysname) + strlen(buf1.release) +1;
t = String;
buffer = new char[size];
strcpy( buffer, buf1.sysname );
strcat( buffer, buf1.release );
break;
case LoadAvg: // lookup_load_avg()
int avenrun[3];
off_t addr = specific.nl[X_AVENRUN].n_value;
if( lseek(specific.kd,addr,0) != addr )
{
dprintf( D_ALWAYS, "Can't seek to addr 0x%x in /dev/kmem\n", addr );
EXCEPT( "lseek in LoadAvg" );
}
if( read(specific.kd,(void *)avenrun,sizeof (avenrun)) !=sizeof (avenrun))
{
EXCEPT( "read in LoadAvg" );
}
size = sizeof(float);
t = Float;
buffer = (char *)new float[1];
*(float *)buffer = ((float)avenrun[0])/ 65536.0;
break;
#if 0
case SwapSpace: // calc_virt_memory()
struct anoninfo a_info;
if (kvm_read (specific.kd, specific.nl[X_ANONINFO].n_value,
&a_info, sizeof (a_info)) != sizeof(a_info))
{
kvm_close( specific.kd );
specific.kd = NULL;
set_condor_euid();
dprintf (D_ALWAYS, "kvm_read error.\n");
return (-1);
}
size = sizeof(int);
t = Integer;
buffer = (char *)new int[1];
int page_to_k = getpagesize() / 1024;
*(int *)buffer = (int)(a_info.ani_max - a_info.ani_resv)* page_to_k;
break;
case PhyMem: // calc_phys_memory()
unsigned int phy;
if (kvm_read (specific.kd, SunOsSpecific::nl[X_PHYMEM].n_value,
&phy, sizeof (phy)) != sizeof(phy))
{
kvm_close( specific.kd );
specific.kd = NULL;
set_condor_euid();
dprintf (D_ALWAYS, "kvm_read error.\n");
return (-1);
}
phy *= getpagesize();
phy += 300000; /* add about 300K to offset for RAM that the
Sun PROM program gobbles at boot time (at
least I think that's where its going). If
we fail to do this the integer divide we do
next will incorrectly round down one meg. */
phy /= 1048576; /* convert from bytes to megabytes */
size = sizeof(int);
t = Integer;
buffer = (char *)new int[1];
*(int *)buffer = phy ;
break;
case CpuType:
dprintf(D_ALWAYS,"Cpu Type not implemented in this platform\n");
return -1;
#endif
default:
dprintf(D_ALWAYS, "readSysParam: default\n");
return -1;
}
set_condor_euid();
return 1;
}
// Function to print out system parameter to log file
void
SunOs::disSysParam(const SysParamName sys, const char* buffer,
const int size, const SysType type)
{
if ( !buffer )
{
dprintf(D_ALWAYS, "display():Buffer pointer is null\n");
return;
}
switch ( sys )
{
case Arch:
if ( size == 0 ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != String ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New Arch = %s\n", buffer);
break;
case OpSys:
if ( size == 0 ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != String ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New OpSys = %s\n", buffer);
break;
case LoadAvg:
if ( size != sizeof(float) ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != Float ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New load = %f\n", *(float *)buffer);
break;
case SwapSpace:
if ( size != sizeof(int) ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != Integer ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New virt_mem = %i\n", *(int *)buffer);
break;
case PhyMem:
if ( size != sizeof(int) ) dprintf(D_ALWAYS,"Error in size\n");
else if ( type != Integer ) dprintf(D_ALWAYS, "Error in type\n");
else dprintf(D_ALWAYS,"New phys_mem = %i\n", *(int *)buffer);
break;
case CpuType:
dprintf(D_ALWAYS, "disSysParam : CpuType not implemented\n");
break;
default:
dprintf(D_ALWAYS, "disSysParam : no match\n");
break;
}
}
// dummy stubs
Osf1:: Osf1() {}
int Osf1::readSysParam(const SysParamName, char*& buffer, int& size, SysType& type){}
void Osf1::disSysParam(const SysParamName sys, const char* buffer, const int size, const SysType type){}
Ultrix:: Ultrix() {}
int Ultrix::readSysParam(const SysParamName, char*& buffer, int& size, SysType& type){}
void Ultrix::disSysParam(const SysParamName sys, const char* buffer, const int size, const SysType type){}
Hpux:: Hpux() {}
int Hpux::readSysParam(const SysParamName, char*& buffer, int& size, SysType& type){}
void Hpux::disSysParam(const SysParamName sys, const char* buffer, const int size, const SysType type){}
<|endoftext|> |
<commit_before>#include <vector>
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "scripting/JavaScriptContext.hpp"
using namespace ci;
using namespace ci::app;
typedef Scripting::interface visualization;
class DukVisApp : public AppMac {
public:
void setup() override;
void resize() override;
void draw() override;
CameraPersp mCamera;
gl::BatchRe mCube;
gl::BatchRef mOverlay;
Scripting::JavaScriptContext* mJSContext;
vector<Scripting::interface> mVisualizations;
int currentVisIndex = 0;
};
void DukVisApp::setup() {
RendererRef renderer = getRenderer();
fs::path dataPath = Platform::get()->getExecutablePath();
dataPath /= fs::path("data");
addAssetDirectory(dataPath);
mJSContext = new Scripting::JavaScriptContext();
auto vis = visualization::loadSourceFromFile(
dataPath.append(std::string("js/spectrum.vis.js"))
);
if (mJSContext->bindInterface((&vis))) {
cout << "Loaded visualization: " << vis.module->name << " v" << vis.module->version << endl;
mVisualizations.push_back(vis);
} else {
cerr << "Could not create JS context, aborting...\n";
exit(1);
}
auto lambert = gl::ShaderDef().lambert().color();
gl::GlslProgRef shader = gl::getStockShader(lambert);
mCube = gl::Batch::create(geom::Cube(), shader);
auto overlayShader = gl::ShaderDef().color();
shader = gl::getStockShader(overlayShader);
mOverlay = gl::Batch::create(geom::Rect(Rectf(0, 0, 1, 1)), shader);
mCamera.lookAt(vec3(5, 3, 2), vec3(0, 0, 0));
gl::enableDepthRead();
gl::enableDepthWrite();
}
void DukVisApp::resize() {
if (mJSContext->isValid()) {
if (!mJSContext->isCurrent())
mJSContext->makeCurrent();
if (!mVisualizations.at(currentVisIndex).screen->setSize(getWindowSize()))
cerr << "Could not update screen size for scripts\n";
mVisualizations.at(currentVisIndex).module->update(Scripting::UpdateType::RESIZE);
}
}
void DukVisApp::draw() {
gl::clear();
gl::setMatrices(mCamera);
float anim = getElapsedFrames() / getFrameRate();
anim *= 0.3;
gl::rotate(glm::radians(anim * 360), vec3(0, 1, 0));
gl::color(Color(CM_RGB, 1, 0, 0));
mCube->draw();
auto windowSize = getWindowSize();
gl::setMatricesWindow(windowSize);
{
gl::ScopedBlend(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gl::scale(windowSize.x, windowSize.y);
gl::color(0.2, 0.2, 0.75, 0.25);
mOverlay->draw();
}
}
CINDER_APP(
DukVisApp,
RendererGl(
RendererGl::Options().version(3, 3).coreProfile(true).msaa(4)
),
[]( App::Settings *settings ) {
settings->setTitle(std::string("DukVis"));
settings->setWindowSize(800, 600);
settings->setResizable(true);
settings->getDefaultWindowFormat().enableFullScreenButton();
settings->setFrameRate(50.0f);
}
)
<commit_msg>Fix typo<commit_after>#include <vector>
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "scripting/JavaScriptContext.hpp"
using namespace ci;
using namespace ci::app;
typedef Scripting::interface visualization;
class DukVisApp : public AppMac {
public:
void setup() override;
void resize() override;
void draw() override;
CameraPersp mCamera;
gl::BatchRef mCube;
gl::BatchRef mOverlay;
Scripting::JavaScriptContext* mJSContext;
vector<Scripting::interface> mVisualizations;
int currentVisIndex = 0;
};
void DukVisApp::setup() {
RendererRef renderer = getRenderer();
fs::path dataPath = Platform::get()->getExecutablePath();
dataPath /= fs::path("data");
addAssetDirectory(dataPath);
mJSContext = new Scripting::JavaScriptContext();
auto vis = visualization::loadSourceFromFile(
dataPath.append(std::string("js/spectrum.vis.js"))
);
if (mJSContext->bindInterface((&vis))) {
cout << "Loaded visualization: " << vis.module->name << " v" << vis.module->version << endl;
mVisualizations.push_back(vis);
} else {
cerr << "Could not create JS context, aborting...\n";
exit(1);
}
auto lambert = gl::ShaderDef().lambert().color();
gl::GlslProgRef shader = gl::getStockShader(lambert);
mCube = gl::Batch::create(geom::Cube(), shader);
auto overlayShader = gl::ShaderDef().color();
shader = gl::getStockShader(overlayShader);
mOverlay = gl::Batch::create(geom::Rect(Rectf(0, 0, 1, 1)), shader);
mCamera.lookAt(vec3(5, 3, 2), vec3(0, 0, 0));
gl::enableDepthRead();
gl::enableDepthWrite();
}
void DukVisApp::resize() {
if (mJSContext->isValid()) {
if (!mJSContext->isCurrent())
mJSContext->makeCurrent();
if (!mVisualizations.at(currentVisIndex).screen->setSize(getWindowSize()))
cerr << "Could not update screen size for scripts\n";
mVisualizations.at(currentVisIndex).module->update(Scripting::UpdateType::RESIZE);
}
}
void DukVisApp::draw() {
gl::clear();
gl::setMatrices(mCamera);
float anim = getElapsedFrames() / getFrameRate();
anim *= 0.3;
gl::rotate(glm::radians(anim * 360), vec3(0, 1, 0));
gl::color(Color(CM_RGB, 1, 0, 0));
mCube->draw();
auto windowSize = getWindowSize();
gl::setMatricesWindow(windowSize);
{
gl::ScopedBlend(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gl::scale(windowSize.x, windowSize.y);
gl::color(0.2, 0.2, 0.75, 0.25);
mOverlay->draw();
}
}
CINDER_APP(
DukVisApp,
RendererGl(
RendererGl::Options().version(3, 3).coreProfile(true).msaa(4)
),
[]( App::Settings *settings ) {
settings->setTitle(std::string("DukVis"));
settings->setWindowSize(800, 600);
settings->setResizable(true);
settings->getDefaultWindowFormat().enableFullScreenButton();
settings->setFrameRate(50.0f);
}
)
<|endoftext|> |
<commit_before>//@author A0094446X
#include "stdafx.h"
#include <QtWidgets/QApplication>
#include "../You-GUI/main_window.h"
#include "../You-GUI/window_title.h"
#include "windows.h"
int main(int argc, char *argv[]) {
HANDLE hMutex;
hMutex = CreateMutex(NULL, FALSE, TEXT("YouGUIUniqueApplicationInstance"));
DWORD m_DwLastError = GetLastError();
if (m_DwLastError == ERROR_ALREADY_EXISTS) {
HWND hwnd = FindWindow(NULL, WINDOW_TITLE.c_str());
SetForegroundWindow(hwnd);
return 0;
} else {
QApplication a(argc, argv);
You::GUI::MainWindow w;
w.show();
return a.exec();
}
}
<commit_msg>Modified main to improve portability<commit_after>//@author A0094446X
#include "stdafx.h"
#include <QtWidgets/QApplication>
#include "../You-GUI/main_window.h"
#include "../You-GUI/window_title.h"
#ifdef _WIN32
#include "windows.h"
int loadSingleApplication(int argc, char *argv[]);
#else
int loadApplication(int argc, char *argv[]);
#endif
int main(int argc, char *argv[]) {
#ifdef _WIN32
return loadSingleApplication(argc, argv);
#else
return loadApplication(argc, argv);
#endif
}
#ifdef _WIN32
int loadSingleApplication(int argc, char *argv[]) {
HANDLE hMutex;
hMutex = CreateMutex(NULL, FALSE, TEXT("YouGUIUniqueApplicationInstance"));
DWORD m_DwLastError = GetLastError();
if (m_DwLastError == ERROR_ALREADY_EXISTS) {
HWND hwnd = FindWindow(NULL, WINDOW_TITLE.c_str());
SetForegroundWindow(hwnd);
return 0;
} else {
QApplication a(argc, argv);
You::GUI::MainWindow w;
w.show();
return a.exec();
}
}
#else
int loadApplication(int argc, char *argv[]) {
QApplication a(argc, argv);
You::GUI::MainWindow w;
w.show();
return a.exec();
}
#endif
<|endoftext|> |
<commit_before>/*
* PoolingGenConn.cpp
*
* Created on: Apr 25, 2011
* Author: peteschultz
*/
#include "PoolingGenConn.hpp"
namespace PV {
PoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
initialize_base();
initialize(name, hc, pre, post, pre2, post2, filename, weightInit);
} // end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)
int PoolingGenConn::initialize_base() {
pre2 = NULL;
post2 = NULL;
return PV_SUCCESS;
}
int PoolingGenConn::initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
int status;
PVParams * params = hc->parameters();
status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);
if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {
this->pre2 = pre2;
this->post2 = post2;
}
else {
status = PV_FAILURE;
}
if( status == PV_SUCCESS ) {
slownessFlag = params->value(name, "slownessFlag", 0.0/*default is false*/);
}
if( slownessFlag ) {
status = getSlownessLayer(&slownessPre, "slownessPre");
status = getSlownessLayer(&slownessPost, "slownessPost")==PV_SUCCESS ? status : PV_FAILURE;
}
if( slownessFlag && status == PV_SUCCESS ) {
status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;
status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;
}
if( status != PV_SUCCESS ) {
abort();
}
return status;
} // end of PoolingGenConn::initialize(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)
bool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {
int nx1 = layer1->getLayerLoc()->nx;
int nx2 = layer2->getLayerLoc()->nx;
int ny1 = layer1->getLayerLoc()->ny;
int ny2 = layer2->getLayerLoc()->ny;
int nf1 = layer1->getLayerLoc()->nf;
int nf2 = layer2->getLayerLoc()->nf;
int nb1 = layer1->getLayerLoc()->nb;
int nb2 = layer2->getLayerLoc()->nb;
bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;
if( !result ) {
const char * name1 = layer1->getName();
const char * name2 = layer2->getName();
fprintf(stderr, "Group \"%s\": Layers \"%s\" and \"%s\" do not have compatible sizes\n", name, name1, name2);
int len1 = (int) strlen(name1);
int len2 = (int) strlen(name2);
int len = len1 >= len2 ? len1 : len2;
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name1, nx1, ny1, nf1, nb1);
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name2, nx2, ny2, nf2, nb2);
}
return result;
} // end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)
int PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {
int status = PV_SUCCESS;
assert(slownessFlag);
const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);
if( slownessLayerName == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": if slownessFlag is set, parameter \"%s\" must be set\n", name, paramname);
}
if( status == PV_SUCCESS ) {
*l = parent->getLayerFromName(slownessLayerName);
if( *l == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": %s layer \"%s\" was not found\n", name, paramname, slownessLayerName);
}
}
return status;
}
int PoolingGenConn::updateWeights(int axonID) {
int nPre = preSynapticLayer()->getNumNeurons();
int nx = preSynapticLayer()->getLayerLoc()->nx;
int ny = preSynapticLayer()->getLayerLoc()->ny;
int nf = preSynapticLayer()->getLayerLoc()->nf;
int pad = preSynapticLayer()->getLayerLoc()->nb;
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
for( int y=0; y<nyp; y++ ) {
int lineoffsetw = 0;
int lineoffseta = 0;
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] + relaxation*(preact*postactRef[lineoffseta + k]+preact2*postact2Ref[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
if( slownessFlag ) {
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = slownessPre->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
for( int y=0; y<nyp; y++ ) {
int lineoffsetw = 0;
int lineoffseta = 0;
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] - relaxation*(preact*postactRef[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
}
if( nonnegConstraintFlag ) {
for(int kPatch=0; kPatch<getNumDataPatches();kPatch++) {
// PVPatch * weights = this->getKernelPatch(axonID, kPatch);
pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); // weights->data;
int nk = nxp * nfp;
int syw = nxp*nfp;
for( int y=0; y < nyp; y++ ) {
int lineoffsetw = 0;
for( int k=0; k<nk; k++ ) {
pvdata_t w = wtpatch[lineoffsetw + k];
if( w<0 ) {
wtpatch[lineoffsetw + k] = 0;
}
}
lineoffsetw += syw;
}
}
}
// normalizeWeights now called in KernelConn::updateState
lastUpdateTime = parent->simulationTime();
return PV_SUCCESS;
}
} // end namespace PV
<commit_msg>weights->offset fix for PoolingGenConn::update_dW<commit_after>/*
* PoolingGenConn.cpp
*
* Created on: Apr 25, 2011
* Author: peteschultz
*/
#include "PoolingGenConn.hpp"
namespace PV {
PoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
initialize_base();
initialize(name, hc, pre, post, pre2, post2, filename, weightInit);
} // end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)
int PoolingGenConn::initialize_base() {
pre2 = NULL;
post2 = NULL;
return PV_SUCCESS;
}
int PoolingGenConn::initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,
const char * filename, InitWeights *weightInit) {
int status;
PVParams * params = hc->parameters();
status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);
if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {
this->pre2 = pre2;
this->post2 = post2;
}
else {
status = PV_FAILURE;
}
if( status == PV_SUCCESS ) {
slownessFlag = params->value(name, "slownessFlag", 0.0/*default is false*/);
}
if( slownessFlag ) {
status = getSlownessLayer(&slownessPre, "slownessPre");
status = getSlownessLayer(&slownessPost, "slownessPost")==PV_SUCCESS ? status : PV_FAILURE;
}
if( slownessFlag && status == PV_SUCCESS ) {
status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;
status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;
}
if( status != PV_SUCCESS ) {
abort();
}
return status;
} // end of PoolingGenConn::initialize(const char *, HyPerCol *,
// HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)
bool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {
int nx1 = layer1->getLayerLoc()->nx;
int nx2 = layer2->getLayerLoc()->nx;
int ny1 = layer1->getLayerLoc()->ny;
int ny2 = layer2->getLayerLoc()->ny;
int nf1 = layer1->getLayerLoc()->nf;
int nf2 = layer2->getLayerLoc()->nf;
int nb1 = layer1->getLayerLoc()->nb;
int nb2 = layer2->getLayerLoc()->nb;
bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;
if( !result ) {
const char * name1 = layer1->getName();
const char * name2 = layer2->getName();
fprintf(stderr, "Group \"%s\": Layers \"%s\" and \"%s\" do not have compatible sizes\n", name, name1, name2);
int len1 = (int) strlen(name1);
int len2 = (int) strlen(name2);
int len = len1 >= len2 ? len1 : len2;
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name1, nx1, ny1, nf1, nb1);
fprintf(stderr, "Layer \"%*s\": nx=%d, ny=%d, nf=%d, nb=%d\n", len, name2, nx2, ny2, nf2, nb2);
}
return result;
} // end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)
int PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {
int status = PV_SUCCESS;
assert(slownessFlag);
const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);
if( slownessLayerName == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": if slownessFlag is set, parameter \"%s\" must be set\n", name, paramname);
}
if( status == PV_SUCCESS ) {
*l = parent->getLayerFromName(slownessLayerName);
if( *l == NULL ) {
status = PV_FAILURE;
fprintf(stderr, "PoolingGenConn \"%s\": %s layer \"%s\" was not found\n", name, paramname, slownessLayerName);
}
}
return status;
}
int PoolingGenConn::updateWeights(int axonID) {
int nPre = preSynapticLayer()->getNumNeurons();
int nx = preSynapticLayer()->getLayerLoc()->nx;
int ny = preSynapticLayer()->getLayerLoc()->ny;
int nf = preSynapticLayer()->getLayerLoc()->nf;
int pad = preSynapticLayer()->getLayerLoc()->nb;
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = preSynapticLayer()->getCLayer()->activity->data[kExt];
pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);
pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
for( int y=0; y<nyp; y++ ) {
int lineoffsetw = weights->offset;
int lineoffseta = 0;
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] + relaxation*(preact*postactRef[lineoffseta + k]+preact2*postact2Ref[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
if( slownessFlag ) {
for(int kPre=0; kPre<nPre;kPre++) {
int kExt = kIndexExtended(kPre, nx, ny, nf, pad);
size_t offset = getAPostOffset(kPre, axonID);
pvdata_t preact = slownessPre->getCLayer()->activity->data[kExt];
PVPatch * weights = getWeights(kPre,axonID);
int nyp = weights->ny;
int nk = weights->nx * nfp;
pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);
int sya = getPostNonextStrides()->sy;
pvdata_t * wtpatch = get_wData(axonID, kExt); // weights->data;
int syw = syp;
for( int y=0; y<nyp; y++ ) {
int lineoffsetw = 0;
int lineoffseta = 0;
for( int k=0; k<nk; k++ ) {
float w = wtpatch[lineoffsetw + k] - relaxation*(preact*postactRef[lineoffseta + k]);
wtpatch[lineoffsetw + k] = w;
}
lineoffsetw += syw;
lineoffseta += sya;
}
}
}
if( nonnegConstraintFlag ) {
for(int kPatch=0; kPatch<getNumDataPatches();kPatch++) {
// PVPatch * weights = this->getKernelPatch(axonID, kPatch);
pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); // weights->data;
int nk = nxp * nfp;
int syw = nxp*nfp;
for( int y=0; y < nyp; y++ ) {
int lineoffsetw = 0;
for( int k=0; k<nk; k++ ) {
pvdata_t w = wtpatch[lineoffsetw + k];
if( w<0 ) {
wtpatch[lineoffsetw + k] = 0;
}
}
lineoffsetw += syw;
}
}
}
// normalizeWeights now called in KernelConn::updateState
lastUpdateTime = parent->simulationTime();
return PV_SUCCESS;
}
} // end namespace PV
<|endoftext|> |
<commit_before>#include "ast_stmts.hpp"
#include "llvm_generator.hpp"
using namespace llvm;
///** Create an alloca instruction in the entry block of the current function.
// * This is used for variables encountered throughout the function that shall be viable for mem2reg.
// */
//static AllocaInst *create_entry_block_alloca(GenScope* scope, Type* varType, const std::string &varName) {
// auto parentFunc = scope->builder->GetInsertBlock()->getParent();
// IRBuilder<> tmpB(&parentFunc->getEntryBlock(), parentFunc->getEntryBlock().begin());
// return tmpB.CreateAlloca(varType, 0, varName);
//}
/** Create an alloca instruction in the entry block of the current function.
* This is used for variables encountered throughout the function that shall be viable for mem2reg.
*/
static AllocaInst *create_alloca(GenScope* scope, Type* varType, const std::string &varName) {
return scope->builder->CreateAlloca(varType, 0, varName);
}
/** @param lval must be of pointer type */
static Value* do_store(LlvmGenerationContext& context, GenScope* scope, Value* lval, Value* rval) {
if (rval->getType()->isPointerTy() && lval->getType()->getPointerElementType() == rval->getType()->getPointerElementType()) {
rval = scope->builder->CreateLoad(rval);
}
return scope->builder->CreateStore(rval, lval);
}
Value* TxLambdaExprNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
FunctionType *ftype = cast<FunctionType>(context.get_llvm_type(this->funcTypeNode->get_type()));
ASSERT(ftype, "Couldn't get LLVM type for function type " << this->funcTypeNode->get_type());
std::string funcName = ""; // anonymous function
if (this->fieldDefNode) {
funcName = this->fieldDefNode->get_entity()->get_full_name().to_string();
}
context.LOG.debug("Creating function: %s", funcName.c_str());
Function *function = cast<Function>(context.llvmModule.getOrInsertFunction(funcName, ftype));
// function->setLinkage(GlobalValue::InternalLinkage); FIXME (can cause LLVM to rename function)
//Function *function = Function::Create(ftype, GlobalValue::InternalLinkage,
// funcName.c_str(), &context.llvmModule);
// note: function is of LLVM function pointer type (since it is an LLVM global value)
BasicBlock *entryBlock = BasicBlock::Create(context.llvmContext, "entry", function);
IRBuilder<> builder( entryBlock );
GenScope fscope(&builder);
// name the concrete args and allocate them on the stack:
auto argDefI = this->funcTypeNode->arguments->begin();
for (Function::arg_iterator fArgI = function->arg_begin();
fArgI != function->arg_end(); fArgI++, argDefI++)
{
auto entity = (*argDefI)->get_entity();
fArgI->setName(entity->get_name());
//context.register_llvm_value(entity->get_full_name().to_string(), fArgI);
auto txType = entity->get_type();
Type* llvmType = context.get_llvm_type(txType);
if (! llvmType)
return nullptr;
auto argField = create_alloca(&fscope, llvmType, entity->get_name() + "_");
do_store(context, &fscope, argField, fArgI);
context.register_llvm_value(entity->get_full_name().to_string(), argField);
}
this->suite->code_gen(context, &fscope);
if (! fscope.builder->GetInsertBlock()->getTerminator()) {
context.LOG.debug("inserting default void return instruction for last block of function %s", funcName.c_str());
fscope.builder->CreateRetVoid();
//ReturnInst::Create(context.llvmContext, entryBlock);
}
ASSERT (entryBlock->getTerminator(), "Function entry block has no terminator");
return function;
}
Value* TxFieldStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto entity = this->field->get_entity();
ASSERT (entity->get_storage() == TXS_STACK, "TxFieldStmtNode can only apply to TX_STACK storage fields: " << entity->get_full_name());
auto txType = entity->get_type();
Type* llvmType = context.get_llvm_type(txType);
if (! llvmType) {
return nullptr;
}
Value* fieldVal;
if (llvmType->isFunctionTy()) {
// FUTURE: make local function capture
fieldVal = this->field->initExpression->code_gen(context, scope);
}
else {
fieldVal = create_alloca(scope, llvmType, entity->get_name());
if (this->field->initExpression) {
// create implicit assignment statement
if (Value* initializer = this->field->initExpression->code_gen(context, scope))
do_store(context, scope, fieldVal, initializer);
}
}
context.register_llvm_value(entity->get_full_name().to_string(), fieldVal);
return fieldVal;
}
Value* TxTypeStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return this->typeDecl->code_gen(context, scope);
}
Value* TxAssignStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto rval = this->rvalue->code_gen(context, scope);
auto lval = this->lvalue->code_gen(context, scope);
if ((! lval) || (! rval))
return NULL;
if (! lval->getType()->isPointerTy()) {
context.LOG.error("L-value is not of pointer type: %s; %s", ::to_string(lval).c_str(), ::to_string(lval->getType()).c_str());
return rval;
}
return do_store(context, scope, lval, rval);
}
Value* TxDerefAssigneeNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto refval = this->operand->code_gen(context, scope);
if (! refval)
return NULL;
return refval;
}
Value* TxSuiteNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
// auto parentFunc = scope->builder->GetInsertBlock()->getParent();
// BasicBlock* suiteBlock = BasicBlock::Create(context.llvmContext, "suite", parentFunc);
// scope->builder->SetInsertPoint(suiteBlock);
for (auto stmt : *this->suite)
stmt->code_gen(context, scope);
// scope->builder->SetInsertPoint(continuationBlock);
return NULL;
}
Value* TxElseClauseNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return this->suite->code_gen(context, scope);
}
Value* TxIfStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto parentFunc = scope->builder->GetInsertBlock()->getParent();
BasicBlock* trueBlock = BasicBlock::Create(context.llvmContext, "if_true", parentFunc);
BasicBlock* falseBlock = BasicBlock::Create(context.llvmContext, "if_false", parentFunc);
BasicBlock* postBlock;
auto condVal = this->cond->code_gen(context, scope);
auto condInstr = scope->builder->CreateCondBr(condVal, trueBlock, falseBlock);
if (this->elseClause) {
postBlock = BasicBlock::Create(context.llvmContext, "if_post", parentFunc);
scope->builder->SetInsertPoint(falseBlock);
this->elseClause->code_gen(context, scope);
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(postBlock); // branch from end of else suite to post-block
}
else
postBlock = falseBlock;
scope->builder->SetInsertPoint(trueBlock);
this->suite->code_gen(context, scope);
// note: trueBlock is may not be the "current" block anymore when reaching end of true body
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(postBlock); // branch from end of true suite to post-block
scope->builder->SetInsertPoint(postBlock);
return condInstr;
}
Value* TxWhileStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto parentFunc = scope->builder->GetInsertBlock()->getParent();
BasicBlock* condBlock = BasicBlock::Create(context.llvmContext, "while_cond", parentFunc);
BasicBlock* loopBlock = BasicBlock::Create(context.llvmContext, "while_loop", parentFunc);
BasicBlock* elseBlock = BasicBlock::Create(context.llvmContext, "while_else", parentFunc);
BasicBlock* postBlock;
scope->builder->CreateBr(condBlock); // branch from end of preceding block to condition-block
scope->builder->SetInsertPoint(condBlock);
auto condVal = this->cond->code_gen(context, scope);
auto condInstr = scope->builder->CreateCondBr(condVal, loopBlock, elseBlock);
if (this->elseClause) {
postBlock = BasicBlock::Create(context.llvmContext, "while_post", parentFunc);
scope->builder->SetInsertPoint(elseBlock);
this->elseClause->code_gen(context, scope);
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(postBlock); // branch from end of else body to post-block
}
else
postBlock = elseBlock;
CompoundStatementScope css(condBlock, postBlock);
scope->compStmtStack.push(&css);
scope->builder->SetInsertPoint(loopBlock);
this->suite->code_gen(context, scope);
scope->compStmtStack.pop();
// note: loopBlock is may not be the "current" block anymore when reaching end of loop body
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(condBlock); // branch from end of loop body to condition-block
scope->builder->SetInsertPoint(postBlock);
return condInstr;
}
Value* TxCallStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return this->call->code_gen(context, scope);
}
Value* TxReturnStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
if (this->expr)
return scope->builder->CreateRet(this->expr->code_gen(context, scope));
else
return scope->builder->CreateRetVoid();
}
Value* TxBreakStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return scope->builder->CreateBr(scope->compStmtStack.top()->breakBlock);
}
Value* TxContinueStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return scope->builder->CreateBr(scope->compStmtStack.top()->continueBlock);
}
<commit_msg>minor refactoring<commit_after>#include "ast_stmts.hpp"
#include "llvm_generator.hpp"
using namespace llvm;
///** Create an alloca instruction in the entry block of the current function.
// * This is used for variables encountered throughout the function that shall be viable for mem2reg.
// */
//static AllocaInst *create_entry_block_alloca(GenScope* scope, Type* varType, const std::string &varName) {
// auto parentFunc = scope->builder->GetInsertBlock()->getParent();
// IRBuilder<> tmpB(&parentFunc->getEntryBlock(), parentFunc->getEntryBlock().begin());
// return tmpB.CreateAlloca(varType, 0, varName);
//}
/** Create an alloca instruction in the entry block of the current function.
* This is used for variables encountered throughout the function that shall be viable for mem2reg.
*/
static AllocaInst *create_alloca(GenScope* scope, Type* varType, const std::string &varName) {
return scope->builder->CreateAlloca(varType, 0, varName);
}
/** @param lval must be of pointer type */
static Value* do_store(LlvmGenerationContext& context, GenScope* scope, Value* lval, Value* rval) {
if (rval->getType()->isPointerTy() && lval->getType()->getPointerElementType() == rval->getType()->getPointerElementType()) {
rval = scope->builder->CreateLoad(rval);
}
return scope->builder->CreateStore(rval, lval);
}
Value* TxLambdaExprNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
FunctionType *ftype = cast<FunctionType>(context.get_llvm_type(this->funcTypeNode->get_type()));
ASSERT(ftype, "Couldn't get LLVM type for function type " << this->funcTypeNode->get_type());
std::string funcName = ""; // anonymous function
if (this->fieldDefNode) {
funcName = this->fieldDefNode->get_entity()->get_full_name().to_string();
}
context.LOG.debug("Creating function: %s", funcName.c_str());
Function *function = cast<Function>(context.llvmModule.getOrInsertFunction(funcName, ftype));
// function->setLinkage(GlobalValue::InternalLinkage); FIXME (can cause LLVM to rename function)
//Function *function = Function::Create(ftype, GlobalValue::InternalLinkage,
// funcName.c_str(), &context.llvmModule);
// note: function is of LLVM function pointer type (since it is an LLVM global value)
BasicBlock *entryBlock = BasicBlock::Create(context.llvmContext, "entry", function);
IRBuilder<> builder( entryBlock );
GenScope fscope(&builder);
// name the concrete args and allocate them on the stack:
auto argDefI = this->funcTypeNode->arguments->begin();
for (Function::arg_iterator fArgI = function->arg_begin();
fArgI != function->arg_end(); fArgI++, argDefI++)
{
auto entity = (*argDefI)->get_entity();
fArgI->setName(entity->get_name());
//context.register_llvm_value(entity->get_full_name().to_string(), fArgI);
auto txType = entity->get_type();
Type* llvmType = context.get_llvm_type(txType);
if (! llvmType)
return nullptr;
auto argField = create_alloca(&fscope, llvmType, entity->get_name() + "_");
do_store(context, &fscope, argField, fArgI);
context.register_llvm_value(entity->get_full_name().to_string(), argField);
}
this->suite->code_gen(context, &fscope);
if (! fscope.builder->GetInsertBlock()->getTerminator()) {
context.LOG.debug("inserting default void return instruction for last block of function %s", funcName.c_str());
fscope.builder->CreateRetVoid();
//ReturnInst::Create(context.llvmContext, entryBlock);
}
ASSERT (entryBlock->getTerminator(), "Function entry block has no terminator");
return function;
}
Value* TxFieldStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto entity = this->field->get_entity();
ASSERT (entity->get_storage() == TXS_STACK, "TxFieldStmtNode can only apply to TX_STACK storage fields: " << entity->get_full_name());
auto txType = entity->get_type();
Type* llvmType = context.get_llvm_type(txType);
if (! llvmType) {
return nullptr;
}
Value* fieldVal;
if (llvmType->isFirstClassType()) {
fieldVal = create_alloca(scope, llvmType, entity->get_name());
if (this->field->initExpression) {
// create implicit assignment statement
if (Value* initializer = this->field->initExpression->code_gen(context, scope))
do_store(context, scope, fieldVal, initializer);
}
}
else if (llvmType->isFunctionTy()) {
// FUTURE: make local function capture
fieldVal = this->field->initExpression->code_gen(context, scope);
}
else // void
return nullptr;
context.register_llvm_value(entity->get_full_name().to_string(), fieldVal);
return fieldVal;
}
Value* TxTypeStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return this->typeDecl->code_gen(context, scope);
}
Value* TxAssignStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto rval = this->rvalue->code_gen(context, scope);
auto lval = this->lvalue->code_gen(context, scope);
if ((! lval) || (! rval))
return NULL;
if (! lval->getType()->isPointerTy()) {
context.LOG.error("L-value is not of pointer type: %s; %s", ::to_string(lval).c_str(), ::to_string(lval->getType()).c_str());
return rval;
}
return do_store(context, scope, lval, rval);
}
Value* TxDerefAssigneeNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto refval = this->operand->code_gen(context, scope);
if (! refval)
return NULL;
return refval;
}
Value* TxSuiteNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
// auto parentFunc = scope->builder->GetInsertBlock()->getParent();
// BasicBlock* suiteBlock = BasicBlock::Create(context.llvmContext, "suite", parentFunc);
// scope->builder->SetInsertPoint(suiteBlock);
for (auto stmt : *this->suite)
stmt->code_gen(context, scope);
// scope->builder->SetInsertPoint(continuationBlock);
return NULL;
}
Value* TxElseClauseNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return this->suite->code_gen(context, scope);
}
Value* TxIfStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto parentFunc = scope->builder->GetInsertBlock()->getParent();
BasicBlock* trueBlock = BasicBlock::Create(context.llvmContext, "if_true", parentFunc);
BasicBlock* falseBlock = BasicBlock::Create(context.llvmContext, "if_false", parentFunc);
BasicBlock* postBlock;
auto condVal = this->cond->code_gen(context, scope);
auto condInstr = scope->builder->CreateCondBr(condVal, trueBlock, falseBlock);
if (this->elseClause) {
postBlock = BasicBlock::Create(context.llvmContext, "if_post", parentFunc);
scope->builder->SetInsertPoint(falseBlock);
this->elseClause->code_gen(context, scope);
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(postBlock); // branch from end of else suite to post-block
}
else
postBlock = falseBlock;
scope->builder->SetInsertPoint(trueBlock);
this->suite->code_gen(context, scope);
// note: trueBlock is may not be the "current" block anymore when reaching end of true body
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(postBlock); // branch from end of true suite to post-block
scope->builder->SetInsertPoint(postBlock);
return condInstr;
}
Value* TxWhileStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
auto parentFunc = scope->builder->GetInsertBlock()->getParent();
BasicBlock* condBlock = BasicBlock::Create(context.llvmContext, "while_cond", parentFunc);
BasicBlock* loopBlock = BasicBlock::Create(context.llvmContext, "while_loop", parentFunc);
BasicBlock* elseBlock = BasicBlock::Create(context.llvmContext, "while_else", parentFunc);
BasicBlock* postBlock;
scope->builder->CreateBr(condBlock); // branch from end of preceding block to condition-block
scope->builder->SetInsertPoint(condBlock);
auto condVal = this->cond->code_gen(context, scope);
auto condInstr = scope->builder->CreateCondBr(condVal, loopBlock, elseBlock);
if (this->elseClause) {
postBlock = BasicBlock::Create(context.llvmContext, "while_post", parentFunc);
scope->builder->SetInsertPoint(elseBlock);
this->elseClause->code_gen(context, scope);
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(postBlock); // branch from end of else body to post-block
}
else
postBlock = elseBlock;
CompoundStatementScope css(condBlock, postBlock);
scope->compStmtStack.push(&css);
scope->builder->SetInsertPoint(loopBlock);
this->suite->code_gen(context, scope);
scope->compStmtStack.pop();
// note: loopBlock is may not be the "current" block anymore when reaching end of loop body
if (! scope->builder->GetInsertBlock()->getTerminator())
scope->builder->CreateBr(condBlock); // branch from end of loop body to condition-block
scope->builder->SetInsertPoint(postBlock);
return condInstr;
}
Value* TxCallStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return this->call->code_gen(context, scope);
}
Value* TxReturnStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
if (this->expr)
return scope->builder->CreateRet(this->expr->code_gen(context, scope));
else
return scope->builder->CreateRetVoid();
}
Value* TxBreakStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return scope->builder->CreateBr(scope->compStmtStack.top()->breakBlock);
}
Value* TxContinueStmtNode::code_gen(LlvmGenerationContext& context, GenScope* scope) const {
context.LOG.trace("%-48s", this->to_string().c_str());
return scope->builder->CreateBr(scope->compStmtStack.top()->continueBlock);
}
<|endoftext|> |
<commit_before><commit_msg>#i22705# Added virtual destructor.<commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Filesystem.h"
#include "Log.h"
#include "OS.h"
#include "DiskFile.h"
#include "Memory.h"
namespace crown
{
//-----------------------------------------------------------------------------
Filesystem::Filesystem(const char* root_path)
{
CE_ASSERT(root_path != NULL, "Root path must be != NULL");
CE_ASSERT(os::is_absolute_path(root_path), "Root path must be absolute");
string::strncpy(m_root_path, root_path, os::MAX_PATH_LENGTH);
}
//-----------------------------------------------------------------------------
Filesystem::~Filesystem()
{
}
//-----------------------------------------------------------------------------
const char* Filesystem::root_path() const
{
return m_root_path;
}
//-----------------------------------------------------------------------------
const char* Filesystem::build_os_path(const char* base_path, const char* relative_path)
{
static char os_path[os::MAX_PATH_LENGTH];
string::strncpy(os_path, base_path, os::MAX_PATH_LENGTH);
size_t base_path_len = string::strlen(base_path);
os_path[base_path_len] = os::PATH_SEPARATOR;
string::strncpy(&os_path[base_path_len + 1], relative_path, os::MAX_PATH_LENGTH);
// FIXME FIXME FIXME Replace Crown-specific path separator with OS-speficic one
for (size_t j = 0; j < string::strlen(os_path); j++)
{
if (os_path[j] == '/')
{
os_path[j] = os::PATH_SEPARATOR;
}
}
return os_path;
}
//-----------------------------------------------------------------------------
bool Filesystem::get_info(const char* relative_path, FilesystemEntry& info)
{
// Entering OS-DEPENDENT-PATH-MODE
// (i.e. os_path is of the form: C:\foo\relative_path or /foo/relative_path)
const char* os_path = build_os_path(m_root_path, relative_path);
string::strncpy(info.os_path, os_path, os::MAX_PATH_LENGTH);
string::strncpy(info.relative_path, relative_path, os::MAX_PATH_LENGTH);
if (os::is_reg(os_path))
{
info.type = FilesystemEntry::FILE;
return true;
}
else if (os::is_dir(os_path))
{
info.type = FilesystemEntry::DIRECTORY;
return true;
}
info.type = FilesystemEntry::UNKNOWN;
return false;
}
//-----------------------------------------------------------------------------
bool Filesystem::exists(const char* relative_path)
{
FilesystemEntry dummy;
return get_info(relative_path, dummy);
}
//-----------------------------------------------------------------------------
bool Filesystem::is_file(const char* relative_path)
{
FilesystemEntry info;
if (get_info(relative_path, info))
{
return info.type == FilesystemEntry::FILE;
}
return false;
}
//-----------------------------------------------------------------------------
bool Filesystem::is_dir(const char* relative_path)
{
FilesystemEntry info;
if (get_info(relative_path, info))
{
return info.type == FilesystemEntry::DIRECTORY;
}
return false;
}
//-----------------------------------------------------------------------------
bool Filesystem::create_file(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::mknod(os_path);
}
//-----------------------------------------------------------------------------
bool Filesystem::create_dir(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::mkdir(os_path);
}
//-----------------------------------------------------------------------------
bool Filesystem::delete_file(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::unlink(os_path);
}
//-----------------------------------------------------------------------------
bool Filesystem::delete_dir(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::rmdir(os_path);
}
//-----------------------------------------------------------------------------
const char* Filesystem::os_path(const char* relative_path)
{
static char os_path[os::MAX_PATH_LENGTH];
FilesystemEntry entry;
get_info(relative_path, entry);
string::strncpy(os_path, entry.os_path, os::MAX_PATH_LENGTH);
return os_path;
}
//-----------------------------------------------------------------------------
DiskFile* Filesystem::open(const char* relative_path, FileOpenMode mode)
{
FilesystemEntry info;
CE_ASSERT(get_info(relative_path, info), "File does not exist: %s", relative_path);
CE_ASSERT(info.type == FilesystemEntry::FILE, "File is not a regular file: %s", relative_path);
return CE_NEW(m_allocator, DiskFile)(mode, info.os_path);
}
//-----------------------------------------------------------------------------
void Filesystem::close(DiskFile* stream)
{
CE_DELETE(m_allocator, stream);
}
} // namespace crown
<commit_msg>Use appropriate functions instead of directly checking structures..."<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Filesystem.h"
#include "Log.h"
#include "OS.h"
#include "DiskFile.h"
#include "Memory.h"
namespace crown
{
//-----------------------------------------------------------------------------
Filesystem::Filesystem(const char* root_path)
{
CE_ASSERT(root_path != NULL, "Root path must be != NULL");
CE_ASSERT(os::is_absolute_path(root_path), "Root path must be absolute");
string::strncpy(m_root_path, root_path, os::MAX_PATH_LENGTH);
}
//-----------------------------------------------------------------------------
Filesystem::~Filesystem()
{
}
//-----------------------------------------------------------------------------
const char* Filesystem::root_path() const
{
return m_root_path;
}
//-----------------------------------------------------------------------------
const char* Filesystem::build_os_path(const char* base_path, const char* relative_path)
{
static char os_path[os::MAX_PATH_LENGTH];
string::strncpy(os_path, base_path, os::MAX_PATH_LENGTH);
size_t base_path_len = string::strlen(base_path);
os_path[base_path_len] = os::PATH_SEPARATOR;
string::strncpy(&os_path[base_path_len + 1], relative_path, os::MAX_PATH_LENGTH);
// FIXME FIXME FIXME Replace Crown-specific path separator with OS-speficic one
for (size_t j = 0; j < string::strlen(os_path); j++)
{
if (os_path[j] == '/')
{
os_path[j] = os::PATH_SEPARATOR;
}
}
return os_path;
}
//-----------------------------------------------------------------------------
bool Filesystem::get_info(const char* relative_path, FilesystemEntry& info)
{
// Entering OS-DEPENDENT-PATH-MODE
// (i.e. os_path is of the form: C:\foo\relative_path or /foo/relative_path)
const char* os_path = build_os_path(m_root_path, relative_path);
string::strncpy(info.os_path, os_path, os::MAX_PATH_LENGTH);
string::strncpy(info.relative_path, relative_path, os::MAX_PATH_LENGTH);
if (os::is_reg(os_path))
{
info.type = FilesystemEntry::FILE;
return true;
}
else if (os::is_dir(os_path))
{
info.type = FilesystemEntry::DIRECTORY;
return true;
}
info.type = FilesystemEntry::UNKNOWN;
return false;
}
//-----------------------------------------------------------------------------
bool Filesystem::exists(const char* relative_path)
{
FilesystemEntry dummy;
return get_info(relative_path, dummy);
}
//-----------------------------------------------------------------------------
bool Filesystem::is_file(const char* relative_path)
{
FilesystemEntry info;
if (get_info(relative_path, info))
{
return info.type == FilesystemEntry::FILE;
}
return false;
}
//-----------------------------------------------------------------------------
bool Filesystem::is_dir(const char* relative_path)
{
FilesystemEntry info;
if (get_info(relative_path, info))
{
return info.type == FilesystemEntry::DIRECTORY;
}
return false;
}
//-----------------------------------------------------------------------------
bool Filesystem::create_file(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::mknod(os_path);
}
//-----------------------------------------------------------------------------
bool Filesystem::create_dir(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::mkdir(os_path);
}
//-----------------------------------------------------------------------------
bool Filesystem::delete_file(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::unlink(os_path);
}
//-----------------------------------------------------------------------------
bool Filesystem::delete_dir(const char* relative_path)
{
const char* os_path = build_os_path(m_root_path, relative_path);
return os::rmdir(os_path);
}
//-----------------------------------------------------------------------------
const char* Filesystem::os_path(const char* relative_path)
{
static char os_path[os::MAX_PATH_LENGTH];
FilesystemEntry entry;
get_info(relative_path, entry);
string::strncpy(os_path, entry.os_path, os::MAX_PATH_LENGTH);
return os_path;
}
//-----------------------------------------------------------------------------
DiskFile* Filesystem::open(const char* relative_path, FileOpenMode mode)
{
FilesystemEntry info;
CE_ASSERT(exists(relative_path), "File does not exist: %s", relative_path);
CE_ASSERT(is_file(relative_path), "File is not a regular file: %s", relative_path);
return CE_NEW(m_allocator, DiskFile)(mode, info.os_path);
}
//-----------------------------------------------------------------------------
void Filesystem::close(DiskFile* stream)
{
CE_DELETE(m_allocator, stream);
}
} // namespace crown
<|endoftext|> |
<commit_before>///
/// @file P2.cpp
/// @brief 2nd partial sieve function. P2(x, y) counts the
/// numbers <= x that have exactly 2 prime factors
/// each exceeding the a-th prime.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <calculator.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <json.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iomanip>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
using namespace nlohmann;
namespace {
/// Count the primes inside [prime, stop]
template <typename T>
int64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)
{
int64_t count = 0;
for (; prime <= stop; count++)
prime = it.next_prime();
return count;
}
/// Calculate the thread sieving distance. The idea is to
/// gradually increase the thread_distance in order to
/// keep all CPU cores busy.
///
void balanceLoad(int64_t* thread_distance,
int64_t low,
int64_t z,
int threads,
double start_time)
{
double seconds = get_wtime() - start_time;
int64_t min_distance = 1 << 23;
int64_t max_distance = ceil_div(z - low, threads);
if (seconds < 60)
*thread_distance *= 2;
if (seconds > 60)
*thread_distance /= 2;
*thread_distance = in_between(min_distance, *thread_distance, max_distance);
}
template <typename T>
T P2_thread(T x,
int64_t y,
int64_t z,
int64_t low,
int64_t thread_num,
int64_t thread_distance,
int64_t& pix,
int64_t& pix_count)
{
pix = 0;
pix_count = 0;
low += thread_distance * thread_num;
z = min(low + thread_distance, z);
int64_t start = (int64_t) max(x / z, y);
int64_t stop = (int64_t) min(x / low, isqrt(x));
primesieve::iterator rit(stop + 1, start);
primesieve::iterator it(low - 1, z);
int64_t next = it.next_prime();
int64_t prime = rit.prev_prime();
T p2 = 0;
// \sum_{i = pi[start]+1}^{pi[stop]} pi(x / primes[i])
while (prime > start &&
x / prime < z)
{
pix += count_primes(it, next, x / prime);
p2 += pix;
pix_count++;
prime = rit.prev_prime();
}
pix += count_primes(it, next, z - 1);
return p2;
}
template <typename T>
void backup(T x,
int64_t y,
int64_t z,
int64_t low,
int64_t thread_distance,
T pix_total,
T p2,
double time)
{
ifstream ifs("primecount.backup");
json j;
if (ifs.is_open())
{
ifs >> j;
ifs.close();
}
double percent = get_percent(low, z);
j["P2"]["x"] = to_string(x);
j["P2"]["y"] = y;
j["P2"]["z"] = z;
j["P2"]["low"] = low;
j["P2"]["thread_distance"] = thread_distance;
j["P2"]["pix_total"] = to_string(pix_total);
j["P2"]["p2"] = to_string(p2);
j["P2"]["percent"] = percent;
j["P2"]["seconds"] = get_wtime() - time;
ofstream ofs("primecount.backup");
ofs << setw(4) << j << endl;
}
template <typename T>
void resume(T x,
int64_t y,
int64_t z,
int64_t& low,
int64_t& thread_distance,
T& pix_total,
T& p2,
double& time)
{
ifstream ifs("primecount.backup");
json j;
if (ifs.is_open())
{
ifs >> j;
ifs.close();
}
if (j.find("P2") != j.end() &&
x == calculator::eval<T>(j["P2"]["x"]) &&
y == j["P2"]["y"] &&
z == j["P2"]["z"])
{
double percent = j["P2"]["percent"];
double seconds = j["P2"]["seconds"];
low = j["P2"]["low"];
thread_distance = j["P2"]["thread_distance"];
pix_total = calculator::eval<T>(j["P2"]["pix_total"]);
p2 = calculator::eval<T>(j["P2"]["p2"]);
time = get_wtime() - seconds;
if (is_print())
{
if (!print_variables())
cout << endl;
cout << "=== Resuming from primecount.backup ===" << endl;
cout << "low = " << low << endl;
cout << "thread_distance = " << thread_distance << endl;
cout << "pix_total = " << pix_total << endl;
cout << "p2 = " << p2 << endl;
cout << "Seconds: " << fixed << setprecision(3) << seconds << endl << endl;
cout << "Status: " << fixed << setprecision(get_status_precision(x)) << percent << '%' << flush;
}
}
}
/// P2(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime.
/// Run-time: O(z log log z)
///
template <typename T>
T P2_OpenMP(T x, int64_t y, int threads)
{
static_assert(prt::is_signed<T>::value,
"P2(T x, ...): T must be signed integer type");
if (x < 4)
return 0;
T a = pi_legendre(y, threads);
T b = pi_legendre((int64_t) isqrt(x), threads);
if (a >= b)
return 0;
// \sum_{i=a+1}^{b} -(i - 1)
T p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;
T pix_total = 0;
int64_t low = 2;
int64_t z = (int64_t)(x / max(y, 1));
int64_t min_distance = 1 << 23;
int64_t thread_distance = min_distance;
aligned_vector<int64_t> pix(threads);
aligned_vector<int64_t> pix_counts(threads);
double time = get_wtime();
resume(x, y, z, low, thread_distance, pix_total, p2, time);
// \sum_{i=a+1}^{b} pi(x / primes[i])
while (low < z)
{
int64_t max_threads = ceil_div(z - low, thread_distance);
threads = in_between(1, threads, max_threads);
double t = get_wtime();
#pragma omp parallel for num_threads(threads) reduction(+: p2)
for (int i = 0; i < threads; i++)
p2 += P2_thread(x, y, z, low, i, thread_distance, pix[i], pix_counts[i]);
low += thread_distance * threads;
balanceLoad(&thread_distance, low, z, threads, t);
// add missing sum contributions in order
for (int i = 0; i < threads; i++)
{
p2 += pix_total * pix_counts[i];
pix_total += pix[i];
}
backup(x, y, z, low, thread_distance, pix_total, p2, time);
if (is_print())
{
double percent = get_percent(low, z);
cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
<< percent << '%' << flush;
}
}
print("P2", p2, time);
return p2;
}
} // namespace
namespace primecount {
int64_t P2(int64_t x, int64_t y, int threads)
{
#ifdef HAVE_MPI
if (mpi_num_procs() > 1)
return P2_mpi(x, y, threads);
#endif
print("");
print("=== P2(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
int64_t p2 = P2_OpenMP(x, y, threads);
return p2;
}
#ifdef HAVE_INT128_T
int128_t P2(int128_t x, int64_t y, int threads)
{
#ifdef HAVE_MPI
if (mpi_num_procs() > 1)
return P2_mpi(x, y, threads);
#endif
print("");
print("=== P2(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
int128_t p2 = P2_OpenMP(x, y, threads);
return p2;
}
#endif
} // namespace
<commit_msg>Refactor<commit_after>///
/// @file P2.cpp
/// @brief 2nd partial sieve function. P2(x, y) counts the
/// numbers <= x that have exactly 2 prime factors
/// each exceeding the a-th prime.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <calculator.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <json.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iomanip>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
using namespace nlohmann;
namespace {
/// Count the primes inside [prime, stop]
template <typename T>
int64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)
{
int64_t count = 0;
for (; prime <= stop; count++)
prime = it.next_prime();
return count;
}
/// Calculate the thread sieving distance. The idea is to
/// gradually increase the thread_distance in order to
/// keep all CPU cores busy.
///
void balanceLoad(int64_t* thread_distance,
int64_t low,
int64_t z,
int threads,
double start_time)
{
double seconds = get_wtime() - start_time;
int64_t min_distance = 1 << 23;
int64_t max_distance = ceil_div(z - low, threads);
if (seconds < 60)
*thread_distance *= 2;
if (seconds > 60)
*thread_distance /= 2;
*thread_distance = in_between(min_distance, *thread_distance, max_distance);
}
template <typename T>
T P2_thread(T x,
int64_t y,
int64_t z,
int64_t low,
int64_t thread_num,
int64_t thread_distance,
int64_t& pix,
int64_t& pix_count)
{
pix = 0;
pix_count = 0;
low += thread_distance * thread_num;
z = min(low + thread_distance, z);
int64_t start = (int64_t) max(x / z, y);
int64_t stop = (int64_t) min(x / low, isqrt(x));
primesieve::iterator rit(stop + 1, start);
primesieve::iterator it(low - 1, z);
int64_t next = it.next_prime();
int64_t prime = rit.prev_prime();
T p2 = 0;
// \sum_{i = pi[start]+1}^{pi[stop]} pi(x / primes[i])
while (prime > start &&
x / prime < z)
{
pix += count_primes(it, next, x / prime);
p2 += pix;
pix_count++;
prime = rit.prev_prime();
}
pix += count_primes(it, next, z - 1);
return p2;
}
template <typename T>
void backup(T x,
int64_t y,
int64_t z,
int64_t low,
int64_t thread_distance,
T pix_total,
T p2,
double time)
{
ifstream ifs("primecount.backup");
json j;
if (ifs.is_open())
{
ifs >> j;
ifs.close();
}
double percent = get_percent(low, z);
j["P2"]["x"] = to_string(x);
j["P2"]["y"] = y;
j["P2"]["z"] = z;
j["P2"]["low"] = low;
j["P2"]["thread_distance"] = thread_distance;
j["P2"]["pix_total"] = to_string(pix_total);
j["P2"]["p2"] = to_string(p2);
j["P2"]["percent"] = percent;
j["P2"]["seconds"] = get_wtime() - time;
ofstream ofs("primecount.backup");
ofs << setw(4) << j << endl;
}
template <typename T>
void resume(T x,
int64_t y,
int64_t z,
int64_t& low,
int64_t& thread_distance,
T& pix_total,
T& p2,
double& time)
{
ifstream ifs("primecount.backup");
json j;
if (ifs.is_open())
{
ifs >> j;
ifs.close();
}
if (j.find("P2") != j.end() &&
x == calculator::eval<T>(j["P2"]["x"]) &&
y == j["P2"]["y"] &&
z == j["P2"]["z"])
{
double percent = j["P2"]["percent"];
double seconds = j["P2"]["seconds"];
low = j["P2"]["low"];
thread_distance = j["P2"]["thread_distance"];
pix_total = calculator::eval<T>(j["P2"]["pix_total"]);
p2 = calculator::eval<T>(j["P2"]["p2"]);
time = get_wtime() - seconds;
if (is_print())
{
if (!print_variables())
cout << endl;
cout << "=== Resuming from primecount.backup ===" << endl;
cout << "low = " << low << endl;
cout << "thread_distance = " << thread_distance << endl;
cout << "pix_total = " << pix_total << endl;
cout << "p2 = " << p2 << endl;
cout << "Seconds: " << fixed << setprecision(3) << seconds << endl << endl;
cout << "Status: " << fixed << setprecision(get_status_precision(x)) << percent << '%' << flush;
}
}
}
/// P2(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime.
/// Run-time: O(z log log z)
///
template <typename T>
T P2_OpenMP(T x, int64_t y, int threads, double& time)
{
static_assert(prt::is_signed<T>::value,
"P2(T x, ...): T must be signed integer type");
if (x < 4)
return 0;
T a = pi_legendre(y, threads);
T b = pi_legendre((int64_t) isqrt(x), threads);
if (a >= b)
return 0;
// \sum_{i=a+1}^{b} -(i - 1)
T p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;
T pix_total = 0;
int64_t low = 2;
int64_t z = (int64_t)(x / max(y, 1));
int64_t min_distance = 1 << 23;
int64_t thread_distance = min_distance;
aligned_vector<int64_t> pix(threads);
aligned_vector<int64_t> pix_counts(threads);
resume(x, y, z, low, thread_distance, pix_total, p2, time);
// \sum_{i=a+1}^{b} pi(x / primes[i])
while (low < z)
{
int64_t max_threads = ceil_div(z - low, thread_distance);
threads = in_between(1, threads, max_threads);
double t = get_wtime();
#pragma omp parallel for num_threads(threads) reduction(+: p2)
for (int i = 0; i < threads; i++)
p2 += P2_thread(x, y, z, low, i, thread_distance, pix[i], pix_counts[i]);
low += thread_distance * threads;
balanceLoad(&thread_distance, low, z, threads, t);
// add missing sum contributions in order
for (int i = 0; i < threads; i++)
{
p2 += pix_total * pix_counts[i];
pix_total += pix[i];
}
backup(x, y, z, low, thread_distance, pix_total, p2, time);
if (is_print())
{
double percent = get_percent(low, z);
cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
<< percent << '%' << flush;
}
}
return p2;
}
} // namespace
namespace primecount {
int64_t P2(int64_t x, int64_t y, int threads)
{
#ifdef HAVE_MPI
if (mpi_num_procs() > 1)
return P2_mpi(x, y, threads);
#endif
print("");
print("=== P2(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int64_t p2 = P2_OpenMP(x, y, threads, time);
print("P2", p2, time);
return p2;
}
#ifdef HAVE_INT128_T
int128_t P2(int128_t x, int64_t y, int threads)
{
#ifdef HAVE_MPI
if (mpi_num_procs() > 1)
return P2_mpi(x, y, threads);
#endif
print("");
print("=== P2(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int128_t p2 = P2_OpenMP(x, y, threads, time);
print("P2", p2, time);
return p2;
}
#endif
} // namespace
<|endoftext|> |
<commit_before>/*
* RTokenizer.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RTokenizer.hpp>
#include <boost/regex.hpp>
#include <iostream>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/StringUtils.hpp>
// TODO: include files in the query
// TODO: open with project-level encoding & convert to UTF-8 / wide
// TODO: indexing queue
// TODO: limit indexing for cases of thousands (or hundreds) of files
// TODO: implement file monitoring
// TODO: once we have file monitoring the source database will only
// need to track indexes for dirty files
// TODO: consider further optimization of only generating source
// indexes on-demand for the src db
namespace core {
namespace r_util {
namespace {
class TokenPatterns
{
private:
friend TokenPatterns& tokenPatterns();
TokenPatterns()
: NUMBER(L"[0-9]*(\\.[0-9]*)?([eE][+-]?[0-9]*)?[Li]?"),
HEX_NUMBER(L"0x[0-9a-fA-F]*L?"),
USER_OPERATOR(L"%[^%]*%"),
QUOTED_IDENTIFIER(L"`[^`]*`"),
UNTIL_END_QUOTE(L"[\\\\\'\"]"),
WHITESPACE(L"[\\s\x00A0\x3000]+"),
COMMENT(L"#.*?$")
{
}
public:
const boost::wregex NUMBER;
const boost::wregex HEX_NUMBER;
const boost::wregex USER_OPERATOR;
const boost::wregex QUOTED_IDENTIFIER;
const boost::wregex UNTIL_END_QUOTE;
const boost::wregex WHITESPACE;
const boost::wregex COMMENT;
};
TokenPatterns& tokenPatterns()
{
static TokenPatterns instance;
return instance;
}
} // anonymous namespace
const wchar_t RToken::LPAREN = L'(';
const wchar_t RToken::RPAREN = L')';
const wchar_t RToken::LBRACKET = L'[';
const wchar_t RToken::RBRACKET = L']';
const wchar_t RToken::LBRACE = L'{';
const wchar_t RToken::RBRACE = L'}';
const wchar_t RToken::COMMA = L',';
const wchar_t RToken::SEMI = L';';
const wchar_t RToken::WHITESPACE = 0x1001;
const wchar_t RToken::STRING = 0x1002;
const wchar_t RToken::NUMBER = 0x1003;
const wchar_t RToken::ID = 0x1004;
const wchar_t RToken::OPER = 0x1005;
const wchar_t RToken::UOPER = 0x1006;
const wchar_t RToken::ERR = 0x1007;
const wchar_t RToken::LDBRACKET = 0x1008;
const wchar_t RToken::RDBRACKET = 0x1009;
const wchar_t RToken::COMMENT = 0x100A;
RToken RTokenizer::nextToken()
{
if (eol())
return RToken() ;
wchar_t c = peek() ;
switch (c)
{
case L'(': case L')':
case L'{': case L'}':
case L';': case L',':
return consumeToken(c, 1) ;
case L'[':
if (peek(1) == L'[')
return consumeToken(RToken::LDBRACKET, 2) ;
else
return consumeToken(c, 1) ;
case L']':
if (peek(1) == L']')
return consumeToken(RToken::RDBRACKET, 2) ;
else
return consumeToken(c, 1) ;
case L'"':
case L'\'':
return matchStringLiteral() ;
case L'`':
return matchQuotedIdentifier();
case L'#':
return matchComment();
case L'%':
return matchUserOperator();
case L' ': case L'\t': case L'\r': case L'\n':
case L'\x00A0': case L'\x3000':
return matchWhitespace() ;
}
wchar_t cNext = peek(1) ;
if ((c >= L'0' && c <= L'9')
|| (c == L'.' && cNext >= L'0' && cNext <= L'9'))
{
RToken numberToken = matchNumber() ;
if (numberToken.length() > 0)
return numberToken ;
}
if (string_utils::isalnum(c) || c == L'.')
{
// From Section 10.3.2, identifiers must not start with
// a digit, nor may they start with a period followed by
// a digit.
//
// Since we're not checking for either condition, we must
// match on identifiers AFTER we have already tried to
// match on number.
return matchIdentifier() ;
}
RToken oper = matchOperator() ;
if (oper)
return oper ;
// Error!!
return consumeToken(RToken::ERR, 1) ;
}
RToken RTokenizer::matchWhitespace()
{
std::wstring whitespace = peek(tokenPatterns().WHITESPACE) ;
return consumeToken(RToken::WHITESPACE, whitespace.length()) ;
}
RToken RTokenizer::matchStringLiteral()
{
std::wstring::const_iterator start = pos_ ;
wchar_t quot = eat() ;
bool wellFormed = false ;
while (!eol())
{
eatUntil(tokenPatterns().UNTIL_END_QUOTE);
if (eol())
break ;
wchar_t c = eat() ;
if (c == quot)
{
wellFormed = true ;
break ;
}
if (c == L'\\')
{
if (!eol())
eat() ;
// Actually the escape expression can be longer than
// just the backslash plus one character--but we don't
// need to distinguish escape expressions from other
// literal text other than for the purposes of breaking
// out of the string
}
}
// NOTE: the Java version of the tokenizer returns a special RStringToken
// subclass which includes the wellFormed flag as an attribute. Our
// implementation of RToken is stack based so doesn't support subclasses
// (because they will be sliced when copied). If we need the well
// formed flag we can just add it onto RToken.
return RToken(RToken::STRING,
start,
pos_,
start - data_.begin());
}
RToken RTokenizer::matchNumber()
{
std::wstring num = peek(tokenPatterns().HEX_NUMBER) ;
if (num.empty())
num = peek(tokenPatterns().NUMBER) ;
return consumeToken(RToken::NUMBER, num.length());
}
RToken RTokenizer::matchIdentifier()
{
std::wstring::const_iterator start = pos_ ;
eat();
while (string_utils::isalnum(peek()) || peek() == L'.' || peek() == L'_')
eat();
return RToken(RToken::ID,
start,
pos_,
start - data_.begin()) ;
}
RToken RTokenizer::matchQuotedIdentifier()
{
std::wstring iden = peek(tokenPatterns().QUOTED_IDENTIFIER) ;
if (iden.empty())
return consumeToken(RToken::ERR, 1);
else
return consumeToken(RToken::ID, iden.length());
}
RToken RTokenizer::matchComment()
{
std::wstring comment = peek(tokenPatterns().COMMENT);
return consumeToken(RToken::COMMENT, comment.length());
}
RToken RTokenizer::matchUserOperator()
{
std::wstring oper = peek(tokenPatterns().USER_OPERATOR) ;
if (oper.empty())
return consumeToken(RToken::ERR, 1) ;
else
return consumeToken(RToken::UOPER, oper.length()) ;
}
RToken RTokenizer::matchOperator()
{
wchar_t cNext = peek(1) ;
switch (peek())
{
case L'+': case L'*': case L'/':
case L'^': case L'&': case L'|':
case L'~': case L'$': case L':':
// single-character operators
return consumeToken(RToken::OPER, 1) ;
case L'-': // also ->
return consumeToken(RToken::OPER, cNext == L'>' ? 2 : 1) ;
case L'>': // also >=
return consumeToken(RToken::OPER, cNext == L'=' ? 2 : 1) ;
case L'<': // also <- and <=
return consumeToken(RToken::OPER, cNext == L'=' ? 2 :
cNext == L'-' ? 2 :
1) ;
case L'=': // also ==
return consumeToken(RToken::OPER, cNext == L'=' ? 2 : 1) ;
case L'!': // also !=
return consumeToken(RToken::OPER, cNext == L'=' ? 2 : 1) ;
default:
return RToken() ;
}
}
bool RTokenizer::eol()
{
return pos_ >= data_.end();
}
wchar_t RTokenizer::peek()
{
return peek(0) ;
}
wchar_t RTokenizer::peek(std::size_t lookahead)
{
if ((pos_ + lookahead) >= data_.end())
return 0 ;
else
return *(pos_ + lookahead) ;
}
wchar_t RTokenizer::eat()
{
wchar_t result = *pos_;
pos_++ ;
return result ;
}
std::wstring RTokenizer::peek(const boost::wregex& regex)
{
boost::wsmatch match;
std::wstring::const_iterator end = data_.end();
boost::match_flag_type flg = boost::match_default | boost::match_continuous;
if (boost::regex_search(pos_, end, match, regex, flg))
{
return match[0];
}
else
{
return std::wstring();
}
}
void RTokenizer::eatUntil(const boost::wregex& regex)
{
boost::wsmatch match;
std::wstring::const_iterator end = data_.end();
if (boost::regex_search(pos_, end, match, regex))
{
pos_ = match[0].first;
}
else
{
// eat all on failure to match
pos_ = data_.end();
}
}
RToken RTokenizer::consumeToken(wchar_t tokenType, std::size_t length)
{
if (length == 0)
{
LOG_WARNING_MESSAGE("Can't create zero-length token");
return RToken();
}
else if ((pos_ + length) > data_.end())
{
LOG_WARNING_MESSAGE("Premature EOF");
return RToken();
}
std::wstring::const_iterator start = pos_ ;
pos_ += length ;
return RToken(tokenType,
start,
pos_,
start - data_.begin()) ;
}
} // namespace r_util
} // namespace core
<commit_msg>update todo comments<commit_after>/*
* RTokenizer.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RTokenizer.hpp>
#include <boost/regex.hpp>
#include <iostream>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/StringUtils.hpp>
// TODO: test recursive directory iterator
// TODO: include files in the query
// TODO: open with project-level encoding & convert to UTF-8 / wide
// TODO: indexing queue
// TODO: limit indexing for cases of thousands (or hundreds) of files
// TODO: implement file monitoring
// TODO: once we have file monitoring the source database will only
// need to track indexes for dirty files
// TODO: consider further optimization of only generating source
// indexes on-demand for the src db
namespace core {
namespace r_util {
namespace {
class TokenPatterns
{
private:
friend TokenPatterns& tokenPatterns();
TokenPatterns()
: NUMBER(L"[0-9]*(\\.[0-9]*)?([eE][+-]?[0-9]*)?[Li]?"),
HEX_NUMBER(L"0x[0-9a-fA-F]*L?"),
USER_OPERATOR(L"%[^%]*%"),
QUOTED_IDENTIFIER(L"`[^`]*`"),
UNTIL_END_QUOTE(L"[\\\\\'\"]"),
WHITESPACE(L"[\\s\x00A0\x3000]+"),
COMMENT(L"#.*?$")
{
}
public:
const boost::wregex NUMBER;
const boost::wregex HEX_NUMBER;
const boost::wregex USER_OPERATOR;
const boost::wregex QUOTED_IDENTIFIER;
const boost::wregex UNTIL_END_QUOTE;
const boost::wregex WHITESPACE;
const boost::wregex COMMENT;
};
TokenPatterns& tokenPatterns()
{
static TokenPatterns instance;
return instance;
}
} // anonymous namespace
const wchar_t RToken::LPAREN = L'(';
const wchar_t RToken::RPAREN = L')';
const wchar_t RToken::LBRACKET = L'[';
const wchar_t RToken::RBRACKET = L']';
const wchar_t RToken::LBRACE = L'{';
const wchar_t RToken::RBRACE = L'}';
const wchar_t RToken::COMMA = L',';
const wchar_t RToken::SEMI = L';';
const wchar_t RToken::WHITESPACE = 0x1001;
const wchar_t RToken::STRING = 0x1002;
const wchar_t RToken::NUMBER = 0x1003;
const wchar_t RToken::ID = 0x1004;
const wchar_t RToken::OPER = 0x1005;
const wchar_t RToken::UOPER = 0x1006;
const wchar_t RToken::ERR = 0x1007;
const wchar_t RToken::LDBRACKET = 0x1008;
const wchar_t RToken::RDBRACKET = 0x1009;
const wchar_t RToken::COMMENT = 0x100A;
RToken RTokenizer::nextToken()
{
if (eol())
return RToken() ;
wchar_t c = peek() ;
switch (c)
{
case L'(': case L')':
case L'{': case L'}':
case L';': case L',':
return consumeToken(c, 1) ;
case L'[':
if (peek(1) == L'[')
return consumeToken(RToken::LDBRACKET, 2) ;
else
return consumeToken(c, 1) ;
case L']':
if (peek(1) == L']')
return consumeToken(RToken::RDBRACKET, 2) ;
else
return consumeToken(c, 1) ;
case L'"':
case L'\'':
return matchStringLiteral() ;
case L'`':
return matchQuotedIdentifier();
case L'#':
return matchComment();
case L'%':
return matchUserOperator();
case L' ': case L'\t': case L'\r': case L'\n':
case L'\x00A0': case L'\x3000':
return matchWhitespace() ;
}
wchar_t cNext = peek(1) ;
if ((c >= L'0' && c <= L'9')
|| (c == L'.' && cNext >= L'0' && cNext <= L'9'))
{
RToken numberToken = matchNumber() ;
if (numberToken.length() > 0)
return numberToken ;
}
if (string_utils::isalnum(c) || c == L'.')
{
// From Section 10.3.2, identifiers must not start with
// a digit, nor may they start with a period followed by
// a digit.
//
// Since we're not checking for either condition, we must
// match on identifiers AFTER we have already tried to
// match on number.
return matchIdentifier() ;
}
RToken oper = matchOperator() ;
if (oper)
return oper ;
// Error!!
return consumeToken(RToken::ERR, 1) ;
}
RToken RTokenizer::matchWhitespace()
{
std::wstring whitespace = peek(tokenPatterns().WHITESPACE) ;
return consumeToken(RToken::WHITESPACE, whitespace.length()) ;
}
RToken RTokenizer::matchStringLiteral()
{
std::wstring::const_iterator start = pos_ ;
wchar_t quot = eat() ;
bool wellFormed = false ;
while (!eol())
{
eatUntil(tokenPatterns().UNTIL_END_QUOTE);
if (eol())
break ;
wchar_t c = eat() ;
if (c == quot)
{
wellFormed = true ;
break ;
}
if (c == L'\\')
{
if (!eol())
eat() ;
// Actually the escape expression can be longer than
// just the backslash plus one character--but we don't
// need to distinguish escape expressions from other
// literal text other than for the purposes of breaking
// out of the string
}
}
// NOTE: the Java version of the tokenizer returns a special RStringToken
// subclass which includes the wellFormed flag as an attribute. Our
// implementation of RToken is stack based so doesn't support subclasses
// (because they will be sliced when copied). If we need the well
// formed flag we can just add it onto RToken.
return RToken(RToken::STRING,
start,
pos_,
start - data_.begin());
}
RToken RTokenizer::matchNumber()
{
std::wstring num = peek(tokenPatterns().HEX_NUMBER) ;
if (num.empty())
num = peek(tokenPatterns().NUMBER) ;
return consumeToken(RToken::NUMBER, num.length());
}
RToken RTokenizer::matchIdentifier()
{
std::wstring::const_iterator start = pos_ ;
eat();
while (string_utils::isalnum(peek()) || peek() == L'.' || peek() == L'_')
eat();
return RToken(RToken::ID,
start,
pos_,
start - data_.begin()) ;
}
RToken RTokenizer::matchQuotedIdentifier()
{
std::wstring iden = peek(tokenPatterns().QUOTED_IDENTIFIER) ;
if (iden.empty())
return consumeToken(RToken::ERR, 1);
else
return consumeToken(RToken::ID, iden.length());
}
RToken RTokenizer::matchComment()
{
std::wstring comment = peek(tokenPatterns().COMMENT);
return consumeToken(RToken::COMMENT, comment.length());
}
RToken RTokenizer::matchUserOperator()
{
std::wstring oper = peek(tokenPatterns().USER_OPERATOR) ;
if (oper.empty())
return consumeToken(RToken::ERR, 1) ;
else
return consumeToken(RToken::UOPER, oper.length()) ;
}
RToken RTokenizer::matchOperator()
{
wchar_t cNext = peek(1) ;
switch (peek())
{
case L'+': case L'*': case L'/':
case L'^': case L'&': case L'|':
case L'~': case L'$': case L':':
// single-character operators
return consumeToken(RToken::OPER, 1) ;
case L'-': // also ->
return consumeToken(RToken::OPER, cNext == L'>' ? 2 : 1) ;
case L'>': // also >=
return consumeToken(RToken::OPER, cNext == L'=' ? 2 : 1) ;
case L'<': // also <- and <=
return consumeToken(RToken::OPER, cNext == L'=' ? 2 :
cNext == L'-' ? 2 :
1) ;
case L'=': // also ==
return consumeToken(RToken::OPER, cNext == L'=' ? 2 : 1) ;
case L'!': // also !=
return consumeToken(RToken::OPER, cNext == L'=' ? 2 : 1) ;
default:
return RToken() ;
}
}
bool RTokenizer::eol()
{
return pos_ >= data_.end();
}
wchar_t RTokenizer::peek()
{
return peek(0) ;
}
wchar_t RTokenizer::peek(std::size_t lookahead)
{
if ((pos_ + lookahead) >= data_.end())
return 0 ;
else
return *(pos_ + lookahead) ;
}
wchar_t RTokenizer::eat()
{
wchar_t result = *pos_;
pos_++ ;
return result ;
}
std::wstring RTokenizer::peek(const boost::wregex& regex)
{
boost::wsmatch match;
std::wstring::const_iterator end = data_.end();
boost::match_flag_type flg = boost::match_default | boost::match_continuous;
if (boost::regex_search(pos_, end, match, regex, flg))
{
return match[0];
}
else
{
return std::wstring();
}
}
void RTokenizer::eatUntil(const boost::wregex& regex)
{
boost::wsmatch match;
std::wstring::const_iterator end = data_.end();
if (boost::regex_search(pos_, end, match, regex))
{
pos_ = match[0].first;
}
else
{
// eat all on failure to match
pos_ = data_.end();
}
}
RToken RTokenizer::consumeToken(wchar_t tokenType, std::size_t length)
{
if (length == 0)
{
LOG_WARNING_MESSAGE("Can't create zero-length token");
return RToken();
}
else if ((pos_ + length) > data_.end())
{
LOG_WARNING_MESSAGE("Premature EOF");
return RToken();
}
std::wstring::const_iterator start = pos_ ;
pos_ += length ;
return RToken(tokenType,
start,
pos_,
start - data_.begin()) ;
}
} // namespace r_util
} // namespace core
<|endoftext|> |
<commit_before>/*
* RToolsInfo.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RToolsInfo.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Log.hpp>
#include <core/StringUtils.hpp>
#include <core/system/RegistryKey.hpp>
#ifndef KEY_WOW64_32KEY
#define KEY_WOW64_32KEY 0x0200
#endif
namespace core {
namespace r_util {
namespace {
} // anonymous namespace
RToolsInfo::RToolsInfo(const std::string& name, const FilePath& installPath)
: name_(name), installPath_(installPath)
{
std::string versionMin, versionMax;
std::vector<std::string> relativePathEntries;
if (name == "2.11")
{
versionMin = "2.10.0";
versionMax = "2.11.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
}
else if (name == "2.12")
{
versionMin = "2.12.0";
versionMax = "2.12.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.13")
{
versionMin = "2.13.0";
versionMax = "2.13.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.14")
{
versionMin = "2.13.0";
versionMax = "2.14.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.15")
{
versionMin = "2.14.2";
versionMax = "2.15.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
}
else if (name == "2.16")
{
versionMin = "2.15.2";
versionMax = "2.16.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
}
// build version predicate and path list if we can
if (!versionMin.empty())
{
boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\"");
versionPredicate_ = boost::str(fmt % versionMin % versionMax);
BOOST_FOREACH(const std::string& relativePath, relativePathEntries)
{
pathEntries_.push_back(installPath_.childPath(relativePath));
}
}
}
std::ostream& operator<<(std::ostream& os, const RToolsInfo& info)
{
os << "Rtools " << info.name() << std::endl;
os << info.versionPredicate() << std::endl;
BOOST_FOREACH(const FilePath& pathEntry, info.pathEntries())
{
os << pathEntry << std::endl;
}
return os;
}
Error scanRegistryForRTools(std::vector<RToolsInfo>* pRTools)
{
core::system::RegistryKey regKey;
Error error = regKey.open(HKEY_LOCAL_MACHINE,
"Software\\R-core\\Rtools",
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
if (error.code() != boost::system::errc::no_such_file_or_directory)
return error;
else
return Success();
}
std::vector<std::string> keys = regKey.keyNames();
for (int i = 0; i < keys.size(); i++)
{
std::string name = keys.at(i);
core::system::RegistryKey verKey;
error = verKey.open(regKey.handle(),
name,
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
LOG_ERROR(error);
continue;
}
std::string installPath = verKey.getStringValue("InstallPath", "");
if (!installPath.empty())
{
std::string utf8InstallPath = string_utils::systemToUtf8(installPath);
RToolsInfo toolsInfo(name, FilePath(utf8InstallPath));
if (toolsInfo.isStillInstalled())
{
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + name);
}
}
}
return Success();
}
} // namespace r_util
} // namespace core
<commit_msg>Rtools binding for R 3.0.0<commit_after>/*
* RToolsInfo.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RToolsInfo.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Log.hpp>
#include <core/StringUtils.hpp>
#include <core/system/RegistryKey.hpp>
#ifndef KEY_WOW64_32KEY
#define KEY_WOW64_32KEY 0x0200
#endif
namespace core {
namespace r_util {
namespace {
} // anonymous namespace
RToolsInfo::RToolsInfo(const std::string& name, const FilePath& installPath)
: name_(name), installPath_(installPath)
{
std::string versionMin, versionMax;
std::vector<std::string> relativePathEntries;
if (name == "2.11")
{
versionMin = "2.10.0";
versionMax = "2.11.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
}
else if (name == "2.12")
{
versionMin = "2.12.0";
versionMax = "2.12.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("perl/bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.13")
{
versionMin = "2.13.0";
versionMax = "2.13.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.14")
{
versionMin = "2.13.0";
versionMax = "2.14.2";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("MinGW/bin");
relativePathEntries.push_back("MinGW64/bin");
}
else if (name == "2.15")
{
versionMin = "2.14.2";
versionMax = "2.15.1";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
}
else if (name == "2.16")
{
versionMin = "2.15.2";
versionMax = "3.0.0";
relativePathEntries.push_back("bin");
relativePathEntries.push_back("gcc-4.6.3/bin");
}
// build version predicate and path list if we can
if (!versionMin.empty())
{
boost::format fmt("getRversion() >= \"%1%\" && getRversion() <= \"%2%\"");
versionPredicate_ = boost::str(fmt % versionMin % versionMax);
BOOST_FOREACH(const std::string& relativePath, relativePathEntries)
{
pathEntries_.push_back(installPath_.childPath(relativePath));
}
}
}
std::ostream& operator<<(std::ostream& os, const RToolsInfo& info)
{
os << "Rtools " << info.name() << std::endl;
os << info.versionPredicate() << std::endl;
BOOST_FOREACH(const FilePath& pathEntry, info.pathEntries())
{
os << pathEntry << std::endl;
}
return os;
}
Error scanRegistryForRTools(std::vector<RToolsInfo>* pRTools)
{
core::system::RegistryKey regKey;
Error error = regKey.open(HKEY_LOCAL_MACHINE,
"Software\\R-core\\Rtools",
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
if (error.code() != boost::system::errc::no_such_file_or_directory)
return error;
else
return Success();
}
std::vector<std::string> keys = regKey.keyNames();
for (int i = 0; i < keys.size(); i++)
{
std::string name = keys.at(i);
core::system::RegistryKey verKey;
error = verKey.open(regKey.handle(),
name,
KEY_READ | KEY_WOW64_32KEY);
if (error)
{
LOG_ERROR(error);
continue;
}
std::string installPath = verKey.getStringValue("InstallPath", "");
if (!installPath.empty())
{
std::string utf8InstallPath = string_utils::systemToUtf8(installPath);
RToolsInfo toolsInfo(name, FilePath(utf8InstallPath));
if (toolsInfo.isStillInstalled())
{
if (toolsInfo.isRecognized())
pRTools->push_back(toolsInfo);
else
LOG_WARNING_MESSAGE("Unknown Rtools version: " + name);
}
}
}
return Success();
}
} // namespace r_util
} // namespace core
<|endoftext|> |
<commit_before>
#include <iostream>
#include "Timer.h"
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
using namespace std;
int main(int argc, char* argv[])
{
bool all= false;
if(argc <3)
{
cerr << "not enough arguments" << endl;
return 0;
}
else if(argc ==4)
{
all = true;
}
string path;
string tmp;
struct stat buf;
int file1;
int file2;
if(all && argv[1][0] == '-'){
if(argv[1][1] != 'a'){
cerr << "Invalid flag" << endl;
return 0;
}
file1 = 2;
file2 = 3;
}
else if(all && argv[2][0] == '-'){
if(argv[2][1] != 'a'){
cerr << "Invalid lag" << endl;
return 0;
}
file1 = 1;
file2 = 3;
}
else if(all && argv[3][0] == '-'){
if(argv[3][1] != 'a'){
cerr << "Invalid flag" << endl;
return 0;
}
file1 = 1;
file2 = 2;
}
else{
file1 = 1;
file2 = 2;
}
if(argv[file1][0] != '.' && argv[file1][0] != '/' ){
path = argv[file1];
string tmp = "./";
path = tmp + path;
if(stat(path.c_str(), &buf) == -1){
perror("stat");
exit(0);
}
if(S_ISDIR(buf.st_mode)){
cerr << "Input file is dir" << endl;
exit(0);
}
}
else{
if(stat(argv[file1], &buf)){
perror("stat");
exit(0);
}
if(S_ISDIR(buf.st_mode)){
cerr << "Input files if dir" << endl;
exit(0);
}
}
if(ifstream(argv[file2])){
cerr << "Output file already exists" << endl;
return 0;
}
else{
ofstream tmp(argv[file2]);
if(!tmp.good()){
cerr << "Unable to open file" << endl;
return 0;
}
tmp.close();
}
if(argv[file2][0] != '.' && argv[file2][0] != '/'){
path = argv[file2];
tmp = "./";
path = tmp + path;
if(stat(path.c_str(), &buf) == -1){
perror("stat");
exit(0);
}
if(S_ISDIR(buf.st_mode)){
cerr << "Input file is dir" << endl;
exit(0);
}
}
else{
if(stat(argv[file2], &buf) == -1){
perror("stat");
exit(0);
}
if(S_ISDIR(buf.st_mode)){
cerr << "Input file is dir" << endl;
exit(0);
}
}
if(all)
{
Timer t;
double eTime;
t.start();
ifstream inpoo(argv[1]);
ofstream outpoo(argv[2]);
if(!inpoo.good()|| !outpoo.good())
{
cerr << "Error: No file" << endl;
return 0;
}
while(inpoo.good())
{
char c = inpoo.get();
if(inpoo.good())
{
outpoo.put(c);
}
}
cout << "Method 1" << endl;
t.elapsedWallclockTime(eTime);
cout << "Wall clock time: " << eTime << endl;
t.elapsedUserTime(eTime);
cout << "User time: " << eTime << endl;
t.elapsedSystemTime(eTime);
cout << "System time: " << eTime << endl;
inpoo.close();
outpoo.close();
}
//next
if(all)
{
Timer t;
double eTime;
t.start();
int in = open(argv[file1], O_RDONLY);
int out = open(argv[file2], O_WRONLY);
char buf;
int n;
if(out == -1)
{
ofstream create(argv[file2]);
create.close();
out = open(argv[file2], O_WRONLY);
}
while((n = read(in, &buf, 1)))
{
int w = write(out, &buf, 1);
if(w == -1)
{
perror("write error");
return 0;
}
}
if (n == -1)
{
perror("woops");
return 0;
}
close(in);
close(out);
cout << "Method 2" << endl;
t.elapsedWallclockTime(eTime);
cout << "Wall clock time: " << eTime << endl;
t.elapsedUserTime(eTime);
cout << "User time: " << eTime << endl;
t.elapsedSystemTime(eTime);
cout << "System time: " << eTime << endl;
}
//next
if(all)
{
Timer t;
double eTime;
t.start();
int in = open(argv[file1], O_RDONLY);
if(in == -1){
perror("open");
return 0;
}
int out = open(argv[file2], O_WRONLY);
if(out == -1)
{
ofstream create(argv[file2]);
create.close();
out = open(argv[file2], O_WRONLY);
}
char* buf = new char[BUFSIZ];
int n = read(in, buf, BUFSIZ);
if (n == -1)
{
perror("erorr");
return 0;
}
int w = write(out, buf, BUFSIZ);
if(w == -1)
{
perror("error");
return 0;
}
delete [] buf;
cout << "Method 3" << endl;
t.elapsedWallclockTime(eTime);
cout << "Wall clock time: " << eTime << endl;
t.elapsedUserTime(eTime);
cout << "User time: " << eTime << endl;
t.elapsedSystemTime(eTime);
cout << "System time: " << eTime << endl;
close(in);
close(out);
}
if(!all){
Timer t;
double eTime;
t.start();
int in = open(argv[file1], O_RDONLY);
if(in == -1){
perror("open");
return 0;
}
int out = open(argv[file2], O_WRONLY);
if(out == -1)
{
ofstream create(argv[file2]);
create.close();
out = open(argv[file2], O_WRONLY);
}
char* buf = new char[BUFSIZ];
int n = read(in, buf, BUFSIZ);
if (n == -1)
{
perror("erorr");
return 0;
}
int w = write(out, buf, BUFSIZ);
if(w == -1)
{
perror("error");
return 0;
}
delete [] buf;
cout << "Method 3" << endl;
t.elapsedWallclockTime(eTime);
cout << eTime << endl;
t.elapsedUserTime(eTime);
cout << eTime << endl;
t.elapsedSystemTime(eTime);
cout << eTime << endl;
close(in);
close(out);
}
return 0;
}
<commit_msg>removing redundant files<commit_after><|endoftext|> |
<commit_before>// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Lab_1.h"
#include "Lab_1Character.h"
#include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h"
#include "Runtime/Engine/Classes/Components/DecalComponent.h"
#include "HouseActor.h"
ALab_1Character::ALab_1Character()
{
// Set size for player capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// Don't rotate character to camera direction
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction
GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f);
GetCharacterMovement()->bConstrainToPlane = true;
GetCharacterMovement()->bSnapToPlaneAtStart = true;
// Create collection sphere and set it's default radius.
DeliverySphere = CreateDefaultSubobject<USphereComponent>(TEXT("DeliverySphere"));
DeliverySphere->SetupAttachment(RootComponent);
DeliverySphere->SetSphereRadius(100.0f);
// Create a camera boom...
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does
CameraBoom->TargetArmLength = 2000.f;
CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f);
CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level
// Create a camera...
TopDownCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera"));
TopDownCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);
TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Activate ticking in order to update the cursor every frame.
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
PizzaCapacity = 1;
PizzaAmount = 0;
}
void ALab_1Character::Tick(float DeltaSeconds)
{
}
int ALab_1Character::GetPizzaAmount() const
{
return PizzaAmount;
}
int ALab_1Character::GetPizzaCapacity() const
{
return PizzaCapacity;
}
bool ALab_1Character::TryGrabPizza()
{
if (PizzaAmount >= PizzaCapacity) {
return false;
}
++PizzaAmount;
return true;
}
bool ALab_1Character::TryDeliverPizza(AHouseActor* HouseActor)
{
if (PizzaAmount == 0) {
UE_LOG(LogTemp, Warning, TEXT("Not enought pizza!"));
return false;
}
if (!HouseActor->WaitsPizzaDelivery()) {
UE_LOG(LogTemp, Warning, TEXT("House doesn't wait for delivery!"));
return false;
}
// Check overlapping.
{
TArray<AActor*> OverlappingActors;
DeliverySphere->GetOverlappingActors(OverlappingActors);
if (OverlappingActors.Find(HouseActor) == INDEX_NONE) {
UE_LOG(LogTemp, Warning, TEXT("Character is not in range for delivery"));
return false;
}
}
--PizzaAmount;
HouseActor->OnPizzaDelivered();
return true;
}
<commit_msg>[Lab_1] Move camera further<commit_after>// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Lab_1.h"
#include "Lab_1Character.h"
#include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h"
#include "Runtime/Engine/Classes/Components/DecalComponent.h"
#include "HouseActor.h"
ALab_1Character::ALab_1Character()
{
// Set size for player capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// Don't rotate character to camera direction
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction
GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f);
GetCharacterMovement()->bConstrainToPlane = true;
GetCharacterMovement()->bSnapToPlaneAtStart = true;
// Create collection sphere and set it's default radius.
DeliverySphere = CreateDefaultSubobject<USphereComponent>(TEXT("DeliverySphere"));
DeliverySphere->SetupAttachment(RootComponent);
DeliverySphere->SetSphereRadius(100.0f);
// Create a camera boom...
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does
CameraBoom->TargetArmLength = 2400.f;
CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f);
CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level
// Create a camera...
TopDownCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera"));
TopDownCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);
TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Activate ticking in order to update the cursor every frame.
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
PizzaCapacity = 1;
PizzaAmount = 0;
}
void ALab_1Character::Tick(float DeltaSeconds)
{
}
int ALab_1Character::GetPizzaAmount() const
{
return PizzaAmount;
}
int ALab_1Character::GetPizzaCapacity() const
{
return PizzaCapacity;
}
bool ALab_1Character::TryGrabPizza()
{
if (PizzaAmount >= PizzaCapacity) {
return false;
}
++PizzaAmount;
return true;
}
bool ALab_1Character::TryDeliverPizza(AHouseActor* HouseActor)
{
if (PizzaAmount == 0) {
UE_LOG(LogTemp, Warning, TEXT("Not enought pizza!"));
return false;
}
if (!HouseActor->WaitsPizzaDelivery()) {
UE_LOG(LogTemp, Warning, TEXT("House doesn't wait for delivery!"));
return false;
}
// Check overlapping.
{
TArray<AActor*> OverlappingActors;
DeliverySphere->GetOverlappingActors(OverlappingActors);
if (OverlappingActors.Find(HouseActor) == INDEX_NONE) {
UE_LOG(LogTemp, Warning, TEXT("Character is not in range for delivery"));
return false;
}
}
--PizzaAmount;
HouseActor->OnPizzaDelivered();
return true;
}
<|endoftext|> |
<commit_before>#include "a_filter.h"
#include "a_system.h"
#include "m_trig.h"
#include "u_misc.h"
namespace a {
///! filter
filter::~filter() {
// Empty
}
///! filterInstance
filterInstance::~filterInstance() {
// Empty
}
void filterInstance::setFilterParam(int, float) {
// Empty
}
void filterInstance::fadeFilterParam(int, float, float, float, float) {
// Rmpty
}
void filterInstance::oscFilterParam(int, float, float, float, float) {
// Empty
}
///! echoFilter
echoFilterInstance::echoFilterInstance(echoFilter *parent)
: m_parent(parent)
, m_offset(0)
{
}
void echoFilterInstance::filter(float *buffer, size_t samples, size_t channels, float sampleRate, float) {
if (m_buffer.empty()) {
const size_t length = m::ceil(m_parent->m_delay * sampleRate) * channels;
m_buffer.resize(length);
}
const size_t bufferLength = m_buffer.size() / channels;
const float decay = m_parent->m_decay;
for (size_t i = 0; i < samples; i++) {
for (size_t j = 0; j < channels; j++) {
const size_t c = j * bufferLength;
const size_t b = j * samples;
float sample = buffer[i + b] + m_buffer[m_offset + c] * decay;
m_buffer[m_offset + c] = sample;
buffer[i + b] = sample;
}
m_offset = (m_offset + 1) % bufferLength;
}
}
echoFilterInstance::~echoFilterInstance() {
// Empty
}
echoFilter::echoFilter()
: m_delay(1.0f)
, m_decay(0.5f)
{
}
void echoFilter::setParams(float delay, float decay) {
m_delay = delay;
m_decay = decay;
}
filterInstance *echoFilter::create() {
return new echoFilterInstance(this);
}
///! BQRFilterInstance
BQRFilterInstance::BQRFilterInstance(BQRFilter *parent)
: m_parent(parent)
, m_filterType(m_parent->m_filterType)
, m_sampleRate(m_parent->m_sampleRate)
, m_frequency(m_parent->m_frequency)
, m_resonance(m_parent->m_resonance)
, m_active(false)
{
calcParams();
}
void BQRFilterInstance::filter(float *buffer, size_t samples, size_t channels, float time, float) {
if (!m_active) return;
if (m_frequencyFader.m_active > 0) {
m_dirty = true;
m_frequency = m_frequencyFader(time);
}
if (m_resonanceFader.m_active > 0) {
m_dirty = true;
m_resonance = m_resonanceFader(time);
}
if (m_sampleRateFader.m_active > 0) {
m_dirty = true;
m_sampleRate = m_sampleRateFader(time);
}
if (m_dirty)
calcParams();
for (size_t s = 0, c = 0; s < channels; s++) {
for (size_t i = 0; i < samples; i += 2, c++) {
// filter the inputs
float x = buffer[c];
m_y2[s] = (m_a.x * x) + (m_a.y * m_x1[s]) + (m_a.z * m_x2[s])
- (m_b.x * m_y1[s]) - (m_b.y * m_y2[s]);
buffer[c++] = m_y2[s];
// permute filter ops to reduce movement
m_x2[s] = buffer[c];
m_y1[s] = (m_a.y * x) + (m_a.x * m_x2[s]) + (m_a.z * m_x1[s])
- (m_b.x * m_y2[s]) - (m_b.y * m_y1[s]);
buffer[c] = m_y1[s];
// move it a little
m_x1[s] = m_x2[s];
m_x2[s] = x;
}
// apply a very small impulse to prevent underflow
m_y1[s] += 1.0e-26f;
}
}
void BQRFilterInstance::setFilterParam(int attrib, float value) {
switch (attrib) {
case BQRFilter::kFrequency:
m_dirty = true;
m_frequencyFader.m_active = 0;
m_frequency = value;
break;
case BQRFilter::kSampleRate:
m_dirty = true;
m_sampleRateFader.m_active = 0;
m_sampleRate = value;
break;
case BQRFilter::kResonance:
m_dirty = true;
m_resonanceFader.m_active = 0;
m_resonance = value;
break;
}
}
void BQRFilterInstance::fadeFilterParam(int attrib, float from, float to, float time, float startTime) {
if (from == to || time <= 0.0f)
return;
switch (attrib) {
case BQRFilter::kFrequency:
m_frequencyFader.lerp(from, to, time, startTime);
break;
case BQRFilter::kSampleRate:
m_sampleRateFader.lerp(from, to, time, startTime);
break;
case BQRFilter::kResonance:
m_sampleRateFader.lerp(from, to, time, startTime);
break;
}
}
void BQRFilterInstance::oscFilterParam(int attrib, float from, float to, float time, float startTime) {
if (from == to || time <= 0.0f)
return;
switch (attrib) {
case BQRFilter::kFrequency:
m_frequencyFader.lfo(from, to, time, startTime);
break;
case BQRFilter::kSampleRate:
m_sampleRateFader.lfo(from, to, time, startTime);
break;
case BQRFilter::kResonance:
m_resonanceFader.lfo(from, to, time, startTime);
break;
}
}
BQRFilterInstance::~BQRFilterInstance() {
// Empty
}
void BQRFilterInstance::calcParams() {
const m::vec2 omega = m::sincos((2.0f * m::kPi * m_frequency) / m_sampleRate);
const float alpha = omega.x / (2.0f * m_resonance);
const float scalar = 1.0f / (1.0f + alpha);
switch (m_filterType) {
case BQRFilter::kNone:
m_active = false;
break;
case BQRFilter::kLowPass:
m_a.x = 0.5f * (1.0f - omega.y) * scalar;
m_a.y = (1.0f - omega.y) * scalar;
m_a.z = m_a.x;
m_b.x = -2.0f * omega.y * scalar;
m_b.y = (1.0f - alpha) * scalar;
m_active = true;
break;
case BQRFilter::kHighPass:
m_a.x = 0.5f * (1.0f + omega.y) * scalar;
m_a.y = -(1.0f + omega.y) * scalar;
m_a.z = m_a.x;
m_b.x = -2.0f * omega.y * scalar;
m_b.y = (1.0f - alpha) * scalar;
m_active = true;
break;
case BQRFilter::kBandPass:
m_a.x = alpha * scalar;
m_a.y = 0.0f;
m_a.z = -m_a.x;
m_b.x = -2.0f * omega.y * scalar;
m_b.y = (1.0f - alpha) * scalar;
m_active = true;
break;
}
}
BQRFilter::BQRFilter()
{
// Empty
}
void BQRFilter::setParams(int type, float sampleRate, float frequency, float resonance) {
m_filterType = type;
m_sampleRate = sampleRate;
m_frequency = frequency;
m_resonance = resonance;
}
BQRFilter::~BQRFilter() {
// Empty
}
BQRFilterInstance *BQRFilter::create() {
return new BQRFilterInstance(this);
}
///! DCRemovalFilterInstance
DCRemovalFilterInstance::DCRemovalFilterInstance(DCRemovalFilter *parent)
: m_offset(0)
, m_parent(parent)
{
}
void DCRemovalFilterInstance::filter(float *buffer, size_t samples, size_t channels, float sampleRate, float) {
if (m_buffer.empty()) {
m_buffer.resize(size_t(m::ceil(m_parent->m_length * sampleRate)) * channels);
m_totals.resize(channels);
}
size_t bufferLength = m_buffer.size() / channels;
for (size_t i = 0; i < samples; i++) {
for (size_t j = 0; j < channels; j++) {
const int c = j * bufferLength;
const int b = j * samples;
float n = buffer[i + b];
m_totals[j] -= m_buffer[m_offset + c];
m_totals[j] += n;
m_buffer[m_offset + c] = n;
n -= m_totals[j] / bufferLength;
buffer[i + b] += (n - buffer[i + b]) * m_parent->m_length;
}
m_offset = (m_offset + 1) % bufferLength;
}
}
DCRemovalFilterInstance::~DCRemovalFilterInstance() {
// Empty
}
DCRemovalFilter::DCRemovalFilter()
: m_length(0.1f)
{
}
void DCRemovalFilter::setParams(float length) {
m_length = length;
}
filterInstance *DCRemovalFilter::create() {
return new DCRemovalFilterInstance(this);
}
}
<commit_msg>Uninitialized dirty field of BQR filters during initialization results in situations where params are not updated<commit_after>#include "a_filter.h"
#include "a_system.h"
#include "m_trig.h"
#include "u_misc.h"
namespace a {
///! filter
filter::~filter() {
// Empty
}
///! filterInstance
filterInstance::~filterInstance() {
// Empty
}
void filterInstance::setFilterParam(int, float) {
// Empty
}
void filterInstance::fadeFilterParam(int, float, float, float, float) {
// Rmpty
}
void filterInstance::oscFilterParam(int, float, float, float, float) {
// Empty
}
///! echoFilter
echoFilterInstance::echoFilterInstance(echoFilter *parent)
: m_parent(parent)
, m_offset(0)
{
}
void echoFilterInstance::filter(float *buffer, size_t samples, size_t channels, float sampleRate, float) {
if (m_buffer.empty()) {
const size_t length = m::ceil(m_parent->m_delay * sampleRate) * channels;
m_buffer.resize(length);
}
const size_t bufferLength = m_buffer.size() / channels;
const float decay = m_parent->m_decay;
for (size_t i = 0; i < samples; i++) {
for (size_t j = 0; j < channels; j++) {
const size_t c = j * bufferLength;
const size_t b = j * samples;
float sample = buffer[i + b] + m_buffer[m_offset + c] * decay;
m_buffer[m_offset + c] = sample;
buffer[i + b] = sample;
}
m_offset = (m_offset + 1) % bufferLength;
}
}
echoFilterInstance::~echoFilterInstance() {
// Empty
}
echoFilter::echoFilter()
: m_delay(1.0f)
, m_decay(0.5f)
{
}
void echoFilter::setParams(float delay, float decay) {
m_delay = delay;
m_decay = decay;
}
filterInstance *echoFilter::create() {
return new echoFilterInstance(this);
}
///! BQRFilterInstance
BQRFilterInstance::BQRFilterInstance(BQRFilter *parent)
: m_parent(parent)
, m_filterType(m_parent->m_filterType)
, m_sampleRate(m_parent->m_sampleRate)
, m_frequency(m_parent->m_frequency)
, m_resonance(m_parent->m_resonance)
, m_active(false)
, m_dirty(false)
{
calcParams();
}
void BQRFilterInstance::filter(float *buffer, size_t samples, size_t channels, float time, float) {
if (!m_active) return;
if (m_frequencyFader.m_active > 0) {
m_dirty = true;
m_frequency = m_frequencyFader(time);
}
if (m_resonanceFader.m_active > 0) {
m_dirty = true;
m_resonance = m_resonanceFader(time);
}
if (m_sampleRateFader.m_active > 0) {
m_dirty = true;
m_sampleRate = m_sampleRateFader(time);
}
if (m_dirty)
calcParams();
for (size_t s = 0, c = 0; s < channels; s++) {
for (size_t i = 0; i < samples; i += 2, c++) {
// filter the inputs
float x = buffer[c];
m_y2[s] = (m_a.x * x) + (m_a.y * m_x1[s]) + (m_a.z * m_x2[s])
- (m_b.x * m_y1[s]) - (m_b.y * m_y2[s]);
buffer[c++] = m_y2[s];
// permute filter ops to reduce movement
m_x2[s] = buffer[c];
m_y1[s] = (m_a.y * x) + (m_a.x * m_x2[s]) + (m_a.z * m_x1[s])
- (m_b.x * m_y2[s]) - (m_b.y * m_y1[s]);
buffer[c] = m_y1[s];
// move it a little
m_x1[s] = m_x2[s];
m_x2[s] = x;
}
// apply a very small impulse to prevent underflow
m_y1[s] += 1.0e-26f;
}
}
void BQRFilterInstance::setFilterParam(int attrib, float value) {
switch (attrib) {
case BQRFilter::kFrequency:
m_dirty = true;
m_frequencyFader.m_active = 0;
m_frequency = value;
break;
case BQRFilter::kSampleRate:
m_dirty = true;
m_sampleRateFader.m_active = 0;
m_sampleRate = value;
break;
case BQRFilter::kResonance:
m_dirty = true;
m_resonanceFader.m_active = 0;
m_resonance = value;
break;
}
}
void BQRFilterInstance::fadeFilterParam(int attrib, float from, float to, float time, float startTime) {
if (from == to || time <= 0.0f)
return;
switch (attrib) {
case BQRFilter::kFrequency:
m_frequencyFader.lerp(from, to, time, startTime);
break;
case BQRFilter::kSampleRate:
m_sampleRateFader.lerp(from, to, time, startTime);
break;
case BQRFilter::kResonance:
m_sampleRateFader.lerp(from, to, time, startTime);
break;
}
}
void BQRFilterInstance::oscFilterParam(int attrib, float from, float to, float time, float startTime) {
if (from == to || time <= 0.0f)
return;
switch (attrib) {
case BQRFilter::kFrequency:
m_frequencyFader.lfo(from, to, time, startTime);
break;
case BQRFilter::kSampleRate:
m_sampleRateFader.lfo(from, to, time, startTime);
break;
case BQRFilter::kResonance:
m_resonanceFader.lfo(from, to, time, startTime);
break;
}
}
BQRFilterInstance::~BQRFilterInstance() {
// Empty
}
void BQRFilterInstance::calcParams() {
const m::vec2 omega = m::sincos((2.0f * m::kPi * m_frequency) / m_sampleRate);
const float alpha = omega.x / (2.0f * m_resonance);
const float scalar = 1.0f / (1.0f + alpha);
switch (m_filterType) {
case BQRFilter::kNone:
m_active = false;
break;
case BQRFilter::kLowPass:
m_a.x = 0.5f * (1.0f - omega.y) * scalar;
m_a.y = (1.0f - omega.y) * scalar;
m_a.z = m_a.x;
m_b.x = -2.0f * omega.y * scalar;
m_b.y = (1.0f - alpha) * scalar;
m_active = true;
break;
case BQRFilter::kHighPass:
m_a.x = 0.5f * (1.0f + omega.y) * scalar;
m_a.y = -(1.0f + omega.y) * scalar;
m_a.z = m_a.x;
m_b.x = -2.0f * omega.y * scalar;
m_b.y = (1.0f - alpha) * scalar;
m_active = true;
break;
case BQRFilter::kBandPass:
m_a.x = alpha * scalar;
m_a.y = 0.0f;
m_a.z = -m_a.x;
m_b.x = -2.0f * omega.y * scalar;
m_b.y = (1.0f - alpha) * scalar;
m_active = true;
break;
}
}
BQRFilter::BQRFilter()
{
// Empty
}
void BQRFilter::setParams(int type, float sampleRate, float frequency, float resonance) {
m_filterType = type;
m_sampleRate = sampleRate;
m_frequency = frequency;
m_resonance = resonance;
}
BQRFilter::~BQRFilter() {
// Empty
}
BQRFilterInstance *BQRFilter::create() {
return new BQRFilterInstance(this);
}
///! DCRemovalFilterInstance
DCRemovalFilterInstance::DCRemovalFilterInstance(DCRemovalFilter *parent)
: m_offset(0)
, m_parent(parent)
{
}
void DCRemovalFilterInstance::filter(float *buffer, size_t samples, size_t channels, float sampleRate, float) {
if (m_buffer.empty()) {
m_buffer.resize(size_t(m::ceil(m_parent->m_length * sampleRate)) * channels);
m_totals.resize(channels);
}
size_t bufferLength = m_buffer.size() / channels;
for (size_t i = 0; i < samples; i++) {
for (size_t j = 0; j < channels; j++) {
const int c = j * bufferLength;
const int b = j * samples;
float n = buffer[i + b];
m_totals[j] -= m_buffer[m_offset + c];
m_totals[j] += n;
m_buffer[m_offset + c] = n;
n -= m_totals[j] / bufferLength;
buffer[i + b] += (n - buffer[i + b]) * m_parent->m_length;
}
m_offset = (m_offset + 1) % bufferLength;
}
}
DCRemovalFilterInstance::~DCRemovalFilterInstance() {
// Empty
}
DCRemovalFilter::DCRemovalFilter()
: m_length(0.1f)
{
}
void DCRemovalFilter::setParams(float length) {
m_length = length;
}
filterInstance *DCRemovalFilter::create() {
return new DCRemovalFilterInstance(this);
}
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iterator>
#include <string>
#include "caffe2/core/blob_serialization.h"
#include "caffe2/core/init.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/share/contrib/observers/observer_config.h"
#include "caffe2/utils/proto_utils.h"
#include "caffe2/utils/string_utils.h"
CAFFE2_DEFINE_string(
init_net,
"",
"The given net to initialize any parameters.");
CAFFE2_DEFINE_string(
input,
"",
"Input that is needed for running the network. If "
"multiple input needed, use comma separated string.");
CAFFE2_DEFINE_string(
input_dims,
"",
"Alternate to input_files, if all inputs are simple "
"float TensorCPUs, specify the dimension using comma "
"separated numbers. If multiple input needed, use "
"semicolon to separate the dimension of different "
"tensors.");
CAFFE2_DEFINE_string(
input_file,
"",
"Input file that contain the serialized protobuf for "
"the input blobs. If multiple input needed, use comma "
"separated string. Must have the same number of items "
"as input does.");
CAFFE2_DEFINE_int(iter, 10, "The number of iterations to run.");
CAFFE2_DEFINE_string(net, "", "The given net to benchmark.");
CAFFE2_DEFINE_string(
output,
"",
"Output that should be dumped after the execution "
"finishes. If multiple outputs are needed, use comma "
"separated string. If you want to dump everything, pass "
"'*' as the output value.");
CAFFE2_DEFINE_string(
output_folder,
"",
"The folder that the output should be written to. This "
"folder must already exist in the file system.");
CAFFE2_DEFINE_bool(
run_individual,
false,
"Whether to benchmark individual operators.");
CAFFE2_DEFINE_bool(
text_output,
false,
"Whether to write out output in text format for regression purpose.");
CAFFE2_DEFINE_int(warmup, 0, "The number of iterations to warm up.");
using std::string;
using std::unique_ptr;
using std::vector;
static void writeTextOutput(
caffe2::TensorCPU* tensor,
const string& output_prefix,
const string& name) {
string output_name = output_prefix + "/" + name + ".txt";
caffe2::TensorSerializer<caffe2::CPUContext> ser;
caffe2::BlobProto blob_proto;
ser.Serialize(
*tensor, output_name, blob_proto.mutable_tensor(), 0, tensor->size());
blob_proto.set_name(output_name);
blob_proto.set_type("Tensor");
CAFFE_ENFORCE(blob_proto.has_tensor());
caffe2::TensorProto tensor_proto = blob_proto.tensor();
vector<float> data;
switch (tensor_proto.data_type()) {
case caffe2::TensorProto::FLOAT: {
std::copy(
tensor_proto.float_data().begin(),
tensor_proto.float_data().end(),
std::back_inserter(data));
break;
}
case caffe2::TensorProto::INT32: {
std::copy(
tensor_proto.int32_data().begin(),
tensor_proto.int32_data().end(),
std::back_inserter(data));
break;
}
default:
CAFFE_THROW("Unimplemented Blob type.");
}
std::ofstream output_file(output_name);
std::ostream_iterator<float> output_iterator(output_file, "\n");
std::copy(data.begin(), data.end(), output_iterator);
}
int main(int argc, char** argv) {
caffe2::GlobalInit(&argc, &argv);
caffe2::ShowLogInfoToStderr();
unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace());
// Run initialization network.
caffe2::NetDef net_def;
CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_init_net, &net_def));
CAFFE_ENFORCE(workspace->RunNetOnce(net_def));
// Load input.
if (caffe2::FLAGS_input.size()) {
vector<string> input_names = caffe2::split(',', caffe2::FLAGS_input);
if (caffe2::FLAGS_input_file.size()) {
vector<string> input_files = caffe2::split(',', caffe2::FLAGS_input_file);
CAFFE_ENFORCE_EQ(
input_names.size(),
input_files.size(),
"Input name and file should have the same number.");
for (int i = 0; i < input_names.size(); ++i) {
caffe2::BlobProto blob_proto;
CAFFE_ENFORCE(caffe2::ReadProtoFromFile(input_files[i], &blob_proto));
workspace->CreateBlob(input_names[i])->Deserialize(blob_proto);
}
} else if (caffe2::FLAGS_input_dims.size()) {
vector<string> input_dims_list =
caffe2::split(';', caffe2::FLAGS_input_dims);
CAFFE_ENFORCE_EQ(
input_names.size(),
input_dims_list.size(),
"Input name and dims should have the same number of items.");
for (int i = 0; i < input_names.size(); ++i) {
vector<string> input_dims_str = caffe2::split(',', input_dims_list[i]);
vector<int> input_dims;
for (const string& s : input_dims_str) {
input_dims.push_back(caffe2::stoi(s));
}
caffe2::TensorCPU* tensor =
workspace->GetBlob(input_names[i])->GetMutable<caffe2::TensorCPU>();
tensor->Resize(input_dims);
tensor->mutable_data<float>();
}
} else {
CAFFE_THROW(
"You requested input tensors, but neither input_file nor "
"input_dims is set.");
}
}
// Run main network.
CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_net, &net_def));
caffe2::NetBase* net = workspace->CreateNet(net_def);
CHECK_NOTNULL(net);
LOG(INFO) << "Starting benchmark.";
caffe2::ObserverConfig::initSampleRate(
1, 1, 1, caffe2::FLAGS_run_individual, caffe2::FLAGS_warmup);
LOG(INFO) << "Running warmup runs.";
for (int i = 0; i < caffe2::FLAGS_warmup; ++i) {
CAFFE_ENFORCE(net->Run(), "Warmup run ", i, " has failed.");
}
LOG(INFO) << "Main runs.";
CAFFE_ENFORCE(
caffe2::FLAGS_iter >= 0,
"Number of main runs should be non negative, provided ",
caffe2::FLAGS_iter,
".");
for (int i = 0; i < caffe2::FLAGS_iter; ++i) {
caffe2::ObserverConfig::initSampleRate(1, 1, 1, 0, caffe2::FLAGS_warmup);
CAFFE_ENFORCE(net->Run(), "Main run ", i, " has failed.");
if (caffe2::FLAGS_run_individual) {
caffe2::ObserverConfig::initSampleRate(1, 1, 1, 1, caffe2::FLAGS_warmup);
CAFFE_ENFORCE(net->Run(), "Main run ", i, " with operator has failed.");
}
}
string output_prefix = caffe2::FLAGS_output_folder.size()
? caffe2::FLAGS_output_folder + "/"
: "";
if (caffe2::FLAGS_output.size()) {
vector<string> output_names = caffe2::split(',', caffe2::FLAGS_output);
if (caffe2::FLAGS_output == "*") {
output_names = workspace->Blobs();
}
for (const string& name : output_names) {
CAFFE_ENFORCE(
workspace->HasBlob(name),
"You requested a non-existing blob: ",
name);
if (caffe2::FLAGS_text_output) {
auto blob = workspace->GetBlob(name)->GetMutable<caffe2::TensorCPU>();
writeTextOutput(blob, output_prefix, name);
} else {
string serialized = workspace->GetBlob(name)->Serialize(name);
string output_filename = output_prefix + name;
caffe2::WriteStringToFile(serialized, output_filename.c_str());
}
}
}
return 0;
}
<commit_msg>Caffe2_benchmark can benchmark multiple backend engines<commit_after>#include <fstream>
#include <iterator>
#include <string>
#include "caffe2/core/blob_serialization.h"
#include "caffe2/core/init.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/share/contrib/observers/observer_config.h"
#include "caffe2/utils/proto_utils.h"
#include "caffe2/utils/string_utils.h"
#if CAFFE2_MOBILE && (CAFFE2_ANDROID || CAFFE2_IOS)
#include "caffe2/mobile/contrib/opengl/core/rewrite_net.h"
#endif
CAFFE2_DEFINE_string(
backend,
"default",
"The backend to use when running the model. The allowed "
"backend choices are: default, nnpack, opengl");
CAFFE2_DEFINE_string(
init_net,
"",
"The given net to initialize any parameters.");
CAFFE2_DEFINE_string(
input,
"",
"Input that is needed for running the network. If "
"multiple input needed, use comma separated string.");
CAFFE2_DEFINE_string(
input_dims,
"",
"Alternate to input_files, if all inputs are simple "
"float TensorCPUs, specify the dimension using comma "
"separated numbers. If multiple input needed, use "
"semicolon to separate the dimension of different "
"tensors.");
CAFFE2_DEFINE_string(
input_file,
"",
"Input file that contain the serialized protobuf for "
"the input blobs. If multiple input needed, use comma "
"separated string. Must have the same number of items "
"as input does.");
CAFFE2_DEFINE_int(iter, 10, "The number of iterations to run.");
CAFFE2_DEFINE_string(net, "", "The given net to benchmark.");
CAFFE2_DEFINE_string(
output,
"",
"Output that should be dumped after the execution "
"finishes. If multiple outputs are needed, use comma "
"separated string. If you want to dump everything, pass "
"'*' as the output value.");
CAFFE2_DEFINE_string(
output_folder,
"",
"The folder that the output should be written to. This "
"folder must already exist in the file system.");
CAFFE2_DEFINE_bool(
run_individual,
false,
"Whether to benchmark individual operators.");
CAFFE2_DEFINE_bool(
text_output,
false,
"Whether to write out output in text format for regression purpose.");
CAFFE2_DEFINE_int(warmup, 0, "The number of iterations to warm up.");
using std::string;
using std::unique_ptr;
using std::vector;
static void writeTextOutput(
caffe2::TensorCPU* tensor,
const string& output_prefix,
const string& name) {
string output_name = output_prefix + "/" + name + ".txt";
caffe2::TensorSerializer<caffe2::CPUContext> ser;
caffe2::BlobProto blob_proto;
ser.Serialize(
*tensor, output_name, blob_proto.mutable_tensor(), 0, tensor->size());
blob_proto.set_name(output_name);
blob_proto.set_type("Tensor");
CAFFE_ENFORCE(blob_proto.has_tensor());
caffe2::TensorProto tensor_proto = blob_proto.tensor();
vector<float> data;
switch (tensor_proto.data_type()) {
case caffe2::TensorProto::FLOAT: {
std::copy(
tensor_proto.float_data().begin(),
tensor_proto.float_data().end(),
std::back_inserter(data));
break;
}
case caffe2::TensorProto::INT32: {
std::copy(
tensor_proto.int32_data().begin(),
tensor_proto.int32_data().end(),
std::back_inserter(data));
break;
}
default:
CAFFE_THROW("Unimplemented Blob type.");
}
std::ofstream output_file(output_name);
std::ostream_iterator<float> output_iterator(output_file, "\n");
std::copy(data.begin(), data.end(), output_iterator);
}
int main(int argc, char** argv) {
caffe2::GlobalInit(&argc, &argv);
caffe2::ShowLogInfoToStderr();
unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace());
// Run initialization network.
caffe2::NetDef init_net_def;
CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_init_net, &init_net_def));
CAFFE_ENFORCE(workspace->RunNetOnce(init_net_def));
// Load input.
if (caffe2::FLAGS_input.size()) {
vector<string> input_names = caffe2::split(',', caffe2::FLAGS_input);
if (caffe2::FLAGS_input_file.size()) {
vector<string> input_files = caffe2::split(',', caffe2::FLAGS_input_file);
CAFFE_ENFORCE_EQ(
input_names.size(),
input_files.size(),
"Input name and file should have the same number.");
for (int i = 0; i < input_names.size(); ++i) {
caffe2::BlobProto blob_proto;
CAFFE_ENFORCE(caffe2::ReadProtoFromFile(input_files[i], &blob_proto));
workspace->CreateBlob(input_names[i])->Deserialize(blob_proto);
}
} else if (caffe2::FLAGS_input_dims.size()) {
vector<string> input_dims_list =
caffe2::split(';', caffe2::FLAGS_input_dims);
CAFFE_ENFORCE_EQ(
input_names.size(),
input_dims_list.size(),
"Input name and dims should have the same number of items.");
for (int i = 0; i < input_names.size(); ++i) {
vector<string> input_dims_str = caffe2::split(',', input_dims_list[i]);
vector<int> input_dims;
for (const string& s : input_dims_str) {
input_dims.push_back(caffe2::stoi(s));
}
caffe2::TensorCPU* tensor =
workspace->GetBlob(input_names[i])->GetMutable<caffe2::TensorCPU>();
tensor->Resize(input_dims);
tensor->mutable_data<float>();
}
} else {
CAFFE_THROW(
"You requested input tensors, but neither input_file nor "
"input_dims is set.");
}
}
// Run main network.
caffe2::NetDef net_def;
CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_net, &net_def));
if (caffe2::FLAGS_backend == "opengl") {
#if CAFFE2_MOBILE && (CAFFE2_ANDROID || CAFFE2_IOS)
caffe2::NetDef opengl_net_def;
if (caffe2::tryConvertToOpenGL(init_net_def, net_def, &opengl_net_def)) {
net_def = opengl_net_def;
if (caffe2::FLAGS_run_individual) {
caffe2::FLAGS_run_individual = false;
LOG(INFO)
<< "OpenGL implementation does not support individual operator delay. Run net delay only";
}
} else {
LOG(ERROR)
<< "Net cannot be converted to OpenGL format, use original model instead";
}
#else
LOG(ERROR) << "OpenGL build can only be used in mobile platform";
#endif
} else if (caffe2::FLAGS_backend == "nnpack") {
for (int i = 0; i < net_def.op_size(); i++) {
caffe2::OperatorDef* op_def = net_def.mutable_op(i);
op_def->set_engine("NNPACK");
}
} else {
CAFFE_ENFORCE(
caffe2::FLAGS_backend == "default", "Backend is not supported");
}
caffe2::NetBase* net = workspace->CreateNet(net_def);
CHECK_NOTNULL(net);
LOG(INFO) << "Starting benchmark.";
caffe2::ObserverConfig::initSampleRate(
1, 1, 1, caffe2::FLAGS_run_individual, caffe2::FLAGS_warmup);
LOG(INFO) << "Running warmup runs.";
for (int i = 0; i < caffe2::FLAGS_warmup; ++i) {
CAFFE_ENFORCE(net->Run(), "Warmup run ", i, " has failed.");
}
LOG(INFO) << "Main runs.";
CAFFE_ENFORCE(
caffe2::FLAGS_iter >= 0,
"Number of main runs should be non negative, provided ",
caffe2::FLAGS_iter,
".");
for (int i = 0; i < caffe2::FLAGS_iter; ++i) {
caffe2::ObserverConfig::initSampleRate(1, 1, 1, 0, caffe2::FLAGS_warmup);
CAFFE_ENFORCE(net->Run(), "Main run ", i, " has failed.");
if (caffe2::FLAGS_run_individual) {
caffe2::ObserverConfig::initSampleRate(1, 1, 1, 1, caffe2::FLAGS_warmup);
CAFFE_ENFORCE(net->Run(), "Main run ", i, " with operator has failed.");
}
}
string output_prefix = caffe2::FLAGS_output_folder.size()
? caffe2::FLAGS_output_folder + "/"
: "";
if (caffe2::FLAGS_output.size()) {
vector<string> output_names = caffe2::split(',', caffe2::FLAGS_output);
if (caffe2::FLAGS_output == "*") {
output_names = workspace->Blobs();
}
for (const string& name : output_names) {
CAFFE_ENFORCE(
workspace->HasBlob(name),
"You requested a non-existing blob: ",
name);
if (caffe2::FLAGS_text_output) {
auto blob = workspace->GetBlob(name)->GetMutable<caffe2::TensorCPU>();
writeTextOutput(blob, output_prefix, name);
} else {
string serialized = workspace->GetBlob(name)->Serialize(name);
string output_filename = output_prefix + name;
caffe2::WriteStringToFile(serialized, output_filename.c_str());
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Coherent Theory LLC
*
* This program 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, 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 Library 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 "session.h"
#include "session_p.h"
#include "assetjob.h"
#include "assetoperations.h"
#include "channelsjob.h"
#include "changelanguagejob.h"
#include "createballotjob.h"
#include "installjob.h"
#include "listballotsjob.h"
#include "participantinfojob.h"
#include "registerjob.h"
#include "resetpasswordjob.h"
#include "searchjob.h"
#include "signonjob.h"
#include <QNetworkAccessManager>
#include <QDebug>
#include <QDir>
using namespace Bodega;
Session::Private::Private(Session *parent)
: q(parent),
points(0),
authenticated(false),
netManager(new QNetworkAccessManager(q))
{
}
void Session::Private::setPoints(int p)
{
if (p > -1) {
points = p;
emit q->pointsChanged(points);
}
}
void Session::Private::signOnFinished(SignOnJob *job)
{
imageUrls = job->imageUrls();
}
void Session::Private::jobFinished(NetworkJob *job)
{
if (authenticated && !job->authSuccess()) {
setPoints(0);
emit q->disconnected();
}
if (authenticated != job->authSuccess()) {
authenticated = !authenticated;
emit q->authenticated(authenticated);
}
if (job->authSuccess()) {
setPoints(job->points());
}
job->deleteLater();
}
QNetworkReply *Session::Private::get(const QUrl &url)
{
QNetworkRequest request;
request.setRawHeader("User-Agent", "Bodega 0.1");
request.setUrl(url);
return netManager->get(request);
}
Session::Session(QObject *parent)
: QObject(parent),
d(new Private(this))
{
}
Session::~Session()
{
delete d;
}
QUrl Session::baseUrl() const
{
return d->baseUrl;
}
void Session::setBaseUrl(const QUrl &url)
{
d->baseUrl = url;
}
SignOnJob *Session::signOn()
{
QUrl url = d->baseUrl;
url.setEncodedPath(d->jsonPath("/auth"));
url.addQueryItem(QLatin1String("auth_user"), d->userName);
url.addQueryItem(QLatin1String("auth_password"), d->password);
url.addQueryItem(QLatin1String("auth_device"), d->deviceId);
//qDebug()<<"url is " <<url;
SignOnJob *job = new SignOnJob(d->get(url), this);
connect(job, SIGNAL(signedOn(Bodega::SignOnJob*)), SLOT(signOnFinished(Bodega::SignOnJob*)));
d->jobConnect(job);
return job;
}
void Session::signOut()
{
if (d->authenticated) {
d->authenticated = false;
d->setPoints(0);
emit disconnected();
}
}
QString Session::userName() const
{
return d->userName;
}
void Session::setUserName(const QString &name)
{
d->userName = name;
}
QString Session::password() const
{
return d->password;
}
void Session::setPassword(const QString &pass)
{
d->password = pass;
}
QString Session::deviceId() const
{
return d->deviceId;
}
void Bodega::Session::setDeviceId(const QString &device)
{
d->deviceId = device;
}
bool Session::isAuthenticated() const
{
return d->authenticated;
}
ChannelsJob * Session::channels(const QString &topChannel, int offset,
int pageSize)
{
QUrl url = d->baseUrl;
QString path;
if (topChannel.isEmpty()) {
//list all channels
path = QLatin1String("/channels");
} else {
path = QString::fromLatin1("/channel/%1").arg(topChannel);
}
url.setEncodedPath(d->jsonPath(path));
if (offset >= 0) {
url.addQueryItem(QLatin1String("offset"),
QString::fromLatin1("%1").arg(offset));
}
if (pageSize >= 0) {
url.addQueryItem(QLatin1String("pageSize"),
QString::fromLatin1("%1").arg(pageSize));
}
//qDebug()<<"url is " <<url;
ChannelsJob *job = new ChannelsJob(topChannel, d->get(url), this);
d->jobConnect(job);
return job;
}
ChannelsJob * Session::search(const QString &text, const QString &channelId, int offset, int pageSize)
{
QUrl url = d->baseUrl;
QString path = QLatin1String("/search");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("query"), text);
//FIXME: decide how this should work, the search field may have to be moved in the channels column
url.addQueryItem(QLatin1String("channelId"), channelId);
if (offset >= 0) {
url.addQueryItem(QLatin1String("offset"),
QString::fromLatin1("%1").arg(offset));
}
if (pageSize >= 0) {
url.addQueryItem(QLatin1String("pageSize"),
QString::fromLatin1("%1").arg(pageSize));
}
//qDebug()<<"url is " <<url;
ChannelsJob *job = new ChannelsJob(text, d->get(url), this);
d->jobConnect(job);
return job;
}
ParticipantInfoJob *Session::participantInfo()
{
QUrl url = d->baseUrl;
const QString path = QLatin1String("/participant/info");
url.setEncodedPath(d->jsonPath(path));
ParticipantInfoJob *job = new ParticipantInfoJob(d->get(url), this);
d->jobConnect(job);
return job;
}
ChannelsJob * Session::nextChannels(const ChannelsJob *job)
{
if (!job || !job->hasMoreAssets())
return 0;
int offset = job->offset() + 1;
int pageSize = job->pageSize();
return channels(job->channelId(),
offset, pageSize);
}
ChannelsJob * Session::prevChannels(const ChannelsJob *job)
{
if (!job || job->offset() <= 0)
return 0;
int offset = job->offset() - 1;
int pageSize = job->pageSize();
return channels(job->channelId(),
offset, pageSize);
}
AssetJob * Session::asset(const QString &assetId,
AssetJob::AssetFlags flags)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/asset/%1")
.arg(assetId);
url.setEncodedPath(d->jsonPath(path));
if (flags & AssetJob::ShowPreviews)
url.addQueryItem(QLatin1String("previews"),
QLatin1String("1"));
if (flags & AssetJob::ShowChangeLog)
url.addQueryItem(QLatin1String("changelog"),
QLatin1String("1"));
//qDebug()<<"url is " <<url;
AssetJob *job = new AssetJob(assetId, d->get(url), this);
d->jobConnect(job);
return job;
}
ChangeLanguageJob * Session::changeLanguage(const QString &lang)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/language/%1")
.arg(lang);
url.setEncodedPath(d->jsonPath(path));
//qDebug()<<"url is " <<url;
ChangeLanguageJob *job = new ChangeLanguageJob(lang, d->get(url), this);
d->jobConnect(job);
return job;
}
int Session::points() const
{
return d->points;
}
QMap<ImageUrl, QUrl> Session::urlsForImage(const QString &name) const
{
QMap<ImageUrl, QUrl>::const_iterator itr;
QMap<ImageUrl, QUrl> ret;
for (itr = d->imageUrls.constBegin(); itr != d->imageUrls.constEnd();
++itr) {
QString path = QString::fromLatin1("%1/%2")
.arg(itr.value().toString())
.arg(name);
ret.insert(itr.key(), QUrl(path));
}
return ret;
}
Bodega::AssetOperations *Session::assetOperations(const QString &assetId)
{
return new AssetOperations(assetId, this);
}
Bodega::InstallJob *Session::install(AssetOperations *operations)
{
QNetworkReply *reply = d->get(operations->assetInfo().path);
InstallJob *job = operations->install(reply, this);
d->jobConnect(job);
return job;
}
Bodega::UninstallJob *Session::uninstall(AssetOperations *operations)
{
QNetworkReply *reply = d->get(operations->assetInfo().path);
return operations->uninstall(this);
}
Bodega::RegisterJob * Session::registerAccount(const QString &email,
const QString &password,
const QString &firstName,
const QString &middleNames,
const QString &lastName)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/register");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("email"), email);
url.addQueryItem(QLatin1String("password"), password);
url.addQueryItem(QLatin1String("firstname"), firstName);
url.addQueryItem(QLatin1String("middlenames"), middleNames);
url.addQueryItem(QLatin1String("lastName"), lastName);
//qDebug()<<"url is " <<url;
RegisterJob *job = new RegisterJob(d->get(url), this);
d->jobConnect(job);
return job;
}
Bodega::ResetPasswordJob * Session::resetPassword(const QString &email)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/resetRequest");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("email"), email);
//qDebug()<<"url is " <<url;
ResetPasswordJob *job = new ResetPasswordJob(d->get(url), this);
d->jobConnect(job);
return job;
}
Bodega::ListBallotsJob * Session::listBallots(int offset, int pageSize)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/listBallots");
url.setEncodedPath(d->jsonPath(path));
if (offset >= 0) {
url.addQueryItem(QLatin1String("offset"),
QString::fromLatin1("%1").arg(offset));
}
if (pageSize >= 0) {
url.addQueryItem(QLatin1String("pageSize"),
QString::fromLatin1("%1").arg(pageSize));
}
//qDebug()<<"url is " <<url;
ListBallotsJob *job = new ListBallotsJob(d->get(url), this);
d->jobConnect(job);
return job;
}
Bodega::CreateBallotJob * Session::createBallot(const QString &name,
BallotInfo::BallotFlags flags)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/createBallot");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("name"), name);
if (flags.testFlag(BallotInfo::Public)) {
url.addQueryItem(QLatin1String("public"), QLatin1String("true"));
} else {
url.addQueryItem(QLatin1String("public"), QLatin1String("false"));
}
if (flags.testFlag(BallotInfo::Wishlist)) {
url.addQueryItem(QLatin1String("wishlist"), QLatin1String("true"));
} else {
url.addQueryItem(QLatin1String("wishlist"), QLatin1String("false"));
}
//qDebug()<<"url is " <<url;
CreateBallotJob *job = new CreateBallotJob(d->get(url), this);
d->jobConnect(job);
return job;
}
#include "session.moc"
<commit_msg>implementation for redeemPointsCode<commit_after>/*
* Copyright 2012 Coherent Theory LLC
*
* This program 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, 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 Library 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 "session.h"
#include "session_p.h"
#include "assetjob.h"
#include "assetoperations.h"
#include "channelsjob.h"
#include "changelanguagejob.h"
#include "createballotjob.h"
#include "installjob.h"
#include "listballotsjob.h"
#include "participantinfojob.h"
#include "registerjob.h"
#include "resetpasswordjob.h"
#include "searchjob.h"
#include "signonjob.h"
#include <QNetworkAccessManager>
#include <QDebug>
#include <QDir>
using namespace Bodega;
Session::Private::Private(Session *parent)
: q(parent),
points(0),
authenticated(false),
netManager(new QNetworkAccessManager(q))
{
}
void Session::Private::setPoints(int p)
{
if (p > -1) {
points = p;
emit q->pointsChanged(points);
}
}
void Session::Private::signOnFinished(SignOnJob *job)
{
imageUrls = job->imageUrls();
}
void Session::Private::jobFinished(NetworkJob *job)
{
if (authenticated && !job->authSuccess()) {
setPoints(0);
emit q->disconnected();
}
if (authenticated != job->authSuccess()) {
authenticated = !authenticated;
emit q->authenticated(authenticated);
}
if (job->authSuccess()) {
setPoints(job->points());
}
job->deleteLater();
}
QNetworkReply *Session::Private::get(const QUrl &url)
{
QNetworkRequest request;
request.setRawHeader("User-Agent", "Bodega 0.1");
request.setUrl(url);
return netManager->get(request);
}
Session::Session(QObject *parent)
: QObject(parent),
d(new Private(this))
{
}
Session::~Session()
{
delete d;
}
QUrl Session::baseUrl() const
{
return d->baseUrl;
}
void Session::setBaseUrl(const QUrl &url)
{
d->baseUrl = url;
}
SignOnJob *Session::signOn()
{
QUrl url = d->baseUrl;
url.setEncodedPath(d->jsonPath("/auth"));
url.addQueryItem(QLatin1String("auth_user"), d->userName);
url.addQueryItem(QLatin1String("auth_password"), d->password);
url.addQueryItem(QLatin1String("auth_device"), d->deviceId);
//qDebug()<<"url is " <<url;
SignOnJob *job = new SignOnJob(d->get(url), this);
connect(job, SIGNAL(signedOn(Bodega::SignOnJob*)), SLOT(signOnFinished(Bodega::SignOnJob*)));
d->jobConnect(job);
return job;
}
void Session::signOut()
{
if (d->authenticated) {
d->authenticated = false;
d->setPoints(0);
emit disconnected();
}
}
QString Session::userName() const
{
return d->userName;
}
void Session::setUserName(const QString &name)
{
d->userName = name;
}
QString Session::password() const
{
return d->password;
}
void Session::setPassword(const QString &pass)
{
d->password = pass;
}
QString Session::deviceId() const
{
return d->deviceId;
}
void Bodega::Session::setDeviceId(const QString &device)
{
d->deviceId = device;
}
bool Session::isAuthenticated() const
{
return d->authenticated;
}
ChannelsJob * Session::channels(const QString &topChannel, int offset,
int pageSize)
{
QUrl url = d->baseUrl;
QString path;
if (topChannel.isEmpty()) {
//list all channels
path = QLatin1String("/channels");
} else {
path = QString::fromLatin1("/channel/%1").arg(topChannel);
}
url.setEncodedPath(d->jsonPath(path));
if (offset >= 0) {
url.addQueryItem(QLatin1String("offset"),
QString::fromLatin1("%1").arg(offset));
}
if (pageSize >= 0) {
url.addQueryItem(QLatin1String("pageSize"),
QString::fromLatin1("%1").arg(pageSize));
}
//qDebug()<<"url is " <<url;
ChannelsJob *job = new ChannelsJob(topChannel, d->get(url), this);
d->jobConnect(job);
return job;
}
ChannelsJob * Session::search(const QString &text, const QString &channelId, int offset, int pageSize)
{
QUrl url = d->baseUrl;
QString path = QLatin1String("/search");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("query"), text);
//FIXME: decide how this should work, the search field may have to be moved in the channels column
url.addQueryItem(QLatin1String("channelId"), channelId);
if (offset >= 0) {
url.addQueryItem(QLatin1String("offset"),
QString::fromLatin1("%1").arg(offset));
}
if (pageSize >= 0) {
url.addQueryItem(QLatin1String("pageSize"),
QString::fromLatin1("%1").arg(pageSize));
}
//qDebug()<<"url is " <<url;
ChannelsJob *job = new ChannelsJob(text, d->get(url), this);
d->jobConnect(job);
return job;
}
ParticipantInfoJob *Session::participantInfo()
{
QUrl url = d->baseUrl;
const QString path = QLatin1String("/participant/info");
url.setEncodedPath(d->jsonPath(path));
ParticipantInfoJob *job = new ParticipantInfoJob(d->get(url), this);
d->jobConnect(job);
return job;
}
ChannelsJob * Session::nextChannels(const ChannelsJob *job)
{
if (!job || !job->hasMoreAssets())
return 0;
int offset = job->offset() + 1;
int pageSize = job->pageSize();
return channels(job->channelId(),
offset, pageSize);
}
ChannelsJob * Session::prevChannels(const ChannelsJob *job)
{
if (!job || job->offset() <= 0)
return 0;
int offset = job->offset() - 1;
int pageSize = job->pageSize();
return channels(job->channelId(),
offset, pageSize);
}
AssetJob * Session::asset(const QString &assetId,
AssetJob::AssetFlags flags)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/asset/%1")
.arg(assetId);
url.setEncodedPath(d->jsonPath(path));
if (flags & AssetJob::ShowPreviews)
url.addQueryItem(QLatin1String("previews"),
QLatin1String("1"));
if (flags & AssetJob::ShowChangeLog)
url.addQueryItem(QLatin1String("changelog"),
QLatin1String("1"));
//qDebug()<<"url is " <<url;
AssetJob *job = new AssetJob(assetId, d->get(url), this);
d->jobConnect(job);
return job;
}
ChangeLanguageJob * Session::changeLanguage(const QString &lang)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/language/%1")
.arg(lang);
url.setEncodedPath(d->jsonPath(path));
//qDebug()<<"url is " <<url;
ChangeLanguageJob *job = new ChangeLanguageJob(lang, d->get(url), this);
d->jobConnect(job);
return job;
}
int Session::points() const
{
return d->points;
}
QMap<ImageUrl, QUrl> Session::urlsForImage(const QString &name) const
{
QMap<ImageUrl, QUrl>::const_iterator itr;
QMap<ImageUrl, QUrl> ret;
for (itr = d->imageUrls.constBegin(); itr != d->imageUrls.constEnd();
++itr) {
QString path = QString::fromLatin1("%1/%2")
.arg(itr.value().toString())
.arg(name);
ret.insert(itr.key(), QUrl(path));
}
return ret;
}
Bodega::AssetOperations *Session::assetOperations(const QString &assetId)
{
return new AssetOperations(assetId, this);
}
Bodega::InstallJob *Session::install(AssetOperations *operations)
{
QNetworkReply *reply = d->get(operations->assetInfo().path);
InstallJob *job = operations->install(reply, this);
d->jobConnect(job);
return job;
}
Bodega::UninstallJob *Session::uninstall(AssetOperations *operations)
{
QNetworkReply *reply = d->get(operations->assetInfo().path);
return operations->uninstall(this);
}
Bodega::NetworkJob *Session::redeemPointsCode(const QString &code)
{
QUrl url = d->baseUrl;
const QString path = QLatin1String("points/redeemCode/") + code;
url.setEncodedPath(d->jsonPath(path));
NetworkJob *job = new NetworkJob(d->get(url), this);
d->jobConnect(job);
return job;
}
Bodega::RegisterJob * Session::registerAccount(const QString &email,
const QString &password,
const QString &firstName,
const QString &middleNames,
const QString &lastName)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/register");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("email"), email);
url.addQueryItem(QLatin1String("password"), password);
url.addQueryItem(QLatin1String("firstname"), firstName);
url.addQueryItem(QLatin1String("middlenames"), middleNames);
url.addQueryItem(QLatin1String("lastName"), lastName);
//qDebug()<<"url is " <<url;
RegisterJob *job = new RegisterJob(d->get(url), this);
d->jobConnect(job);
return job;
}
Bodega::ResetPasswordJob * Session::resetPassword(const QString &email)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/resetRequest");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("email"), email);
//qDebug()<<"url is " <<url;
ResetPasswordJob *job = new ResetPasswordJob(d->get(url), this);
d->jobConnect(job);
return job;
}
Bodega::ListBallotsJob * Session::listBallots(int offset, int pageSize)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/listBallots");
url.setEncodedPath(d->jsonPath(path));
if (offset >= 0) {
url.addQueryItem(QLatin1String("offset"),
QString::fromLatin1("%1").arg(offset));
}
if (pageSize >= 0) {
url.addQueryItem(QLatin1String("pageSize"),
QString::fromLatin1("%1").arg(pageSize));
}
//qDebug()<<"url is " <<url;
ListBallotsJob *job = new ListBallotsJob(d->get(url), this);
d->jobConnect(job);
return job;
}
Bodega::CreateBallotJob * Session::createBallot(const QString &name,
BallotInfo::BallotFlags flags)
{
QUrl url = d->baseUrl;
QString path = QString::fromLatin1("/createBallot");
url.setEncodedPath(d->jsonPath(path));
url.addQueryItem(QLatin1String("name"), name);
if (flags.testFlag(BallotInfo::Public)) {
url.addQueryItem(QLatin1String("public"), QLatin1String("true"));
} else {
url.addQueryItem(QLatin1String("public"), QLatin1String("false"));
}
if (flags.testFlag(BallotInfo::Wishlist)) {
url.addQueryItem(QLatin1String("wishlist"), QLatin1String("true"));
} else {
url.addQueryItem(QLatin1String("wishlist"), QLatin1String("false"));
}
//qDebug()<<"url is " <<url;
CreateBallotJob *job = new CreateBallotJob(d->get(url), this);
d->jobConnect(job);
return job;
}
#include "session.moc"
<|endoftext|> |
<commit_before>#include <cassert>
#include <cstdlib>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
void testBranchOnVariableDeclaration ()
{
std::map<std::string, std::string> data;
data["key"] = "value";
if (std::string * value = &data["key"])
{
assert(* value == "value");
return;
}
assert(0);
}
void testArrayIndexAccess ()
{
int array[3];
array[0] = 0;
array[1] = 1;
array[2] = 2;
assert(array[1] == 1);
assert(*(array + 1) == 1);
assert((*(1 + array)) == 1);
assert(1[array] == 1);
}
void testKeywordOperatorTokens ()
{
assert(1 and 1);
assert(0 or 1);
int array[1];
array[0] = 5;
assert(array<:0:> == 5);
if (1)
<%
assert(1);
return;
%>
assert(0);
}
class ContainsProtectedValue
{
public:
ContainsProtectedValue (const int foo) : foo(foo) { }
protected:
const int foo;
};
class PromotesProtectedValue : public ContainsProtectedValue
{
public:
PromotesProtectedValue (int foo) : ContainsProtectedValue(foo) { }
using ContainsProtectedValue::foo;
};
void testChangingScope ()
{
assert(PromotesProtectedValue(5).foo == 5);
}
#define private public
class NotPrivateHere
{
private:
bool success () const
{
return true;
}
};
#undef private
void testRedefiningKeywords ()
{
assert(NotPrivateHere().success());
}
struct HasStaticMethod {
static bool isCalled ()
{
return true;
}
};
void testStaticInstanceMethodCalls ()
{
assert(HasStaticMethod::isCalled() == HasStaticMethod().isCalled());
}
struct PointToUs {
int value;
bool method () const
{
return true;
}
};
int PointToUs::*valuePointer = &PointToUs::value;
bool (PointToUs::*methodPointer)() const = &PointToUs::method;
void testPointerToMemberOperators ()
{
PointToUs stack;
PointToUs * heap = new PointToUs;
assert((stack.*methodPointer)());
assert((heap->*methodPointer)());
stack.*valuePointer = 1;
assert(stack.*valuePointer == 1);
heap->*valuePointer = 2;
assert(heap->*valuePointer == 2);
delete heap;
}
std::string letMeKeepMyReturnValue ()
{
return "value";
}
void testScopeGuardTrick ()
{
const std::string & value(letMeKeepMyReturnValue());
assert(value == "value");
}
class PrePostInDecrementOverloading {
private:
int _value;
void incrementValue ()
{
_value = _value + 1;
}
void decrementValue ()
{
_value = _value - 1;
}
public:
PrePostInDecrementOverloading () : _value(0) { }
int getValue () const
{
return _value;
}
// pre
PrePostInDecrementOverloading & operator++ (int value)
{
incrementValue();
return * this;
}
PrePostInDecrementOverloading & operator-- (int value)
{
decrementValue();
return * this;
}
// post
PrePostInDecrementOverloading & operator++ ()
{
incrementValue();
return * this;
}
PrePostInDecrementOverloading & operator-- ()
{
decrementValue();
return * this;
}
};
void testPrePostInDecrementOverloading ()
{
PrePostInDecrementOverloading test;
assert(test++.getValue() == 1);
assert(test--.getValue() == 0);
assert((++test).getValue() == 1);
assert((--test).getValue() == 0);
}
template <class T>
class VectorBuilder
{
private:
std::vector<T> _container;
public:
VectorBuilder & addValue (T value)
{
_container.push_back(value);
return * this;
}
VectorBuilder () { }
VectorBuilder (T value)
{
addValue(value);
}
VectorBuilder & operator, (const T & value)
{
return addValue(value);
}
VectorBuilder & operator() (const T & value)
{
return addValue(value);
}
std::vector<T> get () const
{
return _container;
}
};
void testCommaAndBracketOverloads ()
{
std::vector<int> integers;
integers.push_back(0);
integers.push_back(1);
assert((VectorBuilder<int>(0), 1).get() == integers);
std::vector<std::string> strings;
strings.push_back("hello");
strings.push_back("world");
assert(VectorBuilder<std::string>("hello")("world").get() == strings);
}
struct ReturnOverload
{
ReturnOverload () { }
int get ()
{
return 5;
}
std::string get () const
{
return "hello";
}
};
void testReturnOverload ()
{
ReturnOverload returnOverload;
const int & i(returnOverload.get());
assert(i == 5);
const ReturnOverload constReturnOverload;
const std::string & s(constReturnOverload.get());
assert(s == "hello");
}
struct TypedefScopedToClass
{
typedef std::vector<std::string> strings;
};
void testTypedefScopedToClass ()
{
std::vector<std::string> v1;
v1.push_back("hello");
TypedefScopedToClass::strings v2;
v2.push_back("hello");
assert(v1 == v2);
}
int main ()
{
typedef void (*testFunc)();
const std::vector<testFunc> tests(
VectorBuilder<testFunc>
(& testBranchOnVariableDeclaration)
(& testArrayIndexAccess)
(& testKeywordOperatorTokens)
(& testChangingScope)
(& testRedefiningKeywords)
(& testStaticInstanceMethodCalls)
(& testPointerToMemberOperators)
(& testScopeGuardTrick)
(& testPrePostInDecrementOverloading)
(& testCommaAndBracketOverloads)
(& testReturnOverload)
(& testTypedefScopedToClass)
.get()
);
const int & numOfTests(tests.size());
for (int i = 0; i < numOfTests; ++i)
{
tests[i]();
}
std::cout << numOfTests << " tests passed successfully!" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>Making Vector Builder More Generic<commit_after>#include <cassert>
#include <cstdlib>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
void testBranchOnVariableDeclaration ()
{
std::map<std::string, std::string> data;
data["key"] = "value";
if (std::string * value = &data["key"])
{
assert(* value == "value");
return;
}
assert(0);
}
void testArrayIndexAccess ()
{
int array[3];
array[0] = 0;
array[1] = 1;
array[2] = 2;
assert(array[1] == 1);
assert(*(array + 1) == 1);
assert((*(1 + array)) == 1);
assert(1[array] == 1);
}
void testKeywordOperatorTokens ()
{
assert(1 and 1);
assert(0 or 1);
int array[1];
array[0] = 5;
assert(array<:0:> == 5);
if (1)
<%
assert(1);
return;
%>
assert(0);
}
class ContainsProtectedValue
{
public:
ContainsProtectedValue (const int foo) : foo(foo) { }
protected:
const int foo;
};
class PromotesProtectedValue : public ContainsProtectedValue
{
public:
PromotesProtectedValue (int foo) : ContainsProtectedValue(foo) { }
using ContainsProtectedValue::foo;
};
void testChangingScope ()
{
assert(PromotesProtectedValue(5).foo == 5);
}
#define private public
class NotPrivateHere
{
private:
bool success () const
{
return true;
}
};
#undef private
void testRedefiningKeywords ()
{
assert(NotPrivateHere().success());
}
struct HasStaticMethod {
static bool isCalled ()
{
return true;
}
};
void testStaticInstanceMethodCalls ()
{
assert(HasStaticMethod::isCalled() == HasStaticMethod().isCalled());
}
struct PointToUs {
int value;
bool method () const
{
return true;
}
};
int PointToUs::*valuePointer = &PointToUs::value;
bool (PointToUs::*methodPointer)() const = &PointToUs::method;
void testPointerToMemberOperators ()
{
PointToUs stack;
PointToUs * heap = new PointToUs;
assert((stack.*methodPointer)());
assert((heap->*methodPointer)());
stack.*valuePointer = 1;
assert(stack.*valuePointer == 1);
heap->*valuePointer = 2;
assert(heap->*valuePointer == 2);
delete heap;
}
std::string letMeKeepMyReturnValue ()
{
return "value";
}
void testScopeGuardTrick ()
{
const std::string & value(letMeKeepMyReturnValue());
assert(value == "value");
}
class PrePostInDecrementOverloading {
private:
int _value;
void incrementValue ()
{
_value = _value + 1;
}
void decrementValue ()
{
_value = _value - 1;
}
public:
PrePostInDecrementOverloading () : _value(0) { }
int getValue () const
{
return _value;
}
// pre
PrePostInDecrementOverloading & operator++ (int value)
{
incrementValue();
return * this;
}
PrePostInDecrementOverloading & operator-- (int value)
{
decrementValue();
return * this;
}
// post
PrePostInDecrementOverloading & operator++ ()
{
incrementValue();
return * this;
}
PrePostInDecrementOverloading & operator-- ()
{
decrementValue();
return * this;
}
};
void testPrePostInDecrementOverloading ()
{
PrePostInDecrementOverloading test;
assert(test++.getValue() == 1);
assert(test--.getValue() == 0);
assert((++test).getValue() == 1);
assert((--test).getValue() == 0);
}
template<template<class, class> class V, class T>
class VectorBuilder
{
private:
V< T, std::allocator<T> > _container;
public:
VectorBuilder & addValue (const T & value)
{
_container.push_back(value);
return * this;
}
VectorBuilder () { }
VectorBuilder (const T & value)
{
addValue(value);
}
VectorBuilder & operator, (const T & value)
{
return addValue(value);
}
VectorBuilder & operator() (const T & value)
{
return addValue(value);
}
V< T, std::allocator<T> > get () const
{
return _container;
}
};
void testCommaAndBracketOverloads ()
{
std::vector<int> integers;
integers.push_back(0);
integers.push_back(1);
assert((VectorBuilder<std::vector, int>(0), 1).get() == integers);
std::vector<std::string> strings;
strings.push_back("hello");
strings.push_back("world");
assert((VectorBuilder<std::vector, std::string>("hello")("world").get()) == strings);
}
struct ReturnOverload
{
ReturnOverload () { }
int get ()
{
return 5;
}
std::string get () const
{
return "hello";
}
};
void testReturnOverload ()
{
ReturnOverload returnOverload;
const int & i(returnOverload.get());
assert(i == 5);
const ReturnOverload constReturnOverload;
const std::string & s(constReturnOverload.get());
assert(s == "hello");
}
struct TypedefScopedToClass
{
typedef std::vector<std::string> strings;
};
void testTypedefScopedToClass ()
{
std::vector<std::string> v1;
v1.push_back("hello");
TypedefScopedToClass::strings v2;
v2.push_back("hello");
assert(v1 == v2);
}
int main ()
{
typedef void (*testFunc)();
const std::vector<testFunc> tests(
VectorBuilder<std::vector, testFunc>
(& testBranchOnVariableDeclaration)
(& testArrayIndexAccess)
(& testKeywordOperatorTokens)
(& testChangingScope)
(& testRedefiningKeywords)
(& testStaticInstanceMethodCalls)
(& testPointerToMemberOperators)
(& testScopeGuardTrick)
(& testPrePostInDecrementOverloading)
(& testCommaAndBracketOverloads)
(& testReturnOverload)
(& testTypedefScopedToClass)
.get()
);
const int & numOfTests(tests.size());
for (int i = 0; i < numOfTests; ++i)
{
tests[i]();
}
std::cout << numOfTests << " tests passed successfully!" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
> File Name: main.cpp
> Author:
> Mail:
> Created Time: 日 4/ 3 13:24:20 2016
************************************************************************/
#include<iostream>
using namespace std;
int main() {
int x = 1;
return 0;
}
<commit_msg>Update main.cpp<commit_after>/*************************************************************************
> File Name: main.cpp
> Author:
> Mail:
> Created Time: 日 4/ 3 13:24:20 2016
************************************************************************/
#include<iostream>
using namespace std;
int main() {
int x = 1;
cout << "Please input a number:";
cin >> x >> endl;
cout << x << endl;
return 0;
}
<|endoftext|> |
<commit_before>//
// BatchEncoder (Audio Conversion GUI)
// Copyright (C) 2005-2017 Wiesław Šoltés <wieslaw.soltes@gmail.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// 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-1307 USA
//
#include "StdAfx.h"
#include "BatchEncoder.h"
#include "Utilities.h"
#include "AboutDlg.h"
#include ".\aboutdlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNAMIC(CAboutDlg, CDialog)
CAboutDlg::CAboutDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAboutDlg::IDD, pParent)
{
}
CAboutDlg::~CAboutDlg()
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDOK, m_BtnOK);
DDX_Control(pDX, IDC_STATIC_TEXT_APP_NAME, m_StcMainAppName);
DDX_Control(pDX, IDC_STATIC_TEXT_WEBSITE, m_StcWebsite);
DDX_Control(pDX, IDC_STATIC_TEXT_EMAIL, m_StcEmail);
DDX_Control(pDX, IDC_STATIC_LICENSE, m_StcLicense);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
ON_WM_CLOSE()
ON_BN_CLICKED(IDOK, OnBnClickedOk)
END_MESSAGE_MAP()
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
m_StcMainAppName.SetBold(true);
m_StcWebsite.SetBold(false);
m_StcEmail.SetBold(false);
m_StcLicense.SetBold(false);
m_StcMainAppName.SetWindowText(MAIN_APP_NAME_VER);
m_StcWebsite.SetWindowText(MAIN_APP_WEBSITE);
m_StcWebsite.SetTargetUrl(MAIN_APP_WEBSITE);
CString szEmail;
szEmail.Format(_T("mailto:%s"), MAIN_APP_EMAIL);
m_StcEmail.SetWindowText(MAIN_APP_EMAIL);
m_StcEmail.SetTargetUrl(szEmail);
return TRUE;
}
void CAboutDlg::OnOK()
{
CDialog::OnOK();
}
void CAboutDlg::OnCancel()
{
CDialog::OnCancel();
}
void CAboutDlg::OnClose()
{
CDialog::OnClose();
}
void CAboutDlg::OnBnClickedOk()
{
OnOK();
}
<commit_msg>Update AboutDlg.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "BatchEncoder.h"
#include "Utilities.h"
#include "AboutDlg.h"
#include ".\aboutdlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNAMIC(CAboutDlg, CDialog)
CAboutDlg::CAboutDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAboutDlg::IDD, pParent)
{
}
CAboutDlg::~CAboutDlg()
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDOK, m_BtnOK);
DDX_Control(pDX, IDC_STATIC_TEXT_APP_NAME, m_StcMainAppName);
DDX_Control(pDX, IDC_STATIC_TEXT_WEBSITE, m_StcWebsite);
DDX_Control(pDX, IDC_STATIC_TEXT_EMAIL, m_StcEmail);
DDX_Control(pDX, IDC_STATIC_LICENSE, m_StcLicense);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
ON_WM_CLOSE()
ON_BN_CLICKED(IDOK, OnBnClickedOk)
END_MESSAGE_MAP()
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
m_StcMainAppName.SetBold(true);
m_StcWebsite.SetBold(false);
m_StcEmail.SetBold(false);
m_StcLicense.SetBold(false);
m_StcMainAppName.SetWindowText(MAIN_APP_NAME_VER);
m_StcWebsite.SetWindowText(MAIN_APP_WEBSITE);
m_StcWebsite.SetTargetUrl(MAIN_APP_WEBSITE);
CString szEmail;
szEmail.Format(_T("mailto:%s"), MAIN_APP_EMAIL);
m_StcEmail.SetWindowText(MAIN_APP_EMAIL);
m_StcEmail.SetTargetUrl(szEmail);
return TRUE;
}
void CAboutDlg::OnOK()
{
CDialog::OnOK();
}
void CAboutDlg::OnCancel()
{
CDialog::OnCancel();
}
void CAboutDlg::OnClose()
{
CDialog::OnClose();
}
void CAboutDlg::OnBnClickedOk()
{
OnOK();
}
<|endoftext|> |
<commit_before>/*The MIT License (MIT)
Copyright (c) 2015 k-brac
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <string>
#include <vector>
#include <iostream>
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4251 )
#endif
#if __MACH__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wextra-semi"
#pragma clang diagnostic ignored "-Wdocumentation"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#define CPPUNIT_STD_NEED_ALLOCATOR 0
#endif
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/CompilerOutputter.h"
#include "cppunit/XmlOutputter.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/plugin/PlugInManager.h"
#include <chrono>
class TimedBriefTestProgressListener : public CppUnit::BriefTestProgressListener {
private:
std::chrono::time_point<std::chrono::high_resolution_clock> mTimer;
public:
void startTest(CppUnit::Test *test)
{
CppUnit::BriefTestProgressListener::startTest(test);
mTimer = std::chrono::high_resolution_clock::now();
}
void endTest(CppUnit::Test *test)
{
const std::chrono::duration<float, std::milli> elapsed = std::chrono::high_resolution_clock::now() - mTimer;
CppUnit::stdCOut() << " (" << std::to_string(elapsed.count()) << " ms elapsed)";
#if defined(WIN32)
CppUnit::stdCOut().flush();
#endif
CppUnit::BriefTestProgressListener::endTest(test);
}
};
#if __MACH__
#pragma clang diagnostic pop
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
struct CommandLineParser {
std::string xmlOutputFile;
std::string plugName;
std::vector<std::string> testPaths;
void parseArgs(int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg.size() >= 2 && arg.front() == '-') {
auto it = arg.find("=");
if (it != std::string::npos) {
auto key = arg.substr(0, it);
auto val = arg.substr(it + 1, arg.size());
if (val.empty()) {
continue;
}
if (key == "-x" || key == "--xml") {
xmlOutputFile = val;
}
else if (key == "-t" || key == "--test") {
testPaths.emplace_back(val);
}
else {
std::cerr << "Unknow arguments " << key << " with value : " << val << std::endl;
}
}
}
else {
plugName = arg;
}
}
}
};
bool runPlugin(const CommandLineParser &arguments) {
CppUnit::PlugInManager pluginManager;
pluginManager.load(arguments.plugName);
// Create the event manager and test controller
CppUnit::TestResult controller;
// Add a listener that collects test result
CppUnit::TestResultCollector result;
controller.addListener(&result);
// Add a listener
TimedBriefTestProgressListener progress;
controller.addListener(&progress);
pluginManager.addListener(&controller);
// Add the top suite to the test runner
CppUnit::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
try
{
if (arguments.testPaths.empty()) {
std::cout << "Running " << std::endl;
runner.run(controller);
}
else {
for (const auto & p : arguments.testPaths) {
std::cout << "Running " << p << std::endl;
runner.run(controller, p);
}
}
std::cerr << std::endl;
// Print test in a compiler compatible format.
CppUnit::CompilerOutputter outputter(&result, std::cerr);
outputter.write();
if (!arguments.xmlOutputFile.empty()) {
std::ofstream file(arguments.xmlOutputFile);
CppUnit::XmlOutputter xOutputter(&result, file);
xOutputter.write();
}
}
catch (std::invalid_argument &e) // Test path not resolved
{
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
return false;
}
return result.wasSuccessful();
}
int main(int argc, char* argv[])
{
std::cout << "usage : " << argv[0] << "{-x | -xml=file} {-t | --test=Namespace::ClassName::TestName} test_plugin_path" << std::endl << std::endl;
if (argc < 2)
return 1;
bool result = false;
try {
CommandLineParser command;
command.parseArgs(argc, argv);
result = runPlugin(command);
}
catch (std::exception &e) {
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
}
return result ? 0 : 1;
}
<commit_msg>using steady_clock instead of high_resolution_clock<commit_after>/*The MIT License (MIT)
Copyright (c) 2015 k-brac
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <string>
#include <vector>
#include <iostream>
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4251 )
#endif
#if __MACH__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wextra-semi"
#pragma clang diagnostic ignored "-Wdocumentation"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#define CPPUNIT_STD_NEED_ALLOCATOR 0
#endif
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/CompilerOutputter.h"
#include "cppunit/XmlOutputter.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/plugin/PlugInManager.h"
#include <chrono>
class TimedBriefTestProgressListener : public CppUnit::BriefTestProgressListener {
private:
std::chrono::time_point<std::chrono::steady_clock> mTimer;
public:
void startTest(CppUnit::Test *test)
{
CppUnit::BriefTestProgressListener::startTest(test);
mTimer = std::chrono::high_resolution_clock::now();
}
void endTest(CppUnit::Test *test)
{
const std::chrono::duration<float, std::milli> elapsed = std::chrono::steady_clock::now() - mTimer;
CppUnit::stdCOut() << " (" << std::to_string(elapsed.count()) << " ms elapsed)";
#if defined(WIN32)
CppUnit::stdCOut().flush();
#endif
CppUnit::BriefTestProgressListener::endTest(test);
}
};
#if __MACH__
#pragma clang diagnostic pop
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
struct CommandLineParser {
std::string xmlOutputFile;
std::string plugName;
std::vector<std::string> testPaths;
void parseArgs(int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg.size() >= 2 && arg.front() == '-') {
auto it = arg.find("=");
if (it != std::string::npos) {
auto key = arg.substr(0, it);
auto val = arg.substr(it + 1, arg.size());
if (val.empty()) {
continue;
}
if (key == "-x" || key == "--xml") {
xmlOutputFile = val;
}
else if (key == "-t" || key == "--test") {
testPaths.emplace_back(val);
}
else {
std::cerr << "Unknow arguments " << key << " with value : " << val << std::endl;
}
}
}
else {
plugName = arg;
}
}
}
};
bool runPlugin(const CommandLineParser &arguments) {
CppUnit::PlugInManager pluginManager;
pluginManager.load(arguments.plugName);
// Create the event manager and test controller
CppUnit::TestResult controller;
// Add a listener that collects test result
CppUnit::TestResultCollector result;
controller.addListener(&result);
// Add a listener
TimedBriefTestProgressListener progress;
controller.addListener(&progress);
pluginManager.addListener(&controller);
// Add the top suite to the test runner
CppUnit::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
try
{
if (arguments.testPaths.empty()) {
std::cout << "Running " << std::endl;
runner.run(controller);
}
else {
for (const auto & p : arguments.testPaths) {
std::cout << "Running " << p << std::endl;
runner.run(controller, p);
}
}
std::cerr << std::endl;
// Print test in a compiler compatible format.
CppUnit::CompilerOutputter outputter(&result, std::cerr);
outputter.write();
if (!arguments.xmlOutputFile.empty()) {
std::ofstream file(arguments.xmlOutputFile);
CppUnit::XmlOutputter xOutputter(&result, file);
xOutputter.write();
}
}
catch (std::invalid_argument &e) // Test path not resolved
{
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
return false;
}
return result.wasSuccessful();
}
int main(int argc, char* argv[])
{
std::cout << "usage : " << argv[0] << "{-x | -xml=file} {-t | --test=Namespace::ClassName::TestName} test_plugin_path" << std::endl << std::endl;
if (argc < 2)
return 1;
bool result = false;
try {
CommandLineParser command;
command.parseArgs(argc, argv);
result = runPlugin(command);
}
catch (std::exception &e) {
std::cerr << std::endl
<< "ERROR: " << e.what()
<< std::endl;
}
return result ? 0 : 1;
}
<|endoftext|> |
<commit_before>
#include <uv.h>
#include "../../../ui.h"
#include "nbind/nbind.h"
extern int uiEventsPending();
extern int uiLoopWakeup();
extern int waitForNodeEvents(uv_loop_t* loop, int timeout);
static std::atomic<bool> running;
static uv_thread_t* thread;
static uv_timer_t* redrawTimer;
/*
This function is executed in the
background thread and is responsible to continuosly polling
the node backend for pending events.
When pending node events are found, the native GUI
event loop is wake up by calling uiLoopWakeup().
*/
static void backgroundNodeEventsPoller(void* arg) {
while (running) {
/* query node for the desired timout */
int timeout = uv_backend_timeout(uv_default_loop());
/* if timeout is 0, wait for 1s by default */
if (timeout == 0) {
timeout = 1000;
}
int pendingEvents;
/* wait for pending */
do {
pendingEvents = waitForNodeEvents(uv_default_loop(), timeout);
} while (pendingEvents == -1 && errno == EINTR);
if (pendingEvents > 0) {
uiLoopWakeup();
}
}
}
/*
This function run all pending native GUI event in the loop
using libui calls.
It first do a blocking call to uiMainStep that
wait for pending GUI events.
The function also exit when there are pending node
events, because uiLoopWakeup function posts a GUI event
from the background thread for this purpose.
*/
void redraw(uv_timer_t* handle) {
uv_timer_stop(handle);
Nan::HandleScope scope;
/* Blocking call that wait for a node or GUI event pending */
uiMainStep(true);
/* dequeue and run every event pending */
while (uiEventsPending()) {
running = uiMainStep(false);
}
/* schedule another call to redraw as soon as possible */
uv_timer_start(handle, redraw, 1, 0);
}
static void init() {
uiInitOptions o;
memset(&o, 0, sizeof(uiInitOptions));
const char* err = uiInit(&o);
if (err != NULL) {
NBIND_ERR(err);
uiFreeInitError(err);
}
}
struct EventLoop {
/* This function start the event loop and exit immediately */
static void start() {
/* if the loop is already running, this is a noop */
if (running) {
return;
}
init();
running = true;
/* init libui event loop */
uiMainSteps();
/* start the background thread that check for node evnts pending */
thread = new uv_thread_t();
uv_thread_create(thread, backgroundNodeEventsPoller, NULL);
/* start redraw timer */
redrawTimer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
uv_timer_init(uv_default_loop(), redrawTimer);
redraw(redrawTimer);
}
/* This function start the event loop and exit immediately */
static void stop() {
/* if the loop is already running, this is a noop */
if (!running) {
return;
}
running = false;
printf("stopping\n");
/* stop redraw handler */
uv_timer_stop(redrawTimer);
/* await for the background thread to finish */
uv_thread_join(thread);
printf("background thread end.\n");
/* quit libui event loop */
uiQuit();
printf("ui loop quit.\n");
}
};
NBIND_CLASS(EventLoop) {
method(start);
method(stop);
}
<commit_msg>Fixed exit bug<commit_after>
#include <uv.h>
#include "../../../ui.h"
#include "nbind/nbind.h"
extern int uiEventsPending();
extern int uiLoopWakeup();
extern int waitForNodeEvents(uv_loop_t* loop, int timeout);
static std::atomic<bool> running;
static uv_thread_t* thread;
static uv_timer_t* redrawTimer;
/*
This function is executed in the
background thread and is responsible to continuosly polling
the node backend for pending events.
When pending node events are found, the native GUI
event loop is wake up by calling uiLoopWakeup().
*/
static void backgroundNodeEventsPoller(void* arg) {
while (running) {
/* query node for the desired timout */
int timeout = uv_backend_timeout(uv_default_loop());
/* if timeout is 0, wait for 1s by default */
if (timeout == 0) {
timeout = 1000;
}
int pendingEvents;
/* wait for pending */
do {
pendingEvents = waitForNodeEvents(uv_default_loop(), timeout);
} while (pendingEvents == -1 && errno == EINTR);
if (pendingEvents > 0) {
uiLoopWakeup();
}
}
}
/*
This function run all pending native GUI event in the loop
using libui calls.
It first do a blocking call to uiMainStep that
wait for pending GUI events.
The function also exit when there are pending node
events, because uiLoopWakeup function posts a GUI event
from the background thread for this purpose.
*/
void redraw(uv_timer_t* handle) {
if (!running) {
return;
}
uv_timer_stop(handle);
Nan::HandleScope scope;
/* Blocking call that wait for a node or GUI event pending */
uiMainStep(true);
/* dequeue and run every event pending */
while (uiEventsPending()) {
running = uiMainStep(false);
}
/* schedule another call to redraw as soon as possible */
uv_timer_start(handle, redraw, 1, 0);
}
static void init() {
uiInitOptions o;
memset(&o, 0, sizeof(uiInitOptions));
const char* err = uiInit(&o);
if (err != NULL) {
NBIND_ERR(err);
uiFreeInitError(err);
}
}
struct EventLoop {
/* This function start the event loop and exit immediately */
static void start() {
/* if the loop is already running, this is a noop */
if (running) {
return;
}
init();
running = true;
/* init libui event loop */
uiMainSteps();
/* start the background thread that check for node evnts pending */
thread = new uv_thread_t();
uv_thread_create(thread, backgroundNodeEventsPoller, NULL);
/* start redraw timer */
redrawTimer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
uv_timer_init(uv_default_loop(), redrawTimer);
redraw(redrawTimer);
}
/* This function start the event loop and exit immediately */
static void stop() {
/* if the loop is already running, this is a noop */
if (!running) {
return;
}
running = false;
printf("stopping\n");
/* stop redraw handler */
uv_timer_stop(redrawTimer);
uv_close((uv_handle_t*)redrawTimer, NULL);
printf("timer end.\n");
/* await for the background thread to finish */
uv_thread_join(thread);
// uv_close((uv_handle_t*)thread, NULL);
printf("background thread end.\n");
/* quit libui event loop */
uiQuit();
printf("ui loop quit.\n");
}
};
NBIND_CLASS(EventLoop) {
method(start);
method(stop);
}
<|endoftext|> |
<commit_before>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
class CRulePrintHelper : public CPrintHelper {
public:
CRulePrintHelper( const CPrintHelper& _printHelper,
const CVariables& _variables ) :
printHelper( _printHelper ),
variables( _variables )
{
}
virtual void Variable( std::ostream& outputStream,
const TVariableIndex variable ) const
{
outputStream << variables.GetVariable( variable ).GetType();
variables.GetVariable( variable ).GetQualifier().Print( outputStream,
printHelper );
}
virtual void Label( std::ostream& outputStream,
const TLabel label ) const
{
printHelper.Label( outputStream, label );
}
private:
const CPrintHelper& printHelper;
const CVariables& variables;
};
void CRule::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
CRulePrintHelper rulePrintHelper( printHelper, Variables );
outputStream << "\t" << ( RightMatching ? "R" : "" ) << " ";
Left.Print( outputStream, rulePrintHelper );
outputStream << "= ";
Right.Print( outputStream, printHelper );
}
void CRule::Compile( CFunctionCompiler& compiler ) const
{
compiler.CompileRule( const_cast<CRule&>( *this ) );
}
//-----------------------------------------------------------------------------
CPreparatoryFunction::CPreparatoryFunction( const CToken& _nameToken ):
type( PFT_Declared ),
entry( false ),
name( _nameToken.word ),
nameToken( _nameToken ),
firstOperation( nullptr )
{
assert( !name.empty() );
MakeLower( name );
}
const std::string& CPreparatoryFunction::ExternalName() const
{
assert( IsEntry() || IsExternal() );
return externalName;
}
const CToken& CPreparatoryFunction::ExternalNameToken() const
{
assert( IsEntry() || IsExternal() );
return externalNameToken;
}
const CRule* CPreparatoryFunction::FirstRule() const
{
assert( IsOrdinary() );
return firstRule.get();
}
TOperationAddress CPreparatoryFunction::FirstOperation() const
{
assert( IsCompiled() );
return firstOperation;
}
void CPreparatoryFunction::SetDefined( const CToken& _nameToken )
{
assert( _nameToken.type == TT_Word );
assert( CompareNoCase( nameToken.word, _nameToken.word ) );
assert( type == PFT_Declared );
type = PFT_Defined;
nameToken = _nameToken;
}
void CPreparatoryFunction::SetOrdinary( CRulePtr& _firstRule )
{
assert( type == PFT_Defined );
assert( static_cast<bool>( _firstRule ) );
type = PFT_Ordinary;
firstRule.reset( _firstRule.release() );
}
void CPreparatoryFunction::SetEmpty()
{
assert( type == PFT_Defined );
type = PFT_Empty;
}
void CPreparatoryFunction::SetEntry( const CToken& _externalNameToken )
{
assert( type != PFT_External );
entry = true;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::SetExternal( const CToken& _externalNameToken )
{
assert( !entry );
assert( type == PFT_Defined );
type = PFT_External;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::Compile( CFunctionCompiler& compiler )
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Compile( compiler );
rule = rule->NextRule.get();
}
type = PFT_Compiled;
firstOperation = compiler.FinalizeCompilation();
assert( firstOperation != nullptr );
}
void CPreparatoryFunction::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Print( outputStream, printHelper );
outputStream << std::endl;
rule = rule->NextRule.get();
}
}
void CPreparatoryFunction::setExternalName( const CToken& _externalNameToken )
{
assert( ( entry && !IsExternal() ) || ( !entry && IsExternal() ) );
externalNameToken = _externalNameToken;
externalName = externalNameToken.word;
assert( !externalName.empty() );
MakeLower( externalName );
}
//-----------------------------------------------------------------------------
CFunctionBuilder::CFunctionBuilder( IErrorHandler* errorHandler ):
CVariablesBuilder( errorHandler ),
isProcessRightPart( false ),
isRightDirection( false ),
lastRule( nullptr )
{
}
CFunctionBuilder::~CFunctionBuilder()
{
Reset();
}
void CFunctionBuilder::Reset()
{
CVariablesBuilder::Reset();
isProcessRightPart = false;
isRightDirection = false;
acc.Empty();
leftPart.Empty();
emptyRules();
emptyStack();
}
void CFunctionBuilder::Export( CRulePtr& _firstRule )
{
// todo: check rule
if( !HasErrors() && static_cast<bool>( firstRule ) ) {
_firstRule.reset( firstRule.release() );
}
Reset();
}
void CFunctionBuilder::SetRightDirection()
{
isRightDirection = true;
}
void CFunctionBuilder::AddEndOfLeft()
{
if( isProcessRightPart ) {
error( EC_ThereAreMultiplePartsSeparatorInRules );
} else {
while( !balanceStack.empty() ) {
balanceStack.pop();
error( EC_UnclosedLeftParenInLeftPart );
}
if( HasErrors() ) {
acc.Empty();
} else {
acc.Move( leftPart );
}
isProcessRightPart = true;
}
}
void CFunctionBuilder::AddEndOfRight()
{
while( !balanceStack.empty() ) {
CUnitNode* unit = balanceStack.top();
balanceStack.pop();
error( unit->IsLeftParen() ? EC_UnclosedLeftParenInRightPart :
EC_UnclosedLeftBracketInRightPart );
}
if( !isProcessRightPart ) {
error( EC_ThereAreNoPartsSeparatorInRules );
}
if( HasErrors() ) {
acc.Empty();
CVariablesBuilder::Reset();
} else {
addRule();
}
isProcessRightPart = false;
}
void CFunctionBuilder::AddChar( TChar c )
{
if( !HasErrors() ) {
acc.AppendChar( c );
}
}
void CFunctionBuilder::AddLabel( TLabel label )
{
if( !HasErrors() ) {
acc.AppendLabel( label );
}
}
void CFunctionBuilder::AddNumber( TNumber number )
{
if( !HasErrors() ) {
acc.AppendNumber( number );
}
}
void CFunctionBuilder::AddVariable( TVariableTypeTag type, TVariableName name,
CQualifier* qualifier )
{
const TVariableIndex index = isProcessRightPart ?
CVariablesBuilder::AddRight( name, type ) :
CVariablesBuilder::AddLeft( name, type );
if( !HasErrors() ) {
assert( index != InvalidVariableIndex );
if( qualifier != nullptr ) {
CVariablesBuilder::AddQualifier( index, *qualifier );
}
acc.AppendVariable( index );
}
}
void CFunctionBuilder::AddLeftParen()
{
balanceStack.push( acc.AppendLeftParen() );
}
void CFunctionBuilder::AddRightParen()
{
CUnitNode* leftParen = nullptr;
if( !balanceStack.empty() ) {
leftParen = balanceStack.top();
}
if( leftParen != nullptr && leftParen->IsLeftParen() ) {
leftParen->PairedParen() = acc.AppendRightParen(leftParen);
balanceStack.pop();
} else {
error( EC_RightParenDoesNotMatchLeftParen );
}
}
void CFunctionBuilder::AddLeftBracket()
{
if( isProcessRightPart ) {
balanceStack.push( acc.AppendLeftBracket() );
} else {
error( EC_IllegalLeftBracketInLeftPart );
}
}
void CFunctionBuilder::AddRightBracket()
{
if( isProcessRightPart ) {
CUnitNode* leftBracket = nullptr;
if( !balanceStack.empty() ) {
leftBracket = balanceStack.top();
}
if( leftBracket != nullptr && leftBracket->IsLeftBracket() ) {
leftBracket->PairedParen() = acc.AppendRightBracket(leftBracket);
balanceStack.pop();
} else {
error( EC_RightBracketDoesNotMatchLeftBracket );
}
} else {
error( EC_IllegalRightBracketInLeftPart );
}
}
const char* CFunctionBuilder::getErrorMessage( TErrorCode errorCode )
{
switch( errorCode ) {
case EC_IllegalLeftBracketInLeftPart:
return "illegal left bracket in left part of rule";
case EC_IllegalRightBracketInLeftPart:
return "illegal right bracket in left part of rule";
case EC_RightParenDoesNotMatchLeftParen:
return "right paren does not match left paren";
case EC_RightBracketDoesNotMatchLeftBracket:
return "right bracket does not match left bracket";
case EC_UnclosedLeftParenInLeftPart:
return "unclosed left paren in left part of rule";
case EC_UnclosedLeftParenInRightPart:
return "unclosed left paren in right part of rule";
case EC_UnclosedLeftBracketInRightPart:
return "unclosed left bracket in right part of rule";
case EC_ThereAreMultiplePartsSeparatorInRules:
return "there are multiple parts separator in rule";
case EC_ThereAreNoPartsSeparatorInRules:
return "there are no parts separator in rule";
}
assert( false );
return nullptr;
}
void CFunctionBuilder::error( TErrorCode errorCode )
{
CErrorsHelper::RaiseError( ES_Error, getErrorMessage( errorCode ) );
}
void CFunctionBuilder::emptyStack()
{
std::stack<CUnitNode*> emptyStack;
std::swap( balanceStack, emptyStack );
}
void CFunctionBuilder::emptyRules()
{
firstRule.reset();
lastRule = nullptr;
}
void CFunctionBuilder::addRule()
{
if( static_cast<bool>( firstRule ) ) {
lastRule->NextRule.reset( new CRule );
lastRule = lastRule->NextRule.get();
} else {
firstRule.reset( new CRule );
lastRule = firstRule.get();
}
lastRule->RightMatching = isRightDirection;
leftPart.Move( lastRule->Left );
acc.Move( lastRule->Right );
CVariablesBuilder::Export( lastRule->Variables );
}
//-----------------------------------------------------------------------------
} // end of namespace refal2
<commit_msg>fix bug with right matching direction always in function after first R<commit_after>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
class CRulePrintHelper : public CPrintHelper {
public:
CRulePrintHelper( const CPrintHelper& _printHelper,
const CVariables& _variables ) :
printHelper( _printHelper ),
variables( _variables )
{
}
virtual void Variable( std::ostream& outputStream,
const TVariableIndex variable ) const
{
outputStream << variables.GetVariable( variable ).GetType();
variables.GetVariable( variable ).GetQualifier().Print( outputStream,
printHelper );
}
virtual void Label( std::ostream& outputStream,
const TLabel label ) const
{
printHelper.Label( outputStream, label );
}
private:
const CPrintHelper& printHelper;
const CVariables& variables;
};
void CRule::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
CRulePrintHelper rulePrintHelper( printHelper, Variables );
outputStream << "\t" << ( RightMatching ? "R" : "" ) << " ";
Left.Print( outputStream, rulePrintHelper );
outputStream << "= ";
Right.Print( outputStream, printHelper );
}
void CRule::Compile( CFunctionCompiler& compiler ) const
{
compiler.CompileRule( const_cast<CRule&>( *this ) );
}
//-----------------------------------------------------------------------------
CPreparatoryFunction::CPreparatoryFunction( const CToken& _nameToken ):
type( PFT_Declared ),
entry( false ),
name( _nameToken.word ),
nameToken( _nameToken ),
firstOperation( nullptr )
{
assert( !name.empty() );
MakeLower( name );
}
const std::string& CPreparatoryFunction::ExternalName() const
{
assert( IsEntry() || IsExternal() );
return externalName;
}
const CToken& CPreparatoryFunction::ExternalNameToken() const
{
assert( IsEntry() || IsExternal() );
return externalNameToken;
}
const CRule* CPreparatoryFunction::FirstRule() const
{
assert( IsOrdinary() );
return firstRule.get();
}
TOperationAddress CPreparatoryFunction::FirstOperation() const
{
assert( IsCompiled() );
return firstOperation;
}
void CPreparatoryFunction::SetDefined( const CToken& _nameToken )
{
assert( _nameToken.type == TT_Word );
assert( CompareNoCase( nameToken.word, _nameToken.word ) );
assert( type == PFT_Declared );
type = PFT_Defined;
nameToken = _nameToken;
}
void CPreparatoryFunction::SetOrdinary( CRulePtr& _firstRule )
{
assert( type == PFT_Defined );
assert( static_cast<bool>( _firstRule ) );
type = PFT_Ordinary;
firstRule.reset( _firstRule.release() );
}
void CPreparatoryFunction::SetEmpty()
{
assert( type == PFT_Defined );
type = PFT_Empty;
}
void CPreparatoryFunction::SetEntry( const CToken& _externalNameToken )
{
assert( type != PFT_External );
entry = true;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::SetExternal( const CToken& _externalNameToken )
{
assert( !entry );
assert( type == PFT_Defined );
type = PFT_External;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::Compile( CFunctionCompiler& compiler )
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Compile( compiler );
rule = rule->NextRule.get();
}
type = PFT_Compiled;
firstOperation = compiler.FinalizeCompilation();
assert( firstOperation != nullptr );
}
void CPreparatoryFunction::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Print( outputStream, printHelper );
outputStream << std::endl;
rule = rule->NextRule.get();
}
}
void CPreparatoryFunction::setExternalName( const CToken& _externalNameToken )
{
assert( ( entry && !IsExternal() ) || ( !entry && IsExternal() ) );
externalNameToken = _externalNameToken;
externalName = externalNameToken.word;
assert( !externalName.empty() );
MakeLower( externalName );
}
//-----------------------------------------------------------------------------
CFunctionBuilder::CFunctionBuilder( IErrorHandler* errorHandler ):
CVariablesBuilder( errorHandler ),
isProcessRightPart( false ),
isRightDirection( false ),
lastRule( nullptr )
{
}
CFunctionBuilder::~CFunctionBuilder()
{
Reset();
}
void CFunctionBuilder::Reset()
{
CVariablesBuilder::Reset();
isProcessRightPart = false;
isRightDirection = false;
acc.Empty();
leftPart.Empty();
emptyRules();
emptyStack();
}
void CFunctionBuilder::Export( CRulePtr& _firstRule )
{
// todo: check rule
if( !HasErrors() && static_cast<bool>( firstRule ) ) {
_firstRule.reset( firstRule.release() );
}
Reset();
}
void CFunctionBuilder::SetRightDirection()
{
isRightDirection = true;
}
void CFunctionBuilder::AddEndOfLeft()
{
if( isProcessRightPart ) {
error( EC_ThereAreMultiplePartsSeparatorInRules );
} else {
while( !balanceStack.empty() ) {
balanceStack.pop();
error( EC_UnclosedLeftParenInLeftPart );
}
if( HasErrors() ) {
acc.Empty();
} else {
acc.Move( leftPart );
}
isProcessRightPart = true;
}
}
void CFunctionBuilder::AddEndOfRight()
{
while( !balanceStack.empty() ) {
CUnitNode* unit = balanceStack.top();
balanceStack.pop();
error( unit->IsLeftParen() ? EC_UnclosedLeftParenInRightPart :
EC_UnclosedLeftBracketInRightPart );
}
if( !isProcessRightPart ) {
error( EC_ThereAreNoPartsSeparatorInRules );
}
if( HasErrors() ) {
acc.Empty();
CVariablesBuilder::Reset();
} else {
addRule();
}
isRightDirection = false; // reset right direction flag
isProcessRightPart = false;
}
void CFunctionBuilder::AddChar( TChar c )
{
if( !HasErrors() ) {
acc.AppendChar( c );
}
}
void CFunctionBuilder::AddLabel( TLabel label )
{
if( !HasErrors() ) {
acc.AppendLabel( label );
}
}
void CFunctionBuilder::AddNumber( TNumber number )
{
if( !HasErrors() ) {
acc.AppendNumber( number );
}
}
void CFunctionBuilder::AddVariable( TVariableTypeTag type, TVariableName name,
CQualifier* qualifier )
{
const TVariableIndex index = isProcessRightPart ?
CVariablesBuilder::AddRight( name, type ) :
CVariablesBuilder::AddLeft( name, type );
if( !HasErrors() ) {
assert( index != InvalidVariableIndex );
if( qualifier != nullptr ) {
CVariablesBuilder::AddQualifier( index, *qualifier );
}
acc.AppendVariable( index );
}
}
void CFunctionBuilder::AddLeftParen()
{
balanceStack.push( acc.AppendLeftParen() );
}
void CFunctionBuilder::AddRightParen()
{
CUnitNode* leftParen = nullptr;
if( !balanceStack.empty() ) {
leftParen = balanceStack.top();
}
if( leftParen != nullptr && leftParen->IsLeftParen() ) {
leftParen->PairedParen() = acc.AppendRightParen(leftParen);
balanceStack.pop();
} else {
error( EC_RightParenDoesNotMatchLeftParen );
}
}
void CFunctionBuilder::AddLeftBracket()
{
if( isProcessRightPart ) {
balanceStack.push( acc.AppendLeftBracket() );
} else {
error( EC_IllegalLeftBracketInLeftPart );
}
}
void CFunctionBuilder::AddRightBracket()
{
if( isProcessRightPart ) {
CUnitNode* leftBracket = nullptr;
if( !balanceStack.empty() ) {
leftBracket = balanceStack.top();
}
if( leftBracket != nullptr && leftBracket->IsLeftBracket() ) {
leftBracket->PairedParen() = acc.AppendRightBracket(leftBracket);
balanceStack.pop();
} else {
error( EC_RightBracketDoesNotMatchLeftBracket );
}
} else {
error( EC_IllegalRightBracketInLeftPart );
}
}
const char* CFunctionBuilder::getErrorMessage( TErrorCode errorCode )
{
switch( errorCode ) {
case EC_IllegalLeftBracketInLeftPart:
return "illegal left bracket in left part of rule";
case EC_IllegalRightBracketInLeftPart:
return "illegal right bracket in left part of rule";
case EC_RightParenDoesNotMatchLeftParen:
return "right paren does not match left paren";
case EC_RightBracketDoesNotMatchLeftBracket:
return "right bracket does not match left bracket";
case EC_UnclosedLeftParenInLeftPart:
return "unclosed left paren in left part of rule";
case EC_UnclosedLeftParenInRightPart:
return "unclosed left paren in right part of rule";
case EC_UnclosedLeftBracketInRightPart:
return "unclosed left bracket in right part of rule";
case EC_ThereAreMultiplePartsSeparatorInRules:
return "there are multiple parts separator in rule";
case EC_ThereAreNoPartsSeparatorInRules:
return "there are no parts separator in rule";
}
assert( false );
return nullptr;
}
void CFunctionBuilder::error( TErrorCode errorCode )
{
CErrorsHelper::RaiseError( ES_Error, getErrorMessage( errorCode ) );
}
void CFunctionBuilder::emptyStack()
{
std::stack<CUnitNode*> emptyStack;
std::swap( balanceStack, emptyStack );
}
void CFunctionBuilder::emptyRules()
{
firstRule.reset();
lastRule = nullptr;
}
void CFunctionBuilder::addRule()
{
if( static_cast<bool>( firstRule ) ) {
lastRule->NextRule.reset( new CRule );
lastRule = lastRule->NextRule.get();
} else {
firstRule.reset( new CRule );
lastRule = firstRule.get();
}
lastRule->RightMatching = isRightDirection;
leftPart.Move( lastRule->Left );
acc.Move( lastRule->Right );
CVariablesBuilder::Export( lastRule->Variables );
}
//-----------------------------------------------------------------------------
} // end of namespace refal2
<|endoftext|> |
<commit_before>#include <memory>
#include <utility>
#include "Command.h"
#include "Microphone.h"
#include "PocketsphinxWrapper.h"
#include "Recognizer.h"
#include "XCopilot.h"
#include "XPlaneDataRefSDKStub.h"
#include <iostream>
int main(int argc, char *argv[]) {
XPlaneDataRefSDKStub xplaneSDK;
std::unique_ptr<Microphone> microphone = std::make_unique<Microphone>();
std::unique_ptr<Pocketsphinx> pocketsphinx = std::make_unique<Pocketsphinx>();
std::unique_ptr<Recognizer> recognizer = std::make_unique<Recognizer>(std::move(pocketsphinx), std::move(microphone));
XCopilot xcopilot(std::move(recognizer));
Command command("Test Command", "^set altitude ((?:(?:\\\\d|zero|one|two|three|four|five|six|seven|eight|nine)\\\\s?){3,5})$", "set/altitude", &xplaneSDK);
xcopilot.addCommand(&command);
xcopilot.enable();
xcopilot.configureForAircraft("", "", "");
std::cout << "Listening..." << std::endl;
while(!xcopilot.hasCommands()) {}
xcopilot.executePendingCommands();
xcopilot.disable();
return 0;
}
<commit_msg>fix demo project<commit_after>#include <memory>
#include <utility>
#include "Command.h"
#include "Microphone.h"
#include "PocketsphinxWrapper.h"
#include "Recognizer.h"
#include "XCopilot.h"
#include "XPlaneDataRefSDKStub.h"
#include <iostream>
int main(int argc, char *argv[]) {
XPlaneDataRefSDKStub xplaneSDK;
std::unique_ptr<Microphone> microphone = std::make_unique<Microphone>();
std::unique_ptr<Pocketsphinx> pocketsphinx = std::make_unique<Pocketsphinx>();
std::unique_ptr<Recognizer> recognizer = std::make_unique<Recognizer>(std::move(pocketsphinx), std::move(microphone));
XCopilot xcopilot(std::move(recognizer));
Command command("Test Command", "^set altitude ((?:(?:\\\\d|zero|one|two|three|four|five|six|seven|eight|nine)\\\\s?){3,5})$", {"set/altitude"}, &xplaneSDK);
xcopilot.addCommand(&command);
xcopilot.enable();
xcopilot.configureForAircraft("", "", "");
std::cout << "Listening..." << std::endl;
while(!xcopilot.hasCommands()) {}
xcopilot.executePendingCommands();
xcopilot.disable();
return 0;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Rice University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Rice University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Mark Moll */
#include <ompl/base/SpaceInformation.h>
#include <ompl/base/spaces/SE3StateSpace.h>
#include <ompl/base/samplers/ObstacleBasedValidStateSampler.h>
#include <ompl/geometric/planners/prm/PRM.h>
#include <ompl/geometric/SimpleSetup.h>
#include <ompl/config.h>
#include <iostream>
namespace ob = ompl::base;
namespace og = ompl::geometric;
/// @cond IGNORE
// This is a problem-specific sampler that automatically generates valid
// states; it doesn't need to call SpaceInformation::isValid. This is an
// example of constrained sampling. If you can explicitly describe the set valid
// states and can draw samples from it, then this is typically much more
// efficient than generating random samples from the entire state space and
// checking for validity.
class MyValidStateSampler : public ob::ValidStateSampler
{
public:
MyValidStateSampler(const ob::SpaceInformation *si) : ValidStateSampler(si)
{
name_ = "my sampler";
}
// Generate a sample in the valid part of the R^3 state space
// Valid states satisfy the following constraints:
// -1<= x,y,z <=1
// if .25 <= z <= .5, then |x|>.8 and |y|>.8
virtual bool sample(ob::State *state)
{
double* val = static_cast<ob::RealVectorStateSpace::StateType*>(state)->values;
double z = rng_.uniformReal(-1,1);
if (z>.25 && z<.5)
{
double x = rng_.uniformReal(0,1.8), y = rng_.uniformReal(0,.2);
switch(rng_.uniformInt(0,3))
{
case 0: val[0]=x-1; val[1]=y-1;
case 1: val[0]=x-.8; val[1]=y+.8;
case 2: val[0]=y-1; val[1]=x-1;
case 3: val[0]=y+.8; val[1]=x-.8;
}
}
else
{
val[0] = rng_.uniformReal(-1,1);
val[1] = rng_.uniformReal(-1,1);
}
val[2] = z;
assert(si_->isValid(state));
return true;
}
// We don't need this in the example below.
virtual bool sampleNear(ob::State*, const ob::State*, const double)
{
throw ompl::Exception("MyValidStateSampler::sampleNear", "not implemented");
return false;
}
protected:
ompl::RNG rng_;
};
/// @endcond
// this function is needed, even when we can write a sampler like the one
// above, because we need to check path segments for validity
bool isStateValid(const ob::State *state)
{
const ob::RealVectorStateSpace::StateType& pos = *state->as<ob::RealVectorStateSpace::StateType>();
// Let's pretend that the validity check is computationally relatively
// expensive to emphasize the benefit of explicitly generating valid
// samples
std::this_thread::sleep_for(ompl::time::seconds(.0005));
// Valid states satisfy the following constraints:
// -1<= x,y,z <=1
// if .25 <= z <= .5, then |x|>.8 and |y|>.8
return !(fabs(pos[0])<.8 && fabs(pos[1])<.8 && pos[2]>.25 && pos[2]<.5);
}
// return an obstacle-based sampler
ob::ValidStateSamplerPtr allocOBValidStateSampler(const ob::SpaceInformation *si)
{
// we can perform any additional setup / configuration of a sampler here,
// but there is nothing to tweak in case of the ObstacleBasedValidStateSampler.
return ob::ValidStateSamplerPtr(new ob::ObstacleBasedValidStateSampler(si));
}
// return an instance of my sampler
ob::ValidStateSamplerPtr allocMyValidStateSampler(const ob::SpaceInformation *si)
{
return ob::ValidStateSamplerPtr(new MyValidStateSampler(si));
}
void plan(int samplerIndex)
{
// construct the state space we are planning in
ob::StateSpacePtr space(new ob::RealVectorStateSpace(3));
// set the bounds
ob::RealVectorBounds bounds(3);
bounds.setLow(-1);
bounds.setHigh(1);
space->as<ob::RealVectorStateSpace>()->setBounds(bounds);
// define a simple setup class
og::SimpleSetup ss(space);
// set state validity checking for this space
ss.setStateValidityChecker(std::bind(&isStateValid, std::placeholders::_1));
// create a start state
ob::ScopedState<> start(space);
start[0] = start[1] = start[2] = 0;
// create a goal state
ob::ScopedState<> goal(space);
goal[0] = goal[1] = 0.;
goal[2] = 1;
// set the start and goal states
ss.setStartAndGoalStates(start, goal);
// set sampler (optional; the default is uniform sampling)
if (samplerIndex==1)
// use obstacle-based sampling
ss.getSpaceInformation()->setValidStateSamplerAllocator(allocOBValidStateSampler);
else if (samplerIndex==2)
// use my sampler
ss.getSpaceInformation()->setValidStateSamplerAllocator(allocMyValidStateSampler);
// create a planner for the defined space
ob::PlannerPtr planner(new og::PRM(ss.getSpaceInformation()));
ss.setPlanner(planner);
// attempt to solve the problem within ten seconds of planning time
ob::PlannerStatus solved = ss.solve(10.0);
if (solved)
{
std::cout << "Found solution:" << std::endl;
// print the path to screen
ss.getSolutionPath().print(std::cout);
}
else
std::cout << "No solution found" << std::endl;
}
int main(int, char **)
{
std::cout << "Using default uniform sampler:" << std::endl;
plan(0);
std::cout << "\nUsing obstacle-based sampler:" << std::endl;
plan(1);
std::cout << "\nUsing my sampler:" << std::endl;
plan(2);
return 0;
}
<commit_msg>missing include<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Rice University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Rice University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Mark Moll */
#include <ompl/base/SpaceInformation.h>
#include <ompl/base/spaces/SE3StateSpace.h>
#include <ompl/base/samplers/ObstacleBasedValidStateSampler.h>
#include <ompl/geometric/planners/prm/PRM.h>
#include <ompl/geometric/SimpleSetup.h>
#include <ompl/config.h>
#include <iostream>
#include <thread>
namespace ob = ompl::base;
namespace og = ompl::geometric;
/// @cond IGNORE
// This is a problem-specific sampler that automatically generates valid
// states; it doesn't need to call SpaceInformation::isValid. This is an
// example of constrained sampling. If you can explicitly describe the set valid
// states and can draw samples from it, then this is typically much more
// efficient than generating random samples from the entire state space and
// checking for validity.
class MyValidStateSampler : public ob::ValidStateSampler
{
public:
MyValidStateSampler(const ob::SpaceInformation *si) : ValidStateSampler(si)
{
name_ = "my sampler";
}
// Generate a sample in the valid part of the R^3 state space
// Valid states satisfy the following constraints:
// -1<= x,y,z <=1
// if .25 <= z <= .5, then |x|>.8 and |y|>.8
virtual bool sample(ob::State *state)
{
double* val = static_cast<ob::RealVectorStateSpace::StateType*>(state)->values;
double z = rng_.uniformReal(-1,1);
if (z>.25 && z<.5)
{
double x = rng_.uniformReal(0,1.8), y = rng_.uniformReal(0,.2);
switch(rng_.uniformInt(0,3))
{
case 0: val[0]=x-1; val[1]=y-1;
case 1: val[0]=x-.8; val[1]=y+.8;
case 2: val[0]=y-1; val[1]=x-1;
case 3: val[0]=y+.8; val[1]=x-.8;
}
}
else
{
val[0] = rng_.uniformReal(-1,1);
val[1] = rng_.uniformReal(-1,1);
}
val[2] = z;
assert(si_->isValid(state));
return true;
}
// We don't need this in the example below.
virtual bool sampleNear(ob::State*, const ob::State*, const double)
{
throw ompl::Exception("MyValidStateSampler::sampleNear", "not implemented");
return false;
}
protected:
ompl::RNG rng_;
};
/// @endcond
// this function is needed, even when we can write a sampler like the one
// above, because we need to check path segments for validity
bool isStateValid(const ob::State *state)
{
const ob::RealVectorStateSpace::StateType& pos = *state->as<ob::RealVectorStateSpace::StateType>();
// Let's pretend that the validity check is computationally relatively
// expensive to emphasize the benefit of explicitly generating valid
// samples
std::this_thread::sleep_for(ompl::time::seconds(.0005));
// Valid states satisfy the following constraints:
// -1<= x,y,z <=1
// if .25 <= z <= .5, then |x|>.8 and |y|>.8
return !(fabs(pos[0])<.8 && fabs(pos[1])<.8 && pos[2]>.25 && pos[2]<.5);
}
// return an obstacle-based sampler
ob::ValidStateSamplerPtr allocOBValidStateSampler(const ob::SpaceInformation *si)
{
// we can perform any additional setup / configuration of a sampler here,
// but there is nothing to tweak in case of the ObstacleBasedValidStateSampler.
return ob::ValidStateSamplerPtr(new ob::ObstacleBasedValidStateSampler(si));
}
// return an instance of my sampler
ob::ValidStateSamplerPtr allocMyValidStateSampler(const ob::SpaceInformation *si)
{
return ob::ValidStateSamplerPtr(new MyValidStateSampler(si));
}
void plan(int samplerIndex)
{
// construct the state space we are planning in
ob::StateSpacePtr space(new ob::RealVectorStateSpace(3));
// set the bounds
ob::RealVectorBounds bounds(3);
bounds.setLow(-1);
bounds.setHigh(1);
space->as<ob::RealVectorStateSpace>()->setBounds(bounds);
// define a simple setup class
og::SimpleSetup ss(space);
// set state validity checking for this space
ss.setStateValidityChecker(std::bind(&isStateValid, std::placeholders::_1));
// create a start state
ob::ScopedState<> start(space);
start[0] = start[1] = start[2] = 0;
// create a goal state
ob::ScopedState<> goal(space);
goal[0] = goal[1] = 0.;
goal[2] = 1;
// set the start and goal states
ss.setStartAndGoalStates(start, goal);
// set sampler (optional; the default is uniform sampling)
if (samplerIndex==1)
// use obstacle-based sampling
ss.getSpaceInformation()->setValidStateSamplerAllocator(allocOBValidStateSampler);
else if (samplerIndex==2)
// use my sampler
ss.getSpaceInformation()->setValidStateSamplerAllocator(allocMyValidStateSampler);
// create a planner for the defined space
ob::PlannerPtr planner(new og::PRM(ss.getSpaceInformation()));
ss.setPlanner(planner);
// attempt to solve the problem within ten seconds of planning time
ob::PlannerStatus solved = ss.solve(10.0);
if (solved)
{
std::cout << "Found solution:" << std::endl;
// print the path to screen
ss.getSolutionPath().print(std::cout);
}
else
std::cout << "No solution found" << std::endl;
}
int main(int, char **)
{
std::cout << "Using default uniform sampler:" << std::endl;
plan(0);
std::cout << "\nUsing obstacle-based sampler:" << std::endl;
plan(1);
std::cout << "\nUsing my sampler:" << std::endl;
plan(2);
return 0;
}
<|endoftext|> |
<commit_before>#include <bitcoin/deterministic_wallet.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <openssl/ec.h>
#include <openssl/obj_mac.h>
#include <openssl/sha.h>
#include <bitcoin/constants.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/utility/assert.hpp>
#include <bitcoin/utility/sha256.hpp>
namespace libbitcoin {
template <typename ssl_type>
struct ssl_wrapper
{
ssl_wrapper(ssl_type* obj)
: obj(obj) {}
virtual ~ssl_wrapper()
{
}
operator ssl_type*()
{
return obj;
}
ssl_type* obj;
};
struct ssl_bignum
: public ssl_wrapper<BIGNUM>
{
ssl_bignum()
: ssl_wrapper(BN_new()) {}
~ssl_bignum()
{
BN_free(obj);
}
};
#define SSL_TYPE(name, ssl_type, free_func) \
struct name \
: public ssl_wrapper<ssl_type> \
{ \
name(ssl_type* obj) \
: ssl_wrapper(obj) {} \
~name() \
{ \
free_func(obj); \
} \
};
SSL_TYPE(ec_group, EC_GROUP, EC_GROUP_free)
SSL_TYPE(ec_point, EC_POINT, EC_POINT_free)
SSL_TYPE(bn_ctx, BN_CTX, BN_CTX_free)
const std::string bignum_hex(BIGNUM* bn)
{
char* repr = BN_bn2hex(bn);
std::string result = repr;
OPENSSL_free(repr);
boost::algorithm::to_lower(result);
return result;
}
const data_chunk bignum_data(BIGNUM* bn)
{
data_chunk result(BN_num_bytes(bn));
BN_bn2bin(bn, result.data());
return result;
}
void deterministic_wallet::new_seed()
{
constexpr size_t bits_needed = 8 * seed_size / 2;
ssl_bignum rand_value;
BN_rand(rand_value, bits_needed, 0, 0);
bool set_success = set_seed(bignum_hex(rand_value));
BITCOIN_ASSERT(set_success);
}
secret_parameter stretch_seed(const std::string& seed)
{
BITCOIN_ASSERT(seed.size() == deterministic_wallet::seed_size);
secret_parameter stretched;
std::copy(seed.begin(), seed.end(), stretched.begin());
secret_parameter oldseed = stretched;
for (size_t i = 0; i < 100000; ++i)
{
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, stretched.data(), stretched.size());
SHA256_Update(&ctx, oldseed.data(), oldseed.size());
SHA256_Final(stretched.data(), &ctx);
}
return stretched;
}
data_chunk pubkey_from_secret(const secret_parameter& secret)
{
elliptic_curve_key privkey;
if (!privkey.set_secret(secret))
return data_chunk();
return privkey.public_key();
}
bool deterministic_wallet::set_seed(std::string seed)
{
// Trim spaces and newlines around the string.
boost::algorithm::trim(seed);
if (seed.size() != seed_size)
return false;
seed_ = seed;
stretched_seed_ = stretch_seed(seed);
master_public_key_ = pubkey_from_secret(stretched_seed_);
// Snip the beginning 04 byte for compat reasons.
master_public_key_.erase(master_public_key_.begin());
if (master_public_key_.empty())
return false;
return true;
}
const std::string& deterministic_wallet::seed() const
{
return seed_;
}
bool deterministic_wallet::set_master_public_key(const data_chunk& mpk)
{
master_public_key_ = mpk;
return true;
}
const data_chunk& deterministic_wallet::master_public_key() const
{
return master_public_key_;
}
data_chunk deterministic_wallet::generate_public_key(
size_t n, bool for_change) const
{
hash_digest sequence = get_sequence(n, for_change);
ssl_bignum x, y, z;
BN_bin2bn(sequence.data(), sequence.size(), z);
BN_bin2bn(master_public_key_.data(), 32, x);
BN_bin2bn(master_public_key_.data() + 32, 32, y);
// Create a point.
ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1));
ec_point mpk(EC_POINT_new(group));
bn_ctx ctx(BN_CTX_new());
EC_POINT_set_affine_coordinates_GFp(group, mpk, x, y, ctx);
ec_point result(EC_POINT_new(group));
// result pubkey_point = mpk_pubkey_point + z*curve.generator
ssl_bignum one;
BN_one(one);
EC_POINT_mul(group, result, z, mpk, one, ctx);
// Create the actual public key.
EC_POINT_get_affine_coordinates_GFp(group, result, x, y, ctx);
// 04 + x + y
data_chunk raw_pubkey{0x04};
extend_data(raw_pubkey, bignum_data(x));
extend_data(raw_pubkey, bignum_data(y));
return raw_pubkey;
}
secret_parameter deterministic_wallet::generate_secret(
size_t n, bool for_change) const
{
if (seed_.empty())
return null_hash;
ssl_bignum z;
hash_digest sequence = get_sequence(n, for_change);
BN_bin2bn(sequence.data(), sequence.size(), z);
ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1));
ssl_bignum order;
bn_ctx ctx(BN_CTX_new());
EC_GROUP_get_order(group, order, ctx);
// secexp = (stretched_seed + z) % order
ssl_bignum secexp;
BN_bin2bn(stretched_seed_.data(), stretched_seed_.size(), secexp);
BN_add(secexp, secexp, z);
BN_mod(secexp, secexp, order, ctx);
secret_parameter secret;
int secexp_bytes_size = BN_num_bytes(secexp);
BITCOIN_ASSERT(secexp_bytes_size >= 0 &&
static_cast<size_t>(BN_num_bytes(secexp)) <= secret.size());
// If bignum value begins with 0x00, then
// SSL will skip to the first significant digit.
size_t copy_offset = secret.size() - BN_num_bytes(secexp);
BN_bn2bin(secexp, secret.data() + copy_offset);
// Zero out beginning 0x00 bytes (if they exist).
std::fill(secret.begin(), secret.begin() + copy_offset, 0x00);
return secret;
}
hash_digest deterministic_wallet::get_sequence(
size_t n, bool for_change) const
{
data_chunk chunk;
extend_data(chunk, std::to_string(n));
chunk.push_back(':');
chunk.push_back(for_change ? '1' : '0');
chunk.push_back(':');
extend_data(chunk, master_public_key_);
hash_digest result = generate_sha256_hash(chunk);
std::reverse(result.begin(), result.end());
return result;
}
} // namespace libbitcoin
<commit_msg>Fixes issue when generating pub key.<commit_after>#include <bitcoin/deterministic_wallet.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <openssl/ec.h>
#include <openssl/obj_mac.h>
#include <openssl/sha.h>
#include <bitcoin/constants.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/utility/assert.hpp>
#include <bitcoin/utility/sha256.hpp>
namespace libbitcoin {
template <typename ssl_type>
struct ssl_wrapper
{
ssl_wrapper(ssl_type* obj)
: obj(obj) {}
virtual ~ssl_wrapper()
{
}
operator ssl_type*()
{
return obj;
}
ssl_type* obj;
};
struct ssl_bignum
: public ssl_wrapper<BIGNUM>
{
ssl_bignum()
: ssl_wrapper(BN_new()) {}
~ssl_bignum()
{
BN_free(obj);
}
};
#define SSL_TYPE(name, ssl_type, free_func) \
struct name \
: public ssl_wrapper<ssl_type> \
{ \
name(ssl_type* obj) \
: ssl_wrapper(obj) {} \
~name() \
{ \
free_func(obj); \
} \
};
SSL_TYPE(ec_group, EC_GROUP, EC_GROUP_free)
SSL_TYPE(ec_point, EC_POINT, EC_POINT_free)
SSL_TYPE(bn_ctx, BN_CTX, BN_CTX_free)
const std::string bignum_hex(BIGNUM* bn)
{
char* repr = BN_bn2hex(bn);
std::string result = repr;
OPENSSL_free(repr);
boost::algorithm::to_lower(result);
return result;
}
const data_chunk bignum_data(BIGNUM* bn)
{
data_chunk result(32);
size_t copy_offset = result.size() - BN_num_bytes(bn);
BN_bn2bin(bn, result.data() + copy_offset);
// Zero out beginning 0x00 bytes (if they exist).
std::fill(result.begin(), result.begin() + copy_offset, 0x00);
return result;
}
void deterministic_wallet::new_seed()
{
constexpr size_t bits_needed = 8 * seed_size / 2;
ssl_bignum rand_value;
BN_rand(rand_value, bits_needed, 0, 0);
bool set_success = set_seed(bignum_hex(rand_value));
BITCOIN_ASSERT(set_success);
}
secret_parameter stretch_seed(const std::string& seed)
{
BITCOIN_ASSERT(seed.size() == deterministic_wallet::seed_size);
secret_parameter stretched;
std::copy(seed.begin(), seed.end(), stretched.begin());
secret_parameter oldseed = stretched;
for (size_t i = 0; i < 100000; ++i)
{
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, stretched.data(), stretched.size());
SHA256_Update(&ctx, oldseed.data(), oldseed.size());
SHA256_Final(stretched.data(), &ctx);
}
return stretched;
}
data_chunk pubkey_from_secret(const secret_parameter& secret)
{
elliptic_curve_key privkey;
if (!privkey.set_secret(secret))
return data_chunk();
return privkey.public_key();
}
bool deterministic_wallet::set_seed(std::string seed)
{
// Trim spaces and newlines around the string.
boost::algorithm::trim(seed);
if (seed.size() != seed_size)
return false;
seed_ = seed;
stretched_seed_ = stretch_seed(seed);
master_public_key_ = pubkey_from_secret(stretched_seed_);
// Snip the beginning 04 byte for compat reasons.
master_public_key_.erase(master_public_key_.begin());
if (master_public_key_.empty())
return false;
return true;
}
const std::string& deterministic_wallet::seed() const
{
return seed_;
}
bool deterministic_wallet::set_master_public_key(const data_chunk& mpk)
{
master_public_key_ = mpk;
return true;
}
const data_chunk& deterministic_wallet::master_public_key() const
{
return master_public_key_;
}
data_chunk deterministic_wallet::generate_public_key(
size_t n, bool for_change) const
{
hash_digest sequence = get_sequence(n, for_change);
ssl_bignum x, y, z;
BN_bin2bn(sequence.data(), sequence.size(), z);
BN_bin2bn(master_public_key_.data(), 32, x);
BN_bin2bn(master_public_key_.data() + 32, 32, y);
// Create a point.
ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1));
ec_point mpk(EC_POINT_new(group));
bn_ctx ctx(BN_CTX_new());
EC_POINT_set_affine_coordinates_GFp(group, mpk, x, y, ctx);
ec_point result(EC_POINT_new(group));
// result pubkey_point = mpk_pubkey_point + z*curve.generator
ssl_bignum one;
BN_one(one);
EC_POINT_mul(group, result, z, mpk, one, ctx);
// Create the actual public key.
EC_POINT_get_affine_coordinates_GFp(group, result, x, y, ctx);
// 04 + x + y
data_chunk raw_pubkey{0x04};
extend_data(raw_pubkey, bignum_data(x));
extend_data(raw_pubkey, bignum_data(y));
return raw_pubkey;
}
secret_parameter deterministic_wallet::generate_secret(
size_t n, bool for_change) const
{
if (seed_.empty())
return null_hash;
ssl_bignum z;
hash_digest sequence = get_sequence(n, for_change);
BN_bin2bn(sequence.data(), sequence.size(), z);
ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1));
ssl_bignum order;
bn_ctx ctx(BN_CTX_new());
EC_GROUP_get_order(group, order, ctx);
// secexp = (stretched_seed + z) % order
ssl_bignum secexp;
BN_bin2bn(stretched_seed_.data(), stretched_seed_.size(), secexp);
BN_add(secexp, secexp, z);
BN_mod(secexp, secexp, order, ctx);
secret_parameter secret;
int secexp_bytes_size = BN_num_bytes(secexp);
BITCOIN_ASSERT(secexp_bytes_size >= 0 &&
static_cast<size_t>(BN_num_bytes(secexp)) <= secret.size());
// If bignum value begins with 0x00, then
// SSL will skip to the first significant digit.
size_t copy_offset = secret.size() - BN_num_bytes(secexp);
BN_bn2bin(secexp, secret.data() + copy_offset);
// Zero out beginning 0x00 bytes (if they exist).
std::fill(secret.begin(), secret.begin() + copy_offset, 0x00);
return secret;
}
hash_digest deterministic_wallet::get_sequence(
size_t n, bool for_change) const
{
data_chunk chunk;
extend_data(chunk, std::to_string(n));
chunk.push_back(':');
chunk.push_back(for_change ? '1' : '0');
chunk.push_back(':');
extend_data(chunk, master_public_key_);
hash_digest result = generate_sha256_hash(chunk);
std::reverse(result.begin(), result.end());
return result;
}
} // namespace libbitcoin
<|endoftext|> |
<commit_before>/*
* This file is part of openfx-arena <https://github.com/olear/openfx-arena>,
* Copyright (C) 2016 INRIA
*
* openfx-arena 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.
*
* openfx-arena 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 openfx-arena. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
*/
#include "ReadORA.h"
#include <iostream>
#include <stdint.h>
#include <zip.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <Magick++.h>
#include "GenericReader.h"
#include "GenericOCIO.h"
#include "ofxsMacros.h"
#ifdef OFX_IO_USING_OCIO
#include <OpenColorIO/OpenColorIO.h>
#endif
#define kPluginName "ReadORA"
#define kPluginGrouping "Image/Readers"
#define kPluginIdentifier "fr.inria.openfx.ReadORA"
#define kPluginVersionMajor 0
#define kPluginVersionMinor 1
#define kSupportsRGBA true
#define kSupportsRGB false
#define kSupportsAlpha false
#define kSupportsTiles false
// TODO error checking
std::string _extractXML(std::string oraFile)
{
std::string output;
int err = 0;
zip *oraOpen = zip_open(oraFile.c_str(), 0, &err);
const char *xmlName = "stack.xml";
struct zip_stat xmlSt;
zip_stat_init(&xmlSt);
zip_stat(oraOpen, xmlName, 0, &xmlSt);
char *xml = new char[xmlSt.size];
zip_file *xmlFile = zip_fopen(oraOpen, "stack.xml", 0);
zip_fread(xmlFile, xml, xmlSt.size);
zip_fclose(xmlFile);
zip_close(oraOpen);
xml[xmlSt.size] = '\0';
output = xml;
return output;
}
// TODO
void _getImageSize(int *width, int *height, std::string filename)
{
std::string xml = _extractXML(filename);
if (!xml.empty()) {
int imgW = 0;
int imgH = 0;
xmlDocPtr doc;
doc = xmlParseDoc((const xmlChar*)xml.c_str());
xmlNode *root_element = NULL;
xmlNode *cur_node = NULL;
root_element = xmlDocGetRootElement(doc);
for (cur_node = root_element; cur_node; cur_node = cur_node->next) {
if (cur_node->type == XML_ELEMENT_NODE) {
if ((!xmlStrcmp(cur_node->name,(const xmlChar*)"image"))) {
xmlChar *imgWchar;
xmlChar *imgHchar;
imgWchar = xmlGetProp(cur_node,(const xmlChar*)"w");
imgHchar = xmlGetProp(cur_node,(const xmlChar*)"h");
imgW = atoi((const char*)imgWchar);
imgH = atoi((const char*)imgHchar);
xmlFree(imgWchar);
xmlFree(imgHchar);
if (imgW>0 && imgH>0) {
(*width)=imgW;
(*height)=imgH;
}
}
}
}
xmlFreeDoc(doc);
}
}
class ReadORAPlugin : public GenericReaderPlugin
{
public:
ReadORAPlugin(OfxImageEffectHandle handle);
virtual ~ReadORAPlugin();
private:
virtual bool isVideoStream(const std::string& /*filename*/) OVERRIDE FINAL { return false; }
virtual void decode(const std::string& filename, OfxTime time, int view, bool isPlayback, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL;
virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error, int *tile_width, int *tile_height) OVERRIDE FINAL;
virtual void onInputFileChanged(const std::string& newFile, bool setColorSpace, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;
};
ReadORAPlugin::ReadORAPlugin(OfxImageEffectHandle handle)
: GenericReaderPlugin(handle, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles, false)
{
Magick::InitializeMagick(NULL);
}
ReadORAPlugin::~ReadORAPlugin()
{
}
void
ReadORAPlugin::decode(const std::string& filename,
OfxTime time,
int /*view*/,
bool /*isPlayback*/,
const OfxRectI& renderWindow,
float *pixelData,
const OfxRectI& bounds,
OFX::PixelComponentEnum /*pixelComponents*/,
int /*pixelComponentCount*/,
int /*rowBytes*/)
{
#ifdef DEBUG
std::cout << "decode ..." << std::endl;
#endif
// TODO!!!
Magick::Image image;
int width = 0;
int height = 0;
if (!filename.empty())
_getImageSize(&width,&height,filename);
if (width>0 && height>0) {
Magick::Image container(Magick::Geometry(bounds.x2,bounds.y2),Magick::Color("rgba(0,0,0,1)"));
//container.composite(image,0,0,Magick::OverCompositeOp);
//container.composite(image,0,0,Magick::CopyOpacityCompositeOp);
container.flip();
container.write(0,0,renderWindow.x2 - renderWindow.x1,renderWindow.y2 - renderWindow.y1,"RGBA",Magick::FloatPixel,pixelData);
}
else {
setPersistentMessage(OFX::Message::eMessageError, "", "Unable to read image");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
}
bool ReadORAPlugin::getFrameBounds(const std::string& filename,
OfxTime /*time*/,
OfxRectI *bounds,
double *par,
std::string* /*error*/,int *tile_width, int *tile_height)
{
#ifdef DEBUG
std::cout << "getFrameBounds ..." << std::endl;
#endif
int width = 0;
int height = 0;
_getImageSize(&width,&height,filename);
if (width>0 && height>0) {
bounds->x1 = 0;
bounds->x2 = width;
bounds->y1 = 0;
bounds->y2 = height;
*par = 1.0;
}
*tile_width = *tile_height = 0;
return true;
}
void ReadORAPlugin::onInputFileChanged(const std::string& newFile,
bool setColorSpace,
OFX::PreMultiplicationEnum *premult,
OFX::PixelComponentEnum *components,int */*componentCount*/)
{
#ifdef DEBUG
std::cout << "onInputFileChanged ..." << std::endl;
#endif
assert(premult && components);
int width = 0;
int height = 0;
_getImageSize(&width,&height,newFile);
if (width>0 && height>0) {
if (setColorSpace) {
# ifdef OFX_IO_USING_OCIO
_ocio->setInputColorspace("sRGB");
# endif // OFX_IO_USING_OCIO
}
}
else {
setPersistentMessage(OFX::Message::eMessageError, "", "Unable to read image");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
*components = OFX::ePixelComponentRGBA;
*premult = OFX::eImageOpaque;
}
using namespace OFX;
mDeclareReaderPluginFactory(ReadORAPluginFactory, {}, {}, false);
/** @brief The basic describe function, passed a plugin descriptor */
void ReadORAPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
GenericReaderDescribe(desc, kSupportsTiles, false);
desc.setLabel(kPluginName);
#ifdef OFX_EXTENSIONS_TUTTLE
const char* extensions[] = {"ora", NULL};
desc.addSupportedExtensions(extensions);
desc.setPluginEvaluation(50);
#endif
desc.setPluginDescription("Read ORA (OpenRaster) image format.");
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void ReadORAPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)
{
PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles);
GenericReaderDescribeInContextEnd(desc, context, page, "reference", "reference");
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* ReadORAPluginFactory::createInstance(OfxImageEffectHandle handle,
ContextEnum /*context*/)
{
ReadORAPlugin* ret = new ReadORAPlugin(handle);
ret->restoreStateFromParameters();
return ret;
}
void getReadORAPluginID(OFX::PluginFactoryArray &ids)
{
static ReadORAPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
<commit_msg>ReadORA: get layers specs, #212<commit_after>/*
* This file is part of openfx-arena <https://github.com/olear/openfx-arena>,
* Copyright (C) 2016 INRIA
*
* openfx-arena 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.
*
* openfx-arena 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 openfx-arena. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
*/
#include "ReadORA.h"
#include <iostream>
#include <stdint.h>
#include <zip.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <Magick++.h>
#include "GenericReader.h"
#include "GenericOCIO.h"
#include "ofxsMacros.h"
#ifdef OFX_IO_USING_OCIO
#include <OpenColorIO/OpenColorIO.h>
#endif
#define kPluginName "ReadORA"
#define kPluginGrouping "Image/Readers"
#define kPluginIdentifier "fr.inria.openfx.ReadORA"
#define kPluginVersionMajor 0
#define kPluginVersionMinor 1
#define kSupportsRGBA true
#define kSupportsRGB false
#define kSupportsAlpha false
#define kSupportsTiles false
std::string _extractXML(std::string oraFile)
{
std::string output;
int err = 0;
zip *oraOpen = zip_open(oraFile.c_str(), 0, &err);
const char *xmlName = "stack.xml";
struct zip_stat xmlSt;
zip_stat_init(&xmlSt);
err=zip_stat(oraOpen, xmlName, 0, &xmlSt);
if (err!=-1) {
char *xml = new char[xmlSt.size];
zip_file *xmlFile = zip_fopen(oraOpen, "stack.xml", 0);
err=zip_fread(xmlFile, xml, xmlSt.size);
if (err!=-1) {
zip_fclose(xmlFile);
xml[xmlSt.size] = '\0';
output = xml;
}
}
zip_close(oraOpen);
return output;
}
void _getImageSize(int *width, int *height, std::string filename)
{
std::string xml = _extractXML(filename);
if (!xml.empty()) {
int imgW = 0;
int imgH = 0;
xmlDocPtr doc;
doc = xmlParseDoc((const xmlChar*)xml.c_str());
xmlNode *root_element = NULL;
xmlNode *cur_node = NULL;
root_element = xmlDocGetRootElement(doc);
for (cur_node = root_element; cur_node; cur_node = cur_node->next) {
if (cur_node->type == XML_ELEMENT_NODE) {
if ((!xmlStrcmp(cur_node->name,(const xmlChar*)"image"))) {
xmlChar *imgWchar;
xmlChar *imgHchar;
imgWchar = xmlGetProp(cur_node,(const xmlChar*)"w");
imgHchar = xmlGetProp(cur_node,(const xmlChar*)"h");
imgW = atoi((const char*)imgWchar);
imgH = atoi((const char*)imgHchar);
xmlFree(imgWchar);
xmlFree(imgHchar);
if (imgW>0 && imgH>0) {
(*width)=imgW;
(*height)=imgH;
}
}
}
}
xmlFreeDoc(doc);
}
}
class ReadORAPlugin : public GenericReaderPlugin
{
public:
ReadORAPlugin(OfxImageEffectHandle handle);
virtual ~ReadORAPlugin();
private:
virtual bool isVideoStream(const std::string& /*filename*/) OVERRIDE FINAL { return false; }
virtual void decode(const std::string& filename, OfxTime time, int view, bool isPlayback, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL;
virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error, int *tile_width, int *tile_height) OVERRIDE FINAL;
virtual void onInputFileChanged(const std::string& newFile, bool setColorSpace, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;
void setupImage(std::string filename);
void getLayersInfo(xmlNode *node);
std::vector<Magick::Image> _image;
std::vector<std::vector<std::string> > _layersInfo;
};
ReadORAPlugin::ReadORAPlugin(OfxImageEffectHandle handle)
: GenericReaderPlugin(handle, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles, false)
{
Magick::InitializeMagick(NULL);
}
ReadORAPlugin::~ReadORAPlugin()
{
}
void
ReadORAPlugin::getLayersInfo(xmlNode *node)
{
xmlNode *cur_node = NULL;
for (cur_node = node; cur_node; cur_node = cur_node->next) {
if (cur_node->type == XML_ELEMENT_NODE) {
if ((!xmlStrcmp(cur_node->name, (const xmlChar *)"layer"))) {
std::vector<std::string> layerInfo;
xmlChar *xmlLayerName;
xmlChar *xmlOpacity;
xmlChar *xmlVisibility;
xmlChar *xmlComposite;
xmlChar *xmlPng;
xmlChar *xmlOffsetX;
xmlChar *xmlOffsetY;
xmlLayerName = xmlGetProp(cur_node, (const xmlChar *)"name");
xmlOpacity = xmlGetProp(cur_node, (const xmlChar *)"opacity");
xmlVisibility = xmlGetProp(cur_node, (const xmlChar *)"visibility");
xmlComposite = xmlGetProp(cur_node, (const xmlChar *)"composite-op");
xmlPng = xmlGetProp(cur_node, (const xmlChar *)"src");
xmlOffsetX = xmlGetProp(cur_node, (const xmlChar *)"x");
xmlOffsetY = xmlGetProp(cur_node, (const xmlChar *)"y");
std::string layerName,layerOpacity,layerVisibility,layerComposite,layerFile,layerOffsetX,layerOffsetY;
if (xmlLayerName!=NULL)
layerName=(reinterpret_cast<char*>(xmlLayerName));
if (xmlOpacity!=NULL)
layerOpacity=(reinterpret_cast<char*>(xmlOpacity));
if (xmlVisibility!=NULL)
layerVisibility=(reinterpret_cast<char*>(xmlVisibility));
if (xmlComposite!=NULL)
layerComposite=(reinterpret_cast<char*>(xmlComposite));
if (xmlPng!=NULL)
layerFile=(reinterpret_cast<char*>(xmlPng));
if (xmlOffsetX!=NULL)
layerOffsetX=(reinterpret_cast<char*>(xmlOffsetX));
if (xmlOffsetY!=NULL)
layerOffsetY=(reinterpret_cast<char*>(xmlOffsetY));
xmlFree(xmlLayerName);
xmlFree(xmlOpacity);
xmlFree(xmlVisibility);
xmlFree(xmlComposite);
xmlFree(xmlPng);
xmlFree(xmlOffsetX);
xmlFree(xmlOffsetY);
if (layerName.empty())
layerName = "unnamed";
if (layerOpacity.empty())
layerOpacity = "1";
if (layerVisibility.empty())
layerVisibility = "visible";
if (layerComposite.empty())
layerComposite = "svg:src-over";
if (layerOffsetX.empty())
layerOffsetX = "0";
if (layerOffsetY.empty())
layerOffsetY = "0";
if (!layerFile.empty()) {
layerInfo.push_back(layerName);
layerInfo.push_back(layerOpacity);
layerInfo.push_back(layerVisibility);
layerInfo.push_back(layerComposite);
layerInfo.push_back(layerOffsetX);
layerInfo.push_back(layerOffsetY);
layerInfo.push_back(layerFile);
_layersInfo.push_back(layerInfo);
}
}
}
getLayersInfo(cur_node->children);
}
}
void
ReadORAPlugin::setupImage(std::string filename)
{
if (!filename.empty()) {
std::string xml = _extractXML(filename);
if (!xml.empty()) {
_image.clear();
_layersInfo.clear();
xmlDocPtr doc;
doc = xmlParseDoc((const xmlChar *)xml.c_str());
xmlNode *root_element = NULL;
root_element = xmlDocGetRootElement(doc);
getLayersInfo(root_element);
xmlFreeDoc(doc);
if (!_layersInfo.empty()) {
std::reverse(_layersInfo.begin(),_layersInfo.end());
for (int i = 0; i < (int)_layersInfo.size(); i++) {
#ifdef DEBUG
std::cout << _layersInfo[i][0] << " " << _layersInfo[i][1] << " " << _layersInfo[i][2] << " " << _layersInfo[i][3] << " " << _layersInfo[i][4] << " " << _layersInfo[i][5] << " " << _layersInfo[i][6] << std::endl;
#endif
}
}
}
}
}
void
ReadORAPlugin::decode(const std::string& filename,
OfxTime time,
int /*view*/,
bool /*isPlayback*/,
const OfxRectI& renderWindow,
float *pixelData,
const OfxRectI& bounds,
OFX::PixelComponentEnum /*pixelComponents*/,
int /*pixelComponentCount*/,
int /*rowBytes*/)
{
#ifdef DEBUG
std::cout << "decode ..." << std::endl;
#endif
// TODO!!!
int width = 0;
int height = 0;
if (!filename.empty())
_getImageSize(&width,&height,filename);
if (width>0 && height>0) {
setupImage(filename);
Magick::Image container(Magick::Geometry(bounds.x2,bounds.y2),Magick::Color("rgba(0,0,0,1)"));
//container.composite(image,0,0,Magick::OverCompositeOp);
//container.composite(image,0,0,Magick::CopyOpacityCompositeOp);
container.flip();
container.write(0,0,renderWindow.x2 - renderWindow.x1,renderWindow.y2 - renderWindow.y1,"RGBA",Magick::FloatPixel,pixelData);
}
else {
setPersistentMessage(OFX::Message::eMessageError, "", "Unable to read image");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
}
bool ReadORAPlugin::getFrameBounds(const std::string& filename,
OfxTime /*time*/,
OfxRectI *bounds,
double *par,
std::string* /*error*/,int *tile_width, int *tile_height)
{
#ifdef DEBUG
std::cout << "getFrameBounds ..." << std::endl;
#endif
int width = 0;
int height = 0;
_getImageSize(&width,&height,filename);
if (width>0 && height>0) {
bounds->x1 = 0;
bounds->x2 = width;
bounds->y1 = 0;
bounds->y2 = height;
*par = 1.0;
}
*tile_width = *tile_height = 0;
return true;
}
void ReadORAPlugin::onInputFileChanged(const std::string& newFile,
bool setColorSpace,
OFX::PreMultiplicationEnum *premult,
OFX::PixelComponentEnum *components,int */*componentCount*/)
{
#ifdef DEBUG
std::cout << "onInputFileChanged ..." << std::endl;
#endif
assert(premult && components);
int width = 0;
int height = 0;
_getImageSize(&width,&height,newFile);
if (width>0 && height>0) {
if (setColorSpace) {
# ifdef OFX_IO_USING_OCIO
_ocio->setInputColorspace("sRGB");
# endif // OFX_IO_USING_OCIO
}
}
else {
setPersistentMessage(OFX::Message::eMessageError, "", "Unable to read image");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
*components = OFX::ePixelComponentRGBA;
*premult = OFX::eImageOpaque;
}
using namespace OFX;
mDeclareReaderPluginFactory(ReadORAPluginFactory, {}, {}, false);
/** @brief The basic describe function, passed a plugin descriptor */
void ReadORAPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
GenericReaderDescribe(desc, kSupportsTiles, false);
desc.setLabel(kPluginName);
#ifdef OFX_EXTENSIONS_TUTTLE
const char* extensions[] = {"ora", NULL};
desc.addSupportedExtensions(extensions);
desc.setPluginEvaluation(50);
#endif
desc.setPluginDescription("Read ORA (OpenRaster) image format.");
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void ReadORAPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)
{
PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles);
GenericReaderDescribeInContextEnd(desc, context, page, "reference", "reference");
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* ReadORAPluginFactory::createInstance(OfxImageEffectHandle handle,
ContextEnum /*context*/)
{
ReadORAPlugin* ret = new ReadORAPlugin(handle);
ret->restoreStateFromParameters();
return ret;
}
void getReadORAPluginID(OFX::PluginFactoryArray &ids)
{
static ReadORAPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
ids.push_back(&p);
}
<|endoftext|> |
<commit_before>// UCN Observer class
// Author: Matthew Raso-Barnett 19/11/2010
#include <iostream>
#include <sstream>
#include <cassert>
#include "Observer.h"
#include "Particle.h"
#include "RunConfig.h"
#include "Data.h"
#include "TKey.h"
/////////////////////////////////////////////////////////////////////////////
// //
// Observer //
// //
/////////////////////////////////////////////////////////////////////////////
using namespace std;
ClassImp(Observer)
/////////////////////////////////////////////////////////////////////////////
// //
// SpinObserver //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(SpinObserver)
//_____________________________________________________________________________
SpinObserver::SpinObserver()
:Observer(),
fSpinObservables(NULL)
{
// Constructor
Info("SpinObserver","Default Constructor");
}
//_____________________________________________________________________________
SpinObserver::SpinObserver(const RunConfig& runConfig)
:Observer(),
fSpinObservables(NULL)
{
// Constructor
Info("SpinObserver","Constructor");
fMeasAxis = runConfig.PolarisationAxis();
}
//_____________________________________________________________________________
SpinObserver::SpinObserver(const SpinObserver& other)
:Observer(other),
fSpinObservables(other.fSpinObservables),
fMeasAxis(other.fMeasAxis)
{
// Copy Constructor
Info("SpinObserver","Copy Constructor");
}
//_____________________________________________________________________________
SpinObserver& SpinObserver::operator=(const SpinObserver& other)
{
// Assignment
Info("SpinObserver","Assignment");
if(this!=&other) {
Observer::operator=(other);
fSpinObservables = other.fSpinObservables;
fMeasAxis = other.fMeasAxis;
}
return *this;
}
//_____________________________________________________________________________
SpinObserver::~SpinObserver()
{
// Destructor
Info("SpinObserver","Destructor");
}
//_____________________________________________________________________________
void SpinObserver::RecordEvent(const TObject* subject, const string& context)
{
// -- Record the current polarisation
if (subject == fSubject && context == Context::Spin) {
const Particle* particle = dynamic_cast<const Particle*>(subject);
fSpinObservables->insert(pair<Double_t,Bool_t>(particle->T(), particle->IsSpinUp(fMeasAxis)));
}
}
//_____________________________________________________________________________
void SpinObserver::ResetObservables()
{
// -- Delete current observables and create a new version in its place
if (fSpinObservables != NULL) delete fSpinObservables; fSpinObservables = NULL;
fSpinObservables = new SpinObservables();
}
//_____________________________________________________________________________
void SpinObserver::LoadExistingObservables(TDirectory* const particleDir)
{
// -- Look for a SpinObservables object and if so load into memory
particleDir->cd();
// -- Loop on all entries of this directory
TKey *key;
TIter nextkey(particleDir->GetListOfKeys());
while ((key = static_cast<TKey*>(nextkey.Next()))) {
const char *classname = key->GetClassName();
TClass *cl = gROOT->GetClass(classname);
if (!cl) continue;
if (cl->InheritsFrom("SpinObservables")) {
if (fSpinObservables != NULL) delete fSpinObservables; fSpinObservables = NULL;
fSpinObservables = dynamic_cast<SpinObservables*>(key->ReadObj());
break;
}
}
}
//_____________________________________________________________________________
void SpinObserver::WriteToFile(TDirectory* const particleDir)
{
// -- Write out the current observable to the provided directory
particleDir->cd();
fSpinObservables->Write("SpinObservables",TObject::kOverwrite);
}
/////////////////////////////////////////////////////////////////////////////
// //
// BounceObserver //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(BounceObserver)
//_____________________________________________________________________________
BounceObserver::BounceObserver()
:Observer(),
fBounceObservables(NULL)
{
// Constructor
Info("BounceObserver","Default Constructor");
}
//_____________________________________________________________________________
BounceObserver::BounceObserver(const RunConfig& /*runConfig*/)
:Observer(),
fBounceObservables(NULL)
{
// Constructor
Info("BounceObserver","Constructor");
}
//_____________________________________________________________________________
BounceObserver::BounceObserver(const BounceObserver& other)
:Observer(other),
fBounceObservables(other.fBounceObservables)
{
// Copy Constructor
Info("BounceObserver","Copy Constructor");
}
//_____________________________________________________________________________
BounceObserver& BounceObserver::operator=(const BounceObserver& other)
{
// Assignment
Info("BounceObserver","Assignment");
if(this!=&other) {
Observer::operator=(other);
fBounceObservables = other.fBounceObservables;
}
return *this;
}
//_____________________________________________________________________________
BounceObserver::~BounceObserver()
{
// Destructor
Info("BounceObserver","Destructor");
}
//_____________________________________________________________________________
void BounceObserver::RecordEvent(const TObject* subject, const string& context)
{
// -- Record the current polarisation
if (subject == fSubject) {
if (context == Context::SpecBounce) {
fBounceObservables->RecordSpecular();
} else if (context == Context::DiffBounce) {
fBounceObservables->RecordDiffuse();
}
}
}
//_____________________________________________________________________________
void BounceObserver::ResetObservables()
{
// -- Delete current observables and create a new version in its place
if (fBounceObservables != NULL) delete fBounceObservables; fBounceObservables = NULL;
fBounceObservables = new BounceObservables();
}
//_____________________________________________________________________________
void BounceObserver::LoadExistingObservables(TDirectory* const particleDir)
{
// -- Look for a SpinObservables object and if so load into memory
particleDir->cd();
// -- Loop on all entries of this directory
TKey *key;
TIter nextkey(particleDir->GetListOfKeys());
while ((key = static_cast<TKey*>(nextkey.Next()))) {
const char *classname = key->GetClassName();
TClass *cl = gROOT->GetClass(classname);
if (!cl) continue;
if (cl->InheritsFrom("BounceObservables")) {
if (fBounceObservables != NULL) delete fBounceObservables; fBounceObservables = NULL;
fBounceObservables = dynamic_cast<BounceObservables*>(key->ReadObj());
break;
}
}
}
//_____________________________________________________________________________
void BounceObserver::WriteToFile(TDirectory* const particleDir)
{
// -- Write out the current observable to the provided directory
particleDir->cd();
fBounceObservables->Write("BounceObservables",TObject::kOverwrite);
}
/////////////////////////////////////////////////////////////////////////////
// //
// TrackObserver //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(TrackObserver)
//_____________________________________________________________________________
TrackObserver::TrackObserver()
:Observer(),
fTrack(NULL)
{
// Constructor
Info("TrackObserver","Default Constructor");
}
//_____________________________________________________________________________
TrackObserver::TrackObserver(const RunConfig& /*runConfig*/)
:Observer(),
fTrack(NULL)
{
// Constructor
Info("TrackObserver","Constructor");
}
//_____________________________________________________________________________
TrackObserver::TrackObserver(const TrackObserver& other)
:Observer(other),
fTrack(other.fTrack)
{
// Copy Constructor
Info("TrackObserver","Copy Constructor");
}
//_____________________________________________________________________________
TrackObserver& TrackObserver::operator=(const TrackObserver& other)
{
// Assignment
Info("TrackObserver","Assignment");
if(this!=&other) {
Observer::operator=(other);
fTrack = other.fTrack;
}
return *this;
}
//_____________________________________________________________________________
TrackObserver::~TrackObserver()
{
// Destructor
Info("TrackObserver","Destructor");
}
//_____________________________________________________________________________
void TrackObserver::RecordEvent(const TObject* subject, const string& context)
{
// -- Record the current polarisation
if (subject == fSubject && context == Context::Step) {
const Particle* particle = dynamic_cast<const Particle*>(subject);
fTrack->AddVertex(particle->X(), particle->Y(), particle->Z(), particle->T());
}
}
//_____________________________________________________________________________
void TrackObserver::ResetObservables()
{
// -- Delete current observables and create a new version in its place
if (fTrack != NULL) delete fTrack; fTrack = NULL;
fTrack = new Track();
}
//_____________________________________________________________________________
void TrackObserver::LoadExistingObservables(TDirectory* const particleDir)
{
// -- Look for a SpinObservables object and if so load into memory
particleDir->cd();
// -- Loop on all entries of this directory
TKey *key;
TIter nextkey(particleDir->GetListOfKeys());
while ((key = static_cast<TKey*>(nextkey.Next()))) {
const char *classname = key->GetClassName();
TClass *cl = gROOT->GetClass(classname);
if (!cl) continue;
if (cl->InheritsFrom("Track")) {
if (fTrack != NULL) delete fTrack; fTrack = NULL;
fTrack = dynamic_cast<Track*>(key->ReadObj());
break;
}
}
}
//_____________________________________________________________________________
void TrackObserver::WriteToFile(TDirectory* const particleDir)
{
// -- Write out the current observable to the provided directory
particleDir->cd();
fTrack->Write("Track",TObject::kOverwrite);
}
<commit_msg>Fix desruction of Observables in Observer<commit_after>// UCN Observer class
// Author: Matthew Raso-Barnett 19/11/2010
#include <iostream>
#include <sstream>
#include <cassert>
#include "Observer.h"
#include "Particle.h"
#include "RunConfig.h"
#include "Data.h"
#include "TKey.h"
/////////////////////////////////////////////////////////////////////////////
// //
// Observer //
// //
/////////////////////////////////////////////////////////////////////////////
using namespace std;
ClassImp(Observer)
/////////////////////////////////////////////////////////////////////////////
// //
// SpinObserver //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(SpinObserver)
//_____________________________________________________________________________
SpinObserver::SpinObserver()
:Observer(),
fSpinObservables(NULL)
{
// Constructor
Info("SpinObserver","Default Constructor");
}
//_____________________________________________________________________________
SpinObserver::SpinObserver(const RunConfig& runConfig)
:Observer(),
fSpinObservables(NULL)
{
// Constructor
Info("SpinObserver","Constructor");
fMeasAxis = runConfig.PolarisationAxis();
}
//_____________________________________________________________________________
SpinObserver::SpinObserver(const SpinObserver& other)
:Observer(other),
fSpinObservables(other.fSpinObservables),
fMeasAxis(other.fMeasAxis)
{
// Copy Constructor
Info("SpinObserver","Copy Constructor");
}
//_____________________________________________________________________________
SpinObserver& SpinObserver::operator=(const SpinObserver& other)
{
// Assignment
Info("SpinObserver","Assignment");
if(this!=&other) {
Observer::operator=(other);
fSpinObservables = other.fSpinObservables;
fMeasAxis = other.fMeasAxis;
}
return *this;
}
//_____________________________________________________________________________
SpinObserver::~SpinObserver()
{
// Destructor
Info("SpinObserver","Destructor");
if (fSpinObservables != NULL) delete fSpinObservables;
}
//_____________________________________________________________________________
void SpinObserver::RecordEvent(const TObject* subject, const string& context)
{
// -- Record the current polarisation
if (subject == fSubject && context == Context::Spin) {
const Particle* particle = dynamic_cast<const Particle*>(subject);
fSpinObservables->insert(pair<Double_t,Bool_t>(particle->T(), particle->IsSpinUp(fMeasAxis)));
}
}
//_____________________________________________________________________________
void SpinObserver::ResetObservables()
{
// -- Delete current observables and create a new version in its place
if (fSpinObservables != NULL) delete fSpinObservables; fSpinObservables = NULL;
fSpinObservables = new SpinObservables();
}
//_____________________________________________________________________________
void SpinObserver::LoadExistingObservables(TDirectory* const particleDir)
{
// -- Look for a SpinObservables object and if so load into memory
particleDir->cd();
// -- Loop on all entries of this directory
TKey *key;
TIter nextkey(particleDir->GetListOfKeys());
while ((key = static_cast<TKey*>(nextkey.Next()))) {
const char *classname = key->GetClassName();
TClass *cl = gROOT->GetClass(classname);
if (!cl) continue;
if (cl->InheritsFrom("SpinObservables")) {
if (fSpinObservables != NULL) delete fSpinObservables; fSpinObservables = NULL;
fSpinObservables = dynamic_cast<SpinObservables*>(key->ReadObj());
break;
}
}
}
//_____________________________________________________________________________
void SpinObserver::WriteToFile(TDirectory* const particleDir)
{
// -- Write out the current observable to the provided directory
particleDir->cd();
fSpinObservables->Write("SpinObservables",TObject::kOverwrite);
}
/////////////////////////////////////////////////////////////////////////////
// //
// BounceObserver //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(BounceObserver)
//_____________________________________________________________________________
BounceObserver::BounceObserver()
:Observer(),
fBounceObservables(NULL)
{
// Constructor
Info("BounceObserver","Default Constructor");
}
//_____________________________________________________________________________
BounceObserver::BounceObserver(const RunConfig& /*runConfig*/)
:Observer(),
fBounceObservables(NULL)
{
// Constructor
Info("BounceObserver","Constructor");
}
//_____________________________________________________________________________
BounceObserver::BounceObserver(const BounceObserver& other)
:Observer(other),
fBounceObservables(other.fBounceObservables)
{
// Copy Constructor
Info("BounceObserver","Copy Constructor");
}
//_____________________________________________________________________________
BounceObserver& BounceObserver::operator=(const BounceObserver& other)
{
// Assignment
Info("BounceObserver","Assignment");
if(this!=&other) {
Observer::operator=(other);
fBounceObservables = other.fBounceObservables;
}
return *this;
}
//_____________________________________________________________________________
BounceObserver::~BounceObserver()
{
// Destructor
Info("BounceObserver","Destructor");
if (fBounceObservables != NULL) delete fBounceObservables;
}
//_____________________________________________________________________________
void BounceObserver::RecordEvent(const TObject* subject, const string& context)
{
// -- Record the current polarisation
if (subject == fSubject) {
if (context == Context::SpecBounce) {
fBounceObservables->RecordSpecular();
} else if (context == Context::DiffBounce) {
fBounceObservables->RecordDiffuse();
}
}
}
//_____________________________________________________________________________
void BounceObserver::ResetObservables()
{
// -- Delete current observables and create a new version in its place
if (fBounceObservables != NULL) delete fBounceObservables; fBounceObservables = NULL;
fBounceObservables = new BounceObservables();
}
//_____________________________________________________________________________
void BounceObserver::LoadExistingObservables(TDirectory* const particleDir)
{
// -- Look for a SpinObservables object and if so load into memory
particleDir->cd();
// -- Loop on all entries of this directory
TKey *key;
TIter nextkey(particleDir->GetListOfKeys());
while ((key = static_cast<TKey*>(nextkey.Next()))) {
const char *classname = key->GetClassName();
TClass *cl = gROOT->GetClass(classname);
if (!cl) continue;
if (cl->InheritsFrom("BounceObservables")) {
if (fBounceObservables != NULL) delete fBounceObservables; fBounceObservables = NULL;
fBounceObservables = dynamic_cast<BounceObservables*>(key->ReadObj());
break;
}
}
}
//_____________________________________________________________________________
void BounceObserver::WriteToFile(TDirectory* const particleDir)
{
// -- Write out the current observable to the provided directory
particleDir->cd();
fBounceObservables->Write("BounceObservables",TObject::kOverwrite);
}
/////////////////////////////////////////////////////////////////////////////
// //
// TrackObserver //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(TrackObserver)
//_____________________________________________________________________________
TrackObserver::TrackObserver()
:Observer(),
fTrack(NULL)
{
// Constructor
Info("TrackObserver","Default Constructor");
}
//_____________________________________________________________________________
TrackObserver::TrackObserver(const RunConfig& /*runConfig*/)
:Observer(),
fTrack(NULL)
{
// Constructor
Info("TrackObserver","Constructor");
}
//_____________________________________________________________________________
TrackObserver::TrackObserver(const TrackObserver& other)
:Observer(other),
fTrack(other.fTrack)
{
// Copy Constructor
Info("TrackObserver","Copy Constructor");
}
//_____________________________________________________________________________
TrackObserver& TrackObserver::operator=(const TrackObserver& other)
{
// Assignment
Info("TrackObserver","Assignment");
if(this!=&other) {
Observer::operator=(other);
fTrack = other.fTrack;
}
return *this;
}
//_____________________________________________________________________________
TrackObserver::~TrackObserver()
{
// Destructor
Info("TrackObserver","Destructor");
if (fTrack != NULL) delete fTrack;
}
//_____________________________________________________________________________
void TrackObserver::RecordEvent(const TObject* subject, const string& context)
{
// -- Record the current polarisation
if (subject == fSubject && context == Context::Step) {
const Particle* particle = dynamic_cast<const Particle*>(subject);
fTrack->AddVertex(particle->X(), particle->Y(), particle->Z(), particle->T());
}
}
//_____________________________________________________________________________
void TrackObserver::ResetObservables()
{
// -- Delete current observables and create a new version in its place
if (fTrack != NULL) delete fTrack; fTrack = NULL;
fTrack = new Track();
}
//_____________________________________________________________________________
void TrackObserver::LoadExistingObservables(TDirectory* const particleDir)
{
// -- Look for a SpinObservables object and if so load into memory
particleDir->cd();
// -- Loop on all entries of this directory
TKey *key;
TIter nextkey(particleDir->GetListOfKeys());
while ((key = static_cast<TKey*>(nextkey.Next()))) {
const char *classname = key->GetClassName();
TClass *cl = gROOT->GetClass(classname);
if (!cl) continue;
if (cl->InheritsFrom("Track")) {
if (fTrack != NULL) delete fTrack; fTrack = NULL;
fTrack = dynamic_cast<Track*>(key->ReadObj());
break;
}
}
}
//_____________________________________________________________________________
void TrackObserver::WriteToFile(TDirectory* const particleDir)
{
// -- Write out the current observable to the provided directory
particleDir->cd();
fTrack->Write("Track",TObject::kOverwrite);
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <map>
#include <string>
#include <limits>
#include "Prefetch.h"
#include "CodeGen_Internal.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Bounds.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "Util.h"
namespace Halide {
namespace Internal {
using std::map;
using std::string;
using std::vector;
using std::stack;
using std::pair;
namespace {
class HasRealization : public IRVisitor {
public:
std::string realization_name;
bool has = false;
HasRealization(std::string name) : realization_name(name) { }
private:
using IRVisitor::visit;
void visit(const Realize *op) {
if (op->name == realization_name) {
has = true;
} else {
IRVisitor::visit(op);
}
}
};
bool has_realization(Stmt s, const std::string &name) {
HasRealization v(name);
s.accept(&v);
return v.has;
}
class InjectPrefetch : public IRMutator {
public:
InjectPrefetch(const map<string, Function> &e)
: env(e) { }
private:
const map<string, Function> &env;
Scope<Interval> intervals; // Interval scope for boxes_required
private:
using IRMutator::visit;
// Strip down the tuple name, e.g. f.*.var into f
string tuple_func(const string &name) {
vector<string> v = split_string(name, ".");
internal_assert(v.size() > 0);
return v[0];
}
// Strip down the tuple name, e.g. f.*.var into var
string tuple_var(const string &name) {
vector<string> v = split_string(name, ".");
internal_assert(v.size() > 0);
return v[v.size()-1];
}
// Lookup a function in the environment
Function get_func(const string &name) {
map<string, Function>::const_iterator iter = env.find(name);
internal_assert(iter != env.end()) << "function not in environment.\n";
return iter->second;
}
// Determine the static type of a named buffer (if available)
//
// Note: If the type cannot be determined, the variable will
// be flagged as not having a static type (e.g. the type
// of input is only known at runtime, input.elem_size).
//
Type get_type(string varname, bool &has_static_type) {
has_static_type = false;
Type t = UInt(8); // default type
map<string, Function>::const_iterator varit = env.find(varname);
if (varit != env.end()) {
Function varf = varit->second;
if (varf.outputs()) {
vector<Type> varts = varf.output_types();
t = varts[0];
has_static_type = true;
}
}
return t;
}
// Generate the required prefetch code (lets and statements) for the
// specified varname and box
//
Stmt prefetch_box(const string &varname, const Box &box)
{
vector<pair<string, Expr>> plets; // Prefetch let assignments
vector<Stmt> pstmts; // Prefetch stmt sequence
int dims = box.size();
bool has_static_type = true;
Type t = get_type(varname, has_static_type);
string elem_size_name = varname + ".elem_size";
Expr elem_size_bytes;
if (has_static_type) {
elem_size_bytes = t.bytes();
} else { // Use element size for inputs that don't have static types
Expr elem_size_var = Variable::make(Int(32), elem_size_name);
elem_size_bytes = elem_size_var;
}
std::ostringstream ss; ss << t;
string type_name = ss.str();
string pstr = unique_name('p');
debug(1) << " prefetch #" << pstr << ": "
<< varname << " ("
<< (has_static_type ? type_name : elem_size_name)
<< ", dims:" << dims << ")\n";
// TODO: Opt: check box if it should be prefetched?
// TODO - Only prefetch if varying by p.var?
// TODO - Don't prefetch if "small" all constant dimensions?
// TODO e.g. see: camera_pipe.cpp corrected matrix(4,3)
string varname_prefetch_buf = varname + "_prefetch_" + pstr + "_buf";
Expr var_prefetch_buf = Variable::make(Int(32), varname_prefetch_buf);
// Establish the variables for buffer strides, box min & max
vector<Expr> stride_var(dims);
vector<Expr> extent_var(dims);
vector<Expr> min_var(dims);
vector<Expr> max_var(dims);
for (int i = 0; i < dims; i++) {
string istr = std::to_string(i);
// string extent_name = varname + ".extent." + istr;
string stride_name = varname + ".stride." + istr;
string extent_name = varname + ".extent." + istr;
string min_name = varname + "_prefetch_" + pstr + "_min_" + istr;
string max_name = varname + "_prefetch_" + pstr + "_max_" + istr;
stride_var[i] = Variable::make(Int(32), stride_name);
extent_var[i] = Variable::make(Int(32), extent_name);
min_var[i] = Variable::make(Int(32), min_name);
max_var[i] = Variable::make(Int(32), max_name);
// Record let assignments
// except for stride, already defined elsewhere
plets.push_back(make_pair(min_name, box[i].min));
plets.push_back(make_pair(max_name, box[i].max));
}
// Create a buffer_t object for this prefetch.
vector<Expr> args;
Expr first_elem = Load::make(t, varname, 0, BufferPtr(), Parameter());
args.push_back(Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic));
args.push_back(make_zero(t));
for (int i = 0; i < dims; i++) {
args.push_back(min_var[i]);
args.push_back(max_var[i] - min_var[i] + 1);
args.push_back(stride_var[i]);
}
// Create the create_buffer_t call
Expr prefetch_buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,
args, Call::Intrinsic);
plets.push_back(make_pair(varname_prefetch_buf, prefetch_buf));
// Create the prefetch call
Expr num_elem = stride_var[dims-1] * extent_var[dims-1];
vector<Expr> args_prefetch = {
dims,
elem_size_bytes,
num_elem,
var_prefetch_buf
};
Stmt stmt_prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_buffer_t,
args_prefetch, Call::Intrinsic));
// TODO: Opt: Generate more control code for prefetch_buffer_t in Prefetch.cpp?
// TODO Passing box info through a buffer_t results in ~30 additional stores/loads
pstmts.push_back(stmt_prefetch);
// No guard needed, address range checked in prefetch runtime
Stmt pbody = Block::make(pstmts);
for (size_t i = plets.size(); i > 0; i--) {
pbody = LetStmt::make(plets[i-1].first, plets[i-1].second, pbody);
}
return pbody;
}
void visit(const Let *op) {
Interval in = bounds_of_expr_in_scope(op->value, intervals);
intervals.push(op->name, in);
IRMutator::visit(op);
intervals.pop(op->name);
}
void visit(const LetStmt *op) {
Interval in = bounds_of_expr_in_scope(op->value, intervals);
intervals.push(op->name, in);
IRMutator::visit(op);
intervals.pop(op->name);
}
void visit(const For *op) {
Stmt body = op->body;
string func_name = tuple_func(op->name);
const vector<Prefetch> &prefetches = get_func(func_name).schedule().prefetches();
// Add loop variable to interval scope for any inner loop prefetch
Expr loop_var = Variable::make(Int(32), op->name);
Interval prein(loop_var, loop_var);
intervals.push(op->name, prein);
body = mutate(body);
for (const Prefetch &p : prefetches) {
if (!ends_with(op->name, "." + p.var)) {
continue;
}
debug(1) << " " << func_name
<< " prefetch(" << p.var << ", " << p.offset << ")\n";
// Add loop variable + prefetch offset to interval scope for box computation
// Expr loop_var = Variable::make(Int(32), op->name);
Interval prein(loop_var + p.offset, loop_var + p.offset);
intervals.push(op->name, prein);
map<string, Box> boxes = boxes_required(body, intervals);
// TODO: Opt: prefetch the difference from previous iteration
// to the requested iteration (2 calls to boxes_required)
for (auto &b : boxes) {
const string &varname = b.first;
const Box &box = b.second;
if (has_realization(body, varname)) {
debug(1) << " Info: not prefetching realized " << varname << "\n";
continue;
}
Stmt pbody = prefetch_box(varname, box);
body = Block::make({pbody, body});
}
intervals.pop(op->name);
}
intervals.pop(op->name);
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
}
};
} // Anonymous namespace
Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env)
{
debug(1) << "prefetch:\n";
return InjectPrefetch(env).mutate(s);
}
}
}
<commit_msg>Remove now unused tuple_var<commit_after>#include <algorithm>
#include <map>
#include <string>
#include <limits>
#include "Prefetch.h"
#include "CodeGen_Internal.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Bounds.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "Util.h"
namespace Halide {
namespace Internal {
using std::map;
using std::string;
using std::vector;
using std::stack;
using std::pair;
namespace {
class HasRealization : public IRVisitor {
public:
std::string realization_name;
bool has = false;
HasRealization(std::string name) : realization_name(name) { }
private:
using IRVisitor::visit;
void visit(const Realize *op) {
if (op->name == realization_name) {
has = true;
} else {
IRVisitor::visit(op);
}
}
};
bool has_realization(Stmt s, const std::string &name) {
HasRealization v(name);
s.accept(&v);
return v.has;
}
class InjectPrefetch : public IRMutator {
public:
InjectPrefetch(const map<string, Function> &e)
: env(e) { }
private:
const map<string, Function> &env;
Scope<Interval> intervals; // Interval scope for boxes_required
private:
using IRMutator::visit;
// Strip down the tuple name, e.g. f.*.var into f
string tuple_func(const string &name) {
vector<string> v = split_string(name, ".");
internal_assert(v.size() > 0);
return v[0];
}
// Lookup a function in the environment
Function get_func(const string &name) {
map<string, Function>::const_iterator iter = env.find(name);
internal_assert(iter != env.end()) << "function not in environment.\n";
return iter->second;
}
// Determine the static type of a named buffer (if available)
//
// Note: If the type cannot be determined, the variable will
// be flagged as not having a static type (e.g. the type
// of input is only known at runtime, input.elem_size).
//
Type get_type(string varname, bool &has_static_type) {
has_static_type = false;
Type t = UInt(8); // default type
map<string, Function>::const_iterator varit = env.find(varname);
if (varit != env.end()) {
Function varf = varit->second;
if (varf.outputs()) {
vector<Type> varts = varf.output_types();
t = varts[0];
has_static_type = true;
}
}
return t;
}
// Generate the required prefetch code (lets and statements) for the
// specified varname and box
//
Stmt prefetch_box(const string &varname, const Box &box)
{
vector<pair<string, Expr>> plets; // Prefetch let assignments
vector<Stmt> pstmts; // Prefetch stmt sequence
int dims = box.size();
bool has_static_type = true;
Type t = get_type(varname, has_static_type);
string elem_size_name = varname + ".elem_size";
Expr elem_size_bytes;
if (has_static_type) {
elem_size_bytes = t.bytes();
} else { // Use element size for inputs that don't have static types
Expr elem_size_var = Variable::make(Int(32), elem_size_name);
elem_size_bytes = elem_size_var;
}
std::ostringstream ss; ss << t;
string type_name = ss.str();
string pstr = unique_name('p');
debug(1) << " prefetch #" << pstr << ": "
<< varname << " ("
<< (has_static_type ? type_name : elem_size_name)
<< ", dims:" << dims << ")\n";
// TODO: Opt: check box if it should be prefetched?
// TODO - Only prefetch if varying by p.var?
// TODO - Don't prefetch if "small" all constant dimensions?
// TODO e.g. see: camera_pipe.cpp corrected matrix(4,3)
string varname_prefetch_buf = varname + "_prefetch_" + pstr + "_buf";
Expr var_prefetch_buf = Variable::make(Int(32), varname_prefetch_buf);
// Establish the variables for buffer strides, box min & max
vector<Expr> stride_var(dims);
vector<Expr> extent_var(dims);
vector<Expr> min_var(dims);
vector<Expr> max_var(dims);
for (int i = 0; i < dims; i++) {
string istr = std::to_string(i);
// string extent_name = varname + ".extent." + istr;
string stride_name = varname + ".stride." + istr;
string extent_name = varname + ".extent." + istr;
string min_name = varname + "_prefetch_" + pstr + "_min_" + istr;
string max_name = varname + "_prefetch_" + pstr + "_max_" + istr;
stride_var[i] = Variable::make(Int(32), stride_name);
extent_var[i] = Variable::make(Int(32), extent_name);
min_var[i] = Variable::make(Int(32), min_name);
max_var[i] = Variable::make(Int(32), max_name);
// Record let assignments
// except for stride, already defined elsewhere
plets.push_back(make_pair(min_name, box[i].min));
plets.push_back(make_pair(max_name, box[i].max));
}
// Create a buffer_t object for this prefetch.
vector<Expr> args;
Expr first_elem = Load::make(t, varname, 0, BufferPtr(), Parameter());
args.push_back(Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic));
args.push_back(make_zero(t));
for (int i = 0; i < dims; i++) {
args.push_back(min_var[i]);
args.push_back(max_var[i] - min_var[i] + 1);
args.push_back(stride_var[i]);
}
// Create the create_buffer_t call
Expr prefetch_buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,
args, Call::Intrinsic);
plets.push_back(make_pair(varname_prefetch_buf, prefetch_buf));
// Create the prefetch call
Expr num_elem = stride_var[dims-1] * extent_var[dims-1];
vector<Expr> args_prefetch = {
dims,
elem_size_bytes,
num_elem,
var_prefetch_buf
};
Stmt stmt_prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_buffer_t,
args_prefetch, Call::Intrinsic));
// TODO: Opt: Generate more control code for prefetch_buffer_t in Prefetch.cpp?
// TODO Passing box info through a buffer_t results in ~30 additional stores/loads
pstmts.push_back(stmt_prefetch);
// No guard needed, address range checked in prefetch runtime
Stmt pbody = Block::make(pstmts);
for (size_t i = plets.size(); i > 0; i--) {
pbody = LetStmt::make(plets[i-1].first, plets[i-1].second, pbody);
}
return pbody;
}
void visit(const Let *op) {
Interval in = bounds_of_expr_in_scope(op->value, intervals);
intervals.push(op->name, in);
IRMutator::visit(op);
intervals.pop(op->name);
}
void visit(const LetStmt *op) {
Interval in = bounds_of_expr_in_scope(op->value, intervals);
intervals.push(op->name, in);
IRMutator::visit(op);
intervals.pop(op->name);
}
void visit(const For *op) {
Stmt body = op->body;
string func_name = tuple_func(op->name);
const vector<Prefetch> &prefetches = get_func(func_name).schedule().prefetches();
// Add loop variable to interval scope for any inner loop prefetch
Expr loop_var = Variable::make(Int(32), op->name);
Interval prein(loop_var, loop_var);
intervals.push(op->name, prein);
body = mutate(body);
for (const Prefetch &p : prefetches) {
if (!ends_with(op->name, "." + p.var)) {
continue;
}
debug(1) << " " << func_name
<< " prefetch(" << p.var << ", " << p.offset << ")\n";
// Add loop variable + prefetch offset to interval scope for box computation
// Expr loop_var = Variable::make(Int(32), op->name);
Interval prein(loop_var + p.offset, loop_var + p.offset);
intervals.push(op->name, prein);
map<string, Box> boxes = boxes_required(body, intervals);
// TODO: Opt: prefetch the difference from previous iteration
// to the requested iteration (2 calls to boxes_required)
for (auto &b : boxes) {
const string &varname = b.first;
const Box &box = b.second;
if (has_realization(body, varname)) {
debug(1) << " Info: not prefetching realized " << varname << "\n";
continue;
}
Stmt pbody = prefetch_box(varname, box);
body = Block::make({pbody, body});
}
intervals.pop(op->name);
}
intervals.pop(op->name);
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
}
};
} // Anonymous namespace
Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env)
{
debug(1) << "prefetch:\n";
return InjectPrefetch(env).mutate(s);
}
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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 "RJSArray.hpp"
#include "RJSObject.hpp"
#include "RJSUtil.hpp"
#include "object_accessor.hpp"
using namespace realm;
size_t ObjectArray::size() {
return link_view->size();
}
Row ObjectArray::get(std::size_t row_ndx) {
if (row_ndx >= link_view->size()) {
throw std::range_error(std::string("Index ") + std::to_string(row_ndx) + " is outside of range 0..." +
std::to_string(link_view->size()) + ".");
}
return link_view->get(row_ndx);
}
void ObjectArray::verify_attached() {
if (!link_view->is_attached()) {
throw std::runtime_error("Tableview is not attached");
}
link_view->sync_if_needed();
}
static inline ObjectArray * RJSVerifiedArray(JSObjectRef object) {
ObjectArray *array = RJSGetInternal<ObjectArray *>(object);
array->verify_attached();
return array;
}
JSValueRef ArrayGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* jsException) {
try {
// index subscripting
ObjectArray *array = RJSVerifiedArray(object);
size_t size = array->size();
std::string indexStr = RJSStringForJSString(propertyName);
if (indexStr == "length") {
return JSValueMakeNumber(ctx, size);
}
return RJSObjectCreate(ctx, Object(array->realm, array->object_schema, array->get(std::stol(indexStr))));
}
catch (std::invalid_argument &exp) {
// for stol failure this could be another property that is handled externally, so ignore
return NULL;
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
return NULL;
}
}
void ArrayPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames) {
ObjectArray *array = RJSGetInternal<ObjectArray *>(object);
char str[32];
for (int i = 0; i < array->link_view->size(); i++) {
sprintf(str, "%i", i);
JSStringRef name = JSStringCreateWithUTF8CString(str);
JSPropertyNameAccumulatorAddName(propertyNames, name);
JSStringRelease(name);
}
}
JSValueRef ArrayPush(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 1);
for (size_t i = 0; i < argumentCount; i++) {
array->link_view->add(RJSAccessor::to_object_index(ctx, array->realm, const_cast<JSValueRef &>(arguments[i]), array->object_schema.name, false));
}
return JSValueMakeNumber(ctx, array->link_view->size());
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArrayPop(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCount(argumentCount, 0);
if (array->link_view->size() == 0) {
return JSValueMakeUndefined(ctx);
}
size_t index = array->link_view->size()-1;
JSValueRef obj = RJSObjectCreate(ctx, Object(array->realm, array->object_schema, array->get(array->link_view->size()-1)));
array->link_view->remove(index);
return obj;
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArrayUnshift(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 1);
for (size_t i = 0; i < argumentCount; i++) {
array->link_view->insert(i, RJSAccessor::to_object_index(ctx, array->realm, const_cast<JSValueRef &>(arguments[i]), array->object_schema.name, false));
}
return JSValueMakeNumber(ctx, array->link_view->size());
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArrayShift(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCount(argumentCount, 0);
if (array->size() == 0) {
return JSValueMakeUndefined(ctx);
}
JSValueRef obj = RJSObjectCreate(ctx, Object(array->realm, array->object_schema, array->get(0)));
array->link_view->remove(0);
return obj;
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArraySplice(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 2);
long index = RJSValidatedValueToNumber(ctx, arguments[0]);
if (index < 0) {
index = array->size() + index;
}
long remove = RJSValidatedValueToNumber(ctx, arguments[1]);
if (index + remove > array->size()) {
throw std::runtime_error("Attempting to slice elements beyond Array bounds.");
}
while (remove-- > 0) {
array->link_view->remove(index);
}
for (size_t i = 2; i < argumentCount; i++) {
array->link_view->insert(index + i - 2, RJSAccessor::to_object_index(ctx, array->realm, const_cast<JSValueRef &>(arguments[i]), array->object_schema.name, false));
}
return JSValueMakeNumber(ctx, array->link_view->size());
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSObjectRef RJSArrayCreate(JSContextRef ctx, realm::ObjectArray *array) {
return RJSWrapObject<ObjectArray *>(ctx, RJSArrayClass(), array);
}
JSClassRef RJSArrayClass() {
const JSStaticFunction arrayFuncs[] = {
{"push", ArrayPush, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"pop", ArrayPop, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"shift", ArrayShift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"unshift", ArrayUnshift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"splice", ArraySplice, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL},
};
static JSClassRef s_arrayClass = RJSCreateWrapperClass<Object>("RealmArray", ArrayGetProperty, NULL, arrayFuncs, NULL, ArrayPropertyNames);
return s_arrayClass;
}
<commit_msg>Minor cleanups in ArrayPop<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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 "RJSArray.hpp"
#include "RJSObject.hpp"
#include "RJSUtil.hpp"
#include "object_accessor.hpp"
using namespace realm;
size_t ObjectArray::size() {
return link_view->size();
}
Row ObjectArray::get(std::size_t row_ndx) {
if (row_ndx >= link_view->size()) {
throw std::range_error(std::string("Index ") + std::to_string(row_ndx) + " is outside of range 0..." +
std::to_string(link_view->size()) + ".");
}
return link_view->get(row_ndx);
}
void ObjectArray::verify_attached() {
if (!link_view->is_attached()) {
throw std::runtime_error("Tableview is not attached");
}
link_view->sync_if_needed();
}
static inline ObjectArray * RJSVerifiedArray(JSObjectRef object) {
ObjectArray *array = RJSGetInternal<ObjectArray *>(object);
array->verify_attached();
return array;
}
JSValueRef ArrayGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* jsException) {
try {
// index subscripting
ObjectArray *array = RJSVerifiedArray(object);
size_t size = array->size();
std::string indexStr = RJSStringForJSString(propertyName);
if (indexStr == "length") {
return JSValueMakeNumber(ctx, size);
}
return RJSObjectCreate(ctx, Object(array->realm, array->object_schema, array->get(std::stol(indexStr))));
}
catch (std::invalid_argument &exp) {
// for stol failure this could be another property that is handled externally, so ignore
return NULL;
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
return NULL;
}
}
void ArrayPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames) {
ObjectArray *array = RJSGetInternal<ObjectArray *>(object);
char str[32];
for (int i = 0; i < array->link_view->size(); i++) {
sprintf(str, "%i", i);
JSStringRef name = JSStringCreateWithUTF8CString(str);
JSPropertyNameAccumulatorAddName(propertyNames, name);
JSStringRelease(name);
}
}
JSValueRef ArrayPush(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 1);
for (size_t i = 0; i < argumentCount; i++) {
array->link_view->add(RJSAccessor::to_object_index(ctx, array->realm, const_cast<JSValueRef &>(arguments[i]), array->object_schema.name, false));
}
return JSValueMakeNumber(ctx, array->link_view->size());
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArrayPop(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCount(argumentCount, 0);
size_t size = array->size();
if (size == 0) {
return JSValueMakeUndefined(ctx);
}
size_t index = size - 1;
JSValueRef obj = RJSObjectCreate(ctx, Object(array->realm, array->object_schema, array->get(index)));
array->link_view->remove(index);
return obj;
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArrayUnshift(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 1);
for (size_t i = 0; i < argumentCount; i++) {
array->link_view->insert(i, RJSAccessor::to_object_index(ctx, array->realm, const_cast<JSValueRef &>(arguments[i]), array->object_schema.name, false));
}
return JSValueMakeNumber(ctx, array->link_view->size());
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArrayShift(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCount(argumentCount, 0);
if (array->size() == 0) {
return JSValueMakeUndefined(ctx);
}
JSValueRef obj = RJSObjectCreate(ctx, Object(array->realm, array->object_schema, array->get(0)));
array->link_view->remove(0);
return obj;
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSValueRef ArraySplice(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* jsException) {
try {
ObjectArray *array = RJSVerifiedArray(thisObject);
RJSValidateArgumentCountIsAtLeast(argumentCount, 2);
long index = RJSValidatedValueToNumber(ctx, arguments[0]);
if (index < 0) {
index = array->size() + index;
}
long remove = RJSValidatedValueToNumber(ctx, arguments[1]);
if (index + remove > array->size()) {
throw std::runtime_error("Attempting to slice elements beyond Array bounds.");
}
while (remove-- > 0) {
array->link_view->remove(index);
}
for (size_t i = 2; i < argumentCount; i++) {
array->link_view->insert(index + i - 2, RJSAccessor::to_object_index(ctx, array->realm, const_cast<JSValueRef &>(arguments[i]), array->object_schema.name, false));
}
return JSValueMakeNumber(ctx, array->link_view->size());
}
catch (std::exception &exp) {
if (jsException) {
*jsException = RJSMakeError(ctx, exp);
}
}
return NULL;
}
JSObjectRef RJSArrayCreate(JSContextRef ctx, realm::ObjectArray *array) {
return RJSWrapObject<ObjectArray *>(ctx, RJSArrayClass(), array);
}
JSClassRef RJSArrayClass() {
const JSStaticFunction arrayFuncs[] = {
{"push", ArrayPush, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"pop", ArrayPop, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"shift", ArrayShift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"unshift", ArrayUnshift, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"splice", ArraySplice, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL},
};
static JSClassRef s_arrayClass = RJSCreateWrapperClass<Object>("RealmArray", ArrayGetProperty, NULL, arrayFuncs, NULL, ArrayPropertyNames);
return s_arrayClass;
}
<|endoftext|> |
<commit_before>// -*- mode:c++; indent-tabs-mode:nil; -*-
/*
Copyright (c) 2014, Anders Ronnbrant, anders.ronnbrant@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Recorder.h"
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <type_traits>
#include <unordered_map>
#include "zmqutils.h"
void Error(char const* msg) { std::fprintf(stderr, "%s\n", msg); }
// Template instantiation
template<> Recorder&
Recorder::record<char const*>(std::string const& key, char const* value) {
record(key, *value);
return (*this);
}
template Recorder&
Recorder::record<char>(std::string const& key, char value);
template Recorder&
Recorder::record<int32_t>(std::string const& key, int32_t value);
template Recorder&
Recorder::record<int64_t>(std::string const& key, int64_t value);
template Recorder&
Recorder::record<uint32_t>(std::string const& key, uint32_t value);
template Recorder&
Recorder::record<uint64_t>(std::string const& key, uint64_t value);
template Recorder&
Recorder::record<double>(std::string const& key, double value);
Recorder::Item::Item()
: type(Type::INIT), time(-1) {
}
std::string&&
Recorder::Item::toString() const {
char buffer[128];
std::string name(this->name);
std::string unit(this->unit);
unit = "[" + unit + "]";
snprintf(buffer, sizeof(buffer), "%ld %10s = ", this->time, name.c_str());
switch (this->type) {
case Type::CHAR:
sprintf(buffer, "%c", data.c);
break;
case Type::INT:
sprintf(buffer, "%ld", data.i);
break;
case Type::UINT:
sprintf(buffer, "%lu", data.u);
break;
case Type::FLOAT:
sprintf(buffer, "%f", data.d);
break;
case Type::STR:
{
std::string str(data.s, sizeof(data.s));
sprintf(buffer, "%s", str.c_str());
}
break;
default:
break;
}
snprintf(buffer, 2+sizeof(this->unit), "%s\n", unit.c_str());
return std::move(std::string(buffer));
}
Recorder::Item::Item(std::string const& n, std::string const& u)
: Item() {
if (n.length() > sizeof(name)) {
Error("Maximum size of parameter name 8 chars");
std::exit(1);
} else if (u.length() > sizeof(unit)) {
Error("Maximum size of parameter unit 8 chars");
std::exit(1);
}
std::strncpy(name, n.c_str(), sizeof(name));
std::strncpy(unit, u.c_str(), sizeof(unit));
}
Recorder::Recorder(uint64_t id, std::string const address)
: _identifier(id)
, _socket_address(address)
{
_storage.reserve(256);
bool error = false;
if (Recorder::socket_context == nullptr) {
Error("Recorder: setContext() must be called before instantiation");
error = true;
}
if (_socket_address.empty()) {
Error("Recorder: Socket address empty, setAddress() must be called");
Error(" before first instantiation or provide local address");
Error(" using ctor Recorder(uint64_t, std::string)");
error = true;
}
if (error) {
std::exit(1);
}
constexpr int linger = 3000;
_socket.reset(new zmq::socket_t(*Recorder::socket_context, ZMQ_PUSH));
_socket->setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
zmqutils::connect(_socket.get(), _socket_address);
}
Recorder::Recorder(uint64_t id)
: Recorder(id, Recorder::socket_address) {
}
Recorder::~Recorder() {
flushSendBuffer();
if (_socket) {
_socket->close();
}
}
Recorder&
Recorder::setup(std::string const& key, std::string const& unit) {
auto it = _storage.find(key);
if (it == _storage.end()) {
Item item(key, unit);
_storage.emplace(key, item);
} else {
// Ignore already setup parameters
}
return (*this);
}
//!! Create a item from name, value and time paramters.
// ---------------------------------------------------------------------------
template<typename T> Recorder::Item
createItem(Recorder::Item const& clone,
int64_t const time,
T const value) {
Recorder::Item item;
std::memcpy(&item, &clone, sizeof(item));
item.time = time;
if (std::is_same<char, T>::value) {
item.type = Recorder::Item::Type::CHAR;
item.data.c = value;
} else if (std::is_integral<T>::value) {
if (std::is_signed<T>::value) {
item.type = Recorder::Item::Type::INT;
item.data.i = value;
} else if (std::is_unsigned<T>::value) {
item.type = Recorder::Item::Type::UINT;
item.data.u = value;
} else {
static_assert(
std::is_signed<T>::value || std::is_unsigned<T>::value,
"Unknown signedness for integral type");
}
} else if (std::is_floating_point<T>::value) {
item.type = Recorder::Item::Type::FLOAT;
item.data.d = value;
} else {
static_assert(
std::is_integral<T>::value || std::is_floating_point<T>::value,
"Value type must be char, integral or floating point");
}
return item;
}
// Specialization for char const*
// template<> Recorder::Item
// createItem(Recorder::Item const& clone,
// int64_t const time,
// char value[]) {
// Recorder::Item item;
// std::memcpy(&item, &clone, sizeof(item));
// item.time = time;
// item.type = Type::STR;
// strncpy(&item.data.s[0], &value[0], sizeof(item.data.s));
// return item;
//}
// ---------------------------------------------------------------------------
template<typename T>
Recorder& Recorder::record(std::string const& key, T const value) {
auto const time = std::time(nullptr);
auto it = _storage.find(key);
if (it == _storage.end()) {
assert(0 && "Must use setup() prior to record()");
} else if (it->second.type == Item::Type::INIT) {
auto const item = createItem(it->second, time, value);
_storage[key] = item;
send(item);
} else if (memcmp(&value, &(it->second.data), sizeof(value)) != 0) {
auto const item = createItem(it->second, time, value);
it->second.time = time;
send(it->second);
_storage[key] = item;
send(item);
} else {
// Ignore unchanged value
}
return (*this);
}
void
Recorder::send(Item const& item) {
_send_buffer[_send_buffer_index++] = item;
if (_send_buffer_index == _send_buffer.max_size()) {
flushSendBuffer();
}
}
void
Recorder::flushSendBuffer() {
constexpr auto item_size = sizeof(decltype(_send_buffer)::value_type);
if (_send_buffer_index > 0) {
_socket->send(_send_buffer.data(), _send_buffer_index * item_size);
_send_buffer_index = 0;
}
}
void
Recorder::setContext(zmq::context_t* ctx) {
socket_context = ctx;
}
void
Recorder::setAddress(std::string addr) {
socket_address = addr;
}
zmq::context_t* Recorder::socket_context = nullptr;
std::string Recorder::socket_address = "";
//thread_local Recorder::SendBuffer Recorder::send_buffer;
//thread_local Recorder::SendBuffer::size_type Recorder::send_buffer_idx = 0;
<commit_msg>Remove static thread local sendbuffer<commit_after>// -*- mode:c++; indent-tabs-mode:nil; -*-
/*
Copyright (c) 2014, Anders Ronnbrant, anders.ronnbrant@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Recorder.h"
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <type_traits>
#include <unordered_map>
#include "zmqutils.h"
void Error(char const* msg) { std::fprintf(stderr, "%s\n", msg); }
// Template instantiation
template<> Recorder&
Recorder::record<char const*>(std::string const& key, char const* value) {
record(key, *value);
return (*this);
}
template Recorder&
Recorder::record<char>(std::string const& key, char value);
template Recorder&
Recorder::record<int32_t>(std::string const& key, int32_t value);
template Recorder&
Recorder::record<int64_t>(std::string const& key, int64_t value);
template Recorder&
Recorder::record<uint32_t>(std::string const& key, uint32_t value);
template Recorder&
Recorder::record<uint64_t>(std::string const& key, uint64_t value);
template Recorder&
Recorder::record<double>(std::string const& key, double value);
Recorder::Item::Item()
: type(Type::INIT), time(-1) {
}
std::string&&
Recorder::Item::toString() const {
char buffer[128];
std::string name(this->name);
std::string unit(this->unit);
unit = "[" + unit + "]";
snprintf(buffer, sizeof(buffer), "%ld %10s = ", this->time, name.c_str());
switch (this->type) {
case Type::CHAR:
sprintf(buffer, "%c", data.c);
break;
case Type::INT:
sprintf(buffer, "%ld", data.i);
break;
case Type::UINT:
sprintf(buffer, "%lu", data.u);
break;
case Type::FLOAT:
sprintf(buffer, "%f", data.d);
break;
case Type::STR:
{
std::string str(data.s, sizeof(data.s));
sprintf(buffer, "%s", str.c_str());
}
break;
default:
break;
}
snprintf(buffer, 2+sizeof(this->unit), "%s\n", unit.c_str());
return std::move(std::string(buffer));
}
Recorder::Item::Item(std::string const& n, std::string const& u)
: Item() {
if (n.length() > sizeof(name)) {
Error("Maximum size of parameter name 8 chars");
std::exit(1);
} else if (u.length() > sizeof(unit)) {
Error("Maximum size of parameter unit 8 chars");
std::exit(1);
}
std::strncpy(name, n.c_str(), sizeof(name));
std::strncpy(unit, u.c_str(), sizeof(unit));
}
Recorder::Recorder(uint64_t id, std::string const address)
: _identifier(id)
, _socket_address(address)
{
_storage.reserve(256);
bool error = false;
if (Recorder::socket_context == nullptr) {
Error("Recorder: setContext() must be called before instantiation");
error = true;
}
if (_socket_address.empty()) {
Error("Recorder: Socket address empty, setAddress() must be called");
Error(" before first instantiation or provide local address");
Error(" using ctor Recorder(uint64_t, std::string)");
error = true;
}
if (error) {
std::exit(1);
}
constexpr int linger = 3000;
_socket.reset(new zmq::socket_t(*Recorder::socket_context, ZMQ_PUSH));
_socket->setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
zmqutils::connect(_socket.get(), _socket_address);
}
Recorder::Recorder(uint64_t id)
: Recorder(id, Recorder::socket_address) {
}
Recorder::~Recorder() {
flushSendBuffer();
if (_socket) {
_socket->close();
}
}
Recorder&
Recorder::setup(std::string const& key, std::string const& unit) {
auto it = _storage.find(key);
if (it == _storage.end()) {
Item item(key, unit);
_storage.emplace(key, item);
} else {
// Ignore already setup parameters
}
return (*this);
}
//!! Create a item from name, value and time paramters.
// ---------------------------------------------------------------------------
template<typename T> Recorder::Item
createItem(Recorder::Item const& clone,
int64_t const time,
T const value) {
Recorder::Item item;
std::memcpy(&item, &clone, sizeof(item));
item.time = time;
if (std::is_same<char, T>::value) {
item.type = Recorder::Item::Type::CHAR;
item.data.c = value;
} else if (std::is_integral<T>::value) {
if (std::is_signed<T>::value) {
item.type = Recorder::Item::Type::INT;
item.data.i = value;
} else if (std::is_unsigned<T>::value) {
item.type = Recorder::Item::Type::UINT;
item.data.u = value;
} else {
static_assert(
std::is_signed<T>::value || std::is_unsigned<T>::value,
"Unknown signedness for integral type");
}
} else if (std::is_floating_point<T>::value) {
item.type = Recorder::Item::Type::FLOAT;
item.data.d = value;
} else {
static_assert(
std::is_integral<T>::value || std::is_floating_point<T>::value,
"Value type must be char, integral or floating point");
}
return item;
}
// Specialization for char const*
// template<> Recorder::Item
// createItem(Recorder::Item const& clone,
// int64_t const time,
// char value[]) {
// Recorder::Item item;
// std::memcpy(&item, &clone, sizeof(item));
// item.time = time;
// item.type = Type::STR;
// strncpy(&item.data.s[0], &value[0], sizeof(item.data.s));
// return item;
//}
// ---------------------------------------------------------------------------
template<typename T>
Recorder& Recorder::record(std::string const& key, T const value) {
auto const time = std::time(nullptr);
auto it = _storage.find(key);
if (it == _storage.end()) {
assert(0 && "Must use setup() prior to record()");
} else if (it->second.type == Item::Type::INIT) {
auto const item = createItem(it->second, time, value);
_storage[key] = item;
send(item);
} else if (memcmp(&value, &(it->second.data), sizeof(value)) != 0) {
auto const item = createItem(it->second, time, value);
it->second.time = time;
send(it->second);
_storage[key] = item;
send(item);
} else {
// Ignore unchanged value
}
return (*this);
}
void
Recorder::send(Item const& item) {
_send_buffer[_send_buffer_index++] = item;
if (_send_buffer_index == _send_buffer.max_size()) {
flushSendBuffer();
}
}
void
Recorder::flushSendBuffer() {
constexpr auto item_size = sizeof(decltype(_send_buffer)::value_type);
if (_send_buffer_index > 0) {
_socket->send(_send_buffer.data(), _send_buffer_index * item_size);
_send_buffer_index = 0;
}
}
void
Recorder::setContext(zmq::context_t* ctx) {
socket_context = ctx;
}
void
Recorder::setAddress(std::string addr) {
socket_address = addr;
}
zmq::context_t* Recorder::socket_context = nullptr;
std::string Recorder::socket_address = "";
<|endoftext|> |
<commit_before>///
/// @file RiemannR.cpp
/// @brief Logarithmic integral and Riemann R function.
/// Both the Logarithmic integral and the Riemann R function
/// are very accurate approximations of PrimePi(x). The inverse
/// Logarithmic integral and the inverse Riemann R function are
/// very accurate approximations of the nth prime.
///
/// Note that these implementations are only accurate up to
/// about 10^19 (if the long double type has 80 bits). We also
/// include implementations based on the non standard __float128
/// type and libquadmath that can be enabled using
/// 'cmake -DWITH_FLOAT128=ON'. Currently __float128 support
/// is disabled by default because there are warnings during
/// compilation (using -Wpedantic) although the code
/// works perfectly fine.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <stdint.h>
#include <cmath>
#include <limits>
#if defined(HAVE_FLOAT128)
#include <quadmath.h>
#endif
namespace {
using std::abs;
using std::log;
using std::sqrt;
using std::numeric_limits;
using namespace primecount;
/// Calculate the logarithmic integral using
/// Ramanujan's formula:
/// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation
///
long double li(long double x)
{
if (x <= 1)
return 0;
long double gamma = 0.577215664901532860606512090082402431L;
long double sum = 0;
long double inner_sum = 0;
long double factorial = 1;
long double p = -1;
long double q = 0;
long double power2 = 1;
long double logx = log(x);
int k = 0;
for (int n = 1; true; n++)
{
p *= -logx;
factorial *= n;
q = factorial * power2;
power2 *= 2;
for (; k <= (n - 1) / 2; k++)
inner_sum += 1.0L / (2 * k + 1);
auto old_sum = sum;
sum += (p / q) * inner_sum;
// Not converging anymore
if (abs(sum - old_sum) < numeric_limits<long double>::epsilon())
break;
}
return gamma + log(logx) + sqrt(x) * sum;
}
/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes <= x.
/// Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
long double Li(long double x)
{
long double li2 = 1.045163780117492784844588889194613136L;
if (x <= li2)
return 0;
else
return li(x) - li2;
}
/// Calculate the inverse offset logarithmic integral which
/// is a very accurate approximation of the nth prime.
/// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316
///
/// This implementation computes Li^-1(x) as the zero of the
/// function f(z) = Li(z) - x using the Newton–Raphson method.
/// Note that Li'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Li(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Li(zn) - x) * log(zn)
///
long double Li_inverse(long double x)
{
if (x < 2)
return 0;
long double t = x * log(x);
long double old_term = numeric_limits<long double>::infinity();
while (true)
{
long double term = (Li(t) - x) * log(t);
// Not converging anymore
if (abs(term) >= abs(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
/// Calculate the Riemann R function which is a very accurate
/// approximation of the number of primes below x.
/// RiemannR(x) = \sum_{n=1}^{∞} μ(n)/n * li(x^(1/n))
/// http://mathworld.wolfram.com/RiemannPrimeCountingFunction.html
///
long double Ri(long double x)
{
if (x <= 1)
return 0;
long double sum = 0;
long double old_term = numeric_limits<long double>::infinity();
auto terms = (int) (log2(x) * 2 + 10);
auto mu = generate_moebius(terms);
for (int n = 1; n < terms; n++)
{
if (mu[n])
{
long double root = pow(x, 1.0L / n);
long double term = (li(root) * mu[n]) / n;
// Not converging anymore
if (abs(term) >= abs(old_term))
break;
sum += term;
old_term = term;
}
}
return sum;
}
/// Calculate the inverse Riemann R function which is a very
/// accurate approximation of the nth prime.
/// This implementation computes Ri^-1(x) as the zero of the
/// function f(z) = Ri(z) - x using the Newton–Raphson method.
/// Note that Ri'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Ri(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Ri(zn) - x) * log(zn)
///
long double Ri_inverse(long double x)
{
if (x < 2)
return 0;
long double t = Li_inverse(x);
long double old_term = numeric_limits<long double>::infinity();
while (true)
{
long double term = (Ri(t) - x) * log(t);
// Not converging anymore
if (abs(term) >= abs(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
#if defined(HAVE_FLOAT128)
/// Calculate the logarithmic integral using
/// Ramanujan's formula:
/// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation
///
__float128 li(__float128 x)
{
if (x <= 1)
return 0;
__float128 gamma = 0.577215664901532860606512090082402431Q;
__float128 sum = 0;
__float128 inner_sum = 0;
__float128 factorial = 1;
__float128 p = -1;
__float128 q = 0;
__float128 power2 = 1;
__float128 logx = logq(x);
int k = 0;
for (int n = 1; true; n++)
{
p *= -logx;
factorial *= n;
q = factorial * power2;
power2 *= 2;
for (; k <= (n - 1) / 2; k++)
inner_sum += 1.0Q / (2 * k + 1);
auto old_sum = sum;
sum += (p / q) * inner_sum;
// Not converging anymore
if (fabsq(sum - old_sum) < FLT128_EPSILON)
break;
}
return gamma + logq(logx) + sqrtq(x) * sum;
}
/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes <= x.
/// Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
__float128 Li(__float128 x)
{
__float128 li2 = 1.045163780117492784844588889194613136Q;
if (x <= li2)
return 0;
else
return li(x) - li2;
}
/// Calculate the inverse offset logarithmic integral which
/// is a very accurate approximation of the nth prime.
/// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316
///
/// This implementation computes Li^-1(x) as the zero of the
/// function f(z) = Li(z) - x using the Newton–Raphson method.
/// Note that Li'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Li(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Li(zn) - x) * log(zn)
///
__float128 Li_inverse(__float128 x)
{
if (x < 2)
return 0;
__float128 t = x * logq(x);
__float128 old_term = FLT128_MAX;
while (true)
{
__float128 term = (Li(t) - x) * logq(t);
// Not converging anymore
if (fabsq(term) >= fabsq(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
/// Calculate the Riemann R function which is a very accurate
/// approximation of the number of primes below x.
/// RiemannR(x) = \sum_{n=1}^{∞} μ(n)/n * li(x^(1/n))
/// http://mathworld.wolfram.com/RiemannPrimeCountingFunction.html
///
__float128 Ri(__float128 x)
{
if (x <= 1)
return 0;
__float128 sum = 0;
__float128 old_term = FLT128_MAX;
auto terms = (int) (log2q(x) * 2 + 10);
auto mu = generate_moebius(terms);
for (int n = 1; n < terms; n++)
{
if (mu[n])
{
__float128 root = powq(x, 1.0Q / n);
__float128 term = (li(root) * mu[n]) / n;
// Not converging anymore
if (fabsq(term) >= fabsq(old_term))
break;
sum += term;
old_term = term;
}
}
return sum;
}
/// Calculate the inverse Riemann R function which is a very
/// accurate approximation of the nth prime.
/// This implementation computes Ri^-1(x) as the zero of the
/// function f(z) = Ri(z) - x using the Newton–Raphson method.
/// Note that Ri'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Ri(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Ri(zn) - x) * log(zn)
///
__float128 Ri_inverse(__float128 x)
{
if (x < 2)
return 0;
__float128 t = Li_inverse(x);
__float128 old_term = FLT128_MAX;
while (true)
{
__float128 term = (Ri(t) - x) * logq(t);
// Not converging anymore
if (fabsq(term) >= fabsq(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
#endif
} // namespace
namespace primecount {
int64_t Li(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Li((__float128) x);
#endif
return (int64_t) ::Li((long double) x);
}
int64_t Li_inverse(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Li_inverse((__float128) x);
#endif
return (int64_t) ::Li_inverse((long double) x);
}
int64_t Ri(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Ri((__float128) x);
#endif
return (int64_t) ::Ri((long double) x);
}
int64_t Ri_inverse(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Ri_inverse((__float128) x);
#endif
return (int64_t) ::Ri_inverse((long double) x);
}
#ifdef HAVE_INT128_T
int128_t Li(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Li((__float128) x);
#endif
return (int128_t) ::Li((long double) x);
}
int128_t Li_inverse(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Li_inverse((__float128) x);
#endif
return (int128_t) ::Li_inverse((long double) x);
}
int128_t Ri(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Ri((__float128) x);
#endif
return (int128_t) ::Ri((long double) x);
}
int128_t Ri_inverse(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Ri_inverse((__float128) x);
#endif
return (int128_t) ::Ri_inverse((long double) x);
}
#endif
} // namespace
<commit_msg>Get rid of: using namespace std<commit_after>///
/// @file RiemannR.cpp
/// @brief Logarithmic integral and Riemann R function.
/// Both the Logarithmic integral and the Riemann R function
/// are very accurate approximations of PrimePi(x). The inverse
/// Logarithmic integral and the inverse Riemann R function are
/// very accurate approximations of the nth prime.
///
/// Note that these implementations are only accurate up to
/// about 10^19 (if the long double type has 80 bits). We also
/// include implementations based on the non standard __float128
/// type and libquadmath that can be enabled using
/// 'cmake -DWITH_FLOAT128=ON'. Currently __float128 support
/// is disabled by default because there are warnings during
/// compilation (using -Wpedantic) although the code
/// works perfectly fine.
///
/// Copyright (C) 2021 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <stdint.h>
#include <cmath>
#include <limits>
#if defined(HAVE_FLOAT128)
#include <quadmath.h>
#endif
namespace {
using namespace primecount;
/// Calculate the logarithmic integral using
/// Ramanujan's formula:
/// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation
///
long double li(long double x)
{
if (x <= 1)
return 0;
long double gamma = 0.577215664901532860606512090082402431L;
long double sum = 0;
long double inner_sum = 0;
long double factorial = 1;
long double p = -1;
long double q = 0;
long double power2 = 1;
long double logx = std::log(x);
int k = 0;
for (int n = 1; true; n++)
{
p *= -logx;
factorial *= n;
q = factorial * power2;
power2 *= 2;
for (; k <= (n - 1) / 2; k++)
inner_sum += 1.0L / (2 * k + 1);
auto old_sum = sum;
sum += (p / q) * inner_sum;
// Not converging anymore
if (std::abs(sum - old_sum) < std::numeric_limits<long double>::epsilon())
break;
}
return gamma + std::log(logx) + std::sqrt(x) * sum;
}
/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes <= x.
/// Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
long double Li(long double x)
{
long double li2 = 1.045163780117492784844588889194613136L;
if (x <= li2)
return 0;
else
return li(x) - li2;
}
/// Calculate the inverse offset logarithmic integral which
/// is a very accurate approximation of the nth prime.
/// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316
///
/// This implementation computes Li^-1(x) as the zero of the
/// function f(z) = Li(z) - x using the Newton–Raphson method.
/// Note that Li'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Li(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Li(zn) - x) * log(zn)
///
long double Li_inverse(long double x)
{
if (x < 2)
return 0;
long double t = x * std::log(x);
long double old_term = std::numeric_limits<long double>::infinity();
while (true)
{
long double term = (Li(t) - x) * std::log(t);
// Not converging anymore
if (std::abs(term) >= std::abs(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
/// Calculate the Riemann R function which is a very accurate
/// approximation of the number of primes below x.
/// RiemannR(x) = \sum_{n=1}^{∞} μ(n)/n * li(x^(1/n))
/// http://mathworld.wolfram.com/RiemannPrimeCountingFunction.html
///
long double Ri(long double x)
{
if (x <= 1)
return 0;
long double sum = 0;
long double old_term = std::numeric_limits<long double>::infinity();
auto terms = (int) (std::log2(x) * 2 + 10);
auto mu = generate_moebius(terms);
for (int n = 1; n < terms; n++)
{
if (mu[n])
{
long double root = std::pow(x, 1.0L / n);
long double term = (li(root) * mu[n]) / n;
// Not converging anymore
if (std::abs(term) >= std::abs(old_term))
break;
sum += term;
old_term = term;
}
}
return sum;
}
/// Calculate the inverse Riemann R function which is a very
/// accurate approximation of the nth prime.
/// This implementation computes Ri^-1(x) as the zero of the
/// function f(z) = Ri(z) - x using the Newton–Raphson method.
/// Note that Ri'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Ri(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Ri(zn) - x) * log(zn)
///
long double Ri_inverse(long double x)
{
if (x < 2)
return 0;
long double t = Li_inverse(x);
long double old_term = std::numeric_limits<long double>::infinity();
while (true)
{
long double term = (Ri(t) - x) * std::log(t);
// Not converging anymore
if (std::abs(term) >= std::abs(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
#if defined(HAVE_FLOAT128)
/// Calculate the logarithmic integral using
/// Ramanujan's formula:
/// https://en.wikipedia.org/wiki/Logarithmic_integral_function#Series_representation
///
__float128 li(__float128 x)
{
if (x <= 1)
return 0;
__float128 gamma = 0.577215664901532860606512090082402431Q;
__float128 sum = 0;
__float128 inner_sum = 0;
__float128 factorial = 1;
__float128 p = -1;
__float128 q = 0;
__float128 power2 = 1;
__float128 logx = logq(x);
int k = 0;
for (int n = 1; true; n++)
{
p *= -logx;
factorial *= n;
q = factorial * power2;
power2 *= 2;
for (; k <= (n - 1) / 2; k++)
inner_sum += 1.0Q / (2 * k + 1);
auto old_sum = sum;
sum += (p / q) * inner_sum;
// Not converging anymore
if (fabsq(sum - old_sum) < FLT128_EPSILON)
break;
}
return gamma + logq(logx) + sqrtq(x) * sum;
}
/// Calculate the offset logarithmic integral which is a very
/// accurate approximation of the number of primes <= x.
/// Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
__float128 Li(__float128 x)
{
__float128 li2 = 1.045163780117492784844588889194613136Q;
if (x <= li2)
return 0;
else
return li(x) - li2;
}
/// Calculate the inverse offset logarithmic integral which
/// is a very accurate approximation of the nth prime.
/// Li^-1(x) < nth_prime(x) for 7 <= x <= 10^316
///
/// This implementation computes Li^-1(x) as the zero of the
/// function f(z) = Li(z) - x using the Newton–Raphson method.
/// Note that Li'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Li(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Li(zn) - x) * log(zn)
///
__float128 Li_inverse(__float128 x)
{
if (x < 2)
return 0;
__float128 t = x * logq(x);
__float128 old_term = FLT128_MAX;
while (true)
{
__float128 term = (Li(t) - x) * logq(t);
// Not converging anymore
if (fabsq(term) >= fabsq(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
/// Calculate the Riemann R function which is a very accurate
/// approximation of the number of primes below x.
/// RiemannR(x) = \sum_{n=1}^{∞} μ(n)/n * li(x^(1/n))
/// http://mathworld.wolfram.com/RiemannPrimeCountingFunction.html
///
__float128 Ri(__float128 x)
{
if (x <= 1)
return 0;
__float128 sum = 0;
__float128 old_term = FLT128_MAX;
auto terms = (int) (log2q(x) * 2 + 10);
auto mu = generate_moebius(terms);
for (int n = 1; n < terms; n++)
{
if (mu[n])
{
__float128 root = powq(x, 1.0Q / n);
__float128 term = (li(root) * mu[n]) / n;
// Not converging anymore
if (fabsq(term) >= fabsq(old_term))
break;
sum += term;
old_term = term;
}
}
return sum;
}
/// Calculate the inverse Riemann R function which is a very
/// accurate approximation of the nth prime.
/// This implementation computes Ri^-1(x) as the zero of the
/// function f(z) = Ri(z) - x using the Newton–Raphson method.
/// Note that Ri'(z) = 1 / log(z).
/// https://math.stackexchange.com/a/853192
///
/// Newton–Raphson method:
/// zn+1 = zn - (f(zn) / f'(zn)).
/// zn+1 = zn - (Ri(zn) - x) / (1 / log(zn))
/// zn+1 = zn - (Ri(zn) - x) * log(zn)
///
__float128 Ri_inverse(__float128 x)
{
if (x < 2)
return 0;
__float128 t = Li_inverse(x);
__float128 old_term = FLT128_MAX;
while (true)
{
__float128 term = (Ri(t) - x) * logq(t);
// Not converging anymore
if (fabsq(term) >= fabsq(old_term))
break;
t -= term;
old_term = term;
}
return t;
}
#endif
} // namespace
namespace primecount {
int64_t Li(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Li((__float128) x);
#endif
return (int64_t) ::Li((long double) x);
}
int64_t Li_inverse(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Li_inverse((__float128) x);
#endif
return (int64_t) ::Li_inverse((long double) x);
}
int64_t Ri(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Ri((__float128) x);
#endif
return (int64_t) ::Ri((long double) x);
}
int64_t Ri_inverse(int64_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int64_t) ::Ri_inverse((__float128) x);
#endif
return (int64_t) ::Ri_inverse((long double) x);
}
#ifdef HAVE_INT128_T
int128_t Li(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Li((__float128) x);
#endif
return (int128_t) ::Li((long double) x);
}
int128_t Li_inverse(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Li_inverse((__float128) x);
#endif
return (int128_t) ::Li_inverse((long double) x);
}
int128_t Ri(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Ri((__float128) x);
#endif
return (int128_t) ::Ri((long double) x);
}
int128_t Ri_inverse(int128_t x)
{
#if defined(HAVE_FLOAT128)
if (x > 1e14)
return (int128_t) ::Ri_inverse((__float128) x);
#endif
return (int128_t) ::Ri_inverse((long double) x);
}
#endif
} // namespace
<|endoftext|> |
<commit_before>#include "../includes/SUrlArea.hpp"
#include "../includes/SMainWindow.hpp"
#include "../includes/Actions.hpp"
#include <QMessageBox>
SUrlArea::SUrlArea(SMainWindow * parent) :
QProgressBar(parent),
m_parent(parent)
{
QHBoxLayout* layout{ new QHBoxLayout(this) };
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
m_champs->setStyleSheet("background: rgba(255, 255, 255, 0)");
m_champs->setClearButtonEnabled(true);
layout->addWidget(m_champs);
setTextVisible(false);
connect(m_champs, &QLineEdit::returnPressed, this, &SUrlArea::loadUrl);
}
void SUrlArea::setText(const QString& texte)
{
m_champs->setText(texte);
}
void SUrlArea::loadStarted()
{
m_parent->getActions()->refreshOrStop->setIcon(QIcon(m_parent->getActions()->themePath + "stop.png"));
m_parent->getActions()->refreshOrStop->setText("Arrter le chargement");
connect(m_parent->getActions()->refreshOrStop, &QAction::triggered, m_parent, &SMainWindow::stop);
QString url{ m_parent->currentPage()->url().toString() };
if ((url.left(7) != "http://" && url.left(8) != "https://" && url.left(5) != "html/") && !url.isEmpty()) {
QMessageBox warningMsgBox{ QMessageBox::Warning, tr("Site non scuris"), tr("Attention, le site sur lequel vous entrez n'est pas scuris !"), QMessageBox::Ignore | QMessageBox::Cancel, this };
warningMsgBox.setButtonText(QMessageBox::Ignore, tr("Continuer"));
warningMsgBox.setButtonText(QMessageBox::Cancel, tr("Retour la scurit"));
if (warningMsgBox.exec() == QMessageBox::Cancel)
m_parent->back();
}
}
void SUrlArea::loadInProgress(int percent)
{
setStyleSheet("QProgressBar::chunk{background-color: rgba(0, 0, 155, 0.2)}");
setValue(percent);
}
void SUrlArea::loadFinished(bool ok)
{
m_parent->getActions()->refreshOrStop->setIcon(QIcon(m_parent->getActions()->themePath + "refresh.png"));
m_parent->getActions()->refreshOrStop->setText("Rafraichir la page");
connect(m_parent->getActions()->refreshOrStop, &QAction::triggered, m_parent, &SMainWindow::refresh);
}
void SUrlArea::loadUrl()
{
QString url{};
if (m_champs->text().left(7) != "http://" && m_champs->text().left(8) != "https://")
url = "https://" + m_champs->text();
else
url = m_champs->text();
m_parent->currentPage()->load(QUrl(url));
}
<commit_msg>Improve progress bar coloration<commit_after>#include "../includes/SUrlArea.hpp"
#include "../includes/SMainWindow.hpp"
#include "../includes/Actions.hpp"
#include <QMessageBox>
SUrlArea::SUrlArea(SMainWindow * parent) :
QProgressBar(parent),
m_parent(parent)
{
QHBoxLayout* layout{ new QHBoxLayout(this) };
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
m_champs->setStyleSheet("background: rgba(255, 255, 255, 0)");
m_champs->setClearButtonEnabled(true);
layout->addWidget(m_champs);
setTextVisible(false);
connect(m_champs, &QLineEdit::returnPressed, this, &SUrlArea::loadUrl);
}
void SUrlArea::setText(const QString& texte)
{
m_champs->setText(texte);
}
void SUrlArea::loadStarted()
{
m_parent->getActions()->refreshOrStop->setIcon(QIcon(m_parent->getActions()->themePath + "stop.png"));
m_parent->getActions()->refreshOrStop->setText("Arrter le chargement");
connect(m_parent->getActions()->refreshOrStop, &QAction::triggered, m_parent, &SMainWindow::stop);
setStyleSheet("QProgressBar::chunk{background-color: rgba(0, 0, 155, 0.2)}");
QString url{ m_parent->currentPage()->url().toString() };
if ((url.left(7) != "http://" && url.left(8) != "https://" && url.left(5) != "html/") && !url.isEmpty()) {
QMessageBox warningMsgBox{ QMessageBox::Warning, tr("Site non scuris"), tr("Attention, le site sur lequel vous entrez n'est pas scuris !"), QMessageBox::Ignore | QMessageBox::Cancel, this };
warningMsgBox.setButtonText(QMessageBox::Ignore, tr("Continuer"));
warningMsgBox.setButtonText(QMessageBox::Cancel, tr("Retour la scurit"));
if (warningMsgBox.exec() == QMessageBox::Cancel)
m_parent->back();
}
}
void SUrlArea::loadInProgress(int percent)
{
setValue(percent);
}
void SUrlArea::loadFinished(bool ok)
{
m_parent->getActions()->refreshOrStop->setIcon(QIcon(m_parent->getActions()->themePath + "refresh.png"));
m_parent->getActions()->refreshOrStop->setText("Rafraichir la page");
setStyleSheet("QProgressBar::chunk{background-color: rgba(200, 200, 200, 0.2)}");
connect(m_parent->getActions()->refreshOrStop, &QAction::triggered, m_parent, &SMainWindow::refresh);
}
void SUrlArea::loadUrl()
{
QString url{};
if (m_champs->text().left(7) != "http://" && m_champs->text().left(8) != "https://")
url = "https://" + m_champs->text();
else
url = m_champs->text();
m_parent->currentPage()->load(QUrl(url));
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
vector<string> fileParam;
// Loops through arguments looking for flags/files/directories
for(int i = 1; i < argc; ++i)
{
// Is a flag if first char of c-string is '-'
if(argv[i][0] == '-')
{
// Accounts for flags like -laR, -lR, etc.
for(int j = 1; argv[i][j] != '\n'; ++j)
{
if(argv[i][j] == 'a')
{
aFlag = true;
}
else if(argv[i][j] == 'l')
{
lFlag = true;
}
else if(argv[i][j] == 'R')
{
RFlag = true;
}
else
{
// If flag is neither 'l', 'a', nor 'R'
cerr << "Error: Invalid flag" << endl;
exit(1);
}
}
}
else
{
// Adds directories/files to vector
fileParam.push_back(argv[i]);
}
}
if(fileParam.size() == 0)
{
fileParam.push_back("."); // Current directory, if no others specified
}
sort(fileParam.begin(), fileParam.end());
for(auto str : fileParam)
{
vector<dirent*> dirEntries;
DIR* dirp;
if(-1 == (dirp = opendir(str.c_str())))
{
perror("Error in opening directory");
exit(1);
}
dirent* tempDirEnt;
errno = 0;
while(NULL != (tempDirEnt = readdir(dirp)))
{
dirEntries.push_back(tempDirEnt);
}
if(errno != 0)
{
perror("Error in reading directory");
exit(1);
}
}
return 0;
}
<commit_msg>Updated ls<commit_after>#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
vector<string> fileParam;
// Loops through arguments looking for flags/files/directories
for(int i = 1; i < argc; ++i)
{
// Is a flag if first char of c-string is '-'
if(argv[i][0] == '-')
{
// Accounts for flags like -laR, -lR, etc.
for(int j = 1; argv[i][j] != '\n'; ++j)
{
if(argv[i][j] == 'a')
{
aFlag = true;
}
else if(argv[i][j] == 'l')
{
lFlag = true;
}
else if(argv[i][j] == 'R')
{
RFlag = true;
}
else
{
// If flag is neither 'l', 'a', nor 'R'
cerr << "Error: Invalid flag" << endl;
exit(1);
}
}
}
else
{
// Adds directories/files to vector
fileParam.push_back(argv[i]);
}
}
if(fileParam.size() == 0)
{
fileParam.push_back("."); // Current directory, if no others specified
}
sort(fileParam.begin(), fileParam.end());
for(auto str : fileParam)
{
vector<dirent*> dirEntries;
DIR* dirp;
if(-1 == (dirp = opendir(str.c_str())))
{
perror("Error in opening directory");
continue; // Continue to next parameter
}
dirent* tempDirEnt;
errno = 0;
while(NULL != (tempDirEnt = readdir(dirp)))
{
dirEntries.push_back(tempDirEnt);
}
if(errno != 0)
{
perror("Error in reading directory");
continue;
}
if(-1 == closedir(dirp))
{
perror("Error in closing directory");
continue;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#ifndef SH_SHRIKEGL_HPP
#define SH_SHRIKEGL_HPP
#ifdef WIN32
# include <windows.h>
#endif
#ifdef __APPLE__
# define GL_GLEXT_VERBOSE 1
# define GL_GLEXT_PROTOTYPES 1
# include <OpenGL/gl.h>
# include <OpenGL/glext.h>
#else
# define GL_GLEXT_LEGACY
# include <GL/gl.h>
# include <GL/glext.h>
# undef GL_GLEXT_LEGACY
#endif
#if defined(WIN32)
extern PFNGLMULTITEXCOORD1FARBPROC glMultiTexCoord1fARB;
extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB;
extern PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3fARB;
extern PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4fARB;
extern PFNGLMULTITEXCOORD1FVARBPROC glMultiTexCoord1fvARB;
extern PFNGLMULTITEXCOORD2FVARBPROC glMultiTexCoord2fvARB;
extern PFNGLMULTITEXCOORD3FVARBPROC glMultiTexCoord3fvARB;
extern PFNGLMULTITEXCOORD4FVARBPROC glMultiTexCoord4fvARB;
#endif
void shrikeGlInit();
#endif
<commit_msg>Define GL_GLEXT_PROTOTYPES to increase portability.<commit_after>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#ifndef SH_SHRIKEGL_HPP
#define SH_SHRIKEGL_HPP
#ifdef WIN32
# include <windows.h>
#endif
#ifdef __APPLE__
# define GL_GLEXT_VERBOSE 1
# define GL_GLEXT_PROTOTYPES 1
# include <OpenGL/gl.h>
# include <OpenGL/glext.h>
#else
# define GL_GLEXT_LEGACY
# include <GL/gl.h>
# define GL_GLEXT_PROTOTYPES
# include <GL/glext.h>
# undef GL_GLEXT_LEGACY
#endif
#if defined(WIN32)
extern PFNGLMULTITEXCOORD1FARBPROC glMultiTexCoord1fARB;
extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB;
extern PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3fARB;
extern PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4fARB;
extern PFNGLMULTITEXCOORD1FVARBPROC glMultiTexCoord1fvARB;
extern PFNGLMULTITEXCOORD2FVARBPROC glMultiTexCoord2fvARB;
extern PFNGLMULTITEXCOORD3FVARBPROC glMultiTexCoord3fvARB;
extern PFNGLMULTITEXCOORD4FVARBPROC glMultiTexCoord4fvARB;
#endif
void shrikeGlInit();
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <boost/tokenizer.hpp>
#include <vector>
#include <list>
#include <set>
#include <ctype.h>
// puts the argv input from the program into a list
std::list<std::string> GetInput(int argc, char **argcv);
// outputs parameters to the program for debugging
void Output(std::list<std::string> input);
// grabbed from UserHostInfo from rshell.cpp
// the gains from refactoring aren't worth bothering
std::string CurrentPwd();
// iterate each character of each element with a - to look for unknown args
bool UnknownArgs(std::list<std::string> input);
std::set<std::string> Split(std::list<std::string> input);
int main(int argc, char **argv) {
auto input = GetInput(argc, argv);
Output(input);
if(UnknownArgs(input))
std::cout << "oh no" << std::endl;
// DIR *test = opendir("test");
// readdir(test);
// struct stat *buf= new struct stat;
// stat("test",buf);
// buf->st_gid
}
std::list<std::string> GetInput(int argc, char **argv) {
using namespace std;
list<string> input;
for (int i = 0; i < argc; i++) {
string piece(argv[i]);
input.push_back(piece);
}
return input;
}
void Output(std::list<std::string> input) {
for (const auto &element : input)
std::cout << element << std::endl;
}
std::string CurrentPwd() {
char *rawpwd = get_current_dir_name();
if (rawpwd == NULL) {
perror("get_current_dir_name returned NULL");
exit(1);
}
std::string pwd(rawpwd);
delete rawpwd;
return pwd;
}
std::set<std::string> Split(std::list<std::string> input) {
std::set<std::string> args;
input.pop_front();
for (auto& item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for(const auto& letter : item) {
args.emplace(letter);
}
}
}
return args;
}
bool UnknownArgs(std::list<std::string> input) {
for (auto &item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for (const auto &letter : item) {
if (letter != 'l' && letter != 'a' && tolower(letter) != 'r')
return true;
}
}
}
return false;
}
<commit_msg>Split<commit_after>#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <boost/tokenizer.hpp>
#include <vector>
#include <list>
#include <set>
#include <ctype.h>
// puts the argv input from the program into a list
std::list<std::string> GetInput(int argc, char **argcv);
// outputs parameters to the program for debugging
void OutputElements(std::list<std::string> input);
void OutputArgs(std::set<std::string> args);
// grabbed from UserHostInfo from rshell.cpp
// the gains from refactoring aren't worth bothering
std::string CurrentPwd();
// iterate each character of each element with a - to look for unknown args
bool UnknownArgs(std::list<std::string> input);
std::set<std::string> Split(std::list<std::string> input);
int main(int argc, char **argv) {
auto input = GetInput(argc, argv);
OutputElements(input);
if (UnknownArgs(input))
std::cout << "oh no" << std::endl;
auto args = Split(input);
OutputArgs(args);
// DIR *test = opendir("test");
// readdir(test);
// struct stat *buf= new struct stat;
// stat("test",buf);
// buf->st_gid
}
std::list<std::string> GetInput(int argc, char **argv) {
using namespace std;
list<string> input;
for (int i = 0; i < argc; i++) {
string piece(argv[i]);
input.push_back(piece);
}
return input;
}
void OutputElements(std::list<std::string> input) {
using namespace std;
cout << "inputs: " << endl;
for (const auto &element : input)
cout << element << endl;
}
std::string CurrentPwd() {
char *rawpwd = get_current_dir_name();
if (rawpwd == NULL) {
perror("get_current_dir_name returned NULL");
exit(1);
}
std::string pwd(rawpwd);
delete rawpwd;
return pwd;
}
std::set<std::string> Split(std::list<std::string> input) {
std::set<std::string> args;
input.pop_front();
for (auto &item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for (const auto &letter : item) {
args.insert(std::string(1, tolower(letter)));
}
}
}
return args;
}
bool UnknownArgs(std::list<std::string> input) {
for (auto &item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for (const auto &letter : item) {
if (letter != 'l' && letter != 'a' && tolower(letter) != 'r')
return true;
}
}
}
return false;
}
void OutputArgs(std::set<std::string> args) {
using namespace std;
cout << "args: " << endl;
for (const auto &arg : args)
cout << arg << endl;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/font_engine_freetype.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <sstream>
// icu
#include <unicode/ubidi.h>
#include <unicode/ushape.h>
#include <unicode/schriter.h>
#include <unicode/uversion.h>
namespace mapnik
{
freetype_engine::freetype_engine()
{
FT_Error error = FT_Init_FreeType( &library_ );
if (error)
{
throw std::runtime_error("can not load FreeType2 library");
}
}
freetype_engine::~freetype_engine()
{
FT_Done_FreeType(library_);
}
bool freetype_engine::is_font_file(std::string const& file_name)
{
/** only accept files that will be matched by freetype2's `figurefiletype()` */
std::string const& fn = boost::algorithm::to_lower_copy(file_name);
return boost::algorithm::ends_with(fn,std::string(".ttf")) ||
boost::algorithm::ends_with(fn,std::string(".otf")) ||
boost::algorithm::ends_with(fn,std::string(".ttc")) ||
boost::algorithm::ends_with(fn,std::string(".pfa")) ||
boost::algorithm::ends_with(fn,std::string(".pfb")) ||
boost::algorithm::ends_with(fn,std::string(".ttc")) ||
/** Plus OSX custom ext */
boost::algorithm::ends_with(fn,std::string(".dfont"));
}
bool freetype_engine::register_font(std::string const& file_name)
{
if (!boost::filesystem::is_regular_file(file_name) || !is_font_file(file_name)) return false;
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
FT_Library library;
FT_Error error = FT_Init_FreeType(&library);
if (error)
{
throw std::runtime_error("Failed to initialize FreeType2 library");
}
FT_Face face;
error = FT_New_Face (library,file_name.c_str(),0,&face);
if (error)
{
FT_Done_FreeType(library);
return false;
}
// some fonts can lack names, skip them
// http://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_FaceRec
if (face->family_name && face->style_name) {
std::string name = std::string(face->family_name) + " " + std::string(face->style_name);
name2file_.insert(std::make_pair(name,file_name));
FT_Done_Face(face);
FT_Done_FreeType(library);
return true;
} else {
FT_Done_Face(face);
FT_Done_FreeType(library);
std::ostringstream s;
s << "Error: unable to load invalid font file which lacks identifiable family and style name: '"
<< file_name << "'";
throw std::runtime_error(s.str());
}
return true;
}
bool freetype_engine::register_fonts(std::string const& dir, bool recurse)
{
boost::filesystem::path path(dir);
if (!boost::filesystem::exists(path))
return false;
if (!boost::filesystem::is_directory(path))
return mapnik::freetype_engine::register_font(dir);
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(dir); itr != end_itr; ++itr)
{
if (boost::filesystem::is_directory(*itr) && recurse)
{
#if (BOOST_FILESYSTEM_VERSION == 3)
if (!register_fonts(itr->path().string(), true)) return false;
#else // v2
if (!register_fonts(itr->string(), true)) return false;
#endif
}
else
{
#if (BOOST_FILESYSTEM_VERSION == 3)
mapnik::freetype_engine::register_font(itr->path().string());
#else // v2
mapnik::freetype_engine::register_font(itr->string());
#endif
}
}
return true;
}
std::vector<std::string> freetype_engine::face_names ()
{
std::vector<std::string> names;
std::map<std::string,std::string>::const_iterator itr;
for (itr = name2file_.begin();itr!=name2file_.end();++itr)
{
names.push_back(itr->first);
}
return names;
}
std::map<std::string,std::string> const& freetype_engine::get_mapping()
{
return name2file_;
}
face_ptr freetype_engine::create_face(std::string const& family_name)
{
std::map<std::string,std::string>::iterator itr;
itr = name2file_.find(family_name);
if (itr != name2file_.end())
{
FT_Face face;
FT_Error error = FT_New_Face (library_,itr->second.c_str(),0,&face);
if (!error)
{
return face_ptr (new font_face(face));
}
}
return face_ptr();
}
stroker_ptr freetype_engine::create_stroker()
{
FT_Stroker s;
FT_Error error = FT_Stroker_New(library_, &s);
if (!error)
{
return stroker_ptr(new stroker(s));
}
return stroker_ptr();
}
font_face_set::dimension_t font_face_set::character_dimensions(const unsigned c)
{
std::map<unsigned, dimension_t>::const_iterator itr;
itr = dimension_cache_.find(c);
if (itr != dimension_cache_.end()) {
return itr->second;
}
FT_Matrix matrix;
FT_Vector pen;
FT_Error error;
pen.x = 0;
pen.y = 0;
FT_BBox glyph_bbox;
FT_Glyph image;
glyph_ptr glyph = get_glyph(c);
FT_Face face = glyph->get_face()->get_face();
matrix.xx = (FT_Fixed)( 1 * 0x10000L );
matrix.xy = (FT_Fixed)( 0 * 0x10000L );
matrix.yx = (FT_Fixed)( 0 * 0x10000L );
matrix.yy = (FT_Fixed)( 1 * 0x10000L );
FT_Set_Transform(face, &matrix, &pen);
error = FT_Load_Glyph (face, glyph->get_index(), FT_LOAD_NO_HINTING);
if ( error )
return dimension_t(0, 0, 0);
error = FT_Get_Glyph(face->glyph, &image);
if ( error )
return dimension_t(0, 0, 0);
FT_Glyph_Get_CBox(image, ft_glyph_bbox_pixels, &glyph_bbox);
FT_Done_Glyph(image);
unsigned tempx = face->glyph->advance.x >> 6;
//std::clog << "glyph: " << glyph_index << " x: " << tempx << " y: " << tempy << std::endl;
dimension_t dim(tempx, glyph_bbox.yMax, glyph_bbox.yMin);
//dimension_cache_[c] = dim; would need an default constructor for dimension_t
dimension_cache_.insert(std::pair<unsigned, dimension_t>(c, dim));
return dim;
}
void font_face_set::get_string_info(string_info & info)
{
unsigned width = 0;
unsigned height = 0;
UErrorCode err = U_ZERO_ERROR;
UnicodeString reordered;
UnicodeString shaped;
UnicodeString const& ustr = info.get_string();
int32_t length = ustr.length();
UBiDi *bidi = ubidi_openSized(length, 0, &err);
ubidi_setPara(bidi, ustr.getBuffer(), length, UBIDI_DEFAULT_LTR, 0, &err);
ubidi_writeReordered(bidi, reordered.getBuffer(length),
length, UBIDI_DO_MIRRORING, &err);
reordered.releaseBuffer(length);
u_shapeArabic(reordered.getBuffer(), length,
shaped.getBuffer(length), length,
U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR |
U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err);
shaped.releaseBuffer(length);
if (U_SUCCESS(err)) {
StringCharacterIterator iter(shaped);
for (iter.setToStart(); iter.hasNext();) {
UChar ch = iter.nextPostInc();
dimension_t char_dim = character_dimensions(ch);
info.add_info(ch, char_dim.width, char_dim.height);
width += char_dim.width;
height = (char_dim.height > height) ? char_dim.height : height;
}
}
#if (U_ICU_VERSION_MAJOR_NUM*100 + U_ICU_VERSION_MINOR_NUM >= 406)
if (ubidi_getBaseDirection(ustr.getBuffer(), length) == UBIDI_RTL)
{
info.set_rtl(true);
}
#endif
ubidi_close(bidi);
info.set_dimensions(width, height);
}
#ifdef MAPNIK_THREADSAFE
boost::mutex freetype_engine::mutex_;
#endif
std::map<std::string,std::string> freetype_engine::name2file_;
}
<commit_msg>adding support for multiple fonts in one font file, for instance .ttc<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/font_engine_freetype.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <sstream>
// icu
#include <unicode/ubidi.h>
#include <unicode/ushape.h>
#include <unicode/schriter.h>
#include <unicode/uversion.h>
namespace mapnik
{
freetype_engine::freetype_engine()
{
FT_Error error = FT_Init_FreeType( &library_ );
if (error)
{
throw std::runtime_error("can not load FreeType2 library");
}
}
freetype_engine::~freetype_engine()
{
FT_Done_FreeType(library_);
}
bool freetype_engine::is_font_file(std::string const& file_name)
{
/** only accept files that will be matched by freetype2's `figurefiletype()` */
std::string const& fn = boost::algorithm::to_lower_copy(file_name);
return boost::algorithm::ends_with(fn,std::string(".ttf")) ||
boost::algorithm::ends_with(fn,std::string(".otf")) ||
boost::algorithm::ends_with(fn,std::string(".ttc")) ||
boost::algorithm::ends_with(fn,std::string(".pfa")) ||
boost::algorithm::ends_with(fn,std::string(".pfb")) ||
boost::algorithm::ends_with(fn,std::string(".ttc")) ||
/** Plus OSX custom ext */
boost::algorithm::ends_with(fn,std::string(".dfont"));
}
bool freetype_engine::register_font(std::string const& file_name)
{
if (!boost::filesystem::is_regular_file(file_name) || !is_font_file(file_name)) return false;
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
FT_Library library;
FT_Error error = FT_Init_FreeType(&library);
if (error)
{
throw std::runtime_error("Failed to initialize FreeType2 library");
}
FT_Face face;
// fome font files have multiple fonts in a file
// the count is in the 'root' face library[0]
// see the FT_FaceRec in freetype.h
for ( int i = 0; face == 0 || i < face->num_faces; i++ ) {
// if face is null then this is the first face
error = FT_New_Face (library,file_name.c_str(),i,&face);
if (error)
{
FT_Done_FreeType(library);
return false;
}
// some fonts can lack names, skip them
// http://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_FaceRec
if (face->family_name && face->style_name) {
std::string name = std::string(face->family_name) + " " + std::string(face->style_name);
name2file_.insert(std::make_pair(name,file_name));
FT_Done_Face(face);
//FT_Done_FreeType(library);
//return true;
} else {
FT_Done_Face(face);
FT_Done_FreeType(library);
std::ostringstream s;
s << "Error: unable to load invalid font file which lacks identifiable family and style name: '"
<< file_name << "'";
throw std::runtime_error(s.str());
}
}
FT_Done_FreeType(library);
return true;
}
bool freetype_engine::register_fonts(std::string const& dir, bool recurse)
{
boost::filesystem::path path(dir);
if (!boost::filesystem::exists(path))
return false;
if (!boost::filesystem::is_directory(path))
return mapnik::freetype_engine::register_font(dir);
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(dir); itr != end_itr; ++itr)
{
if (boost::filesystem::is_directory(*itr) && recurse)
{
#if (BOOST_FILESYSTEM_VERSION == 3)
if (!register_fonts(itr->path().string(), true)) return false;
#else // v2
if (!register_fonts(itr->string(), true)) return false;
#endif
}
else
{
#if (BOOST_FILESYSTEM_VERSION == 3)
mapnik::freetype_engine::register_font(itr->path().string());
#else // v2
mapnik::freetype_engine::register_font(itr->string());
#endif
}
}
return true;
}
std::vector<std::string> freetype_engine::face_names ()
{
std::vector<std::string> names;
std::map<std::string,std::string>::const_iterator itr;
for (itr = name2file_.begin();itr!=name2file_.end();++itr)
{
names.push_back(itr->first);
}
return names;
}
std::map<std::string,std::string> const& freetype_engine::get_mapping()
{
return name2file_;
}
face_ptr freetype_engine::create_face(std::string const& family_name)
{
std::map<std::string,std::string>::iterator itr;
itr = name2file_.find(family_name);
if (itr != name2file_.end())
{
FT_Face face;
FT_Error error = FT_New_Face (library_,itr->second.c_str(),0,&face);
if (!error)
{
return face_ptr (new font_face(face));
}
}
return face_ptr();
}
stroker_ptr freetype_engine::create_stroker()
{
FT_Stroker s;
FT_Error error = FT_Stroker_New(library_, &s);
if (!error)
{
return stroker_ptr(new stroker(s));
}
return stroker_ptr();
}
font_face_set::dimension_t font_face_set::character_dimensions(const unsigned c)
{
std::map<unsigned, dimension_t>::const_iterator itr;
itr = dimension_cache_.find(c);
if (itr != dimension_cache_.end()) {
return itr->second;
}
FT_Matrix matrix;
FT_Vector pen;
FT_Error error;
pen.x = 0;
pen.y = 0;
FT_BBox glyph_bbox;
FT_Glyph image;
glyph_ptr glyph = get_glyph(c);
FT_Face face = glyph->get_face()->get_face();
matrix.xx = (FT_Fixed)( 1 * 0x10000L );
matrix.xy = (FT_Fixed)( 0 * 0x10000L );
matrix.yx = (FT_Fixed)( 0 * 0x10000L );
matrix.yy = (FT_Fixed)( 1 * 0x10000L );
FT_Set_Transform(face, &matrix, &pen);
error = FT_Load_Glyph (face, glyph->get_index(), FT_LOAD_NO_HINTING);
if ( error )
return dimension_t(0, 0, 0);
error = FT_Get_Glyph(face->glyph, &image);
if ( error )
return dimension_t(0, 0, 0);
FT_Glyph_Get_CBox(image, ft_glyph_bbox_pixels, &glyph_bbox);
FT_Done_Glyph(image);
unsigned tempx = face->glyph->advance.x >> 6;
//std::clog << "glyph: " << glyph_index << " x: " << tempx << " y: " << tempy << std::endl;
dimension_t dim(tempx, glyph_bbox.yMax, glyph_bbox.yMin);
//dimension_cache_[c] = dim; would need an default constructor for dimension_t
dimension_cache_.insert(std::pair<unsigned, dimension_t>(c, dim));
return dim;
}
void font_face_set::get_string_info(string_info & info)
{
unsigned width = 0;
unsigned height = 0;
UErrorCode err = U_ZERO_ERROR;
UnicodeString reordered;
UnicodeString shaped;
UnicodeString const& ustr = info.get_string();
int32_t length = ustr.length();
UBiDi *bidi = ubidi_openSized(length, 0, &err);
ubidi_setPara(bidi, ustr.getBuffer(), length, UBIDI_DEFAULT_LTR, 0, &err);
ubidi_writeReordered(bidi, reordered.getBuffer(length),
length, UBIDI_DO_MIRRORING, &err);
reordered.releaseBuffer(length);
u_shapeArabic(reordered.getBuffer(), length,
shaped.getBuffer(length), length,
U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR |
U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err);
shaped.releaseBuffer(length);
if (U_SUCCESS(err)) {
StringCharacterIterator iter(shaped);
for (iter.setToStart(); iter.hasNext();) {
UChar ch = iter.nextPostInc();
dimension_t char_dim = character_dimensions(ch);
info.add_info(ch, char_dim.width, char_dim.height);
width += char_dim.width;
height = (char_dim.height > height) ? char_dim.height : height;
}
}
#if (U_ICU_VERSION_MAJOR_NUM*100 + U_ICU_VERSION_MINOR_NUM >= 406)
if (ubidi_getBaseDirection(ustr.getBuffer(), length) == UBIDI_RTL)
{
info.set_rtl(true);
}
#endif
ubidi_close(bidi);
info.set_dimensions(width, height);
}
#ifdef MAPNIK_THREADSAFE
boost::mutex freetype_engine::mutex_;
#endif
std::map<std::string,std::string> freetype_engine::name2file_;
}
<|endoftext|> |
<commit_before>#include <slice.hpp>
#include <range.hpp>
#include <iostream>
#include <vector>
#include <array>
int main() {
std::cout << std::endl << "Slice range test" << std::endl << std::endl;
std::vector<int> a{0,1,2,3,4,5,6,7,8,9,10,11,12,13};
std::vector<std::string> b{"hey","how","are","you","doing"};
std::cout << "step out of slice\n";
for (auto i : iter::slice(a, 1, 4, 5)) {
std::cout << i << '\n';
}
std::cout << "end step out\n";
for (auto i : iter::slice(a,2)) {
std::cout << i << std::endl;
}
std::cout<<std::endl;
for (auto & s : iter::slice(b,3,4)) {
std::cout << s << std::endl;
s = "test";
}
std::cout<<std::endl;
for (auto s : b) {
std::cout << s << std::endl;
}
std::cout<<std::endl;
for (auto i : iter::slice(a,0,15,3)) {
std::cout << i << std::endl;
}
std::cout<< "\n13 down to 0\n";
for (auto i : iter::slice(a,13,-1,-1)) {
std::cout << i << std::endl;
}
std::cout<< "\nunevent step [0:5:3]\n";
for (auto i : iter::slice(a, 0, 5, 3)) {
std::cout << i << '\n';
}
std::cout<< "\nInvalid range [1:10:-1]\n";
for (auto i : iter::slice(a,1,10,-1)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout<< "\nOversize range [1:100:1]\n";
for (auto i : iter::slice(a,1,100,1)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout<< "\nOversize range and undersize[1:100:1]\n";
for (auto i : iter::slice(a,-100,100,1)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout<< "\nstatic array[1:8:2]\n";
int arr[10] = {0,1,2,3,4,5,6,7,8,9};
for (auto i : iter::slice(arr,1,8,2)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout << "\ninitializer list\n";
for (auto i : iter::slice({1, 2, 4, 8, 16, 32, 64, 128}, 2, 6)) {
std::cout << i << '\n';
}
}
<commit_msg>Adds slice test with temporary<commit_after>#include <iostream>
#include <slice.hpp>
#include <range.hpp>
#include <vector>
#include <array>
int main() {
std::cout << std::endl << "Slice range test" << std::endl << std::endl;
std::vector<int> a{0,1,2,3,4,5,6,7,8,9,10,11,12,13};
std::vector<std::string> b{"hey","how","are","you","doing"};
std::cout << "step out of slice\n";
for (auto i : iter::slice(a, 1, 4, 5)) {
std::cout << i << '\n';
}
std::cout << "end step out\n";
for (auto i : iter::slice(a,2)) {
std::cout << i << std::endl;
}
std::cout<<std::endl;
for (auto & s : iter::slice(b,3,4)) {
std::cout << s << std::endl;
s = "test";
}
std::cout<<std::endl;
for (auto s : b) {
std::cout << s << std::endl;
}
std::cout<<std::endl;
for (auto i : iter::slice(a,0,15,3)) {
std::cout << i << std::endl;
}
std::cout<< "\n13 down to 0\n";
for (auto i : iter::slice(a,13,-1,-1)) {
std::cout << i << std::endl;
}
std::cout<< "\nunevent step [0:5:3]\n";
for (auto i : iter::slice(a, 0, 5, 3)) {
std::cout << i << '\n';
}
std::cout<< "\nInvalid range [1:10:-1]\n";
for (auto i : iter::slice(a,1,10,-1)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout<< "\nOversize range [1:100:1]\n";
for (auto i : iter::slice(a,1,100,1)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout<< "\nOversize range and undersize[1:100:1]\n";
for (auto i : iter::slice(a,-100,100,1)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout<< "\nstatic array[1:8:2]\n";
int arr[10] = {0,1,2,3,4,5,6,7,8,9};
for (auto i : iter::slice(arr,1,8,2)) {
//invalid range returns two begin iters
std::cout << i << std::endl;
}
std::cout << "\ninitializer list\n";
for (auto i : iter::slice({1, 2, 4, 8, 16, 32, 64, 128}, 2, 6)) {
std::cout << i << '\n';
}
std::cout << "\nvector temporary\n";
for (auto i : iter::slice(
std::vector<int>{1, 2, 4, 8, 16, 32, 64, 128}, 2, 6)) {
std::cout << i << '\n';
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns 0 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array()) {
/* If the array is a variable dereference, it dereferences the
* whole array, by definition. Use this to get the variable.
*
* FINISHME: Should some methods for getting / setting / testing
* FINISHME: array access limits be added to ir_dereference?
*/
ir_variable *const v = array->whole_variable_referenced();
if ((v != NULL) && (unsigned(idx) > v->max_array_access)) {
v->max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(v->name, idx+1, loc, state);
}
}
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->array_size() == 0) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
} else if (array->type->fields.array->is_interface()) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*/
if (array->type->element_type()->is_sampler()) {
if (!state->is_version(130, 100)) {
if (state->es_shader) {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is optional in %s",
state->get_version_string());
} else {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL 1.30 "
"and later");
}
} else {
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is forbidden in GLSL 1.30 and "
"later");
}
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<commit_msg>glsl: Permit non-ubo input interface arrays to use non-const indexing.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns 0 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array()) {
/* If the array is a variable dereference, it dereferences the
* whole array, by definition. Use this to get the variable.
*
* FINISHME: Should some methods for getting / setting / testing
* FINISHME: array access limits be added to ir_dereference?
*/
ir_variable *const v = array->whole_variable_referenced();
if ((v != NULL) && (unsigned(idx) > v->max_array_access)) {
v->max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(v->name, idx+1, loc, state);
}
}
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->array_size() == 0) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
} else if (array->type->fields.array->is_interface()
&& array->variable_referenced()->mode == ir_var_uniform) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*/
if (array->type->element_type()->is_sampler()) {
if (!state->is_version(130, 100)) {
if (state->es_shader) {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is optional in %s",
state->get_version_string());
} else {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL 1.30 "
"and later");
}
} else {
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is forbidden in GLSL 1.30 and "
"later");
}
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "amr_includes.H"
#include <sc_statistics.h>
#define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \
SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \
"Timer " #NAME " still running in amrreset"); \
sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \
(ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \
} while (0)
void amrreset(fclaw2d_domain_t **domain)
{
fclaw2d_domain_data_t *ddata = get_domain_data (*domain);
for(int i = 0; i < (*domain)->num_blocks; i++)
{
fclaw2d_block_t *block = (*domain)->blocks + i;
fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user;
for(int j = 0; j < block->num_patches; j++)
{
fclaw2d_patch_t *patch = block->patches + j;
fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;
delete pdata->cp;
pdata->cp = NULL;
++ddata->count_delete_clawpatch;
FCLAW2D_FREE (pdata);
patch->user = NULL;
}
FCLAW2D_FREE (bd);
block->user = NULL;
}
// Free old parallel ghost patch data structure, must exist by construction.
delete_ghost_patches(*domain);
fclaw2d_domain_exchange_t *e_old = get_domain_exchange_data(*domain);
fclaw2d_domain_free_after_exchange (*domain, e_old);
// Output memory discrepancy for the ClawPatch
if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) {
printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n",
(*domain)->mpirank,
ddata->count_set_clawpatch, ddata->count_delete_clawpatch);
}
// Evaluate timers if this domain has not been superseded yet.
if (ddata->is_latest_domain) {
sc_statinfo_t stats[FCLAW2D_TIMER_COUNT];
fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);
FCLAW2D_STATS_SET (stats, ddata, INIT);
FCLAW2D_STATS_SET (stats, ddata, REGRID);
FCLAW2D_STATS_SET (stats, ddata, OUTPUT);
FCLAW2D_STATS_SET (stats, ddata, CHECK);
FCLAW2D_STATS_SET (stats, ddata, ADVANCE);
FCLAW2D_STATS_SET (stats, ddata, EXCHANGE);
FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES);
FCLAW2D_STATS_SET (stats, ddata, WALLTIME);
FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES);
sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED],
ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative -
(ddata->timers[FCLAW2D_TIMER_INIT].cumulative +
ddata->timers[FCLAW2D_TIMER_REGRID].cumulative +
ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative +
ddata->timers[FCLAW2D_TIMER_CHECK].cumulative +
ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative +
ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative),
"UNACCOUNTED");
sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats);
sc_stats_print (sc_package_id, SC_LP_PRODUCTION, FCLAW2D_TIMER_COUNT,
stats, 1, 0);
SC_GLOBAL_PRODUCTIONF ("Procs %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].average,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].average,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].average);
SC_GLOBAL_PRODUCTIONF ("Max/P %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].max,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].max,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].max);
}
delete_domain_data(*domain); // Delete allocated pointers to set of functions.
fclaw2d_domain_destroy(*domain);
*domain = NULL;
}
<commit_msg>Timer BUILDPATCHES was being reset twice<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "amr_includes.H"
#include <sc_statistics.h>
#define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \
SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \
"Timer " #NAME " still running in amrreset"); \
sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \
(ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \
} while (0)
void amrreset(fclaw2d_domain_t **domain)
{
fclaw2d_domain_data_t *ddata = get_domain_data (*domain);
for(int i = 0; i < (*domain)->num_blocks; i++)
{
fclaw2d_block_t *block = (*domain)->blocks + i;
fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user;
for(int j = 0; j < block->num_patches; j++)
{
fclaw2d_patch_t *patch = block->patches + j;
fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;
delete pdata->cp;
pdata->cp = NULL;
++ddata->count_delete_clawpatch;
FCLAW2D_FREE (pdata);
patch->user = NULL;
}
FCLAW2D_FREE (bd);
block->user = NULL;
}
// Free old parallel ghost patch data structure, must exist by construction.
delete_ghost_patches(*domain);
fclaw2d_domain_exchange_t *e_old = get_domain_exchange_data(*domain);
fclaw2d_domain_free_after_exchange (*domain, e_old);
// Output memory discrepancy for the ClawPatch
if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) {
printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n",
(*domain)->mpirank,
ddata->count_set_clawpatch, ddata->count_delete_clawpatch);
}
// Evaluate timers if this domain has not been superseded yet.
if (ddata->is_latest_domain) {
sc_statinfo_t stats[FCLAW2D_TIMER_COUNT];
fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);
FCLAW2D_STATS_SET (stats, ddata, INIT);
FCLAW2D_STATS_SET (stats, ddata, REGRID);
FCLAW2D_STATS_SET (stats, ddata, OUTPUT);
FCLAW2D_STATS_SET (stats, ddata, CHECK);
FCLAW2D_STATS_SET (stats, ddata, ADVANCE);
FCLAW2D_STATS_SET (stats, ddata, EXCHANGE);
FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES);
FCLAW2D_STATS_SET (stats, ddata, WALLTIME);
sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED],
ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative -
(ddata->timers[FCLAW2D_TIMER_INIT].cumulative +
ddata->timers[FCLAW2D_TIMER_REGRID].cumulative +
ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative +
ddata->timers[FCLAW2D_TIMER_CHECK].cumulative +
ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative +
ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative),
"UNACCOUNTED");
sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats);
sc_stats_print (sc_package_id, SC_LP_PRODUCTION, FCLAW2D_TIMER_COUNT,
stats, 1, 0);
SC_GLOBAL_PRODUCTIONF ("Procs %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].average,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].average,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].average);
SC_GLOBAL_PRODUCTIONF ("Max/P %d advance %d %g exchange %d %g "
"regrid %d %g\n", (*domain)->mpisize,
ddata->count_amr_advance,
stats[FCLAW2D_TIMER_ADVANCE].max,
ddata->count_ghost_exchange,
stats[FCLAW2D_TIMER_EXCHANGE].max,
ddata->count_amr_regrid,
stats[FCLAW2D_TIMER_REGRID].max);
}
delete_domain_data(*domain); // Delete allocated pointers to set of functions.
fclaw2d_domain_destroy(*domain);
*domain = NULL;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: otherjre.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2006-03-08 14:14:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "osl/thread.h"
#include "otherjre.hxx"
using namespace rtl;
using namespace std;
namespace jfw_plugin
{
Reference<VendorBase> OtherInfo::createInstance()
{
return new OtherInfo;
}
char const* const* OtherInfo::getJavaExePaths(int * size)
{
static char const * ar[] = {
#ifdef WNT
"bin/java.exe",
"jre/bin/java.exe"
#elif UNX
"bin/java",
"jre/bin/java"
#endif
};
*size = sizeof (ar) / sizeof (char*);
return ar;
}
char const* const* OtherInfo::getRuntimePaths(int * size)
{
static char const* ar[]= {
#ifdef WNT
"/bin/client/jvm.dll",
"/bin/hotspot/jvm.dll",
"/bin/classic/jvm.dll",
"/bin/jrockit/jvm.dll"
#elif UNX
#ifdef MACOSX
"/../../../JavaVM"
#else
"/bin/classic/libjvm.so", // for IBM Java
"/jre/bin/classic/libjvm.so", // for IBM Java
"/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC
"/lib/" JFW_PLUGIN_ARCH "/server/libjvm.so", // for Blackdown AMD64
"/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so", // for Blackdown PPC
"/lib/" JFW_PLUGIN_ARCH "/jrockit/libjvm.so" // for Java of BEA Systems
#endif
#endif
};
*size = sizeof(ar) / sizeof (char*);
return ar;
}
char const* const* OtherInfo::getLibraryPaths(int* size)
{
#ifdef UNX
static char const * ar[] = {
#ifdef MACOSX
"/../Libraries",
"/lib"
#else
"/bin",
"/jre/bin",
"/bin/classic",
"/jre/bin/classic",
"/lib/" JFW_PLUGIN_ARCH "/client",
"/lib/" JFW_PLUGIN_ARCH "/server",
"/lib/" JFW_PLUGIN_ARCH "/classic",
"/lib/" JFW_PLUGIN_ARCH "/jrockit",
"/lib/" JFW_PLUGIN_ARCH "/native_threads",
"/lib/" JFW_PLUGIN_ARCH
#endif
};
*size = sizeof(ar) / sizeof (char*);
return ar;
#endif
size = 0;
return NULL;
}
int OtherInfo::compareVersions(const rtl::OUString& sSecond) const
{
//Need to provide an own algorithm for comparing version.
//Because this function returns always 0, which means the version of
//this JRE and the provided version "sSecond" are equal, one cannot put
//any excludeVersion entries in the javavendors.xml file.
return 0;
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.8.6); FILE MERGED 2006/04/07 19:55:44 sb 1.8.6.4: RESYNC: (1.10-1.11); FILE MERGED 2006/01/25 20:29:13 sb 1.8.6.3: RESYNC: (1.9-1.10); FILE MERGED 2005/11/07 18:54:37 pl 1.8.6.2: RESYNC: (1.8-1.9); FILE MERGED 2005/10/27 15:08:47 pl 1.8.6.1: #i55991# removed warnings for solaris platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: otherjre.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2006-06-20 00:08: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
*
************************************************************************/
#include "osl/thread.h"
#include "otherjre.hxx"
using namespace rtl;
using namespace std;
namespace jfw_plugin
{
Reference<VendorBase> OtherInfo::createInstance()
{
return new OtherInfo;
}
char const* const* OtherInfo::getJavaExePaths(int * size)
{
static char const * ar[] = {
#ifdef WNT
"bin/java.exe",
"jre/bin/java.exe"
#elif UNX
"bin/java",
"jre/bin/java"
#endif
};
*size = sizeof (ar) / sizeof (char*);
return ar;
}
char const* const* OtherInfo::getRuntimePaths(int * size)
{
static char const* ar[]= {
#ifdef WNT
"/bin/client/jvm.dll",
"/bin/hotspot/jvm.dll",
"/bin/classic/jvm.dll",
"/bin/jrockit/jvm.dll"
#elif UNX
#ifdef MACOSX
"/../../../JavaVM"
#else
"/bin/classic/libjvm.so", // for IBM Java
"/jre/bin/classic/libjvm.so", // for IBM Java
"/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC
"/lib/" JFW_PLUGIN_ARCH "/server/libjvm.so", // for Blackdown AMD64
"/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so", // for Blackdown PPC
"/lib/" JFW_PLUGIN_ARCH "/jrockit/libjvm.so" // for Java of BEA Systems
#endif
#endif
};
*size = sizeof(ar) / sizeof (char*);
return ar;
}
char const* const* OtherInfo::getLibraryPaths(int* size)
{
#ifdef UNX
static char const * ar[] = {
#ifdef MACOSX
"/../Libraries",
"/lib"
#else
"/bin",
"/jre/bin",
"/bin/classic",
"/jre/bin/classic",
"/lib/" JFW_PLUGIN_ARCH "/client",
"/lib/" JFW_PLUGIN_ARCH "/server",
"/lib/" JFW_PLUGIN_ARCH "/classic",
"/lib/" JFW_PLUGIN_ARCH "/jrockit",
"/lib/" JFW_PLUGIN_ARCH "/native_threads",
"/lib/" JFW_PLUGIN_ARCH
#endif
};
*size = sizeof(ar) / sizeof (char*);
return ar;
#else
size = 0;
return NULL;
#endif
}
int OtherInfo::compareVersions(const rtl::OUString& /*sSecond*/) const
{
//Need to provide an own algorithm for comparing version.
//Because this function returns always 0, which means the version of
//this JRE and the provided version "sSecond" are equal, one cannot put
//any excludeVersion entries in the javavendors.xml file.
return 0;
}
}
<|endoftext|> |
<commit_before>//===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
//
// This file implements the BUDataStructures class, which represents the
// Bottom-Up Interprocedural closure of the data structure graph over the
// program. This is useful for applications like pool allocation, but **not**
// applications like alias analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Analysis/DSGraph.h"
#include "llvm/Module.h"
//#include "llvm/DerivedTypes.h"
#include "Support/Statistic.h"
//#include <set>
using std::map;
static RegisterAnalysis<BUDataStructures>
X("budatastructure", "Bottom-up Data Structure Analysis Closure");
// TODO: FIXME
namespace DataStructureAnalysis {
// isPointerType - Return true if this first class type is big enough to hold
// a pointer.
//
bool isPointerType(const Type *Ty);
}
using namespace DataStructureAnalysis;
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
void BUDataStructures::releaseMemory() {
for (map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I)
delete I->second;
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
}
// run - Calculate the bottom up data structure graphs for each function in the
// program.
//
bool BUDataStructures::run(Module &M) {
// Simply calculate the graphs for each function...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal())
calculateGraph(*I);
return false;
}
// ResolveArguments - Resolve the formal and actual arguments for a function
// call.
//
static void ResolveArguments(std::vector<DSNodeHandle> &Call, Function &F,
map<Value*, DSNodeHandle> &ValueMap) {
// Resolve all of the function arguments...
Function::aiterator AI = F.abegin();
for (unsigned i = 2, e = Call.size(); i != e; ++i) {
// Advance the argument iterator to the first pointer argument...
while (!isPointerType(AI->getType())) ++AI;
// Add the link from the argument scalar to the provided value
DSNodeHandle &NN = ValueMap[AI];
NN.addEdgeTo(Call[i]);
++AI;
}
}
// MergeGlobalNodes - Merge all existing global nodes with globals
// inlined from the callee or with globals from the GlobalsGraph.
//
static void MergeGlobalNodes(DSGraph &Graph,
map<Value*, DSNodeHandle> &OldValMap) {
map<Value*, DSNodeHandle> &ValMap = Graph.getValueMap();
for (map<Value*, DSNodeHandle>::iterator I = ValMap.begin(), E = ValMap.end();
I != E; ++I)
if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
map<Value*, DSNodeHandle>::iterator NHI = OldValMap.find(GV);
if (NHI != OldValMap.end()) // was it inlined from the callee?
I->second.mergeWith(NHI->second);
#if 0
else // get it from the GlobalsGraph
I->second.mergeWith(Graph.cloneGlobalInto(GV));
#endif
}
// Add unused inlined global nodes into the value map
for (map<Value*, DSNodeHandle>::iterator I = OldValMap.begin(),
E = OldValMap.end(); I != E; ++I)
if (isa<GlobalValue>(I->first)) {
DSNodeHandle &NH = ValMap[I->first]; // If global is not in ValMap...
if (NH.getNode() == 0)
NH = I->second; // Add the one just inlined.
}
}
DSGraph &BUDataStructures::calculateGraph(Function &F) {
// Make sure this graph has not already been calculated, or that we don't get
// into an infinite loop with mutually recursive functions.
//
DSGraph *&Graph = DSInfo[&F];
if (Graph) return *Graph;
// Copy the local version into DSInfo...
Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(F));
#if 0
// Populate the GlobalsGraph with globals from this one.
Graph->GlobalsGraph->cloneGlobals(*Graph, /*cloneCalls*/ false);
// Save a copy of the original call nodes for the top-down pass
Graph->saveOrigFunctionCalls();
#endif
// Start resolving calls...
std::vector<std::vector<DSNodeHandle> > &FCs = Graph->getFunctionCalls();
DEBUG(std::cerr << " [BU] Inlining: " << F.getName() << "\n");
#if 0
// Add F to the PendingCallers list of each direct callee for use in the
// top-down pass so we don't have to compute this again. We don't want
// to do it for indirect callees inlined later, so remember which calls
// are in the original FCs set.
std::set<const DSNode*> directCallees;
for (unsigned i = 0; i < FCs.size(); ++i)
directCallees.insert(FCs[i][1]); // ptr to function node
#endif
bool Inlined;
do {
Inlined = false;
for (unsigned i = 0; i != FCs.size(); ++i) {
// Copy the call, because inlining graphs may invalidate the FCs vector.
std::vector<DSNodeHandle> Call = FCs[i];
// If the function list is complete...
if ((Call[1].getNode()->NodeType & DSNode::Incomplete) == 0) {
// Start inlining all of the functions we can... some may not be
// inlinable if they are external...
//
std::vector<GlobalValue*> Callees(Call[1].getNode()->getGlobals());
// Loop over the functions, inlining whatever we can...
for (unsigned c = 0; c != Callees.size(); ++c) {
// Must be a function type, so this cast MUST succeed.
Function &FI = cast<Function>(*Callees[c]);
if (&FI == &F) {
// Self recursion... simply link up the formal arguments with the
// actual arguments...
DEBUG(std::cerr << "\t[BU] Self Inlining: " << F.getName() << "\n");
if (Call[0].getNode()) // Handle the return value if present...
Graph->getRetNode().mergeWith(Call[0]);
// Resolve the arguments in the call to the actual values...
ResolveArguments(Call, F, Graph->getValueMap());
// Erase the entry in the callees vector
Callees.erase(Callees.begin()+c--);
} else if (!FI.isExternal()) {
DEBUG(std::cerr << "\t[BU] In " << F.getName() << " inlining: "
<< FI.getName() << "\n");
// Get the data structure graph for the called function, closing it
// if possible (which is only impossible in the case of mutual
// recursion...
//
DSGraph &GI = calculateGraph(FI); // Graph to inline
DEBUG(std::cerr << "\t\t[BU] Got graph for " << FI.getName()
<< " in: " << F.getName() << "\n");
// Clone the callee's graph into the current graph, keeping
// track of where scalars in the old graph _used_ to point,
// and of the new nodes matching nodes of the old graph.
map<Value*, DSNodeHandle> OldValMap;
map<const DSNode*, DSNode*> OldNodeMap;
// The clone call may invalidate any of the vectors in the data
// structure graph. Strip locals and don't copy the list of callers
DSNodeHandle RetVal = Graph->cloneInto(GI, OldValMap, OldNodeMap,
/*StripScalars*/ true,
/*StripAllocas*/ true,
/*CopyCallers*/ false,
/*CopyOrigCalls*/ false);
// Resolve the arguments in the call to the actual values...
ResolveArguments(Call, FI, OldValMap);
if (Call[0].getNode()) // Handle the return value if present
RetVal.mergeWith(Call[0]);
// Merge global value nodes in the inlined graph with the global
// value nodes in the current graph if there are duplicates.
//
MergeGlobalNodes(*Graph, OldValMap);
#if 0
// If this was an original call, add F to the PendingCallers list
if (directCallees.find(Call[1]) != directCallees.end())
GI.addCaller(F);
#endif
// Erase the entry in the Callees vector
Callees.erase(Callees.begin()+c--);
} else if (FI.getName() == "printf" || FI.getName() == "sscanf" ||
FI.getName() == "fprintf" || FI.getName() == "open" ||
FI.getName() == "sprintf") {
// Erase the entry in the globals vector
Callees.erase(Callees.begin()+c--);
}
}
if (Callees.empty()) { // Inlined all of the function calls?
// Erase the call if it is resolvable...
FCs.erase(FCs.begin()+i--); // Don't skip a the next call...
Inlined = true;
} else if (Callees.size() != Call[1].getNode()->getGlobals().size()) {
// Was able to inline SOME, but not all of the functions. Construct a
// new global node here.
//
assert(0 && "Unimpl!");
Inlined = true;
}
}
}
// Recompute the Incomplete markers. If there are any function calls left
// now that are complete, we must loop!
if (Inlined) {
Graph->maskIncompleteMarkers();
Graph->markIncompleteNodes();
Graph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
}
} while (Inlined && !FCs.empty());
#if 0
// Copy any unresolved call nodes into the Globals graph and
// filter out unresolved call nodes inlined from the callee.
if (!FCs.empty())
Graph->GlobalsGraph->cloneCalls(*Graph);
#endif
Graph->maskIncompleteMarkers();
Graph->markIncompleteNodes();
Graph->removeTriviallyDeadNodes(false);
Graph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
DEBUG(std::cerr << " [BU] Done inlining: " << F.getName() << " ["
<< Graph->getGraphSize() << "+" << Graph->getFunctionCalls().size()
<< "]\n");
return *Graph;
}
<commit_msg> * Add data structures and code to track the call sites for each function<commit_after>//===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
//
// This file implements the BUDataStructures class, which represents the
// Bottom-Up Interprocedural closure of the data structure graph over the
// program. This is useful for applications like pool allocation, but **not**
// applications like alias analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Analysis/DSGraph.h"
#include "llvm/Module.h"
#include "Support/Statistic.h"
using std::map;
static RegisterAnalysis<BUDataStructures>
X("budatastructure", "Bottom-up Data Structure Analysis Closure");
// TODO: FIXME
namespace DataStructureAnalysis {
// isPointerType - Return true if this first class type is big enough to hold
// a pointer.
//
bool isPointerType(const Type *Ty);
}
using namespace DataStructureAnalysis;
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
void BUDataStructures::releaseMemory() {
// Delete all call site information
CallSites.clear();
for (map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I)
delete I->second;
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
}
// run - Calculate the bottom up data structure graphs for each function in the
// program.
//
bool BUDataStructures::run(Module &M) {
// Simply calculate the graphs for each function...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal())
calculateGraph(*I);
return false;
}
// ResolveArguments - Resolve the formal and actual arguments for a function
// call.
//
static void ResolveArguments(std::vector<DSNodeHandle> &Call, Function &F,
map<Value*, DSNodeHandle> &ValueMap) {
// Resolve all of the function arguments...
Function::aiterator AI = F.abegin();
for (unsigned i = 2, e = Call.size(); i != e; ++i) {
// Advance the argument iterator to the first pointer argument...
while (!isPointerType(AI->getType())) ++AI;
// Add the link from the argument scalar to the provided value
DSNodeHandle &NN = ValueMap[AI];
NN.addEdgeTo(Call[i]);
++AI;
}
}
// MergeGlobalNodes - Merge all existing global nodes with globals
// inlined from the callee or with globals from the GlobalsGraph.
//
static void MergeGlobalNodes(DSGraph &Graph,
map<Value*, DSNodeHandle> &OldValMap) {
map<Value*, DSNodeHandle> &ValMap = Graph.getValueMap();
for (map<Value*, DSNodeHandle>::iterator I = ValMap.begin(), E = ValMap.end();
I != E; ++I)
if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
map<Value*, DSNodeHandle>::iterator NHI = OldValMap.find(GV);
if (NHI != OldValMap.end()) // was it inlined from the callee?
I->second.mergeWith(NHI->second);
#if 0
else // get it from the GlobalsGraph
I->second.mergeWith(Graph.cloneGlobalInto(GV));
#endif
}
// Add unused inlined global nodes into the value map
for (map<Value*, DSNodeHandle>::iterator I = OldValMap.begin(),
E = OldValMap.end(); I != E; ++I)
if (isa<GlobalValue>(I->first)) {
DSNodeHandle &NH = ValMap[I->first]; // If global is not in ValMap...
if (NH.getNode() == 0)
NH = I->second; // Add the one just inlined.
}
}
DSGraph &BUDataStructures::calculateGraph(Function &F) {
// Make sure this graph has not already been calculated, or that we don't get
// into an infinite loop with mutually recursive functions.
//
DSGraph *&Graph = DSInfo[&F];
if (Graph) return *Graph;
// Copy the local version into DSInfo...
Graph = new DSGraph(getAnalysis<LocalDataStructures>().getDSGraph(F));
#if 0
// Populate the GlobalsGraph with globals from this one.
Graph->GlobalsGraph->cloneGlobals(*Graph, /*cloneCalls*/ false);
// Save a copy of the original call nodes for the top-down pass
Graph->saveOrigFunctionCalls();
#endif
// Start resolving calls...
std::vector<std::vector<DSNodeHandle> > &FCs = Graph->getFunctionCalls();
DEBUG(std::cerr << " [BU] Inlining: " << F.getName() << "\n");
#if 0
// Add F to the PendingCallers list of each direct callee for use in the
// top-down pass so we don't have to compute this again. We don't want
// to do it for indirect callees inlined later, so remember which calls
// are in the original FCs set.
std::set<const DSNode*> directCallees;
for (unsigned i = 0; i < FCs.size(); ++i)
directCallees.insert(FCs[i][1]); // ptr to function node
#endif
bool Inlined;
do {
Inlined = false;
for (unsigned i = 0; i != FCs.size(); ++i) {
// Copy the call, because inlining graphs may invalidate the FCs vector.
std::vector<DSNodeHandle> Call = FCs[i];
// If the function list is complete...
if ((Call[1].getNode()->NodeType & DSNode::Incomplete) == 0) {
// Start inlining all of the functions we can... some may not be
// inlinable if they are external...
//
std::vector<GlobalValue*> Callees(Call[1].getNode()->getGlobals());
// Loop over the functions, inlining whatever we can...
for (unsigned c = 0; c != Callees.size(); ++c) {
// Must be a function type, so this cast MUST succeed.
Function &FI = cast<Function>(*Callees[c]);
// Record that this is a call site of FI.
CallSites[&FI].push_back(CallSite(F, Call));
if (&FI == &F) {
// Self recursion... simply link up the formal arguments with the
// actual arguments...
DEBUG(std::cerr << "\t[BU] Self Inlining: " << F.getName() << "\n");
if (Call[0].getNode()) // Handle the return value if present...
Graph->getRetNode().mergeWith(Call[0]);
// Resolve the arguments in the call to the actual values...
ResolveArguments(Call, F, Graph->getValueMap());
// Erase the entry in the callees vector
Callees.erase(Callees.begin()+c--);
} else if (!FI.isExternal()) {
DEBUG(std::cerr << "\t[BU] In " << F.getName() << " inlining: "
<< FI.getName() << "\n");
// Get the data structure graph for the called function, closing it
// if possible (which is only impossible in the case of mutual
// recursion...
//
DSGraph &GI = calculateGraph(FI); // Graph to inline
DEBUG(std::cerr << "\t\t[BU] Got graph for " << FI.getName()
<< " in: " << F.getName() << "\n");
// Clone the callee's graph into the current graph, keeping
// track of where scalars in the old graph _used_ to point,
// and of the new nodes matching nodes of the old graph.
map<Value*, DSNodeHandle> OldValMap;
map<const DSNode*, DSNode*> OldNodeMap;
// The clone call may invalidate any of the vectors in the data
// structure graph. Strip locals and don't copy the list of callers
DSNodeHandle RetVal = Graph->cloneInto(GI, OldValMap, OldNodeMap,
/*StripScalars*/ true,
/*StripAllocas*/ true,
/*CopyCallers*/ false,
/*CopyOrigCalls*/ false);
// Resolve the arguments in the call to the actual values...
ResolveArguments(Call, FI, OldValMap);
if (Call[0].getNode()) // Handle the return value if present
RetVal.mergeWith(Call[0]);
// Merge global value nodes in the inlined graph with the global
// value nodes in the current graph if there are duplicates.
//
MergeGlobalNodes(*Graph, OldValMap);
#if 0
// If this was an original call, add F to the PendingCallers list
if (directCallees.find(Call[1]) != directCallees.end())
GI.addCaller(F);
#endif
// Erase the entry in the Callees vector
Callees.erase(Callees.begin()+c--);
} else if (FI.getName() == "printf" || FI.getName() == "sscanf" ||
FI.getName() == "fprintf" || FI.getName() == "open" ||
FI.getName() == "sprintf") {
// Erase the entry in the globals vector
Callees.erase(Callees.begin()+c--);
}
}
if (Callees.empty()) { // Inlined all of the function calls?
// Erase the call if it is resolvable...
FCs.erase(FCs.begin()+i--); // Don't skip a the next call...
Inlined = true;
} else if (Callees.size() != Call[1].getNode()->getGlobals().size()) {
// Was able to inline SOME, but not all of the functions. Construct a
// new global node here.
//
assert(0 && "Unimpl!");
Inlined = true;
}
}
}
// Recompute the Incomplete markers. If there are any function calls left
// now that are complete, we must loop!
if (Inlined) {
Graph->maskIncompleteMarkers();
Graph->markIncompleteNodes();
Graph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
}
} while (Inlined && !FCs.empty());
#if 0
// Copy any unresolved call nodes into the Globals graph and
// filter out unresolved call nodes inlined from the callee.
if (!FCs.empty())
Graph->GlobalsGraph->cloneCalls(*Graph);
#endif
Graph->maskIncompleteMarkers();
Graph->markIncompleteNodes();
Graph->removeTriviallyDeadNodes(false);
Graph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
DEBUG(std::cerr << " [BU] Done inlining: " << F.getName() << " ["
<< Graph->getGraphSize() << "+" << Graph->getFunctionCalls().size()
<< "]\n");
return *Graph;
}
<|endoftext|> |
<commit_before>//===--- ExecuteCompilerInvocation.cpp ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file holds ExecuteCompilerInvocation(). It is split into its own file to
// minimize the impact of pulling in essentially everything else in Clang.
//
//===----------------------------------------------------------------------===//
#include "clang/FrontendTool/Utils.h"
#include "clang/ARCMigrate/ARCMTActions.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
using namespace llvm::opt;
static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
using namespace clang::frontend;
StringRef Action("unknown");
switch (CI.getFrontendOpts().ProgramAction) {
case ASTDeclList: return new ASTDeclListAction();
case ASTDump: return new ASTDumpAction();
case ASTPrint: return new ASTPrintAction();
case ASTView: return new ASTViewAction();
case DumpRawTokens: return new DumpRawTokensAction();
case DumpTokens: return new DumpTokensAction();
case EmitAssembly: return new EmitAssemblyAction();
case EmitBC: return new EmitBCAction();
#ifdef CLANG_ENABLE_REWRITER
case EmitHTML: return new HTMLPrintAction();
#else
case EmitHTML: Action = "EmitHTML"; break;
#endif
case EmitLLVM: return new EmitLLVMAction();
case EmitLLVMOnly: return new EmitLLVMOnlyAction();
case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
case EmitObj: return new EmitObjAction();
#ifdef CLANG_ENABLE_REWRITER
case FixIt: return new FixItAction();
#else
case FixIt: Action = "FixIt"; break;
#endif
case GenerateModule: return new GenerateModuleAction;
case GeneratePCH: return new GeneratePCHAction;
case GeneratePTH: return new GeneratePTHAction();
case InitOnly: return new InitOnlyAction();
case ParseSyntaxOnly: return new SyntaxOnlyAction();
case ModuleFileInfo: return new DumpModuleInfoAction();
case PluginAction: {
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
it != ie; ++it) {
if (it->getName() == CI.getFrontendOpts().ActionName) {
OwningPtr<PluginASTAction> P(it->instantiate());
if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
return 0;
return P.take();
}
}
CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
<< CI.getFrontendOpts().ActionName;
return 0;
}
case PrintDeclContext: return new DeclContextPrintAction();
case PrintPreamble: return new PrintPreambleAction();
case PrintPreprocessedInput: {
if (CI.getPreprocessorOutputOpts().RewriteIncludes) {
#ifdef CLANG_ENABLE_REWRITER
return new RewriteIncludesAction();
#else
Action = "RewriteIncludesAction";
break;
#endif
}
return new PrintPreprocessedAction();
}
#ifdef CLANG_ENABLE_REWRITER
case RewriteMacros: return new RewriteMacrosAction();
case RewriteObjC: return new RewriteObjCAction();
case RewriteTest: return new RewriteTestAction();
#else
case RewriteMacros: Action = "RewriteMacros"; break;
case RewriteObjC: Action = "RewriteObjC"; break;
case RewriteTest: Action = "RewriteTest"; break;
#endif
#ifdef CLANG_ENABLE_ARCMT
case MigrateSource: return new arcmt::MigrateSourceAction();
#else
case MigrateSource: Action = "MigrateSource"; break;
#endif
#ifdef CLANG_ENABLE_STATIC_ANALYZER
case RunAnalysis: return new ento::AnalysisAction();
#else
case RunAnalysis: Action = "RunAnalysis"; break;
#endif
case RunPreprocessorOnly: return new PreprocessOnlyAction();
}
#if !defined(CLANG_ENABLE_ARCMT) || !defined(CLANG_ENABLE_STATIC_ANALYZER) \
|| !defined(CLANG_ENABLE_REWRITER)
CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
return 0;
#else
llvm_unreachable("Invalid program action!");
#endif
}
static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
// Create the underlying action.
FrontendAction *Act = CreateFrontendBaseAction(CI);
if (!Act)
return 0;
const FrontendOptions &FEOpts = CI.getFrontendOpts();
#ifdef CLANG_ENABLE_REWRITER
if (FEOpts.FixAndRecompile) {
Act = new FixItRecompile(Act);
}
#endif
#ifdef CLANG_ENABLE_ARCMT
// Potentially wrap the base FE action in an ARC Migrate Tool action.
switch (FEOpts.ARCMTAction) {
case FrontendOptions::ARCMT_None:
break;
case FrontendOptions::ARCMT_Check:
Act = new arcmt::CheckAction(Act);
break;
case FrontendOptions::ARCMT_Modify:
Act = new arcmt::ModifyAction(Act);
break;
case FrontendOptions::ARCMT_Migrate:
Act = new arcmt::MigrateAction(Act,
FEOpts.MTMigrateDir,
FEOpts.ARCMTMigrateReportOut,
FEOpts.ARCMTMigrateEmitARCErrors);
break;
}
if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
Act = new arcmt::ObjCMigrateAction(Act, FEOpts.MTMigrateDir,
FEOpts.ObjCMTAction);
}
#endif
// If there are any AST files to merge, create a frontend action
// adaptor to perform the merge.
if (!FEOpts.ASTMergeFiles.empty())
Act = new ASTMergeAction(Act, FEOpts.ASTMergeFiles);
return Act;
}
bool clang::ExecuteCompilerInvocation(CompilerInstance *Clang) {
// Honor -help.
if (Clang->getFrontendOpts().ShowHelp) {
OwningPtr<OptTable> Opts(driver::createDriverOptTable());
Opts->PrintHelp(llvm::outs(), "clang -cc1",
"LLVM 'Clang' Compiler: http://clang.llvm.org",
/*Include=*/ driver::options::CC1Option, /*Exclude=*/ 0);
return true;
}
// Honor -version.
//
// FIXME: Use a better -version message?
if (Clang->getFrontendOpts().ShowVersion) {
llvm::cl::PrintVersionMessage();
return true;
}
// Load any requested plugins.
for (unsigned i = 0,
e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
const std::string &Path = Clang->getFrontendOpts().Plugins[i];
std::string Error;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
<< Path << Error;
}
// Honor -mllvm.
//
// FIXME: Remove this, one day.
// This should happen AFTER plugins have been loaded!
if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
const char **Args = new const char*[NumArgs + 2];
Args[0] = "clang (LLVM option parsing)";
for (unsigned i = 0; i != NumArgs; ++i)
Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
Args[NumArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
}
#ifdef CLANG_ENABLE_STATIC_ANALYZER
// Honor -analyzer-checker-help.
// This should happen AFTER plugins have been loaded!
if (Clang->getAnalyzerOpts()->ShowCheckerHelp) {
ento::printCheckerHelp(llvm::outs(), Clang->getFrontendOpts().Plugins);
return true;
}
#endif
// If there were errors in processing arguments, don't do anything else.
if (Clang->getDiagnostics().hasErrorOccurred())
return false;
// Create and execute the frontend action.
OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
if (!Act)
return false;
bool Success = Clang->ExecuteAction(*Act);
if (Clang->getFrontendOpts().DisableFree)
Act.take();
return Success;
}
<commit_msg>[objcmt] If the frontend option is frontend::MigrateSource then we don't need to create the arcmt wrappers.<commit_after>//===--- ExecuteCompilerInvocation.cpp ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file holds ExecuteCompilerInvocation(). It is split into its own file to
// minimize the impact of pulling in essentially everything else in Clang.
//
//===----------------------------------------------------------------------===//
#include "clang/FrontendTool/Utils.h"
#include "clang/ARCMigrate/ARCMTActions.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
using namespace llvm::opt;
static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
using namespace clang::frontend;
StringRef Action("unknown");
switch (CI.getFrontendOpts().ProgramAction) {
case ASTDeclList: return new ASTDeclListAction();
case ASTDump: return new ASTDumpAction();
case ASTPrint: return new ASTPrintAction();
case ASTView: return new ASTViewAction();
case DumpRawTokens: return new DumpRawTokensAction();
case DumpTokens: return new DumpTokensAction();
case EmitAssembly: return new EmitAssemblyAction();
case EmitBC: return new EmitBCAction();
#ifdef CLANG_ENABLE_REWRITER
case EmitHTML: return new HTMLPrintAction();
#else
case EmitHTML: Action = "EmitHTML"; break;
#endif
case EmitLLVM: return new EmitLLVMAction();
case EmitLLVMOnly: return new EmitLLVMOnlyAction();
case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
case EmitObj: return new EmitObjAction();
#ifdef CLANG_ENABLE_REWRITER
case FixIt: return new FixItAction();
#else
case FixIt: Action = "FixIt"; break;
#endif
case GenerateModule: return new GenerateModuleAction;
case GeneratePCH: return new GeneratePCHAction;
case GeneratePTH: return new GeneratePTHAction();
case InitOnly: return new InitOnlyAction();
case ParseSyntaxOnly: return new SyntaxOnlyAction();
case ModuleFileInfo: return new DumpModuleInfoAction();
case PluginAction: {
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
it != ie; ++it) {
if (it->getName() == CI.getFrontendOpts().ActionName) {
OwningPtr<PluginASTAction> P(it->instantiate());
if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
return 0;
return P.take();
}
}
CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
<< CI.getFrontendOpts().ActionName;
return 0;
}
case PrintDeclContext: return new DeclContextPrintAction();
case PrintPreamble: return new PrintPreambleAction();
case PrintPreprocessedInput: {
if (CI.getPreprocessorOutputOpts().RewriteIncludes) {
#ifdef CLANG_ENABLE_REWRITER
return new RewriteIncludesAction();
#else
Action = "RewriteIncludesAction";
break;
#endif
}
return new PrintPreprocessedAction();
}
#ifdef CLANG_ENABLE_REWRITER
case RewriteMacros: return new RewriteMacrosAction();
case RewriteObjC: return new RewriteObjCAction();
case RewriteTest: return new RewriteTestAction();
#else
case RewriteMacros: Action = "RewriteMacros"; break;
case RewriteObjC: Action = "RewriteObjC"; break;
case RewriteTest: Action = "RewriteTest"; break;
#endif
#ifdef CLANG_ENABLE_ARCMT
case MigrateSource: return new arcmt::MigrateSourceAction();
#else
case MigrateSource: Action = "MigrateSource"; break;
#endif
#ifdef CLANG_ENABLE_STATIC_ANALYZER
case RunAnalysis: return new ento::AnalysisAction();
#else
case RunAnalysis: Action = "RunAnalysis"; break;
#endif
case RunPreprocessorOnly: return new PreprocessOnlyAction();
}
#if !defined(CLANG_ENABLE_ARCMT) || !defined(CLANG_ENABLE_STATIC_ANALYZER) \
|| !defined(CLANG_ENABLE_REWRITER)
CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
return 0;
#else
llvm_unreachable("Invalid program action!");
#endif
}
static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
// Create the underlying action.
FrontendAction *Act = CreateFrontendBaseAction(CI);
if (!Act)
return 0;
const FrontendOptions &FEOpts = CI.getFrontendOpts();
#ifdef CLANG_ENABLE_REWRITER
if (FEOpts.FixAndRecompile) {
Act = new FixItRecompile(Act);
}
#endif
#ifdef CLANG_ENABLE_ARCMT
if (CI.getFrontendOpts().ProgramAction != frontend::MigrateSource) {
// Potentially wrap the base FE action in an ARC Migrate Tool action.
switch (FEOpts.ARCMTAction) {
case FrontendOptions::ARCMT_None:
break;
case FrontendOptions::ARCMT_Check:
Act = new arcmt::CheckAction(Act);
break;
case FrontendOptions::ARCMT_Modify:
Act = new arcmt::ModifyAction(Act);
break;
case FrontendOptions::ARCMT_Migrate:
Act = new arcmt::MigrateAction(Act,
FEOpts.MTMigrateDir,
FEOpts.ARCMTMigrateReportOut,
FEOpts.ARCMTMigrateEmitARCErrors);
break;
}
if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
Act = new arcmt::ObjCMigrateAction(Act, FEOpts.MTMigrateDir,
FEOpts.ObjCMTAction);
}
}
#endif
// If there are any AST files to merge, create a frontend action
// adaptor to perform the merge.
if (!FEOpts.ASTMergeFiles.empty())
Act = new ASTMergeAction(Act, FEOpts.ASTMergeFiles);
return Act;
}
bool clang::ExecuteCompilerInvocation(CompilerInstance *Clang) {
// Honor -help.
if (Clang->getFrontendOpts().ShowHelp) {
OwningPtr<OptTable> Opts(driver::createDriverOptTable());
Opts->PrintHelp(llvm::outs(), "clang -cc1",
"LLVM 'Clang' Compiler: http://clang.llvm.org",
/*Include=*/ driver::options::CC1Option, /*Exclude=*/ 0);
return true;
}
// Honor -version.
//
// FIXME: Use a better -version message?
if (Clang->getFrontendOpts().ShowVersion) {
llvm::cl::PrintVersionMessage();
return true;
}
// Load any requested plugins.
for (unsigned i = 0,
e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
const std::string &Path = Clang->getFrontendOpts().Plugins[i];
std::string Error;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
<< Path << Error;
}
// Honor -mllvm.
//
// FIXME: Remove this, one day.
// This should happen AFTER plugins have been loaded!
if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
const char **Args = new const char*[NumArgs + 2];
Args[0] = "clang (LLVM option parsing)";
for (unsigned i = 0; i != NumArgs; ++i)
Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
Args[NumArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
}
#ifdef CLANG_ENABLE_STATIC_ANALYZER
// Honor -analyzer-checker-help.
// This should happen AFTER plugins have been loaded!
if (Clang->getAnalyzerOpts()->ShowCheckerHelp) {
ento::printCheckerHelp(llvm::outs(), Clang->getFrontendOpts().Plugins);
return true;
}
#endif
// If there were errors in processing arguments, don't do anything else.
if (Clang->getDiagnostics().hasErrorOccurred())
return false;
// Create and execute the frontend action.
OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
if (!Act)
return false;
bool Success = Clang->ExecuteAction(*Act);
if (Clang->getFrontendOpts().DisableFree)
Act.take();
return Success;
}
<|endoftext|> |
<commit_before>// Report data as I2C slave on address 0x70.
#include "LPC8xx.h"
#include "lpc_types.h"
#include "romapi_8xx.h"
#include "serial.h"
#include <string.h>
#define FIXED_CLOCK_RATE_HZ 10000000
#define FIXED_UART_BAUD_RATE 115200
uint32_t i2cBuffer[24]; // data area used by ROM-based I2C driver
I2C_HANDLE_T* ih; // opaque handle used by ROM-based I2C driver
I2C_PARAM_T i2cParam; // input parameters for pending I2C request
I2C_RESULT_T i2cResult; // return values for pending I2C request
uint8_t i2cRecvBuf[2]; // receive buffer: address + register number
uint8_t i2cSendBuf[32]; // send buffer
void timersInit() {
LPC_SYSCON->SYSAHBCLKCTRL |= (1<<10); // enable MRT clock
LPC_SYSCON->PRESETCTRL &= ~(1<<7); // reset MRT
LPC_SYSCON->PRESETCTRL |= (1<<7);
LPC_MRT->Channel[2].CTRL = (0x01 << 1); //MRT2 one-shot mode
}
void delayMs(int milliseconds) {
LPC_MRT->Channel[2].INTVAL = (((FIXED_CLOCK_RATE_HZ / 250L) * milliseconds) >> 2) - 286;
while (LPC_MRT->Channel[2].STAT & 0x02)
; //wait while running
}
void initMainClock() {
LPC_SYSCON->PDRUNCFG &= ~(0x1 << 7); // Power up PLL
LPC_SYSCON->SYSPLLCTRL = 0x24; // MSEL=4, PSEL=1 -> M=5, P=2 -> Fclkout = 60Mhz
while (!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock
LPC_SYSCON->MAINCLKSEL = 0x03; // Set main clock to PLL source and wait for update
LPC_SYSCON->SYSAHBCLKDIV = 6; // Set divider to get final system clock of 10Mhz
LPC_SYSCON->MAINCLKUEN = 0x00;
LPC_SYSCON->MAINCLKUEN = 0x01;
while (!(LPC_SYSCON->MAINCLKUEN & 0x01));
}
#define SW_FREQ 38000
#define SW_MATCH_PERIOD (FIXED_CLOCK_RATE_HZ / SW_FREQ)
#define SW_MATCH_HALF_PERIOD (SW_MATCH_PERIOD / 2)
#define SW_MODULATE_PERIOD_A_ON 1000
#define SW_MODULATE_PERIOD_A_OFF 1000
#define SW_MODULATE_PERIOD_B_ON 2000
#define SW_MODULATE_PERIOD_B_OFF 2000
volatile int g_nextSctModulate = 0;
void sctSquareWaveModulateA() {
LPC_SCT->MATCHREL[0].H = SW_MODULATE_PERIOD_A_ON + SW_MODULATE_PERIOD_A_OFF;
LPC_SCT->MATCHREL[2].H = SW_MODULATE_PERIOD_A_ON;
g_nextSctModulate = 1;
}
void sctSquareWaveModulateB() {
LPC_SCT->MATCHREL[0].H = SW_MODULATE_PERIOD_B_ON + SW_MODULATE_PERIOD_B_OFF;
LPC_SCT->MATCHREL[2].H = SW_MODULATE_PERIOD_B_ON;
g_nextSctModulate = 0;
}
extern "C" void SCT_IRQHandler(void) {
// For full IR send implementation, this handler should do the following:
// * If sequence end reached
// * Configure event 1 to halt both timers and clear output
// * Else
// * Load next H cycle period values into H timer match regs 0 and 2
//
if (g_nextSctModulate) {
sctSquareWaveModulateB();
}
else {
sctSquareWaveModulateA();
}
LPC_SCT->EVFLAG = 0;
}
void initSCTSquareWave() {
// ---------------------------------
// -- Common timer initialisation --
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 8); // Turn on the clock to the SCT
LPC_SWM->PINASSIGN6 = 0x01FFFFFF; // Set up output pin - (ISP)
LPC_SCT->CONFIG = (1<<17)|(1<<18); // H and L 16 bit counter timers, using match reg 0 each to limit
// ------------------------------------------------------
// -- L timer - generates carrier square wave at 38kHz --
// Use match reg 0 to define end of cycle, and act as auto limit
// Use match regs 1 and 2 to define events 1 and 2 for start and
// middle of cycle, turning output on and off respectively
LPC_SCT->MATCH[0].L = SW_MATCH_PERIOD;
LPC_SCT->MATCHREL[0].L = SW_MATCH_PERIOD;
LPC_SCT->MATCH[1].L = 0;
LPC_SCT->MATCHREL[1].L = 0;
LPC_SCT->MATCH[2].L = SW_MATCH_HALF_PERIOD;
LPC_SCT->MATCHREL[2].L = SW_MATCH_HALF_PERIOD;
LPC_SCT->EVENT[0].CTRL = 0x5001;
LPC_SCT->EVENT[0].STATE = 0x01;
LPC_SCT->EVENT[1].CTRL = 0x5002;
LPC_SCT->EVENT[1].STATE = 0x01;
LPC_SCT->OUT[0].SET = 0x01;
LPC_SCT->OUT[0].CLR = 0x0a; // Also turned off by event 3 (see below)
// ----------------------------------------
// -- H timer - modulates L timer on/off --
// Match reg 0 defines overall H timer cycle.
// Event 2 turns on timer L, and occurs at start of H cycle (via match reg 1)
LPC_SCT->MATCH[1].H = 0;
LPC_SCT->MATCHREL[1].H = 0;
LPC_SCT->EVENT[2].CTRL = 0x5011;
LPC_SCT->EVENT[2].STATE = 0x01;
LPC_SCT->START_L = 0x04;
// Event 3 turns off timer L and output, and occurs in middle portion of H cycle
// (via match reg 1) - and fires interrupt to configure the following H cycle.
LPC_SCT->EVENT[3].CTRL = 0x5012;
LPC_SCT->EVENT[3].STATE = 0x01;
LPC_SCT->STOP_L = 0x08;
LPC_SCT->EVEN = 0x08;
NVIC_EnableIRQ(SCT_IRQn);
}
void sctSquareWaveOn() {
// Full implementation for IR send should clear event 1
// from halting timers and clearing output
// Set L counter into stopped but unhalted
uint16_t ctrl_l = LPC_SCT->CTRL_L;
ctrl_l &= ~(1<<2);
ctrl_l |= 1<<1;
LPC_SCT->CTRL_L = ctrl_l;
// Configure & start H counter (which will start L counter)
LPC_SCT->MATCH[0].H = SW_MODULATE_PERIOD_A_ON + SW_MODULATE_PERIOD_A_OFF;
LPC_SCT->MATCH[2].H = SW_MODULATE_PERIOD_A_ON;
g_nextSctModulate = 1;
LPC_SCT->CTRL_H &= ~(1<<2);
}
void sctSquareWaveOff() {
LPC_SCT->CTRL_U |= (1<<2)|(1<<18); // Halt counters
LPC_SCT->CTRL_U |= (1<<3)|(1<<19); // Clear counters
LPC_SCT->OUTPUT = 0; // Clear output
}
void i2cSetupRecv (), i2cSetupSend (int);
void i2cSetup () {
for (int i = 0; i < 3000000; ++i) __ASM("");
LPC_SWM->PINENABLE0 |= 3<<2; // disable SWCLK and SWDIO
LPC_SWM->PINASSIGN7 = 0x02FFFFFF; // SDA on P2, pin 4
LPC_SWM->PINASSIGN8 = 0xFFFFFF03; // SCL on P3, pin 3
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<5; // enable I2C clock
ih = LPC_I2CD_API->i2c_setup(LPC_I2C_BASE, i2cBuffer);
LPC_I2CD_API->i2c_set_slave_addr(ih, 0x70<<1, 0);
NVIC_EnableIRQ(I2C_IRQn);
}
extern "C" void I2C0_IRQHandler () {
LPC_I2CD_API->i2c_isr_handler(ih);
}
void i2cRecvDone (uint32_t err, uint32_t) {
i2cSetupRecv();
if (err == 0)
i2cSetupSend(i2cRecvBuf[1]);
}
void i2cSendDone (uint32_t err, uint32_t) {
i2cSetupRecv();
}
void i2cSetupRecv () {
i2cParam.func_pt = i2cRecvDone;
i2cParam.num_bytes_send = 0;
i2cParam.num_bytes_rec = 2;
i2cParam.buffer_ptr_rec = i2cRecvBuf;
LPC_I2CD_API->i2c_slave_receive_intr(ih, &i2cParam, &i2cResult);
}
void i2cSetupSend (int regNum) {
i2cParam.func_pt = i2cSendDone;
i2cParam.num_bytes_rec = 0;
switch (regNum) {
case 0:
i2cParam.num_bytes_send = 1;
i2cSendBuf[0] = 0xff;
break;
case 1:
i2cParam.num_bytes_send = 16;
strcpy((char*)i2cSendBuf, "0123456789ABCDEF");
break;
case 2:
i2cParam.num_bytes_send = 1;
i2cSendBuf[0] = 0xfe;
sctSquareWaveOn();
break;
case 3:
i2cParam.num_bytes_send = 1;
i2cSendBuf[0] = 0xfd;
sctSquareWaveOff();
break;
}
i2cParam.buffer_ptr_send = i2cSendBuf;
LPC_I2CD_API->i2c_slave_transmit_intr(ih, &i2cParam, &i2cResult);
}
int main () {
initMainClock();
serial.init(LPC_USART0, FIXED_UART_BAUD_RATE);
delayMs(100);
puts("i2c-ir started");
i2cSetup();
i2cSetupRecv();
initSCTSquareWave();
puts("Waiting...");
while (true) {
__WFI();
}
}
<commit_msg>H timer now modulates L timer square wave accurately<commit_after>// Report data as I2C slave on address 0x70.
#include "LPC8xx.h"
#include "lpc_types.h"
#include "romapi_8xx.h"
#include "serial.h"
#include <string.h>
#define FIXED_CLOCK_RATE_HZ 10000000
#define FIXED_UART_BAUD_RATE 115200
uint32_t i2cBuffer[24]; // data area used by ROM-based I2C driver
I2C_HANDLE_T* ih; // opaque handle used by ROM-based I2C driver
I2C_PARAM_T i2cParam; // input parameters for pending I2C request
I2C_RESULT_T i2cResult; // return values for pending I2C request
uint8_t i2cRecvBuf[2]; // receive buffer: address + register number
uint8_t i2cSendBuf[32]; // send buffer
void timersInit() {
LPC_SYSCON->SYSAHBCLKCTRL |= (1<<10); // enable MRT clock
LPC_SYSCON->PRESETCTRL &= ~(1<<7); // reset MRT
LPC_SYSCON->PRESETCTRL |= (1<<7);
LPC_MRT->Channel[2].CTRL = (0x01 << 1); //MRT2 one-shot mode
}
void delayMs(int milliseconds) {
LPC_MRT->Channel[2].INTVAL = (((FIXED_CLOCK_RATE_HZ / 250L) * milliseconds) >> 2) - 286;
while (LPC_MRT->Channel[2].STAT & 0x02)
; //wait while running
}
void initMainClock() {
LPC_SYSCON->PDRUNCFG &= ~(0x1 << 7); // Power up PLL
LPC_SYSCON->SYSPLLCTRL = 0x24; // MSEL=4, PSEL=1 -> M=5, P=2 -> Fclkout = 60Mhz
while (!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock
LPC_SYSCON->MAINCLKSEL = 0x03; // Set main clock to PLL source and wait for update
LPC_SYSCON->SYSAHBCLKDIV = 6; // Set divider to get final system clock of 10Mhz
LPC_SYSCON->MAINCLKUEN = 0x00;
LPC_SYSCON->MAINCLKUEN = 0x01;
while (!(LPC_SYSCON->MAINCLKUEN & 0x01));
}
#define SW_FREQ 38000
#define SW_MATCH_PERIOD (FIXED_CLOCK_RATE_HZ / SW_FREQ)
#define SW_MATCH_HALF_PERIOD (SW_MATCH_PERIOD / 2)
#define SW_MODULATE_PERIOD_A_ON 1000
#define SW_MODULATE_PERIOD_A_OFF 1000
#define SW_MODULATE_PERIOD_B_ON 2000
#define SW_MODULATE_PERIOD_B_OFF 2000
volatile int g_nextSctModulate = 0;
void sctSquareWaveModulateA() {
LPC_SCT->MATCHREL[0].H = SW_MODULATE_PERIOD_A_ON + SW_MODULATE_PERIOD_A_OFF;
LPC_SCT->MATCHREL[2].H = SW_MODULATE_PERIOD_A_ON;
}
void sctSquareWaveModulateB() {
LPC_SCT->MATCHREL[0].H = SW_MODULATE_PERIOD_B_ON + SW_MODULATE_PERIOD_B_OFF;
LPC_SCT->MATCHREL[2].H = SW_MODULATE_PERIOD_B_ON;
}
extern "C" void SCT_IRQHandler(void) {
g_nextSctModulate++;
if (g_nextSctModulate == 4) {
// To finish, event 0 set to halt both timers and clear output
LPC_SCT->HALT_L = 0x01;
LPC_SCT->HALT_H = 0x01;
LPC_SCT->OUT[0].CLR = 0x01;
}
if (g_nextSctModulate & 1) {
sctSquareWaveModulateB();
}
else {
sctSquareWaveModulateA();
}
LPC_SCT->EVFLAG |= 0xf;
}
void initSCTSquareWave() {
// ---------------------------------
// -- Common timer initialisation --
LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 8); // Turn on the clock to the SCT
LPC_SWM->PINASSIGN6 = 0x01FFFFFF; // Set up output pin - (ISP)
LPC_SCT->CONFIG = (1<<17)|(1<<18); // H and L 16 bit counter timers, using match reg 0 each to limit
// ------------------------------------------------------
// -- L timer - generates carrier square wave at 38kHz --
// Use match reg 0 to define end of cycle, and act as auto limit
// Use match regs 1 and 2 to define events 0 and 1 for start and
// middle of cycle, turning output on and off respectively
LPC_SCT->MATCH[0].L = SW_MATCH_PERIOD;
LPC_SCT->MATCHREL[0].L = SW_MATCH_PERIOD;
LPC_SCT->MATCH[1].L = 0;
LPC_SCT->MATCHREL[1].L = 0;
LPC_SCT->MATCH[2].L = SW_MATCH_HALF_PERIOD;
LPC_SCT->MATCHREL[2].L = SW_MATCH_HALF_PERIOD;
LPC_SCT->EVENT[0].CTRL = 0x5001;
LPC_SCT->EVENT[0].STATE = 0x01;
LPC_SCT->EVENT[1].CTRL = 0x5002;
LPC_SCT->EVENT[1].STATE = 0x01;
LPC_SCT->OUT[0].SET = 0x01;
// ----------------------------------------
// -- H timer - modulates L timer on/off --
// Match reg 0 defines overall H timer cycle.
// Event 2 turns on timer L, and occurs at start of H cycle (via match reg 1)
LPC_SCT->MATCH[1].H = 0;
LPC_SCT->MATCHREL[1].H = 0;
LPC_SCT->EVENT[2].CTRL = 0x5011;
LPC_SCT->EVENT[2].STATE = 0x01;
LPC_SCT->START_L = 0x04;
// Event 3 turns off timer L and output, and occurs in middle portion of H cycle
// (via match reg 2) - and fires interrupt to configure the following H cycle.
LPC_SCT->EVENT[3].CTRL = 0x5012;
LPC_SCT->EVENT[3].STATE = 0x01;
LPC_SCT->STOP_L = 0x08;
LPC_SCT->EVEN = 0x08;
NVIC_EnableIRQ(SCT_IRQn);
}
void sctSquareWaveOn() {
LPC_SCT->HALT_L = 0x00;
LPC_SCT->HALT_H = 0x00;
LPC_SCT->OUT[0].CLR = 0x0a; // events 1 and 3 clear output
// Set L counter into stopped but unhalted
uint16_t ctrl_l = LPC_SCT->CTRL_L;
ctrl_l &= ~(1<<2);
ctrl_l |= 1<<1;
LPC_SCT->CTRL_L = ctrl_l;
// Configure & start H counter (which will start L counter)
LPC_SCT->MATCH[0].H = SW_MODULATE_PERIOD_A_ON + SW_MODULATE_PERIOD_A_OFF;
LPC_SCT->MATCH[2].H = SW_MODULATE_PERIOD_A_ON;
g_nextSctModulate = 0;
LPC_SCT->CTRL_U |= (1<<3)|(1<<19); // Clear counters
LPC_SCT->CTRL_H &= ~(1<<2);
}
void sctSquareWaveOff() {
LPC_SCT->CTRL_U |= (1<<2)|(1<<18); // Halt counters
LPC_SCT->CTRL_U |= (1<<3)|(1<<19); // Clear counters
LPC_SCT->OUTPUT = 0; // Clear output
}
void i2cSetupRecv (), i2cSetupSend (int);
void i2cSetup () {
for (int i = 0; i < 3000000; ++i) __ASM("");
LPC_SWM->PINENABLE0 |= 3<<2; // disable SWCLK and SWDIO
LPC_SWM->PINASSIGN7 = 0x02FFFFFF; // SDA on P2, pin 4
LPC_SWM->PINASSIGN8 = 0xFFFFFF03; // SCL on P3, pin 3
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<5; // enable I2C clock
ih = LPC_I2CD_API->i2c_setup(LPC_I2C_BASE, i2cBuffer);
LPC_I2CD_API->i2c_set_slave_addr(ih, 0x70<<1, 0);
NVIC_EnableIRQ(I2C_IRQn);
}
extern "C" void I2C0_IRQHandler () {
LPC_I2CD_API->i2c_isr_handler(ih);
}
void i2cRecvDone (uint32_t err, uint32_t) {
i2cSetupRecv();
if (err == 0)
i2cSetupSend(i2cRecvBuf[1]);
}
void i2cSendDone (uint32_t err, uint32_t) {
i2cSetupRecv();
}
void i2cSetupRecv () {
i2cParam.func_pt = i2cRecvDone;
i2cParam.num_bytes_send = 0;
i2cParam.num_bytes_rec = 2;
i2cParam.buffer_ptr_rec = i2cRecvBuf;
LPC_I2CD_API->i2c_slave_receive_intr(ih, &i2cParam, &i2cResult);
}
void i2cSetupSend (int regNum) {
i2cParam.func_pt = i2cSendDone;
i2cParam.num_bytes_rec = 0;
switch (regNum) {
case 0:
i2cParam.num_bytes_send = 1;
i2cSendBuf[0] = 0xff;
break;
case 1:
i2cParam.num_bytes_send = 16;
strcpy((char*)i2cSendBuf, "0123456789ABCDEF");
break;
case 2:
i2cParam.num_bytes_send = 1;
i2cSendBuf[0] = 0xfe;
sctSquareWaveOn();
break;
case 3:
i2cParam.num_bytes_send = 1;
i2cSendBuf[0] = 0xfd;
sctSquareWaveOff();
break;
}
i2cParam.buffer_ptr_send = i2cSendBuf;
LPC_I2CD_API->i2c_slave_transmit_intr(ih, &i2cParam, &i2cResult);
}
int main () {
initMainClock();
serial.init(LPC_USART0, FIXED_UART_BAUD_RATE);
delayMs(100);
puts("i2c-ir started");
i2cSetup();
i2cSetupRecv();
initSCTSquareWave();
puts("Waiting...");
while (true) {
__WFI();
}
}
<|endoftext|> |
<commit_before>//===- AArch64MachineLegalizer.cpp -------------------------------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for
/// AArch64.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//
#include "AArch64MachineLegalizer.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/Target/TargetOpcodes.h"
using namespace llvm;
#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif
AArch64MachineLegalizer::AArch64MachineLegalizer() {
using namespace TargetOpcode;
const LLT p0 = LLT::pointer(0);
const LLT s1 = LLT::scalar(1);
const LLT s8 = LLT::scalar(8);
const LLT s16 = LLT::scalar(16);
const LLT s32 = LLT::scalar(32);
const LLT s64 = LLT::scalar(64);
const LLT v2s32 = LLT::vector(2, 32);
const LLT v4s32 = LLT::vector(4, 32);
const LLT v2s64 = LLT::vector(2, 64);
for (auto BinOp : {G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR}) {
// These operations naturally get the right answer when used on
// GPR32, even if the actual type is narrower.
for (auto Ty : {s1, s8, s16, s32, s64, v2s32, v4s32, v2s64})
setAction({BinOp, Ty}, Legal);
}
for (auto BinOp : {G_SHL, G_LSHR, G_ASHR, G_SDIV, G_UDIV})
for (auto Ty : {s32, s64})
setAction({BinOp, Ty}, Legal);
for (auto Op : { G_UADDE, G_USUBE, G_SADDO, G_SSUBO, G_SMULO, G_UMULO })
for (auto Ty : { s32, s64 })
setAction({Op, Ty}, Legal);
for (auto BinOp : {G_FADD, G_FSUB, G_FMUL, G_FDIV})
for (auto Ty : {s32, s64})
setAction({BinOp, Ty}, Legal);
for (auto MemOp : {G_LOAD, G_STORE}) {
for (auto Ty : {s8, s16, s32, s64})
setAction({MemOp, Ty}, Legal);
setAction({MemOp, s1}, WidenScalar);
// And everything's fine in addrspace 0.
setAction({MemOp, 1, p0}, Legal);
}
// Constants
for (auto Ty : {s32, s64}) {
setAction({TargetOpcode::G_CONSTANT, Ty}, Legal);
setAction({TargetOpcode::G_FCONSTANT, Ty}, Legal);
}
setAction({G_CONSTANT, p0}, Legal);
for (auto Ty : {s1, s8, s16})
setAction({TargetOpcode::G_CONSTANT, Ty}, WidenScalar);
setAction({TargetOpcode::G_FCONSTANT, s16}, WidenScalar);
// Comparisons: we produce a result in s32 with undefined high-bits for
// now. Values being compared can be 32 or 64-bits.
for (auto CmpOp : { G_ICMP }) {
setAction({CmpOp, 0, s32}, Legal);
setAction({CmpOp, 1, s32}, Legal);
setAction({CmpOp, 1, s64}, Legal);
for (auto Ty : {s1, s8, s16}) {
setAction({CmpOp, 0, Ty}, WidenScalar);
setAction({CmpOp, 1, Ty}, WidenScalar);
}
}
// Extensions
for (auto Ty : { s1, s8, s16, s32, s64 }) {
setAction({G_ZEXT, Ty}, Legal);
setAction({G_SEXT, Ty}, Legal);
setAction({G_ANYEXT, Ty}, Legal);
}
for (auto Ty : { s1, s8, s16, s32 }) {
setAction({G_ZEXT, 1, Ty}, Legal);
setAction({G_SEXT, 1, Ty}, Legal);
setAction({G_ANYEXT, 1, Ty}, Legal);
}
// Truncations
for (auto Ty : { s16, s32 })
setAction({G_FPTRUNC, Ty}, Legal);
for (auto Ty : { s32, s64 })
setAction({G_FPTRUNC, 1, Ty}, Legal);
for (auto Ty : { s1, s8, s16, s32 })
setAction({G_TRUNC, Ty}, Legal);
for (auto Ty : { s8, s16, s32, s64 })
setAction({G_TRUNC, 1, Ty}, Legal);
// Control-flow
setAction({G_BR, LLT::unsized()}, Legal);
setAction({G_BRCOND, s32}, Legal);
for (auto Ty : {s1, s8, s16})
setAction({G_BRCOND, Ty}, WidenScalar);
// Pointer-handling
setAction({G_FRAME_INDEX, p0}, Legal);
setAction({G_PTRTOINT, 0, s64}, Legal);
setAction({G_PTRTOINT, 1, p0}, Legal);
setAction({G_INTTOPTR, 0, p0}, Legal);
setAction({G_INTTOPTR, 1, s64}, Legal);
computeTables();
}
<commit_msg>GlobalISel: mark overflow bit of overflow ops legal.<commit_after>//===- AArch64MachineLegalizer.cpp -------------------------------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for
/// AArch64.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//
#include "AArch64MachineLegalizer.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/Target/TargetOpcodes.h"
using namespace llvm;
#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif
AArch64MachineLegalizer::AArch64MachineLegalizer() {
using namespace TargetOpcode;
const LLT p0 = LLT::pointer(0);
const LLT s1 = LLT::scalar(1);
const LLT s8 = LLT::scalar(8);
const LLT s16 = LLT::scalar(16);
const LLT s32 = LLT::scalar(32);
const LLT s64 = LLT::scalar(64);
const LLT v2s32 = LLT::vector(2, 32);
const LLT v4s32 = LLT::vector(4, 32);
const LLT v2s64 = LLT::vector(2, 64);
for (auto BinOp : {G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR}) {
// These operations naturally get the right answer when used on
// GPR32, even if the actual type is narrower.
for (auto Ty : {s1, s8, s16, s32, s64, v2s32, v4s32, v2s64})
setAction({BinOp, Ty}, Legal);
}
for (auto BinOp : {G_SHL, G_LSHR, G_ASHR, G_SDIV, G_UDIV})
for (auto Ty : {s32, s64})
setAction({BinOp, Ty}, Legal);
for (auto Op : { G_UADDE, G_USUBE, G_SADDO, G_SSUBO, G_SMULO, G_UMULO }) {
for (auto Ty : { s32, s64 })
setAction({Op, Ty}, Legal);
setAction({Op, 1, s1}, Legal);
}
for (auto BinOp : {G_FADD, G_FSUB, G_FMUL, G_FDIV})
for (auto Ty : {s32, s64})
setAction({BinOp, Ty}, Legal);
for (auto MemOp : {G_LOAD, G_STORE}) {
for (auto Ty : {s8, s16, s32, s64})
setAction({MemOp, Ty}, Legal);
setAction({MemOp, s1}, WidenScalar);
// And everything's fine in addrspace 0.
setAction({MemOp, 1, p0}, Legal);
}
// Constants
for (auto Ty : {s32, s64}) {
setAction({TargetOpcode::G_CONSTANT, Ty}, Legal);
setAction({TargetOpcode::G_FCONSTANT, Ty}, Legal);
}
setAction({G_CONSTANT, p0}, Legal);
for (auto Ty : {s1, s8, s16})
setAction({TargetOpcode::G_CONSTANT, Ty}, WidenScalar);
setAction({TargetOpcode::G_FCONSTANT, s16}, WidenScalar);
// Comparisons: we produce a result in s32 with undefined high-bits for
// now. Values being compared can be 32 or 64-bits.
for (auto CmpOp : { G_ICMP }) {
setAction({CmpOp, 0, s32}, Legal);
setAction({CmpOp, 1, s32}, Legal);
setAction({CmpOp, 1, s64}, Legal);
for (auto Ty : {s1, s8, s16}) {
setAction({CmpOp, 0, Ty}, WidenScalar);
setAction({CmpOp, 1, Ty}, WidenScalar);
}
}
// Extensions
for (auto Ty : { s1, s8, s16, s32, s64 }) {
setAction({G_ZEXT, Ty}, Legal);
setAction({G_SEXT, Ty}, Legal);
setAction({G_ANYEXT, Ty}, Legal);
}
for (auto Ty : { s1, s8, s16, s32 }) {
setAction({G_ZEXT, 1, Ty}, Legal);
setAction({G_SEXT, 1, Ty}, Legal);
setAction({G_ANYEXT, 1, Ty}, Legal);
}
// Truncations
for (auto Ty : { s16, s32 })
setAction({G_FPTRUNC, Ty}, Legal);
for (auto Ty : { s32, s64 })
setAction({G_FPTRUNC, 1, Ty}, Legal);
for (auto Ty : { s1, s8, s16, s32 })
setAction({G_TRUNC, Ty}, Legal);
for (auto Ty : { s8, s16, s32, s64 })
setAction({G_TRUNC, 1, Ty}, Legal);
// Control-flow
setAction({G_BR, LLT::unsized()}, Legal);
setAction({G_BRCOND, s32}, Legal);
for (auto Ty : {s1, s8, s16})
setAction({G_BRCOND, Ty}, WidenScalar);
// Pointer-handling
setAction({G_FRAME_INDEX, p0}, Legal);
setAction({G_PTRTOINT, 0, s64}, Legal);
setAction({G_PTRTOINT, 1, p0}, Legal);
setAction({G_INTTOPTR, 0, p0}, Legal);
setAction({G_INTTOPTR, 1, s64}, Legal);
computeTables();
}
<|endoftext|> |
<commit_before>#include <boost/filesystem.hpp>
#include <boost/range/algorithm/mismatch.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <unordered_set>
#include <fstream>
#include <iostream>
namespace meka {
namespace folder {
auto const build = "build";
auto const src = "src";
auto const include = "include";
auto const test = "test";
}
namespace extension {
auto const cpp = { ".cpp", ".cc", ".C", ".c++", ".cxx" };
auto const hpp = { ".hpp", ".hh", ".H", ".h++", ".hxx" };
auto const c = { ".c" };
auto const h = { ".h" };
auto const obj = ".o";
auto const arc = ".a";
}
namespace suffix {
auto const test = "_test";
}
auto const mekaninja = R"(
ninja_required_version = 1.3
builddir = build
cblk = [30m
cred = [31m
cgrn = [32m
cylw = [33m
cblu = [34m
cprp = [35m
ccyn = [36m
cwht = [37m
crgb = [38m
cdef = [39m
crst = [0m
cbblk = ${cblk}[1m
cbred = ${cred}[1m
cbgrn = ${cgrn}[1m
cbylw = ${cylw}[1m
cbblu = ${cblu}[1m
cbprp = ${cprp}[1m
cbcyn = ${ccyn}[1m
cbwht = ${cwht}[1m
cbrgb = ${crgb}[1m
cbdef = ${cdef}[1m
cbrst = ${crst}[1m
cxx = clang++-3.6
cc = clang-3.6
ar = ar
cflags = -std=c11 -fpic -g -O0
cxxflags = -std=c++1y -fpic -g -O0
ldflags = -L$builddir/lib -Wl,-rpath,$builddir/lib -L/usr/local/lib
rule cxx
command = $cxx -MMD -MT $out -MF $out.d $cxxflags $incdirs -xc++ -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule cc
command = $cc -MMD -MT $out -MF $out.d $cflags $incdirs -xc -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule arc
command = rm -f $out && $ar crs $out $in
description = ${cylw}AR${crst} ${cblu}$out${crst}
rule exe
command = $cxx -o $out $in $ldflags -Wl,--start-group $libs -Wl,--end-group
description = ${cylw}EXE${crst} ${cblu}$out${crst}
)";
namespace fs {
using namespace ::boost::filesystem;
auto const filename = [](fs::path path) { return std::move(path).filename().generic_string(); };
auto const relative = [](fs::path from, fs::path to) {
auto const pair = boost::mismatch(from, to);
if (pair.first == std::begin(from))
return std::move(to);
auto rel = fs::path {};
std::for_each(pair.first, from.end(), [&](fs::path const& i) { rel /= ".."; });
std::for_each(pair.second, to.end(), [&](fs::path const& i) { rel /= i; });
return std::move(rel);
};
auto const is_file = [](auto it) {
switch (it.status().type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::directory_file:
case fs::type_unknown:
return false;
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return true;
}
};
auto const is_directory = [](auto it) {
switch (it.status().type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::type_unknown:
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return false;
case fs::directory_file:
return true;
}
};
}
struct project {
project() = default;
project(std::string name, fs::path path, std::vector<fs::path> sources, std::vector<fs::path> tests)
: name(std::move(name)), path(std::move(path)), sources(std::move(sources)), tests(std::move(tests)) {}
std::string name;
fs::path path;
std::vector<fs::path> sources;
std::vector<fs::path> tests;
std::vector<fs::path> objects = {};
std::vector<fs::path> binaries = {};
};
auto const find_sources = [](fs::path root) {
auto sources = std::vector<fs::path> {};
if (!fs::exists(root / folder::src))
return std::move(sources);
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp) &&
std::find(std::begin(extension::c), std::end(extension::c), ext) == std::end(extension::c))
continue;
if (boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
sources.emplace_back(fs::relative(root, *it));
}
return std::move(sources);
};
auto const find_tests = [](fs::path root) {
auto tests = std::vector<fs::path> {};
if (fs::exists(root / folder::src)) {
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
if (!boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
tests.emplace_back(fs::relative(root, *it));
}
}
if (!fs::exists(root / folder::test))
return std::move(tests);
for (auto it = fs::recursive_directory_iterator{root / folder::test}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
tests.emplace_back(fs::relative(root, *it));
}
return std::move(tests);
};
auto const find_projects = [](fs::path root) {
auto names = std::unordered_set<std::string> {};
auto projects = std::vector<project> {};
for (auto it = fs::recursive_directory_iterator{root}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_directory(it))
continue;
auto const base = fs::filename(*it);
if (base == folder::build) {
it.no_push();
continue;
}
if (base == folder::include && fs::exists(*it / ".." / folder::src))
continue;
if (base != folder::src && base != folder::include)
continue;
it.no_push();
auto const path = fs::path(*it).parent_path();
auto const relp = fs::relative(root, path);
auto const name = fs::filename(path);
if (names.find(name) != names.end()) {
std::cerr << "W: project " << name << " in " << path << " already found, ignoring\n";
continue;
}
names.insert(name);
projects.emplace_back(name, relp, find_sources(path), find_tests(path));
}
return std::move(projects);
};
extern "C" int main(int, char*[]) {
auto const root = fs::current_path();
auto const ninja = std::string { std::getenv("NINJA") ? std::getenv("NINJA") : "ninja" };
auto const builddir = fs::path(folder::build);
auto const objdir = builddir / "obj";
auto const libdir = builddir / "lib";
auto const bindir = builddir / "bin";
auto projects = find_projects(root);
{
auto const ninjafile = (objdir / "build.ninja").generic_string();
fs::create_directories(objdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto incdirs = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(incdirs), [&root](auto project) { return "-I" + (project.path / folder::include).generic_string(); });
for (auto const& p : projects) {
for (auto const& s : p.sources) {
if (std::find(std::begin(extension::c), std::end(extension::c), fs::extension(s)) == std::end(extension::c))
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).generic_string() << ": cxx " << (p.path / s).generic_string() << "\n";
else
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).generic_string() << ": cc " << (p.path / s).generic_string() << "\n";
out << " incdirs = -I" << (p.path / folder::src).generic_string() << " " << boost::algorithm::join(incdirs, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (libdir / "build.ninja").generic_string();
fs::create_directories(libdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
for (auto& p : projects) {
for (auto const& s : p.sources) {
auto const object = fs::change_extension(objdir / p.name / s, extension::obj);
auto const command = "nm " + object.generic_string() + " --defined-only | grep --quiet ' T main'";
auto const result = std::system(command.c_str());
if (result)
p.objects.emplace_back(std::move(object));
else
p.binaries.emplace_back(std::move(object));
}
auto objects = std::vector<std::string> {};
std::transform(std::begin(p.objects), std::end(p.objects), std::back_inserter(objects), [](auto path) { return path.generic_string(); });
out << "build " << (libdir / p.name).generic_string() << extension::arc << ": arc $\n";
for (auto const& o : objects)
out << " " << o << " $\n";
out << "\n";
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (bindir / "build.ninja").generic_string();
fs::create_directories(bindir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto archives = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(archives), [libdir](auto project) { return (libdir / project.name).generic_string() + extension::arc; });
for (auto const& p : projects) {
for (auto const& o : p.binaries) {
out << "build " << (bindir / p.name / fs::basename(o)).generic_string() << ": exe " << o.generic_string() << " | " << boost::algorithm::join(archives, " $\n ") << "\n";
out << " libs = " << boost::algorithm::join(archives, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
return 0;
}
}
<commit_msg>Use fs::status(path) instead of it.status().<commit_after>#include <boost/filesystem.hpp>
#include <boost/range/algorithm/mismatch.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <unordered_set>
#include <fstream>
#include <iostream>
namespace meka {
namespace folder {
auto const build = "build";
auto const src = "src";
auto const include = "include";
auto const test = "test";
}
namespace extension {
auto const cpp = { ".cpp", ".cc", ".C", ".c++", ".cxx" };
auto const hpp = { ".hpp", ".hh", ".H", ".h++", ".hxx" };
auto const c = { ".c" };
auto const h = { ".h" };
auto const obj = ".o";
auto const arc = ".a";
}
namespace suffix {
auto const test = "_test";
}
auto const mekaninja = R"(
ninja_required_version = 1.3
builddir = build
cblk = [30m
cred = [31m
cgrn = [32m
cylw = [33m
cblu = [34m
cprp = [35m
ccyn = [36m
cwht = [37m
crgb = [38m
cdef = [39m
crst = [0m
cbblk = ${cblk}[1m
cbred = ${cred}[1m
cbgrn = ${cgrn}[1m
cbylw = ${cylw}[1m
cbblu = ${cblu}[1m
cbprp = ${cprp}[1m
cbcyn = ${ccyn}[1m
cbwht = ${cwht}[1m
cbrgb = ${crgb}[1m
cbdef = ${cdef}[1m
cbrst = ${crst}[1m
cxx = clang++-3.6
cc = clang-3.6
ar = ar
cflags = -std=c11 -fpic -g -O0
cxxflags = -std=c++1y -fpic -g -O0
ldflags = -L$builddir/lib -Wl,-rpath,$builddir/lib -L/usr/local/lib
rule cxx
command = $cxx -MMD -MT $out -MF $out.d $cxxflags $incdirs -xc++ -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule cc
command = $cc -MMD -MT $out -MF $out.d $cflags $incdirs -xc -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule arc
command = rm -f $out && $ar crs $out $in
description = ${cylw}AR${crst} ${cblu}$out${crst}
rule exe
command = $cxx -o $out $in $ldflags -Wl,--start-group $libs -Wl,--end-group
description = ${cylw}EXE${crst} ${cblu}$out${crst}
)";
namespace fs {
using namespace ::boost::filesystem;
auto const filename = [](fs::path path) { return std::move(path).filename().generic_string(); };
auto const relative = [](fs::path from, fs::path to) {
auto const pair = boost::mismatch(from, to);
if (pair.first == std::begin(from))
return std::move(to);
auto rel = fs::path {};
std::for_each(pair.first, from.end(), [&](fs::path const& i) { rel /= ".."; });
std::for_each(pair.second, to.end(), [&](fs::path const& i) { rel /= i; });
return std::move(rel);
};
auto const is_file = [](fs::path path) {
switch (fs::status(path).type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::directory_file:
case fs::type_unknown:
return false;
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return true;
}
};
auto const is_directory = [](fs::path path) {
switch (fs::status(path).type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::type_unknown:
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return false;
case fs::directory_file:
return true;
}
};
}
struct project {
project() = default;
project(std::string name, fs::path path, std::vector<fs::path> sources, std::vector<fs::path> tests)
: name(std::move(name)), path(std::move(path)), sources(std::move(sources)), tests(std::move(tests)) {}
std::string name;
fs::path path;
std::vector<fs::path> sources;
std::vector<fs::path> tests;
std::vector<fs::path> objects = {};
std::vector<fs::path> binaries = {};
};
auto const find_sources = [](fs::path root) {
auto sources = std::vector<fs::path> {};
if (!fs::exists(root / folder::src))
return std::move(sources);
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
auto const path = *it;
if (!fs::is_file(path))
continue;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp) &&
std::find(std::begin(extension::c), std::end(extension::c), ext) == std::end(extension::c))
continue;
if (boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
sources.emplace_back(fs::relative(root, *it));
}
return std::move(sources);
};
auto const find_tests = [](fs::path root) {
auto tests = std::vector<fs::path> {};
if (fs::exists(root / folder::src)) {
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
auto const path = *it;
if (!fs::is_file(path))
continue;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
if (!boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
tests.emplace_back(fs::relative(root, *it));
}
}
if (!fs::exists(root / folder::test))
return std::move(tests);
for (auto it = fs::recursive_directory_iterator{root / folder::test}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
auto const path = *it;
if (!fs::is_file(path))
continue;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
tests.emplace_back(fs::relative(root, *it));
}
return std::move(tests);
};
auto const find_projects = [](fs::path root) {
auto names = std::unordered_set<std::string> {};
auto projects = std::vector<project> {};
for (auto it = fs::recursive_directory_iterator{root}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_directory(*it))
continue;
auto const base = fs::filename(*it);
if (base == folder::build) {
it.no_push();
continue;
}
if (base == folder::include && fs::exists(*it / ".." / folder::src))
continue;
if (base != folder::src && base != folder::include)
continue;
it.no_push();
auto const path = fs::path(*it).parent_path();
auto const relp = fs::relative(root, path);
auto const name = fs::filename(path);
if (names.find(name) != names.end()) {
std::cerr << "W: project " << name << " in " << path << " already found, ignoring\n";
continue;
}
names.insert(name);
projects.emplace_back(name, relp, find_sources(path), find_tests(path));
}
return std::move(projects);
};
extern "C" int main(int, char*[]) {
auto const root = fs::current_path();
auto const ninja = std::string { std::getenv("NINJA") ? std::getenv("NINJA") : "ninja" };
auto const builddir = fs::path(folder::build);
auto const objdir = builddir / "obj";
auto const libdir = builddir / "lib";
auto const bindir = builddir / "bin";
auto projects = find_projects(root);
{
auto const ninjafile = (objdir / "build.ninja").generic_string();
fs::create_directories(objdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto incdirs = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(incdirs), [&root](auto project) { return "-I" + (project.path / folder::include).generic_string(); });
for (auto const& p : projects) {
for (auto const& s : p.sources) {
if (std::find(std::begin(extension::c), std::end(extension::c), fs::extension(s)) == std::end(extension::c))
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).generic_string() << ": cxx " << (p.path / s).generic_string() << "\n";
else
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).generic_string() << ": cc " << (p.path / s).generic_string() << "\n";
out << " incdirs = -I" << (p.path / folder::src).generic_string() << " " << boost::algorithm::join(incdirs, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (libdir / "build.ninja").generic_string();
fs::create_directories(libdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
for (auto& p : projects) {
for (auto const& s : p.sources) {
auto const object = fs::change_extension(objdir / p.name / s, extension::obj);
auto const command = "nm " + object.generic_string() + " --defined-only | grep --quiet ' T main'";
auto const result = std::system(command.c_str());
if (result)
p.objects.emplace_back(std::move(object));
else
p.binaries.emplace_back(std::move(object));
}
auto objects = std::vector<std::string> {};
std::transform(std::begin(p.objects), std::end(p.objects), std::back_inserter(objects), [](auto path) { return path.generic_string(); });
out << "build " << (libdir / p.name).generic_string() << extension::arc << ": arc $\n";
for (auto const& o : objects)
out << " " << o << " $\n";
out << "\n";
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (bindir / "build.ninja").generic_string();
fs::create_directories(bindir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto archives = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(archives), [libdir](auto project) { return (libdir / project.name).generic_string() + extension::arc; });
for (auto const& p : projects) {
for (auto const& o : p.binaries) {
out << "build " << (bindir / p.name / fs::basename(o)).generic_string() << ": exe " << o.generic_string() << " | " << boost::algorithm::join(archives, " $\n ") << "\n";
out << " libs = " << boost::algorithm::join(archives, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
return 0;
}
}
<|endoftext|> |
<commit_before>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include "Bytecode.hpp"
namespace Implementation {
// These two static arrays describe language: all possible
// functions ans specifications.
static const char* const specifications_registry[] = {
"r"
};
static const char* const functions_registry[] = {
"eat", "go", "clon", "str", "left", "right", "back", "turn",
"jg", "jl", "j", "je", "jfe", "jw", "jfw", "jb", "jfb"
};
// These four static arrays contain IDs of functions from
// functions_registry.
static const int two_parameter_functions[] = {
8, 9
};
static const int one_parameter_functions[] = {
0, 1, 3, 4, 5, 10, 11, 12, 13, 14, 15, 16
};
static const int spec_functions[] = {
0, 1, 7
};
static const int non_argument_functions[] = {
0, 1, 2, 3, 4, 5, 6
};
static void split(
const std::string& str,
char delimiter,
Strings items
) {
std::stringstream s_stream(str);
std::string item;
while (std::getline(s_stream, item, delimiter)) {
if (!item.empty()) {
items.push_back(item);
}
}
}
static int isParameter(const std::string& what) {
bool is_parameter = true;
for (int i = 0; i < what.size(); i++) {
if (!isdigit(what[i])) {
is_parameter = false;
}
}
return (is_parameter) ? atoi(what.c_str()) : -1;
}
static bool isSpecification(const std::string& what) {
size_t el_size = sizeof(char*);
size_t size = sizeof(specifications_registry) / el_size;
for (int i = 0; i < size; i++) {
if (what.compare(specifications_registry[i]) == 0) {
return true;
}
}
return false;
}
static int isFunction(const std::string& what) {
size_t el_size = sizeof(char*);
size_t size = sizeof(functions_registry) / el_size;
for (int i = 0; i < size; i++) {
if (what.compare(functions_registry[i]) == 0) {
return i;
}
}
return -1;
}
static Token makeToken(const std::string& token_str) {
Type type;
if (token_str == "\n") {
type = DELIMITER;
} else if (isParameter(token_str) != -1) {
type = PARAMETER;
} else if (isSpecification(token_str)) {
type = SPECIFICATION;
} else if (isFunction(token_str) != -1) {
type = FUNCTION;
} else {
throw Exception("Interpreter: invalid token");
}
Token token(
type,
isParameter(token_str),
isSpecification(token_str),
isFunction(token_str)
);
return token;
}
static void checkFunctions(const Token& first, int funcs) {
if ((first.type != FUNCTION) || (funcs != 1)) {
throw Exception("Interpreter: function is missed "
"/ it's in the incorrect position "
"/ there are too many functions "
"for one command.");
}
}
static bool searchID(int id, const int* array, int size) {
for (int i = 0; i < size; i++) {
if (array[i] == id) {
return true;
}
}
return false;
}
static void checkByID(int id, int params, int specs) {
bool ok = false;
if ((params == 2) && (specs == 0)) {
int size = sizeof(two_parameter_functions) / sizeof(int);
ok = searchID(id, two_parameter_functions, size);
} else if ((params == 1) && (specs == 0)) {
int size = sizeof(one_parameter_functions) / sizeof(int);
ok = searchID(id, one_parameter_functions, size);
} else if ((params == 0) && (specs == 1)) {
int size = sizeof(spec_functions) / sizeof(int);
ok = searchID(id, spec_functions, size);
} else if ((params == 0) && (specs == 0)) {
int size = sizeof(non_argument_functions) / sizeof(int);
ok = searchID(id, non_argument_functions, size);
}
if (!ok) {
throw Exception("Interpreter: invalid arguments of function");
}
}
Token::Token(
Type type,
int parameter,
bool spec,
int function_id
)
: type(type)
, parameter(parameter)
, spec(spec)
, function_id(function_id)
{
}
Instruction::Instruction(
Token function,
Token p1,
Token p2,
Token spec
)
: function(function)
, p1(p1)
, p2(p2)
, spec(spec)
{
}
PackedInstruction::PackedInstruction(
int function_id,
int p1,
int p2,
bool spec
)
: function_id(function_id)
, p1(p1)
, p2(p2)
, spec(spec)
{
}
}
<commit_msg>Static function makeInstruction()<commit_after>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include "Bytecode.hpp"
namespace Implementation {
// These two static arrays describe language: all possible
// functions ans specifications.
static const char* const specifications_registry[] = {
"r"
};
static const char* const functions_registry[] = {
"eat", "go", "clon", "str", "left", "right", "back", "turn",
"jg", "jl", "j", "je", "jfe", "jw", "jfw", "jb", "jfb"
};
// These four static arrays contain IDs of functions from
// functions_registry.
static const int two_parameter_functions[] = {
8, 9
};
static const int one_parameter_functions[] = {
0, 1, 3, 4, 5, 10, 11, 12, 13, 14, 15, 16
};
static const int spec_functions[] = {
0, 1, 7
};
static const int non_argument_functions[] = {
0, 1, 2, 3, 4, 5, 6
};
static void split(
const std::string& str,
char delimiter,
Strings items
) {
std::stringstream s_stream(str);
std::string item;
while (std::getline(s_stream, item, delimiter)) {
if (!item.empty()) {
items.push_back(item);
}
}
}
static int isParameter(const std::string& what) {
bool is_parameter = true;
for (int i = 0; i < what.size(); i++) {
if (!isdigit(what[i])) {
is_parameter = false;
}
}
return (is_parameter) ? atoi(what.c_str()) : -1;
}
static bool isSpecification(const std::string& what) {
size_t el_size = sizeof(char*);
size_t size = sizeof(specifications_registry) / el_size;
for (int i = 0; i < size; i++) {
if (what.compare(specifications_registry[i]) == 0) {
return true;
}
}
return false;
}
static int isFunction(const std::string& what) {
size_t el_size = sizeof(char*);
size_t size = sizeof(functions_registry) / el_size;
for (int i = 0; i < size; i++) {
if (what.compare(functions_registry[i]) == 0) {
return i;
}
}
return -1;
}
static Token makeToken(const std::string& token_str) {
Type type;
if (token_str == "\n") {
type = DELIMITER;
} else if (isParameter(token_str) != -1) {
type = PARAMETER;
} else if (isSpecification(token_str)) {
type = SPECIFICATION;
} else if (isFunction(token_str) != -1) {
type = FUNCTION;
} else {
throw Exception("Interpreter: invalid token");
}
Token token(
type,
isParameter(token_str),
isSpecification(token_str),
isFunction(token_str)
);
return token;
}
static void checkFunctions(const Token& first, int funcs) {
if ((first.type != FUNCTION) || (funcs != 1)) {
throw Exception("Interpreter: function is missed "
"/ it's in the incorrect position "
"/ there are too many functions "
"for one command.");
}
}
static bool searchID(int id, const int* array, int size) {
for (int i = 0; i < size; i++) {
if (array[i] == id) {
return true;
}
}
return false;
}
static void checkByID(int id, int params, int specs) {
bool ok = false;
if ((params == 2) && (specs == 0)) {
int size = sizeof(two_parameter_functions) / sizeof(int);
ok = searchID(id, two_parameter_functions, size);
} else if ((params == 1) && (specs == 0)) {
int size = sizeof(one_parameter_functions) / sizeof(int);
ok = searchID(id, one_parameter_functions, size);
} else if ((params == 0) && (specs == 1)) {
int size = sizeof(spec_functions) / sizeof(int);
ok = searchID(id, spec_functions, size);
} else if ((params == 0) && (specs == 0)) {
int size = sizeof(non_argument_functions) / sizeof(int);
ok = searchID(id, non_argument_functions, size);
}
if (!ok) {
throw Exception("Interpreter: invalid arguments of function");
}
}
static Instruction makeInstruction(
int params,
int specs,
const Tokens& tokens_group
) {
Token function = tokens_group[0];
Token p1(PARAMETER);
Token p2(PARAMETER);
Token spec(SPECIFICATION);
if (params == 2) {
p1 = tokens_group[1];
p2 = tokens_group[2];
} else if (params == 1) {
p1 = tokens_group[1];
} else if (specs == 1) {
spec = tokens_group[1];
}
Instruction instruction(function, p1, p2, spec);
return instruction;
}
Token::Token(
Type type,
int parameter,
bool spec,
int function_id
)
: type(type)
, parameter(parameter)
, spec(spec)
, function_id(function_id)
{
}
Instruction::Instruction(
Token function,
Token p1,
Token p2,
Token spec
)
: function(function)
, p1(p1)
, p2(p2)
, spec(spec)
{
}
PackedInstruction::PackedInstruction(
int function_id,
int p1,
int p2,
bool spec
)
: function_id(function_id)
, p1(p1)
, p2(p2)
, spec(spec)
{
}
}
<|endoftext|> |
<commit_before>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2020 EOS di Manlio Morini.
*
* \license
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/
*/
#if !defined(VITA_SRC_EVALUATOR_H)
# error "Don't include this file directly, include the specific .h instead"
#endif
#if !defined(VITA_SRC_EVALUATOR_TCC)
#define VITA_SRC_EVALUATOR_TCC
///
/// \param[in] d dataset that the evaluator will use
///
template<class T, class DAT>
src_evaluator<T, DAT>::src_evaluator(DAT &d) : dat_(&d)
{
}
///
/// \param[in] d the training dataset
///
template<class T, class ERRF, class DAT>
sum_of_errors_evaluator<T, ERRF, DAT>::sum_of_errors_evaluator(DAT &d)
: src_evaluator<T, DAT>(d)
{
}
///
/// Sums the error reported by the error functor over a training set.
///
/// \param[in] prg program (individual/team) used for fitness evaluation
/// \param[in] n consider just '1' example every 'n'
/// \return the fitness (greater is better, max is `0`)
///
template<class T, class ERRF, class DAT>
fitness_t sum_of_errors_evaluator<T, ERRF, DAT>::sum_of_errors_impl(
const T &prg, unsigned n)
{
Expects(this->dat_->begin() != this->dat_->end());
Expects(!detail::classes(this->dat_));
double total_error(0.0);
ERRF err_fctr(prg);
if (this->dat_->size() <= 20)
n = 1;
for (auto it(this->dat_->begin());
it != this->dat_->end();
std::advance(it, n))
{
const auto err(err_fctr(*it));
// User specified examples could not support difficulty.
if constexpr (detail::has_difficulty_v<DAT>)
if (!issmall(err))
++it->difficulty;
total_error += err;
}
// Note that we take the average error: this way fast() and operator()
// outputs can be compared.
return
{
static_cast<fitness_t::value_type>(
-total_error / static_cast<double>(this->dat_->size()))
};
}
///
/// \param[in] prg program (individual/team) used for fitness evaluation
/// \return the fitness (greater is better, max is `0`)
///
template<class T, class ERRF, class DAT>
fitness_t sum_of_errors_evaluator<T, ERRF, DAT>::operator()(const T &prg)
{
return sum_of_errors_impl(prg, 1);
}
///
/// \param[in] prg program (individual/team) used for fitness evaluation
/// \return the fitness (greater is better, max is `0`)
///
/// This function is similar to operator()() but will skip 4 out of 5
/// training instances, so it's faster.
///
template<class T, class ERRF, class DAT>
fitness_t sum_of_errors_evaluator<T, ERRF, DAT>::fast(const T &prg)
{
return sum_of_errors_impl(prg, 5);
}
///
/// \param[in] prg program(individual/team) to be transformed in a lambda
/// function
/// \return the lambda function associated with `prg` (`nullptr` in case
/// of errors).
///
template<class T, class LAMBDA, class DAT>
std::unique_ptr<basic_lambda_f>
sum_of_errors_evaluator<T, LAMBDA, DAT>::lambdify(const T &prg) const
{
return std::make_unique<basic_reg_lambda_f<T, true>>(prg);
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
mae_error_functor<T>::mae_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return a measurement of the error of the model/program on the
/// given training case (value in the `[0;+inf[` range)
///
template<class T>
double mae_error_functor<T>::operator()(const dataframe::example &example) const
{
if (const auto model_value = agent_(example); has_value(model_value))
return std::fabs(lexical_cast<D_DOUBLE>(model_value)
- label_as<D_DOUBLE>(example));
return std::numeric_limits<double>::max() / 100.0;
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
rmae_error_functor<T>::rmae_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return measurement of the error of the model/program on the
/// current training case. The value returned is in the
/// `[0;200]` range
///
template<class T>
double rmae_error_functor<T>::operator()(
const dataframe::example &example) const
{
double err(200.0);
if (const auto model_value = agent_(example); has_value(model_value))
{
const auto approx(lexical_cast<D_DOUBLE>(model_value));
const auto target(label_as<D_DOUBLE>(example));
const auto delta(std::fabs(target - approx));
// Check if the numbers are really close. Needed when comparing numbers
// near zero.
if (delta <= 10.0 * std::numeric_limits<D_DOUBLE>::min())
err = 0.0;
else
err = 200.0 * delta / (std::fabs(approx) + std::fabs(target));
// Some alternatives for the error:
// * delta / std::max(approx, target)
// * delta / std::fabs(target)
//
// The chosen formula seems numerically more stable and gives a result
// in a limited range of values.
}
return err;
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
mse_error_functor<T>::mse_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return a measurement of the error of the model/program on the
/// the current training case. The value returned is in the
/// `[0;+inf[` range
///
template<class T>
double mse_error_functor<T>::operator()(const dataframe::example &example) const
{
if (const auto model_value = agent_(example); has_value(model_value))
{
const double err(lexical_cast<D_DOUBLE>(model_value)
- label_as<D_DOUBLE>(example));
return err * err;
}
return std::numeric_limits<double>::max() / 100.0;
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
count_error_functor<T>::count_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return a measurement of the error of the model/program on the
/// current training case. The value returned is in the
/// `[0;+inf[` range
///
template<class T>
double count_error_functor<T>::operator()(
const dataframe::example &example) const
{
const auto model_value(agent_(example));
const bool err(!has_value(model_value)
|| !issmall(lexical_cast<D_DOUBLE>(model_value)
- label_as<D_DOUBLE>(example)));
return err ? 1.0 : 0.0;
}
///
/// \param[in] p current dataset
/// \param[in] x_slot basic parameter for the Slotted Dynamic Class Boundary
/// Determination algorithm
///
template<class T>
dyn_slot_evaluator<T>::dyn_slot_evaluator(dataframe &d, unsigned x_slot)
: classification_evaluator<T>(d), x_slot_(x_slot)
{
assert(x_slot_);
}
///
/// \param[in] ind program used for class recognition
/// \return the fitness (greater is better, max is `0`)
///
template<class T>
fitness_t dyn_slot_evaluator<T>::operator()(const T &ind)
{
basic_dyn_slot_lambda_f<T, false, false> lambda(ind, *this->dat_, x_slot_);
fitness_t::value_type err(0.0);
for (auto &example : *this->dat_)
if (lambda.tag(example).label != label(example))
{
++err;
++example.difficulty;
}
return {-err};
// The following code is faster but doesn't work for teams and doesn't
// "cooperate" with DSS.
//
// basic_dyn_slot_lambda_f<T,false,false> lambda(ind, *this->dat_, x_slot_);
// return {100.0 * (lambda.training_accuracy() - 1.0)};
}
///
/// \param[in] ind individual to be transformed in a lambda function
/// \return the lambda function associated with `ind` (`nullptr` in case
/// of errors)
///
template<class T>
std::unique_ptr<basic_lambda_f> dyn_slot_evaluator<T>::lambdify(
const T &ind) const
{
return std::make_unique<dyn_slot_lambda_f<T>>(ind, *this->dat_, x_slot_);
}
///
/// \param[in] ind program used for class recognition
/// \return the fitness (greater is better, max is `0`)
///
/// For details about this algorithm see:
/// * "Using Gaussian Distribution to Construct Fitnesss Functions in Genetic
/// Programming for Multiclass Object Classification" - Mengjie Zhang, Will
/// Smart (december 2005).
///
template<class T>
fitness_t gaussian_evaluator<T>::operator()(const T &ind)
{
assert(this->dat_->classes() >= 2);
basic_gaussian_lambda_f<T, false, false> lambda(ind, *this->dat_);
fitness_t::value_type d(0.0);
for (auto &example : *this->dat_)
if (const auto res = lambda.tag(example); res.label == label(example))
{
const auto scale(static_cast<fitness_t::value_type>(this->dat_->classes()
- 1));
// Note:
// * `(1.0 - res.sureness)` is the sum of the errors;
// * `(res.sureness - 1.0)` is the opposite (standardized fitness);
// * `(res.sureness - 1.0) / scale` is the opposite of the average error.
d += (res.sureness - 1.0) / scale;
}
else
{
// Note:
// * the maximum single class error is 1.0;
// * the maximum average class error is `1.0 / dat_->classes()`;
// So -1.0 is like to say that we have a complete failure.
d -= 1.0;
++example.difficulty;
}
return {d};
}
///
/// \param[in] ind individual to be transformed in a lambda function
/// \return the lambda function associated with `ind` (`nullptr` in case
/// of errors)
///
template<class T>
std::unique_ptr<basic_lambda_f> gaussian_evaluator<T>::lambdify(
const T &ind) const
{
return std::make_unique<gaussian_lambda_f<T>>(ind, *this->dat_);
}
///
/// \param[in] ind an individual
/// \return the fitness of `ind` (greater is better, max is `0`)
///
template<class T>
fitness_t binary_evaluator<T>::operator()(const T &ind)
{
Expects(this->dat_->classes() == 2);
basic_binary_lambda_f<T, false, false> agent(ind, *this->dat_);
fitness_t::value_type err(0.0);
for (auto &example : *this->dat_)
if (label(example) != agent.tag(example).label)
{
++example.difficulty;
++err;
// err += std::fabs(val);
}
return {-err};
}
///
/// \param[in] ind individual to be transformed in a lambda function
/// \return the lambda function associated with `ind` (`nullptr` in case
/// of errors)
///
template<class T>
std::unique_ptr<basic_lambda_f> binary_evaluator<T>::lambdify(
const T &ind) const
{
return std::make_unique<binary_lambda_f<T>>(ind, *this->dat_);
}
#endif // include guard
<commit_msg>[FIX] Close #30<commit_after>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2020 EOS di Manlio Morini.
*
* \license
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/
*/
#if !defined(VITA_SRC_EVALUATOR_H)
# error "Don't include this file directly, include the specific .h instead"
#endif
#if !defined(VITA_SRC_EVALUATOR_TCC)
#define VITA_SRC_EVALUATOR_TCC
///
/// \param[in] d dataset that the evaluator will use
///
template<class T, class DAT>
src_evaluator<T, DAT>::src_evaluator(DAT &d) : dat_(&d)
{
}
///
/// \param[in] d the training dataset
///
template<class T, class ERRF, class DAT>
sum_of_errors_evaluator<T, ERRF, DAT>::sum_of_errors_evaluator(DAT &d)
: src_evaluator<T, DAT>(d)
{
}
///
/// Sums the error reported by the error functor over a training set.
///
/// \param[in] prg program (individual/team) used for fitness evaluation
/// \param[in] step consider just `1` example every `step`
/// \return the fitness (greater is better, max is `0`)
///
template<class T, class ERRF, class DAT>
fitness_t sum_of_errors_evaluator<T, ERRF, DAT>::sum_of_errors_impl(
const T &prg, unsigned step)
{
Expects(this->dat_->begin() != this->dat_->end());
Expects(!detail::classes(this->dat_));
const ERRF err_fctr(prg);
double average_error(0.0), n(0.0);
for (auto it(std::begin(*this->dat_));
std::distance(it, std::end(*this->dat_)) >= step;
std::advance(it, step))
{
const auto err(err_fctr(*it));
// User specified examples could not support difficulty.
if constexpr (detail::has_difficulty_v<DAT>)
if (!issmall(err))
++it->difficulty;
average_error += (err - average_error) / ++n;
}
// Note that we take the average error: this way fast() and operator()
// outputs can be compared.
return {static_cast<fitness_t::value_type>(-average_error)};
}
///
/// \param[in] prg program (individual/team) used for fitness evaluation
/// \return the fitness (greater is better, max is `0`)
///
template<class T, class ERRF, class DAT>
fitness_t sum_of_errors_evaluator<T, ERRF, DAT>::operator()(const T &prg)
{
return sum_of_errors_impl(prg, 1);
}
///
/// \param[in] prg program (individual/team) used for fitness evaluation
/// \return the fitness (greater is better, max is `0`)
///
/// This function is similar to operator()() but will skip 4 out of 5
/// training instances, so it's faster.
///
template<class T, class ERRF, class DAT>
fitness_t sum_of_errors_evaluator<T, ERRF, DAT>::fast(const T &prg)
{
Expects(std::distance(this->dat_->begin(), this->dat_->end()) >= 100);
return sum_of_errors_impl(prg, 5);
}
///
/// \param[in] prg program(individual/team) to be transformed in a lambda
/// function
/// \return the lambda function associated with `prg` (`nullptr` in case
/// of errors).
///
template<class T, class LAMBDA, class DAT>
std::unique_ptr<basic_lambda_f>
sum_of_errors_evaluator<T, LAMBDA, DAT>::lambdify(const T &prg) const
{
return std::make_unique<basic_reg_lambda_f<T, true>>(prg);
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
mae_error_functor<T>::mae_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return a measurement of the error of the model/program on the
/// given training case (value in the `[0;+inf[` range)
///
template<class T>
double mae_error_functor<T>::operator()(const dataframe::example &example) const
{
if (const auto model_value = agent_(example); has_value(model_value))
return std::fabs(lexical_cast<D_DOUBLE>(model_value)
- label_as<D_DOUBLE>(example));
return std::numeric_limits<double>::max() / 100.0;
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
rmae_error_functor<T>::rmae_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return measurement of the error of the model/program on the
/// current training case. The value returned is in the
/// `[0;200]` range
///
template<class T>
double rmae_error_functor<T>::operator()(
const dataframe::example &example) const
{
double err(200.0);
if (const auto model_value = agent_(example); has_value(model_value))
{
const auto approx(lexical_cast<D_DOUBLE>(model_value));
const auto target(label_as<D_DOUBLE>(example));
const auto delta(std::fabs(target - approx));
// Check if the numbers are really close. Needed when comparing numbers
// near zero.
if (delta <= 10.0 * std::numeric_limits<D_DOUBLE>::min())
err = 0.0;
else
err = 200.0 * delta / (std::fabs(approx) + std::fabs(target));
// Some alternatives for the error:
// * delta / std::max(approx, target)
// * delta / std::fabs(target)
//
// The chosen formula seems numerically more stable and gives a result
// in a limited range of values.
}
return err;
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
mse_error_functor<T>::mse_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return a measurement of the error of the model/program on the
/// the current training case. The value returned is in the
/// `[0;+inf[` range
///
template<class T>
double mse_error_functor<T>::operator()(const dataframe::example &example) const
{
if (const auto model_value = agent_(example); has_value(model_value))
{
const double err(lexical_cast<D_DOUBLE>(model_value)
- label_as<D_DOUBLE>(example));
return err * err;
}
return std::numeric_limits<double>::max() / 100.0;
}
///
/// Sets up the environment for error measurement.
///
/// \param[in] prg the program to be measured
///
template<class T>
count_error_functor<T>::count_error_functor(const T &prg) : agent_(prg)
{
}
///
/// \param[in] example current training case
/// \return a measurement of the error of the model/program on the
/// current training case. The value returned is in the
/// `[0;+inf[` range
///
template<class T>
double count_error_functor<T>::operator()(
const dataframe::example &example) const
{
const auto model_value(agent_(example));
const bool err(!has_value(model_value)
|| !issmall(lexical_cast<D_DOUBLE>(model_value)
- label_as<D_DOUBLE>(example)));
return err ? 1.0 : 0.0;
}
///
/// \param[in] p current dataset
/// \param[in] x_slot basic parameter for the Slotted Dynamic Class Boundary
/// Determination algorithm
///
template<class T>
dyn_slot_evaluator<T>::dyn_slot_evaluator(dataframe &d, unsigned x_slot)
: classification_evaluator<T>(d), x_slot_(x_slot)
{
assert(x_slot_);
}
///
/// \param[in] ind program used for class recognition
/// \return the fitness (greater is better, max is `0`)
///
template<class T>
fitness_t dyn_slot_evaluator<T>::operator()(const T &ind)
{
basic_dyn_slot_lambda_f<T, false, false> lambda(ind, *this->dat_, x_slot_);
fitness_t::value_type err(0.0);
for (auto &example : *this->dat_)
if (lambda.tag(example).label != label(example))
{
++err;
++example.difficulty;
}
return {-err};
// The following code is faster but doesn't work for teams and doesn't
// "cooperate" with DSS.
//
// basic_dyn_slot_lambda_f<T,false,false> lambda(ind, *this->dat_, x_slot_);
// return {100.0 * (lambda.training_accuracy() - 1.0)};
}
///
/// \param[in] ind individual to be transformed in a lambda function
/// \return the lambda function associated with `ind` (`nullptr` in case
/// of errors)
///
template<class T>
std::unique_ptr<basic_lambda_f> dyn_slot_evaluator<T>::lambdify(
const T &ind) const
{
return std::make_unique<dyn_slot_lambda_f<T>>(ind, *this->dat_, x_slot_);
}
///
/// \param[in] ind program used for class recognition
/// \return the fitness (greater is better, max is `0`)
///
/// For details about this algorithm see:
/// * "Using Gaussian Distribution to Construct Fitnesss Functions in Genetic
/// Programming for Multiclass Object Classification" - Mengjie Zhang, Will
/// Smart (december 2005).
///
template<class T>
fitness_t gaussian_evaluator<T>::operator()(const T &ind)
{
assert(this->dat_->classes() >= 2);
basic_gaussian_lambda_f<T, false, false> lambda(ind, *this->dat_);
fitness_t::value_type d(0.0);
for (auto &example : *this->dat_)
if (const auto res = lambda.tag(example); res.label == label(example))
{
const auto scale(static_cast<fitness_t::value_type>(this->dat_->classes()
- 1));
// Note:
// * `(1.0 - res.sureness)` is the sum of the errors;
// * `(res.sureness - 1.0)` is the opposite (standardized fitness);
// * `(res.sureness - 1.0) / scale` is the opposite of the average error.
d += (res.sureness - 1.0) / scale;
}
else
{
// Note:
// * the maximum single class error is 1.0;
// * the maximum average class error is `1.0 / dat_->classes()`;
// So -1.0 is like to say that we have a complete failure.
d -= 1.0;
++example.difficulty;
}
return {d};
}
///
/// \param[in] ind individual to be transformed in a lambda function
/// \return the lambda function associated with `ind` (`nullptr` in case
/// of errors)
///
template<class T>
std::unique_ptr<basic_lambda_f> gaussian_evaluator<T>::lambdify(
const T &ind) const
{
return std::make_unique<gaussian_lambda_f<T>>(ind, *this->dat_);
}
///
/// \param[in] ind an individual
/// \return the fitness of `ind` (greater is better, max is `0`)
///
template<class T>
fitness_t binary_evaluator<T>::operator()(const T &ind)
{
Expects(this->dat_->classes() == 2);
basic_binary_lambda_f<T, false, false> agent(ind, *this->dat_);
fitness_t::value_type err(0.0);
for (auto &example : *this->dat_)
if (label(example) != agent.tag(example).label)
{
++example.difficulty;
++err;
// err += std::fabs(val);
}
return {-err};
}
///
/// \param[in] ind individual to be transformed in a lambda function
/// \return the lambda function associated with `ind` (`nullptr` in case
/// of errors)
///
template<class T>
std::unique_ptr<basic_lambda_f> binary_evaluator<T>::lambdify(
const T &ind) const
{
return std::make_unique<binary_lambda_f<T>>(ind, *this->dat_);
}
#endif // include guard
<|endoftext|> |
<commit_before>// tsStego.cpp
// Released under the MIT License
//
// A simple implementation of stegonography in C++
// Uses the LodePNG library version 20140801 by Lode Vandevenne
#include <fstream>
#include <sstream>
#include <iostream>
#include <exception>
#include "lodepng.h"
// Read the plain text file in
void read_text_file(const char* filename, std::vector<unsigned char>& plaintext)
{
try
{
std::fstream text_file(filename);
while (text_file.good())
{
unsigned char c = text_file.get();
if (text_file.good())
plaintext.push_back(c);
}
}
catch (...)
{
throw std::exception("Exception in read_text_file()");
return;
}
}
// Write the plain text file out
void write_text_file(const char* filename, std::vector<unsigned char>& plaintext)
{
try
{
std::ofstream text_file(filename);
for (auto& c : plaintext)
text_file.put(c);
}
catch (...)
{
throw std::exception("Exception in write_text_file()");
return;
}
}
// Read the PNG file and save the data into the data structure
// Color values in the vector are 4 bytes per pixel, ordered RGBARGBA...
// On an error, throws an exception
void read_png_from_file(const char* filename, std::vector<unsigned char>& image, unsigned int& width, unsigned int& height)
{
unsigned int error = 0;
try
{
unsigned int error = lodepng::decode(image, width, height, filename);
}
catch (...)
{
throw std::exception("Exception in lodepng::decode()");
return;
}
if (error)
{
std::stringstream err_desc;
err_desc << "Decoder error " << error << ": " << lodepng_error_text(error);
std::string s = err_desc.str();
throw std::exception(s.c_str());
}
}
// Write the PNG file from the data structure
// Color values in the vector are 4 bytes per pixel, ordered RGBARGBA...
// On an error, throws an exception
void write_png_to_file(const char* filename, std::vector<unsigned char>& image, unsigned int width, unsigned int height)
{
unsigned int error = 0;
try
{
unsigned error = lodepng::encode(filename, image, width, height);
}
catch (...)
{
throw std::exception("Exception in lodepng::decode()");
return;
}
if (error)
{
std::stringstream err_desc;
err_desc << "Encoder error " << error << ": " << lodepng_error_text(error);
std::string s = err_desc.str();
throw std::exception(s.c_str());
}
}
// Take the 8 bits per char and split them 3-2-3, putting 3 bits into the Red, 2 bits into the Green,
// 3 bits into the Blue, and nothing in Alpha
// The bits will be placed starting from the LSB of each byte so as to make the least impact to the
// image when viewed by a human
// We put fewer bits into the Green channel because human eyes are more sensitive to a yellowish-green
void merge_plaintext_into_img_data(std::vector<unsigned char>& plaintext, std::vector<unsigned char>& img_data)
{
// Bounds check
// Using 4 * the plaintext size because each element in img_data is a color channel of a pixel, of which
// there are 4 channels per pixel, and we're going to overwrite certain bits across three of the channels
if (img_data.size() < 4 * plaintext.size())
throw std::exception("Exception in merge_plaintext_into_img_data: image is too small to fit all the text");
unsigned char tmp = 0;
unsigned int img_index = 0;
// Loop through all the characters
for (auto& c : plaintext)
{
// First color channel is Red
// First 3 MSBs from the character are put into the Red channel's 3 LSBs
tmp = c >> 5; // shift those 3 bits to the right 5 to make them align with the 3 LSBs
// merge the 5 bits from the original with the 3 shifted MSBs of the text
img_data[img_index] = (img_data[img_index] & 0xF8) | (tmp & 0x7);
img_index++; // Next color channel (Blue)
// Next 3 bits from the character are put into the Blue channel's 3 LSBs
tmp = c << 3; // shave off the 3 MSBs
tmp = tmp >> 5; // shift back 5 to make them align with the 3 LSBs
// merge the 5 bits from the original with the 3 shifted bits of the text
img_data[img_index] = (img_data[img_index] & 0xF8) | (tmp & 0x7);
img_index++; // Next color channel (Green)
// The 2 LSBs from the character are put into the Green channel's 2 LSBs
tmp = c << 6; // shave off the 6 MSBs
tmp = tmp >> 6; // shift back 6 to make them align with the 2 LSBs
// merge the 6 bits from the original with the 2 shifted bits of the text
img_data[img_index] = (img_data[img_index] & 0xFC) | (tmp & 0x3);
img_index++; // Next color channel (Alpha)
img_index++; // Next color channel (Red of the next pixel...so we're ready for next char)
}
}
// TODO:
// - Load the PNG file into the image data structure [ DONE ]
// - Load the plain text file [ DONE ]
// - Save the image data structure as a new PNG file [ DONE ]
// - Save the plain text as a new text file [ DONE ]
// - Handle command line input
// - Encipher the plain text
// - Merge the cipher text into the image data structure
// - Load the enciphered PNG file into the enciphered image data structure
// - Extract the cipher text from the enciphered image data structure
// - Decipher to plain text
int main(int argc, char** argv)
{
// Testing the read file function
std::vector<unsigned char>plain_text;
read_text_file("example.txt", plain_text);
plain_text[3] = 'F';
write_text_file("output.txt", plain_text);
// Just testing the LodePNG library for now...input, modification, and output
std::vector<unsigned char> img_data;
unsigned int h, w;
read_png_from_file("planet.png", img_data, w, h);
unsigned int index = 0;
for (auto& color_val : img_data)
{
if (index % 4 == 2)
{
if (color_val >= 255)
color_val = 0;
}
index++;
}
merge_plaintext_into_img_data(plain_text, img_data);
write_png_to_file("output.png", img_data, w, h);
return 0;
}<commit_msg>Removed the extraneous data modification in main I'd unintentionally left in a loop to modify the data before writing it out. removed that in favor of using the text file merge function which seems to be working. Next up is to create an XOR version of the merge, which will require the original image to properly extract the stego data.<commit_after>// tsStego.cpp
// Released under the MIT License
//
// A simple implementation of stegonography in C++
// Uses the LodePNG library version 20140801 by Lode Vandevenne
#include <fstream>
#include <sstream>
#include <iostream>
#include <exception>
#include "lodepng.h"
// Read the plain text file in
void read_text_file(const char* filename, std::vector<unsigned char>& plaintext)
{
try
{
std::fstream text_file(filename);
while (text_file.good())
{
unsigned char c = text_file.get();
if (text_file.good())
plaintext.push_back(c);
}
}
catch (...)
{
throw std::exception("Exception in read_text_file()");
return;
}
}
// Write the plain text file out
void write_text_file(const char* filename, std::vector<unsigned char>& plaintext)
{
try
{
std::ofstream text_file(filename);
for (auto& c : plaintext)
text_file.put(c);
}
catch (...)
{
throw std::exception("Exception in write_text_file()");
return;
}
}
// Read the PNG file and save the data into the data structure
// Color values in the vector are 4 bytes per pixel, ordered RGBARGBA...
// On an error, throws an exception
void read_png_from_file(const char* filename, std::vector<unsigned char>& image, unsigned int& width, unsigned int& height)
{
unsigned int error = 0;
try
{
unsigned int error = lodepng::decode(image, width, height, filename);
}
catch (...)
{
throw std::exception("Exception in lodepng::decode()");
return;
}
if (error)
{
std::stringstream err_desc;
err_desc << "Decoder error " << error << ": " << lodepng_error_text(error);
std::string s = err_desc.str();
throw std::exception(s.c_str());
}
}
// Write the PNG file from the data structure
// Color values in the vector are 4 bytes per pixel, ordered RGBARGBA...
// On an error, throws an exception
void write_png_to_file(const char* filename, std::vector<unsigned char>& image, unsigned int width, unsigned int height)
{
unsigned int error = 0;
try
{
unsigned error = lodepng::encode(filename, image, width, height);
}
catch (...)
{
throw std::exception("Exception in lodepng::decode()");
return;
}
if (error)
{
std::stringstream err_desc;
err_desc << "Encoder error " << error << ": " << lodepng_error_text(error);
std::string s = err_desc.str();
throw std::exception(s.c_str());
}
}
// Take the 8 bits per char and split them 3-2-3, putting 3 bits into the Red, 2 bits into the Green,
// 3 bits into the Blue, and nothing in Alpha
// The bits will be placed starting from the LSB of each byte so as to make the least impact to the
// image when viewed by a human
// We put fewer bits into the Green channel because human eyes are more sensitive to a yellowish-green
void merge_plaintext_into_img_data(std::vector<unsigned char>& plaintext, std::vector<unsigned char>& img_data)
{
// Bounds check
// Using 4 * the plaintext size because each element in img_data is a color channel of a pixel, of which
// there are 4 channels per pixel, and we're going to overwrite certain bits across three of the channels
if (img_data.size() < 4 * plaintext.size())
throw std::exception("Exception in merge_plaintext_into_img_data: image is too small to fit all the text");
unsigned char tmp = 0;
unsigned int img_index = 0;
// Loop through all the characters
for (auto& c : plaintext)
{
// First color channel is Red
// First 3 MSBs from the character are put into the Red channel's 3 LSBs
tmp = c >> 5; // shift those 3 bits to the right 5 to make them align with the 3 LSBs
// merge the 5 bits from the original with the 3 shifted MSBs of the text
img_data[img_index] = (img_data[img_index] & 0xF8) | (tmp & 0x7);
img_index++; // Next color channel (Blue)
// Next 3 bits from the character are put into the Blue channel's 3 LSBs
tmp = c << 3; // shave off the 3 MSBs
tmp = tmp >> 5; // shift back 5 to make them align with the 3 LSBs
// merge the 5 bits from the original with the 3 shifted bits of the text
img_data[img_index] = (img_data[img_index] & 0xF8) | (tmp & 0x7);
img_index++; // Next color channel (Green)
// The 2 LSBs from the character are put into the Green channel's 2 LSBs
tmp = c << 6; // shave off the 6 MSBs
tmp = tmp >> 6; // shift back 6 to make them align with the 2 LSBs
// merge the 6 bits from the original with the 2 shifted bits of the text
img_data[img_index] = (img_data[img_index] & 0xFC) | (tmp & 0x3);
img_index++; // Next color channel (Alpha)
img_index++; // Next color channel (Red of the next pixel...so we're ready for next char)
}
}
// TODO:
// - Load the PNG file into the image data structure [ DONE ]
// - Load the plain text file [ DONE ]
// - Save the image data structure as a new PNG file [ DONE ]
// - Save the plain text as a new text file [ DONE ]
// - Handle command line input
// - Encipher the plain text
// - Merge the cipher text into the image data structure
// - Load the enciphered PNG file into the enciphered image data structure
// - Extract the cipher text from the enciphered image data structure
// - Decipher to plain text
int main(int argc, char** argv)
{
// Testing the read file function
std::vector<unsigned char>plain_text;
read_text_file("example.txt", plain_text);
plain_text[3] = 'F';
write_text_file("output.txt", plain_text);
// Just testing the LodePNG library for now...input, modification, and output
std::vector<unsigned char> img_data;
unsigned int h, w;
read_png_from_file("planet.png", img_data, w, h);
merge_plaintext_into_img_data(plain_text, img_data);
write_png_to_file("output.png", img_data, w, h);
return 0;
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <functional>
#include <vector>
#include <boost/range/algorithm/replace.hpp>
#include <boost/range/algorithm/remove.hpp>
namespace utils {
template <typename... Args>
class observable {
public:
class observer;
private:
std::vector<observer*> _observers;
public:
class observer {
friend class observable;
observable* _observable;
std::function<void (Args...)> _callback;
private:
void moved(observer* from) {
if (_observable) {
_observable->moved(from, this);
}
}
public:
observer(observable* o, std::function<void (Args...)> callback) noexcept
: _observable(o), _callback(std::move(callback)) {
}
observer(observer&& o) noexcept
: _observable(std::exchange(o._observable, nullptr))
, _callback(std::move(o._callback)) {
moved(&o);
}
observer& operator=(observer&& o) noexcept {
if (this != &o) {
disconnect();
_observable = std::exchange(o._observable, nullptr);
_callback = std::move(o._callback);
moved(&o);
}
return *this;
}
~observer() {
disconnect();
}
void disconnect() {
if (_observable) {
_observable->destroyed(this);
}
}
};
friend class observer;
private:
void destroyed(observer* dead) {
_observers.erase(boost::remove(_observers, dead), _observers.end());
}
void moved(observer* from, observer* to) {
boost::replace(_observers, from, to);
}
void update_observers(observable* ob) {
for (auto&& c : _observers) {
c->_observable = ob;
}
}
public:
observable() = default;
observable(observable&& o) noexcept
: _observers(std::move(o._observers)) {
update_observers(this);
}
observable& operator=(observable&& o) noexcept {
if (this != &o) {
update_observers(nullptr);
_observers = std::move(o._observers);
update_observers(this);
}
return *this;
}
~observable() {
update_observers(nullptr);
}
// Send args to all connected observers
void operator()(Args... args) const {
std::exception_ptr e;
for (auto&& ob : _observers) {
try {
ob->_callback(args...);
} catch (...) {
if (!e) {
e = std::current_exception();
}
}
}
if (e) {
std::rethrow_exception(std::move(e));
}
}
// Adds an observer to an observable
observer observe(std::function<void (Args...)> callback) {
observer ob(this, std::move(callback));
_observers.push_back(&ob);
return ob;
}
};
template <typename... Args>
using observer = typename observable<Args...>::observer;
}
<commit_msg>observable: switch to noncopyable_function<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/util/noncopyable_function.hh>
#include <vector>
#include <boost/range/algorithm/replace.hpp>
#include <boost/range/algorithm/remove.hpp>
namespace utils {
template <typename... Args>
class observable {
public:
class observer;
private:
std::vector<observer*> _observers;
public:
class observer {
friend class observable;
observable* _observable;
seastar::noncopyable_function<void (Args...)> _callback;
private:
void moved(observer* from) {
if (_observable) {
_observable->moved(from, this);
}
}
public:
observer(observable* o, seastar::noncopyable_function<void (Args...)> callback) noexcept
: _observable(o), _callback(std::move(callback)) {
}
observer(observer&& o) noexcept
: _observable(std::exchange(o._observable, nullptr))
, _callback(std::move(o._callback)) {
moved(&o);
}
observer& operator=(observer&& o) noexcept {
if (this != &o) {
disconnect();
_observable = std::exchange(o._observable, nullptr);
_callback = std::move(o._callback);
moved(&o);
}
return *this;
}
~observer() {
disconnect();
}
void disconnect() {
if (_observable) {
_observable->destroyed(this);
}
}
};
friend class observer;
private:
void destroyed(observer* dead) {
_observers.erase(boost::remove(_observers, dead), _observers.end());
}
void moved(observer* from, observer* to) {
boost::replace(_observers, from, to);
}
void update_observers(observable* ob) {
for (auto&& c : _observers) {
c->_observable = ob;
}
}
public:
observable() = default;
observable(observable&& o) noexcept
: _observers(std::move(o._observers)) {
update_observers(this);
}
observable& operator=(observable&& o) noexcept {
if (this != &o) {
update_observers(nullptr);
_observers = std::move(o._observers);
update_observers(this);
}
return *this;
}
~observable() {
update_observers(nullptr);
}
// Send args to all connected observers
void operator()(Args... args) const {
std::exception_ptr e;
for (auto&& ob : _observers) {
try {
ob->_callback(args...);
} catch (...) {
if (!e) {
e = std::current_exception();
}
}
}
if (e) {
std::rethrow_exception(std::move(e));
}
}
// Adds an observer to an observable
observer observe(std::function<void (Args...)> callback) {
observer ob(this, std::move(callback));
_observers.push_back(&ob);
return ob;
}
};
template <typename... Args>
using observer = typename observable<Args...>::observer;
}
<|endoftext|> |
<commit_before>#include "lxc_isolation_module.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <algorithm>
#include "foreach.hpp"
using std::cerr;
using std::cout;
using std::endl;
using std::list;
using std::make_pair;
using std::max;
using std::ostringstream;
using std::pair;
using std::queue;
using std::string;
using std::vector;
using boost::lexical_cast;
using boost::unordered_map;
using boost::unordered_set;
using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::slave;
LxcIsolationModule::LxcIsolationModule(Slave* slave)
{
this->slave = slave;
reaper = new Reaper(this);
Process::spawn(reaper);
// Run a basic check to see whether Linux Container tools are available
if (system("lxc-version > /dev/null") != 0) {
PLOG(FATAL) << "Could not run lxc-version; make sure Linux Container "
<< "tools are installed";
}
}
LxcIsolationModule::~LxcIsolationModule()
{
// We want to wait until the reaper has completed because it
// accesses 'this' in order to make callbacks ... deleting 'this'
// could thus lead to a seg fault!
Process::post(reaper->getPID(), SHUTDOWN_REAPER);
Process::wait(reaper);
delete reaper;
}
void LxcIsolationModule::frameworkAdded(Framework* framework)
{
lxcExecutePid[framework->id] = -1;
container[framework->id] = "";
framework->executorStatus = "No executor running";
}
void LxcIsolationModule::frameworkRemoved(Framework *framework)
{
lxcExecutePid.erase(framework->id);
container.erase(framework->id);
}
void LxcIsolationModule::startExecutor(Framework *fw)
{
LOG(INFO) << "Starting executor for framework " << fw->id << ": "
<< fw->executorInfo.uri;
CHECK(lxcExecutePid[fw->id] == -1 && container[fw->id] == "");
// Get location of Nexus install in order to find nexus-launcher.
const char *nexusHome = getenv("NEXUS_HOME");
if (!nexusHome)
nexusHome = "..";
string nexusLauncher = string(nexusHome) + "/src/nexus-launcher";
// Create a name for the container
ostringstream oss;
oss << "nexus.slave-" << slave->id << ".framework-" << fw->id;
string containerName = oss.str();
container[fw->id] = containerName;
fw->executorStatus = "Container: " + containerName;
// Run lxc-execute nexus-launcher using a fork-exec (since lxc-execute
// does not return until the container is finished). Note that lxc-execute
// automatically creates the container and will delete it when finished.
pid_t pid;
if ((pid = fork()) == -1)
PLOG(FATAL) << "Failed to fork to launch lxc-execute";
if (pid) {
// In parent process
lxcExecutePid[fw->id] = pid;
LOG(INFO) << "Started lxc-execute, pid = " << pid;
int status;
} else {
// Set any environment variables given as env.* params in the ExecutorInfo
const string_map& params = fw->executorInfo.params;
foreachpair (const string& key, const string& value, params) {
if (key.find("env.") == 0) {
const string& var = key.substr(strlen("env."));
setenv(var.c_str(), value.c_str(), true);
}
}
// Set up Nexus environment variables for launcher.
setenv("NEXUS_FRAMEWORK_ID", lexical_cast<string>(fw->id).c_str(), 1);
setenv("NEXUS_EXECUTOR_URI", fw->executorInfo.uri.c_str(), 1);
setenv("NEXUS_USER", fw->user.c_str(), 1);
setenv("NEXUS_SLAVE_PID", lexical_cast<string>(slave->self()).c_str(), 1);
setenv("NEXUS_REDIRECT_IO", slave->local ? "1" : "0", 1);
setenv("NEXUS_WORK_DIRECTORY", slave->getWorkDirectory(fw->id).c_str(), 1);
// Run lxc-execute.
execlp("lxc-execute", "lxc-execute", "-n", containerName.c_str(),
nexusLauncher.c_str(), (char *) NULL);
// If we get here, the execl call failed.
fatalerror("Could not exec lxc-execute");
// TODO: Exit the slave if this happens
}
}
void LxcIsolationModule::killExecutor(Framework* fw)
{
if (container[fw->id] != "") {
LOG(INFO) << "Stopping container " << container[fw->id];
int ret = shell("lxc-stop -n %s", container[fw->id].c_str());
if (ret != 0)
LOG(ERROR) << "lxc-stop returned " << ret;
container[fw->id] = "";
fw->executorStatus = "No executor running";
}
}
void LxcIsolationModule::resourcesChanged(Framework* fw)
{
if (container[fw->id] != "") {
// For now, just try setting the CPUs and mem right away.
// A slightly smarter thing might be to only update them periodically.
int ret;
int32_t cpuShares = max(1024 * fw->resources.cpus, 10);
LOG(INFO) << "Setting CPU shares for " << fw->id << " to " << cpuShares;
ret = shell("lxc-cgroup -n %s cpu.shares %d",
container[fw->id].c_str(), cpuShares);
if (ret != 0)
LOG(ERROR) << "lxc-cgroup returned " << ret;
int64_t rssLimit = max(fw->resources.mem, 128 * Megabyte);
LOG(INFO) << "Setting RSS limit for " << fw->id << " to " << rssLimit;
ret = shell("lxc-cgroup -n %s memory.limit_in_bytes %lld",
container[fw->id].c_str(), rssLimit);
if (ret != 0)
LOG(ERROR) << "lxc-cgroup returned " << ret;
// TODO: Decreasing the RSS limit will fail if the current RSS is too
// large and memory can't be swapped out. In that case, we should
// either freeze the container before changing RSS, or just kill it.
}
}
int LxcIsolationModule::shell(const char* fmt, ...)
{
char *cmd;
FILE *f;
int ret;
va_list args;
va_start(args, fmt);
if (vasprintf(&cmd, fmt, args) == -1)
return -1;
if ((f = popen(cmd, "w")) == NULL)
return -1;
ret = pclose(f);
if (ret == -1)
LOG(INFO) << "pclose error: " << strerror(errno);
free(cmd);
va_end(args);
return ret;
}
LxcIsolationModule::Reaper::Reaper(LxcIsolationModule* m)
: module(m)
{}
void LxcIsolationModule::Reaper::operator () ()
{
link(module->slave->getPID());
while (true) {
switch (receive(1)) {
case PROCESS_TIMEOUT: {
// Check whether any child process has exited
pid_t pid;
int status;
if ((pid = waitpid((pid_t) -1, &status, WNOHANG)) > 0) {
foreachpair (FrameworkID fid, pid_t& fwPid, module->lxcExecutePid) {
if (fwPid == pid) {
module->container[fid] = "";
module->lxcExecutePid[fid] = -1;
LOG(INFO) << "Telling slave of lost framework " << fid;
// TODO(benh): This is broken if/when libprocess is parallel!
module->slave->executorExited(fid, status);
break;
}
}
}
break;
}
case SHUTDOWN_REAPER:
case PROCESS_EXIT:
return;
}
}
}
<commit_msg>Have LXC isolation module check that slave is running as root<commit_after>#include "lxc_isolation_module.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <algorithm>
#include "foreach.hpp"
using std::cerr;
using std::cout;
using std::endl;
using std::list;
using std::make_pair;
using std::max;
using std::ostringstream;
using std::pair;
using std::queue;
using std::string;
using std::vector;
using boost::lexical_cast;
using boost::unordered_map;
using boost::unordered_set;
using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::slave;
LxcIsolationModule::LxcIsolationModule(Slave* slave)
{
this->slave = slave;
reaper = new Reaper(this);
Process::spawn(reaper);
// Run a basic check to see whether Linux Container tools are available
if (system("lxc-version > /dev/null") != 0) {
PLOG(FATAL) << "Could not run lxc-version; make sure Linux Container "
<< "tools are installed";
}
// Check that we are root (technically it might be possible to create
// containers without being root, but we can support that later)
if (getuid() != 0) {
PLOG(FATAL) << "LXC isolation module requires slave to run as root";
}
}
LxcIsolationModule::~LxcIsolationModule()
{
// We want to wait until the reaper has completed because it
// accesses 'this' in order to make callbacks ... deleting 'this'
// could thus lead to a seg fault!
Process::post(reaper->getPID(), SHUTDOWN_REAPER);
Process::wait(reaper);
delete reaper;
}
void LxcIsolationModule::frameworkAdded(Framework* framework)
{
lxcExecutePid[framework->id] = -1;
container[framework->id] = "";
framework->executorStatus = "No executor running";
}
void LxcIsolationModule::frameworkRemoved(Framework *framework)
{
lxcExecutePid.erase(framework->id);
container.erase(framework->id);
}
void LxcIsolationModule::startExecutor(Framework *fw)
{
LOG(INFO) << "Starting executor for framework " << fw->id << ": "
<< fw->executorInfo.uri;
CHECK(lxcExecutePid[fw->id] == -1 && container[fw->id] == "");
// Get location of Nexus install in order to find nexus-launcher.
const char *nexusHome = getenv("NEXUS_HOME");
if (!nexusHome)
nexusHome = "..";
string nexusLauncher = string(nexusHome) + "/src/nexus-launcher";
// Create a name for the container
ostringstream oss;
oss << "nexus.slave-" << slave->id << ".framework-" << fw->id;
string containerName = oss.str();
container[fw->id] = containerName;
fw->executorStatus = "Container: " + containerName;
// Run lxc-execute nexus-launcher using a fork-exec (since lxc-execute
// does not return until the container is finished). Note that lxc-execute
// automatically creates the container and will delete it when finished.
pid_t pid;
if ((pid = fork()) == -1)
PLOG(FATAL) << "Failed to fork to launch lxc-execute";
if (pid) {
// In parent process
lxcExecutePid[fw->id] = pid;
LOG(INFO) << "Started lxc-execute, pid = " << pid;
int status;
} else {
// Set any environment variables given as env.* params in the ExecutorInfo
const string_map& params = fw->executorInfo.params;
foreachpair (const string& key, const string& value, params) {
if (key.find("env.") == 0) {
const string& var = key.substr(strlen("env."));
setenv(var.c_str(), value.c_str(), true);
}
}
// Set up Nexus environment variables for launcher.
setenv("NEXUS_FRAMEWORK_ID", lexical_cast<string>(fw->id).c_str(), 1);
setenv("NEXUS_EXECUTOR_URI", fw->executorInfo.uri.c_str(), 1);
setenv("NEXUS_USER", fw->user.c_str(), 1);
setenv("NEXUS_SLAVE_PID", lexical_cast<string>(slave->self()).c_str(), 1);
setenv("NEXUS_REDIRECT_IO", slave->local ? "1" : "0", 1);
setenv("NEXUS_WORK_DIRECTORY", slave->getWorkDirectory(fw->id).c_str(), 1);
// Run lxc-execute.
execlp("lxc-execute", "lxc-execute", "-n", containerName.c_str(),
nexusLauncher.c_str(), (char *) NULL);
// If we get here, the execl call failed.
fatalerror("Could not exec lxc-execute");
// TODO: Exit the slave if this happens
}
}
void LxcIsolationModule::killExecutor(Framework* fw)
{
if (container[fw->id] != "") {
LOG(INFO) << "Stopping container " << container[fw->id];
int ret = shell("lxc-stop -n %s", container[fw->id].c_str());
if (ret != 0)
LOG(ERROR) << "lxc-stop returned " << ret;
container[fw->id] = "";
fw->executorStatus = "No executor running";
}
}
void LxcIsolationModule::resourcesChanged(Framework* fw)
{
if (container[fw->id] != "") {
// For now, just try setting the CPUs and mem right away.
// A slightly smarter thing might be to only update them periodically.
int ret;
int32_t cpuShares = max(1024 * fw->resources.cpus, 10);
LOG(INFO) << "Setting CPU shares for " << fw->id << " to " << cpuShares;
ret = shell("lxc-cgroup -n %s cpu.shares %d",
container[fw->id].c_str(), cpuShares);
if (ret != 0)
LOG(ERROR) << "lxc-cgroup returned " << ret;
int64_t rssLimit = max(fw->resources.mem, 128 * Megabyte);
LOG(INFO) << "Setting RSS limit for " << fw->id << " to " << rssLimit;
ret = shell("lxc-cgroup -n %s memory.limit_in_bytes %lld",
container[fw->id].c_str(), rssLimit);
if (ret != 0)
LOG(ERROR) << "lxc-cgroup returned " << ret;
// TODO: Decreasing the RSS limit will fail if the current RSS is too
// large and memory can't be swapped out. In that case, we should
// either freeze the container before changing RSS, or just kill it.
}
}
int LxcIsolationModule::shell(const char* fmt, ...)
{
char *cmd;
FILE *f;
int ret;
va_list args;
va_start(args, fmt);
if (vasprintf(&cmd, fmt, args) == -1)
return -1;
if ((f = popen(cmd, "w")) == NULL)
return -1;
ret = pclose(f);
if (ret == -1)
LOG(INFO) << "pclose error: " << strerror(errno);
free(cmd);
va_end(args);
return ret;
}
LxcIsolationModule::Reaper::Reaper(LxcIsolationModule* m)
: module(m)
{}
void LxcIsolationModule::Reaper::operator () ()
{
link(module->slave->getPID());
while (true) {
switch (receive(1)) {
case PROCESS_TIMEOUT: {
// Check whether any child process has exited
pid_t pid;
int status;
if ((pid = waitpid((pid_t) -1, &status, WNOHANG)) > 0) {
foreachpair (FrameworkID fid, pid_t& fwPid, module->lxcExecutePid) {
if (fwPid == pid) {
module->container[fid] = "";
module->lxcExecutePid[fid] = -1;
LOG(INFO) << "Telling slave of lost framework " << fid;
// TODO(benh): This is broken if/when libprocess is parallel!
module->slave->executorExited(fid, status);
break;
}
}
}
break;
}
case SHUTDOWN_REAPER:
case PROCESS_EXIT:
return;
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <laplacian/version.hpp>
#include <laplacian/convolve.hpp>
#include <laplacian/kernel/gaussian.hpp>
#include <laplacian/laplacian.hpp>
#define usage() \
std::cerr << "Usage: " << argv[0] << " [options] input output" << std::endl << std::endl; \
std::cerr << "Options: " << std::endl; \
std::cerr << opts << std::endl; \
return 0; \
namespace po = boost::program_options;
int main(int argc, char* argv[]) {
po::variables_map vm;
po::options_description opts;
opts.add_options()
("help", "produce this help message")
("version", "print version information")
("input", po::value<std::string>(), "input file")
("output", po::value<std::string>(), "output file")
;
po::positional_options_description positional_opts;
positional_opts.add("input", 1);
positional_opts.add("output", 2);
po::store(po::command_line_parser(argc, argv).options(opts).positional(positional_opts).run(), vm);
try {
po::notify(vm);
} catch (std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
usage();
}
if (vm.count("help")){
usage();
}
if (vm.count("version")) {
std::cerr << std::endl;
laplacian::print_version_info(std::cerr);
std::cerr << std::endl;
return 0;
}
if (vm.count("input")) {
const std::string input(vm["input"].as<std::string>());
std::string output;
if (vm.count("output")) {
output = vm["output"].as<std::string>();
} else {
output = "output_" + vm["input"].as<std::string>();
std::cerr << "Using " << output << " as the output file." << std::endl;
}
laplacian::GaussianConvolve<laplacian::kernel::gaussian::Sigma1> smoother;
smoother.convolve(input, output);
} else {
std::cerr << "Missing input file" << std::endl;
usage();
}
}
<commit_msg>more program options<commit_after>#include <iostream>
#include <string>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <laplacian/version.hpp>
#include <laplacian/convolve.hpp>
#include <laplacian/kernel/gaussian.hpp>
#include <laplacian/kernel/laplace.hpp>
#include <laplacian/laplacian.hpp>
#define usage() \
std::cerr << "Usage: " << argv[0] << " [options] input output" << std::endl << std::endl; \
std::cerr << "Options: " << std::endl; \
std::cerr << opts << std::endl; \
return 0; \
namespace po = boost::program_options;
template<typename T>
void convolve(const std::string& input, const std::string& output) {
laplacian::GaussianConvolve<T> smoother;
smoother.convolve(input, output);
}
int main(int argc, char* argv[]) {
po::variables_map vm;
po::options_description opts;
opts.add_options()
("help", "produce this help message")
("version", "print version information")
("input", po::value<std::string>(), "input file")
("output", po::value<std::string>(), "output file")
("l1", "laplacian scale=1")
("l2", "laplacian scale=2")
("l3", "laplacian scale=3")
("l4", "laplacian scale=4")
("g1", "gaussian sigma=1")
("g2", "gaussian sigma=2")
("g3", "gaussian sigma=3")
("g4", "gaussian sigma=4")
;
po::positional_options_description positional_opts;
positional_opts.add("input", 1);
positional_opts.add("output", 2);
po::store(po::command_line_parser(argc, argv).options(opts).positional(positional_opts).run(), vm);
try {
po::notify(vm);
} catch (std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
usage();
}
if (vm.count("help")){
usage();
}
if (vm.count("version")) {
std::cerr << std::endl;
laplacian::print_version_info(std::cerr);
std::cerr << std::endl;
return 0;
}
if (vm.count("input")) {
const std::string input(vm["input"].as<std::string>());
std::string output;
if (vm.count("output")) {
output = vm["output"].as<std::string>();
} else {
output = "output_" + vm["input"].as<std::string>();
std::cerr << "Using " << output << " as the output file." << std::endl;
}
if (vm.count("l1")) {
std::cerr << "Using laplacian (scale=1) convolution" << std::endl;
convolve<laplacian::kernel::laplace::Scale1>(input, output);
} else if (vm.count("l2")) {
std::cerr << "Using laplacian (scale=2) convolution" << std::endl;
convolve<laplacian::kernel::laplace::Scale2>(input, output);
} else if (vm.count("l3")) {
std::cerr << "Using laplacian (scale=3) convolution" << std::endl;
convolve<laplacian::kernel::laplace::Scale3>(input, output);
} else if (vm.count("l4")) {
std::cerr << "Using laplacian (scale=4) convolution" << std::endl;
convolve<laplacian::kernel::laplace::Scale4>(input, output);
} else if (vm.count("g1")) {
std::cerr << "Using gaussian (sigma=1) convolution" << std::endl;
convolve<laplacian::kernel::gaussian::Sigma1>(input, output);
} else if (vm.count("g2")) {
std::cerr << "Using gaussian (sigma=2) convolution" << std::endl;
convolve<laplacian::kernel::gaussian::Sigma2>(input, output);
} else if (vm.count("g3")) {
std::cerr << "Using gaussian (sigma=3) convolution" << std::endl;
convolve<laplacian::kernel::gaussian::Sigma3>(input, output);
} else if (vm.count("g4")) {
std::cerr << "Using gaussian (sigma=4) convolution" << std::endl;
convolve<laplacian::kernel::gaussian::Sigma4>(input, output);
}
} else {
std::cerr << "Missing input file" << std::endl;
usage();
}
}
<|endoftext|> |
<commit_before>#ifndef VEXCL_EXCLUSIVE_HPP
#define VEXCLEXCLUSIVE_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <ddemidov@ksu.ru>
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.
*/
/**
* \file exclusive.hpp
* \author Denis Demidov <ddemidov@ksu.ru>
* \brief Device filter allowing exclusive access
*
* \note This file should be included manually since it depends on
* boost::interprocess library.
*/
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <vector>
#include <string>
#include <fstream>
#include <memory>
#include <cstdlib>
#include <boost/interprocess/sync/file_lock.hpp>
#include <CL/cl.hpp>
namespace vex {
/// Device filters.
namespace Filter {
/// \internal Exclusive access to selected devices.
template <class Filter>
class ExclusiveFilter {
private:
const Filter &filter;
static std::map<cl_device_id, std::string> get_uids() {
std::map<cl_device_id, std::string> uids;
std::vector<cl::Platform> platform;
cl::Platform::get(&platform);
const char *lock_dir = getenv("VEXCL_LOCK_DIR");
for(size_t p_id = 0; p_id < platform.size(); p_id++) {
std::vector<cl::Device> device;
platform[p_id].getDevices(CL_DEVICE_TYPE_ALL, &device);
for(size_t d_id = 0; d_id < device.size(); d_id++) {
std::ostringstream id;
#ifdef WIN32
id << (lock_dir ? lock_dir : getenv("TMPDIR")) << "\\";
#else
id << (lock_dir ? lock_dir : "/tmp") << "/";
#endif
id << "vexcl_device_" << p_id << "_" << d_id << ".lock";
uids[device[d_id]()] = id.str();
}
}
return uids;
}
struct locker {
locker(std::string fname) : file(fname)
{
if (!file.is_open() || file.fail()) {
std::cerr
<< "WARNING: failed to open file \"" << fname << "\"\n"
<< " Check that target directory is exists and is writable.\n"
<< " Exclusive mode is off.\n"
<< std::endl;
} else {
flock.reset(new boost::interprocess::file_lock(fname.c_str()));
}
}
bool try_lock() {
if (flock)
return flock->try_lock();
else
return true;
}
void unlock() {
flock->unlock();
}
std::ofstream file;
std::unique_ptr<boost::interprocess::file_lock> flock;
};
public:
ExclusiveFilter(const Filter &filter) : filter(filter) {}
bool operator()(const cl::Device &d) const {
static std::map<cl_device_id, std::string> dev_uids = get_uids();
static std::vector<std::unique_ptr<locker>> locks;
std::unique_ptr<locker> lck(new locker(dev_uids[d()]));
if (lck->try_lock()) {
if (filter(d)) {
locks.push_back(std::move(lck));
return true;
} else {
lck->unlock();
return false;
}
}
return false;
}
};
/// Allows exclusive access to compute devices across several processes.
/**
* Returns devices that pass through provided device filter and are not
* locked.
*
* \param filter Compute device filter
*
* \note Depends on boost::interprocess library.
*
* lock files are created in directory specified in VEXCL_LOCK_DIR
* environment variable. If the variable does not exist, /tmp is
* used on Linux and %TMPDIR% on Windows. The lock directory should exist
* and be writable by the running user.
*/
template <class Filter>
ExclusiveFilter<Filter> Exclusive(const Filter &filter) {
return ExclusiveFilter<Filter>(filter);
}
}
}
#endif
<commit_msg>Simplified exclusive filter<commit_after>#ifndef VEXCL_EXCLUSIVE_HPP
#define VEXCLEXCLUSIVE_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <ddemidov@ksu.ru>
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.
*/
/**
* \file exclusive.hpp
* \author Denis Demidov <ddemidov@ksu.ru>
* \brief Device filter allowing exclusive access
*
* \note This file should be included manually since it depends on
* boost::interprocess library.
*/
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <vector>
#include <string>
#include <fstream>
#include <memory>
#include <cstdlib>
#include <boost/interprocess/sync/file_lock.hpp>
#include <CL/cl.hpp>
namespace vex {
/// Device filters.
namespace Filter {
/// \internal Exclusive access to selected devices.
template <class Filter>
class ExclusiveFilter {
private:
const Filter &filter;
static std::map<cl_device_id, std::string> get_uids() {
std::map<cl_device_id, std::string> uids;
std::vector<cl::Platform> platform;
cl::Platform::get(&platform);
const char *lock_dir = getenv("VEXCL_LOCK_DIR");
for(size_t p_id = 0; p_id < platform.size(); p_id++) {
std::vector<cl::Device> device;
platform[p_id].getDevices(CL_DEVICE_TYPE_ALL, &device);
for(size_t d_id = 0; d_id < device.size(); d_id++) {
std::ostringstream id;
#ifdef WIN32
id << (lock_dir ? lock_dir : getenv("TMPDIR")) << "\\";
#else
id << (lock_dir ? lock_dir : "/tmp") << "/";
#endif
id << "vexcl_device_" << p_id << "_" << d_id << ".lock";
uids[device[d_id]()] = id.str();
}
}
return uids;
}
struct locker {
locker(std::string fname) : file(fname)
{
if (!file.is_open() || file.fail()) {
std::cerr
<< "WARNING: failed to open file \"" << fname << "\"\n"
<< " Check that target directory is exists and is writable.\n"
<< " Exclusive mode is off.\n"
<< std::endl;
} else {
flock.reset(new boost::interprocess::file_lock(fname.c_str()));
}
}
bool try_lock() {
if (flock)
return flock->try_lock();
else
return true;
}
std::ofstream file;
std::unique_ptr<boost::interprocess::file_lock> flock;
};
public:
ExclusiveFilter(const Filter &filter) : filter(filter) {}
bool operator()(const cl::Device &d) const {
static std::map<cl_device_id, std::string> dev_uids = get_uids();
static std::vector<std::unique_ptr<locker>> locks;
std::unique_ptr<locker> lck(new locker(dev_uids[d()]));
if (lck->try_lock() && filter(d)) {
locks.push_back(std::move(lck));
return true;
}
return false;
}
};
/// Allows exclusive access to compute devices across several processes.
/**
* Returns devices that pass through provided device filter and are not
* locked.
*
* \param filter Compute device filter
*
* \note Depends on boost::interprocess library.
*
* lock files are created in directory specified in VEXCL_LOCK_DIR
* environment variable. If the variable does not exist, /tmp is
* used on Linux and %TMPDIR% on Windows. The lock directory should exist
* and be writable by the running user.
*/
template <class Filter>
ExclusiveFilter<Filter> Exclusive(const Filter &filter) {
return ExclusiveFilter<Filter>(filter);
}
}
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <sstream>
#include <float.h>
#include "reductions.h"
#include "gd.h"
struct oaa{
size_t k;
vw* all; // for raw
};
template <bool is_learn, bool print_all>
void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) {
MULTICLASS::label_t mc_label_data = ec.l.multi;
if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1))
cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl;
stringstream outputStringStream;
uint32_t prediction = 1;
ec.l.simple = {0.f, mc_label_data.weight, 0.f};
float score = INT_MIN;
for (uint32_t i = 1; i <= o.k; i++) {
if (is_learn) {
ec.l.simple.label = (mc_label_data.label == i) ? 1.f : -1.f;
base.learn(ec, i-1);
} else
base.predict(ec, i-1);
if (ec.partial_prediction > score) {
score = ec.partial_prediction;
prediction = i;
}
if (print_all) {
if (i > 1) outputStringStream << ' ';
outputStringStream << i << ':' << ec.partial_prediction;
}
}
ec.pred.multiclass = prediction;
ec.l.multi = mc_label_data;
if (print_all)
o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag);
}
LEARNER::base_learner* oaa_setup(vw& all)
{
if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels"))
return NULL;
oaa& data = calloc_or_die<oaa>();
data.k = all.vm["oaa"].as<size_t>();
data.all = &all;
LEARNER::learner<oaa>* l;
if (all.raw_prediction > 0)
l = &LEARNER::init_multiclass_learner(&data, setup_base(all), predict_or_learn<true, true>,
predict_or_learn<false, true>, all.p, data.k);
else
l = &LEARNER::init_multiclass_learner(&data, setup_base(all),predict_or_learn<true, false>,
predict_or_learn<false, false>, all.p, data.k);
return make_base(*l);
}
<commit_msg>remove spurious include<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <sstream>
#include <float.h>
#include "reductions.h"
struct oaa{
size_t k;
vw* all; // for raw
};
template <bool is_learn, bool print_all>
void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) {
MULTICLASS::label_t mc_label_data = ec.l.multi;
if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1))
cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl;
stringstream outputStringStream;
uint32_t prediction = 1;
ec.l.simple = {0.f, mc_label_data.weight, 0.f};
float score = INT_MIN;
for (uint32_t i = 1; i <= o.k; i++) {
if (is_learn) {
ec.l.simple.label = (mc_label_data.label == i) ? 1.f : -1.f;
base.learn(ec, i-1);
} else
base.predict(ec, i-1);
if (ec.partial_prediction > score) {
score = ec.partial_prediction;
prediction = i;
}
if (print_all) {
if (i > 1) outputStringStream << ' ';
outputStringStream << i << ':' << ec.partial_prediction;
}
}
ec.pred.multiclass = prediction;
ec.l.multi = mc_label_data;
if (print_all)
o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag);
}
LEARNER::base_learner* oaa_setup(vw& all)
{
if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels"))
return NULL;
oaa& data = calloc_or_die<oaa>();
data.k = all.vm["oaa"].as<size_t>();
data.all = &all;
LEARNER::learner<oaa>* l;
if (all.raw_prediction > 0)
l = &LEARNER::init_multiclass_learner(&data, setup_base(all), predict_or_learn<true, true>,
predict_or_learn<false, true>, all.p, data.k);
else
l = &LEARNER::init_multiclass_learner(&data, setup_base(all),predict_or_learn<true, false>,
predict_or_learn<false, false>, all.p, data.k);
return make_base(*l);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2020 The WebM 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 "vp9/ratectrl_rtc.h"
#include <new>
#include "vp9/common/vp9_common.h"
#include "vp9/encoder/vp9_encoder.h"
#include "vp9/encoder/vp9_picklpf.h"
#include "vpx/vp8cx.h"
#include "vpx/vpx_codec.h"
namespace libvpx {
std::unique_ptr<VP9RateControlRTC> VP9RateControlRTC::Create(
const VP9RateControlRtcConfig &cfg) {
std::unique_ptr<VP9RateControlRTC> rc_api(new (std::nothrow)
VP9RateControlRTC());
if (!rc_api) return nullptr;
rc_api->cpi_ = static_cast<VP9_COMP *>(vpx_memalign(32, sizeof(*cpi_)));
if (!rc_api->cpi_) return nullptr;
vp9_zero(*rc_api->cpi_);
rc_api->InitRateControl(cfg);
if (cfg.aq_mode) {
VP9_COMP *const cpi = rc_api->cpi_;
cpi->segmentation_map = static_cast<uint8_t *>(
vpx_calloc(cpi->common.mi_rows * cpi->common.mi_cols,
sizeof(*cpi->segmentation_map)));
cpi->cyclic_refresh =
vp9_cyclic_refresh_alloc(cpi->common.mi_rows, cpi->common.mi_cols);
cpi->cyclic_refresh->content_mode = 0;
}
return rc_api;
}
void VP9RateControlRTC::InitRateControl(const VP9RateControlRtcConfig &rc_cfg) {
VP9_COMMON *cm = &cpi_->common;
VP9EncoderConfig *oxcf = &cpi_->oxcf;
RATE_CONTROL *const rc = &cpi_->rc;
cm->profile = PROFILE_0;
cm->bit_depth = VPX_BITS_8;
cm->show_frame = 1;
oxcf->profile = cm->profile;
oxcf->bit_depth = cm->bit_depth;
oxcf->rc_mode = rc_cfg.rc_mode;
oxcf->pass = 0;
oxcf->aq_mode = rc_cfg.aq_mode ? CYCLIC_REFRESH_AQ : NO_AQ;
oxcf->content = VP9E_CONTENT_DEFAULT;
oxcf->drop_frames_water_mark = 0;
cm->current_video_frame = 0;
rc->kf_boost = DEFAULT_KF_BOOST;
UpdateRateControl(rc_cfg);
vp9_set_mb_mi(cm, cm->width, cm->height);
cpi_->use_svc = (cpi_->svc.number_spatial_layers > 1 ||
cpi_->svc.number_temporal_layers > 1)
? 1
: 0;
rc->rc_1_frame = 0;
rc->rc_2_frame = 0;
vp9_rc_init_minq_luts();
vp9_rc_init(oxcf, 0, rc);
rc->constrain_gf_key_freq_onepass_vbr = 0;
cpi_->sf.use_nonrd_pick_mode = 1;
}
void VP9RateControlRTC::UpdateRateControl(
const VP9RateControlRtcConfig &rc_cfg) {
VP9_COMMON *cm = &cpi_->common;
VP9EncoderConfig *oxcf = &cpi_->oxcf;
RATE_CONTROL *const rc = &cpi_->rc;
cm->width = rc_cfg.width;
cm->height = rc_cfg.height;
oxcf->width = rc_cfg.width;
oxcf->height = rc_cfg.height;
oxcf->worst_allowed_q = vp9_quantizer_to_qindex(rc_cfg.max_quantizer);
oxcf->best_allowed_q = vp9_quantizer_to_qindex(rc_cfg.min_quantizer);
rc->worst_quality = oxcf->worst_allowed_q;
rc->best_quality = oxcf->best_allowed_q;
oxcf->init_framerate = rc_cfg.framerate;
oxcf->target_bandwidth = 1000 * rc_cfg.target_bandwidth;
oxcf->starting_buffer_level_ms = rc_cfg.buf_initial_sz;
oxcf->optimal_buffer_level_ms = rc_cfg.buf_optimal_sz;
oxcf->maximum_buffer_size_ms = rc_cfg.buf_sz;
oxcf->under_shoot_pct = rc_cfg.undershoot_pct;
oxcf->over_shoot_pct = rc_cfg.overshoot_pct;
oxcf->ss_number_layers = rc_cfg.ss_number_layers;
oxcf->ts_number_layers = rc_cfg.ts_number_layers;
oxcf->temporal_layering_mode = (VP9E_TEMPORAL_LAYERING_MODE)(
(rc_cfg.ts_number_layers > 1) ? rc_cfg.ts_number_layers : 0);
cpi_->oxcf.rc_max_intra_bitrate_pct = rc_cfg.max_intra_bitrate_pct;
cpi_->oxcf.rc_max_inter_bitrate_pct = rc_cfg.max_inter_bitrate_pct;
cpi_->framerate = rc_cfg.framerate;
cpi_->svc.number_spatial_layers = rc_cfg.ss_number_layers;
cpi_->svc.number_temporal_layers = rc_cfg.ts_number_layers;
vp9_set_mb_mi(cm, cm->width, cm->height);
for (int sl = 0; sl < cpi_->svc.number_spatial_layers; ++sl) {
for (int tl = 0; tl < cpi_->svc.number_temporal_layers; ++tl) {
const int layer =
LAYER_IDS_TO_IDX(sl, tl, cpi_->svc.number_temporal_layers);
LAYER_CONTEXT *lc = &cpi_->svc.layer_context[layer];
RATE_CONTROL *const lrc = &lc->rc;
oxcf->layer_target_bitrate[layer] =
1000 * rc_cfg.layer_target_bitrate[layer];
lrc->worst_quality =
vp9_quantizer_to_qindex(rc_cfg.max_quantizers[layer]);
lrc->best_quality = vp9_quantizer_to_qindex(rc_cfg.min_quantizers[layer]);
lc->scaling_factor_num = rc_cfg.scaling_factor_num[sl];
lc->scaling_factor_den = rc_cfg.scaling_factor_den[sl];
oxcf->ts_rate_decimator[tl] = rc_cfg.ts_rate_decimator[tl];
}
}
vp9_set_rc_buffer_sizes(cpi_);
vp9_new_framerate(cpi_, cpi_->framerate);
if (cpi_->svc.number_temporal_layers > 1 ||
cpi_->svc.number_spatial_layers > 1) {
if (cm->current_video_frame == 0) vp9_init_layer_context(cpi_);
vp9_update_layer_context_change_config(cpi_,
(int)cpi_->oxcf.target_bandwidth);
}
vp9_check_reset_rc_flag(cpi_);
}
void VP9RateControlRTC::ComputeQP(const VP9FrameParamsQpRTC &frame_params) {
VP9_COMMON *const cm = &cpi_->common;
int width, height;
cpi_->svc.spatial_layer_id = frame_params.spatial_layer_id;
cpi_->svc.temporal_layer_id = frame_params.temporal_layer_id;
if (cpi_->svc.number_spatial_layers > 1) {
const int layer = LAYER_IDS_TO_IDX(cpi_->svc.spatial_layer_id,
cpi_->svc.temporal_layer_id,
cpi_->svc.number_temporal_layers);
LAYER_CONTEXT *lc = &cpi_->svc.layer_context[layer];
get_layer_resolution(cpi_->oxcf.width, cpi_->oxcf.height,
lc->scaling_factor_num, lc->scaling_factor_den, &width,
&height);
cm->width = width;
cm->height = height;
}
vp9_set_mb_mi(cm, cm->width, cm->height);
cm->frame_type = frame_params.frame_type;
cpi_->refresh_golden_frame = (cm->frame_type == KEY_FRAME) ? 1 : 0;
cpi_->sf.use_nonrd_pick_mode = 1;
if (cpi_->svc.number_spatial_layers == 1 &&
cpi_->svc.number_temporal_layers == 1) {
int target = 0;
if (cpi_->oxcf.rc_mode == VPX_CBR) {
if (cpi_->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
vp9_cyclic_refresh_update_parameters(cpi_);
if (frame_is_intra_only(cm))
target = vp9_calc_iframe_target_size_one_pass_cbr(cpi_);
else
target = vp9_calc_pframe_target_size_one_pass_cbr(cpi_);
} else if (cpi_->oxcf.rc_mode == VPX_VBR) {
if (cm->frame_type == KEY_FRAME) {
cpi_->rc.this_key_frame_forced = cm->current_video_frame != 0;
cpi_->rc.frames_to_key = cpi_->oxcf.key_freq;
}
vp9_set_gf_update_one_pass_vbr(cpi_);
if (cpi_->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
vp9_cyclic_refresh_update_parameters(cpi_);
if (frame_is_intra_only(cm))
target = vp9_calc_iframe_target_size_one_pass_vbr(cpi_);
else
target = vp9_calc_pframe_target_size_one_pass_vbr(cpi_);
}
vp9_rc_set_frame_target(cpi_, target);
vp9_update_buffer_level_preencode(cpi_);
} else {
vp9_update_temporal_layer_framerate(cpi_);
vp9_restore_layer_context(cpi_);
vp9_rc_get_svc_params(cpi_);
}
int bottom_index, top_index;
cpi_->common.base_qindex =
vp9_rc_pick_q_and_bounds(cpi_, &bottom_index, &top_index);
if (cpi_->oxcf.aq_mode == CYCLIC_REFRESH_AQ) vp9_cyclic_refresh_setup(cpi_);
}
int VP9RateControlRTC::GetQP() const { return cpi_->common.base_qindex; }
int VP9RateControlRTC::GetLoopfilterLevel() const {
struct loopfilter *const lf = &cpi_->common.lf;
vp9_pick_filter_level(nullptr, cpi_, LPF_PICK_FROM_Q);
return lf->filter_level;
}
signed char *VP9RateControlRTC::GetCyclicRefreshMap() const {
return cpi_->cyclic_refresh->map;
}
int *VP9RateControlRTC::GetDeltaQ() const {
return cpi_->cyclic_refresh->qindex_delta;
}
void VP9RateControlRTC::PostEncodeUpdate(uint64_t encoded_frame_size) {
vp9_rc_postencode_update(cpi_, encoded_frame_size);
if (cpi_->svc.number_spatial_layers > 1 ||
cpi_->svc.number_temporal_layers > 1)
vp9_save_layer_context(cpi_);
cpi_->common.current_video_frame++;
}
} // namespace libvpx
<commit_msg>VP9RateControlRTC::Create: check segmentation_map alloc<commit_after>/*
* Copyright (c) 2020 The WebM 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 "vp9/ratectrl_rtc.h"
#include <new>
#include "vp9/common/vp9_common.h"
#include "vp9/encoder/vp9_encoder.h"
#include "vp9/encoder/vp9_picklpf.h"
#include "vpx/vp8cx.h"
#include "vpx/vpx_codec.h"
namespace libvpx {
std::unique_ptr<VP9RateControlRTC> VP9RateControlRTC::Create(
const VP9RateControlRtcConfig &cfg) {
std::unique_ptr<VP9RateControlRTC> rc_api(new (std::nothrow)
VP9RateControlRTC());
if (!rc_api) return nullptr;
rc_api->cpi_ = static_cast<VP9_COMP *>(vpx_memalign(32, sizeof(*cpi_)));
if (!rc_api->cpi_) {
rc_api.reset();
return nullptr;
}
vp9_zero(*rc_api->cpi_);
rc_api->InitRateControl(cfg);
if (cfg.aq_mode) {
VP9_COMP *const cpi = rc_api->cpi_;
cpi->segmentation_map = static_cast<uint8_t *>(
vpx_calloc(cpi->common.mi_rows * cpi->common.mi_cols,
sizeof(*cpi->segmentation_map)));
if (!cpi->segmentation_map) {
rc_api.reset();
return nullptr;
}
cpi->cyclic_refresh =
vp9_cyclic_refresh_alloc(cpi->common.mi_rows, cpi->common.mi_cols);
cpi->cyclic_refresh->content_mode = 0;
}
return rc_api;
}
void VP9RateControlRTC::InitRateControl(const VP9RateControlRtcConfig &rc_cfg) {
VP9_COMMON *cm = &cpi_->common;
VP9EncoderConfig *oxcf = &cpi_->oxcf;
RATE_CONTROL *const rc = &cpi_->rc;
cm->profile = PROFILE_0;
cm->bit_depth = VPX_BITS_8;
cm->show_frame = 1;
oxcf->profile = cm->profile;
oxcf->bit_depth = cm->bit_depth;
oxcf->rc_mode = rc_cfg.rc_mode;
oxcf->pass = 0;
oxcf->aq_mode = rc_cfg.aq_mode ? CYCLIC_REFRESH_AQ : NO_AQ;
oxcf->content = VP9E_CONTENT_DEFAULT;
oxcf->drop_frames_water_mark = 0;
cm->current_video_frame = 0;
rc->kf_boost = DEFAULT_KF_BOOST;
UpdateRateControl(rc_cfg);
vp9_set_mb_mi(cm, cm->width, cm->height);
cpi_->use_svc = (cpi_->svc.number_spatial_layers > 1 ||
cpi_->svc.number_temporal_layers > 1)
? 1
: 0;
rc->rc_1_frame = 0;
rc->rc_2_frame = 0;
vp9_rc_init_minq_luts();
vp9_rc_init(oxcf, 0, rc);
rc->constrain_gf_key_freq_onepass_vbr = 0;
cpi_->sf.use_nonrd_pick_mode = 1;
}
void VP9RateControlRTC::UpdateRateControl(
const VP9RateControlRtcConfig &rc_cfg) {
VP9_COMMON *cm = &cpi_->common;
VP9EncoderConfig *oxcf = &cpi_->oxcf;
RATE_CONTROL *const rc = &cpi_->rc;
cm->width = rc_cfg.width;
cm->height = rc_cfg.height;
oxcf->width = rc_cfg.width;
oxcf->height = rc_cfg.height;
oxcf->worst_allowed_q = vp9_quantizer_to_qindex(rc_cfg.max_quantizer);
oxcf->best_allowed_q = vp9_quantizer_to_qindex(rc_cfg.min_quantizer);
rc->worst_quality = oxcf->worst_allowed_q;
rc->best_quality = oxcf->best_allowed_q;
oxcf->init_framerate = rc_cfg.framerate;
oxcf->target_bandwidth = 1000 * rc_cfg.target_bandwidth;
oxcf->starting_buffer_level_ms = rc_cfg.buf_initial_sz;
oxcf->optimal_buffer_level_ms = rc_cfg.buf_optimal_sz;
oxcf->maximum_buffer_size_ms = rc_cfg.buf_sz;
oxcf->under_shoot_pct = rc_cfg.undershoot_pct;
oxcf->over_shoot_pct = rc_cfg.overshoot_pct;
oxcf->ss_number_layers = rc_cfg.ss_number_layers;
oxcf->ts_number_layers = rc_cfg.ts_number_layers;
oxcf->temporal_layering_mode = (VP9E_TEMPORAL_LAYERING_MODE)(
(rc_cfg.ts_number_layers > 1) ? rc_cfg.ts_number_layers : 0);
cpi_->oxcf.rc_max_intra_bitrate_pct = rc_cfg.max_intra_bitrate_pct;
cpi_->oxcf.rc_max_inter_bitrate_pct = rc_cfg.max_inter_bitrate_pct;
cpi_->framerate = rc_cfg.framerate;
cpi_->svc.number_spatial_layers = rc_cfg.ss_number_layers;
cpi_->svc.number_temporal_layers = rc_cfg.ts_number_layers;
vp9_set_mb_mi(cm, cm->width, cm->height);
for (int sl = 0; sl < cpi_->svc.number_spatial_layers; ++sl) {
for (int tl = 0; tl < cpi_->svc.number_temporal_layers; ++tl) {
const int layer =
LAYER_IDS_TO_IDX(sl, tl, cpi_->svc.number_temporal_layers);
LAYER_CONTEXT *lc = &cpi_->svc.layer_context[layer];
RATE_CONTROL *const lrc = &lc->rc;
oxcf->layer_target_bitrate[layer] =
1000 * rc_cfg.layer_target_bitrate[layer];
lrc->worst_quality =
vp9_quantizer_to_qindex(rc_cfg.max_quantizers[layer]);
lrc->best_quality = vp9_quantizer_to_qindex(rc_cfg.min_quantizers[layer]);
lc->scaling_factor_num = rc_cfg.scaling_factor_num[sl];
lc->scaling_factor_den = rc_cfg.scaling_factor_den[sl];
oxcf->ts_rate_decimator[tl] = rc_cfg.ts_rate_decimator[tl];
}
}
vp9_set_rc_buffer_sizes(cpi_);
vp9_new_framerate(cpi_, cpi_->framerate);
if (cpi_->svc.number_temporal_layers > 1 ||
cpi_->svc.number_spatial_layers > 1) {
if (cm->current_video_frame == 0) vp9_init_layer_context(cpi_);
vp9_update_layer_context_change_config(cpi_,
(int)cpi_->oxcf.target_bandwidth);
}
vp9_check_reset_rc_flag(cpi_);
}
void VP9RateControlRTC::ComputeQP(const VP9FrameParamsQpRTC &frame_params) {
VP9_COMMON *const cm = &cpi_->common;
int width, height;
cpi_->svc.spatial_layer_id = frame_params.spatial_layer_id;
cpi_->svc.temporal_layer_id = frame_params.temporal_layer_id;
if (cpi_->svc.number_spatial_layers > 1) {
const int layer = LAYER_IDS_TO_IDX(cpi_->svc.spatial_layer_id,
cpi_->svc.temporal_layer_id,
cpi_->svc.number_temporal_layers);
LAYER_CONTEXT *lc = &cpi_->svc.layer_context[layer];
get_layer_resolution(cpi_->oxcf.width, cpi_->oxcf.height,
lc->scaling_factor_num, lc->scaling_factor_den, &width,
&height);
cm->width = width;
cm->height = height;
}
vp9_set_mb_mi(cm, cm->width, cm->height);
cm->frame_type = frame_params.frame_type;
cpi_->refresh_golden_frame = (cm->frame_type == KEY_FRAME) ? 1 : 0;
cpi_->sf.use_nonrd_pick_mode = 1;
if (cpi_->svc.number_spatial_layers == 1 &&
cpi_->svc.number_temporal_layers == 1) {
int target = 0;
if (cpi_->oxcf.rc_mode == VPX_CBR) {
if (cpi_->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
vp9_cyclic_refresh_update_parameters(cpi_);
if (frame_is_intra_only(cm))
target = vp9_calc_iframe_target_size_one_pass_cbr(cpi_);
else
target = vp9_calc_pframe_target_size_one_pass_cbr(cpi_);
} else if (cpi_->oxcf.rc_mode == VPX_VBR) {
if (cm->frame_type == KEY_FRAME) {
cpi_->rc.this_key_frame_forced = cm->current_video_frame != 0;
cpi_->rc.frames_to_key = cpi_->oxcf.key_freq;
}
vp9_set_gf_update_one_pass_vbr(cpi_);
if (cpi_->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
vp9_cyclic_refresh_update_parameters(cpi_);
if (frame_is_intra_only(cm))
target = vp9_calc_iframe_target_size_one_pass_vbr(cpi_);
else
target = vp9_calc_pframe_target_size_one_pass_vbr(cpi_);
}
vp9_rc_set_frame_target(cpi_, target);
vp9_update_buffer_level_preencode(cpi_);
} else {
vp9_update_temporal_layer_framerate(cpi_);
vp9_restore_layer_context(cpi_);
vp9_rc_get_svc_params(cpi_);
}
int bottom_index, top_index;
cpi_->common.base_qindex =
vp9_rc_pick_q_and_bounds(cpi_, &bottom_index, &top_index);
if (cpi_->oxcf.aq_mode == CYCLIC_REFRESH_AQ) vp9_cyclic_refresh_setup(cpi_);
}
int VP9RateControlRTC::GetQP() const { return cpi_->common.base_qindex; }
int VP9RateControlRTC::GetLoopfilterLevel() const {
struct loopfilter *const lf = &cpi_->common.lf;
vp9_pick_filter_level(nullptr, cpi_, LPF_PICK_FROM_Q);
return lf->filter_level;
}
signed char *VP9RateControlRTC::GetCyclicRefreshMap() const {
return cpi_->cyclic_refresh->map;
}
int *VP9RateControlRTC::GetDeltaQ() const {
return cpi_->cyclic_refresh->qindex_delta;
}
void VP9RateControlRTC::PostEncodeUpdate(uint64_t encoded_frame_size) {
vp9_rc_postencode_update(cpi_, encoded_frame_size);
if (cpi_->svc.number_spatial_layers > 1 ||
cpi_->svc.number_temporal_layers > 1)
vp9_save_layer_context(cpi_);
cpi_->common.current_video_frame++;
}
} // namespace libvpx
<|endoftext|> |
<commit_before>#include "File.h"
#include "Index.h"
#include "LineSink.h"
#include "ConsoleLog.h"
#include <tclap/CmdLine.h>
#include <iostream>
#include <stdexcept>
#include "RangeFetcher.h"
using namespace std;
using namespace TCLAP;
namespace {
struct PrintSink : LineSink {
bool printLineNum;
PrintSink(bool printLineNum) : printLineNum(printLineNum) { }
bool onLine(size_t l, size_t, const char *line, size_t length) override {
if (printLineNum) cout << l << ":";
cout << string(line, length) << endl;
return true;
}
};
struct PrintHandler : RangeFetcher::Handler {
Index &index;
LineSink &sink;
const bool printSep;
const std::string sep;
PrintHandler(Index &index, LineSink &sink, bool printSep,
const std::string &sep)
: index(index), sink(sink), printSep(printSep), sep(sep) { }
virtual void onLine(uint64_t line) override {
index.getLine(line, sink);
}
virtual void onSeparator() override {
if (printSep)
cout << sep << endl;
}
};
uint64_t toInt(const string &s) {
char *endP;
auto res = strtoull(&s[0], &endP, 10);
if (*endP != '\0') throw runtime_error("Non-numeric value: '" + s + "'");
return res;
}
}
int Main(int argc, const char *argv[]) {
CmdLine cmd("Lookup indices in a compressed text file");
UnlabeledValueArg<string> inputFile(
"input-file", "Read input from <file>", true, "", "file", cmd);
UnlabeledMultiArg<string> query(
"query", "Query for <query>", false, "<query>", cmd);
SwitchArg lineMode("l", "line",
"Treat query as a series of line numbers to print", cmd);
SwitchArg verbose("v", "verbose", "Be more verbose", cmd);
SwitchArg debug("", "debug", "Be even more verbose", cmd);
SwitchArg forceColour("", "colour", "Use colour even on non-TTY", cmd);
SwitchArg forceColor("", "color", "Use color even on non-TTY", cmd);
SwitchArg forceLoad("", "force", "Load index even if it appears "
"inconsistent with the index", cmd);
SwitchArg lineNum("n", "line-number",
"Prefix each line of output with its line number", cmd);
ValueArg<uint64_t> afterArg("A", "after-context",
"Print NUM lines of context after each match",
false, 0, "NUM", cmd);
ValueArg<uint64_t> beforeArg("B", "before-context",
"Print NUM lines of context before each match",
false, 0, "NUM", cmd);
ValueArg<uint64_t> contextArg("C", "context",
"Print NUM lines of context around each match",
false, 0, "NUM", cmd);
SwitchArg noSepArg("", "no-separator",
"Don't print a separator between non-overlapping contexts",
cmd);
ValueArg<string> sepArg("S", "separator",
"Print SEPARATOR between non-overlapping contexts "
"(if -A, -B or -C specified)",
false, "--", "SEPARATOR", cmd);
ValueArg<string> indexArg("", "index-file", "Use index from <index-file> "
"(default <file>.zindex)", false, "", "index", cmd);
cmd.parse(argc, argv);
ConsoleLog log(
debug.isSet() ? Log::Severity::Debug : verbose.isSet()
? Log::Severity::Info
: Log::Severity::Warning,
forceColour.isSet() || forceColor.isSet());
try {
auto compressedFile = inputFile.getValue();
File in(fopen(compressedFile.c_str(), "rb"));
if (in.get() == nullptr) {
log.error("Could not open ", compressedFile, " for reading");
return 1;
}
auto indexFile = indexArg.isSet() ? indexArg.getValue() :
inputFile.getValue() + ".zindex";
auto index = Index::load(log, move(in), indexFile.c_str(),
forceLoad.isSet());
uint64_t before = 0u;
uint64_t after = 0u;
if (beforeArg.isSet()) before = beforeArg.getValue();
if (afterArg.isSet()) after = afterArg.getValue();
if (contextArg.isSet()) before = after = contextArg.getValue();
log.debug("Fetching context of ", before, " lines before and ", after,
" lines after");
PrintSink sink(lineNum.isSet());
PrintHandler ph(index, sink, (before || after) && !noSepArg.isSet(),
sepArg.getValue());
RangeFetcher rangeFetcher(ph, before, after);
if (lineMode.isSet()) {
for (auto &q : query.getValue())
rangeFetcher(toInt(q));
} else {
index.queryIndexMulti("default", query.getValue(), rangeFetcher);
}
} catch (const exception &e) {
log.error(e.what());
}
return 0;
}
int main(int argc, const char *argv[]) {
try {
return Main(argc, argv);
} catch (const exception &e) {
cerr << e.what() << endl;
return 1;
}
}
<commit_msg>Add param to allow searching a specific index if there are multiple<commit_after>#include "File.h"
#include "Index.h"
#include "LineSink.h"
#include "ConsoleLog.h"
#include <tclap/CmdLine.h>
#include <iostream>
#include <stdexcept>
#include "RangeFetcher.h"
using namespace std;
using namespace TCLAP;
namespace {
struct PrintSink : LineSink {
bool printLineNum;
PrintSink(bool printLineNum) : printLineNum(printLineNum) { }
bool onLine(size_t l, size_t, const char *line, size_t length) override {
if (printLineNum) cout << l << ":";
cout << string(line, length) << endl;
return true;
}
};
struct PrintHandler : RangeFetcher::Handler {
Index &index;
LineSink &sink;
const bool printSep;
const std::string sep;
PrintHandler(Index &index, LineSink &sink, bool printSep,
const std::string &sep)
: index(index), sink(sink), printSep(printSep), sep(sep) { }
virtual void onLine(uint64_t line) override {
index.getLine(line, sink);
}
virtual void onSeparator() override {
if (printSep)
cout << sep << endl;
}
};
uint64_t toInt(const string &s) {
char *endP;
auto res = strtoull(&s[0], &endP, 10);
if (*endP != '\0') throw runtime_error("Non-numeric value: '" + s + "'");
return res;
}
}
int Main(int argc, const char *argv[]) {
CmdLine cmd("Lookup indices in a compressed text file");
UnlabeledValueArg<string> inputFile(
"input-file", "Read input from <file>", true, "", "file", cmd);
UnlabeledMultiArg<string> query(
"query", "Query for <query>", false, "<query>", cmd);
SwitchArg lineMode("l", "line",
"Treat query as a series of line numbers to print", cmd);
SwitchArg verbose("v", "verbose", "Be more verbose", cmd);
SwitchArg debug("", "debug", "Be even more verbose", cmd);
SwitchArg forceColour("", "colour", "Use colour even on non-TTY", cmd);
SwitchArg forceColor("", "color", "Use color even on non-TTY", cmd);
SwitchArg forceLoad("", "force", "Load index even if it appears "
"inconsistent with the index", cmd);
SwitchArg lineNum("n", "line-number",
"Prefix each line of output with its line number", cmd);
ValueArg<uint64_t> afterArg("A", "after-context",
"Print NUM lines of context after each match",
false, 0, "NUM", cmd);
ValueArg<uint64_t> beforeArg("B", "before-context",
"Print NUM lines of context before each match",
false, 0, "NUM", cmd);
ValueArg<uint64_t> contextArg("C", "context",
"Print NUM lines of context around each match",
false, 0, "NUM", cmd);
SwitchArg noSepArg("", "no-separator",
"Don't print a separator between non-overlapping contexts",
cmd);
ValueArg<string> sepArg("S", "separator",
"Print SEPARATOR between non-overlapping contexts "
"(if -A, -B or -C specified)",
false, "--", "SEPARATOR", cmd);
ValueArg<string> indexArg("", "index-file", "Use index from <index-file> "
"(default <file>.zindex)", false, "", "index", cmd);
ValueArg<string> queryIndexArg("i", "index", "Use specified index for searching"
, false, "", "index", cmd);
cmd.parse(argc, argv);
ConsoleLog log(
debug.isSet() ? Log::Severity::Debug : verbose.isSet()
? Log::Severity::Info
: Log::Severity::Warning,
forceColour.isSet() || forceColor.isSet());
try {
auto compressedFile = inputFile.getValue();
File in(fopen(compressedFile.c_str(), "rb"));
if (in.get() == nullptr) {
log.error("Could not open ", compressedFile, " for reading");
return 1;
}
auto indexFile = indexArg.isSet() ? indexArg.getValue() :
inputFile.getValue() + ".zindex";
auto index = Index::load(log, move(in), indexFile.c_str(),
forceLoad.isSet());
auto queryIndex = queryIndexArg.isSet() ? queryIndexArg.getValue() : "default";
uint64_t before = 0u;
uint64_t after = 0u;
if (beforeArg.isSet()) before = beforeArg.getValue();
if (afterArg.isSet()) after = afterArg.getValue();
if (contextArg.isSet()) before = after = contextArg.getValue();
log.debug("Fetching context of ", before, " lines before and ", after,
" lines after");
PrintSink sink(lineNum.isSet());
PrintHandler ph(index, sink, (before || after) && !noSepArg.isSet(),
sepArg.getValue());
RangeFetcher rangeFetcher(ph, before, after);
std::cout << queryIndex << std::endl;
if (lineMode.isSet()) {
for (auto &q : query.getValue())
rangeFetcher(toInt(q));
} else {
index.queryIndexMulti(queryIndex, query.getValue(), rangeFetcher);
}
} catch (const exception &e) {
log.error(e.what());
}
return 0;
}
int main(int argc, const char *argv[]) {
try {
return Main(argc, argv);
} catch (const exception &e) {
cerr << e.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) Sjors Gielen, 2010
* See LICENSE for license.
*/
#include "database.h"
#include "config.h"
#include "utils.h"
#include <mongo.h>
#include <cerrno>
#include <cassert>
#include <sstream>
// #define DEBUG
#define M (mongo_sync_connection*)m_
#define PROPERTIES std::string(databaseName_ + ".properties").c_str()
/**
* @brief Constructor.
*/
Database::Database( const std::string &hostname, uint16_t port, const std::string &database, const std::string &username, const std::string &password )
: m_(0)
{
hostName_ = hostname;
port_ = port;
databaseName_ = database;
username_ = username;
password_ = password;
}
/**
* @brief Destructor.
*/
Database::~Database()
{
if(m_)
mongo_sync_disconnect(M);
}
/**
* @brief Returns the last error in the QSqlDatabase object.
*/
std::string Database::lastError() const
{
return lastError_;
}
bool Database::open()
{
#ifdef DEBUG
fprintf(stderr, "Initiating connection to Mongo daemon at %s:%d\n",
hostName_.c_str(), port_);
#endif
m_ = (void*)mongo_sync_connect(hostName_.c_str(), port_, TRUE);
if(!m_) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Connection error: %s\n", lastError_.c_str());
#endif
return false;
}
if(!mongo_sync_conn_set_auto_reconnect(M, TRUE)) {
lastError_ = strerror(errno);
mongo_sync_disconnect(M);
#ifdef DEBUG
fprintf(stderr, "Cannot set auto-reconnect: %s\n", lastError_.c_str());
#endif
return false;
}
#ifdef DEBUG
fprintf(stderr, "Building index on table %s...\n", PROPERTIES);
#endif
bson *index = bson_build(
BSON_TYPE_INT32, "network", 1,
BSON_TYPE_INT32, "receiver", 1,
BSON_TYPE_INT32, "sender", 1,
BSON_TYPE_NONE
);
bson_finish(index);
if(!mongo_sync_cmd_index_create(M, PROPERTIES, index, 0))
{
#ifdef DEBUG
fprintf(stderr, "Index create error: %s\n", strerror(errno));
#endif
lastError_ = strerror(errno);
bson_free(index);
return false;
}
bson_free(index);
return true;
}
/**
* @brief Retrieve all properties under a certain namespace.
*
* All properties whose names start with the given namespace name, then a
* single dot, and that match the given scope values, are returned from this
* method.
*
* This method guarantees that if it returns a certain key, property() will
* return the correct value of that key given that network, receiver and
* sender scope are the same.
*/
std::vector<std::string> Database::propertyKeys( const std::string &ns, const std::string &networkScope,
const std::string &receiverScope, const std::string &senderScope )
{
std::stringstream regexStr;
regexStr << "^\\Q" << ns << "\\E\\.";
std::string regex = regexStr.str();
bson *selector = bson_new();
bson_append_regex(selector, "variable", regex.c_str(), "");
if(networkScope.length() > 0) {
bson_append_string(selector, "network", networkScope.c_str(), -1);
if(receiverScope.length() > 0) {
bson_append_string(selector, "receiver", receiverScope.c_str(), -1);
if(senderScope.length() > 0) {
bson_append_string(selector, "sender", senderScope.c_str(), -1);
} else {
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "network");
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
bson_finish(selector);
mongo_packet *p = mongo_sync_cmd_query(M, PROPERTIES, 0, 0, 0, selector, NULL /* TODO: variable only? */);
bson_free(selector);
if(!p) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
return std::vector<std::string>();
}
mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, PROPERTIES, p);
if(!cursor) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
return std::vector<std::string>();
}
std::vector<std::string> res;
while(mongo_sync_cursor_next(cursor)) {
bson *result = mongo_sync_cursor_get_data(cursor);
if(!result) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
mongo_sync_cursor_free(cursor);
return res;
}
bson_cursor *c = bson_find(result, "variable");
const char *value;
if(!bson_cursor_get_string(c, &value)) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
mongo_sync_cursor_free(cursor);
bson_cursor_free(c);
return res;
}
value += ns.length() + 1;
res.push_back(value);
}
return res;
}
/**
* @brief Retrieve property from database.
*
* The most specific scope will be selected first, i.e. user-specific scope.
* If that yields no results, channel-specific scope will be returned, then
* network-specific scope, then global scope.
*
* Variable should be formatted using reverse-domain format, i.e. for the
* plugin MyFirstPlugin created by John Doe, to save a 'foo' variable one
* could use:
* <code>net.jondoe.myfirstplugin.foo</code>
*/
std::string Database::property( const std::string &variable,
const std::string &networkScope, const std::string &receiverScope,
const std::string &senderScope )
{
// variable, [networkScope, [receiverScope, [senderScope]]]
// (empty if not given)
// db.c.
// find() // for everything
// find({network:{$in: ['NETWORKNAME',null]}}) // for network scope
// find({network:{$in: ['NETWORKNAME',null]}, receiver:{$in: ['RECEIVER',null]}}) // for receiver scope
// find({network:..., receiver:..., sender:{$in: ['SENDER',null]}}) // for sender scope
// .sort({'a':-1,'b':-1,'c':-1}).limit(1)
// Reverse sort and limit(1) will make sure we only receive the most
// specific result. This works, as long as the assumption is true that
// no specific fields are set without their less specific fields also
// being set (i.e. receiver can't be empty if sender is non-empty).
bson *query = bson_build_full(
BSON_TYPE_DOCUMENT, "$orderby", TRUE,
bson_build(BSON_TYPE_INT32, "network", -1, BSON_TYPE_INT32, "receiver", -1, BSON_TYPE_INT32, "sender", -1, BSON_TYPE_NONE),
BSON_TYPE_NONE
);
/*
'$query':{
'variable':'foo',
'network':{'$in':['bla',null]},
'receiver':{'$in':['moo', null]},
}
*/
bson *selector = bson_new();
bson *network = 0, *receiver = 0, *sender = 0;
bson_append_string(selector, "variable", variable.c_str(), -1);
if(networkScope.length() > 0) {
network = bson_build_full(
BSON_TYPE_ARRAY, "$in", TRUE,
bson_build(BSON_TYPE_STRING, "1", networkScope.c_str(), -1,
BSON_TYPE_NULL, "2", BSON_TYPE_NONE),
BSON_TYPE_NONE );
bson_finish(network);
bson_append_document(selector, "network", network);
if(receiverScope.length() > 0) {
receiver = bson_build_full(
BSON_TYPE_ARRAY, "$in", TRUE,
bson_build(BSON_TYPE_STRING, "1", receiverScope.c_str(), -1,
BSON_TYPE_NULL, "2", BSON_TYPE_NONE),
BSON_TYPE_NONE );
bson_finish(receiver);
bson_append_document(selector, "receiver", receiver);
if(senderScope.length() > 0) {
sender = bson_build_full(
BSON_TYPE_ARRAY, "$in", TRUE,
bson_build(BSON_TYPE_STRING, "1", senderScope.c_str(), -1,
BSON_TYPE_NULL, "2", BSON_TYPE_NONE),
BSON_TYPE_NONE );
bson_finish(sender);
bson_append_document(selector, "sender", sender);
}
}
}
bson_finish(selector);
bson_append_document(query, "$query", selector);
bson_finish(query);
mongo_packet *p = mongo_sync_cmd_query(M, PROPERTIES, 0, 0, 1, query, NULL /* TODO: value only? */);
bson_free(query);
bson_free(selector);
if(network) bson_free(network);
if(receiver) bson_free(receiver);
if(sender) bson_free(sender);
if(!p) {
lastError_ = strerror(errno);
return std::string();
}
mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, PROPERTIES, p);
if(!cursor) {
lastError_ = strerror(errno);
return std::string();
}
if(!mongo_sync_cursor_next(cursor)) {
#ifdef DEBUG
fprintf(stderr, "Variable %s not found within given scope.\n", variable.c_str());
#endif
}
bson *result = mongo_sync_cursor_get_data(cursor);
if(!result) {
lastError_ = strerror(errno);
mongo_sync_cursor_free(cursor);
return std::string();
}
bson_cursor *c = bson_find(result, "value");
const char *value;
if(!bson_cursor_get_string(c, &value)) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
mongo_sync_cursor_free(cursor);
bson_cursor_free(c);
return std::string();
}
std::string res(value);
bson_free(result);
bson_cursor_free(c);
// only one result
assert(!mongo_sync_cursor_next(cursor));
mongo_sync_cursor_free(cursor);
return res;
}
void Database::setProperty( const std::string &variable,
const std::string &value, const std::string &networkScope,
const std::string &receiverScope, const std::string &senderScope )
{
/**
selector: {network:'foo',receiver:'bar',sender:null,variable:'bla.blob'}
object: {'$set':{ 'value': 'bla'}}
*/
bson *object = bson_build_full(
BSON_TYPE_DOCUMENT, "$set", TRUE,
bson_build(
BSON_TYPE_STRING, "value", value.c_str(), -1,
BSON_TYPE_NONE),
BSON_TYPE_NONE);
bson_finish(object);
bson *selector = bson_build(
BSON_TYPE_STRING, "variable", variable.c_str(), -1,
BSON_TYPE_NONE);
if(networkScope.length() > 0) {
bson_append_string(selector, "network", networkScope.c_str(), -1);
if(receiverScope.length() > 0) {
bson_append_string(selector, "receiver", receiverScope.c_str(), -1);
if(senderScope.length() > 0) {
bson_append_string(selector, "sender", senderScope.c_str(), -1);
} else {
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "network");
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
bson_finish(selector);
// if the value length is zero, run a delete instead
if(value.length() == 0) {
if(!mongo_sync_cmd_delete(M, PROPERTIES,
0, selector))
{
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Error: %s\n", lastError_.c_str());
#endif
}
} else if(!mongo_sync_cmd_update(M, PROPERTIES,
MONGO_WIRE_FLAG_UPDATE_UPSERT, selector, object))
{
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Error: %s\n", lastError_.c_str());
#endif
}
bson_free(object);
bson_free(selector);
}
<commit_msg>Add required header on other platforms<commit_after>/**
* Copyright (c) Sjors Gielen, 2010
* See LICENSE for license.
*/
#include "database.h"
#include "config.h"
#include "utils.h"
#include <mongo.h>
#include <cerrno>
#include <cassert>
#include <sstream>
#include <stdio.h>
// #define DEBUG
#define M (mongo_sync_connection*)m_
#define PROPERTIES std::string(databaseName_ + ".properties").c_str()
/**
* @brief Constructor.
*/
Database::Database( const std::string &hostname, uint16_t port, const std::string &database, const std::string &username, const std::string &password )
: m_(0)
{
hostName_ = hostname;
port_ = port;
databaseName_ = database;
username_ = username;
password_ = password;
}
/**
* @brief Destructor.
*/
Database::~Database()
{
if(m_)
mongo_sync_disconnect(M);
}
/**
* @brief Returns the last error in the QSqlDatabase object.
*/
std::string Database::lastError() const
{
return lastError_;
}
bool Database::open()
{
#ifdef DEBUG
fprintf(stderr, "Initiating connection to Mongo daemon at %s:%d\n",
hostName_.c_str(), port_);
#endif
m_ = (void*)mongo_sync_connect(hostName_.c_str(), port_, TRUE);
if(!m_) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Connection error: %s\n", lastError_.c_str());
#endif
return false;
}
if(!mongo_sync_conn_set_auto_reconnect(M, TRUE)) {
lastError_ = strerror(errno);
mongo_sync_disconnect(M);
#ifdef DEBUG
fprintf(stderr, "Cannot set auto-reconnect: %s\n", lastError_.c_str());
#endif
return false;
}
#ifdef DEBUG
fprintf(stderr, "Building index on table %s...\n", PROPERTIES);
#endif
bson *index = bson_build(
BSON_TYPE_INT32, "network", 1,
BSON_TYPE_INT32, "receiver", 1,
BSON_TYPE_INT32, "sender", 1,
BSON_TYPE_NONE
);
bson_finish(index);
if(!mongo_sync_cmd_index_create(M, PROPERTIES, index, 0))
{
#ifdef DEBUG
fprintf(stderr, "Index create error: %s\n", strerror(errno));
#endif
lastError_ = strerror(errno);
bson_free(index);
return false;
}
bson_free(index);
return true;
}
/**
* @brief Retrieve all properties under a certain namespace.
*
* All properties whose names start with the given namespace name, then a
* single dot, and that match the given scope values, are returned from this
* method.
*
* This method guarantees that if it returns a certain key, property() will
* return the correct value of that key given that network, receiver and
* sender scope are the same.
*/
std::vector<std::string> Database::propertyKeys( const std::string &ns, const std::string &networkScope,
const std::string &receiverScope, const std::string &senderScope )
{
std::stringstream regexStr;
regexStr << "^\\Q" << ns << "\\E\\.";
std::string regex = regexStr.str();
bson *selector = bson_new();
bson_append_regex(selector, "variable", regex.c_str(), "");
if(networkScope.length() > 0) {
bson_append_string(selector, "network", networkScope.c_str(), -1);
if(receiverScope.length() > 0) {
bson_append_string(selector, "receiver", receiverScope.c_str(), -1);
if(senderScope.length() > 0) {
bson_append_string(selector, "sender", senderScope.c_str(), -1);
} else {
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "network");
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
bson_finish(selector);
mongo_packet *p = mongo_sync_cmd_query(M, PROPERTIES, 0, 0, 0, selector, NULL /* TODO: variable only? */);
bson_free(selector);
if(!p) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
return std::vector<std::string>();
}
mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, PROPERTIES, p);
if(!cursor) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
return std::vector<std::string>();
}
std::vector<std::string> res;
while(mongo_sync_cursor_next(cursor)) {
bson *result = mongo_sync_cursor_get_data(cursor);
if(!result) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
mongo_sync_cursor_free(cursor);
return res;
}
bson_cursor *c = bson_find(result, "variable");
const char *value;
if(!bson_cursor_get_string(c, &value)) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
mongo_sync_cursor_free(cursor);
bson_cursor_free(c);
return res;
}
value += ns.length() + 1;
res.push_back(value);
}
return res;
}
/**
* @brief Retrieve property from database.
*
* The most specific scope will be selected first, i.e. user-specific scope.
* If that yields no results, channel-specific scope will be returned, then
* network-specific scope, then global scope.
*
* Variable should be formatted using reverse-domain format, i.e. for the
* plugin MyFirstPlugin created by John Doe, to save a 'foo' variable one
* could use:
* <code>net.jondoe.myfirstplugin.foo</code>
*/
std::string Database::property( const std::string &variable,
const std::string &networkScope, const std::string &receiverScope,
const std::string &senderScope )
{
// variable, [networkScope, [receiverScope, [senderScope]]]
// (empty if not given)
// db.c.
// find() // for everything
// find({network:{$in: ['NETWORKNAME',null]}}) // for network scope
// find({network:{$in: ['NETWORKNAME',null]}, receiver:{$in: ['RECEIVER',null]}}) // for receiver scope
// find({network:..., receiver:..., sender:{$in: ['SENDER',null]}}) // for sender scope
// .sort({'a':-1,'b':-1,'c':-1}).limit(1)
// Reverse sort and limit(1) will make sure we only receive the most
// specific result. This works, as long as the assumption is true that
// no specific fields are set without their less specific fields also
// being set (i.e. receiver can't be empty if sender is non-empty).
bson *query = bson_build_full(
BSON_TYPE_DOCUMENT, "$orderby", TRUE,
bson_build(BSON_TYPE_INT32, "network", -1, BSON_TYPE_INT32, "receiver", -1, BSON_TYPE_INT32, "sender", -1, BSON_TYPE_NONE),
BSON_TYPE_NONE
);
/*
'$query':{
'variable':'foo',
'network':{'$in':['bla',null]},
'receiver':{'$in':['moo', null]},
}
*/
bson *selector = bson_new();
bson *network = 0, *receiver = 0, *sender = 0;
bson_append_string(selector, "variable", variable.c_str(), -1);
if(networkScope.length() > 0) {
network = bson_build_full(
BSON_TYPE_ARRAY, "$in", TRUE,
bson_build(BSON_TYPE_STRING, "1", networkScope.c_str(), -1,
BSON_TYPE_NULL, "2", BSON_TYPE_NONE),
BSON_TYPE_NONE );
bson_finish(network);
bson_append_document(selector, "network", network);
if(receiverScope.length() > 0) {
receiver = bson_build_full(
BSON_TYPE_ARRAY, "$in", TRUE,
bson_build(BSON_TYPE_STRING, "1", receiverScope.c_str(), -1,
BSON_TYPE_NULL, "2", BSON_TYPE_NONE),
BSON_TYPE_NONE );
bson_finish(receiver);
bson_append_document(selector, "receiver", receiver);
if(senderScope.length() > 0) {
sender = bson_build_full(
BSON_TYPE_ARRAY, "$in", TRUE,
bson_build(BSON_TYPE_STRING, "1", senderScope.c_str(), -1,
BSON_TYPE_NULL, "2", BSON_TYPE_NONE),
BSON_TYPE_NONE );
bson_finish(sender);
bson_append_document(selector, "sender", sender);
}
}
}
bson_finish(selector);
bson_append_document(query, "$query", selector);
bson_finish(query);
mongo_packet *p = mongo_sync_cmd_query(M, PROPERTIES, 0, 0, 1, query, NULL /* TODO: value only? */);
bson_free(query);
bson_free(selector);
if(network) bson_free(network);
if(receiver) bson_free(receiver);
if(sender) bson_free(sender);
if(!p) {
lastError_ = strerror(errno);
return std::string();
}
mongo_sync_cursor *cursor = mongo_sync_cursor_new(M, PROPERTIES, p);
if(!cursor) {
lastError_ = strerror(errno);
return std::string();
}
if(!mongo_sync_cursor_next(cursor)) {
#ifdef DEBUG
fprintf(stderr, "Variable %s not found within given scope.\n", variable.c_str());
#endif
}
bson *result = mongo_sync_cursor_get_data(cursor);
if(!result) {
lastError_ = strerror(errno);
mongo_sync_cursor_free(cursor);
return std::string();
}
bson_cursor *c = bson_find(result, "value");
const char *value;
if(!bson_cursor_get_string(c, &value)) {
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Database error: %s\n", lastError_.c_str());
#endif
mongo_sync_cursor_free(cursor);
bson_cursor_free(c);
return std::string();
}
std::string res(value);
bson_free(result);
bson_cursor_free(c);
// only one result
assert(!mongo_sync_cursor_next(cursor));
mongo_sync_cursor_free(cursor);
return res;
}
void Database::setProperty( const std::string &variable,
const std::string &value, const std::string &networkScope,
const std::string &receiverScope, const std::string &senderScope )
{
/**
selector: {network:'foo',receiver:'bar',sender:null,variable:'bla.blob'}
object: {'$set':{ 'value': 'bla'}}
*/
bson *object = bson_build_full(
BSON_TYPE_DOCUMENT, "$set", TRUE,
bson_build(
BSON_TYPE_STRING, "value", value.c_str(), -1,
BSON_TYPE_NONE),
BSON_TYPE_NONE);
bson_finish(object);
bson *selector = bson_build(
BSON_TYPE_STRING, "variable", variable.c_str(), -1,
BSON_TYPE_NONE);
if(networkScope.length() > 0) {
bson_append_string(selector, "network", networkScope.c_str(), -1);
if(receiverScope.length() > 0) {
bson_append_string(selector, "receiver", receiverScope.c_str(), -1);
if(senderScope.length() > 0) {
bson_append_string(selector, "sender", senderScope.c_str(), -1);
} else {
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
} else {
bson_append_null(selector, "network");
bson_append_null(selector, "receiver");
bson_append_null(selector, "sender");
}
bson_finish(selector);
// if the value length is zero, run a delete instead
if(value.length() == 0) {
if(!mongo_sync_cmd_delete(M, PROPERTIES,
0, selector))
{
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Error: %s\n", lastError_.c_str());
#endif
}
} else if(!mongo_sync_cmd_update(M, PROPERTIES,
MONGO_WIRE_FLAG_UPDATE_UPSERT, selector, object))
{
lastError_ = strerror(errno);
#ifdef DEBUG
fprintf(stderr, "Error: %s\n", lastError_.c_str());
#endif
}
bson_free(object);
bson_free(selector);
}
<|endoftext|> |
<commit_before>#include "editview.h"
#include "ui_editview.h"
EditView::EditView(QWidget *parent, ObjectRect* rect, image_info_struct image_info, ObjectItem* item, int mode) :
QMainWindow(parent),
ui(new Ui::EditView)
{
ui->setupUi(this);
this->mode = mode;
this->item = item;
this->ref_rect = rect;
this->pano_parent = qobject_cast<PanoramaViewer *>(parent);
QStandardItemModel* model =
qobject_cast<QStandardItemModel*>(this->ui->typeList->model());
QModelIndex firstIndex = model->index(0, this->ui->typeList->modelColumn(),
this->ui->typeList->rootModelIndex());
QStandardItem* firstItem = model->itemFromIndex(firstIndex);
firstItem->setSelectable(false);
// Connect signal for labels refresh
connect(this, SIGNAL(refreshLabels()), parent, SLOT(refreshLabels_slot()));
// Remove margins
this->setContentsMargins(-5, -5, -5, -5);
//this->centralWidget()->layout()->setContentsMargins(50,50,50,50);
// Center window on screen
this->setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
this->size(),
qApp->desktop()->availableGeometry()
));
// Start window maximized
this->showMaximized();
// Create panorama viewer
this->pano = new PanoramaViewer(this, false);
// Set image settings
this->pano->image_info = image_info;
// Add panorama viewer to current window
this->ui->mainLayout->addWidget(this->pano);
// Configure panorama viewer
this->pano->setup(
this->size().width(), // Default width
this->size().height(), // Default height
pano_parent->scale_factor, // Image scale factor
pano_parent->zoom_min, // Minimum zoom
pano_parent->zoom_max, // Maximum zoom
100.0, // Default zoom level
pano_parent->threads_count // Number of threads
);
this->pano->setView( rect->proj_azimuth(), rect->proj_elevation() );
this->pano->setZoom( rect->proj_aperture() / (LG_PI / 180.0) );
this->pano->setMoveEnabled( false );
this->pano->setZoomEnabled( false );
this->pano->setCreateEnabled( false );
this->pano->setEditEnabled( false );
if (this->ref_rect->getAutomaticStatus() != "None")
{
this->ui->typeList->setEnabled( false );
this->ui->subTypeList->setEnabled( false );
this->ui->deleteButton->setEnabled( false );
}
// Set-up labels
this->ui->subClassLabel->setText("Sub classes: None");
switch(this->ref_rect->getType())
{
case ObjectType::None:
this->ui->classNameLabel->setText("Class name: None");
break;
case ObjectType::Face:
this->ui->classNameLabel->setText("Class name: Face");
break;
case ObjectType::NumberPlate:
this->ui->classNameLabel->setText("Class name: NumberPlate");
break;
case ObjectType::ToBlur:
this->ui->classNameLabel->setText("Class name: ToBlur");
this->ui->validCheckBox->setEnabled( false );
this->ui->blurCheckBox->setEnabled( false );
break;
}
switch(this->ref_rect->getSubType())
{
case ObjectSubType::None:
this->ui->subClassLabel->setText("Sub class name: None");
break;
case ObjectSubType::Front:
this->ui->subClassLabel->setText("Sub class name: Front");
break;
case ObjectSubType::Profile:
this->ui->subClassLabel->setText("Sub class name: Profile");
break;
case ObjectSubType::Back:
this->ui->subClassLabel->setText("Sub class name: Back");
break;
case ObjectSubType::Eyes:
this->ui->subClassLabel->setText("Sub class name: Eyes");
break;
}
this->ui->widthLabel->setText("Width: " + QString::number( (int) this->ref_rect->getSize().width() ));
this->ui->heightLabel->setText("Height: " + QString::number( (int) this->ref_rect->getSize().height() ));
this->ui->preFiltersLabel->setText("Pre-filter status: " + this->ref_rect->getAutomaticStatus());
this->ui->validCheckBox->setChecked( this->ref_rect->isValidated() );
this->ui->blurCheckBox->setChecked( this->ref_rect->isBlurred() );
switch(this->ref_rect->getType())
{
case ObjectType::None:
this->ui->typeList->setCurrentIndex( 0 );
break;
case ObjectType::Face:
this->ui->typeList->setCurrentIndex( 1 );
break;
case ObjectType::NumberPlate:
this->ui->typeList->setCurrentIndex( 2 );
break;
case ObjectType::ToBlur:
this->ui->typeList->setCurrentIndex( 3 );
break;
}
switch(this->ref_rect->getSubType())
{
case ObjectSubType::None:
this->ui->subTypeList->setCurrentIndex( 0 );
break;
case ObjectSubType::Front:
this->ui->subTypeList->setCurrentIndex( 1 );
break;
case ObjectSubType::Profile:
this->ui->subTypeList->setCurrentIndex( 2 );
break;
case ObjectSubType::Back:
this->ui->subTypeList->setCurrentIndex( 3 );
break;
case ObjectSubType::Eyes:
this->ui->subTypeList->setCurrentIndex( 4 );
break;
}
this->rect_copy = this->ref_rect->copy();
//this->rect_copy->setResizeEnabled( false );
this->rect_copy->mapTo(this->pano->dest_image_map.width(),
this->pano->dest_image_map.height(),
this->rect_copy->proj_azimuth(),
this->rect_copy->proj_elevation(),
this->rect_copy->proj_aperture());
this->pano->rect_list.append( this->rect_copy );
this->pano->scene->addItem( this->rect_copy );
}
EditView::~EditView()
{
delete ui;
}
void EditView::on_cancelButton_clicked()
{
this->close();
}
void EditView::on_deleteButton_clicked()
{
switch(this->mode)
{
case EditMode::Single:
this->item->remove( true );
emit refreshLabels();
this->close();
break;
case EditMode::Scene:
pano_parent->rect_list.removeOne( this->ref_rect );
delete this->ref_rect;
emit refreshLabels();
this->close();
break;
}
}
void EditView::mergeEditedRect(ObjectRect* destination)
{
switch(this->ui->typeList->currentIndex())
{
case 1:
destination->setType( ObjectType::Face );
break;
case 2:
destination->setType( ObjectType::NumberPlate );
break;
case 3:
destination->setType( ObjectType::ToBlur );
break;
}
switch(this->ui->subTypeList->currentIndex())
{
case 0:
destination->setSubType( ObjectSubType::None );
break;
case 1:
destination->setSubType( ObjectSubType::Front );
break;
case 2:
destination->setSubType( ObjectSubType::Profile );
break;
case 3:
destination->setSubType( ObjectSubType::Back );
break;
case 4:
destination->setSubType( ObjectSubType::Eyes );
break;
}
}
void EditView::mergeEditedItem(ObjectItem* destination)
{
switch(this->ui->typeList->currentIndex())
{
case 1:
destination->setType( ObjectType::Face );
break;
case 2:
destination->setType( ObjectType::NumberPlate );
break;
case 3:
destination->setType( ObjectType::ToBlur );
break;
}
switch(this->ui->subTypeList->currentIndex())
{
case 0:
destination->setSubType( ObjectSubType::None );
break;
case 1:
destination->setSubType( ObjectSubType::Front );
break;
case 2:
destination->setSubType( ObjectSubType::Profile );
break;
}
if(destination->type == ObjectType::ToBlur)
{
destination->setValidState( ObjectRectState::ToBlur );
} else {
destination->setValidState( this->ui->validCheckBox->checkState() ? ObjectRectState::Valid : ObjectRectState::Invalid );
}
destination->setManualStatus( this->ui->validCheckBox->checkState() ? "Valid" : "Invalid" );
destination->setBlurred( this->ui->blurCheckBox->checkState() );
}
void EditView::on_confirmButton_clicked()
{
switch(this->mode)
{
case EditMode::Single:
this->ref_rect->mergeWith( this->rect_copy );
this->mergeEditedItem( this->item );
this->item->setImage( this->pano_parent->cropObject( this->rect_copy ) );
break;
case EditMode::Scene:
foreach(ObjectRect* rect, this->pano_parent->rect_list)
{
if(rect->getId() == this->rect_copy->getId())
{
rect->mergeWith( this->rect_copy );
this->mergeEditedRect( rect );
break;
}
}
this->pano_parent->render();
break;
}
emit refreshLabels();
this->close();
}
void EditView::on_validCheckBox_clicked()
{
this->rect_copy->setObjectRectState( this->ui->validCheckBox->checkState() ? ObjectRectState::Valid : ObjectRectState::Invalid );
}
<commit_msg>Fixed Back/Eyes merging on Edit view<commit_after>#include "editview.h"
#include "ui_editview.h"
EditView::EditView(QWidget *parent, ObjectRect* rect, image_info_struct image_info, ObjectItem* item, int mode) :
QMainWindow(parent),
ui(new Ui::EditView)
{
ui->setupUi(this);
this->mode = mode;
this->item = item;
this->ref_rect = rect;
this->pano_parent = qobject_cast<PanoramaViewer *>(parent);
QStandardItemModel* model =
qobject_cast<QStandardItemModel*>(this->ui->typeList->model());
QModelIndex firstIndex = model->index(0, this->ui->typeList->modelColumn(),
this->ui->typeList->rootModelIndex());
QStandardItem* firstItem = model->itemFromIndex(firstIndex);
firstItem->setSelectable(false);
// Connect signal for labels refresh
connect(this, SIGNAL(refreshLabels()), parent, SLOT(refreshLabels_slot()));
// Remove margins
this->setContentsMargins(-5, -5, -5, -5);
//this->centralWidget()->layout()->setContentsMargins(50,50,50,50);
// Center window on screen
this->setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
this->size(),
qApp->desktop()->availableGeometry()
));
// Start window maximized
this->showMaximized();
// Create panorama viewer
this->pano = new PanoramaViewer(this, false);
// Set image settings
this->pano->image_info = image_info;
// Add panorama viewer to current window
this->ui->mainLayout->addWidget(this->pano);
// Configure panorama viewer
this->pano->setup(
this->size().width(), // Default width
this->size().height(), // Default height
pano_parent->scale_factor, // Image scale factor
pano_parent->zoom_min, // Minimum zoom
pano_parent->zoom_max, // Maximum zoom
100.0, // Default zoom level
pano_parent->threads_count // Number of threads
);
this->pano->setView( rect->proj_azimuth(), rect->proj_elevation() );
this->pano->setZoom( rect->proj_aperture() / (LG_PI / 180.0) );
this->pano->setMoveEnabled( false );
this->pano->setZoomEnabled( false );
this->pano->setCreateEnabled( false );
this->pano->setEditEnabled( false );
if (this->ref_rect->getAutomaticStatus() != "None")
{
this->ui->typeList->setEnabled( false );
this->ui->subTypeList->setEnabled( false );
this->ui->deleteButton->setEnabled( false );
}
// Set-up labels
this->ui->subClassLabel->setText("Sub classes: None");
switch(this->ref_rect->getType())
{
case ObjectType::None:
this->ui->classNameLabel->setText("Class name: None");
break;
case ObjectType::Face:
this->ui->classNameLabel->setText("Class name: Face");
break;
case ObjectType::NumberPlate:
this->ui->classNameLabel->setText("Class name: NumberPlate");
break;
case ObjectType::ToBlur:
this->ui->classNameLabel->setText("Class name: ToBlur");
this->ui->validCheckBox->setEnabled( false );
this->ui->blurCheckBox->setEnabled( false );
break;
}
switch(this->ref_rect->getSubType())
{
case ObjectSubType::None:
this->ui->subClassLabel->setText("Sub class name: None");
break;
case ObjectSubType::Front:
this->ui->subClassLabel->setText("Sub class name: Front");
break;
case ObjectSubType::Profile:
this->ui->subClassLabel->setText("Sub class name: Profile");
break;
case ObjectSubType::Back:
this->ui->subClassLabel->setText("Sub class name: Back");
break;
case ObjectSubType::Eyes:
this->ui->subClassLabel->setText("Sub class name: Eyes");
break;
}
this->ui->widthLabel->setText("Width: " + QString::number( (int) this->ref_rect->getSize().width() ));
this->ui->heightLabel->setText("Height: " + QString::number( (int) this->ref_rect->getSize().height() ));
this->ui->preFiltersLabel->setText("Pre-filter status: " + this->ref_rect->getAutomaticStatus());
this->ui->validCheckBox->setChecked( this->ref_rect->isValidated() );
this->ui->blurCheckBox->setChecked( this->ref_rect->isBlurred() );
switch(this->ref_rect->getType())
{
case ObjectType::None:
this->ui->typeList->setCurrentIndex( 0 );
break;
case ObjectType::Face:
this->ui->typeList->setCurrentIndex( 1 );
break;
case ObjectType::NumberPlate:
this->ui->typeList->setCurrentIndex( 2 );
break;
case ObjectType::ToBlur:
this->ui->typeList->setCurrentIndex( 3 );
break;
}
switch(this->ref_rect->getSubType())
{
case ObjectSubType::None:
this->ui->subTypeList->setCurrentIndex( 0 );
break;
case ObjectSubType::Front:
this->ui->subTypeList->setCurrentIndex( 1 );
break;
case ObjectSubType::Profile:
this->ui->subTypeList->setCurrentIndex( 2 );
break;
case ObjectSubType::Back:
this->ui->subTypeList->setCurrentIndex( 3 );
break;
case ObjectSubType::Eyes:
this->ui->subTypeList->setCurrentIndex( 4 );
break;
}
this->rect_copy = this->ref_rect->copy();
//this->rect_copy->setResizeEnabled( false );
this->rect_copy->mapTo(this->pano->dest_image_map.width(),
this->pano->dest_image_map.height(),
this->rect_copy->proj_azimuth(),
this->rect_copy->proj_elevation(),
this->rect_copy->proj_aperture());
this->pano->rect_list.append( this->rect_copy );
this->pano->scene->addItem( this->rect_copy );
}
EditView::~EditView()
{
delete ui;
}
void EditView::on_cancelButton_clicked()
{
this->close();
}
void EditView::on_deleteButton_clicked()
{
switch(this->mode)
{
case EditMode::Single:
this->item->remove( true );
emit refreshLabels();
this->close();
break;
case EditMode::Scene:
pano_parent->rect_list.removeOne( this->ref_rect );
delete this->ref_rect;
emit refreshLabels();
this->close();
break;
}
}
void EditView::mergeEditedRect(ObjectRect* destination)
{
switch(this->ui->typeList->currentIndex())
{
case 1:
destination->setType( ObjectType::Face );
break;
case 2:
destination->setType( ObjectType::NumberPlate );
break;
case 3:
destination->setType( ObjectType::ToBlur );
break;
}
switch(this->ui->subTypeList->currentIndex())
{
case 0:
destination->setSubType( ObjectSubType::None );
break;
case 1:
destination->setSubType( ObjectSubType::Front );
break;
case 2:
destination->setSubType( ObjectSubType::Profile );
break;
case 3:
destination->setSubType( ObjectSubType::Back );
break;
case 4:
destination->setSubType( ObjectSubType::Eyes );
break;
}
}
void EditView::mergeEditedItem(ObjectItem* destination)
{
switch(this->ui->typeList->currentIndex())
{
case 1:
destination->setType( ObjectType::Face );
break;
case 2:
destination->setType( ObjectType::NumberPlate );
break;
case 3:
destination->setType( ObjectType::ToBlur );
break;
}
switch(this->ui->subTypeList->currentIndex())
{
case 0:
destination->setSubType( ObjectSubType::None );
break;
case 1:
destination->setSubType( ObjectSubType::Front );
break;
case 2:
destination->setSubType( ObjectSubType::Profile );
break;
case 3:
destination->setSubType( ObjectSubType::Back );
break;
case 4:
destination->setSubType( ObjectSubType::Eyes );
break;
}
if(destination->type == ObjectType::ToBlur)
{
destination->setValidState( ObjectRectState::ToBlur );
} else {
destination->setValidState( this->ui->validCheckBox->checkState() ? ObjectRectState::Valid : ObjectRectState::Invalid );
}
destination->setManualStatus( this->ui->validCheckBox->checkState() ? "Valid" : "Invalid" );
destination->setBlurred( this->ui->blurCheckBox->checkState() );
}
void EditView::on_confirmButton_clicked()
{
switch(this->mode)
{
case EditMode::Single:
this->ref_rect->mergeWith( this->rect_copy );
this->mergeEditedItem( this->item );
this->item->setImage( this->pano_parent->cropObject( this->rect_copy ) );
break;
case EditMode::Scene:
foreach(ObjectRect* rect, this->pano_parent->rect_list)
{
if(rect->getId() == this->rect_copy->getId())
{
rect->mergeWith( this->rect_copy );
this->mergeEditedRect( rect );
break;
}
}
this->pano_parent->render();
break;
}
emit refreshLabels();
this->close();
}
void EditView::on_validCheckBox_clicked()
{
this->rect_copy->setObjectRectState( this->ui->validCheckBox->checkState() ? ObjectRectState::Valid : ObjectRectState::Invalid );
}
<|endoftext|> |
<commit_before>#include <array>
#include <cstdint>
#include <string>
#include <iostream>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "chip8.h"
#include "res/blip.h"
std::array<sf::Keyboard::Key, 16> layout{{
sf::Keyboard::Num1,
sf::Keyboard::Num2,
sf::Keyboard::Num3,
sf::Keyboard::Q,
sf::Keyboard::W,
sf::Keyboard::E,
sf::Keyboard::A,
sf::Keyboard::S,
sf::Keyboard::D,
sf::Keyboard::X,
sf::Keyboard::Y,
sf::Keyboard::C,
sf::Keyboard::Num4,
sf::Keyboard::R,
sf::Keyboard::F,
sf::Keyboard::V
}};
int main(int argc, char* argv[])
{
// initialize chip8 module
chip8 emu;
// parse arguments
std::string filename;
if (argc > 1) {
filename = argv[1];
if (!emu.loadGame(filename)) {
std::cerr << "File " << filename << " does not exist!" << std::endl;
return 1;
}
} else {
std::cerr << "No filename given!" << std::endl;
return 1;
}
// create window
sf::RenderWindow window(sf::VideoMode(640, 320), "YAC8E");
window.setFramerateLimit(120);
sf::RectangleShape shape(sf::Vector2<float>(10, 10));
shape.setFillColor(sf::Color::Green);
// set up audio
sf::SoundBuffer buffer;
if (!buffer.loadFromMemory(blip.data(), blip.size()))
std::cerr << "Could not load audio resources, continuing without!" << std::endl;
sf::Sound sound;
sound.setBuffer(buffer);
while (window.isOpen()) {
// poll events
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
// get keys
std::array<std::uint8_t, 16> keys;
for (int i = 0; i < 16; i++)
if (sf::Keyboard::isKeyPressed(layout[i]))
keys[i] = 1;
else
keys[i] = 0;
emu.setKeys(keys);
// do cpu cycles
emu.emulateCycle();
// draw
if (emu.drawFlag) {
emu.drawFlag = false;
window.clear(sf::Color(0,0,0,255));
for (int x = 0; x < 64; x++)
for (int y = 0; y < 32; y++)
if (emu.gfx[x + y*64]) {
shape.setPosition(x*10, y*10);
window.draw(shape);
}
}
window.display();
// audio
if(emu.beep)
sound.play();
}
return 0;
}<commit_msg>Fixed extra whitespace.<commit_after>#include <array>
#include <cstdint>
#include <string>
#include <iostream>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "chip8.h"
#include "res/blip.h"
std::array<sf::Keyboard::Key, 16> layout{{
sf::Keyboard::Num1,
sf::Keyboard::Num2,
sf::Keyboard::Num3,
sf::Keyboard::Q,
sf::Keyboard::W,
sf::Keyboard::E,
sf::Keyboard::A,
sf::Keyboard::S,
sf::Keyboard::D,
sf::Keyboard::X,
sf::Keyboard::Y,
sf::Keyboard::C,
sf::Keyboard::Num4,
sf::Keyboard::R,
sf::Keyboard::F,
sf::Keyboard::V
}};
int main(int argc, char* argv[])
{
// initialize chip8 module
chip8 emu;
// parse arguments
std::string filename;
if (argc > 1) {
filename = argv[1];
if (!emu.loadGame(filename)) {
std::cerr << "File " << filename << " does not exist!" << std::endl;
return 1;
}
} else {
std::cerr << "No filename given!" << std::endl;
return 1;
}
// create window
sf::RenderWindow window(sf::VideoMode(640, 320), "YAC8E");
window.setFramerateLimit(120);
sf::RectangleShape shape(sf::Vector2<float>(10, 10));
shape.setFillColor(sf::Color::Green);
// set up audio
sf::SoundBuffer buffer;
if (!buffer.loadFromMemory(blip.data(), blip.size()))
std::cerr << "Could not load audio resources, continuing without!" << std::endl;
sf::Sound sound;
sound.setBuffer(buffer);
while (window.isOpen()) {
// poll events
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
// get keys
std::array<std::uint8_t, 16> keys;
for (int i = 0; i < 16; i++)
if (sf::Keyboard::isKeyPressed(layout[i]))
keys[i] = 1;
else
keys[i] = 0;
emu.setKeys(keys);
// do cpu cycles
emu.emulateCycle();
// draw
if (emu.drawFlag) {
emu.drawFlag = false;
window.clear(sf::Color(0,0,0,255));
for (int x = 0; x < 64; x++)
for (int y = 0; y < 32; y++)
if (emu.gfx[x + y*64]) {
shape.setPosition(x*10, y*10);
window.draw(shape);
}
}
window.display();
// audio
if(emu.beep)
sound.play();
}
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <cassert>
#include <cmath>
#include "Matrix.hpp"
#include "maps.hpp"
class FourBit
{
// shorthand
using uchar = unsigned char;
private:
static constexpr uchar NONE_CHAR = '-';
uchar pack_(const uchar lhs, const uchar rhs)
{
assert(lhs < 16 and rhs < 16);
return (lhs << 4) | rhs;
}
static inline std::pair<uchar, uchar> unpack_(const uchar c)
{
static const uchar upper_mask = 0b11110000;
static const uchar lower_mask = 0b00001111;
return {(c & upper_mask) >> 4, c & lower_mask};
}
public:
FourBit()
: to_fourbit_(128, 128, 16)
{
static_assert(NT_MAP_SIZE == 16, "Weird NT map size, go adjust encoder code!");
// both chars are valid characters:
const auto map_size = static_cast<uchar>(NT_MAP_SIZE);
for (uchar i = 0; i < map_size; ++i) {
assert(NT_MAP[i] == std::toupper(NT_MAP[i]));
for (uchar j = 0; j < map_size; ++j) {
uchar packed_char = pack_(i,j);
// uppercase
auto row = NT_MAP[i];
auto col = NT_MAP[j];
to_fourbit_.at(row, col) = packed_char;
// lowercase
row = std::tolower(NT_MAP[i]);
to_fourbit_.at(row, col) = packed_char;
col = std::tolower(NT_MAP[j]);
to_fourbit_.at(row, col) = packed_char;
row = NT_MAP[i];
to_fourbit_.at(row, col) = packed_char;
}
}
// valid + padding
for (uchar i = 0; i < map_size; ++i) {
uchar packed_char = pack_(i,0);
// uppercase
auto row = NT_MAP[i];
auto col = NONE_CHAR;
to_fourbit_.at(row, col) = packed_char;
row = std::tolower(NT_MAP[i]);
to_fourbit_.at(row, col) = packed_char;
}
// make the reverse lookup
for (size_t i = 0; i < from_fourbit_.max_size() * 2; i+=2) {
auto pair = unpack_(i/2);
reinterpret_cast<uchar*>(from_fourbit_.data())[i] =
NT_MAP[pair.first];
reinterpret_cast<uchar*>(from_fourbit_.data())[i+1u] =
NT_MAP[pair.second];
}
}
~FourBit() = default;
inline size_t packed_size(const size_t size)
{
return std::ceil(size / 2.0);
}
// conversion functions
inline std::basic_string<char> to_fourbit(const std::string& s)
{
const size_t p_size = packed_size(s.size());
std::basic_string<char> res;
res.reserve(p_size);
size_t i = 0;
for (; i + 1 < s.size(); i += 2) {
res.push_back(to_fourbit_.at(s[i], s[i+1u]));
}
// original string size not divisible by 2: trailing padding
if (i < s.size()) {
res.push_back(to_fourbit_.at(s[i], NONE_CHAR));
}
return res;
}
std::string from_fourbit(const std::basic_string<char>& s, const size_t n)
{
// prepare the result string
std::string res;
res.resize(n);
// determine wether the packed string has padding
const bool padded = (s.size() < n);
// unpack
size_t i = 0;
for (; i < s.size() - 1u; ++i) {
reinterpret_cast<char16_t*>(&res[0])[i]
= from_fourbit_[static_cast<uchar>(s[i])];
}
// last element is special
auto char_pair = unpack_(static_cast<uchar>(s.back()));
res[i*2] = NT_MAP[char_pair.first];
if (not padded) {
res[i*2+1] = NT_MAP[char_pair.second];
} else {
assert(NT_MAP[char_pair.second] == NONE_CHAR);
}
assert(res.size() == n);
return res;
}
private:
Matrix<char> to_fourbit_;
std::array<char16_t, 256> from_fourbit_;
};
<commit_msg>fixed bug with decoder where padding was not detected correctly<commit_after>#pragma once
#include <algorithm>
#include <cassert>
#include <cmath>
#include "Matrix.hpp"
#include "maps.hpp"
class FourBit
{
// shorthand
using uchar = unsigned char;
private:
static constexpr uchar NONE_CHAR = '-';
uchar pack_(const uchar lhs, const uchar rhs)
{
assert(lhs < 16 and rhs < 16);
return (lhs << 4) | rhs;
}
static inline std::pair<uchar, uchar> unpack_(const uchar c)
{
static const uchar upper_mask = 0b11110000;
static const uchar lower_mask = 0b00001111;
return {(c & upper_mask) >> 4, c & lower_mask};
}
public:
FourBit()
: to_fourbit_(128, 128, 16)
{
static_assert(NT_MAP_SIZE == 16, "Weird NT map size, go adjust encoder code!");
// both chars are valid characters:
const auto map_size = static_cast<uchar>(NT_MAP_SIZE);
for (uchar i = 0; i < map_size; ++i) {
assert(NT_MAP[i] == std::toupper(NT_MAP[i]));
for (uchar j = 0; j < map_size; ++j) {
uchar packed_char = pack_(i,j);
// uppercase
auto row = NT_MAP[i];
auto col = NT_MAP[j];
to_fourbit_.at(row, col) = packed_char;
// lowercase
row = std::tolower(NT_MAP[i]);
to_fourbit_.at(row, col) = packed_char;
col = std::tolower(NT_MAP[j]);
to_fourbit_.at(row, col) = packed_char;
row = NT_MAP[i];
to_fourbit_.at(row, col) = packed_char;
}
}
// valid + padding
for (uchar i = 0; i < map_size; ++i) {
uchar packed_char = pack_(i,0);
// uppercase
auto row = NT_MAP[i];
auto col = NONE_CHAR;
to_fourbit_.at(row, col) = packed_char;
row = std::tolower(NT_MAP[i]);
to_fourbit_.at(row, col) = packed_char;
}
// make the reverse lookup
for (size_t i = 0; i < from_fourbit_.max_size() * 2; i+=2) {
auto pair = unpack_(i/2);
reinterpret_cast<uchar*>(from_fourbit_.data())[i] =
NT_MAP[pair.first];
reinterpret_cast<uchar*>(from_fourbit_.data())[i+1u] =
NT_MAP[pair.second];
}
}
~FourBit() = default;
inline size_t packed_size(const size_t size)
{
return std::ceil(size / 2.0);
}
// conversion functions
inline std::basic_string<char> to_fourbit(const std::string& s)
{
const size_t p_size = packed_size(s.size());
std::basic_string<char> res;
res.reserve(p_size);
size_t i = 0;
for (; i + 1 < s.size(); i += 2) {
res.push_back(to_fourbit_.at(s[i], s[i+1u]));
}
// original string size not divisible by 2: trailing padding
if (i < s.size()) {
res.push_back(to_fourbit_.at(s[i], NONE_CHAR));
}
return res;
}
std::string from_fourbit(const std::basic_string<char>& s, const size_t n)
{
// prepare the result string
std::string res;
res.resize(n);
// determine wether the packed string has padding
const bool padded = (s.size() * 2 < n);
// unpack
size_t i = 0;
for (; i < s.size() - 1u; ++i) {
reinterpret_cast<char16_t*>(&res[0])[i]
= from_fourbit_[static_cast<uchar>(s[i])];
}
// last element is special
auto char_pair = unpack_(static_cast<uchar>(s[i]));
res[i*2] = NT_MAP[char_pair.first];
if (not padded) {
res[i*2+1] = NT_MAP[char_pair.second];
} else {
assert(NT_MAP[char_pair.second] == NONE_CHAR);
}
assert(res.size() == n);
return res;
}
private:
Matrix<char> to_fourbit_;
std::array<char16_t, 256> from_fourbit_;
};
<|endoftext|> |
<commit_before>/*
* @file sa_test.cpp
* @auther Zhihao Lou
*
* Test file for SA (simulated annealing).
*/
#include <mlpack/core.hpp>
#include <mlpack/core/optimizers/sa/sa.hpp>
#include <mlpack/core/optimizers/sa/exponential_schedule.hpp>
#include <mlpack/core/optimizers/lbfgs/test_functions.hpp>
#include <mlpack/core/metrics/ip_metric.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
#include <mlpack/core/metrics/mahalanobis_distance.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::optimization;
using namespace mlpack::optimization::test;
using namespace mlpack::metric;
BOOST_AUTO_TEST_SUITE(SATest);
BOOST_AUTO_TEST_CASE(GeneralizedRosenbrockTest)
{
size_t dim = 50;
GeneralizedRosenbrockFunction f(dim);
ExponentialSchedule schedule(1e-5);
SA<GeneralizedRosenbrockFunction, ExponentialSchedule>
sa(f, schedule, 10000000, 1000.,1000, 100, 1e-9, 3, 20, 0.3, 0.3);
arma::mat coordinates = f.GetInitialPoint();
double result = sa.Optimize(coordinates);
BOOST_REQUIRE_SMALL(result, 1e-6);
for (size_t j = 0; j < dim; ++j)
BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 1e-2);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Add some more tests for simulated annealing, including a highly nonconvex function (the Rastrigin function).<commit_after>/*
* @file sa_test.cpp
* @auther Zhihao Lou
*
* Test file for SA (simulated annealing).
*/
#include <mlpack/core.hpp>
#include <mlpack/core/optimizers/sa/sa.hpp>
#include <mlpack/core/optimizers/sa/exponential_schedule.hpp>
#include <mlpack/core/optimizers/lbfgs/test_functions.hpp>
#include <mlpack/core/metrics/ip_metric.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
#include <mlpack/core/metrics/mahalanobis_distance.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::optimization;
using namespace mlpack::optimization::test;
using namespace mlpack::metric;
BOOST_AUTO_TEST_SUITE(SATest);
BOOST_AUTO_TEST_CASE(GeneralizedRosenbrockTest)
{
size_t dim = 50;
GeneralizedRosenbrockFunction f(dim);
ExponentialSchedule schedule(1e-5);
SA<GeneralizedRosenbrockFunction, ExponentialSchedule>
sa(f, schedule, 10000000, 1000., 1000, 100, 1e-9, 3, 20, 0.3, 0.3);
arma::mat coordinates = f.GetInitialPoint();
const double result = sa.Optimize(coordinates);
BOOST_REQUIRE_SMALL(result, 1e-6);
for (size_t j = 0; j < dim; ++j)
BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 1e-2);
}
// The Rosenbrock function is a simple function to optimize.
BOOST_AUTO_TEST_CASE(RosenbrockTest)
{
RosenbrockFunction f;
ExponentialSchedule schedule(1e-5);
SA<RosenbrockFunction> //sa(f, schedule); // All default parameters.
sa(f, schedule, 10000000, 1000., 1000, 100, 1e-11, 3, 20, 0.3, 0.3);
arma::mat coordinates = f.GetInitialPoint();
const double result = sa.Optimize(coordinates);
BOOST_REQUIRE_SMALL(result, 1e-6);
BOOST_REQUIRE_CLOSE(coordinates[0], 1.0, 1e-3);
BOOST_REQUIRE_CLOSE(coordinates[1], 1.0, 1e-3);
}
/**
* The Rastigrin function, a (not very) simple nonconvex function. It is
* defined by
*
* f(x) = 10n + \sum_{i = 1}^{n} (x_i^2 - 10 cos(2 \pi x_i)).
*
* It has very many local minima, so finding the true global minimum is
* difficult. The function is two-dimensional, and has minimum 0 where
* x = [0 0]. We are only using it for simulated annealing, so there is no need
* to implement the gradient.
*/
class RastrigrinFunction
{
public:
double Evaluate(const arma::mat& coordinates) const
{
double objective = 20; // 10 * n, n = 2.
objective += std::pow(coordinates[0], 2.0) -
10 * std::cos(2 * M_PI * coordinates[0]);
objective += std::pow(coordinates[1], 2.0) -
10 * std::cos(2 * M_PI * coordinates[1]);
return objective;
}
arma::mat GetInitialPoint() const
{
return arma::mat("-3 -3");
}
};
BOOST_AUTO_TEST_CASE(RastrigrinFunctionTest)
{
// Simulated annealing isn't guaranteed to converge (except in very specific
// situations). If this works 1 of 3 times, I'm fine with that. All I want
// to know is that this implementation will escape from local minima.
size_t successes = 0;
for (size_t trial = 0; trial < 3; ++trial)
{
RastrigrinFunction f;
ExponentialSchedule schedule(3e-6);
SA<RastrigrinFunction> //sa(f, schedule);
sa(f, schedule, 20000000, 100, 50, 1000, 1e-9, 2, 0.2, 0.01, 0.1);
arma::mat coordinates = f.GetInitialPoint();
const double result = sa.Optimize(coordinates);
if ((std::abs(result) < 1e-3) &&
(std::abs(coordinates[0]) < 1e-3) &&
(std::abs(coordinates[1]) < 1e-3))
++successes;
}
BOOST_REQUIRE_GE(successes, 1);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>#include "Marshal.hpp"
#include "node/node_helpers.hpp"
using namespace v8;
Marshal::NativeResult Marshal::Native(int value)
{
HandleScope scope;
return scope.Close(Int32::New(value));
}
Marshal::NativeResult Marshal::Native(size_t value)
{
HandleScope scope;
return scope.Close(Uint32::New(value));
}
Marshal::NativeResult Marshal::Native(float value)
{
HandleScope scope;
return scope.Close(Number::New(value));
}
Marshal::NativeResult Marshal::Native(double value)
{
HandleScope scope;
return scope.Close(Number::New(value));
}
Marshal::NativeResult Marshal::Native(const char * value)
{
HandleScope scope;
return scope.Close(String::New(value));
}
Marshal::NativeResult Marshal::Native(const std::string& value)
{
HandleScope scope;
return scope.Close(String::New(value.c_str(), value.size()));
}
//////////////////////////////////////////////////////////////////////////
// OpenCV Types
Marshal::NativeResult Marshal::Native(const cv::Size& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("width"), Native(value.width));
structure->Set(String::NewSymbol("height"), Native(value.height));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const cv::Point& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("x"), Native(value.x));
structure->Set(String::NewSymbol("y"), Native(value.y));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const cv::Point2f& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("x"), Native(value.x));
structure->Set(String::NewSymbol("y"), Native(value.y));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const cv::Scalar& value)
{
HandleScope scope;
Handle<Array> result = Array::New(4);
for (size_t i = 0; i < 4; i++)
result->Set(i, Native(value.val[i]));
return scope.Close(result);
}
Marshal::NativeResult Marshal::Native(const cv::Mat& value)
{
HandleScope scope;
return scope.Close(Native(toDataUri(value, kImageTypePng)));
}
//////////////////////////////////////////////////////////////////////////
// CloudCV Structures
Marshal::NativeResult Marshal::Native(const Distribution& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("min"), Native(value.min));
structure->Set(String::NewSymbol("max"), Native(value.max));
structure->Set(String::NewSymbol("average"), Native(value.average));
structure->Set(String::NewSymbol("standardDeviation"), Native(value.standardDeviation));
structure->Set(String::NewSymbol("entropy"), Native(value.entropy));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const rgb8u_color_t& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("min"), Native(static_cast<int>(value.r)));
structure->Set(String::NewSymbol("max"), Native(static_cast<int>(value.g)));
structure->Set(String::NewSymbol("average"), Native(static_cast<int>(value.b)));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const RGBDistribution& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("r"), Native(value.r));
structure->Set(String::NewSymbol("g"), Native(value.g));
structure->Set(String::NewSymbol("b"), Native(value.b));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const AnalyzeResult& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("common"), Native(value.common));
structure->Set(String::NewSymbol("grayscale"), Native(value.grayscale));
structure->Set(String::NewSymbol("color"), Native(value.color));
structure->Set(String::NewSymbol("edges"), Native(value.edges));
structure->Set(String::NewSymbol("profiling"), Native(value.profiling));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const ImageInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const DominantColor& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("color"), Native(value.color));
structure->Set(String::NewSymbol("error"), Native(value.error));
structure->Set(String::NewSymbol("interclassVariance"), Native(value.interclassVariance));
structure->Set(String::NewSymbol("totalPixels"), Native(value.totalPixels));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const IntensityInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("intensity"), Native(value.intensity));
structure->Set(String::NewSymbol("rmsContrast"), Native(value.rmsContrast));
structure->Set(String::NewSymbol("histogramImage"), Native(value.histogramImage));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const ColorsInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("colorDeviation"), Native(value.colorDeviation));
structure->Set(String::NewSymbol("uniqieColors"), Native(value.uniqieColors));
structure->Set(String::NewSymbol("histogramImage"), Native(value.reducedColors));
structure->Set(String::NewSymbol("intensity"), Native(value.dominantColors));
structure->Set(String::NewSymbol("rmsContrast"), Native(value.dominantColorsImage));
structure->Set(String::NewSymbol("histogramImage"), Native(value.histogramImage));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const MorphologicInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("cannyImage"), Native(value.cannyImage));
structure->Set(String::NewSymbol("cannyLowerThreshold"), Native(value.cannyLowerThreshold));
structure->Set(String::NewSymbol("cannyUpperThreshold"), Native(value.cannyUpperThreshold));
return scope.Close(structure);
}<commit_msg>Add missing structures for marshaling analyze result data<commit_after>#include "Marshal.hpp"
#include "node/node_helpers.hpp"
using namespace v8;
Marshal::NativeResult Marshal::Native(int value)
{
HandleScope scope;
return scope.Close(Int32::New(value));
}
Marshal::NativeResult Marshal::Native(size_t value)
{
HandleScope scope;
return scope.Close(Uint32::New(value));
}
Marshal::NativeResult Marshal::Native(float value)
{
HandleScope scope;
return scope.Close(Number::New(value));
}
Marshal::NativeResult Marshal::Native(double value)
{
HandleScope scope;
return scope.Close(Number::New(value));
}
Marshal::NativeResult Marshal::Native(const char * value)
{
HandleScope scope;
return scope.Close(String::New(value));
}
Marshal::NativeResult Marshal::Native(const std::string& value)
{
HandleScope scope;
return scope.Close(String::New(value.c_str(), value.size()));
}
//////////////////////////////////////////////////////////////////////////
// OpenCV Types
Marshal::NativeResult Marshal::Native(const cv::Size& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("width"), Native(value.width));
structure->Set(String::NewSymbol("height"), Native(value.height));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const cv::Point& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("x"), Native(value.x));
structure->Set(String::NewSymbol("y"), Native(value.y));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const cv::Point2f& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("x"), Native(value.x));
structure->Set(String::NewSymbol("y"), Native(value.y));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const cv::Scalar& value)
{
HandleScope scope;
Handle<Array> result = Array::New(4);
for (size_t i = 0; i < 4; i++)
result->Set(i, Native(value.val[i]));
return scope.Close(result);
}
Marshal::NativeResult Marshal::Native(const cv::Mat& value)
{
HandleScope scope;
return scope.Close(Native(toDataUri(value, kImageTypePng)));
}
//////////////////////////////////////////////////////////////////////////
// CloudCV Structures
Marshal::NativeResult Marshal::Native(const Distribution& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("min"), Native(value.min));
structure->Set(String::NewSymbol("max"), Native(value.max));
structure->Set(String::NewSymbol("average"), Native(value.average));
structure->Set(String::NewSymbol("standardDeviation"), Native(value.standardDeviation));
structure->Set(String::NewSymbol("entropy"), Native(value.entropy));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const rgb8u_color_t& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("min"), Native(static_cast<int>(value.r)));
structure->Set(String::NewSymbol("max"), Native(static_cast<int>(value.g)));
structure->Set(String::NewSymbol("average"), Native(static_cast<int>(value.b)));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const RGBDistribution& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("r"), Native(value.r));
structure->Set(String::NewSymbol("g"), Native(value.g));
structure->Set(String::NewSymbol("b"), Native(value.b));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const AnalyzeResult& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("common"), Native(value.common));
structure->Set(String::NewSymbol("grayscale"), Native(value.grayscale));
structure->Set(String::NewSymbol("color"), Native(value.color));
structure->Set(String::NewSymbol("edges"), Native(value.edges));
structure->Set(String::NewSymbol("profiling"), Native(value.profiling));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const ImageInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("grayscaleImage"), Native(value.grayscaleImage));
structure->Set(String::NewSymbol("frameSize"), Native(value.frameSize));
structure->Set(String::NewSymbol("aspectRatio"), Native(value.aspectRatio));
structure->Set(String::NewSymbol("hasColor"), Native(value.hasColor));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const DominantColor& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("color"), Native(value.color));
structure->Set(String::NewSymbol("error"), Native(value.error));
structure->Set(String::NewSymbol("interclassVariance"), Native(value.interclassVariance));
structure->Set(String::NewSymbol("totalPixels"), Native(value.totalPixels));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const IntensityInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("intensity"), Native(value.intensity));
structure->Set(String::NewSymbol("rmsContrast"), Native(value.rmsContrast));
structure->Set(String::NewSymbol("histogramImage"), Native(value.histogramImage));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const ColorsInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("colorDeviation"), Native(value.colorDeviation));
structure->Set(String::NewSymbol("uniqieColors"), Native(value.uniqieColors));
structure->Set(String::NewSymbol("reducedColors"), Native(value.reducedColors));
structure->Set(String::NewSymbol("dominantColors"), Native(value.dominantColors));
structure->Set(String::NewSymbol("dominantColorsImage"), Native(value.dominantColorsImage));
structure->Set(String::NewSymbol("histogramImage"), Native(value.histogramImage));
return scope.Close(structure);
}
Marshal::NativeResult Marshal::Native(const MorphologicInformation& value)
{
HandleScope scope;
Local<Object> structure = Object::New();
structure->Set(String::NewSymbol("cannyImage"), Native(value.cannyImage));
structure->Set(String::NewSymbol("cannyLowerThreshold"), Native(value.cannyLowerThreshold));
structure->Set(String::NewSymbol("cannyUpperThreshold"), Native(value.cannyUpperThreshold));
return scope.Close(structure);
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
void throw_exception(const char* thrower)
{
DWORD err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
libtorrent::wchar_utf8(wbuffer, tmp_utf8);
char const* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(safe_convert(file_name));
HANDLE new_handle = CreateFile(
wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
utf8_native(file_name).c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes >= 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>removed incorrect assert<commit_after>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include <sstream>
#include <windows.h>
namespace
{
// must be used to not leak memory in case something would throw
class auto_localfree
{
public:
auto_localfree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_localfree()
{
if (m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
void throw_exception(const char* thrower)
{
DWORD err = GetLastError();
#ifdef UNICODE
wchar_t *wbuffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
auto_localfree auto_free(wbuffer);
std::string tmp_utf8;
libtorrent::wchar_utf8(wbuffer, tmp_utf8);
char const* buffer = tmp_utf8.c_str();
#else
char* buffer = 0;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_ALLOCATE_BUFFER
, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_localfree auto_free(buffer);
#endif
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
#ifdef UNICODE
std::wstring wfile_name(safe_convert(file_name));
HANDLE new_handle = CreateFile(
wfile_name.c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#else
HANDLE new_handle = CreateFile(
utf8_native(file_name).c_str()
, access_mask
, FILE_SHARE_READ
, 0
, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
#endif
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
throw_exception(file_name);
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, 0))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes >= 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, 0))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0 || from_where != seek_begin);
assert(pos <= 0 || from_where != seek_end);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
assert(p.is_complete());
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/file.hpp"
#include <sstream>
#include <windows.h>
#define DWORD_MAX 0xffffffffu
namespace
{
void throw_exception(const char* thrower)
{
char buffer[1024];
int err = GetLastError();
// TODO: can this be done in an exception safe AND
// buffer overrun-safe way?
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, err, 0, buffer, 0, 0);
std::stringstream s;
s << thrower << ": " << buffer;
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
HANDLE new_handle = CreateFile(
file_name
, access_mask
, FILE_SHARE_READ
, NULL
, OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL);
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
s << "couldn't open file '" << file_name << "'";
throw file_error(s.str());
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, NULL))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, NULL))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>*** empty log message ***<commit_after>/*
Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/file.hpp"
#include <sstream>
#include <windows.h>
#define DWORD_MAX 0xffffffffu
namespace
{
// must be used to not leak memory in case something would throw
class auto_LocalFree
{
public:
auto_LocalFree(HLOCAL memory)
: m_memory(memory)
{
}
~auto_LocalFree()
{
if(m_memory)
LocalFree(m_memory);
}
private:
HLOCAL m_memory;
};
void throw_exception(const char* thrower)
{
char *buffer=0;
int err = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, err, 0, (LPSTR)&buffer, 0, 0);
auto_LocalFree auto_free(buffer); // needed for exception safety
std::stringstream s;
s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");
throw libtorrent::file_error(s.str());
}
}
namespace libtorrent
{
struct file::impl : boost::noncopyable
{
enum open_flags
{
read_flag = 1,
write_flag = 2
};
enum seek_mode
{
seek_begin = FILE_BEGIN,
seek_from_here = FILE_CURRENT,
seek_end = FILE_END
};
impl()
{
m_file_handle = INVALID_HANDLE_VALUE;
}
void open(const char *file_name, open_flags flags)
{
assert(file_name);
assert(flags & (read_flag | write_flag));
DWORD access_mask = 0;
if (flags & read_flag)
access_mask |= GENERIC_READ;
if (flags & write_flag)
access_mask |= GENERIC_WRITE;
assert(access_mask & (GENERIC_READ | GENERIC_WRITE));
HANDLE new_handle = CreateFile(
file_name
, access_mask
, FILE_SHARE_READ
, NULL
, OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL);
if (new_handle == INVALID_HANDLE_VALUE)
{
std::stringstream s;
s << "couldn't open file '" << file_name << "'";
throw file_error(s.str());
}
// will only close old file if the open succeeded
close();
m_file_handle = new_handle;
}
void close()
{
if (m_file_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
}
}
~impl()
{
close();
}
size_type write(const char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_written = 0;
if (num_bytes != 0)
{
if (FALSE == WriteFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_written
, NULL))
{
throw_exception("file::write");
}
}
return bytes_written;
}
size_type read(char* buffer, size_type num_bytes)
{
assert(buffer);
assert(num_bytes > 0);
assert((DWORD)num_bytes == num_bytes);
DWORD bytes_read = 0;
if (num_bytes != 0)
{
if (FALSE == ReadFile(
m_file_handle
, buffer
, (DWORD)num_bytes
, &bytes_read
, NULL))
{
throw_exception("file::read");
}
}
return bytes_read;
}
void seek(size_type pos, seek_mode from_where)
{
assert(pos >= 0);
LARGE_INTEGER offs;
offs.QuadPart = pos;
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, from_where))
{
throw_exception("file::seek");
}
}
size_type tell()
{
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (FALSE == SetFilePointerEx(
m_file_handle
, offs
, &offs
, FILE_CURRENT))
{
throw_exception("file::tell");
}
size_type pos=offs.QuadPart;
assert(pos>=0);
return pos;
}
/*
size_type size()
{
LARGE_INTEGER s;
if (FALSE == GetFileSizeEx(m_file_handle, &s))
{
throw_exception("file::size");
}
size_type size = s.QuadPart;
assert(size >= 0);
return size;
}
*/
private:
HANDLE m_file_handle;
};
}
namespace libtorrent
{
const file::seek_mode file::begin(file::impl::seek_begin);
const file::seek_mode file::end(file::impl::seek_end);
const file::open_mode file::in(file::impl::read_flag);
const file::open_mode file::out(file::impl::write_flag);
file::file()
: m_impl(new libtorrent::file::impl())
{
}
file::file(boost::filesystem::path const& p, open_mode m)
: m_impl(new libtorrent::file::impl())
{
open(p,m);
}
file::~file()
{
}
void file::open(boost::filesystem::path const& p, open_mode m)
{
m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buffer, size_type num_bytes)
{
return m_impl->write(buffer, num_bytes);
}
size_type file::read(char* buffer, size_type num_bytes)
{
return m_impl->read(buffer, num_bytes);
}
void file::seek(size_type pos, seek_mode m)
{
m_impl->seek(pos,impl::seek_mode(m.m_val));
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "SkBitmapProcState_opts_SSE2.h"
#include "SkBlitRow_opts_SSE2.h"
#include "SkUtils_opts_SSE2.h"
#include "SkUtils.h"
/* This file must *not* be compiled with -msse or -msse2, otherwise
gcc may generate sse2 even for scalar ops (and thus give an invalid
instruction on Pentium3 on the code below). Only files named *_SSE2.cpp
in this directory should be compiled with -msse2. */
#if defined(__x86_64__) || defined(_WIN64)
/* All x86_64 machines have SSE2, so don't even bother checking. */
static inline bool hasSSE2() {
return true;
}
#else
#ifdef _MSC_VER
static inline void getcpuid(int info_type, int info[4]) {
__asm {
mov eax, [info_type]
cpuid
mov edi, [info]
mov [edi], eax
mov [edi+4], ebx
mov [edi+8], ecx
mov [edi+12], edx
}
}
#else
static inline void getcpuid(int info_type, int info[4]) {
// We save and restore ebx, so this code can be compatible with -fPIC
asm volatile (
"pushl %%ebx \n\t"
"cpuid \n\t"
"movl %%ebx, %1 \n\t"
"popl %%ebx \n\t"
: "=a"(info[0]), "=r"(info[1]), "=c"(info[2]), "=d"(info[3])
: "a"(info_type)
:
);
}
#endif
static inline bool hasSSE2() {
int cpu_info[4] = { 0 };
getcpuid(1, cpu_info);
return (cpu_info[3] & (1<<26)) != 0;
}
#endif
void SkBitmapProcState::platformProcs() {
if (hasSSE2()) {
if (fSampleProc32 == S32_opaque_D32_filter_DX) {
fSampleProc32 = S32_opaque_D32_filter_DX_SSE2;
} else if (fSampleProc32 == S32_alpha_D32_filter_DX) {
fSampleProc32 = S32_alpha_D32_filter_DX_SSE2;
}
}
}
static SkBlitRow::Proc32 platform_32_procs[] = {
NULL, // S32_Opaque,
S32_Blend_BlitRow32_SSE2, // S32_Blend,
S32A_Opaque_BlitRow32_SSE2, // S32A_Opaque
S32A_Blend_BlitRow32_SSE2, // S32A_Blend,
};
SkBlitRow::Proc SkBlitRow::PlatformProcs4444(unsigned flags) {
return NULL;
}
SkBlitRow::Proc SkBlitRow::PlatformProcs565(unsigned flags) {
return NULL;
}
SkBlitRow::Proc32 SkBlitRow::PlatformProcs32(unsigned flags) {
if (hasSSE2()) {
return platform_32_procs[flags];
} else {
return NULL;
}
}
SkMemset16Proc SkMemset16GetPlatformProc() {
if (hasSSE2()) {
return sk_memset16_SSE2;
} else {
return NULL;
}
}
SkMemset32Proc SkMemset32GetPlatformProc() {
if (hasSSE2()) {
return sk_memset32_SSE2;
} else {
return NULL;
}
}
<commit_msg>http://codereview.appspot.com/1706045/show<commit_after>/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "SkBitmapProcState_opts_SSE2.h"
#include "SkBlitRow_opts_SSE2.h"
#include "SkUtils_opts_SSE2.h"
#include "SkUtils.h"
/* This file must *not* be compiled with -msse or -msse2, otherwise
gcc may generate sse2 even for scalar ops (and thus give an invalid
instruction on Pentium3 on the code below). Only files named *_SSE2.cpp
in this directory should be compiled with -msse2. */
#if defined(__x86_64__) || defined(_WIN64)
/* All x86_64 machines have SSE2, so don't even bother checking. */
static inline bool hasSSE2() {
return true;
}
#else
#ifdef _MSC_VER
static inline void getcpuid(int info_type, int info[4]) {
__asm {
mov eax, [info_type]
cpuid
mov edi, [info]
mov [edi], eax
mov [edi+4], ebx
mov [edi+8], ecx
mov [edi+12], edx
}
}
#else
static inline void getcpuid(int info_type, int info[4]) {
// We save and restore ebx, so this code can be compatible with -fPIC
asm volatile (
"pushl %%ebx \n\t"
"cpuid \n\t"
"movl %%ebx, %1 \n\t"
"popl %%ebx \n\t"
: "=a"(info[0]), "=r"(info[1]), "=c"(info[2]), "=d"(info[3])
: "a"(info_type)
);
}
#endif
static inline bool hasSSE2() {
int cpu_info[4] = { 0 };
getcpuid(1, cpu_info);
return (cpu_info[3] & (1<<26)) != 0;
}
#endif
void SkBitmapProcState::platformProcs() {
if (hasSSE2()) {
if (fSampleProc32 == S32_opaque_D32_filter_DX) {
fSampleProc32 = S32_opaque_D32_filter_DX_SSE2;
} else if (fSampleProc32 == S32_alpha_D32_filter_DX) {
fSampleProc32 = S32_alpha_D32_filter_DX_SSE2;
}
}
}
static SkBlitRow::Proc32 platform_32_procs[] = {
NULL, // S32_Opaque,
S32_Blend_BlitRow32_SSE2, // S32_Blend,
S32A_Opaque_BlitRow32_SSE2, // S32A_Opaque
S32A_Blend_BlitRow32_SSE2, // S32A_Blend,
};
SkBlitRow::Proc SkBlitRow::PlatformProcs4444(unsigned flags) {
return NULL;
}
SkBlitRow::Proc SkBlitRow::PlatformProcs565(unsigned flags) {
return NULL;
}
SkBlitRow::Proc32 SkBlitRow::PlatformProcs32(unsigned flags) {
if (hasSSE2()) {
return platform_32_procs[flags];
} else {
return NULL;
}
}
SkMemset16Proc SkMemset16GetPlatformProc() {
if (hasSSE2()) {
return sk_memset16_SSE2;
} else {
return NULL;
}
}
SkMemset32Proc SkMemset32GetPlatformProc() {
if (hasSSE2()) {
return sk_memset32_SSE2;
} else {
return NULL;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcState_opts_SSE2.h"
#include "SkBitmapProcState_opts_SSSE3.h"
#include "SkBlitMask.h"
#include "SkBlitRect.h"
#include "SkBlitRow.h"
#include "SkBlitRect_opts_SSE2.h"
#include "SkBlitRow_opts_SSE2.h"
#include "SkUtils_opts_SSE2.h"
#include "SkUtils.h"
/* This file must *not* be compiled with -msse or -msse2, otherwise
gcc may generate sse2 even for scalar ops (and thus give an invalid
instruction on Pentium3 on the code below). Only files named *_SSE2.cpp
in this directory should be compiled with -msse2. */
#ifdef _MSC_VER
static inline void getcpuid(int info_type, int info[4]) {
__asm {
mov eax, [info_type]
cpuid
mov edi, [info]
mov [edi], eax
mov [edi+4], ebx
mov [edi+8], ecx
mov [edi+12], edx
}
}
#else
#if defined(__x86_64__)
static inline void getcpuid(int info_type, int info[4]) {
asm volatile (
"cpuid \n\t"
: "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3])
: "a"(info_type)
);
}
#else
static inline void getcpuid(int info_type, int info[4]) {
// We save and restore ebx, so this code can be compatible with -fPIC
asm volatile (
"pushl %%ebx \n\t"
"cpuid \n\t"
"movl %%ebx, %1 \n\t"
"popl %%ebx \n\t"
: "=a"(info[0]), "=r"(info[1]), "=c"(info[2]), "=d"(info[3])
: "a"(info_type)
);
}
#endif
#endif
#if defined(__x86_64__) || defined(_WIN64)
/* All x86_64 machines have SSE2, so don't even bother checking. */
static inline bool hasSSE2() {
return true;
}
#else
static inline bool hasSSE2() {
int cpu_info[4] = { 0 };
getcpuid(1, cpu_info);
return (cpu_info[3] & (1<<26)) != 0;
}
#endif
static inline bool hasSSSE3() {
int cpu_info[4] = { 0 };
getcpuid(1, cpu_info);
return (cpu_info[2] & 0x200) != 0;
}
static bool cachedHasSSE2() {
static bool gHasSSE2 = hasSSE2();
return gHasSSE2;
}
static bool cachedHasSSSE3() {
static bool gHasSSSE3 = hasSSSE3();
return gHasSSSE3;
}
void SkBitmapProcState::platformProcs() {
if (cachedHasSSSE3()) {
if (fSampleProc32 == S32_opaque_D32_filter_DX) {
fSampleProc32 = S32_opaque_D32_filter_DX_SSSE3;
} else if (fSampleProc32 == S32_alpha_D32_filter_DX) {
fSampleProc32 = S32_alpha_D32_filter_DX_SSSE3;
}
if (fSampleProc32 == S32_opaque_D32_filter_DXDY) {
fSampleProc32 = S32_opaque_D32_filter_DXDY_SSSE3;
} else if (fSampleProc32 == S32_alpha_D32_filter_DXDY) {
fSampleProc32 = S32_alpha_D32_filter_DXDY_SSSE3;
}
} else if (cachedHasSSE2()) {
if (fSampleProc32 == S32_opaque_D32_filter_DX) {
fSampleProc32 = S32_opaque_D32_filter_DX_SSE2;
} else if (fSampleProc32 == S32_alpha_D32_filter_DX) {
fSampleProc32 = S32_alpha_D32_filter_DX_SSE2;
}
}
if (cachedHasSSSE3() || cachedHasSSE2()) {
if (fMatrixProc == ClampX_ClampY_filter_scale) {
fMatrixProc = ClampX_ClampY_filter_scale_SSE2;
} else if (fMatrixProc == ClampX_ClampY_nofilter_scale) {
fMatrixProc = ClampX_ClampY_nofilter_scale_SSE2;
}
if (fMatrixProc == ClampX_ClampY_filter_affine) {
fMatrixProc = ClampX_ClampY_filter_affine_SSE2;
} else if (fMatrixProc == ClampX_ClampY_nofilter_affine) {
fMatrixProc = ClampX_ClampY_nofilter_affine_SSE2;
}
}
}
static SkBlitRow::Proc32 platform_32_procs[] = {
NULL, // S32_Opaque,
S32_Blend_BlitRow32_SSE2, // S32_Blend,
S32A_Opaque_BlitRow32_SSE2, // S32A_Opaque
S32A_Blend_BlitRow32_SSE2, // S32A_Blend,
};
SkBlitRow::Proc SkBlitRow::PlatformProcs4444(unsigned flags) {
return NULL;
}
SkBlitRow::Proc SkBlitRow::PlatformProcs565(unsigned flags) {
return NULL;
}
SkBlitRow::ColorProc SkBlitRow::PlatformColorProc() {
if (cachedHasSSE2()) {
return Color32_SSE2;
} else {
return NULL;
}
}
SkBlitRow::Proc32 SkBlitRow::PlatformProcs32(unsigned flags) {
if (cachedHasSSE2()) {
return platform_32_procs[flags];
} else {
return NULL;
}
}
SkBlitMask::ColorProc SkBlitMask::PlatformColorProcs(SkBitmap::Config dstConfig,
SkMask::Format maskFormat,
SkColor color) {
if (SkMask::kA8_Format != maskFormat) {
return NULL;
}
ColorProc proc = NULL;
if (cachedHasSSE2()) {
switch (dstConfig) {
case SkBitmap::kARGB_8888_Config:
// The SSE2 version is not (yet) faster for black, so we check
// for that.
if (SK_ColorBLACK != color) {
proc = SkARGB32_A8_BlitMask_SSE2;
}
break;
default:
break;
}
}
return proc;
}
SkBlitMask::BlitLCD16RowProc SkBlitMask::PlatformBlitRowProcs16(bool isOpaque) {
if (cachedHasSSE2()) {
if (isOpaque) {
return SkBlitLCD16OpaqueRow_SSE2;
} else {
return SkBlitLCD16Row_SSE2;
}
} else {
return NULL;
}
}
SkBlitMask::RowProc SkBlitMask::PlatformRowProcs(SkBitmap::Config dstConfig,
SkMask::Format maskFormat,
RowFlags flags) {
return NULL;
}
SkMemset16Proc SkMemset16GetPlatformProc() {
if (cachedHasSSE2()) {
return sk_memset16_SSE2;
} else {
return NULL;
}
}
SkMemset32Proc SkMemset32GetPlatformProc() {
if (cachedHasSSE2()) {
return sk_memset32_SSE2;
} else {
return NULL;
}
}
SkBlitRow::ColorRectProc PlatformColorRectProcFactory() {
if (cachedHasSSE2()) {
return ColorRect32_SSE2;
} else {
return NULL;
}
}
<commit_msg>Remove stale #include.<commit_after>/*
* Copyright 2009 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcState_opts_SSE2.h"
#include "SkBitmapProcState_opts_SSSE3.h"
#include "SkBlitMask.h"
#include "SkBlitRow.h"
#include "SkBlitRect_opts_SSE2.h"
#include "SkBlitRow_opts_SSE2.h"
#include "SkUtils_opts_SSE2.h"
#include "SkUtils.h"
/* This file must *not* be compiled with -msse or -msse2, otherwise
gcc may generate sse2 even for scalar ops (and thus give an invalid
instruction on Pentium3 on the code below). Only files named *_SSE2.cpp
in this directory should be compiled with -msse2. */
#ifdef _MSC_VER
static inline void getcpuid(int info_type, int info[4]) {
__asm {
mov eax, [info_type]
cpuid
mov edi, [info]
mov [edi], eax
mov [edi+4], ebx
mov [edi+8], ecx
mov [edi+12], edx
}
}
#else
#if defined(__x86_64__)
static inline void getcpuid(int info_type, int info[4]) {
asm volatile (
"cpuid \n\t"
: "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3])
: "a"(info_type)
);
}
#else
static inline void getcpuid(int info_type, int info[4]) {
// We save and restore ebx, so this code can be compatible with -fPIC
asm volatile (
"pushl %%ebx \n\t"
"cpuid \n\t"
"movl %%ebx, %1 \n\t"
"popl %%ebx \n\t"
: "=a"(info[0]), "=r"(info[1]), "=c"(info[2]), "=d"(info[3])
: "a"(info_type)
);
}
#endif
#endif
#if defined(__x86_64__) || defined(_WIN64)
/* All x86_64 machines have SSE2, so don't even bother checking. */
static inline bool hasSSE2() {
return true;
}
#else
static inline bool hasSSE2() {
int cpu_info[4] = { 0 };
getcpuid(1, cpu_info);
return (cpu_info[3] & (1<<26)) != 0;
}
#endif
static inline bool hasSSSE3() {
int cpu_info[4] = { 0 };
getcpuid(1, cpu_info);
return (cpu_info[2] & 0x200) != 0;
}
static bool cachedHasSSE2() {
static bool gHasSSE2 = hasSSE2();
return gHasSSE2;
}
static bool cachedHasSSSE3() {
static bool gHasSSSE3 = hasSSSE3();
return gHasSSSE3;
}
void SkBitmapProcState::platformProcs() {
if (cachedHasSSSE3()) {
if (fSampleProc32 == S32_opaque_D32_filter_DX) {
fSampleProc32 = S32_opaque_D32_filter_DX_SSSE3;
} else if (fSampleProc32 == S32_alpha_D32_filter_DX) {
fSampleProc32 = S32_alpha_D32_filter_DX_SSSE3;
}
if (fSampleProc32 == S32_opaque_D32_filter_DXDY) {
fSampleProc32 = S32_opaque_D32_filter_DXDY_SSSE3;
} else if (fSampleProc32 == S32_alpha_D32_filter_DXDY) {
fSampleProc32 = S32_alpha_D32_filter_DXDY_SSSE3;
}
} else if (cachedHasSSE2()) {
if (fSampleProc32 == S32_opaque_D32_filter_DX) {
fSampleProc32 = S32_opaque_D32_filter_DX_SSE2;
} else if (fSampleProc32 == S32_alpha_D32_filter_DX) {
fSampleProc32 = S32_alpha_D32_filter_DX_SSE2;
}
}
if (cachedHasSSSE3() || cachedHasSSE2()) {
if (fMatrixProc == ClampX_ClampY_filter_scale) {
fMatrixProc = ClampX_ClampY_filter_scale_SSE2;
} else if (fMatrixProc == ClampX_ClampY_nofilter_scale) {
fMatrixProc = ClampX_ClampY_nofilter_scale_SSE2;
}
if (fMatrixProc == ClampX_ClampY_filter_affine) {
fMatrixProc = ClampX_ClampY_filter_affine_SSE2;
} else if (fMatrixProc == ClampX_ClampY_nofilter_affine) {
fMatrixProc = ClampX_ClampY_nofilter_affine_SSE2;
}
}
}
static SkBlitRow::Proc32 platform_32_procs[] = {
NULL, // S32_Opaque,
S32_Blend_BlitRow32_SSE2, // S32_Blend,
S32A_Opaque_BlitRow32_SSE2, // S32A_Opaque
S32A_Blend_BlitRow32_SSE2, // S32A_Blend,
};
SkBlitRow::Proc SkBlitRow::PlatformProcs4444(unsigned flags) {
return NULL;
}
SkBlitRow::Proc SkBlitRow::PlatformProcs565(unsigned flags) {
return NULL;
}
SkBlitRow::ColorProc SkBlitRow::PlatformColorProc() {
if (cachedHasSSE2()) {
return Color32_SSE2;
} else {
return NULL;
}
}
SkBlitRow::Proc32 SkBlitRow::PlatformProcs32(unsigned flags) {
if (cachedHasSSE2()) {
return platform_32_procs[flags];
} else {
return NULL;
}
}
SkBlitMask::ColorProc SkBlitMask::PlatformColorProcs(SkBitmap::Config dstConfig,
SkMask::Format maskFormat,
SkColor color) {
if (SkMask::kA8_Format != maskFormat) {
return NULL;
}
ColorProc proc = NULL;
if (cachedHasSSE2()) {
switch (dstConfig) {
case SkBitmap::kARGB_8888_Config:
// The SSE2 version is not (yet) faster for black, so we check
// for that.
if (SK_ColorBLACK != color) {
proc = SkARGB32_A8_BlitMask_SSE2;
}
break;
default:
break;
}
}
return proc;
}
SkBlitMask::BlitLCD16RowProc SkBlitMask::PlatformBlitRowProcs16(bool isOpaque) {
if (cachedHasSSE2()) {
if (isOpaque) {
return SkBlitLCD16OpaqueRow_SSE2;
} else {
return SkBlitLCD16Row_SSE2;
}
} else {
return NULL;
}
}
SkBlitMask::RowProc SkBlitMask::PlatformRowProcs(SkBitmap::Config dstConfig,
SkMask::Format maskFormat,
RowFlags flags) {
return NULL;
}
SkMemset16Proc SkMemset16GetPlatformProc() {
if (cachedHasSSE2()) {
return sk_memset16_SSE2;
} else {
return NULL;
}
}
SkMemset32Proc SkMemset32GetPlatformProc() {
if (cachedHasSSE2()) {
return sk_memset32_SSE2;
} else {
return NULL;
}
}
SkBlitRow::ColorRectProc PlatformColorRectProcFactory() {
if (cachedHasSSE2()) {
return ColorRect32_SSE2;
} else {
return NULL;
}
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/boundary_info.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/mesh_base.h"
#include "libmesh/node.h"
#include "libmesh/parallel.h"
#include "libmesh/parallel_mesh.h"
// Helper functions in anonymous namespace
namespace
{
using namespace libMesh;
#ifdef LIBMESH_ENABLE_UNIQUE_ID
static const unsigned int header_size = 3;
#else
static const unsigned int header_size = 2;
#endif
// use "(a+b-1)/b" trick to get a/b to round up
static const unsigned int idtypes_per_Real =
(sizeof(Real) + sizeof(largest_id_type) - 1) / sizeof(largest_id_type);
#ifndef NDEBUG
// Currently this constant is only used for debugging.
static const largest_id_type node_magic_header = 1234567890;
#endif
}
namespace libMesh
{
namespace Parallel
{
template <>
template <>
unsigned int
Packing<const Node *>::packable_size (const Node * const & node,
const MeshBase * mesh)
{
return
#ifndef NDEBUG
1 + // add an int for the magic header when testing
#endif
header_size + LIBMESH_DIM*idtypes_per_Real +
node->packed_indexing_size() +
1 + mesh->get_boundary_info().n_boundary_ids(node);
}
template <>
template <>
unsigned int
Packing<const Node *>::packed_size (const std::vector<largest_id_type>::const_iterator in)
{
const unsigned int pre_indexing_size =
#ifndef NDEBUG
1 + // add an int for the magic header when testing
#endif
header_size + LIBMESH_DIM*idtypes_per_Real;
const unsigned int indexing_size =
DofObject::unpackable_indexing_size(in+pre_indexing_size);
const int n_bcs = cast_int<int>
(*(in + pre_indexing_size + indexing_size));
libmesh_assert_greater_equal (n_bcs, 0);
return pre_indexing_size + indexing_size + 1 + n_bcs;
}
template <>
template <>
unsigned int
Packing<const Node *>::packed_size (const std::vector<largest_id_type>::iterator in)
{
return packed_size(std::vector<largest_id_type>::const_iterator(in));
}
template <>
template <>
unsigned int
Packing<const Node *>::packable_size (const Node * const & node,
const DistributedMesh * mesh)
{
return packable_size(node, static_cast<const MeshBase *>(mesh));
}
template <>
template <>
unsigned int
Packing<const Node *>::packable_size (const Node * const & node,
const ParallelMesh * mesh)
{
return packable_size(node, static_cast<const MeshBase *>(mesh));
}
template <>
template <>
void
Packing<const Node *>::pack (const Node * const & node,
std::back_insert_iterator<std::vector<largest_id_type>> data_out,
const MeshBase * mesh)
{
libmesh_assert(node);
#ifndef NDEBUG
*data_out++ = (node_magic_header);
#endif
*data_out++ = (static_cast<largest_id_type>(node->processor_id()));
*data_out++ = (static_cast<largest_id_type>(node->id()));
#ifdef LIBMESH_ENABLE_UNIQUE_ID
if (node->valid_unique_id())
*data_out++ = (static_cast<largest_id_type>(node->unique_id()));
else
// OK to send invalid unique id, we must not own this DOF
*data_out++ = (static_cast<largest_id_type>(DofObject::invalid_unique_id));
#endif
// use "(a+b-1)/b" trick to get a/b to round up
static const unsigned int idtypes_per_Real =
(sizeof(Real) + sizeof(largest_id_type) - 1) / sizeof(largest_id_type);
for (unsigned int i=0; i != LIBMESH_DIM; ++i)
{
const largest_id_type * Real_as_idtypes =
reinterpret_cast<const largest_id_type *>(&((*node)(i)));
for (unsigned int j=0; j != idtypes_per_Real; ++j)
{
*data_out++ =(Real_as_idtypes[j]);
}
}
// Add any DofObject indices
node->pack_indexing(data_out);
// Add any nodal boundary condition ids
std::vector<boundary_id_type> bcs;
mesh->get_boundary_info().boundary_ids(node, bcs);
libmesh_assert(bcs.size() < std::numeric_limits<largest_id_type>::max());
*data_out++ =(bcs.size());
for (const auto & bid : bcs)
*data_out++ = bid;
}
template <>
template <>
void
Packing<const Node *>::pack (const Node * const & node,
std::back_insert_iterator<std::vector<largest_id_type>> data_out,
const DistributedMesh * mesh)
{
pack(node, data_out, static_cast<const MeshBase*>(mesh));
}
template <>
template <>
void
Packing<const Node *>::pack (const Node * const & node,
std::back_insert_iterator<std::vector<largest_id_type>> data_out,
const ParallelMesh * mesh)
{
pack(node, data_out, static_cast<const MeshBase*>(mesh));
}
template <>
template <>
Node *
Packing<Node *>::unpack (std::vector<largest_id_type>::const_iterator in,
MeshBase * mesh)
{
#ifndef NDEBUG
const std::vector<largest_id_type>::const_iterator original_in = in;
const largest_id_type incoming_header = *in++;
libmesh_assert_equal_to (incoming_header, node_magic_header);
#endif
const processor_id_type processor_id = cast_int<processor_id_type>(*in++);
libmesh_assert(processor_id == DofObject::invalid_processor_id ||
processor_id < mesh->n_processors());
const dof_id_type id = cast_int<dof_id_type>(*in++);
#ifdef LIBMESH_ENABLE_UNIQUE_ID
const unique_id_type unique_id = cast_int<unique_id_type>(*in++);
#endif
Node * node = mesh->query_node_ptr(id);
if (node)
{
libmesh_assert_equal_to (node->processor_id(), processor_id);
// We currently don't communicate mesh motion via packed Nodes,
// so it should usually be safe to assume (and assert) that Node
// locations are consistent between processors.
//
// There may be exceptions due to rounding in file I/O, so we'll
// only assert equality to within a tight tolerance, and we'll
// believe the sender's node locations over our own if we don't
// own the node.
for (unsigned int i=0; i != LIBMESH_DIM; ++i)
{
const Real & idtypes_as_Real = *(reinterpret_cast<const Real *>(&(*in)));
libmesh_assert_less_equal ((*node)(i), idtypes_as_Real + (std::max(Real(1),idtypes_as_Real)*TOLERANCE*TOLERANCE));
libmesh_assert_greater_equal ((*node)(i), idtypes_as_Real - (std::max(Real(1),idtypes_as_Real)*TOLERANCE*TOLERANCE));
if (processor_id != mesh->processor_id())
(*node)(i) = idtypes_as_Real;
in += idtypes_per_Real;
}
if (!node->has_dofs())
{
node->unpack_indexing(in);
libmesh_assert_equal_to (DofObject::unpackable_indexing_size(in),
node->packed_indexing_size());
in += node->packed_indexing_size();
}
else
{
// FIXME: We should add some debug mode tests to ensure that
// the encoded indexing is consistent
in += DofObject::unpackable_indexing_size(in);
}
}
else
{
// If we don't already have it, we need to allocate it
node = new Node();
for (unsigned int i=0; i != LIBMESH_DIM; ++i)
{
const Real * idtypes_as_Real = reinterpret_cast<const Real *>(&(*in));
(*node)(i) = *idtypes_as_Real;
in += idtypes_per_Real;
}
node->set_id() = id;
#ifdef LIBMESH_ENABLE_UNIQUE_ID
node->set_unique_id() = unique_id;
#endif
node->processor_id() = processor_id;
node->unpack_indexing(in);
libmesh_assert_equal_to (DofObject::unpackable_indexing_size(in),
node->packed_indexing_size());
in += node->packed_indexing_size();
}
// FIXME: We should add some debug mode tests to ensure that the
// encoded boundary conditions are consistent
// Add any nodal boundary condition ids
const largest_id_type num_bcs = *in++;
// libmesh_assert_greater_equal (num_bcs, 0);
for (largest_id_type bc_it=0; bc_it < num_bcs; bc_it++)
mesh->get_boundary_info().add_node
(node, cast_int<boundary_id_type>(*in++));
#ifndef NDEBUG
libmesh_assert (in - original_in ==
cast_int<int>
(Parallel::Packing<const Node*>::packed_size(original_in)));
#endif
return node;
}
template <>
template <>
Node *
Packing<Node *>::unpack (std::vector<largest_id_type>::const_iterator in,
DistributedMesh * mesh)
{
return unpack(in, static_cast<MeshBase*>(mesh));
}
template <>
template <>
Node *
Packing<Node *>::unpack (std::vector<largest_id_type>::const_iterator in,
ParallelMesh * mesh)
{
return unpack(in, static_cast<MeshBase*>(mesh));
}
} // namespace Parallel
} // namespace libMesh
<commit_msg>Use memcpy instead of reinterpret_cast<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "libmesh/boundary_info.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/mesh_base.h"
#include "libmesh/node.h"
#include "libmesh/parallel.h"
#include "libmesh/parallel_mesh.h"
// Helper functions in anonymous namespace
namespace
{
using namespace libMesh;
#ifdef LIBMESH_ENABLE_UNIQUE_ID
static const unsigned int header_size = 3;
#else
static const unsigned int header_size = 2;
#endif
// use "(a+b-1)/b" trick to get a/b to round up
static const unsigned int idtypes_per_Real =
(sizeof(Real) + sizeof(largest_id_type) - 1) / sizeof(largest_id_type);
#ifndef NDEBUG
// Currently this constant is only used for debugging.
static const largest_id_type node_magic_header = 1234567890;
#endif
}
namespace libMesh
{
namespace Parallel
{
template <>
template <>
unsigned int
Packing<const Node *>::packable_size (const Node * const & node,
const MeshBase * mesh)
{
return
#ifndef NDEBUG
1 + // add an int for the magic header when testing
#endif
header_size + LIBMESH_DIM*idtypes_per_Real +
node->packed_indexing_size() +
1 + mesh->get_boundary_info().n_boundary_ids(node);
}
template <>
template <>
unsigned int
Packing<const Node *>::packed_size (const std::vector<largest_id_type>::const_iterator in)
{
const unsigned int pre_indexing_size =
#ifndef NDEBUG
1 + // add an int for the magic header when testing
#endif
header_size + LIBMESH_DIM*idtypes_per_Real;
const unsigned int indexing_size =
DofObject::unpackable_indexing_size(in+pre_indexing_size);
const int n_bcs = cast_int<int>
(*(in + pre_indexing_size + indexing_size));
libmesh_assert_greater_equal (n_bcs, 0);
return pre_indexing_size + indexing_size + 1 + n_bcs;
}
template <>
template <>
unsigned int
Packing<const Node *>::packed_size (const std::vector<largest_id_type>::iterator in)
{
return packed_size(std::vector<largest_id_type>::const_iterator(in));
}
template <>
template <>
unsigned int
Packing<const Node *>::packable_size (const Node * const & node,
const DistributedMesh * mesh)
{
return packable_size(node, static_cast<const MeshBase *>(mesh));
}
template <>
template <>
unsigned int
Packing<const Node *>::packable_size (const Node * const & node,
const ParallelMesh * mesh)
{
return packable_size(node, static_cast<const MeshBase *>(mesh));
}
template <>
template <>
void
Packing<const Node *>::pack (const Node * const & node,
std::back_insert_iterator<std::vector<largest_id_type>> data_out,
const MeshBase * mesh)
{
libmesh_assert(node);
#ifndef NDEBUG
*data_out++ = (node_magic_header);
#endif
*data_out++ = (static_cast<largest_id_type>(node->processor_id()));
*data_out++ = (static_cast<largest_id_type>(node->id()));
#ifdef LIBMESH_ENABLE_UNIQUE_ID
if (node->valid_unique_id())
*data_out++ = (static_cast<largest_id_type>(node->unique_id()));
else
// OK to send invalid unique id, we must not own this DOF
*data_out++ = (static_cast<largest_id_type>(DofObject::invalid_unique_id));
#endif
for (unsigned int i=0; i != LIBMESH_DIM; ++i)
{
const Real node_i = (*node)(i);
largest_id_type Real_as_idtypes[idtypes_per_Real];
memcpy(Real_as_idtypes, &node_i, sizeof(Real));
for (unsigned int j=0; j != idtypes_per_Real; ++j)
*data_out++ =(Real_as_idtypes[j]);
}
// Add any DofObject indices
node->pack_indexing(data_out);
// Add any nodal boundary condition ids
std::vector<boundary_id_type> bcs;
mesh->get_boundary_info().boundary_ids(node, bcs);
libmesh_assert(bcs.size() < std::numeric_limits<largest_id_type>::max());
*data_out++ =(bcs.size());
for (const auto & bid : bcs)
*data_out++ = bid;
}
template <>
template <>
void
Packing<const Node *>::pack (const Node * const & node,
std::back_insert_iterator<std::vector<largest_id_type>> data_out,
const DistributedMesh * mesh)
{
pack(node, data_out, static_cast<const MeshBase*>(mesh));
}
template <>
template <>
void
Packing<const Node *>::pack (const Node * const & node,
std::back_insert_iterator<std::vector<largest_id_type>> data_out,
const ParallelMesh * mesh)
{
pack(node, data_out, static_cast<const MeshBase*>(mesh));
}
template <>
template <>
Node *
Packing<Node *>::unpack (std::vector<largest_id_type>::const_iterator in,
MeshBase * mesh)
{
#ifndef NDEBUG
const std::vector<largest_id_type>::const_iterator original_in = in;
const largest_id_type incoming_header = *in++;
libmesh_assert_equal_to (incoming_header, node_magic_header);
#endif
const processor_id_type processor_id = cast_int<processor_id_type>(*in++);
libmesh_assert(processor_id == DofObject::invalid_processor_id ||
processor_id < mesh->n_processors());
const dof_id_type id = cast_int<dof_id_type>(*in++);
#ifdef LIBMESH_ENABLE_UNIQUE_ID
const unique_id_type unique_id = cast_int<unique_id_type>(*in++);
#endif
Node * node = mesh->query_node_ptr(id);
if (node)
{
libmesh_assert_equal_to (node->processor_id(), processor_id);
// We currently don't communicate mesh motion via packed Nodes,
// so it should usually be safe to assume (and assert) that Node
// locations are consistent between processors.
//
// There may be exceptions due to rounding in file I/O, so we'll
// only assert equality to within a tight tolerance, and we'll
// believe the sender's node locations over our own if we don't
// own the node.
for (unsigned int i=0; i != LIBMESH_DIM; ++i)
{
Real idtypes_as_Real;
memcpy(&idtypes_as_Real, &(*in), sizeof(Real));
in += idtypes_per_Real;
libmesh_assert_less_equal ((*node)(i), idtypes_as_Real + (std::max(Real(1),idtypes_as_Real)*TOLERANCE*TOLERANCE));
libmesh_assert_greater_equal ((*node)(i), idtypes_as_Real - (std::max(Real(1),idtypes_as_Real)*TOLERANCE*TOLERANCE));
if (processor_id != mesh->processor_id())
(*node)(i) = idtypes_as_Real;
}
if (!node->has_dofs())
{
node->unpack_indexing(in);
libmesh_assert_equal_to (DofObject::unpackable_indexing_size(in),
node->packed_indexing_size());
in += node->packed_indexing_size();
}
else
{
// FIXME: We should add some debug mode tests to ensure that
// the encoded indexing is consistent
in += DofObject::unpackable_indexing_size(in);
}
}
else
{
// If we don't already have it, we need to allocate it
node = new Node();
for (unsigned int i=0; i != LIBMESH_DIM; ++i)
{
Real idtypes_as_Real;
memcpy(&idtypes_as_Real, &(*in), sizeof(Real));
(*node)(i) = idtypes_as_Real;
in += idtypes_per_Real;
}
node->set_id() = id;
#ifdef LIBMESH_ENABLE_UNIQUE_ID
node->set_unique_id() = unique_id;
#endif
node->processor_id() = processor_id;
node->unpack_indexing(in);
libmesh_assert_equal_to (DofObject::unpackable_indexing_size(in),
node->packed_indexing_size());
in += node->packed_indexing_size();
}
// FIXME: We should add some debug mode tests to ensure that the
// encoded boundary conditions are consistent
// Add any nodal boundary condition ids
const largest_id_type num_bcs = *in++;
// libmesh_assert_greater_equal (num_bcs, 0);
for (largest_id_type bc_it=0; bc_it < num_bcs; bc_it++)
mesh->get_boundary_info().add_node
(node, cast_int<boundary_id_type>(*in++));
#ifndef NDEBUG
libmesh_assert (in - original_in ==
cast_int<int>
(Parallel::Packing<const Node*>::packed_size(original_in)));
#endif
return node;
}
template <>
template <>
Node *
Packing<Node *>::unpack (std::vector<largest_id_type>::const_iterator in,
DistributedMesh * mesh)
{
return unpack(in, static_cast<MeshBase*>(mesh));
}
template <>
template <>
Node *
Packing<Node *>::unpack (std::vector<largest_id_type>::const_iterator in,
ParallelMesh * mesh)
{
return unpack(in, static_cast<MeshBase*>(mesh));
}
} // namespace Parallel
} // namespace libMesh
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// sql_statement.cpp
//
// Identification: src/parser/sql_statement.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
/*-------------------------------------------------------------------------
*
* sql_statement.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/parser/sql_statement.cpp
*
*-------------------------------------------------------------------------
*/
#include "parser/sql_statement.h"
#include "parser/parser_utils.h"
namespace peloton {
namespace parser {
//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//
const std::string SQLStatement::GetInfo() const {
std::ostringstream os;
os << "SQLStatement[" << StatementTypeToString(stmt_type) << "]\n";
int indent = 1;
switch (stmt_type) {
case StatementType::SELECT:
GetSelectStatementInfo((SelectStatement*)this, indent);
break;
case StatementType::INSERT:
GetInsertStatementInfo((InsertStatement*)this, indent);
break;
case StatementType::CREATE:
GetCreateStatementInfo((CreateStatement*)this, indent);
break;
case StatementType::DELETE:
GetDeleteStatementInfo((DeleteStatement*)this, indent);
break;
default:
break;
}
return os.str();
}
const std::string SQLStatementList::GetInfo() const {
std::ostringstream os;
if (is_valid) {
std::cout<<"----"<<std::endl;
for (auto stmt : statements) {
os << stmt->GetInfo();
std::cout<<stmt->GetInfo()<<std::endl;
}
} else {
os << "Invalid statement list \n";
}
return os.str();
}
} // End parser namespace
} // End peloton namespace
<commit_msg>Resolve validation not succesful.<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// sql_statement.cpp
//
// Identification: src/parser/sql_statement.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
/*-------------------------------------------------------------------------
*
* sql_statement.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/parser/sql_statement.cpp
*
*-------------------------------------------------------------------------
*/
#include "parser/sql_statement.h"
#include "parser/parser_utils.h"
namespace peloton {
namespace parser {
//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//
const std::string SQLStatement::GetInfo() const {
std::ostringstream os;
os << "SQLStatement[" << StatementTypeToString(stmt_type) << "]\n";
int indent = 1;
switch (stmt_type) {
case StatementType::SELECT:
GetSelectStatementInfo((SelectStatement*)this, indent);
break;
case StatementType::INSERT:
GetInsertStatementInfo((InsertStatement*)this, indent);
break;
case StatementType::CREATE:
GetCreateStatementInfo((CreateStatement*)this, indent);
break;
case StatementType::DELETE:
GetDeleteStatementInfo((DeleteStatement*)this, indent);
break;
default:
break;
}
return os.str();
}
const std::string SQLStatementList::GetInfo() const {
std::ostringstream os;
if (is_valid) {
for (auto stmt : statements) {
os << stmt->GetInfo();
std::cout<<stmt->GetInfo()<<std::endl;
}
} else {
os << "Invalid statement list \n";
}
return os.str();
}
} // End parser namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2016 by Contributors
* \file infer_shape.cc
* \brief Inference the shapes given existin information.
*/
#include <nnvm/pass.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/graph_attr_types.h>
namespace nnvm {
namespace pass {
namespace {
template<typename AttrType, typename IsNone>
Graph InferAttr(Graph &&ret,
const AttrType default_val,
const char* infer_name,
const char* input_name,
const char* attr_key_name,
const char* attr_name,
const char* unknown_name,
IsNone fis_none) {
using AttrVector = std::vector<AttrType>;
const IndexedGraph& idx = ret.indexed_graph();
static auto& finfer_shape =
Op::GetAttr<FInferNodeEntryAttr<AttrType> >(infer_name);
static auto& backward_map =
Op::GetAttr<FBackwardOutToInIndex>("FBackwardOutToInIndex");
// reshape shape vector
AttrVector rshape;
if (ret.attrs.count(attr_name) != 0) {
rshape = ret.MoveCopyAttr<AttrVector>(attr_name);
} else {
rshape.resize(idx.num_node_entries(), default_val);
}
if (ret.attrs.count(input_name) != 0) {
const AttrVector& shape_args = ret.GetAttr<AttrVector>(input_name);
CHECK_LE(shape_args.size(), idx.input_nodes().size())
<< "More provided shapes than number of arguments.";
for (size_t i = 0; i < shape_args.size(); ++i) {
rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i];
}
// erase the provided arguments
ret.attrs.erase(input_name);
}
std::string shape_attr_key;
if (ret.attrs.count(attr_key_name) != 0) {
shape_attr_key = ret.GetAttr<std::string>(attr_key_name);
// erase the provided arguments
ret.attrs.erase(attr_key_name);
}
// Temp space for shape inference.
std::vector<AttrType> ishape, oshape;
// number of completed nodes
size_t num_unknown = 0;
for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {
const auto& inode = idx[nid];
const uint32_t num_inputs = inode.inputs.size();
const uint32_t num_outputs = inode.source->num_outputs();
if (inode.source->is_variable()) {
// Variable node. No operator. Only one output entry.
CHECK(inode.source->op() == nullptr);
CHECK_EQ(num_outputs, 1);
const uint32_t out_ent_id = idx.entry_id(nid, 0);
if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) {
auto it = inode.source->attrs.dict.find(shape_attr_key);
if (it != inode.source->attrs.dict.end()) {
std::istringstream is(it->second);
CHECK(is >> rshape[out_ent_id]) << "Invalid attribute";
}
}
} else if (finfer_shape.count(inode.source->op())) {
// Forward operator inference.
ishape.resize(num_inputs, default_val);
for (uint32_t i = 0; i < ishape.size(); ++i) {
ishape[i] = rshape[idx.entry_id(inode.inputs[i])];
}
oshape.resize(num_outputs, default_val);
for (uint32_t i = 0; i < oshape.size(); ++i) {
oshape[i] = rshape[idx.entry_id(nid, i)];
}
// Call inference function of the operator.
bool forward_known = finfer_shape[inode.source->op()](
inode.source->attrs, &ishape, &oshape);
num_unknown += !forward_known;
// Save to the result map.
for (uint32_t i = 0; i < num_inputs; ++i) {
rshape[idx.entry_id(inode.inputs[i])] = ishape[i];
}
for (uint32_t i = 0; i < num_outputs; ++i) {
rshape[idx.entry_id(nid, i)] = oshape[i];
}
} else if (backward_map.count(inode.source->op())) {
// Backward operator inference.
CHECK_GE(inode.control_deps.size(), 1)
<< "BackwardOp need to have control_deps to its forward op";
const IndexedGraph::Node& fnode = idx[inode.control_deps[0]];
// Inference the outputs of backward operator (equal to the inputs
// of its corresponding forward operator).
std::vector<uint32_t> out_map =
backward_map[inode.source->op()](inode.source->attrs);
bool known = true;
for (size_t i = 0; i < out_map.size(); ++i) {
uint32_t in_id = out_map[i];
CHECK_LT(in_id, fnode.inputs.size());
rshape[idx.entry_id(nid, i)] =
rshape[idx.entry_id(fnode.inputs[in_id])];
if (fis_none(rshape[idx.entry_id(nid, i)])) known = false;
}
num_unknown += !known;
}
}
// set the shapes
ret.attrs[attr_name] = std::make_shared<any>(std::move(rshape));
// number of nodes who knows the shape.
ret.attrs[unknown_name] = std::make_shared<any>(num_unknown);
return ret;
}
NNVM_REGISTER_PASS(InferShape)
.describe("Infer the shape of each node entries.")
.set_body([](Graph ret) {
return InferAttr<TShape>(
std::move(ret), TShape(),
"FInferShape", "shape_inputs", "shape_attr_key",
"shape", "shape_num_unknown_nodes",
[](const TShape& s) { return s.ndim() == 0; });
})
.set_change_graph(false)
.provide_graph_attr("shape");
NNVM_REGISTER_PASS(InferType)
.describe("Infer the dtype of each node entries.")
.set_body([](Graph ret) {
return InferAttr<int>(
std::move(ret), 0,
"FInferType", "dtype_inputs", "dtype_attr_key",
"dtype", "dtype_num_unknown_nodes",
[](const int t) { return t == -1; });
})
.set_change_graph(false)
.provide_graph_attr("dtype");
DMLC_JSON_ENABLE_ANY(ShapeVector, list_shape);
DMLC_JSON_ENABLE_ANY(DTypeVector, list_int);
DMLC_JSON_ENABLE_ANY(size_t, size_t);
} // namespace
} // namespace pass
} // namespace nnvm
<commit_msg>[Infer] More robust inference, support backward inference (#54)<commit_after>/*!
* Copyright (c) 2016 by Contributors
* \file infer_shape.cc
* \brief Inference the shapes given existin information.
*/
#include <nnvm/pass.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/graph_attr_types.h>
namespace nnvm {
namespace pass {
namespace {
template<typename AttrType, typename IsNone, typename FDefault>
Graph InferAttr(Graph &&ret,
const AttrType empty_val,
const char* infer_name,
const char* input_name,
const char* attr_key_name,
const char* attr_name,
const char* unknown_name,
IsNone fis_none,
FDefault fdefault) {
using AttrVector = std::vector<AttrType>;
const IndexedGraph& idx = ret.indexed_graph();
static auto& finfer_shape =
Op::GetAttr<FInferNodeEntryAttr<AttrType> >(infer_name);
static auto& backward_map =
Op::GetAttr<FBackwardOutToInIndex>("FBackwardOutToInIndex");
// reshape shape vector
AttrVector rshape;
if (ret.attrs.count(attr_name) != 0) {
rshape = ret.MoveCopyAttr<AttrVector>(attr_name);
} else {
rshape.resize(idx.num_node_entries(), empty_val);
}
if (ret.attrs.count(input_name) != 0) {
const AttrVector& shape_args = ret.GetAttr<AttrVector>(input_name);
CHECK_LE(shape_args.size(), idx.input_nodes().size())
<< "More provided shapes than number of arguments.";
for (size_t i = 0; i < shape_args.size(); ++i) {
rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i];
}
// erase the provided arguments
ret.attrs.erase(input_name);
}
std::string shape_attr_key;
if (ret.attrs.count(attr_key_name) != 0) {
shape_attr_key = ret.GetAttr<std::string>(attr_key_name);
// erase the provided arguments
ret.attrs.erase(attr_key_name);
}
// Temp space for shape inference.
std::vector<AttrType> ishape, oshape;
size_t num_unknown;
// inference step function for nid
auto infer_step = [&](uint32_t nid) {
const auto& inode = idx[nid];
const uint32_t num_inputs = inode.inputs.size();
const uint32_t num_outputs = inode.source->num_outputs();
if (inode.source->is_variable()) {
// Variable node. No operator. Only one output entry.
CHECK(inode.source->op() == nullptr);
CHECK_EQ(num_outputs, 1);
const uint32_t out_ent_id = idx.entry_id(nid, 0);
if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) {
auto it = inode.source->attrs.dict.find(shape_attr_key);
if (it != inode.source->attrs.dict.end()) {
std::istringstream is(it->second);
CHECK(is >> rshape[out_ent_id]) << "Invalid attribute";
}
}
} else if (backward_map.count(inode.source->op())) {
// Backward operator inference.
CHECK_GE(inode.control_deps.size(), 1)
<< "BackwardOp need to have control_deps to its forward op";
const IndexedGraph::Node& fnode = idx[inode.control_deps[0]];
// Inference the outputs of backward operator (equal to the inputs
// of its corresponding forward operator).
std::vector<uint32_t> out_map =
backward_map[inode.source->op()](inode.source->attrs);
bool known = true;
for (size_t i = 0; i < out_map.size(); ++i) {
uint32_t in_id = out_map[i];
CHECK_LT(in_id, fnode.inputs.size());
rshape[idx.entry_id(nid, i)] =
rshape[idx.entry_id(fnode.inputs[in_id])];
if (fis_none(rshape[idx.entry_id(nid, i)])) known = false;
}
num_unknown += !known;
} else {
bool forward_known = true;
// Forward operator inference.
ishape.resize(num_inputs, empty_val);
for (uint32_t i = 0; i < ishape.size(); ++i) {
ishape[i] = rshape[idx.entry_id(inode.inputs[i])];
if (fis_none(ishape[i])) forward_known = false;
}
oshape.resize(num_outputs, empty_val);
for (uint32_t i = 0; i < oshape.size(); ++i) {
oshape[i] = rshape[idx.entry_id(nid, i)];
if (fis_none(oshape[i])) forward_known = false;
}
if (!forward_known) {
auto finfer = finfer_shape.get(inode.source->op(), fdefault);
CHECK(finfer != nullptr)
<< "Attribute " << infer_name
<< " is not registed by op " << inode.source->op()->name;
// Call inference function of the operator.
forward_known = finfer(inode.source->attrs, &ishape, &oshape);
}
num_unknown += !forward_known;
// Save to the result map.
for (uint32_t i = 0; i < num_inputs; ++i) {
rshape[idx.entry_id(inode.inputs[i])] = ishape[i];
}
for (uint32_t i = 0; i < num_outputs; ++i) {
rshape[idx.entry_id(nid, i)] = oshape[i];
}
}
};
num_unknown = 0;
for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {
infer_step(nid);
}
if (num_unknown != 0) {
num_unknown = 0;
// backward inference
for (uint32_t i = idx.num_nodes(); i != 0; --i) {
infer_step(i - 1);
}
}
// set the shapes
ret.attrs[attr_name] = std::make_shared<any>(std::move(rshape));
// number of nodes who knows the shape.
ret.attrs[unknown_name] = std::make_shared<any>(num_unknown);
return ret;
}
NNVM_REGISTER_PASS(InferShape)
.describe("Infer the shape of each node entries.")
.set_body([](Graph ret) {
return InferAttr<TShape>(
std::move(ret), TShape(),
"FInferShape", "shape_inputs", "shape_attr_key",
"shape", "shape_num_unknown_nodes",
[](const TShape& s) { return s.ndim() == 0; },
nullptr);
})
.set_change_graph(false)
.provide_graph_attr("shape");
// inference fucntion for same type
inline bool SameType(const NodeAttrs& attrs,
std::vector<int> *iattr,
std::vector<int> *oattr) {
int def_v = -1;
for (int v : *oattr) {
if (v != -1) {
def_v = v; break;
}
}
if (def_v == -1) {
for (int v : *iattr) {
if (v != -1) {
def_v = v; break;
}
}
}
if (def_v == -1) return false;
for (int& v : *oattr) {
v = def_v;
}
for (int& v : *iattr) {
v = def_v;
}
return true;
}
NNVM_REGISTER_PASS(InferType)
.describe("Infer the dtype of each node entries.")
.set_body([](Graph ret) {
return InferAttr<int>(
std::move(ret), -1,
"FInferType", "dtype_inputs", "dtype_attr_key",
"dtype", "dtype_num_unknown_nodes",
[](const int t) { return t == -1; },
SameType);
})
.set_change_graph(false)
.provide_graph_attr("dtype");
DMLC_JSON_ENABLE_ANY(ShapeVector, list_shape);
DMLC_JSON_ENABLE_ANY(DTypeVector, list_int);
DMLC_JSON_ENABLE_ANY(size_t, size_t);
} // namespace
} // namespace pass
} // namespace nnvm
<|endoftext|> |
<commit_before>#include <node.h>
#include "gn_player.h"
#include "gn_playlist_item.h"
#include "gn_file.h"
using namespace v8;
GNPlayer::GNPlayer() {
event = new GroovePlayerEvent;
};
GNPlayer::~GNPlayer() {
delete event;
};
Persistent<Function> GNPlayer::constructor;
template <typename target_t, typename func_t>
static void AddGetter(target_t tpl, const char* name, func_t fn) {
tpl->PrototypeTemplate()->SetAccessor(String::NewSymbol(name), fn);
}
template <typename target_t, typename func_t>
static void AddMethod(target_t tpl, const char* name, func_t fn) {
tpl->PrototypeTemplate()->Set(String::NewSymbol(name),
FunctionTemplate::New(fn)->GetFunction());
}
void GNPlayer::Init() {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("GroovePlayer"));
tpl->InstanceTemplate()->SetInternalFieldCount(2);
// Methods
AddMethod(tpl, "destroy", Destroy);
AddMethod(tpl, "play", Play);
AddMethod(tpl, "playlist", Playlist);
AddMethod(tpl, "pause", Pause);
AddMethod(tpl, "seek", Seek);
AddMethod(tpl, "insert", Insert);
AddMethod(tpl, "remove", Remove);
AddMethod(tpl, "position", Position);
AddMethod(tpl, "playing", Playing);
AddMethod(tpl, "clear", Clear);
AddMethod(tpl, "count", Count);
AddMethod(tpl, "_eventPoll", EventPoll);
AddMethod(tpl, "setReplayGainMode", SetReplayGainMode);
AddMethod(tpl, "setReplayGainPreamp", SetReplayGainPreamp);
AddMethod(tpl, "getReplayGainPreamp", GetReplayGainPreamp);
AddMethod(tpl, "setReplayGainDefault", SetReplayGainDefault);
AddMethod(tpl, "getReplayGainDefault", GetReplayGainDefault);
constructor = Persistent<Function>::New(tpl->GetFunction());
}
Handle<Value> GNPlayer::New(const Arguments& args) {
HandleScope scope;
GNPlayer *obj = new GNPlayer();
obj->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value> GNPlayer::NewInstance(GroovePlayer *player) {
HandleScope scope;
Local<Object> instance = constructor->NewInstance();
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(instance);
gn_player->player = player;
return scope.Close(instance);
}
Handle<Value> GNPlayer::Play(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
groove_player_play(gn_player->player);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Playlist(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
Local<Array> playlist = Array::New();
GroovePlaylistItem *item = gn_player->player->playlist_head;
int i = 0;
while (item) {
playlist->Set(Number::New(i), GNPlaylistItem::NewInstance(item));
item = item->next;
}
return scope.Close(playlist);
}
Handle<Value> GNPlayer::Pause(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
groove_player_pause(gn_player->player);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Seek(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
GNPlaylistItem *gn_playlist_item =
node::ObjectWrap::Unwrap<GNPlaylistItem>(args[0]->ToObject());
double pos = args[1]->NumberValue();
groove_player_seek(gn_player->player, gn_playlist_item->playlist_item, pos);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Insert(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
GNFile *gn_file = node::ObjectWrap::Unwrap<GNFile>(args[0]->ToObject());
GroovePlaylistItem *item = NULL;
if (!args[1]->IsObject() && !args[1]->IsUndefined()) {
GNPlaylistItem *gn_pl_item =
node::ObjectWrap::Unwrap<GNPlaylistItem>(args[1]->ToObject());
item = gn_pl_item->playlist_item;
}
groove_player_insert(gn_player->player, gn_file->file, item);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Remove(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Position(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Playing(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Clear(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Count(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::EventPoll(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
int ret = groove_player_event_poll(gn_player->player, gn_player->event);
return scope.Close(Number::New(ret > 0 ? gn_player->event->type : -1));
}
Handle<Value> GNPlayer::SetReplayGainMode(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::SetReplayGainPreamp(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::GetReplayGainPreamp(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::SetReplayGainDefault(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::GetReplayGainDefault(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
struct CreateReq {
uv_work_t req;
GroovePlayer *player;
Persistent<Function> callback;
};
static void CreateAsync(uv_work_t *req) {
CreateReq *r = reinterpret_cast<CreateReq *>(req->data);
r->player = groove_create_player();
}
static void CreateAfter(uv_work_t *req) {
HandleScope scope;
CreateReq *r = reinterpret_cast<CreateReq *>(req->data);
const unsigned argc = 2;
Handle<Value> argv[argc];
if (r->player) {
argv[0] = Null();
argv[1] = GNPlayer::NewInstance(r->player);
} else {
argv[0] = Exception::Error(String::New("create player failed"));
argv[1] = Null();
}
r->callback->Call(Context::GetCurrent()->Global(), argc, argv);
delete r;
}
Handle<Value> GNPlayer::Create(const Arguments& args) {
HandleScope scope;
if (args.Length() < 1 || !args[0]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Expected function arg[0]")));
return scope.Close(Undefined());
}
CreateReq *request = new CreateReq;
request->callback = Persistent<Function>::New(Local<Function>::Cast(args[0]));
request->req.data = request;
uv_queue_work(uv_default_loop(), &request->req, CreateAsync,
(uv_after_work_cb)CreateAfter);
return scope.Close(Undefined());
}
struct DestroyReq {
uv_work_t req;
GroovePlayer *player;
Persistent<Function> callback;
};
static void DestroyAsync(uv_work_t *req) {
DestroyReq *r = reinterpret_cast<DestroyReq *>(req->data);
groove_destroy_player(r->player);
}
static void DestroyAfter(uv_work_t *req) {
HandleScope scope;
DestroyReq *r = reinterpret_cast<DestroyReq *>(req->data);
const unsigned argc = 1;
Handle<Value> argv[argc];
argv[0] = Null();
r->callback->Call(Context::GetCurrent()->Global(), argc, argv);
delete r;
}
Handle<Value> GNPlayer::Destroy(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
if (args.Length() < 1 || !args[0]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Expected function arg[0]")));
return scope.Close(Undefined());
}
DestroyReq *request = new DestroyReq;
request->callback = Persistent<Function>::New(Local<Function>::Cast(args[0]));
request->player = gn_player->player;
request->req.data = request;
uv_queue_work(uv_default_loop(), &request->req, DestroyAsync,
(uv_after_work_cb)DestroyAfter);
return scope.Close(Undefined());
}
<commit_msg>implement remove and position<commit_after>#include <node.h>
#include "gn_player.h"
#include "gn_playlist_item.h"
#include "gn_file.h"
using namespace v8;
GNPlayer::GNPlayer() {
event = new GroovePlayerEvent;
};
GNPlayer::~GNPlayer() {
delete event;
};
Persistent<Function> GNPlayer::constructor;
template <typename target_t, typename func_t>
static void AddGetter(target_t tpl, const char* name, func_t fn) {
tpl->PrototypeTemplate()->SetAccessor(String::NewSymbol(name), fn);
}
template <typename target_t, typename func_t>
static void AddMethod(target_t tpl, const char* name, func_t fn) {
tpl->PrototypeTemplate()->Set(String::NewSymbol(name),
FunctionTemplate::New(fn)->GetFunction());
}
void GNPlayer::Init() {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("GroovePlayer"));
tpl->InstanceTemplate()->SetInternalFieldCount(2);
// Methods
AddMethod(tpl, "destroy", Destroy);
AddMethod(tpl, "play", Play);
AddMethod(tpl, "playlist", Playlist);
AddMethod(tpl, "pause", Pause);
AddMethod(tpl, "seek", Seek);
AddMethod(tpl, "insert", Insert);
AddMethod(tpl, "remove", Remove);
AddMethod(tpl, "position", Position);
AddMethod(tpl, "playing", Playing);
AddMethod(tpl, "clear", Clear);
AddMethod(tpl, "count", Count);
AddMethod(tpl, "_eventPoll", EventPoll);
AddMethod(tpl, "setReplayGainMode", SetReplayGainMode);
AddMethod(tpl, "setReplayGainPreamp", SetReplayGainPreamp);
AddMethod(tpl, "getReplayGainPreamp", GetReplayGainPreamp);
AddMethod(tpl, "setReplayGainDefault", SetReplayGainDefault);
AddMethod(tpl, "getReplayGainDefault", GetReplayGainDefault);
constructor = Persistent<Function>::New(tpl->GetFunction());
}
Handle<Value> GNPlayer::New(const Arguments& args) {
HandleScope scope;
GNPlayer *obj = new GNPlayer();
obj->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value> GNPlayer::NewInstance(GroovePlayer *player) {
HandleScope scope;
Local<Object> instance = constructor->NewInstance();
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(instance);
gn_player->player = player;
return scope.Close(instance);
}
Handle<Value> GNPlayer::Play(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
groove_player_play(gn_player->player);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Playlist(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
Local<Array> playlist = Array::New();
GroovePlaylistItem *item = gn_player->player->playlist_head;
int i = 0;
while (item) {
playlist->Set(Number::New(i), GNPlaylistItem::NewInstance(item));
item = item->next;
}
return scope.Close(playlist);
}
Handle<Value> GNPlayer::Pause(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
groove_player_pause(gn_player->player);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Seek(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
GNPlaylistItem *gn_playlist_item =
node::ObjectWrap::Unwrap<GNPlaylistItem>(args[0]->ToObject());
double pos = args[1]->NumberValue();
groove_player_seek(gn_player->player, gn_playlist_item->playlist_item, pos);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Insert(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
GNFile *gn_file = node::ObjectWrap::Unwrap<GNFile>(args[0]->ToObject());
GroovePlaylistItem *item = NULL;
if (!args[1]->IsNull() && !args[1]->IsUndefined()) {
GNPlaylistItem *gn_pl_item =
node::ObjectWrap::Unwrap<GNPlaylistItem>(args[1]->ToObject());
item = gn_pl_item->playlist_item;
}
groove_player_insert(gn_player->player, gn_file->file, item);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Remove(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
GNPlaylistItem *gn_pl_item = node::ObjectWrap::Unwrap<GNPlaylistItem>(args[0]->ToObject());
groove_player_remove(gn_player->player, gn_pl_item->playlist_item);
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Position(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
GroovePlaylistItem *item;
double pos;
groove_player_position(gn_player->player, &item, &pos);
Local<Object> obj = Object::New();
obj->Set(String::NewSymbol("pos"), Number::New(pos));
obj->Set(String::NewSymbol("item"), GNPlaylistItem::NewInstance(item));
return scope.Close(obj);
}
Handle<Value> GNPlayer::Playing(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Clear(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::Count(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::EventPoll(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
int ret = groove_player_event_poll(gn_player->player, gn_player->event);
return scope.Close(Number::New(ret > 0 ? gn_player->event->type : -1));
}
Handle<Value> GNPlayer::SetReplayGainMode(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::SetReplayGainPreamp(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::GetReplayGainPreamp(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::SetReplayGainDefault(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
Handle<Value> GNPlayer::GetReplayGainDefault(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
fprintf(stderr, "TODO: implement\n");
return scope.Close(Undefined());
}
struct CreateReq {
uv_work_t req;
GroovePlayer *player;
Persistent<Function> callback;
};
static void CreateAsync(uv_work_t *req) {
CreateReq *r = reinterpret_cast<CreateReq *>(req->data);
r->player = groove_create_player();
}
static void CreateAfter(uv_work_t *req) {
HandleScope scope;
CreateReq *r = reinterpret_cast<CreateReq *>(req->data);
const unsigned argc = 2;
Handle<Value> argv[argc];
if (r->player) {
argv[0] = Null();
argv[1] = GNPlayer::NewInstance(r->player);
} else {
argv[0] = Exception::Error(String::New("create player failed"));
argv[1] = Null();
}
r->callback->Call(Context::GetCurrent()->Global(), argc, argv);
delete r;
}
Handle<Value> GNPlayer::Create(const Arguments& args) {
HandleScope scope;
if (args.Length() < 1 || !args[0]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Expected function arg[0]")));
return scope.Close(Undefined());
}
CreateReq *request = new CreateReq;
request->callback = Persistent<Function>::New(Local<Function>::Cast(args[0]));
request->req.data = request;
uv_queue_work(uv_default_loop(), &request->req, CreateAsync,
(uv_after_work_cb)CreateAfter);
return scope.Close(Undefined());
}
struct DestroyReq {
uv_work_t req;
GroovePlayer *player;
Persistent<Function> callback;
};
static void DestroyAsync(uv_work_t *req) {
DestroyReq *r = reinterpret_cast<DestroyReq *>(req->data);
groove_destroy_player(r->player);
}
static void DestroyAfter(uv_work_t *req) {
HandleScope scope;
DestroyReq *r = reinterpret_cast<DestroyReq *>(req->data);
const unsigned argc = 1;
Handle<Value> argv[argc];
argv[0] = Null();
r->callback->Call(Context::GetCurrent()->Global(), argc, argv);
delete r;
}
Handle<Value> GNPlayer::Destroy(const Arguments& args) {
HandleScope scope;
GNPlayer *gn_player = node::ObjectWrap::Unwrap<GNPlayer>(args.This());
if (args.Length() < 1 || !args[0]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Expected function arg[0]")));
return scope.Close(Undefined());
}
DestroyReq *request = new DestroyReq;
request->callback = Persistent<Function>::New(Local<Function>::Cast(args[0]));
request->player = gn_player->player;
request->req.data = request;
uv_queue_work(uv_default_loop(), &request->req, DestroyAsync,
(uv_after_work_cb)DestroyAfter);
return scope.Close(Undefined());
}
<|endoftext|> |
<commit_before>
#include <sstream>
#include <boost/foreach.hpp>
#include <H5Cpp.h>
#include "scsi/h5writer.h"
#include "scsi/h5loader.h"
// H5::Exception doesn't derive from std::exception
// so translate to some type which does.
// TODO: sub-class mixing H5::Exception and std::exception?
#define CATCH() catch(H5::Exception& he) { \
std::ostringstream strm; \
strm<<"H5 Error "<<he.getDetailMsg(); \
throw std::runtime_error(strm.str()); \
}
namespace {
struct StateElement {
unsigned idx;
StateBase::ArrayInfo info;
H5::DataSet dset;
std::vector<hsize_t> shape;
H5::DataSpace memspace;
};
}
struct H5StateWriter::Pvt {
H5::H5File file;
H5::Group group;
std::vector<StateElement> elements;
};
H5StateWriter::H5StateWriter() :pvt(new Pvt) {}
H5StateWriter::H5StateWriter(const char *spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::H5StateWriter(const std::string& spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::~H5StateWriter()
{
try{
close();
} catch(...) {
delete pvt;
throw;
}
delete pvt;
}
void H5StateWriter::open(const char *spec)
{
open(std::string(spec));
}
void H5StateWriter::open(const std::string& spec)
{
try {
close();
/* The provided spec may contain both file path and group(s)
* seperated by '/' which is ambigious as the file path
* may contain '/' as well...
* so do as h5ls does and strip off from the right hand side until
* and try to open while '/' remain.
*/
size_t sep = spec.npos;
while(true) {
sep = spec.find_last_of('/', sep-1);
std::string fname(spec.substr(0, sep));
try {
pvt->file.openFile(fname, H5F_ACC_RDWR|H5F_ACC_CREAT);
} catch(H5::FileIException& e) {
if(sep==spec.npos) {
// no more '/' so this is failure
throw std::runtime_error("Unable to open file");
}
continue; // keep trying
} CATCH()
if(sep!=spec.npos) {
std::string group(spec.substr(sep+1));
// delete group if it already exists
try{
H5G_stat_t stat;
pvt->file.getObjinfo(group, stat);
pvt->file.unlink(group);
} catch(H5::FileIException&) {
// ignore non-existant
}
pvt->group = pvt->file.createGroup(group);
} else {
//TODO: cleanup root?
pvt->group = pvt->file.openGroup("/");
}
return;
}
} CATCH()
}
void H5StateWriter::close()
{
try{
pvt->group.close();
pvt->file.close();
}CATCH()
}
void H5StateWriter::prepare(const StateBase *RS)
{
try {
// hack since getArray() is non-const
// we won't actually modify the state
StateBase *S = const_cast<StateBase*>(RS);
assert(pvt->elements.empty());
for(unsigned idx=0; true; idx++) {
StateBase::ArrayInfo info;
if(!S->getArray(idx, info))
break;
H5::DataType dtype;
switch(info.type) {
case StateBase::ArrayInfo::Double:
dtype = H5::DataType(H5::PredType::NATIVE_DOUBLE);
break;
case StateBase::ArrayInfo::Sizet:
if(sizeof(size_t)==8)
dtype = H5::DataType(H5::PredType::NATIVE_UINT64);
else if(sizeof(size_t)==4)
dtype = H5::DataType(H5::PredType::NATIVE_UINT32);
else
throw std::logic_error("unsupported size_t");
break;
default:
continue; // TODO string
}
StateElement elem;
elem.idx = idx;
elem.info = info;
// first dim is simulation "time"
std::vector<hsize_t> dims(info.ndim+1), maxdims(info.ndim+1);
for(size_t i=0; i<info.ndim; i++) {
maxdims[i+1] = dims[i+1] = info.dim[i];
}
elem.shape = dims; // copy
// size w/ first dim==0
dims[0] = 0;
maxdims[0] = H5S_UNLIMITED;
H5::DataSpace dspace(dims.size(), &dims[0], &maxdims[0]);
dims[0] = 10; // chunk size in "time" steps
H5::DSetCreatPropList props;
props.setChunk(dims.size(), &dims[0]);
// memspace is simple from origin to [1,shape]
dims[0] = 1;
elem.memspace = H5::DataSpace(dims.size(), &dims[0]);
elem.dset = pvt->group.createDataSet(info.name, dtype, dspace, props);
pvt->elements.push_back(elem);
}
if(pvt->elements.empty()) {
throw std::logic_error("state type has not elements to store?");
}
} CATCH()
}
void H5StateWriter::append(const StateBase *RS)
{
try {
StateBase *S = const_cast<StateBase*>(RS);
if(pvt->elements.empty())
prepare(RS);
BOOST_FOREACH(StateElement& elem, pvt->elements)
{
StateBase::ArrayInfo info;
if(!S->getArray(elem.idx, info))
throw std::logic_error("can't re-fetch state parameter?");
assert((elem.info.ndim==info.ndim) && (elem.info.type==info.type));
size_t index = elem.shape[0]; // we will write data[index,...]
elem.shape[0]++;
elem.dset.extend(&elem.shape[0]); // resize
// filespace is hyper from [index,0...] to [index,shape]
std::vector<hsize_t> start(elem.shape.size(), 0);
start[0] = index;
elem.shape[0] = 1; // reuse as count
H5::DataSpace filespace(elem.dset.getSpace());
filespace.selectHyperslab(H5S_SELECT_SET, &elem.shape[0], &start[0]);
H5::DataType dtype(elem.dset.getDataType());
elem.dset.write(info.ptr, dtype, elem.memspace, filespace);
elem.shape[0] = index+1;
}
} CATCH()
}
void H5StateWriter::setAttr(const char *name, const char *val)
{
try {
if(pvt->group.attrExists(name)) {
pvt->group.removeAttr(name);
}
{
H5::DataSpace scalar;
H5::StrType dtype(H5::PredType::C_S1, std::max((size_t)16u, strlen(val)));
H5::Attribute attr(pvt->group.createAttribute(name, dtype, scalar));
attr.write(dtype, val);
}
} CATCH()
}
void H5StateWriter::dontPrint()
{
try {
H5::Exception::dontPrint();
}CATCH()
}
<commit_msg>hdf5 compat<commit_after>
#include <sstream>
#include <boost/foreach.hpp>
#include <H5Cpp.h>
#include "scsi/h5writer.h"
#include "scsi/h5loader.h"
// H5::Exception doesn't derive from std::exception
// so translate to some type which does.
// TODO: sub-class mixing H5::Exception and std::exception?
#define CATCH() catch(H5::Exception& he) { \
std::ostringstream strm; \
strm<<"H5 Error "<<he.getDetailMsg(); \
throw std::runtime_error(strm.str()); \
}
namespace {
struct StateElement {
unsigned idx;
StateBase::ArrayInfo info;
H5::DataSet dset;
std::vector<hsize_t> shape;
H5::DataSpace memspace;
};
}
struct H5StateWriter::Pvt {
H5::H5File file;
H5::Group group;
std::vector<StateElement> elements;
};
H5StateWriter::H5StateWriter() :pvt(new Pvt) {}
H5StateWriter::H5StateWriter(const char *spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::H5StateWriter(const std::string& spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::~H5StateWriter()
{
try{
close();
} catch(...) {
delete pvt;
throw;
}
delete pvt;
}
void H5StateWriter::open(const char *spec)
{
open(std::string(spec));
}
void H5StateWriter::open(const std::string& spec)
{
try {
close();
/* The provided spec may contain both file path and group(s)
* seperated by '/' which is ambigious as the file path
* may contain '/' as well...
* so do as h5ls does and strip off from the right hand side until
* and try to open while '/' remain.
*/
size_t sep = spec.npos;
while(true) {
sep = spec.find_last_of('/', sep-1);
std::string fname(spec.substr(0, sep));
try {
pvt->file.openFile(fname, H5F_ACC_RDWR|H5F_ACC_CREAT);
} catch(H5::FileIException& e) {
if(sep==spec.npos) {
// no more '/' so this is failure
throw std::runtime_error("Unable to open file");
}
continue; // keep trying
} CATCH()
if(sep!=spec.npos) {
std::string group(spec.substr(sep+1));
// delete group if it already exists
try{
H5G_stat_t stat;
pvt->file.getObjinfo(group, stat);
pvt->file.unlink(group);
} catch(H5::FileIException&) {
// ignore non-existant
}
pvt->group = pvt->file.createGroup(group);
} else {
//TODO: cleanup root?
pvt->group = pvt->file.openGroup("/");
}
return;
}
} CATCH()
}
void H5StateWriter::close()
{
try{
pvt->group.close();
pvt->file.close();
}CATCH()
}
void H5StateWriter::prepare(const StateBase *RS)
{
try {
// hack since getArray() is non-const
// we won't actually modify the state
StateBase *S = const_cast<StateBase*>(RS);
assert(pvt->elements.empty());
for(unsigned idx=0; true; idx++) {
StateBase::ArrayInfo info;
if(!S->getArray(idx, info))
break;
H5::DataType dtype;
switch(info.type) {
case StateBase::ArrayInfo::Double:
dtype = H5::DataType(H5::PredType::NATIVE_DOUBLE);
break;
case StateBase::ArrayInfo::Sizet:
if(sizeof(size_t)==8)
dtype = H5::DataType(H5::PredType::NATIVE_UINT64);
else if(sizeof(size_t)==4)
dtype = H5::DataType(H5::PredType::NATIVE_UINT32);
else
throw std::logic_error("unsupported size_t");
break;
default:
continue; // TODO string
}
StateElement elem;
elem.idx = idx;
elem.info = info;
// first dim is simulation "time"
std::vector<hsize_t> dims(info.ndim+1), maxdims(info.ndim+1);
for(size_t i=0; i<info.ndim; i++) {
maxdims[i+1] = dims[i+1] = info.dim[i];
}
elem.shape = dims; // copy
// size w/ first dim==0
dims[0] = 0;
maxdims[0] = H5S_UNLIMITED;
H5::DataSpace dspace(dims.size(), &dims[0], &maxdims[0]);
dims[0] = 10; // chunk size in "time" steps
H5::DSetCreatPropList props;
props.setChunk(dims.size(), &dims[0]);
// memspace is simple from origin to [1,shape]
dims[0] = 1;
elem.memspace = H5::DataSpace(dims.size(), &dims[0]);
elem.dset = pvt->group.createDataSet(info.name, dtype, dspace, props);
pvt->elements.push_back(elem);
}
if(pvt->elements.empty()) {
throw std::logic_error("state type has not elements to store?");
}
} CATCH()
}
void H5StateWriter::append(const StateBase *RS)
{
try {
StateBase *S = const_cast<StateBase*>(RS);
if(pvt->elements.empty())
prepare(RS);
BOOST_FOREACH(StateElement& elem, pvt->elements)
{
StateBase::ArrayInfo info;
if(!S->getArray(elem.idx, info))
throw std::logic_error("can't re-fetch state parameter?");
assert((elem.info.ndim==info.ndim) && (elem.info.type==info.type));
size_t index = elem.shape[0]; // we will write data[index,...]
elem.shape[0]++;
elem.dset.extend(&elem.shape[0]); // resize
// filespace is hyper from [index,0...] to [index,shape]
std::vector<hsize_t> start(elem.shape.size(), 0);
start[0] = index;
elem.shape[0] = 1; // reuse as count
H5::DataSpace filespace(elem.dset.getSpace());
filespace.selectHyperslab(H5S_SELECT_SET, &elem.shape[0], &start[0]);
H5::DataType dtype(elem.dset.getDataType());
elem.dset.write(info.ptr, dtype, elem.memspace, filespace);
elem.shape[0] = index+1;
}
} CATCH()
}
void H5StateWriter::setAttr(const char *name, const char *val)
{
try {
if(H5Aexists(pvt->group.getId(), name)>0)
//if(pvt->group.attrExists(name)) // H5Aexists was added in 1.8.0, c++ wrapper wasn't added until later...
{
pvt->group.removeAttr(name);
}
{
H5::DataSpace scalar;
H5::StrType dtype(H5::PredType::C_S1, std::max((size_t)16u, strlen(val)));
H5::Attribute attr(pvt->group.createAttribute(name, dtype, scalar));
attr.write(dtype, val);
}
} CATCH()
}
void H5StateWriter::dontPrint()
{
try {
H5::Exception::dontPrint();
}CATCH()
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
//#include <string.h>
#include <set>
#include <vector>
#include "http/json.hpp"
#include "stl_utils.hpp"
#include "utils.hpp"
#include "containers/archive/stl_types.hpp"
#ifndef NDEBUG
std::string (*cJSON_default_print)(cJSON *json) = cJSON_print_std_string;
#else
std::string (*cJSON_default_print)(cJSON *json) = cJSON_print_unformatted_std_string;
#endif
http_res_t http_json_res(cJSON *json) {
return http_res_t(HTTP_OK, "application/json", cJSON_default_print(json));
}
scoped_cJSON_t::scoped_cJSON_t(cJSON *_val)
: val(_val)
{ }
scoped_cJSON_t::~scoped_cJSON_t() {
if (val) {
cJSON_Delete(val);
}
}
/* Render a cJSON entity to text for transfer/storage. */
std::string scoped_cJSON_t::Print() const {
char *s = cJSON_Print(val);
std::string res(s);
free(s);
return res;
}
/* Render a cJSON entity to text for transfer/storage without any formatting. */
std::string scoped_cJSON_t::PrintUnformatted() const {
char *s = cJSON_PrintUnformatted(val);
std::string res(s);
free(s);
return res;
}
cJSON *scoped_cJSON_t::get() const {
return val;
}
cJSON *scoped_cJSON_t::release() {
cJSON *tmp = val;
val = NULL;
return tmp;
}
void scoped_cJSON_t::reset(cJSON *v) {
if (val) {
cJSON_Delete(val);
}
val = v;
}
copyable_cJSON_t::copyable_cJSON_t(cJSON *_val)
: val(_val)
{ }
copyable_cJSON_t::copyable_cJSON_t(const copyable_cJSON_t &other)
: val(cJSON_DeepCopy(other.val))
{ }
copyable_cJSON_t::~copyable_cJSON_t() {
cJSON_Delete(val);
}
cJSON *copyable_cJSON_t::get() const {
return val;
}
json_iterator_t::json_iterator_t(cJSON *target) {
node = target->child;
}
cJSON *json_iterator_t::next() {
cJSON *res = node;
if (node) {
node = node->next;
}
return res;
}
json_object_iterator_t::json_object_iterator_t(cJSON *target)
: json_iterator_t(target)
{
rassert(target->type == cJSON_Object);
}
json_array_iterator_t::json_array_iterator_t(cJSON *target)
: json_iterator_t(target)
{
rassert(target->type == cJSON_Array);
}
std::string cJSON_print_std_string(cJSON *json) {
char *s = cJSON_Print(json);
std::string res(s);
free(s);
return res;
}
std::string cJSON_print_unformatted_std_string(cJSON *json) {
char *s = cJSON_PrintUnformatted(json);
std::string res(s);
free(s);
return res;
}
void project(cJSON *json, std::set<std::string> keys) {
rassert(json->type == cJSON_Object);
json_object_iterator_t it(json);
std::vector<std::string> keys_to_delete;
while (cJSON *node = it.next()) {
std::string str(node->string);
if (!std_contains(keys, str)) {
keys_to_delete.push_back(str);
}
}
for (std::vector<std::string>::iterator it = keys_to_delete.begin();
it != keys_to_delete.end();
++it) {
cJSON_DeleteItemFromObject(json, it->c_str());
}
}
cJSON *merge(cJSON *x, cJSON *y) {
cJSON *res = cJSON_CreateObject();
json_object_iterator_t xit(x), yit(y);
std::set<std::string> keys;
cJSON *hd;
while ((hd = xit.next())) {
keys.insert(hd->string);
}
for (std::set<std::string>::iterator it = keys.begin();
it != keys.end();
++it) {
cJSON_AddItemToObject(res, it->c_str(), cJSON_DetachItemFromObject(x, it->c_str()));
}
keys.clear();
while ((hd = yit.next())) {
keys.insert(hd->string);
}
for (std::set<std::string>::iterator it = keys.begin();
it != keys.end();
++it) {
rassert(!cJSON_GetObjectItem(res, it->c_str()), "Overlapping names in merge, name was: %s\n", it->c_str());
cJSON_AddItemToObject(res, it->c_str(), cJSON_DetachItemFromObject(y, it->c_str()));
}
return res;
}
write_message_t &operator<<(write_message_t &msg, const cJSON &cjson) {
msg << cjson.type;
switch(cjson.type) {
case cJSON_False:
break;
case cJSON_True:
break;
case cJSON_NULL:
break;
case cJSON_Number:
msg << cjson.valuedouble;
break;
case cJSON_String:
{
std::string s(cjson.valuestring);
msg << s;
}
break;
case cJSON_Array:
case cJSON_Object:
{
msg << cJSON_GetArraySize(&cjson);
cJSON *hd = cjson.child;
while (hd) {
if (cjson.type == cJSON_Object) {
msg << std::string(hd->string);
}
msg << *hd;
hd = hd->next;
}
}
break;
default:
crash("Unreachable");
break;
}
return msg;
}
#define CHECK_RES(res) if (res != ARCHIVE_SUCCESS) {\
return res;\
}
MUST_USE archive_result_t deserialize(read_stream_t *s, cJSON *cjson) {
archive_result_t res = deserialize(s, &cjson->type);
CHECK_RES(res);
switch (cjson->type) {
case cJSON_False:
case cJSON_True:
case cJSON_NULL:
return ARCHIVE_SUCCESS;
break;
case cJSON_Number:
res = deserialize(s, &cjson->valuedouble);
CHECK_RES(res);
cjson->valueint = cjson->valuedouble;
return ARCHIVE_SUCCESS;
break;
case cJSON_String:
{
std::string str;
res = deserialize(s, &str);
CHECK_RES(res);
cjson->valuestring = strdup(str.c_str());
return ARCHIVE_SUCCESS;
}
break;
case cJSON_Array:
{
int size;
res = deserialize(s, &size);
CHECK_RES(res);
for (int i = 0; i < size; ++i) {
cJSON *item = cJSON_CreateBlank();
res = deserialize(s, item);
CHECK_RES(res);
cJSON_AddItemToArray(cjson, item);
}
return ARCHIVE_SUCCESS;
}
break;
case cJSON_Object:
{
int size;
res = deserialize(s, &size);
CHECK_RES(res);
for (int i = 0; i < size; ++i) {
//grab the key
std::string key;
res = deserialize(s, &key);
CHECK_RES(res);
//grab the item
cJSON *item = cJSON_CreateBlank();
res = deserialize(s, item);
CHECK_RES(res);
cJSON_AddItemToObject(cjson, key.c_str(), item);
}
return ARCHIVE_SUCCESS;
}
break;
default:
crash("Unreachable");
break;
}
}
write_message_t &operator<<(write_message_t &msg, const boost::shared_ptr<scoped_cJSON_t> &cjson) {
rassert(NULL != cjson.get() && NULL != cjson->get());
msg << *cjson->get();
return msg;
}
MUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr<scoped_cJSON_t> *cjson) {
cJSON *data = cJSON_CreateBlank();
archive_result_t res = deserialize(s, data);
CHECK_RES(res);
*cjson = boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(data));
return ARCHIVE_SUCCESS;
}
<commit_msg>Fixed a compile warning in a place where we convert double to int.<commit_after>#include <stdlib.h>
//#include <string.h>
#include <set>
#include <vector>
#include "http/json.hpp"
#include "stl_utils.hpp"
#include "utils.hpp"
#include "containers/archive/stl_types.hpp"
#ifndef NDEBUG
std::string (*cJSON_default_print)(cJSON *json) = cJSON_print_std_string;
#else
std::string (*cJSON_default_print)(cJSON *json) = cJSON_print_unformatted_std_string;
#endif
http_res_t http_json_res(cJSON *json) {
return http_res_t(HTTP_OK, "application/json", cJSON_default_print(json));
}
scoped_cJSON_t::scoped_cJSON_t(cJSON *_val)
: val(_val)
{ }
scoped_cJSON_t::~scoped_cJSON_t() {
if (val) {
cJSON_Delete(val);
}
}
/* Render a cJSON entity to text for transfer/storage. */
std::string scoped_cJSON_t::Print() const {
char *s = cJSON_Print(val);
std::string res(s);
free(s);
return res;
}
/* Render a cJSON entity to text for transfer/storage without any formatting. */
std::string scoped_cJSON_t::PrintUnformatted() const {
char *s = cJSON_PrintUnformatted(val);
std::string res(s);
free(s);
return res;
}
cJSON *scoped_cJSON_t::get() const {
return val;
}
cJSON *scoped_cJSON_t::release() {
cJSON *tmp = val;
val = NULL;
return tmp;
}
void scoped_cJSON_t::reset(cJSON *v) {
if (val) {
cJSON_Delete(val);
}
val = v;
}
copyable_cJSON_t::copyable_cJSON_t(cJSON *_val)
: val(_val)
{ }
copyable_cJSON_t::copyable_cJSON_t(const copyable_cJSON_t &other)
: val(cJSON_DeepCopy(other.val))
{ }
copyable_cJSON_t::~copyable_cJSON_t() {
cJSON_Delete(val);
}
cJSON *copyable_cJSON_t::get() const {
return val;
}
json_iterator_t::json_iterator_t(cJSON *target) {
node = target->child;
}
cJSON *json_iterator_t::next() {
cJSON *res = node;
if (node) {
node = node->next;
}
return res;
}
json_object_iterator_t::json_object_iterator_t(cJSON *target)
: json_iterator_t(target)
{
rassert(target->type == cJSON_Object);
}
json_array_iterator_t::json_array_iterator_t(cJSON *target)
: json_iterator_t(target)
{
rassert(target->type == cJSON_Array);
}
std::string cJSON_print_std_string(cJSON *json) {
char *s = cJSON_Print(json);
std::string res(s);
free(s);
return res;
}
std::string cJSON_print_unformatted_std_string(cJSON *json) {
char *s = cJSON_PrintUnformatted(json);
std::string res(s);
free(s);
return res;
}
void project(cJSON *json, std::set<std::string> keys) {
rassert(json->type == cJSON_Object);
json_object_iterator_t it(json);
std::vector<std::string> keys_to_delete;
while (cJSON *node = it.next()) {
std::string str(node->string);
if (!std_contains(keys, str)) {
keys_to_delete.push_back(str);
}
}
for (std::vector<std::string>::iterator it = keys_to_delete.begin();
it != keys_to_delete.end();
++it) {
cJSON_DeleteItemFromObject(json, it->c_str());
}
}
cJSON *merge(cJSON *x, cJSON *y) {
cJSON *res = cJSON_CreateObject();
json_object_iterator_t xit(x), yit(y);
std::set<std::string> keys;
cJSON *hd;
while ((hd = xit.next())) {
keys.insert(hd->string);
}
for (std::set<std::string>::iterator it = keys.begin();
it != keys.end();
++it) {
cJSON_AddItemToObject(res, it->c_str(), cJSON_DetachItemFromObject(x, it->c_str()));
}
keys.clear();
while ((hd = yit.next())) {
keys.insert(hd->string);
}
for (std::set<std::string>::iterator it = keys.begin();
it != keys.end();
++it) {
rassert(!cJSON_GetObjectItem(res, it->c_str()), "Overlapping names in merge, name was: %s\n", it->c_str());
cJSON_AddItemToObject(res, it->c_str(), cJSON_DetachItemFromObject(y, it->c_str()));
}
return res;
}
write_message_t &operator<<(write_message_t &msg, const cJSON &cjson) {
msg << cjson.type;
switch(cjson.type) {
case cJSON_False:
break;
case cJSON_True:
break;
case cJSON_NULL:
break;
case cJSON_Number:
msg << cjson.valuedouble;
break;
case cJSON_String:
{
std::string s(cjson.valuestring);
msg << s;
}
break;
case cJSON_Array:
case cJSON_Object:
{
msg << cJSON_GetArraySize(&cjson);
cJSON *hd = cjson.child;
while (hd) {
if (cjson.type == cJSON_Object) {
msg << std::string(hd->string);
}
msg << *hd;
hd = hd->next;
}
}
break;
default:
crash("Unreachable");
break;
}
return msg;
}
#define CHECK_RES(res) if (res != ARCHIVE_SUCCESS) {\
return res;\
}
MUST_USE archive_result_t deserialize(read_stream_t *s, cJSON *cjson) {
archive_result_t res = deserialize(s, &cjson->type);
CHECK_RES(res);
switch (cjson->type) {
case cJSON_False:
case cJSON_True:
case cJSON_NULL:
return ARCHIVE_SUCCESS;
break;
case cJSON_Number:
res = deserialize(s, &cjson->valuedouble);
CHECK_RES(res);
cjson->valueint = static_cast<int>(cjson->valuedouble);
return ARCHIVE_SUCCESS;
break;
case cJSON_String:
{
std::string str;
res = deserialize(s, &str);
CHECK_RES(res);
cjson->valuestring = strdup(str.c_str());
return ARCHIVE_SUCCESS;
}
break;
case cJSON_Array:
{
int size;
res = deserialize(s, &size);
CHECK_RES(res);
for (int i = 0; i < size; ++i) {
cJSON *item = cJSON_CreateBlank();
res = deserialize(s, item);
CHECK_RES(res);
cJSON_AddItemToArray(cjson, item);
}
return ARCHIVE_SUCCESS;
}
break;
case cJSON_Object:
{
int size;
res = deserialize(s, &size);
CHECK_RES(res);
for (int i = 0; i < size; ++i) {
//grab the key
std::string key;
res = deserialize(s, &key);
CHECK_RES(res);
//grab the item
cJSON *item = cJSON_CreateBlank();
res = deserialize(s, item);
CHECK_RES(res);
cJSON_AddItemToObject(cjson, key.c_str(), item);
}
return ARCHIVE_SUCCESS;
}
break;
default:
crash("Unreachable");
break;
}
}
write_message_t &operator<<(write_message_t &msg, const boost::shared_ptr<scoped_cJSON_t> &cjson) {
rassert(NULL != cjson.get() && NULL != cjson->get());
msg << *cjson->get();
return msg;
}
MUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr<scoped_cJSON_t> *cjson) {
cJSON *data = cJSON_CreateBlank();
archive_result_t res = deserialize(s, data);
CHECK_RES(res);
*cjson = boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(data));
return ARCHIVE_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "instance.h"
/*void Instance::set_id(int i){
id = i;
}
void Instance::set_task_number(int t){
tasks_number = t;
}*/
void Instance::generate_instance(int quantity, int max_time, int identifier, bool verbose){
srand(time(NULL));
id = identifier;
tasks_number = quantity;
int t1_1, t1_2, rt, mt, opt;
Task t;
for (int i = 0; i < quantity; i++){
t1_1 = rand() % max_time+1;
t1_2 = rand() % max_time+1;
if ( i < quantity/2 ){
rt = 0;
}
else{
rt = rand() % ((max_time*(quantity/4))+1);
}
t.set_op_time(1, t1_1);
t.set_op_time(2, t1_2);
t.set_rt(rt);
task_v.push_back(t);
//debug only:
if (verbose == true){
std::cout << t1_1 << ";" << t1_2 << ";" << 1 << ";" << 2 << ";" << rt <<';'<< endl;
}
}
if (verbose == true){
std::cout << "---------------------------------------------------------------------------\n";
}
Maitenance m;
for (int i = 0; i < quantity/5; i++){
mt = rand() % (max_time /2 ) + 1;
opt = mt + max_time * i;
m.set_mt(mt);
m.set_opt(opt);
m.set_id(i);
if (verbose == true){
std::cout << i << ';' << 1 << ';' << opt << ';' << mt << ';' << endl;
}
maitenance_v.push_back(m);
}
}
void Instance::dump_instance(string filename){
ofstream file(filename.c_str());
//file.open(filename.c_str());
if (file.good() == true){
file << "****" << id << "****\n";
file << tasks_number << endl;
for(vector<int>::size_type i = 0; i < task_v.size(); i++){
file << task_v[i].get_op_time(1) << ";" << task_v[i].get_op_time(2) << ";" << "1" <<";" << "2" << ";" << task_v[i].get_rt() << ";" << endl;
}
for (vector<int>::size_type i = 0; i < maitenance_v.size(); i++){
file << maitenance_v[i].get_id() <<';' << 1 << ";" << maitenance_v[i].get_opt() << ";" << maitenance_v[i].get_mt() << ";" << endl;
}
}
else{
cerr<<"Cannot open and write to instance file!\n";
exit(-1);
}
clear_all();
}
void Instance::read_instance(string filename){
string s;
int quantity, tmp;
Task t;
Maitenance m;
fstream file;
file.open(filename.c_str());
if(file.good() == true){
getline(file, s); //ignoring one line
getline(file, s);
quantity = atoi(s.c_str());
std::cout << quantity << endl;
for (int i = 0; i < quantity; i++){
getline(file, s, ';');
tmp = atoi(s.c_str());
t.set_op_time(1, tmp);
getline(file, s, ';');
tmp = atoi(s.c_str());
t.set_op_time(2,tmp);
getline(file, s, ';'); //ignoring two lines
getline(file, s, ';');
getline(file, s, ';');
tmp = atoi(s.c_str());
t.set_rt(tmp);
task_v.push_back(t);
std::cout << t.get_op_time(1) << ";" << t.get_op_time(2) << ";" << "1" <<";" << "2" << ";" << t.get_rt() << ";" << endl;
}
for(int i = 0; i < quantity/5; i++){
getline(file, s, ';');
tmp = atoi(s.c_str());
m.set_id(tmp);
getline(file, s, ';'); // ignoring machine number
getline(file, s, ';');
tmp = atoi(s.c_str());
m.set_opt(tmp);
getline(file, s, ';');
tmp = atoi(s.c_str());
m.set_mt(tmp);
maitenance_v.push_back(m);
std::cout << m.get_id() << ";" << m.get_opt() << ";" << m.get_mt() << ";" << endl;
}
}
else{
cerr <<"Cannot open and read instance file!\n";
exit(-1);
}
}
void Instance::clear_task_v(){
task_v.clear();
}
void Instance::clear_maitenance_v(){
maitenance_v.clear();
}
void Instance::clear_all(){
clear_task_v();
clear_maitenance_v();
}
<commit_msg>Generate instance minor changes & fixes<commit_after>#include "instance.h"
/*void Instance::set_id(int i){
id = i;
}
void Instance::set_task_number(int t){
tasks_number = t;
}*/
void Instance::generate_instance(int quantity, int max_time, int identifier, bool verbose){
srand(time(NULL));
id = identifier;
tasks_number = quantity;
int t1_1, t1_2, rt, mt, opt;
Task t;
for (int i = 0; i < quantity; i++){
t1_1 = rand() % max_time+1;
t1_2 = rand() % max_time+1;
if ( i < quantity/2 ){
rt = 0;
}
else{
rt = rand() % ((max_time*(quantity/4))+1);
}
t.set_op_time(1, t1_1);
t.set_op_time(2, t1_2);
t.set_rt(rt);
task_v.push_back(t);
//debug only:
if (verbose == true){
std::cout << t1_1 << ";" << t1_2 << ";" << 1 << ";" << 2 << ";" << rt <<';'<< endl;
}
}
if (verbose == true){
std::cout << "---------------------------------------------------------------------------\n";
}
Maitenance m;
for (int i = 0; i < quantity/5; i++){
mt = rand() % (max_time /2 ) + 1;
opt = mt + max_time * i;
m.set_mt(mt);
m.set_opt(opt);
m.set_id(i);
if (verbose == true){
std::cout << i << ';' << 1 << ';' << opt << ';' << mt << ';' << endl;
}
maitenance_v.push_back(m);
}
}
void Instance::dump_instance(string filename){
ofstream file(filename.c_str());
//file.open(filename.c_str());
if (file.good() == true){
file << "****" << id << "****\n";
file << tasks_number << endl;
for(vector<int>::size_type i = 0; i < task_v.size(); i++){
file << task_v[i].get_op_time(1) << ";" << task_v[i].get_op_time(2) << ";" << "1" <<";" << "2" << ";" << task_v[i].get_rt() << ";" << endl;
}
for (vector<int>::size_type i = 0; i < maitenance_v.size(); i++){
file << maitenance_v[i].get_id() <<';' << 1 << ";" << maitenance_v[i].get_opt() << ";" << maitenance_v[i].get_mt() << ";" << endl;
}
}
else{
cerr<<"Cannot open and write to instance file!\n";
exit(-1);
}
file.close();
clear_all();
}
void Instance::read_instance(string filename){
string s;
int quantity, tmp;
Task t;
Maitenance m;
fstream file;
file.open(filename.c_str());
if(file.good() == true){
getline(file, s); //ignoring one line
getline(file, s);
quantity = atoi(s.c_str());
std::cout << quantity << endl;
for (int i = 0; i < quantity; i++){
getline(file, s, ';');
tmp = atoi(s.c_str());
t.set_op_time(1, tmp);
getline(file, s, ';');
tmp = atoi(s.c_str());
t.set_op_time(2,tmp);
getline(file, s, ';'); //ignoring two lines
getline(file, s, ';');
getline(file, s, ';');
tmp = atoi(s.c_str());
t.set_rt(tmp);
task_v.push_back(t);
//std::cout << t.get_op_time(1) << ";" << t.get_op_time(2) << ";" << "1" <<";" << "2" << ";" << t.get_rt() << ";" << endl;
}
for(int i = 0; i < quantity/5; i++){
getline(file, s, ';');
tmp = atoi(s.c_str());
m.set_id(tmp);
getline(file, s, ';'); // ignoring machine number
getline(file, s, ';');
tmp = atoi(s.c_str());
m.set_opt(tmp);
getline(file, s, ';');
tmp = atoi(s.c_str());
m.set_mt(tmp);
maitenance_v.push_back(m);
//std::cout << m.get_id() << ";" << m.get_opt() << ";" << m.get_mt() << ";" << endl;
}
}
else{
cerr <<"Cannot open and read instance file!\n";
exit(-1);
}
file.close();
}
void Instance::clear_task_v(){
task_v.clear();
}
void Instance::clear_maitenance_v(){
maitenance_v.clear();
}
void Instance::clear_all(){
clear_task_v();
clear_maitenance_v();
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* common headers */
#include "common.h"
#ifdef HAVE_SDL
/* interface headers */
#include "SDLJoystick.h"
/* implementation headers */
#include "ErrorHandler.h"
#include "bzfSDL.h"
SDLJoystick::SDLJoystick() : joystickID(NULL)
{
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) {
std::vector<std::string> args;
args.push_back(SDL_GetError());
printError("Could not initialize SDL Joystick subsystem: %s.\n", &args);
};
}
SDLJoystick::~SDLJoystick()
{
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
}
void SDLJoystick::initJoystick(const char* joystickName)
{
if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) {
if (joystickID != NULL) {
SDL_JoystickClose(joystickID);
joystickID = NULL;
}
return;
}
int numJoystick = SDL_NumJoysticks();
if (!numJoystick) {
printError("No supported SDL joysticks were found.");
joystickID = NULL;
return;
}
int i;
for (i = 0; i < numJoystick; i++)
if (strcmp(SDL_JoystickName(i), joystickName) == 0)
break;
if (i >= numJoystick)
i = 0;
joystickID = SDL_JoystickOpen(i);
if (joystickID == NULL)
return;
if (SDL_JoystickNumAxes(joystickID) < 2) {
SDL_JoystickClose(joystickID);
printError("Joystick has less then 2 axis:\n");
joystickID = NULL;
return;
}
joystickButtons = SDL_JoystickNumButtons(joystickID);
}
bool SDLJoystick::joystick() const
{
return joystickID != NULL;
}
void SDLJoystick::getJoy(int& x, int& y) const
{
x = y = 0;
if (!joystickID)
return;
SDL_JoystickUpdate();
x = SDL_JoystickGetAxis(joystickID, 0);
y = SDL_JoystickGetAxis(joystickID, 1);
x = x * 1000 / 32768;
y = y * 1000 / 32768;
// ballistic
x = (x * abs(x)) / 1000;
y = (y * abs(y)) / 1000;
}
unsigned long SDLJoystick::getJoyButtons() const
{
unsigned long buttons = 0;
if (!joystickID)
return 0;
SDL_JoystickUpdate();
for (int i = 0; i < joystickButtons; i++)
buttons |= SDL_JoystickGetButton(joystickID, i) << i;
return buttons;
}
void SDLJoystick::getJoyDevices(std::vector<std::string>
&list) const
{
int numJoystick = SDL_NumJoysticks();
int i;
for (i = 0; i < numJoystick; i++)
list.push_back(SDL_JoystickName(i));
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Allowing to choose from similar joysticks<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* common headers */
#include "common.h"
#ifdef HAVE_SDL
/* interface headers */
#include "SDLJoystick.h"
/* implementation headers */
#include "ErrorHandler.h"
#include "bzfSDL.h"
SDLJoystick::SDLJoystick() : joystickID(NULL)
{
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) {
std::vector<std::string> args;
args.push_back(SDL_GetError());
printError("Could not initialize SDL Joystick subsystem: %s.\n", &args);
};
}
SDLJoystick::~SDLJoystick()
{
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
}
void SDLJoystick::initJoystick(const char* joystickName)
{
if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) {
if (joystickID != NULL) {
SDL_JoystickClose(joystickID);
joystickID = NULL;
}
return;
}
char num = joystickName[0];
int i = (int)num - '0';
if (!isdigit(num) || i >= SDL_NumJoysticks()) {
printError("No supported SDL joysticks were found.");
joystickID = NULL;
return;
}
joystickID = SDL_JoystickOpen(i);
if (joystickID == NULL)
return;
if (SDL_JoystickNumAxes(joystickID) < 2) {
SDL_JoystickClose(joystickID);
printError("Joystick has less then 2 axis:\n");
joystickID = NULL;
return;
}
joystickButtons = SDL_JoystickNumButtons(joystickID);
}
bool SDLJoystick::joystick() const
{
return joystickID != NULL;
}
void SDLJoystick::getJoy(int& x, int& y) const
{
x = y = 0;
if (!joystickID)
return;
SDL_JoystickUpdate();
x = SDL_JoystickGetAxis(joystickID, 0);
y = SDL_JoystickGetAxis(joystickID, 1);
x = x * 1000 / 32768;
y = y * 1000 / 32768;
// ballistic
x = (x * abs(x)) / 1000;
y = (y * abs(y)) / 1000;
}
unsigned long SDLJoystick::getJoyButtons() const
{
unsigned long buttons = 0;
if (!joystickID)
return 0;
SDL_JoystickUpdate();
for (int i = 0; i < joystickButtons; i++)
buttons |= SDL_JoystickGetButton(joystickID, i) << i;
return buttons;
}
void SDLJoystick::getJoyDevices(std::vector<std::string>
&list) const
{
int numJoystick = SDL_NumJoysticks();
int i;
for (i = 0; i < numJoystick; i++) {
char joystickName[256];
sprintf(joystickName, "%d - %s", i, SDL_JoystickName(i));
list.push_back(joystickName);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "main.h"
#include "base58.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
QString addressOld = "";
QString nameOld = "";
class SendCoinsDialog;
bool DoNotRegister;
extern QList<CKeyID> reserved;
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
GUIUtil::setupAddressWidget(ui->labelEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("Propose new names"));
ui->addressEdit->setEnabled(false);
ui->labelEdit->setEnabled(false);
break;
case NewNotRegisteredAddress:
setWindowTitle(tr("One can register name only by solving block"));
ui->addressEdit->setEnabled(true);
ui->labelEdit->setEnabled(true);
break;
case NewSendingAddress:
setWindowTitle(tr("One can register name only by solving block"));
ui->addressEdit->setEnabled(false);
ui->labelEdit->setEnabled(false);
break;
case EditReceivingAddress:
setWindowTitle(tr("You can edit only your addresses"));
ui->addressEdit->setEnabled(true);
ui->labelEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Names registered in PLM Network"));
ui->addressEdit->setEnabled(false);
ui->labelEdit->setEnabled(false);
break;
case EditNotRegisteredAddress:
setWindowTitle(tr("Put your name"));
ui->addressEdit->setEnabled(true);
ui->labelEdit->setEnabled(true);
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
addressOld = ui->addressEdit->text();
nameOld = ui->labelEdit->text();
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
if(yourName == "" || synchronizingComplete == false)
acceptAndDestroy();
switch(mode)
{
case NewSendingAddress:
model->noChanges();
break;
case NewReceivingAddress:
model->noChanges();
break;
case NewNotRegisteredAddress:
name = ui->labelEdit->text();
address = model->addRow(
AddressTableModel::NotRegistered,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditSendingAddress:
model->noChanges();
break;
case EditNotRegisteredAddress:
case EditReceivingAddress:
if(::IsMine(*(model->wallet),model->wallet->GetAddress(nameOld.toStdString()).Get()) == false && ::IsMine(*(model->wallet),CQcoinAddress(addressOld.toStdString()).Get()) == false)
{
return false;
}
if(mapper->submit())
{
address = ui->addressEdit->text();
name = ui->labelEdit->text();
if(model->changeName(name,address,nameOld.toStdString()) == false)
{
if(model->changeAddress(name,address,addressOld.toStdString()) == false)
{
return false;
}else{
addressOld = "";
nameOld = name;
}
}else{
nameOld = "";
}
}
if(address != addressOld && name == nameOld)
{
SendCoinsRecipient toChn;
toChn.address = address;
toChn.amount = -100;
toChn.label = name;
QList<SendCoinsRecipient> recipients;
recipients.clear();
recipients.append(toChn);
::WalletModel::UnlockContext ctx(model->walletModel->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
return false;
}
if(this->model->walletModel != NULL)
{
WalletModel::SendCoinsReturn sendstatus = this->model->walletModel->changePubKey(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the transaction fee is included."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed!"),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of myq.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
goto et7;
}
return false;
}
}else if(address == addressOld && name == nameOld)
{
return false;
}
break;
}
et7:
if(name.isEmpty())
return false;
DoNotRegister = false;
return !address.isEmpty();
}
void EditAddressDialog::acceptAndDestroy()
{
if(synchronizingComplete == false)
{
QMessageBox::warning(this,QString("Wait for synchronization !"),"Synchronization with network is in progress ...", QMessageBox::Ok);
return;
}
QString name((const char *)yourName.c_str());
CQcoinAddress qaddress((CKeyID)(model->wallet->vchDefaultKey.GetID()));
QString address((const char *)(qaddress.ToString().c_str()));
while(name == "")
{
sleep(2);
name = ui->labelEdit->text();
if(name != "")
{
if(model->changeName(name,address,"") == false)
{
QMessageBox::warning(this,QString("Could not register name !"),QString("%1 is existing in network").arg(name), QMessageBox::Ok);
name = "";
return;
}
}else{
QMessageBox::warning(this,QString("Could not register name !"),QString("Name cannot be empty string!").arg(name), QMessageBox::Ok);
return;
}
}
yourName =name.toStdString();
this->hide();
}
void EditAddressDialog::accept()
{
if(!model)
return;
DoNotRegister = ui->DoNotRegisterChb->isChecked();
model->setEditStatus(AddressTableModel::NO_CHANGES);
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
if (minerThreads != NULL)
{
minerThreads->interrupt_all();
delete minerThreads;
minerThreads = NULL;
}
minerThreads = new boost::thread_group();
minerThreads->create_thread(boost::bind(&RestartMining));
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Mark address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<commit_msg>sleep<commit_after>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "main.h"
#include "base58.h"
#include "boost/thread.hpp"
#include <QDataWidgetMapper>
#include <QMessageBox>
QString addressOld = "";
QString nameOld = "";
class SendCoinsDialog;
bool DoNotRegister;
extern QList<CKeyID> reserved;
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
GUIUtil::setupAddressWidget(ui->labelEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("Propose new names"));
ui->addressEdit->setEnabled(false);
ui->labelEdit->setEnabled(false);
break;
case NewNotRegisteredAddress:
setWindowTitle(tr("One can register name only by solving block"));
ui->addressEdit->setEnabled(true);
ui->labelEdit->setEnabled(true);
break;
case NewSendingAddress:
setWindowTitle(tr("One can register name only by solving block"));
ui->addressEdit->setEnabled(false);
ui->labelEdit->setEnabled(false);
break;
case EditReceivingAddress:
setWindowTitle(tr("You can edit only your addresses"));
ui->addressEdit->setEnabled(true);
ui->labelEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Names registered in PLM Network"));
ui->addressEdit->setEnabled(false);
ui->labelEdit->setEnabled(false);
break;
case EditNotRegisteredAddress:
setWindowTitle(tr("Put your name"));
ui->addressEdit->setEnabled(true);
ui->labelEdit->setEnabled(true);
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
addressOld = ui->addressEdit->text();
nameOld = ui->labelEdit->text();
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
if(yourName == "" || synchronizingComplete == false)
acceptAndDestroy();
switch(mode)
{
case NewSendingAddress:
model->noChanges();
break;
case NewReceivingAddress:
model->noChanges();
break;
case NewNotRegisteredAddress:
name = ui->labelEdit->text();
address = model->addRow(
AddressTableModel::NotRegistered,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditSendingAddress:
model->noChanges();
break;
case EditNotRegisteredAddress:
case EditReceivingAddress:
if(::IsMine(*(model->wallet),model->wallet->GetAddress(nameOld.toStdString()).Get()) == false && ::IsMine(*(model->wallet),CQcoinAddress(addressOld.toStdString()).Get()) == false)
{
return false;
}
if(mapper->submit())
{
address = ui->addressEdit->text();
name = ui->labelEdit->text();
if(model->changeName(name,address,nameOld.toStdString()) == false)
{
if(model->changeAddress(name,address,addressOld.toStdString()) == false)
{
return false;
}else{
addressOld = "";
nameOld = name;
}
}else{
nameOld = "";
}
}
if(address != addressOld && name == nameOld)
{
SendCoinsRecipient toChn;
toChn.address = address;
toChn.amount = -100;
toChn.label = name;
QList<SendCoinsRecipient> recipients;
recipients.clear();
recipients.append(toChn);
::WalletModel::UnlockContext ctx(model->walletModel->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
return false;
}
if(this->model->walletModel != NULL)
{
WalletModel::SendCoinsReturn sendstatus = this->model->walletModel->changePubKey(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the transaction fee is included."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed!"),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of myq.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
goto et7;
}
return false;
}
}else if(address == addressOld && name == nameOld)
{
return false;
}
break;
}
et7:
if(name.isEmpty())
return false;
DoNotRegister = false;
return !address.isEmpty();
}
void EditAddressDialog::acceptAndDestroy()
{
if(synchronizingComplete == false)
{
QMessageBox::warning(this,QString("Wait for synchronization !"),"Synchronization with network is in progress ...", QMessageBox::Ok);
return;
}
QString name((const char *)yourName.c_str());
CQcoinAddress qaddress((CKeyID)(model->wallet->vchDefaultKey.GetID()));
QString address((const char *)(qaddress.ToString().c_str()));
while(name == "")
{
sleep(2);
name = ui->labelEdit->text();
if(name != "")
{
if(model->changeName(name,address,"") == false)
{
QMessageBox::warning(this,QString("Could not register name !"),QString("%1 is existing in network").arg(name), QMessageBox::Ok);
name = "";
return;
}
}else{
QMessageBox::warning(this,QString("Could not register name !"),QString("Name cannot be empty string!").arg(name), QMessageBox::Ok);
return;
}
}
yourName =name.toStdString();
this->hide();
}
void EditAddressDialog::accept()
{
if(!model)
return;
DoNotRegister = ui->DoNotRegisterChb->isChecked();
model->setEditStatus(AddressTableModel::NO_CHANGES);
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
if (minerThreads != NULL)
{
minerThreads->interrupt_all();
delete minerThreads;
minerThreads = NULL;
}
minerThreads = new boost::thread_group();
minerThreads->create_thread(boost::bind(&RestartMining));
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Mark address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<|endoftext|> |
<commit_before>/*
* RInterface.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef R_INTERFACE_HPP
#define R_INTERFACE_HPP
#include <string>
#include <setjmp.h>
#ifdef _WIN32
#include <R_ext/Boolean.h>
#include <R_ext/RStartup.h>
extern "C" void R_RestoreGlobalEnvFromFile(const char *, Rboolean);
extern "C" void R_SaveGlobalEnvToFile(const char *);
extern "C" void R_Suicide(const char *);
extern "C" char *R_HomeDir(void);
extern "C" void Rf_jump_to_toplevel(void);
extern "C" void Rf_onintr(void);
#define R_ClearerrConsole void
extern "C" void R_FlushConsole();
extern "C" int R_SignalHandlers;
extern "C" void run_Rmainloop();
extern "C" void Rf_mainloop(void);
extern "C" void* R_GlobalContext;
typedef struct SEXPREC *SEXP;
#else
#define R_INTERFACE_PTRS 1
#include <Rinterface.h>
#endif
typedef struct RCNTXT {
struct RCNTXT *nextcontext;
int callflag;
#ifdef _WIN32
jmp_buf cmpbuf;
#else
sigjmp_buf cjmpbuf;
#endif
int cstacktop;
int evaldepth;
SEXP promargs;
SEXP callfun;
SEXP sysparent;
SEXP call;
SEXP cloenv;
SEXP conexit;
void (*cend)(void *);
void *cenddata;
void *vmax;
int intsusp;
SEXP handlerstack;
SEXP restartstack;
struct RPRSTACK *prstack;
SEXP *nodestack;
#ifdef BC_INT_STACK
IStackval *intstack;
#endif
SEXP srcref;
} RCNTXT, *context;
enum {
CTXT_TOPLEVEL = 0,
CTXT_NEXT = 1,
CTXT_BREAK = 2,
CTXT_LOOP = 3,
CTXT_FUNCTION = 4,
CTXT_CCODE = 8,
CTXT_RETURN = 12,
CTXT_BROWSER = 16,
CTXT_GENERIC = 20,
CTXT_RESTART = 32,
CTXT_BUILTIN = 64
};
namespace r {
inline RCNTXT* getGlobalContext()
{
return static_cast<RCNTXT*>(R_GlobalContext);
}
} // namespace r
#endif // R_INTERFACE_HPP
<commit_msg>fix mismatched RCNTXT memory layout on Windows<commit_after>/*
* RInterface.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef R_INTERFACE_HPP
#define R_INTERFACE_HPP
#include <string>
#include <setjmp.h>
#ifdef _WIN32
#include <R_ext/Boolean.h>
#include <R_ext/RStartup.h>
extern "C" void R_RestoreGlobalEnvFromFile(const char *, Rboolean);
extern "C" void R_SaveGlobalEnvToFile(const char *);
extern "C" void R_Suicide(const char *);
extern "C" char *R_HomeDir(void);
extern "C" void Rf_jump_to_toplevel(void);
extern "C" void Rf_onintr(void);
#define R_ClearerrConsole void
extern "C" void R_FlushConsole();
extern "C" int R_SignalHandlers;
extern "C" void run_Rmainloop();
extern "C" void Rf_mainloop(void);
extern "C" void* R_GlobalContext;
typedef struct SEXPREC *SEXP;
#else
#define R_INTERFACE_PTRS 1
#include <Rinterface.h>
#endif
typedef struct RCNTXT {
struct RCNTXT *nextcontext;
int callflag;
#ifdef _WIN32
// on Windows, the size of the buffer used by R is larger than the one
// declared in setjmp.h; we need to match this size exactly so the rest of
// the structure layout in memory is valid.
_JBTYPE cjmpbuf[_JBLEN + 2];
#else
sigjmp_buf cjmpbuf;
#endif
int cstacktop;
int evaldepth;
SEXP promargs;
SEXP callfun;
SEXP sysparent;
SEXP call;
SEXP cloenv;
SEXP conexit;
void (*cend)(void *);
void *cenddata;
void *vmax;
int intsusp;
SEXP handlerstack;
SEXP restartstack;
struct RPRSTACK *prstack;
SEXP *nodestack;
#ifdef BC_INT_STACK
IStackval *intstack;
#endif
SEXP srcref;
} RCNTXT, *context;
enum {
CTXT_TOPLEVEL = 0,
CTXT_NEXT = 1,
CTXT_BREAK = 2,
CTXT_LOOP = 3,
CTXT_FUNCTION = 4,
CTXT_CCODE = 8,
CTXT_RETURN = 12,
CTXT_BROWSER = 16,
CTXT_GENERIC = 20,
CTXT_RESTART = 32,
CTXT_BUILTIN = 64
};
namespace r {
inline RCNTXT* getGlobalContext()
{
return static_cast<RCNTXT*>(R_GlobalContext);
}
} // namespace r
#endif // R_INTERFACE_HPP
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.