text stringlengths 54 60.6k |
|---|
<commit_before>#include "common.h"
int main(int argc, const char *argv[])
{
if(argc < 2)
{
std::cout << "Missing compose model! Can't run any further.\n";
return 1;
}
// read EOS table
// read abundances
// browse EOS table and compute rates
int entries = 0;
// Read nuclear data (masses)
entries = read_nuclear_data("data/mass.mas12");
std::cout << "Read " << entries << " nuclear data entries\n";
FILE *fp_nuclear = fopen("output/compare_qvalues.res", "w+");
int prev_A = 0;
for(auto it = nuclear_table.begin(); it != nuclear_table.end(); it++) {
fprintf(fp_nuclear, "%d %d %e %e %e %e\n", it->second->A, it->second->Z, it->second->m, SEMF(it->second->A, it->second->Z),
it->second->beta_q, SEMF(it->second->A, it->second->Z)-SEMF(it->second->A, it->second->Z+1));
if(prev_A != it->second->A)
{
fprintf(fp, "\n");
prev_A = it->second->A;
}
}
fclose(fp_nuclear);
// Read abundance data
std::cout << "Reading compose data from " << argv[1] << "...\n";
entries = read_abundance_data(argv[1]);
std::cout << "Read " << entries << " nuclear abundance data entries\n";
// Read full EOS data
full_EOS_table full_table;
full_table.read("data/eosls220_low.h5", EOS_TYPE_LOW);
//full_table.read("data/eoscompose.h5", EOS_TYPE_COMPOSE);
// Read rate EOS data
short_EOS_table rates_table;
rates_table.read("data/elec_capt_rate_ls220.h5", 0);
// Read output rates
short_EOS_table output_table;
output_table.read("output/sigma_scattering_rate.h5", 0);
entries = rates_table.size();
std::cout << "Read " << entries << " EOS entries ("
<< rates_table.m_ln_rho << "x" << rates_table.n_ln_t << "x" << rates_table.o_y_e << ")\n";
rates_table.dump();
entries = full_table.size();
std::cout << "Read " << entries << " EOS entries\n";
full_table.dump();
FILE *fp_scattering = fopen("output/compare_neutrinos.res", "w+");
FILE *fp_capture = fopen("output/compare_capture.res", "w+");
FILE *fp_nuclei = fopen("output/compare_nuclei.res", "w+");
for(int m = 0; m < rates_table.m_ln_rho; ++m)
for(int n = 0; n < rates_table.n_ln_t; ++n)
for(int o = 0; o < rates_table.o_y_e; ++o)
for(int p = 0; p < rates_table.p_mu; ++p)
{
int i = o*(rates_table.n_ln_t*rates_table.m_ln_rho*rates_table.p_mu) + n*(rates_table.m_ln_rho*rates_table.p_mu) + m*rates_table.p_mu + p;
int ii = m + n * rates_table.m_ln_rho + o * rates_table.m_ln_rho * rates_table.n_ln_t;
const double mu_e = -full_table.muq_eos[ii] + full_table.mul_eos[ii], //- 0.51099891;
mu_nu = full_table.mul_eos[ii],
mu_neut = full_table.mub_eos[ii], //- 939.56536; // non relativistic mu
mu_p = full_table.mub_eos[ii] + full_table.muq_eos[ii];
const double nb = exp(rates_table.ln_rho_eos[m]), T = exp(rates_table.ln_t_eos[n]), Y_e = rates_table.y_e_eos[o], ec_tab = rates_table.elec_rate_tab_eos[i];
const double mu_nu_eff = mu_nu * rates_table.mu_nu_eos[p],
eta = -mu_nu_eff / T;
//const double eta_pn = eta_pn_v3(mu_neut, mu_p, T);
double conditions[3] = {T, nb, Y_e};
double total_abundance = 0;
std::vector<element> elements;
get_abundances(conditions, elements);
double aheavy = 0, zheavy = 0;
for(int j = 0; j < elements.size(); ++j)
{
int A = elements[j].A, Z = elements[j].Z;
double abundance = elements[j].abundance;
if(A < 4 || Z < 2 || abundance <= 0) continue;
aheavy += A*abundance;
zheavy += Z*abundance;
total_abundance += abundance;
}
if(total_abundance > 1e-30)
{
aheavy /= total_abundance;
zheavy /= total_abundance;
}
double /*mu_e = degenerate_potential(M_ELECTRON, nb*Y_e),*/ eps_mu = average_neutrino_energy(T, mu_nu_eff);
if(T > 0.01 && T < 5 && nb > 1e-8 && nb < 1e-2 && Y_e > 0.1)
{
fprintf(fp_capture, "%e %e %.3f %e %e %e %e %.3f\n", T, nb, Y_e, mu_nu_eff, rates_table.elec_rate_tab_eos[i], output_table.elec_rate_fast_eos[i], output_table.elec_rate_tab_eos[i], (float)shell_capt_factor(aheavy, zheavy));
fprintf(fp_scattering, "%e %e %e %e %e %e %e %e %e %e\n", T, nb, Y_e, mu_nu_eff, aheavy, zheavy, full_table.aheavy_eos[ii], full_table.zheavy_eos[ii], output_table.scattering_xs_nu_eos[i], output_table.scattering_xs_nu_sna_eos[i]);
fprintf(fp_nuclei, "%.3f %.3f %.3f %.3f %e %e %d\n", aheavy, zheavy, full_table.aheavy_eos[ii], full_table.zheavy_eos[ii], total_abundance, full_table.xheavy_eos[ii], elements.size());
}
//printf("%e %e %e\n", T, mu_e, degenerate_potential(M_ELECTRON, nb*Y_e));
//continue;
}
fclose(fp_scattering);
fclose(fp_capture);
fclose(fp_nuclei);
return 0;
}
<commit_msg>tests fix<commit_after>#include "common.h"
int main(int argc, const char *argv[])
{
if(argc < 2)
{
std::cout << "Missing compose model! Can't run any further.\n";
return 1;
}
// read EOS table
// read abundances
// browse EOS table and compute rates
int entries = 0;
// Read nuclear data (masses)
entries = read_nuclear_data("data/mass.mas12");
std::cout << "Read " << entries << " nuclear data entries\n";
FILE *fp_nuclear = fopen("output/compare_qvalues.res", "w+");
int prev_A = 0;
for(auto it = nuclear_table.begin(); it != nuclear_table.end(); it++) {
fprintf(fp_nuclear, "%d %d %e %e %e %e\n", it->second->A, it->second->Z, it->second->m, SEMF(it->second->A, it->second->Z),
it->second->beta_q, SEMF(it->second->A, it->second->Z)-SEMF(it->second->A, it->second->Z+1));
if(prev_A != it->second->A)
{
fprintf(fp_nuclear, "\n");
prev_A = it->second->A;
}
}
fclose(fp_nuclear);
// Read abundance data
std::cout << "Reading compose data from " << argv[1] << "...\n";
entries = read_abundance_data(argv[1]);
std::cout << "Read " << entries << " nuclear abundance data entries\n";
// Read full EOS data
full_EOS_table full_table;
full_table.read("data/eosls220_low.h5", EOS_TYPE_LOW);
//full_table.read("data/eoscompose.h5", EOS_TYPE_COMPOSE);
// Read rate EOS data
short_EOS_table rates_table;
rates_table.read("data/elec_capt_rate_ls220.h5", 0);
// Read output rates
short_EOS_table output_table;
output_table.read("output/sigma_scattering_rate.h5", 0);
entries = rates_table.size();
std::cout << "Read " << entries << " EOS entries ("
<< rates_table.m_ln_rho << "x" << rates_table.n_ln_t << "x" << rates_table.o_y_e << ")\n";
rates_table.dump();
entries = full_table.size();
std::cout << "Read " << entries << " EOS entries\n";
full_table.dump();
FILE *fp_scattering = fopen("output/compare_neutrinos.res", "w+");
FILE *fp_capture = fopen("output/compare_capture.res", "w+");
FILE *fp_nuclei = fopen("output/compare_nuclei.res", "w+");
for(int m = 0; m < rates_table.m_ln_rho; ++m)
for(int n = 0; n < rates_table.n_ln_t; ++n)
for(int o = 0; o < rates_table.o_y_e; ++o)
for(int p = 0; p < rates_table.p_mu; ++p)
{
int i = o*(rates_table.n_ln_t*rates_table.m_ln_rho*rates_table.p_mu) + n*(rates_table.m_ln_rho*rates_table.p_mu) + m*rates_table.p_mu + p;
int ii = m + n * rates_table.m_ln_rho + o * rates_table.m_ln_rho * rates_table.n_ln_t;
const double mu_e = -full_table.muq_eos[ii] + full_table.mul_eos[ii], //- 0.51099891;
mu_nu = full_table.mul_eos[ii],
mu_neut = full_table.mub_eos[ii], //- 939.56536; // non relativistic mu
mu_p = full_table.mub_eos[ii] + full_table.muq_eos[ii];
const double nb = exp(rates_table.ln_rho_eos[m]), T = exp(rates_table.ln_t_eos[n]), Y_e = rates_table.y_e_eos[o], ec_tab = rates_table.elec_rate_tab_eos[i];
const double mu_nu_eff = mu_nu * rates_table.mu_nu_eos[p],
eta = -mu_nu_eff / T;
//const double eta_pn = eta_pn_v3(mu_neut, mu_p, T);
double conditions[3] = {T, nb, Y_e};
double total_abundance = 0;
std::vector<element> elements;
get_abundances(conditions, elements);
double aheavy = 0, zheavy = 0;
for(int j = 0; j < elements.size(); ++j)
{
int A = elements[j].A, Z = elements[j].Z;
double abundance = elements[j].abundance;
if(A < 4 || Z < 2 || abundance <= 0) continue;
aheavy += A*abundance;
zheavy += Z*abundance;
total_abundance += abundance;
}
if(total_abundance > 1e-30)
{
aheavy /= total_abundance;
zheavy /= total_abundance;
}
double /*mu_e = degenerate_potential(M_ELECTRON, nb*Y_e),*/ eps_mu = average_neutrino_energy(T, mu_nu_eff);
if(T > 0.01 && T < 5 && nb > 1e-8 && nb < 1e-2 && Y_e > 0.1)
{
fprintf(fp_capture, "%e %e %.3f %e %e %e %e %.3f\n", T, nb, Y_e, mu_nu_eff, rates_table.elec_rate_tab_eos[i], output_table.elec_rate_fast_eos[i], output_table.elec_rate_tab_eos[i], (float)shell_capt_factor(aheavy, zheavy));
fprintf(fp_scattering, "%e %e %e %e %e %e %e %e %e %e\n", T, nb, Y_e, mu_nu_eff, aheavy, zheavy, full_table.aheavy_eos[ii], full_table.zheavy_eos[ii], output_table.scattering_xs_nu_eos[i], output_table.scattering_xs_nu_sna_eos[i]);
fprintf(fp_nuclei, "%.3f %.3f %.3f %.3f %e %e %d\n", aheavy, zheavy, full_table.aheavy_eos[ii], full_table.zheavy_eos[ii], total_abundance, full_table.xheavy_eos[ii], elements.size());
}
//printf("%e %e %e\n", T, mu_e, degenerate_potential(M_ELECTRON, nb*Y_e));
//continue;
}
fclose(fp_scattering);
fclose(fp_capture);
fclose(fp_nuclei);
return 0;
}
<|endoftext|> |
<commit_before> /*!
* \file File timer.cpp
* \brief Implementation of the class Timer
*
* Auxiliary documentation
* \sa timer.hpp
*/
#include <timer.hpp>
/*!
@class Timer
@brief This class provides the timer to the game
*/
//! A constructor.
/*!
This is a empty constructor method of Timer class
*/
Timer::Timer() {
}
/*!
@fn void Timer::add_time(float additional_time)
@brief Method that adds time to the timer
@param additional_time
@brief A float, that represents time that will bee add to the timer
@return The execution of this method returns no value
*/
void Timer::add_time(float additional_time) {
time+=additional_time;
}
/*!
@fn void Timer::restart_time()
@brief Method that resets the timer
@return The execution of this method returns no value
*/
void Timer::restart_time() {
time=0;
}
/*!
@fn float Timer::get_time()
@brief A getter of the attribute time
@return A positive float, that represents the timer's current time
*/
float Timer::get_time() {
return time;
}
<commit_msg>applies log to timmer.cpp<commit_after> /*!
* \file File timer.cpp
* \brief Implementation of the class Timer
*
* Auxiliary documentation
* \sa timer.hpp
*/
#include <timer.hpp>
/*!
@class Timer
@brief This class provides the timer to the game
*/
//! A constructor.
/*!
This is a empty constructor method of Timer class
*/
Timer::Timer() {
LOG_METHOD_START("Timer::Timer");
LOG_MSG("This is a empty constructor method of Timer class");
LOG_METHOD_CLOSE("Timer::Timer", "constructor");
}
/*!
@fn void Timer::add_time(float additional_time)
@brief Method that adds time to the timer
@param additional_time
@brief A float, that represents time that will bee add to the timer
@return The execution of this method returns no value
*/
void Timer::add_time(float additional_time) {
LOG_METHOD_START("Timer::add_time");
LOG_VARIABLE("time", time);
time+=additional_time;
LOG_METHOD_CLOSE("Timer::add_time","void");
}
/*!
@fn void Timer::restart_time()
@brief Method that resets the timer
@return The execution of this method returns no value
*/
void Timer::restart_time() {
LOG_METHOD_START("Timer::restart_time");
time=0;
LOG_METHOD_CLOSE("Timer::restart_time","void");
}
/*!
@fn float Timer::get_time()
@brief A getter of the attribute time
@return A positive float, that represents the timer's current time
*/
float Timer::get_time() {
LOG_METHOD_START("Timer::get_time");
LOG_METHOD_CLOSE("Timer::get_time",time);
return time;
}
<|endoftext|> |
<commit_before>#include "tween.h"
template<> sf::Color Tween<sf::Color>::tweenApply(float f, const sf::Color& value0, const sf::Color& value1)
{
return sf::Color(
value0.r + (value1.r - value0.r) * f,
value0.g + (value1.g - value0.g) * f,
value0.b + (value1.b - value0.b) * f,
value0.a + (value1.a - value0.a) * f
);
}
<commit_msg>Update tween.cpp (#104)<commit_after>#include "tween.h"
#include <cstdint>
template<> sf::Color Tween<sf::Color>::tweenApply(float f, const sf::Color& value0, const sf::Color& value1)
{
return sf::Color(
static_cast<uint8_t>(value0.r + (value1.r - value0.r) * f),
static_cast<uint8_t>(value0.g + (value1.g - value0.g) * f),
static_cast<uint8_t>(value0.b + (value1.b - value0.b) * f),
static_cast<uint8_t>(value0.a + (value1.a - value0.a) * f)
);
}
<|endoftext|> |
<commit_before>#include "utils2.hpp"
#include "arch/arch.hpp"
#include <unistd.h>
#include <stdlib.h>
/* System configuration*/
int get_cpu_count() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
long get_available_ram() {
return (long)sysconf(_SC_AVPHYS_PAGES) * (long)sysconf(_SC_PAGESIZE);
}
long get_total_ram() {
return (long)sysconf(_SC_PHYS_PAGES) * (long)sysconf(_SC_PAGESIZE);
}
const repli_timestamp repli_timestamp::invalid = { -1 };
repli_timestamp repli_time(time_t t) {
repli_timestamp ret;
uint32_t x = t;
ret.time = (x == (uint32_t)-1 ? 0 : x);
return ret;
}
repli_timestamp current_time() {
// Get the current time, cast it to 32 bits. The lack of
// precision will not break things in 2038 or 2106 if we compare
// times correctly.
// time(NULL) does not do a system call (on Linux), last time we
// checked, but it's still kind of slow.
return repli_time(time(NULL));
}
int repli_compare(repli_timestamp x, repli_timestamp y) {
return int(int32_t(x.time - y.time));
}
repli_timestamp repli_max(repli_timestamp x, repli_timestamp y) {
return repli_compare(x, y) < 0 ? y : x;
}
void *malloc_aligned(size_t size, size_t alignment) {
void *ptr = NULL;
int res = posix_memalign(&ptr, alignment, size);
if(res != 0) crash_or_trap("Out of memory.");
return ptr;
}
/* Function to create a random delay. Defined in .cc instead of in .tcc because it
uses the IO layer, and it must be safe to include utils2 from within the IO layer. */
void random_delay(void (*fun)(void*), void *arg) {
/* In one in ten thousand requests, we delay up to 10 seconds. In half of the remaining
requests, we delay up to 50 milliseconds; in the other half we delay a very short time. */
int kind = randint(10000), ms;
if (kind == 0) ms = randint(10000);
else if (kind % 2 == 0) ms = 0;
else ms = randint(50);
fire_timer_once(ms, fun, arg);
}
void debugf(const char *msg, ...) {
flockfile(stderr);
va_list args;
va_start(args, msg);
fprintf(stderr, "CPU %d: ", get_cpu_id());
vfprintf(stderr, msg, args);
va_end(args);
funlockfile(stderr);
}
int randint(int n) {
static bool initted = false;
if (!initted) {
srand(time(NULL));
initted = true;
}
assert(n > 0 && n < RAND_MAX);
return rand() % n;
}
bool begins_with_minus(const char *string) {
while (isspace(*string)) string++;
return *string == '-';
}
unsigned long strtoul_strict(const char *string, char **end, int base) {
if (begins_with_minus(string)) {
*end = const_cast<char *>(string);
return 0;
}
return strtoul(string, end, base);
}
unsigned long long strtoull_strict(const char *string, char **end, int base) {
if (begins_with_minus(string)) {
*end = const_cast<char *>(string);
return 0;
}
return strtoull(string, end, base);
}
ticks_t secs_to_ticks(float secs) {
return (unsigned long long)secs * 1000000000L;
}
ticks_t get_ticks() {
timespec tv;
clock_gettime(CLOCK_MONOTONIC, &tv);
return secs_to_ticks(tv.tv_sec) + tv.tv_nsec;
}
long get_ticks_res() {
timespec tv;
clock_getres(CLOCK_MONOTONIC, &tv);
return secs_to_ticks(tv.tv_sec) + tv.tv_nsec;
}
float ticks_to_secs(ticks_t ticks) {
return ticks / 1000000000.0f;
}
float ticks_to_ms(ticks_t ticks) {
return ticks / 1000000.0f;
}
float ticks_to_us(ticks_t ticks) {
return ticks / 1000.0f;
}
<commit_msg>Check for too large values in strtoull_strict and stroul_strict<commit_after>#include "utils2.hpp"
#include "arch/arch.hpp"
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>
/* System configuration*/
int get_cpu_count() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
long get_available_ram() {
return (long)sysconf(_SC_AVPHYS_PAGES) * (long)sysconf(_SC_PAGESIZE);
}
long get_total_ram() {
return (long)sysconf(_SC_PHYS_PAGES) * (long)sysconf(_SC_PAGESIZE);
}
const repli_timestamp repli_timestamp::invalid = { -1 };
repli_timestamp repli_time(time_t t) {
repli_timestamp ret;
uint32_t x = t;
ret.time = (x == (uint32_t)-1 ? 0 : x);
return ret;
}
repli_timestamp current_time() {
// Get the current time, cast it to 32 bits. The lack of
// precision will not break things in 2038 or 2106 if we compare
// times correctly.
// time(NULL) does not do a system call (on Linux), last time we
// checked, but it's still kind of slow.
return repli_time(time(NULL));
}
int repli_compare(repli_timestamp x, repli_timestamp y) {
return int(int32_t(x.time - y.time));
}
repli_timestamp repli_max(repli_timestamp x, repli_timestamp y) {
return repli_compare(x, y) < 0 ? y : x;
}
void *malloc_aligned(size_t size, size_t alignment) {
void *ptr = NULL;
int res = posix_memalign(&ptr, alignment, size);
if(res != 0) crash_or_trap("Out of memory.");
return ptr;
}
/* Function to create a random delay. Defined in .cc instead of in .tcc because it
uses the IO layer, and it must be safe to include utils2 from within the IO layer. */
void random_delay(void (*fun)(void*), void *arg) {
/* In one in ten thousand requests, we delay up to 10 seconds. In half of the remaining
requests, we delay up to 50 milliseconds; in the other half we delay a very short time. */
int kind = randint(10000), ms;
if (kind == 0) ms = randint(10000);
else if (kind % 2 == 0) ms = 0;
else ms = randint(50);
fire_timer_once(ms, fun, arg);
}
void debugf(const char *msg, ...) {
flockfile(stderr);
va_list args;
va_start(args, msg);
fprintf(stderr, "CPU %d: ", get_cpu_id());
vfprintf(stderr, msg, args);
va_end(args);
funlockfile(stderr);
}
int randint(int n) {
static bool initted = false;
if (!initted) {
srand(time(NULL));
initted = true;
}
assert(n > 0 && n < RAND_MAX);
return rand() % n;
}
bool begins_with_minus(const char *string) {
while (isspace(*string)) string++;
return *string == '-';
}
unsigned long strtoul_strict(const char *string, char **end, int base) {
if (begins_with_minus(string)) {
*end = const_cast<char *>(string);
return 0;
}
unsigned long result = strtoul(string, end, base);
if (result == ULONG_MAX && errno == ERANGE)
{
*end = const_cast<char *>(string);
return 0;
}
return result;
}
unsigned long long strtoull_strict(const char *string, char **end, int base) {
if (begins_with_minus(string)) {
*end = const_cast<char *>(string);
return 0;
}
unsigned long long result = strtoull(string, end, base);
if (result == ULLONG_MAX && errno == ERANGE)
{
*end = const_cast<char *>(string);
return 0;
}
return result;
}
ticks_t secs_to_ticks(float secs) {
return (unsigned long long)secs * 1000000000L;
}
ticks_t get_ticks() {
timespec tv;
clock_gettime(CLOCK_MONOTONIC, &tv);
return secs_to_ticks(tv.tv_sec) + tv.tv_nsec;
}
long get_ticks_res() {
timespec tv;
clock_getres(CLOCK_MONOTONIC, &tv);
return secs_to_ticks(tv.tv_sec) + tv.tv_nsec;
}
float ticks_to_secs(ticks_t ticks) {
return ticks / 1000000000.0f;
}
float ticks_to_ms(ticks_t ticks) {
return ticks / 1000000.0f;
}
float ticks_to_us(ticks_t ticks) {
return ticks / 1000.0f;
}
<|endoftext|> |
<commit_before>/**
* \file stuff.hh
* \brief contains some stuff
**/
#ifndef STUFF_MISC_HH_INCLUDED
#define STUFF_MISC_HH_INCLUDED
#define SEGFAULT {int*J=0;*J=9;}
template <typename T>
bool isnan( T x ) { return !(x==x); }
#ifndef NDEBUG
#ifndef LOGIC_ERROR
#include <stdexcept>
#include <sstream>
#define LOGIC_ERROR \
{\
std::stringstream ss; ss << __FILE__ << ":" << __LINE__ << " should never be called"; \
throw std::logic_error(ss.str());\
}
#endif
#else
#define LOGIC_ERROR
#endif
#include <fstream>
#include <ostream>
#include <sstream>
#include <vector>
#include <assert.h>
#include <cmath>
#define HAS_RUN_INFO
struct RunInfo //define this beforepass is included so it's known in pass, i know it's ugly
{
std::vector< double > L2Errors;
double grid_width;
int refine_level;
double run_time;
long codim0;
int polorder_velocity;
int polorder_pressure;
int polorder_sigma;
double c11,d11,c12,d12;
bool bfg;
std::string gridname;
double solver_accuracy;
double bfg_tau;
std::string extra_info;
int iterations_inner_avg;
int iterations_inner_min;
int iterations_inner_max;
int iterations_outer_total;
double max_inner_accuracy;
};
namespace Stuff
{
/**
* \todo doc me
**/
template < class ReturnType >
ReturnType fromString(const std::string& s)
{
std::stringstream ss;
ss << s;
ReturnType r;
ss >> r;
return r;
}
/**
* \todo doc
**/
template < class ReturnType >
std::string toString(const ReturnType& s)
{
std::stringstream ss;
ss << s;
std::string r;
ss >> r;
return r;
}
template < class Info >
class TexOutputBase
{
protected:
typedef std::vector< std::string >
Strings;
typedef TexOutputBase<Info>
BaseType;
Info info_;
double current_h_;
Strings headers_;
public:
TexOutputBase( const Info& info, Strings& headers )
: info_(info),
current_h_(1.0),
headers_(headers)
{}
TexOutputBase( Strings& headers )
: info_(Info()),
current_h_(1.0),
headers_(headers)
{}
void setInfo( const Info& info )
{
info_ = info;
}
void putLineEnd( std::ofstream& outputFile_ )
{
outputFile_ << "\n"
<< "\\tabularnewline\n"
<< "\\hline \n";
outputFile_.flush();
}
virtual void putErrorCol( std::ofstream& outputFile_, const double prevError_, const double error_, const double prevh_, const bool /*initial*/ ) = 0;
virtual void putHeader( std::ofstream& outputFile_ ) = 0;
virtual void putStaticCols( std::ofstream& outputFile_ ) = 0;
void endTable( std::ofstream& outputFile_ )
{
outputFile_ << "\\end{longtable}";
outputFile_ << info_.extra_info;
outputFile_.flush();
}
double get_h ()
{
return current_h_;
}
};
class EocOutput : public TexOutputBase<RunInfo>
{
typedef TexOutputBase<RunInfo>
BaseType;
public:
EocOutput( const RunInfo& info, BaseType::Strings& headers )
: BaseType( info, headers )
{}
EocOutput( BaseType::Strings& headers )
: BaseType( RunInfo(), headers )
{}
void putErrorCol( std::ofstream& outputFile_, const double prevError_, const double error_, const double prevh_, const bool /*initial*/ )
{
current_h_ = info_.grid_width;
double factor = current_h_/prevh_;
double eoc = std::log(error_/prevError_)/std::log(factor);
outputFile_ << " & " << error_ << " & " << eoc;
}
void putHeader( std::ofstream& outputFile_ )
{
const unsigned int dynColSize = 2;
const unsigned int statColSize = headers_.size() - 2;
outputFile_ << "\\begin{longtable}{";
for (unsigned int i=0;i<statColSize;i++) {
if ( i == 2 )
outputFile_ << "|r|";//runtime col
else
outputFile_ << "|c|";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << "|cc|";
}
outputFile_ << "}\n"
<< "\\caption{"
<< info_.gridname
<< ( info_.bfg ? std::string(", BFG ($\\tau = ")+ toString( info_.bfg_tau ) + std::string("$ ),"): std::string(", no BFG,") )
<< "\\\\"
<< " Polorder (u,p,$\\sigma$): (" << info_.polorder_velocity << ", "<< info_.polorder_pressure << ", "<< info_.polorder_sigma << " ) "
<< " Solver accuracy: " << info_.solver_accuracy
<< "}\\\\ \n"
<< "\\hline \n";
for (unsigned int i=0;i<statColSize;i++) {
outputFile_ << headers_[i];
if ( i < statColSize - 1 )
outputFile_ << " & ";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << " & " << headers_[i+statColSize]
<< " & EOC ";
}
outputFile_ << "\n \\endhead\n"
<< "\\hline\n"
<< "\\hline\n";
}
virtual void putStaticCols( std::ofstream& outputFile_ )
{
std::stringstream runtime;
if ( info_.run_time > 59 )
runtime << long(info_.run_time) / 60 << ":" << long(info_.run_time) % 60 ;
else
runtime << long(info_.run_time) ;
outputFile_ << std::setw( 4 )
<< info_.grid_width << " & "
<< info_.codim0 << " & "
<< runtime.str() << " & "
<< info_.c11 << " & "
<< info_.d11 << " & "
<< info_.c12 << " & "
<< info_.d12 ;
}
};
class RefineOutput : public EocOutput
{
typedef EocOutput
BaseType;
public:
RefineOutput ( const RunInfo& info, BaseType::Strings& headers )
: BaseType( info, headers )
{}
RefineOutput ( BaseType::Strings& headers )
: BaseType( RunInfo(), headers )
{}
void putStaticCols( std::ofstream& outputFile_ )
{
std::stringstream runtime;
if ( info_.run_time > 59 )
runtime << long(info_.run_time) / 60 << ":" << long(info_.run_time) % 60 ;
else
runtime << long(info_.run_time) ;
outputFile_ << std::setw( 4 )
<< info_.grid_width << " & "
<< info_.codim0 << " & "
<< runtime.str() ;
}
};
class BfgOutput : public TexOutputBase<RunInfo>
{
typedef TexOutputBase<RunInfo>
BaseType;
RunInfo reference_;
public:
BfgOutput( const RunInfo& info, BaseType::Strings& headers )
: BaseType( info, headers )
{}
BfgOutput( BaseType::Strings& headers, RunInfo reference )
: BaseType( RunInfo(), headers ),
reference_(reference)
{}
void putErrorCol( std::ofstream& outputFile_, const double prevError_, const double error_, const double prevh_, const bool /*initial*/ )
{
//some trickery to calc correct diff w/o further work on the fem stuff
static bool col = true;
col = ! col;
current_h_ = info_.grid_width;
double diff = std::abs( error_ - reference_.L2Errors[col] );
outputFile_ << " & " << error_ << " & " << diff;
}
void putHeader( std::ofstream& outputFile_ )
{
const unsigned int dynColSize = 2;
const unsigned int statColSize = headers_.size() - 2;
outputFile_ << "\\begin{longtable}{";
for (unsigned int i=0;i<statColSize;i++) {
if ( i == 2 )
outputFile_ << "|r|";//runtime col
else
outputFile_ << "|c|";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << "|cc|";
}
outputFile_ << "}\n"
<< "\\caption{"
<< info_.gridname
<< " Polorder (u,p,$\\sigma$): (" << info_.polorder_velocity << ", "<< info_.polorder_pressure << ", "<< info_.polorder_sigma << " ) "
<< " Solver accuracy: " << info_.solver_accuracy
<< "}\\\\ \n"
<< "\\hline \n";
for (unsigned int i=0;i<statColSize;i++) {
outputFile_ << headers_[i];
if ( i < statColSize - 1 )
outputFile_ << " & ";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << " & " << headers_[i+statColSize]
<< " & Diff to ref ";
}
outputFile_ << "\n \\endhead\n"
<< "\\hline\n"
<< "\\hline\n";
}
void putStaticCols( std::ofstream& outputFile_ )
{
std::stringstream runtime;
if ( info_.run_time > 59 )
runtime << long(info_.run_time) / 60 << ":" << long(info_.run_time) % 60 ;
else
runtime << long(info_.run_time) ;
outputFile_ << std::setw( 4 )
<< info_.grid_width << " & "
<< info_.codim0 << " & "
<< runtime.str() << " & "
<< ( info_.bfg ? toString( info_.bfg_tau ) : std::string("--") ) << " & " //don't output a num in reference row
<< info_.iterations_inner_avg << " & "
<< info_.iterations_inner_min << " & "
<< info_.iterations_inner_max << " & "
<< info_.iterations_outer_total << " & "
<< info_.max_inner_accuracy ;
}
};
/**
* \brief Only free mem pointed to by valid pointer, log warning otherwise
*
**/
template < class T >
void safe_delete ( T t ) //this is actually bullshit :P
{
if (t){
delete t;
t=0;
}
//else log warning
}
template < class Container, class Element >
int getIdx( const Container& ct, Element e )
{
int idx = 0;
for ( typename Container::const_iterator it = ct.begin(); it != ct.end(); ++it, ++idx )
{
if ( *it == e )
return idx;
}
return -1;
}
//! strip filename from \path if present, return empty string if only filename present
std::string pathOnly ( std::string path )
{
if (!path.empty())
{
char buf[1024];//not _exactly_ sure this is max path length, but it's suggested in wx source
// Local copy
strcpy (buf, path.c_str() );
int l = path.length();
int i = l - 1;
// Search backward for a backward or forward slash
while (i > -1)
{
if ( ( path[i] == '/' ) || ( path[i] == '\\' ) )
{
// Don't return an empty string
if (i == 0)
i ++;
buf[i] = 0;
return std::string(buf);
}
i --;
}
}
return std::string();
}
//! may include filename, will be stripped
bool testCreateDirectory( std::string path ) {
std::string pathonly = pathOnly(path);
if ( pathonly.empty() )
return true; //no dir to create
//maybe test if dir exists??
bool ok = ( mkdir(pathonly.c_str(), 0755 ) == 0 );
if ( !ok ) {
perror( pathonly.c_str() );
return errno == EEXIST;
}
return true;
}
} // end namepspace stuff
template < typename T >
std::string getParameterString( const std::string& prefix, T min, T max, T inc )
{
std::stringstream ss;
ss << prefix << " ";
for ( ; min < max ; min+=inc ) {
ss << min << ", " ;
}
return ss.str();
}
#endif // end of stuff.hh
<commit_msg>do not use abs for diff display<commit_after>/**
* \file stuff.hh
* \brief contains some stuff
**/
#ifndef STUFF_MISC_HH_INCLUDED
#define STUFF_MISC_HH_INCLUDED
#define SEGFAULT {int*J=0;*J=9;}
template <typename T>
bool isnan( T x ) { return !(x==x); }
#ifndef NDEBUG
#ifndef LOGIC_ERROR
#include <stdexcept>
#include <sstream>
#define LOGIC_ERROR \
{\
std::stringstream ss; ss << __FILE__ << ":" << __LINE__ << " should never be called"; \
throw std::logic_error(ss.str());\
}
#endif
#else
#define LOGIC_ERROR
#endif
#include <fstream>
#include <ostream>
#include <sstream>
#include <vector>
#include <assert.h>
#include <cmath>
#define HAS_RUN_INFO
struct RunInfo //define this beforepass is included so it's known in pass, i know it's ugly
{
std::vector< double > L2Errors;
double grid_width;
int refine_level;
double run_time;
long codim0;
int polorder_velocity;
int polorder_pressure;
int polorder_sigma;
std::pair<int,double> c11,d11,c12,d12;
bool bfg;
std::string gridname;
double solver_accuracy;
double bfg_tau;
std::string extra_info;
int iterations_inner_avg;
int iterations_inner_min;
int iterations_inner_max;
int iterations_outer_total;
double max_inner_accuracy;
};
namespace Stuff
{
/**
* \todo doc me
**/
template < class ReturnType >
ReturnType fromString(const std::string& s)
{
std::stringstream ss;
ss << s;
ReturnType r;
ss >> r;
return r;
}
/**
* \todo doc
**/
template < class ReturnType >
std::string toString(const ReturnType& s)
{
std::stringstream ss;
ss << s;
std::string r;
ss >> r;
return r;
}
template < class Info >
class TexOutputBase
{
protected:
typedef std::vector< std::string >
Strings;
typedef TexOutputBase<Info>
BaseType;
Info info_;
double current_h_;
Strings headers_;
public:
TexOutputBase( const Info& info, Strings& headers )
: info_(info),
current_h_(1.0),
headers_(headers)
{}
TexOutputBase( Strings& headers )
: info_(Info()),
current_h_(1.0),
headers_(headers)
{}
void setInfo( const Info& info )
{
info_ = info;
}
void putLineEnd( std::ofstream& outputFile_ )
{
outputFile_ << "\n"
<< "\\tabularnewline\n"
<< "\\hline \n";
outputFile_.flush();
}
virtual void putErrorCol( std::ofstream& outputFile_, const double prevError_, const double error_, const double prevh_, const bool /*initial*/ ) = 0;
virtual void putHeader( std::ofstream& outputFile_ ) = 0;
virtual void putStaticCols( std::ofstream& outputFile_ ) = 0;
void endTable( std::ofstream& outputFile_ )
{
outputFile_ << "\\end{longtable}";
outputFile_ << info_.extra_info;
outputFile_.flush();
}
double get_h ()
{
return current_h_;
}
};
class EocOutput : public TexOutputBase<RunInfo>
{
typedef TexOutputBase<RunInfo>
BaseType;
public:
EocOutput( const RunInfo& info, BaseType::Strings& headers )
: BaseType( info, headers )
{}
EocOutput( BaseType::Strings& headers )
: BaseType( RunInfo(), headers )
{}
void putErrorCol( std::ofstream& outputFile_, const double prevError_, const double error_, const double prevh_, const bool /*initial*/ )
{
current_h_ = info_.grid_width;
double factor = current_h_/prevh_;
double eoc = std::log(error_/prevError_)/std::log(factor);
outputFile_ << " & " << error_ << " & " << eoc;
}
void putHeader( std::ofstream& outputFile_ )
{
const unsigned int dynColSize = 2;
const unsigned int statColSize = headers_.size() - 2;
outputFile_ << "\\begin{longtable}{";
for (unsigned int i=0;i<statColSize;i++) {
if ( i == 2 )
outputFile_ << "|r|";//runtime col
else
outputFile_ << "|c|";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << "|cc|";
}
outputFile_ << "}\n"
<< "\\caption{"
<< info_.gridname
<< ( info_.bfg ? std::string(", BFG ($\\tau = ")+ toString( info_.bfg_tau ) + std::string("$ ),"): std::string(", no BFG,") )
<< "\\\\"
<< " Polorder (u,p,$\\sigma$): (" << info_.polorder_velocity << ", "<< info_.polorder_pressure << ", "<< info_.polorder_sigma << " ) "
<< " Solver accuracy: " << info_.solver_accuracy
<< "}\\\\ \n"
<< "\\hline \n";
for (unsigned int i=0;i<statColSize;i++) {
outputFile_ << headers_[i];
if ( i < statColSize - 1 )
outputFile_ << " & ";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << " & " << headers_[i+statColSize]
<< " & EOC ";
}
outputFile_ << "\n \\endhead\n"
<< "\\hline\n"
<< "\\hline\n";
}
virtual void putStaticCols( std::ofstream& outputFile_ )
{
std::stringstream runtime;
if ( info_.run_time > 59 )
runtime << long(info_.run_time) / 60 << ":" << long(info_.run_time) % 60 ;
else
runtime << long(info_.run_time) ;
outputFile_ << std::setw( 4 )
<< info_.grid_width << " & "
<< info_.codim0 << " & "
<< runtime.str() << " & "
<< info_.c11.first << " / " << info_.c11.second << " & "
<< info_.c12.first << " / " << info_.c12.second << " & "
<< info_.d11.first << " / " << info_.d11.second << " & "
<< info_.d12.first << " / " << info_.d12.second ;
}
};
class RefineOutput : public EocOutput
{
typedef EocOutput
BaseType;
public:
RefineOutput ( const RunInfo& info, BaseType::Strings& headers )
: BaseType( info, headers )
{}
RefineOutput ( BaseType::Strings& headers )
: BaseType( RunInfo(), headers )
{}
void putStaticCols( std::ofstream& outputFile_ )
{
std::stringstream runtime;
if ( info_.run_time > 59 )
runtime << long(info_.run_time) / 60 << ":" << long(info_.run_time) % 60 ;
else
runtime << long(info_.run_time) ;
outputFile_ << std::setw( 4 )
<< info_.grid_width << " & "
<< info_.codim0 << " & "
<< runtime.str() ;
}
};
class BfgOutput : public TexOutputBase<RunInfo>
{
typedef TexOutputBase<RunInfo>
BaseType;
RunInfo reference_;
public:
BfgOutput( const RunInfo& info, BaseType::Strings& headers )
: BaseType( info, headers )
{}
BfgOutput( BaseType::Strings& headers, RunInfo reference )
: BaseType( RunInfo(), headers ),
reference_(reference)
{}
void putErrorCol( std::ofstream& outputFile_, const double prevError_, const double error_, const double prevh_, const bool /*initial*/ )
{
//some trickery to calc correct diff w/o further work on the fem stuff
static bool col = true;
col = ! col;
current_h_ = info_.grid_width;
double diff = error_ - reference_.L2Errors[col];
outputFile_ << " & " << error_ << " & " << diff;
}
void putHeader( std::ofstream& outputFile_ )
{
const unsigned int dynColSize = 2;
const unsigned int statColSize = headers_.size() - 2;
outputFile_ << "\\begin{longtable}{";
for (unsigned int i=0;i<statColSize;i++) {
if ( i == 2 )
outputFile_ << "|r|";//runtime col
else
outputFile_ << "|c|";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << "|cc|";
}
outputFile_ << "}\n"
<< "\\caption{"
<< info_.gridname
<< " Polorder (u,p,$\\sigma$): (" << info_.polorder_velocity << ", "<< info_.polorder_pressure << ", "<< info_.polorder_sigma << " ) "
<< " Solver accuracy: " << info_.solver_accuracy
<< "}\\\\ \n"
<< "\\hline \n";
for (unsigned int i=0;i<statColSize;i++) {
outputFile_ << headers_[i];
if ( i < statColSize - 1 )
outputFile_ << " & ";
}
for (unsigned int i=0;i<dynColSize;i++) {
outputFile_ << " & " << headers_[i+statColSize]
<< " & Diff to ref ";
}
outputFile_ << "\n \\endhead\n"
<< "\\hline\n"
<< "\\hline\n";
}
void putStaticCols( std::ofstream& outputFile_ )
{
std::stringstream runtime;
if ( info_.run_time > 59 )
runtime << long(info_.run_time) / 60 << ":" << long(info_.run_time) % 60 ;
else
runtime << long(info_.run_time) ;
outputFile_ << std::setw( 4 )
<< info_.grid_width << " & "
<< info_.codim0 << " & "
<< runtime.str() << " & "
<< ( info_.bfg ? toString( info_.bfg_tau ) : std::string("--") ) << " & " //don't output a num in reference row
<< info_.iterations_inner_avg << " & "
<< info_.iterations_inner_min << " & "
<< info_.iterations_inner_max << " & "
<< info_.iterations_outer_total << " & "
<< info_.max_inner_accuracy ;
}
};
/**
* \brief Only free mem pointed to by valid pointer, log warning otherwise
*
**/
template < class T >
void safe_delete ( T t ) //this is actually bullshit :P
{
if (t){
delete t;
t=0;
}
//else log warning
}
template < class Container, class Element >
int getIdx( const Container& ct, Element e )
{
int idx = 0;
for ( typename Container::const_iterator it = ct.begin(); it != ct.end(); ++it, ++idx )
{
if ( *it == e )
return idx;
}
return -1;
}
//! strip filename from \path if present, return empty string if only filename present
std::string pathOnly ( std::string path )
{
if (!path.empty())
{
char buf[1024];//not _exactly_ sure this is max path length, but it's suggested in wx source
// Local copy
strcpy (buf, path.c_str() );
int l = path.length();
int i = l - 1;
// Search backward for a backward or forward slash
while (i > -1)
{
if ( ( path[i] == '/' ) || ( path[i] == '\\' ) )
{
// Don't return an empty string
if (i == 0)
i ++;
buf[i] = 0;
return std::string(buf);
}
i --;
}
}
return std::string();
}
//! may include filename, will be stripped
bool testCreateDirectory( std::string path ) {
std::string pathonly = pathOnly(path);
if ( pathonly.empty() )
return true; //no dir to create
//maybe test if dir exists??
bool ok = ( mkdir(pathonly.c_str(), 0755 ) == 0 );
if ( !ok ) {
perror( pathonly.c_str() );
return errno == EEXIST;
}
return true;
}
} // end namepspace stuff
template < typename T >
std::string getParameterString( const std::string& prefix, T min, T max, T inc )
{
std::stringstream ss;
ss << prefix << " ";
for ( ; min < max ; min+=inc ) {
ss << min << ", " ;
}
return ss.str();
}
#endif // end of stuff.hh
<|endoftext|> |
<commit_before>//
// Created by dc on 15/12/17.
//
#ifndef SUIL_CMDL_HPP
#define SUIL_CMDL_HPP
#include <suil/sys.hpp>
namespace suil {
namespace cmdl {
static const char NOSF = '\0';
struct Arg {
zcstring lf{nullptr};
zcstring help;
char sf{NOSF};
bool option{true};
bool required{false};
bool global{false};
private:
friend struct Cmd;
inline bool check(const zcstring& arg) const {
return lf == arg;
}
inline bool check(char c) const {
return c == sf;
}
inline bool check(char s, const zcstring& l) {
return ((s != NOSF) && Ego.check(s)) || Ego.check(l);
}
};
struct Cmd {
Cmd(zcstring&& name, const char *descript = nullptr, bool help = true);
Cmd&operator()(zcstring&& lf, zcstring&& help, char sf, bool opt, bool req);
Cmd&operator<<(Arg&&arg);
Cmd&operator()(std::function<void(Cmd&)> handler) {
if (Ego.handler != nullptr) {
throw SuilError::create("command '", name,
"' already assigned a handler");
}
Ego.handler = handler;
return Ego;
}
void showhelp(const char *app, zbuffer &help, bool ishelp = false) const;
bool parse(int argc, char *argv[], bool debug = false);
template <typename... O>
bool parse(iod::sio<O...>& obj, int argc, char *argv[]) {
// parse arguments as usual
bool ishelp = parse(argc, argv, true);
if (ishelp) {
return ishelp;
}
// parse arguments based on object
iod::foreach2(obj) |
[&](auto& m) {
auto& n = m.symbol().name();
zcstring name{n.data(), n.size(), false};
getvalue(name, m.value());
};
}
inline bool interactive(bool showhelp=false) {
Ego.inter = true;
Ego.interhelp = showhelp;
return true;
}
zcstring operator[](char sf) {
Arg& arg = Ego.check(nullptr, sf);
return Ego[arg.lf].peek();
}
zcstring operator[](const char *lf) {
Arg& arg = Ego.check(lf, NOSF);
return Ego[arg.lf].peek();
}
zcstring operator[](const zcstring& lf);
template <typename V>
V getvalue(const char*lf, const V def) {
zcstring zlf{lf};
return std::move(getvalue(zlf, def));
}
zcstring getvalue(const char*lf, const char* def) {
zcstring zlf{lf};
zcstring zdef{def};
return std::move(getvalue(zlf, zdef));
}
template <typename V>
V getvalue(const zcstring& name, const V def) {
Arg *_;
if (!check(_, name, NOSF)) {
throw SuilError::create("passed parameter '",
name, "' is not an argument");
}
V tmp = def;
zcstring zstr = Ego[name];
if (!zstr.empty()) {
setvalue(tmp, zstr);
}
return std::move(tmp);
}
private:
friend struct Parser;
template <typename V>
inline void setvalue(V& out, zcstring& from) {
utils::cast(from, out);
}
template <typename V>
inline void setvalue(std::vector<V>& out, zcstring& from) {
auto& parts = utils::strsplit(from, ",");
for (auto& part: parts) {
V val;
zcstring tmp{part};
zcstring trimd = utils::strtrim(tmp, ' ');
setvalue(val, trimd);
out.emplace_back(std::move(val));
}
}
static int isvalid(const char *flag) {
if (flag[0] == '-') {
if (flag[1] == '-') {
return (flag[2] != '\0' && flag[2] != '-' && isalpha(flag[2]))?
2 : 0;
}
return (flag[1] != '\0' && isalpha(flag[1]))? 1: 0;
}
return 0;
}
void requestvalue(Arg& arg);
Arg& check(const zcstring& lf, char sf);
bool check(Arg*& found, const zcstring& lf, char sf);
zcstring name;
zcstring descript;
std::vector<Arg> args;
size_t longest{0};
bool required{false};
bool internal{false};
bool inter{false};
bool interhelp{false};
zmap<zcstring> passed;
std::function<void(Cmd&)> handler;
};
struct Parser {
Parser(const char* app, const char *version, const char *descript = nullptr);
template <typename... Commands>
void add(Cmd&& cmd, Commands&&... cmds) {
add(std::forward<Cmd>(cmd));
add(std::forward<Commands>(cmds)...);
}
void add(Cmd&& cmd);
Parser&operator<<(Arg&& arg);
void parse(int argc, char *argv[]);
void handle();
void showcmdhelp(zbuffer& out, Cmd& cmd, bool ishelp);
const Cmd* getcmd() const {
return parsed;
}
template <typename __T>
zcstring operator[](char sf) {
zcstring _{nullptr};
Arg *arg = findarg(_, sf);
if (arg) {
return Ego.getvalue(arg->lf, arg);
}
return zcstring{};
}
zcstring operator[](const char* lf) {
zcstring zlf{lf};
return getvalue(zlf, nullptr);
}
zcstring operator[](const zcstring& lf) {
return getvalue(lf, nullptr);
}
private:
zcstring getvalue(const zcstring&, Arg* arg);
void showhelp(const char *prefix = nullptr);
Cmd* find(const zcstring& name);
Arg* findarg(const zcstring& name, char sf=NOSF);
Arg shallowcopy(const Arg& arg);
void add(){}
std::vector<Cmd> commands;
std::vector<Arg> globals;
// this is the command that successfully passed
Cmd *parsed{nullptr};
zcstring appname;
zcstring descript;
zcstring appversion;
size_t longestcmd{0};
size_t longestflag{0};
bool required{false};
bool inter{false};
};
zcstring readparam(const zcstring& display, const char *def);
zcstring readpasswd(const zcstring& display);
}
}
#endif //SUIL_CMDL_HPP
<commit_msg>- Updating for C++17 compiler<commit_after>//
// Created by dc on 15/12/17.
//
#ifndef SUIL_CMDL_HPP
#define SUIL_CMDL_HPP
#include <suil/sys.hpp>
namespace suil {
namespace cmdl {
static const char NOSF = '\0';
struct Arg {
zcstring lf{nullptr};
zcstring help;
char sf{NOSF};
bool option{true};
bool required{false};
bool global{false};
private:
friend struct Cmd;
inline bool check(const zcstring& arg) const {
return lf == arg;
}
inline bool check(char c) const {
return c == sf;
}
inline bool check(char s, const zcstring& l) {
return ((s != NOSF) && Ego.check(s)) || Ego.check(l);
}
};
struct Cmd {
Cmd(zcstring&& name, const char *descript = nullptr, bool help = true);
Cmd&operator()(zcstring&& lf, zcstring&& help, char sf, bool opt, bool req);
Cmd&operator<<(Arg&&arg);
Cmd&operator()(std::function<void(Cmd&)> handler) {
if (Ego.handler != nullptr) {
throw SuilError::create("command '", name,
"' already assigned a handler");
}
Ego.handler = handler;
return Ego;
}
void showhelp(const char *app, zbuffer &help, bool ishelp = false) const;
bool parse(int argc, char *argv[], bool debug = false);
template <typename... O>
bool parse(iod::sio<O...>& obj, int argc, char *argv[]) {
// parse arguments as usual
bool ishelp = parse(argc, argv, true);
if (ishelp) {
return ishelp;
}
// parse arguments based on object
iod::foreach2(obj) |
[&](auto& m) {
auto& n = m.symbol().name();
zcstring name{n.data(), n.size(), false};
getvalue(name, m.value());
};
return false;
}
inline bool interactive(bool showhelp=false) {
Ego.inter = true;
Ego.interhelp = showhelp;
return true;
}
zcstring operator[](char sf) {
Arg& arg = Ego.check(nullptr, sf);
return Ego[arg.lf].peek();
}
zcstring operator[](const char *lf) {
Arg& arg = Ego.check(lf, NOSF);
return Ego[arg.lf].peek();
}
zcstring operator[](const zcstring& lf);
template <typename V>
V getvalue(const char*lf, const V def) {
zcstring zlf{lf};
return std::move(getvalue(zlf, def));
}
zcstring getvalue(const char*lf, const char* def) {
zcstring zlf{lf};
zcstring zdef{def};
return std::move(getvalue(zlf, zdef));
}
template <typename V>
V getvalue(const zcstring& name, const V def) {
Arg *_;
if (!check(_, name, NOSF)) {
throw SuilError::create("passed parameter '",
name, "' is not an argument");
}
V tmp = def;
zcstring zstr = Ego[name];
if (!zstr.empty()) {
setvalue(tmp, zstr);
}
return std::move(tmp);
}
private:
friend struct Parser;
template <typename V>
inline void setvalue(V& out, zcstring& from) {
utils::cast(from, out);
}
template <typename V>
inline void setvalue(std::vector<V>& out, zcstring& from) {
auto& parts = utils::strsplit(from, ",");
for (auto& part: parts) {
V val;
zcstring tmp{part};
zcstring trimd = utils::strtrim(tmp, ' ');
setvalue(val, trimd);
out.emplace_back(std::move(val));
}
}
static int isvalid(const char *flag) {
if (flag[0] == '-') {
if (flag[1] == '-') {
return (flag[2] != '\0' && flag[2] != '-' && isalpha(flag[2]))?
2 : 0;
}
return (flag[1] != '\0' && isalpha(flag[1]))? 1: 0;
}
return 0;
}
void requestvalue(Arg& arg);
Arg& check(const zcstring& lf, char sf);
bool check(Arg*& found, const zcstring& lf, char sf);
zcstring name;
zcstring descript;
std::vector<Arg> args;
size_t longest{0};
bool required{false};
bool internal{false};
bool inter{false};
bool interhelp{false};
zmap<zcstring> passed;
std::function<void(Cmd&)> handler;
};
struct Parser {
Parser(const char* app, const char *version, const char *descript = nullptr);
template <typename... Commands>
void add(Cmd&& cmd, Commands&&... cmds) {
add(std::forward<Cmd>(cmd));
add(std::forward<Commands>(cmds)...);
}
void add(Cmd&& cmd);
Parser&operator<<(Arg&& arg);
void parse(int argc, char *argv[]);
void handle();
void showcmdhelp(zbuffer& out, Cmd& cmd, bool ishelp);
const Cmd* getcmd() const {
return parsed;
}
template <typename __T>
zcstring operator[](char sf) {
zcstring _{nullptr};
Arg *arg = findarg(_, sf);
if (arg) {
return Ego.getvalue(arg->lf, arg);
}
return zcstring{};
}
zcstring operator[](const char* lf) {
zcstring zlf{lf};
return getvalue(zlf, nullptr);
}
zcstring operator[](const zcstring& lf) {
return getvalue(lf, nullptr);
}
private:
zcstring getvalue(const zcstring&, Arg* arg);
void showhelp(const char *prefix = nullptr);
Cmd* find(const zcstring& name);
Arg* findarg(const zcstring& name, char sf=NOSF);
Arg shallowcopy(const Arg& arg);
void add(){}
std::vector<Cmd> commands;
std::vector<Arg> globals;
// this is the command that successfully passed
Cmd *parsed{nullptr};
zcstring appname;
zcstring descript;
zcstring appversion;
size_t longestcmd{0};
size_t longestflag{0};
bool required{false};
bool inter{false};
};
zcstring readparam(const zcstring& display, const char *def);
zcstring readpasswd(const zcstring& display);
}
}
#endif //SUIL_CMDL_HPP
<|endoftext|> |
<commit_before>
int main()
{
return 0;
}<commit_msg>Add implementation for bundle-child-process<commit_after>#include <conio.h>
#include <cassert>
#include <iostream>
#include <string>
#include <Windows.h>
bool LaunchAndWait(const std::wstring& cmdline, HANDLE job)
{
wchar_t buf[255] {0};
wcscpy_s(buf, cmdline.c_str());
STARTUPINFO startup {0};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process_information {nullptr};
if (!CreateProcessW(nullptr,
buf,
nullptr,
nullptr,
FALSE,
CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,
nullptr,
nullptr,
&startup,
&process_information)) {
auto err = GetLastError();
std::cerr << "Failed to create process: " << err;
return false;
}
if (!AssignProcessToJobObject(job, process_information.hProcess)) {
std::cerr << "Failed to assign process to job: " << GetLastError();
return false;
}
ResumeThread(process_information.hThread);
CloseHandle(process_information.hProcess);
CloseHandle(process_information.hThread);
return true;
}
int main()
{
BOOL is_in_job;
IsProcessInJob(GetCurrentProcess(), nullptr, &is_in_job);
std::cout << "Is the main process in job: " << is_in_job << std::endl;
std::cout << "Wait for constructing job object!\n";
HANDLE job = CreateJobObjectW(nullptr, nullptr);
if (!job) {
auto err = GetLastError();
std::cerr << "Failed to create job: " << err << std::endl;
return 0;
}
JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_limits;
memset(&job_limits, 0, sizeof(job_limits));
job_limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &job_limits, sizeof(job_limits))) {
auto err = GetLastError();
std::cerr << "Failed to set job information: " << err << std::endl;
}
std::cout << "Job object created! Launch test subjects...\n";
bool r = LaunchAndWait(LR"(C:\Windows\notepad.exe)", job);
assert(r);
_getch();
return 0;
}<|endoftext|> |
<commit_before>#include <Arduino.h>
#include "state_search.h"
#include "settings.h"
#include "settings_internal.h"
#include "settings_eeprom.h"
#include "receiver.h"
#include "channels.h"
#include "buttons.h"
#include "ui.h"
void StateMachine::SearchStateHandler::onUpdate() {
Receiver::waitForStableRssi();
if (!manual) {
onUpdateAuto();
}
Ui::needUpdate();
}
void StateMachine::SearchStateHandler::onUpdateAuto() {
if (scanningPeak) {
uint8_t peaksIndex = peakChannelIndex - orderedChanelIndex;
peaks[peaksIndex] = Receiver::rssiA;
peakChannelIndex++;
if (peaksIndex >= PEAK_LOOKAHEAD || peakChannelIndex >= CHANNELS_SIZE) {
uint8_t largestPeak = 0;
uint8_t largestPeakIndex = 0;
for (uint8_t i = 0; i < PEAK_LOOKAHEAD; i++) {
uint8_t peak = peaks[i];
if (peak > largestPeak) {
largestPeak = peak;
largestPeakIndex = i;
}
}
uint8_t peakChannel = orderedChanelIndex + largestPeakIndex;
orderedChanelIndex = peakChannel;
Receiver::setChannel(Channels::getOrderedIndex(peakChannel));
scanningPeak = false;
} else {
Receiver::setChannel(Channels::getOrderedIndex(peakChannelIndex));
}
} else {
if (scanning) {
if (!forceNext && Receiver::rssiA >= RSSI_SEEK_TRESHOLD) {
scanning = false;
scanningPeak = true;
peakChannelIndex = orderedChanelIndex;
for (uint8_t i = 0; i < PEAK_LOOKAHEAD; i++)
peaks[i] = 0;
} else {
orderedChanelIndex += static_cast<int8_t>(direction);
if (orderedChanelIndex == 255)
orderedChanelIndex = CHANNELS_SIZE - 1;
else if (orderedChanelIndex >= CHANNELS_SIZE)
orderedChanelIndex = 0;
Receiver::setChannel(
Channels::getOrderedIndex(orderedChanelIndex));
if (forceNext)
forceNext = false;
}
}
}
}
void StateMachine::SearchStateHandler::onUpdateManual() {
}
void StateMachine::SearchStateHandler::onButtonChange() {
if (Buttons::get(Button::MODE)->pressed) {
manual = !manual;
}
if (manual) {
if (Buttons::get(Button::UP)->pressed) {
orderedChanelIndex += 1;
} else if (Buttons::get(Button::DOWN)->pressed) {
orderedChanelIndex -= 1;
}
if (orderedChanelIndex == 255)
orderedChanelIndex = CHANNELS_SIZE - 1;
else if (orderedChanelIndex >= CHANNELS_SIZE)
orderedChanelIndex = 0;
Receiver::setChannel(Channels::getOrderedIndex(orderedChanelIndex));
} else {
if (Buttons::get(Button::UP)->pressed) {
scanning = true;
forceNext = true;
direction = ScanDirection::UP;
} else if (Buttons::get(Button::DOWN)->pressed) {
scanning = true;
forceNext = true;
direction = ScanDirection::DOWN;
}
}
}
<commit_msg>Quick hack to allow quick scanning in manual search<commit_after>#include <Arduino.h>
#include "state_search.h"
#include "settings.h"
#include "settings_internal.h"
#include "settings_eeprom.h"
#include "receiver.h"
#include "channels.h"
#include "buttons.h"
#include "ui.h"
void StateMachine::SearchStateHandler::onUpdate() {
Receiver::waitForStableRssi();
if (!manual) {
onUpdateAuto();
} else {
onUpdateManual();
}
Ui::needUpdate();
}
void StateMachine::SearchStateHandler::onUpdateAuto() {
if (scanningPeak) {
uint8_t peaksIndex = peakChannelIndex - orderedChanelIndex;
peaks[peaksIndex] = Receiver::rssiA;
peakChannelIndex++;
if (peaksIndex >= PEAK_LOOKAHEAD || peakChannelIndex >= CHANNELS_SIZE) {
uint8_t largestPeak = 0;
uint8_t largestPeakIndex = 0;
for (uint8_t i = 0; i < PEAK_LOOKAHEAD; i++) {
uint8_t peak = peaks[i];
if (peak > largestPeak) {
largestPeak = peak;
largestPeakIndex = i;
}
}
uint8_t peakChannel = orderedChanelIndex + largestPeakIndex;
orderedChanelIndex = peakChannel;
Receiver::setChannel(Channels::getOrderedIndex(peakChannel));
scanningPeak = false;
} else {
Receiver::setChannel(Channels::getOrderedIndex(peakChannelIndex));
}
} else {
if (scanning) {
if (!forceNext && Receiver::rssiA >= RSSI_SEEK_TRESHOLD) {
scanning = false;
scanningPeak = true;
peakChannelIndex = orderedChanelIndex;
for (uint8_t i = 0; i < PEAK_LOOKAHEAD; i++)
peaks[i] = 0;
} else {
orderedChanelIndex += static_cast<int8_t>(direction);
if (orderedChanelIndex == 255)
orderedChanelIndex = CHANNELS_SIZE - 1;
else if (orderedChanelIndex >= CHANNELS_SIZE)
orderedChanelIndex = 0;
Receiver::setChannel(
Channels::getOrderedIndex(orderedChanelIndex));
if (forceNext)
forceNext = false;
}
}
}
}
void StateMachine::SearchStateHandler::onUpdateManual() {
if (
Buttons::get(Button::UP)->pressed &&
millis() - Buttons::get(Button::UP)->pressTime > 500
) {
orderedChanelIndex += 1;
}
if (
Buttons::get(Button::DOWN)->pressed &&
millis() - Buttons::get(Button::DOWN)->pressTime > 500
) {
orderedChanelIndex -= 1;
}
if (orderedChanelIndex == 255)
orderedChanelIndex = CHANNELS_SIZE - 1;
else if (orderedChanelIndex >= CHANNELS_SIZE)
orderedChanelIndex = 0;
Receiver::setChannel(Channels::getOrderedIndex(orderedChanelIndex));
}
void StateMachine::SearchStateHandler::onButtonChange() {
if (Buttons::get(Button::MODE)->pressed) {
manual = !manual;
}
if (manual) {
if (Buttons::get(Button::UP)->pressed) {
orderedChanelIndex += 1;
} else if (Buttons::get(Button::DOWN)->pressed) {
orderedChanelIndex -= 1;
}
if (orderedChanelIndex == 255)
orderedChanelIndex = CHANNELS_SIZE - 1;
else if (orderedChanelIndex >= CHANNELS_SIZE)
orderedChanelIndex = 0;
Receiver::setChannel(Channels::getOrderedIndex(orderedChanelIndex));
} else {
if (Buttons::get(Button::UP)->pressed) {
scanning = true;
forceNext = true;
direction = ScanDirection::UP;
} else if (Buttons::get(Button::DOWN)->pressed) {
scanning = true;
forceNext = true;
direction = ScanDirection::DOWN;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Fixed clang build errors<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "MockPagePopupDriver.h"
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoader.h"
#include "core/page/PagePopup.h"
#include "core/page/PagePopupController.h"
#include "platform/Timer.h"
namespace WebCore {
class MockPagePopup : public PagePopup, public RefCounted<MockPagePopup> {
public:
static PassRefPtr<MockPagePopup> create(PagePopupClient*, const IntRect& originBoundsInRootView, LocalFrame*);
virtual ~MockPagePopup();
void closeLater();
private:
MockPagePopup(PagePopupClient*, const IntRect& originBoundsInRootView, LocalFrame*);
void close(Timer<MockPagePopup>*);
PagePopupClient* m_popupClient;
RefPtr<HTMLIFrameElement> m_iframe;
Timer<MockPagePopup> m_closeTimer;
};
inline MockPagePopup::MockPagePopup(PagePopupClient* client, const IntRect& originBoundsInRootView, LocalFrame* mainFrame)
: m_popupClient(client)
, m_closeTimer(this, &MockPagePopup::close)
{
Document* document = mainFrame->document();
ASSERT(document);
m_iframe = HTMLIFrameElement::create(*document);
m_iframe->setIdAttribute("mock-page-popup");
m_iframe->setInlineStyleProperty(CSSPropertyBorderWidth, 0.0, CSSPrimitiveValue::CSS_PX);
m_iframe->setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
m_iframe->setInlineStyleProperty(CSSPropertyLeft, originBoundsInRootView.x(), CSSPrimitiveValue::CSS_PX, true);
m_iframe->setInlineStyleProperty(CSSPropertyTop, originBoundsInRootView.maxY(), CSSPrimitiveValue::CSS_PX, true);
if (document->body())
document->body()->appendChild(m_iframe.get());
const char scriptToSetUpPagePopupController[] = "<script>window.pagePopupController = parent.internals.pagePopupController;</script>";
RefPtr<SharedBuffer> data = SharedBuffer::create(scriptToSetUpPagePopupController, sizeof(scriptToSetUpPagePopupController));
m_popupClient->writeDocument(data.get());
toLocalFrame(m_iframe->contentFrame())->loader().load(FrameLoadRequest(0, blankURL(), SubstituteData(data, "text/html", "UTF-8", KURL(), ForceSynchronousLoad)));
}
PassRefPtr<MockPagePopup> MockPagePopup::create(PagePopupClient* client, const IntRect& originBoundsInRootView, LocalFrame* mainFrame)
{
return adoptRef(new MockPagePopup(client, originBoundsInRootView, mainFrame));
}
void MockPagePopup::closeLater()
{
ref();
m_popupClient->didClosePopup();
m_popupClient = 0;
// This can be called in detach(), and we should not change DOM structure
// during detach().
m_closeTimer.startOneShot(0, FROM_HERE);
}
void MockPagePopup::close(Timer<MockPagePopup>*)
{
deref();
}
MockPagePopup::~MockPagePopup()
{
if (m_iframe && m_iframe->parentNode())
m_iframe->parentNode()->removeChild(m_iframe.get());
}
inline MockPagePopupDriver::MockPagePopupDriver(LocalFrame* mainFrame)
: m_mainFrame(mainFrame)
{
}
PassOwnPtr<MockPagePopupDriver> MockPagePopupDriver::create(LocalFrame* mainFrame)
{
return adoptPtr(new MockPagePopupDriver(mainFrame));
}
MockPagePopupDriver::~MockPagePopupDriver()
{
closePagePopup(m_mockPagePopup.get());
}
PagePopup* MockPagePopupDriver::openPagePopup(PagePopupClient* client, const IntRect& originBoundsInRootView)
{
if (m_mockPagePopup)
closePagePopup(m_mockPagePopup.get());
if (!client || !m_mainFrame)
return 0;
m_pagePopupController = PagePopupController::create(client);
m_mockPagePopup = MockPagePopup::create(client, originBoundsInRootView, m_mainFrame);
return m_mockPagePopup.get();
}
void MockPagePopupDriver::closePagePopup(PagePopup* popup)
{
if (!popup || popup != m_mockPagePopup.get())
return;
m_mockPagePopup->closeLater();
m_mockPagePopup.clear();
m_pagePopupController->clearPagePopupClient();
m_pagePopupController.clear();
}
}
<commit_msg>Handle failure to initialize MockPagePopup<commit_after>/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "MockPagePopupDriver.h"
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoader.h"
#include "core/page/PagePopup.h"
#include "core/page/PagePopupController.h"
#include "platform/Timer.h"
namespace WebCore {
class MockPagePopup : public PagePopup, public RefCounted<MockPagePopup> {
public:
static PassRefPtr<MockPagePopup> create(PagePopupClient*, const IntRect& originBoundsInRootView, LocalFrame*);
virtual ~MockPagePopup();
bool initialize();
void closeLater();
private:
MockPagePopup(PagePopupClient*, const IntRect& originBoundsInRootView, LocalFrame*);
void close(Timer<MockPagePopup>*);
PagePopupClient* m_popupClient;
RefPtr<HTMLIFrameElement> m_iframe;
Timer<MockPagePopup> m_closeTimer;
};
inline MockPagePopup::MockPagePopup(PagePopupClient* client, const IntRect& originBoundsInRootView, LocalFrame* mainFrame)
: m_popupClient(client)
, m_closeTimer(this, &MockPagePopup::close)
{
Document* document = mainFrame->document();
ASSERT(document);
m_iframe = HTMLIFrameElement::create(*document);
m_iframe->setIdAttribute("mock-page-popup");
m_iframe->setInlineStyleProperty(CSSPropertyBorderWidth, 0.0, CSSPrimitiveValue::CSS_PX);
m_iframe->setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
m_iframe->setInlineStyleProperty(CSSPropertyLeft, originBoundsInRootView.x(), CSSPrimitiveValue::CSS_PX, true);
m_iframe->setInlineStyleProperty(CSSPropertyTop, originBoundsInRootView.maxY(), CSSPrimitiveValue::CSS_PX, true);
if (document->body())
document->body()->appendChild(m_iframe.get());
}
bool MockPagePopup::initialize()
{
const char scriptToSetUpPagePopupController[] = "<script>window.pagePopupController = parent.internals.pagePopupController;</script>";
RefPtr<SharedBuffer> data = SharedBuffer::create(scriptToSetUpPagePopupController, sizeof(scriptToSetUpPagePopupController));
m_popupClient->writeDocument(data.get());
LocalFrame* localFrame = toLocalFrame(m_iframe->contentFrame());
if (!localFrame)
return false;
localFrame->loader().load(FrameLoadRequest(0, blankURL(), SubstituteData(data, "text/html", "UTF-8", KURL(), ForceSynchronousLoad)));
return true;
}
PassRefPtr<MockPagePopup> MockPagePopup::create(PagePopupClient* client, const IntRect& originBoundsInRootView, LocalFrame* mainFrame)
{
return adoptRef(new MockPagePopup(client, originBoundsInRootView, mainFrame));
}
void MockPagePopup::closeLater()
{
ref();
m_popupClient->didClosePopup();
m_popupClient = 0;
// This can be called in detach(), and we should not change DOM structure
// during detach().
m_closeTimer.startOneShot(0, FROM_HERE);
}
void MockPagePopup::close(Timer<MockPagePopup>*)
{
deref();
}
MockPagePopup::~MockPagePopup()
{
if (m_iframe && m_iframe->parentNode())
m_iframe->parentNode()->removeChild(m_iframe.get());
}
inline MockPagePopupDriver::MockPagePopupDriver(LocalFrame* mainFrame)
: m_mainFrame(mainFrame)
{
}
PassOwnPtr<MockPagePopupDriver> MockPagePopupDriver::create(LocalFrame* mainFrame)
{
return adoptPtr(new MockPagePopupDriver(mainFrame));
}
MockPagePopupDriver::~MockPagePopupDriver()
{
closePagePopup(m_mockPagePopup.get());
}
PagePopup* MockPagePopupDriver::openPagePopup(PagePopupClient* client, const IntRect& originBoundsInRootView)
{
if (m_mockPagePopup)
closePagePopup(m_mockPagePopup.get());
if (!client || !m_mainFrame)
return 0;
m_pagePopupController = PagePopupController::create(client);
m_mockPagePopup = MockPagePopup::create(client, originBoundsInRootView, m_mainFrame);
if (!m_mockPagePopup->initialize()) {
m_mockPagePopup->closeLater();
m_mockPagePopup.clear();
}
return m_mockPagePopup.get();
}
void MockPagePopupDriver::closePagePopup(PagePopup* popup)
{
if (!popup || popup != m_mockPagePopup.get())
return;
m_mockPagePopup->closeLater();
m_mockPagePopup.clear();
m_pagePopupController->clearPagePopupClient();
m_pagePopupController.clear();
}
}
<|endoftext|> |
<commit_before>#ifndef __INGAME_SCENE_HPP__
#define __INGAME_SCENE_HPP__
#include <Core/Engine.hh>
#include <Core/AScene.hh>
/////////////
// RESOURCES
/////////////
#include <ResourceManager/Texture.hh>
#include <ResourceManager/CubeMap.hh>
#include <ResourceManager/SharedMesh.hh>
/////////////
// SYSTEMS
/////////////
#include <Systems/MeshRenderSystem.h>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/TrackBallSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/BulletCollisionSystem.hpp>
#include <Systems/VelocitySystem.hpp>
#include <Systems/CollisionAdderSystem.hpp>
#include <Systems/CollisionCleanerSystem.hpp>
#include <Systems/BulletDynamicSystem.hpp>
#include <Systems/FPControllerSystem.hpp>
#include <Systems/FirstPersonViewSystem.hpp>
////////////
// COMPONENTS
////////////
#include <Components/CameraComponent.hh>
#include <Components/GraphNode.hpp>
#include <Components/FPController.hpp>
#include <Components/FirstPersonView.hpp>
#include <Components/VelocityComponent.hpp>
#include <Components/RigidBody.hpp>
class InGameScene : public AScene
{
public:
InGameScene(Engine &engine)
: AScene(engine)
{}
virtual ~InGameScene(void)
{}
virtual bool userStart()
{
addSystem<MeshRendererSystem>(0);
addSystem<GraphNodeSystem>(1); // UPDATE GRAPH NODE POSITION
addSystem<BulletDynamicSystem>(10); // CHECK FOR COLLISIONS
addSystem<CollisionAdder>(20); // ADD COLLISION COMPONENT TO COLLIDING ELEMENTS
addSystem<VelocitySystem>(50); // UPDATE VELOCITY
addSystem<FPControllerSystem>(60); // UPDATE FIRST PERSON CONTROLLER
addSystem<TrackBallSystem>(150); // UPDATE CAMERA TRACKBALL BEHAVIOR
addSystem<FirstPersonViewSystem>(150); // UPDATE FIRST PERSON CAMERA
addSystem<CameraSystem>(200); // UPDATE CAMERA AND RENDER TO SCREEN
addSystem<CollisionCleaner>(300); // REMOVE COLLISION COMPONENT FROM COLLIDING ELEMENTS
std::string perModelVars[] =
{
"model"
};
std::string perFrameVars[] =
{
"projection",
"view",
"light",
"time"
};
std::string materialBasic[] =
{
"ambient",
"diffuse",
"specular",
"transmittance",
"emission",
"shininess"
};
OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("MaterialBasic",
"./Shaders/MaterialBasic.vp",
"./Shaders/MaterialBasic.fp");
_engine.getInstance<Renderer>().addUniform("MaterialBasic")
.init(&s, "MaterialBasic", materialBasic);
_engine.getInstance<Renderer>().addUniform("PerFrame")
.init(&s, "PerFrame", perFrameVars);
_engine.getInstance<Renderer>().addUniform("PerModel")
.init(&s, "PerModel", perModelVars);
_engine.getInstance<Renderer>().getShader("MaterialBasic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
_engine.getInstance<Renderer>().addShader("basic", "Shaders/basic.vp", "Shaders/basic.fp", "Shaders/basic.gp");
_engine.getInstance<Renderer>().addShader("basicLight", "Shaders/light.vp", "Shaders/light.fp");
_engine.getInstance<Renderer>().addShader("bump", "Shaders/bump.vp", "Shaders/bump.fp");
_engine.getInstance<Renderer>().addShader("fboToScreen", "Shaders/fboToScreen.vp", "Shaders/fboToScreen.fp");
_engine.getInstance<Renderer>().addShader("brightnessFilter", "Shaders/brightnessFilter.vp", "Shaders/brightnessFilter.fp");
_engine.getInstance<Renderer>().addShader("blurY", "Shaders/brightnessFilter.vp", "Shaders/blur1.fp");
_engine.getInstance<Renderer>().getShader("basic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().getShader("basicLight")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().getShader("bump")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(2).build();
_engine.getInstance<Renderer>().getShader("fboToScreen")->addTarget(GL_COLOR_ATTACHMENT0)
.addLayer(GL_COLOR_ATTACHMENT0).build();
// _engine.getInstance<Renderer>().getShader("earth")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
_engine.getInstance<Renderer>().getShader("brightnessFilter")->addTarget(GL_COLOR_ATTACHMENT1)
.addLayer(GL_COLOR_ATTACHMENT0).build();
_engine.getInstance<Renderer>().getShader("blurY")->addTarget(GL_COLOR_ATTACHMENT2)
.addLayer(GL_COLOR_ATTACHMENT0).addLayer(GL_COLOR_ATTACHMENT1).build();
_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));
_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerModel", "PerModel");
// _engine.getInstance<Renderer>().bindShaderToUniform("basic", "MaterialBasic", "MateriaBasic");
_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "MaterialBasic", "MaterialBasic");
_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerModel", "PerModel");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/ball.obj");
SmartPointer<Resources::Texture> toRepeat = new Resources::Texture();
toRepeat->setWrapMode(GL_REPEAT);
_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earth", new Resources::Texture(), "./Assets/EarthTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthBump", new Resources::Texture(), "./Assets/EarthTextureBump.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthNight", new Resources::Texture(), "./Assets/EarthNightTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthClouds", toRepeat, "./Assets/EarthClouds.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:moon", new Resources::Texture(), "./Assets/MoonTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:moonBump", new Resources::Texture(), "./Assets/MoonNormalMap.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("cubemap:space", new Resources::CubeMap(), "./Assets/lake.skybox");
std::string vars[] =
{
"projection",
"view"
};
OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");
_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().addUniform("cameraUniform").
init(&sky, "cameraUniform", vars);
_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");
////////////////////////
/////////
// COMPLEXE OBJ LOAD TEST
///
///
// _engine.getInstance<Resources::ResourceManager>().addResource("model:sponza", new Resources::SharedMesh(), "./Assets/dabrovic-sponza/sponza.obj");
_engine.getInstance<Resources::ResourceManager>().addResource("model:sponza", new Resources::SharedMesh(), "./Assets/city/city.obj");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:sponza", new Resources::SharedMesh(), "./Assets/cube/cube.obj");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/head/head.obj");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:galileo", new Resources::SharedMesh(), "./Assets/galileo/galileo.obj");
_engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/ball/ball.obj");
///
///
///
////////
////////////////////////
/////////////////////////////
/////
/////
///// !!!! GAME
/////
////
///
//
// HEROS
Handle heros;
{
heros = createHeros(glm::vec3(3, -10, 2));
heros->setLocalTransform() = glm::scale(heros->getLocalTransform(), glm::vec3(100, 100, 100));
// heros->setLocalTransform() = glm::rotate(heros->getLocalTransform(), 2.0f, glm::vec3(0, 1, 1));
auto rigidBody = heros->addComponent<Component::RigidBody>();
rigidBody->setMass(0.0f);
rigidBody->setCollisionShape(Component::RigidBody::MESH, "model:sponza");
auto mesh = heros->addComponent<Component::MeshRenderer>("model:sponza");
mesh->setShader("MaterialBasic");
}
// {
// auto heros = createHeros(glm::vec3(2, 40, 5));
// heros->setLocalTransform() = glm::scale(heros->getLocalTransform(), glm::vec3(5));
//// heros->setLocalTransform() = glm::rotate(heros->getLocalTransform(), 2.0f, glm::vec3(0, 1, 1));
// auto rigidBody = heros->addComponent<Component::RigidBody>();
// rigidBody->setMass(0.0f);
// rigidBody->setCollisionShape(Component::RigidBody::CONCAVE_STATIC_MESH, "model:sponza");
// auto mesh = heros->addComponent<Component::MeshRenderer>("model:sponza");
// mesh->setShader("MaterialBasic");
// }
for (auto i = 0; i < 100; ++i)
{
}
//{
// auto heros = createHeros(glm::vec3(10, 100, 1));
// heros->setLocalTransform() = glm::scale(heros->getLocalTransform(), glm::vec3(2,1,1));
// heros->addComponent<Component::FPController>();
// heros->addComponent<Component::FirstPersonView>();
// auto cameraComponent = heros->addComponent<Component::CameraComponent>();
// cameraComponent->attachSkybox("cubemap:space", "cubemapShader");
//}
auto camera = createEntity();
camera->addComponent<Component::GraphNode>();
auto cameraComponent = camera->addComponent<Component::CameraComponent>();
auto trackBall = camera->addComponent<Component::TrackBall>(heros, 5.0f, 3.0f, 1.0f);
// CAMERA
//auto camera = createEntity();
//camera->addComponent<Component::GraphNode>();
//auto cameraComponent = camera->addComponent<Component::CameraComponent>();
//auto trackBall = camera->addComponent<Component::TrackBall>(heros, 5.0f, 3.0f, 1.0f);
return true;
}
Handle createHeros(const glm::vec3 &pos)
{
auto e = createEntity();
e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
e->addComponent<Component::GraphNode>();
// material->pushShader("basic");
e->addComponent<Component::MaterialComponent>(std::string("material:heros"));
auto material = _engine.getInstance<Renderer>().getMaterialManager().createMaterial("material:heros");
// mesh->addTexture("texture:sun", 0);
//mesh->addTexture("texture:earthNight", 1);
//mesh->addTexture("texture:earthClouds", 2);
//mesh->addTexture("texture:earthBump", 3);
return e;
}
virtual bool userUpdate(double time)
{
if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
_engine.getInstance<Input>().getInput(SDL_QUIT))
return (false);
static auto lol = 0.0f;
if (_engine.getInstance<Input>().getInput(SDLK_r) && lol <= 0.0f)
{
lol = 2.0f;
for (auto i = 0; i < 10; ++i)
{
auto heros = createHeros(glm::vec3(rand() % 20, 50 + rand() % 100, rand() % 20));
heros->setLocalTransform() = glm::scale(heros->getLocalTransform(), glm::vec3((float)(rand() % 10) / 0.8));
// heros->setLocalTransform() = glm::rotate(heros->getLocalTransform(), 90.0f, glm::vec3(0, 1, 1));
auto rigidBody = heros->addComponent<Component::RigidBody>();
rigidBody->setMass(1.0f);
rigidBody->setCollisionShape(Component::RigidBody::SPHERE);
auto mesh = heros->addComponent<Component::MeshRenderer>("model:ball");
//heros->addComponent<Component::FPController>();
mesh->setShader("MaterialBasic");
}
}
if (lol > 0.0f)
lol -= time;
return (true);
}
};
#endif //__INGAME_SCENE_HPP__<commit_msg>Some test scene cleanings<commit_after>#ifndef __INGAME_SCENE_HPP__
#define __INGAME_SCENE_HPP__
#include <Core/Engine.hh>
#include <Core/AScene.hh>
/////////////
// RESOURCES
/////////////
#include <ResourceManager/Texture.hh>
#include <ResourceManager/CubeMap.hh>
#include <ResourceManager/SharedMesh.hh>
/////////////
// SYSTEMS
/////////////
#include <Systems/MeshRenderSystem.h>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/TrackBallSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/BulletCollisionSystem.hpp>
#include <Systems/VelocitySystem.hpp>
#include <Systems/CollisionAdderSystem.hpp>
#include <Systems/CollisionCleanerSystem.hpp>
#include <Systems/BulletDynamicSystem.hpp>
#include <Systems/FPControllerSystem.hpp>
#include <Systems/FirstPersonViewSystem.hpp>
////////////
// COMPONENTS
////////////
#include <Components/CameraComponent.hh>
#include <Components/GraphNode.hpp>
#include <Components/FPController.hpp>
#include <Components/FirstPersonView.hpp>
#include <Components/VelocityComponent.hpp>
#include <Components/RigidBody.hpp>
class InGameScene : public AScene
{
public:
InGameScene(Engine &engine)
: AScene(engine)
{}
virtual ~InGameScene(void)
{}
virtual bool userStart()
{
addSystem<MeshRendererSystem>(0);
addSystem<GraphNodeSystem>(1); // UPDATE GRAPH NODE POSITION
addSystem<BulletDynamicSystem>(10); // CHECK FOR COLLISIONS
addSystem<CollisionAdder>(20); // ADD COLLISION COMPONENT TO COLLIDING ELEMENTS
addSystem<VelocitySystem>(50); // UPDATE VELOCITY
addSystem<FPControllerSystem>(60); // UPDATE FIRST PERSON CONTROLLER
addSystem<TrackBallSystem>(150); // UPDATE CAMERA TRACKBALL BEHAVIOR
addSystem<FirstPersonViewSystem>(150); // UPDATE FIRST PERSON CAMERA
addSystem<CameraSystem>(200); // UPDATE CAMERA AND RENDER TO SCREEN
addSystem<CollisionCleaner>(300); // REMOVE COLLISION COMPONENT FROM COLLIDING ELEMENTS
std::string perModelVars[] =
{
"model"
};
std::string perFrameVars[] =
{
"projection",
"view",
"light",
"time"
};
std::string materialBasic[] =
{
"ambient",
"diffuse",
"specular",
"transmittance",
"emission",
"shininess"
};
OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("MaterialBasic",
"./Shaders/MaterialBasic.vp",
"./Shaders/MaterialBasic.fp");
_engine.getInstance<Renderer>().addUniform("MaterialBasic")
.init(&s, "MaterialBasic", materialBasic);
_engine.getInstance<Renderer>().addUniform("PerFrame")
.init(&s, "PerFrame", perFrameVars);
_engine.getInstance<Renderer>().addUniform("PerModel")
.init(&s, "PerModel", perModelVars);
_engine.getInstance<Renderer>().getShader("MaterialBasic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));
_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "MaterialBasic", "MaterialBasic");
SmartPointer<Resources::Texture> toRepeat = new Resources::Texture();
toRepeat->setWrapMode(GL_REPEAT);
_engine.getInstance<Resources::ResourceManager>().addResource("cubemap:space", new Resources::CubeMap(), "./Assets/lake.skybox");
std::string vars[] =
{
"projection",
"view"
};
OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");
_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().addUniform("cameraUniform").
init(&sky, "cameraUniform", vars);
_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");
////////////////////////
/////////
// COMPLEXE OBJ LOAD TEST
///
///
_engine.getInstance<Resources::ResourceManager>().addResource("model:sponza", new Resources::SharedMesh(), "./Assets/dabrovic-sponza/sponza.obj");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:sponza", new Resources::SharedMesh(), "./Assets/city/city.obj");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:sponza", new Resources::SharedMesh(), "./Assets/cube/cube.obj");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/head/head.obj");
// _engine.getInstance<Resources::ResourceManager>().addResource("model:galileo", new Resources::SharedMesh(), "./Assets/galileo/galileo.obj");
_engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/ball/ball.obj");
///
///
///
////////
////////////////////////
/////////////////////////////
/////
/////
///// !!!! GAME
/////
////
///
//
// HEROS
Handle heros;
{
heros = createHeros(glm::vec3(3, -10, 2));
heros->setLocalTransform() = glm::scale(heros->getLocalTransform(), glm::vec3(100, 100, 100));
auto rigidBody = heros->addComponent<Component::RigidBody>();
rigidBody->setMass(0.0f);
rigidBody->setCollisionShape(Component::RigidBody::MESH, "model:sponza");
auto mesh = heros->addComponent<Component::MeshRenderer>("model:sponza");
mesh->setShader("MaterialBasic");
}
auto camera = createEntity();
camera->addComponent<Component::GraphNode>();
auto cameraComponent = camera->addComponent<Component::CameraComponent>();
auto trackBall = camera->addComponent<Component::TrackBall>(heros, 5.0f, 3.0f, 1.0f);
cameraComponent->attachSkybox("cubemap:space", "cubemapShader");
return true;
}
Handle createHeros(const glm::vec3 &pos)
{
auto e = createEntity();
e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
e->addComponent<Component::GraphNode>();
e->addComponent<Component::MaterialComponent>(std::string("material:heros"));
auto material = _engine.getInstance<Renderer>().getMaterialManager().createMaterial("material:heros");
return e;
}
virtual bool userUpdate(double time)
{
if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
_engine.getInstance<Input>().getInput(SDL_QUIT))
return (false);
static auto timer = 0.0f;
if (_engine.getInstance<Input>().getInput(SDLK_r) && timer <= 0.0f)
{
timer = 2.0f;
for (auto i = 0; i < 10; ++i)
{
auto heros = createHeros(glm::vec3(rand() % 20, 50 + rand() % 100, rand() % 20));
heros->setLocalTransform() = glm::scale(heros->getLocalTransform(), glm::vec3((float)(rand() % 10) / 0.8));
auto rigidBody = heros->addComponent<Component::RigidBody>();
rigidBody->setMass(1.0f);
rigidBody->setCollisionShape(Component::RigidBody::SPHERE);
auto mesh = heros->addComponent<Component::MeshRenderer>("model:ball");
mesh->setShader("MaterialBasic");
}
}
if (timer > 0.0f)
timer -= time;
return (true);
}
};
#endif //__INGAME_SCENE_HPP__<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/accessibility/AXTableRow.h"
#include "core/rendering/RenderTableRow.h"
#include "modules/accessibility/AXTableCell.h"
namespace blink {
using namespace HTMLNames;
AXTableRow::AXTableRow(RenderObject* renderer)
: AXRenderObject(renderer)
{
}
AXTableRow::~AXTableRow()
{
}
PassRefPtr<AXTableRow> AXTableRow::create(RenderObject* renderer)
{
return adoptRef(new AXTableRow(renderer));
}
AccessibilityRole AXTableRow::determineAccessibilityRole()
{
if (!isTableRow())
return AXRenderObject::determineAccessibilityRole();
m_ariaRole = determineAriaRoleAttribute();
AccessibilityRole ariaRole = ariaRoleAttribute();
if (ariaRole != UnknownRole)
return ariaRole;
return RowRole;
}
bool AXTableRow::isTableRow() const
{
AXObject* table = parentTable();
if (!table || !table->isAXTable())
return false;
return true;
}
AXObject* AXTableRow::observableObject() const
{
// This allows the table to be the one who sends notifications about tables.
return parentTable();
}
bool AXTableRow::computeAccessibilityIsIgnored() const
{
AXObjectInclusion decision = defaultObjectInclusion();
if (decision == IncludeObject)
return false;
if (decision == IgnoreObject)
return true;
if (!isTableRow())
return AXRenderObject::computeAccessibilityIsIgnored();
return false;
}
AXObject* AXTableRow::parentTable() const
{
AXObject* parent = parentObjectUnignored();
if (!parent || !parent->isAXTable())
return 0;
return parent;
}
AXObject* AXTableRow::headerObject()
{
if (!m_renderer || !m_renderer->isTableRow())
return 0;
AccessibilityChildrenVector rowChildren = children();
if (!rowChildren.size())
return 0;
// check the first element in the row to see if it is a TH element
AXObject* cell = rowChildren[0].get();
if (!cell->isTableCell())
return 0;
RenderObject* cellRenderer = toAXTableCell(cell)->renderer();
if (!cellRenderer)
return 0;
Node* cellNode = cellRenderer->node();
if (!cellNode || !cellNode->hasTagName(thTag))
return 0;
return cell;
}
} // namespace blink
<commit_msg>Do the early return when role is different than UnknownRole<commit_after>/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/accessibility/AXTableRow.h"
#include "core/rendering/RenderTableRow.h"
#include "modules/accessibility/AXTableCell.h"
namespace blink {
using namespace HTMLNames;
AXTableRow::AXTableRow(RenderObject* renderer)
: AXRenderObject(renderer)
{
}
AXTableRow::~AXTableRow()
{
}
PassRefPtr<AXTableRow> AXTableRow::create(RenderObject* renderer)
{
return adoptRef(new AXTableRow(renderer));
}
AccessibilityRole AXTableRow::determineAccessibilityRole()
{
if (!isTableRow())
return AXRenderObject::determineAccessibilityRole();
if ((m_ariaRole = determineAriaRoleAttribute()) != UnknownRole)
return m_ariaRole;
return RowRole;
}
bool AXTableRow::isTableRow() const
{
AXObject* table = parentTable();
if (!table || !table->isAXTable())
return false;
return true;
}
AXObject* AXTableRow::observableObject() const
{
// This allows the table to be the one who sends notifications about tables.
return parentTable();
}
bool AXTableRow::computeAccessibilityIsIgnored() const
{
AXObjectInclusion decision = defaultObjectInclusion();
if (decision == IncludeObject)
return false;
if (decision == IgnoreObject)
return true;
if (!isTableRow())
return AXRenderObject::computeAccessibilityIsIgnored();
return false;
}
AXObject* AXTableRow::parentTable() const
{
AXObject* parent = parentObjectUnignored();
if (!parent || !parent->isAXTable())
return 0;
return parent;
}
AXObject* AXTableRow::headerObject()
{
if (!m_renderer || !m_renderer->isTableRow())
return 0;
AccessibilityChildrenVector rowChildren = children();
if (!rowChildren.size())
return 0;
// check the first element in the row to see if it is a TH element
AXObject* cell = rowChildren[0].get();
if (!cell->isTableCell())
return 0;
RenderObject* cellRenderer = toAXTableCell(cell)->renderer();
if (!cellRenderer)
return 0;
Node* cellNode = cellRenderer->node();
if (!cellNode || !cellNode->hasTagName(thTag))
return 0;
return cell;
}
} // namespace blink
<|endoftext|> |
<commit_before>#include "vtkBarMark.h"
#include "vtkContextScene.h"
#include "vtkContextView.h"
#include "vtkDoubleArray.h"
#include "vtkLineMark.h"
#include "vtkMarkUtil.h"
#include "vtkPanelMark.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTable.h"
namespace
{
double PanelLeftFunction(vtkMark* m, vtkDataElement& vtkNotUsed(d))
{
return 20 + m->GetIndex()*15;
}
vtkDataElement DataFunction(vtkMark* vtkNotUsed(m), vtkDataElement& d)
{
return d;
}
double LeftFunction(vtkMark* m, vtkDataElement& vtkNotUsed(d))
{
return m->GetIndex()* 20;
}
double HeightFunction(vtkMark* vtkNotUsed(m), vtkDataElement& d)
{
return d.GetValue().ToDouble()* 80;
}
}
int TestMarks(int argc, char* argv[])
{
// Set up a 2D context view, context test object and add it to the scene
vtkSmartPointer<vtkContextView> view = vtkSmartPointer<vtkContextView>::New();
view->GetRenderer()->SetBackground(1.0, 1.0, 1.0);
view->GetRenderWindow()->SetSize(400, 400);
vtkSmartPointer<vtkTable> t = vtkSmartPointer<vtkTable>::New();
vtkSmartPointer<vtkDoubleArray> arr1 = vtkSmartPointer<vtkDoubleArray>::New();
arr1->SetName("Array1");
vtkSmartPointer<vtkDoubleArray> arr2 = vtkSmartPointer<vtkDoubleArray>::New();
arr2->SetName("Array2");
vtkSmartPointer<vtkDoubleArray> arr3 = vtkSmartPointer<vtkDoubleArray>::New();
arr3->SetName("Array3");
for (vtkIdType i = 0; i < 20; ++i)
{
arr1->InsertNextValue(sin(i/5.0) + 1);
arr2->InsertNextValue(cos(i/5.0) + 1);
arr3->InsertNextValue(i/10.0);
}
t->AddColumn(arr1);
t->AddColumn(arr2);
t->AddColumn(arr3);
vtkDataElement data(t);
data.SetDimension(1);
vtkSmartPointer<vtkPanelMark> panel = vtkSmartPointer<vtkPanelMark>::New();
view->GetScene()->AddItem(panel);
panel->SetData(data);
//panel->SetLeft(PanelLeftFunction);
panel->SetLeft(2);
panel->SetBottom(2);
vtkMark* bar = panel->Add(vtkMark::BAR);
bar->SetData(DataFunction);
bar->SetLeft(LeftFunction);
bar->SetBottom(vtkMarkUtil::StackBottom);
//bar->SetBottom(0.0);
bar->SetWidth(15);
bar->SetHeight(HeightFunction);
vtkMark* line = panel->Add(vtkMark::LINE);
line->SetLineColor(vtkMarkUtil::DefaultSeriesColor);
line->SetLineWidth(2);
line->SetBottom(bar->GetHeight());
view->GetInteractor()->Initialize();
int retVal = vtkRegressionTestImage(view->GetRenderWindow());
if(retVal == vtkRegressionTester::DO_INTERACTOR)
{
view->GetInteractor()->Start();
}
return !retVal;
}
<commit_msg>BUG:Force to not use multisampling.<commit_after>#include "vtkBarMark.h"
#include "vtkContextScene.h"
#include "vtkContextView.h"
#include "vtkDoubleArray.h"
#include "vtkLineMark.h"
#include "vtkMarkUtil.h"
#include "vtkPanelMark.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTable.h"
namespace
{
double PanelLeftFunction(vtkMark* m, vtkDataElement& vtkNotUsed(d))
{
return 20 + m->GetIndex()*15;
}
vtkDataElement DataFunction(vtkMark* vtkNotUsed(m), vtkDataElement& d)
{
return d;
}
double LeftFunction(vtkMark* m, vtkDataElement& vtkNotUsed(d))
{
return m->GetIndex()* 20;
}
double HeightFunction(vtkMark* vtkNotUsed(m), vtkDataElement& d)
{
return d.GetValue().ToDouble()* 80;
}
}
int TestMarks(int argc, char* argv[])
{
// Set up a 2D context view, context test object and add it to the scene
vtkSmartPointer<vtkContextView> view = vtkSmartPointer<vtkContextView>::New();
view->GetRenderer()->SetBackground(1.0, 1.0, 1.0);
view->GetRenderWindow()->SetSize(400, 400);
view->GetRenderWindow()->SetMultiSamples(0);
vtkSmartPointer<vtkTable> t = vtkSmartPointer<vtkTable>::New();
vtkSmartPointer<vtkDoubleArray> arr1 = vtkSmartPointer<vtkDoubleArray>::New();
arr1->SetName("Array1");
vtkSmartPointer<vtkDoubleArray> arr2 = vtkSmartPointer<vtkDoubleArray>::New();
arr2->SetName("Array2");
vtkSmartPointer<vtkDoubleArray> arr3 = vtkSmartPointer<vtkDoubleArray>::New();
arr3->SetName("Array3");
for (vtkIdType i = 0; i < 20; ++i)
{
arr1->InsertNextValue(sin(i/5.0) + 1);
arr2->InsertNextValue(cos(i/5.0) + 1);
arr3->InsertNextValue(i/10.0);
}
t->AddColumn(arr1);
t->AddColumn(arr2);
t->AddColumn(arr3);
vtkDataElement data(t);
data.SetDimension(1);
vtkSmartPointer<vtkPanelMark> panel = vtkSmartPointer<vtkPanelMark>::New();
view->GetScene()->AddItem(panel);
panel->SetData(data);
//panel->SetLeft(PanelLeftFunction);
panel->SetLeft(2);
panel->SetBottom(2);
vtkMark* bar = panel->Add(vtkMark::BAR);
bar->SetData(DataFunction);
bar->SetLeft(LeftFunction);
bar->SetBottom(vtkMarkUtil::StackBottom);
//bar->SetBottom(0.0);
bar->SetWidth(15);
bar->SetHeight(HeightFunction);
vtkMark* line = panel->Add(vtkMark::LINE);
line->SetLineColor(vtkMarkUtil::DefaultSeriesColor);
line->SetLineWidth(2);
line->SetBottom(bar->GetHeight());
view->GetInteractor()->Initialize();
int retVal = vtkRegressionTestImage(view->GetRenderWindow());
if(retVal == vtkRegressionTester::DO_INTERACTOR)
{
view->GetInteractor()->Start();
}
return !retVal;
}
<|endoftext|> |
<commit_before>/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common/FatalException.hpp"
#include <cxxabi.h> // for abi
#include <execinfo.h> // for backtrace, backtrace_symbols
#include <cstdlib> // for malloc/free
#include <cstring> // for strn*
#include <dlfcn.h>
#include <stdio.h> // for fopen, fprintf, fclose
#include <string.h>
#include <ucontext.h>
namespace voltdb {
FatalException::FatalException(std::string message,
const char *filename, unsigned long lineno,
std::string backtrace_path)
: m_reason(message)
, m_filename(filename), m_lineno(lineno)
, m_backtracepath(backtrace_path)
{
FILE *bt = fopen(m_backtracepath.c_str(), "a+");
/**
* Stack trace code from http://tombarta.wordpress.com/2008/08/01/c-stack-traces-with-gcc/
*/
void *traces[128];
for (int i=0; i < 128; i++) traces[i] = NULL; // silence valgrind
const int numTraces = backtrace( traces, 128);
char** traceSymbols = backtrace_symbols( traces, numTraces);
// write header for backtrace file
if (bt) fprintf(bt, "VoltDB Backtrace (%d)\n", numTraces);
for (int ii = 0; ii < numTraces; ii++) {
std::size_t sz = 200;
// Note: must use malloc vs. new so __cxa_demangle can use realloc.
char *function = static_cast<char*>(::malloc(sz));
char *begin = NULL, *end = NULL;
// write original symbol to file.
if (bt) fprintf(bt, "raw[%d]: %s\n", ii, traceSymbols[ii]);
//Find parens surrounding mangled name
for (char *j = traceSymbols[ii]; *j; ++j) {
if (*j == '(') {
begin = j;
}
else if (*j == '+') {
end = j;
}
}
if (begin && end) {
*begin++ = '\0';
*end = '\0';
int status;
char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
if (ret) {
//return value may be a realloc of input
function = ret;
} else {
// demangle failed, treat it like a C function with no args
strncpy(function, begin, sz);
strncat(function, "()", sz);
function[sz-1] = '\0';
}
m_traces.push_back(std::string(function));
} else {
//didn't find the mangled name in the trace
m_traces.push_back(std::string(traceSymbols[ii]));
}
::free(function);
}
if (bt) {
for (int ii=0; ii < m_traces.size(); ii++) {
const char* str = m_traces[ii].c_str();
fprintf(bt, "demangled[%d]: %s\n", ii, str);
}
fclose(bt);
}
::free(traceSymbols);
}
void FatalException::reportAnnotations(const std::string& str)
{
FILE *bt = fopen(m_backtracepath.c_str(), "a+");
if (!bt) {
return;
}
// append to backtrace file
fprintf(bt, "Additional annotations to the above Fatal Exception:\n%s", str.c_str());
fclose(bt);
}
FatalLogicError::FatalLogicError(const std::string buffer, const char *filename, unsigned long lineno)
: FatalLogicErrorBaseInitializer("FatalLogicError")
, m_fatality(buffer, filename, lineno)
{
initWhat();
}
FatalLogicError::~FatalLogicError() throw () {} // signature required by exception base class?
void FatalLogicError::initWhat()
{
std::ostringstream buffer;
buffer << m_fatality;
m_whatwhat = buffer.str();
}
void FatalLogicError::appendAnnotation(const std::string& buffer)
{
m_whatwhat += buffer;
m_fatality.reportAnnotations(buffer);
}
const char* FatalLogicError::what() const throw()
{
return m_whatwhat.c_str();
}
}
<commit_msg>ENG-3834: Make FatalException compile on my mac.<commit_after>/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common/FatalException.hpp"
#include <cxxabi.h> // for abi
#include <execinfo.h> // for backtrace, backtrace_symbols
#include <cstdlib> // for malloc/free
#include <cstring> // for strn*
#include <dlfcn.h>
#include <stdio.h> // for fopen, fprintf, fclose
#include <string.h>
#ifdef MACOSX // mac os requires _XOPEN_SOURCE for ucontext for some reason
#define _XOPEN_SOURCE
#endif
#include <ucontext.h>
namespace voltdb {
FatalException::FatalException(std::string message,
const char *filename, unsigned long lineno,
std::string backtrace_path)
: m_reason(message)
, m_filename(filename), m_lineno(lineno)
, m_backtracepath(backtrace_path)
{
FILE *bt = fopen(m_backtracepath.c_str(), "a+");
/**
* Stack trace code from http://tombarta.wordpress.com/2008/08/01/c-stack-traces-with-gcc/
*/
void *traces[128];
for (int i=0; i < 128; i++) traces[i] = NULL; // silence valgrind
const int numTraces = backtrace( traces, 128);
char** traceSymbols = backtrace_symbols( traces, numTraces);
// write header for backtrace file
if (bt) fprintf(bt, "VoltDB Backtrace (%d)\n", numTraces);
for (int ii = 0; ii < numTraces; ii++) {
std::size_t sz = 200;
// Note: must use malloc vs. new so __cxa_demangle can use realloc.
char *function = static_cast<char*>(::malloc(sz));
char *begin = NULL, *end = NULL;
// write original symbol to file.
if (bt) fprintf(bt, "raw[%d]: %s\n", ii, traceSymbols[ii]);
//Find parens surrounding mangled name
for (char *j = traceSymbols[ii]; *j; ++j) {
if (*j == '(') {
begin = j;
}
else if (*j == '+') {
end = j;
}
}
if (begin && end) {
*begin++ = '\0';
*end = '\0';
int status;
char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
if (ret) {
//return value may be a realloc of input
function = ret;
} else {
// demangle failed, treat it like a C function with no args
strncpy(function, begin, sz);
strncat(function, "()", sz);
function[sz-1] = '\0';
}
m_traces.push_back(std::string(function));
} else {
//didn't find the mangled name in the trace
m_traces.push_back(std::string(traceSymbols[ii]));
}
::free(function);
}
if (bt) {
for (int ii=0; ii < m_traces.size(); ii++) {
const char* str = m_traces[ii].c_str();
fprintf(bt, "demangled[%d]: %s\n", ii, str);
}
fclose(bt);
}
::free(traceSymbols);
}
void FatalException::reportAnnotations(const std::string& str)
{
FILE *bt = fopen(m_backtracepath.c_str(), "a+");
if (!bt) {
return;
}
// append to backtrace file
fprintf(bt, "Additional annotations to the above Fatal Exception:\n%s", str.c_str());
fclose(bt);
}
FatalLogicError::FatalLogicError(const std::string buffer, const char *filename, unsigned long lineno)
: FatalLogicErrorBaseInitializer("FatalLogicError")
, m_fatality(buffer, filename, lineno)
{
initWhat();
}
FatalLogicError::~FatalLogicError() throw () {} // signature required by exception base class?
void FatalLogicError::initWhat()
{
std::ostringstream buffer;
buffer << m_fatality;
m_whatwhat = buffer.str();
}
void FatalLogicError::appendAnnotation(const std::string& buffer)
{
m_whatwhat += buffer;
m_fatality.reportAnnotations(buffer);
}
const char* FatalLogicError::what() const throw()
{
return m_whatwhat.c_str();
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2006 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 "SkBlurMaskFilter.h"
#include "SkBlurMask.h"
#include "SkBuffer.h"
#include "SkMaskFilter.h"
class SkBlurMaskFilterImpl : public SkMaskFilter {
public:
SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle,
uint32_t flags);
// overrides from SkMaskFilter
virtual SkMask::Format getFormat();
virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
SkIPoint* margin);
virtual BlurType asABlur(BlurInfo*);
// overrides from SkFlattenable
virtual Factory getFactory();
virtual void flatten(SkFlattenableWriteBuffer&);
static SkFlattenable* CreateProc(SkFlattenableReadBuffer&);
private:
SkScalar fRadius;
SkBlurMaskFilter::BlurStyle fBlurStyle;
uint32_t fBlurFlags;
SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);
typedef SkMaskFilter INHERITED;
};
SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
SkBlurMaskFilter::BlurStyle style,
uint32_t flags) {
if (radius <= 0 || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
|| flags > SkBlurMaskFilter::kAll_BlurFlag) {
return NULL;
}
return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags));
}
///////////////////////////////////////////////////////////////////////////////
SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius,
SkBlurMaskFilter::BlurStyle style,
uint32_t flags)
: fRadius(radius), fBlurStyle(style), fBlurFlags(flags) {
#if 0
fGamma = NULL;
if (gammaScale) {
fGamma = new U8[256];
if (gammaScale > 0)
SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
else
SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
}
#endif
SkASSERT(radius >= 0);
SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
}
SkMask::Format SkBlurMaskFilterImpl::getFormat() {
return SkMask::kA8_Format;
}
bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
const SkMatrix& matrix, SkIPoint* margin) {
SkScalar radius;
if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
radius = fRadius;
} else {
radius = matrix.mapRadius(fRadius);
}
// To avoid unseemly allocation requests (esp. for finite platforms like
// handset) we limit the radius so something manageable. (as opposed to
// a request like 10,000)
static const SkScalar MAX_RADIUS = SkIntToScalar(128);
radius = SkMinScalar(radius, MAX_RADIUS);
SkBlurMask::Quality blurQuality =
(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;
return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
blurQuality, margin);
}
SkFlattenable* SkBlurMaskFilterImpl::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkBlurMaskFilterImpl, (buffer));
}
SkFlattenable::Factory SkBlurMaskFilterImpl::getFactory() {
return CreateProc;
}
SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
: SkMaskFilter(buffer) {
fRadius = buffer.readScalar();
fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readS32();
fBlurFlags = buffer.readU32() & SkBlurMaskFilter::kAll_BlurFlag;
SkASSERT(fRadius >= 0);
SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
}
void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeScalar(fRadius);
buffer.write32(fBlurStyle);
buffer.write32(fBlurFlags);
}
static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = {
SkMaskFilter::kNormal_BlurType,
SkMaskFilter::kSolid_BlurType,
SkMaskFilter::kOuter_BlurType,
SkMaskFilter::kInner_BlurType,
};
SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) {
if (info) {
info->fRadius = fRadius;
info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag);
}
return gBlurStyle2BlurType[fBlurStyle];
}
///////////////////////////////////////////////////////////////////////////////
static SkFlattenable::Registrar gReg("SkBlurMaskFilter",
SkBlurMaskFilterImpl::CreateProc);
<commit_msg>Ignore blur margin fix flag for backward bug compatibility. http://codereview.appspot.com/4981046/<commit_after>
/*
* Copyright 2006 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 "SkBlurMaskFilter.h"
#include "SkBlurMask.h"
#include "SkBuffer.h"
#include "SkMaskFilter.h"
class SkBlurMaskFilterImpl : public SkMaskFilter {
public:
SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle,
uint32_t flags);
// overrides from SkMaskFilter
virtual SkMask::Format getFormat();
virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
SkIPoint* margin);
virtual BlurType asABlur(BlurInfo*);
// overrides from SkFlattenable
virtual Factory getFactory();
virtual void flatten(SkFlattenableWriteBuffer&);
static SkFlattenable* CreateProc(SkFlattenableReadBuffer&);
private:
SkScalar fRadius;
SkBlurMaskFilter::BlurStyle fBlurStyle;
uint32_t fBlurFlags;
SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);
typedef SkMaskFilter INHERITED;
};
SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
SkBlurMaskFilter::BlurStyle style,
uint32_t flags) {
if (radius <= 0 || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
|| flags > SkBlurMaskFilter::kAll_BlurFlag) {
return NULL;
}
return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags));
}
///////////////////////////////////////////////////////////////////////////////
SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius,
SkBlurMaskFilter::BlurStyle style,
uint32_t flags)
: fRadius(radius), fBlurStyle(style), fBlurFlags(flags) {
#if 0
fGamma = NULL;
if (gammaScale) {
fGamma = new U8[256];
if (gammaScale > 0)
SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
else
SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
}
#endif
SkASSERT(radius >= 0);
SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
}
SkMask::Format SkBlurMaskFilterImpl::getFormat() {
return SkMask::kA8_Format;
}
bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
const SkMatrix& matrix, SkIPoint* margin) {
SkScalar radius;
if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
radius = fRadius;
} else {
radius = matrix.mapRadius(fRadius);
}
// To avoid unseemly allocation requests (esp. for finite platforms like
// handset) we limit the radius so something manageable. (as opposed to
// a request like 10,000)
static const SkScalar MAX_RADIUS = SkIntToScalar(128);
radius = SkMinScalar(radius, MAX_RADIUS);
SkBlurMask::Quality blurQuality =
(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;
#if defined(SK_BLUR_MASK_FILTER_IGNORE_MARGIN_FIX)
if (SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
blurQuality)) {
if (margin) {
// we need to integralize radius for our margin, so take the ceil
// just to be safe.
margin->set(SkScalarCeil(radius), SkScalarCeil(radius));
}
return true;
}
return false;
#else
return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
blurQuality, margin);
#endif
}
SkFlattenable* SkBlurMaskFilterImpl::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkBlurMaskFilterImpl, (buffer));
}
SkFlattenable::Factory SkBlurMaskFilterImpl::getFactory() {
return CreateProc;
}
SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
: SkMaskFilter(buffer) {
fRadius = buffer.readScalar();
fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readS32();
fBlurFlags = buffer.readU32() & SkBlurMaskFilter::kAll_BlurFlag;
SkASSERT(fRadius >= 0);
SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
}
void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeScalar(fRadius);
buffer.write32(fBlurStyle);
buffer.write32(fBlurFlags);
}
static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = {
SkMaskFilter::kNormal_BlurType,
SkMaskFilter::kSolid_BlurType,
SkMaskFilter::kOuter_BlurType,
SkMaskFilter::kInner_BlurType,
};
SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) {
if (info) {
info->fRadius = fRadius;
info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag);
}
return gBlurStyle2BlurType[fBlurStyle];
}
///////////////////////////////////////////////////////////////////////////////
static SkFlattenable::Registrar gReg("SkBlurMaskFilter",
SkBlurMaskFilterImpl::CreateProc);
<|endoftext|> |
<commit_before>// $Id: AliHLTTPCClusterTransformation.cxx 41244 2010-05-14 08:13:35Z kkanaki $
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Kalliopi Kanaki <Kalliopi.Kanaki@ift.uib.no> *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTTPCClusterTransformation.cxx
@author Kalliopi Kanaki, Sergey Gorbubnov
@date
@brief
*/
#include "AliHLTTPCClusterTransformation.h"
#include "AliHLTTPCFastTransform.h"
#include "AliHLTTPCDefinitions.h"
#include "AliCDBPath.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliGRPObject.h"
#include "AliTPCcalibDB.h"
#include "AliTPCTransform.h"
#include "AliTPCParam.h"
#include "AliTPCRecoParam.h"
#include "AliGeomManager.h"
#include "AliRunInfo.h"
#include "AliEventInfo.h"
#include "AliRawEventHeaderBase.h"
#include <iostream>
#include <iomanip>
using namespace std;
ClassImp(AliHLTTPCClusterTransformation) //ROOT macro for the implementation of ROOT specific class methods
AliRecoParam AliHLTTPCClusterTransformation::fOfflineRecoParam;
AliHLTTPCClusterTransformation::AliHLTTPCClusterTransformation()
:
fError(),
fFastTransform()
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTTPCClusterTransformation::~AliHLTTPCClusterTransformation()
{
// see header file for class documentation
}
int AliHLTTPCClusterTransformation::Init( double FieldBz, Long_t TimeStamp )
{
// Initialisation
if(!AliGeomManager::GetGeometry()){
AliGeomManager::LoadGeometry();
}
if(!AliGeomManager::GetGeometry()) return Error(-1,"AliHLTTPCClusterTransformation::Init: Can not initialise geometry");
AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance();
if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found");
pCalib->SetExBField(FieldBz);
if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::Init: No TPC transformation found");
// -- Get AliRunInfo variables
AliGRPObject tmpGRP, *pGRP=0;
AliCDBEntry *entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
if(!entry) return Error(-4,"AliHLTTPCClusterTransformation::Init: No GRP object found in data base");
{
TMap* m = dynamic_cast<TMap*>(entry->GetObject()); // old GRP entry
if (m) {
//cout<<"Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject"<<endl;
m->Print();
pGRP = &tmpGRP;
pGRP->ReadValuesFromMap(m);
}
else {
//cout<<"Found an AliGRPObject in GRP/GRP/Data, reading it"<<endl;
pGRP = dynamic_cast<AliGRPObject*>(entry->GetObject()); // new GRP entry
}
}
if( !pGRP ){
return Error(-5,"AliHLTTPCClusterTransformation::Init: Unknown format of the GRP object in data base");
}
AliRunInfo runInfo(pGRP->GetLHCState(),pGRP->GetBeamType(),pGRP->GetBeamEnergy(),pGRP->GetRunType(),pGRP->GetDetectorMask());
AliEventInfo evInfo;
evInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent);
entry=AliCDBManager::Instance()->Get("TPC/Calib/RecoParam");
if(!entry) return Error(-6,"AliHLTTPCClusterTransformation::Init: No TPC reco param entry found in data base");
TObject *recoParamObj = entry->GetObject();
if(!recoParamObj) return Error(-7,"AliHLTTPCClusterTransformation::Init: Empty TPC reco param entry in data base");
if (dynamic_cast<TObjArray*>(recoParamObj)) {
//cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: TObjArray found \n"<<endl;
TObjArray *copy = (TObjArray*)( static_cast<TObjArray*>(recoParamObj)->Clone() );
fOfflineRecoParam.AddDetRecoParamArray(1,copy);
}
else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
//cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: AliDetectorRecoParam found \n"<<endl;
AliDetectorRecoParam *copy = (AliDetectorRecoParam*)static_cast<AliDetectorRecoParam*>(recoParamObj)->Clone();
fOfflineRecoParam.AddDetRecoParam(1,copy);
} else {
return Error(-8,"AliHLTTPCClusterTransformation::Init: Unknown format of the TPC Reco Param entry in the data base");
}
fOfflineRecoParam.SetEventSpecie(&runInfo, evInfo, 0);
//
AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1);
if( !recParam ) return Error(-9,"AliHLTTPCClusterTransformation::Init: No TPC Reco Param entry found for the given event specification");
pCalib->GetTransform()->SetCurrentRecoParam(recParam);
// set current time stamp and initialize the fast transformation
int err = fFastTransform.Init( pCalib->GetTransform(), TimeStamp );
if( err!=0 ){
return Error(-10,Form( "AliHLTTPCClusterTransformation::Init: Initialisation of Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) );
}
return 0;
}
Int_t AliHLTTPCClusterTransformation::Init( const AliHLTTPCFastTransformObject &obj )
{
// Initialisation
if(!AliGeomManager::GetGeometry()){
AliGeomManager::LoadGeometry();
}
if(!AliGeomManager::GetGeometry()) return Error(-1,"AliHLTTPCClusterTransformation::Init: Can not initialise geometry");
// set current time stamp and initialize the fast transformation
int err = fFastTransform.ReadFromObject( obj );
if( err!=0 ){
return Error(-10,Form( "AliHLTTPCClusterTransformation::Init: Initialisation of Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) );
}
return(0);
}
Bool_t AliHLTTPCClusterTransformation::IsInitialised() const
{
// Is the transformation initialised
return fFastTransform.IsInitialised();
}
void AliHLTTPCClusterTransformation::DeInit()
{
// Deinitialisation
fFastTransform.DeInit();
}
Int_t AliHLTTPCClusterTransformation::SetCurrentTimeStamp( Long_t TimeStamp )
{
// Set the current time stamp
AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1);
if( !recParam ) return Error(-1,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC Reco Param entry found");
AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance();
if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found");
if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC transformation found");
pCalib->GetTransform()->SetCurrentRecoParam(recParam);
int err = fFastTransform.SetCurrentTimeStamp( TimeStamp );
if( err!=0 ){
return Error(-4,Form( "AliHLTTPCClusterTransformation::SetCurrentTimeStamp: SetCurrentTimeStamp to the Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) );
}
return 0;
}
void AliHLTTPCClusterTransformation::Print(const char* /*option*/) const
{
// print info
fFastTransform.Print();
}
Int_t AliHLTTPCClusterTransformation::GetSize() const
{
// total size of the object
int size = sizeof(AliHLTTPCClusterTransformation) - sizeof(AliHLTTPCFastTransform) + fFastTransform.GetSize();
return size;
}
<commit_msg>ExB map is initialized twice, fix the same issue here as well<commit_after>// $Id: AliHLTTPCClusterTransformation.cxx 41244 2010-05-14 08:13:35Z kkanaki $
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Kalliopi Kanaki <Kalliopi.Kanaki@ift.uib.no> *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTTPCClusterTransformation.cxx
@author Kalliopi Kanaki, Sergey Gorbubnov
@date
@brief
*/
#include "AliHLTTPCClusterTransformation.h"
#include "AliHLTTPCFastTransform.h"
#include "AliHLTTPCDefinitions.h"
#include "AliCDBPath.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliGRPObject.h"
#include "AliTPCcalibDB.h"
#include "AliTPCTransform.h"
#include "AliTPCParam.h"
#include "AliTPCRecoParam.h"
#include "AliGeomManager.h"
#include "AliRunInfo.h"
#include "AliEventInfo.h"
#include "AliRawEventHeaderBase.h"
#include <iostream>
#include <iomanip>
#include <TGeoGlobalMagField.h>
using namespace std;
ClassImp(AliHLTTPCClusterTransformation) //ROOT macro for the implementation of ROOT specific class methods
AliRecoParam AliHLTTPCClusterTransformation::fOfflineRecoParam;
AliHLTTPCClusterTransformation::AliHLTTPCClusterTransformation()
:
fError(),
fFastTransform()
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTTPCClusterTransformation::~AliHLTTPCClusterTransformation()
{
// see header file for class documentation
}
int AliHLTTPCClusterTransformation::Init( double FieldBz, Long_t TimeStamp )
{
// Initialisation
if(!AliGeomManager::GetGeometry()){
AliGeomManager::LoadGeometry();
}
if(!AliGeomManager::GetGeometry()) return Error(-1,"AliHLTTPCClusterTransformation::Init: Can not initialise geometry");
AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance();
if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found");
const AliMagF * field = (AliMagF*) TGeoGlobalMagField::Instance()->GetField();
pCalib->SetExBField(field);
if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::Init: No TPC transformation found");
// -- Get AliRunInfo variables
AliGRPObject tmpGRP, *pGRP=0;
AliCDBEntry *entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
if(!entry) return Error(-4,"AliHLTTPCClusterTransformation::Init: No GRP object found in data base");
{
TMap* m = dynamic_cast<TMap*>(entry->GetObject()); // old GRP entry
if (m) {
//cout<<"Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject"<<endl;
m->Print();
pGRP = &tmpGRP;
pGRP->ReadValuesFromMap(m);
}
else {
//cout<<"Found an AliGRPObject in GRP/GRP/Data, reading it"<<endl;
pGRP = dynamic_cast<AliGRPObject*>(entry->GetObject()); // new GRP entry
}
}
if( !pGRP ){
return Error(-5,"AliHLTTPCClusterTransformation::Init: Unknown format of the GRP object in data base");
}
AliRunInfo runInfo(pGRP->GetLHCState(),pGRP->GetBeamType(),pGRP->GetBeamEnergy(),pGRP->GetRunType(),pGRP->GetDetectorMask());
AliEventInfo evInfo;
evInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent);
entry=AliCDBManager::Instance()->Get("TPC/Calib/RecoParam");
if(!entry) return Error(-6,"AliHLTTPCClusterTransformation::Init: No TPC reco param entry found in data base");
TObject *recoParamObj = entry->GetObject();
if(!recoParamObj) return Error(-7,"AliHLTTPCClusterTransformation::Init: Empty TPC reco param entry in data base");
if (dynamic_cast<TObjArray*>(recoParamObj)) {
//cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: TObjArray found \n"<<endl;
TObjArray *copy = (TObjArray*)( static_cast<TObjArray*>(recoParamObj)->Clone() );
fOfflineRecoParam.AddDetRecoParamArray(1,copy);
}
else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
//cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: AliDetectorRecoParam found \n"<<endl;
AliDetectorRecoParam *copy = (AliDetectorRecoParam*)static_cast<AliDetectorRecoParam*>(recoParamObj)->Clone();
fOfflineRecoParam.AddDetRecoParam(1,copy);
} else {
return Error(-8,"AliHLTTPCClusterTransformation::Init: Unknown format of the TPC Reco Param entry in the data base");
}
fOfflineRecoParam.SetEventSpecie(&runInfo, evInfo, 0);
//
AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1);
if( !recParam ) return Error(-9,"AliHLTTPCClusterTransformation::Init: No TPC Reco Param entry found for the given event specification");
pCalib->GetTransform()->SetCurrentRecoParam(recParam);
// set current time stamp and initialize the fast transformation
int err = fFastTransform.Init( pCalib->GetTransform(), TimeStamp );
if( err!=0 ){
return Error(-10,Form( "AliHLTTPCClusterTransformation::Init: Initialisation of Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) );
}
return 0;
}
Int_t AliHLTTPCClusterTransformation::Init( const AliHLTTPCFastTransformObject &obj )
{
// Initialisation
if(!AliGeomManager::GetGeometry()){
AliGeomManager::LoadGeometry();
}
if(!AliGeomManager::GetGeometry()) return Error(-1,"AliHLTTPCClusterTransformation::Init: Can not initialise geometry");
// set current time stamp and initialize the fast transformation
int err = fFastTransform.ReadFromObject( obj );
if( err!=0 ){
return Error(-10,Form( "AliHLTTPCClusterTransformation::Init: Initialisation of Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) );
}
return(0);
}
Bool_t AliHLTTPCClusterTransformation::IsInitialised() const
{
// Is the transformation initialised
return fFastTransform.IsInitialised();
}
void AliHLTTPCClusterTransformation::DeInit()
{
// Deinitialisation
fFastTransform.DeInit();
}
Int_t AliHLTTPCClusterTransformation::SetCurrentTimeStamp( Long_t TimeStamp )
{
// Set the current time stamp
AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1);
if( !recParam ) return Error(-1,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC Reco Param entry found");
AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance();
if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found");
if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC transformation found");
pCalib->GetTransform()->SetCurrentRecoParam(recParam);
int err = fFastTransform.SetCurrentTimeStamp( TimeStamp );
if( err!=0 ){
return Error(-4,Form( "AliHLTTPCClusterTransformation::SetCurrentTimeStamp: SetCurrentTimeStamp to the Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) );
}
return 0;
}
void AliHLTTPCClusterTransformation::Print(const char* /*option*/) const
{
// print info
fFastTransform.Print();
}
Int_t AliHLTTPCClusterTransformation::GetSize() const
{
// total size of the object
int size = sizeof(AliHLTTPCClusterTransformation) - sizeof(AliHLTTPCFastTransform) + fFastTransform.GetSize();
return size;
}
<|endoftext|> |
<commit_before>/*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
void GuardsOnSalute(Player* pPlayer, Unit* pUnit)
{
if(pPlayer == NULL || pUnit == NULL)
return;
// Check if we are friendly with our Guards (they will salute only when You are)
if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
{
uint32 EmoteChance = RandomUInt(100);
if(EmoteChance < 33) // 1/3 chance to get Salute from Guard
pUnit->Emote(EMOTE_ONESHOT_SALUTE);
}
}
void GaurdsOnKiss(Player* pPlayer, Unit* pUnit)
{
if(pPlayer == NULL || pUnit == NULL)
return;
// Check if we are friendly with our Guards (they will bow only when You are)
if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
{
uint32 EmoteChance = RandomUInt(100);
if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
pUnit->Emote(EMOTE_ONESHOT_BOW);
}
}
void GuardsOnWave(Player* pPlayer, Unit* pUnit)
{
if(pPlayer == NULL || pUnit == NULL)
return;
// Check if we are friendly with our Guards (they will wave only when You are)
if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
{
uint32 EmoteChance = RandomUInt(100);
if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
pUnit->Emote(EMOTE_ONESHOT_WAVE);
}
}
void OnEmote(Player* pPlayer, uint32 Emote, Unit* pUnit)
{
if(!pUnit || !pUnit->isAlive() || pUnit->GetAIInterface()->getNextTarget())
return;
// Switch For Emote Name (You do EmoteName to Script Name link).
switch(Emote)
{
case EMOTE_ONESHOT_SALUTE: // <- Its EMOTE name.
GuardsOnSalute(pPlayer, pUnit); // <- Its Link.
break;
case EMOTE_ONESHOT_KISS:
GaurdsOnKiss(pPlayer, pUnit);
break;
case EMOTE_ONESHOT_WAVE:
GuardsOnWave(pPlayer, pUnit);
break;
}
}
void SetupRandomScripts(ScriptMgr* mgr)
{
// Register Hook Event here
mgr->register_hook(SERVER_HOOK_EVENT_ON_EMOTE, (void*)&OnEmote);
}<commit_msg>added script for jean pierre in dalaran<commit_after>/*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
void GuardsOnSalute(Player* pPlayer, Unit* pUnit)
{
if(pPlayer == NULL || pUnit == NULL)
return;
// Check if we are friendly with our Guards (they will salute only when You are)
if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
{
uint32 EmoteChance = RandomUInt(100);
if(EmoteChance < 33) // 1/3 chance to get Salute from Guard
pUnit->Emote(EMOTE_ONESHOT_SALUTE);
}
}
void GaurdsOnKiss(Player* pPlayer, Unit* pUnit)
{
if(pPlayer == NULL || pUnit == NULL)
return;
// Check if we are friendly with our Guards (they will bow only when You are)
if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
{
uint32 EmoteChance = RandomUInt(100);
if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
pUnit->Emote(EMOTE_ONESHOT_BOW);
}
}
void GuardsOnWave(Player* pPlayer, Unit* pUnit)
{
if(pPlayer == NULL || pUnit == NULL)
return;
// Check if we are friendly with our Guards (they will wave only when You are)
if(((pUnit->GetEntry() == 68 || pUnit->GetEntry() == 1976) && pPlayer->GetStandingRank(72) >= STANDING_FRIENDLY) || (pUnit->GetEntry() == 3296 && pPlayer->GetStandingRank(76) >= STANDING_FRIENDLY))
{
uint32 EmoteChance = RandomUInt(100);
if(EmoteChance < 33) // 1/3 chance to get Bow from Guard
pUnit->Emote(EMOTE_ONESHOT_WAVE);
}
}
void OnEmote(Player* pPlayer, uint32 Emote, Unit* pUnit)
{
if(!pUnit || !pUnit->isAlive() || pUnit->GetAIInterface()->getNextTarget())
return;
// Switch For Emote Name (You do EmoteName to Script Name link).
switch(Emote)
{
case EMOTE_ONESHOT_SALUTE: // <- Its EMOTE name.
GuardsOnSalute(pPlayer, pUnit); // <- Its Link.
break;
case EMOTE_ONESHOT_KISS:
GaurdsOnKiss(pPlayer, pUnit);
break;
case EMOTE_ONESHOT_WAVE:
GuardsOnWave(pPlayer, pUnit);
break;
}
}
class JeanPierrePoulain : public GossipScript
{
public:
void GossipHello(Object* pObject, Player* plr)
{
GossipMenu* Menu;
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 14500, plr);
if(plr->HasFinishedQuest(13668) || plr->GetQuestLogForEntry(13668) || plr->HasFinishedQuest(13667) || plr->GetQuestLogForEntry(13667))
Menu->SendTo(plr);
else
Menu->AddItem(0, "I'll take the flight." ,1);
Menu->SendTo(plr);
}
void GossipSelectOption(Object* pObject, Player* Plr, uint32 Id, uint32 IntId, const char* Code)
{
switch(IntId)
{
case 0:
GossipHello(pObject, Plr);
break;
case 1:
Plr->CastSpell(Plr, 64795, true);
break;
}
Plr->Gossip_Complete();
}
};
void SetupRandomScripts(ScriptMgr* mgr)
{
// Register Hook Event here
mgr->register_hook(SERVER_HOOK_EVENT_ON_EMOTE, (void*)&OnEmote);
mgr->register_gossip_script(34244, new JeanPierrePoulain);
}<|endoftext|> |
<commit_before>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// 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 "jaspdoublevalidator.h"
#include <math.h>
QValidator::State JASPDoubleValidator::validate(QString& s, int& pos) const
{
if (s.isEmpty() || (s.startsWith("-") && s.length() == 1 && bottom() < 0))
{
// allow empty field or standalone minus sign
return QValidator::Intermediate;
}
if (s.contains("-") && bottom() >= 0)
return QValidator::Invalid;
// check length of decimal places
QChar point = locale().decimalPoint();
if (s.indexOf(point) != -1)
{
if (decimals() == 0)
return QValidator::Invalid;
int lengthDecimals = s.length() - s.indexOf(point) - 1;
if (lengthDecimals > decimals())
return QValidator::Invalid;
}
// check range of value
bool isNumber;
double value = locale().toDouble(s, &isNumber);
if (!isNumber)
{
if (s.length() == 1 && s[0] == point)
{
isNumber = true;
value = 0;
}
else
return QValidator::Invalid;
}
bool isMaxExclusive = _inclusive == JASPControlBase::Inclusive::None || _inclusive == JASPControlBase::Inclusive::MinOnly;
bool isMinExclusive = _inclusive == JASPControlBase::Inclusive::None || _inclusive == JASPControlBase::Inclusive::MaxOnly;
if (value >= 0)
{
if (value > top() || (isMaxExclusive && value == top()))
return QValidator::Invalid;
else if (value < bottom() || (isMinExclusive && value == bottom()))
return QValidator::Intermediate;
}
else
{
if (value < bottom() || (isMinExclusive && value == bottom()))
return QValidator::Invalid;
else if (value > top() || (isMaxExclusive && value == top()))
return QValidator::Intermediate;
}
return QValidator::Acceptable;
}
QString JASPDoubleValidator::validationMessage(const QString& fieldName)
{
QString message = tr("The value must be ");
bool hasValidation = false;
if (!_isInf(bottom()))
{
hasValidation = true;
if (_inclusive == JASPControlBase::Inclusive::MinMax || _inclusive == JASPControlBase::Inclusive::MinOnly)
message += tr("≥ %1").arg(bottom());
else
message += tr("> %1").arg(bottom());
}
if (!_isInf(top()))
{
if (hasValidation)
message += tr(" and ");
hasValidation = true;
if (_inclusive == JASPControlBase::Inclusive::MinMax || _inclusive == JASPControlBase::Inclusive::MaxOnly)
message += tr("≤ %1").arg(top());
else
message += tr("< %1").arg(top());
}
if (!hasValidation)
message = tr("No validation error");
return message;
}
bool JASPDoubleValidator::_isInf(double value)
{
static int intInfinity = 2147483647; // 2 ^ 32 - 1
return isinf(value) || int(value) == intInfinity || int(value) == -intInfinity;
}
<commit_msg>Do not forbid entering numeric values in Integer/Double fields<commit_after>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// 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 "jaspdoublevalidator.h"
#include <math.h>
QValidator::State JASPDoubleValidator::validate(QString& s, int& pos) const
{
if (s.isEmpty() || (s.startsWith("-") && s.length() == 1 && bottom() < 0))
{
// allow empty field or standalone minus sign
return QValidator::Intermediate;
}
if (s.contains("-") && bottom() >= 0)
return QValidator::Invalid;
// check length of decimal places
QChar point = locale().decimalPoint();
if (s.indexOf(point) != -1)
{
if (decimals() == 0)
return QValidator::Invalid;
int lengthDecimals = s.length() - s.indexOf(point) - 1;
if (lengthDecimals > decimals())
return QValidator::Invalid;
}
// check range of value
bool isNumber;
double value = locale().toDouble(s, &isNumber);
if (!isNumber)
{
if (s.length() == 1 && s[0] == point)
{
isNumber = true;
value = 0;
}
else
return QValidator::Invalid;
}
bool isMaxExclusive = _inclusive == JASPControlBase::Inclusive::None || _inclusive == JASPControlBase::Inclusive::MinOnly;
bool isMinExclusive = _inclusive == JASPControlBase::Inclusive::None || _inclusive == JASPControlBase::Inclusive::MaxOnly;
if (value >= 0)
{
if (value > top() || (isMaxExclusive && value == top()))
return QValidator::Intermediate;
else if (value < bottom() || (isMinExclusive && value == bottom()))
return QValidator::Intermediate;
}
else
{
if (value < bottom() || (isMinExclusive && value == bottom()))
return QValidator::Intermediate;
else if (value > top() || (isMaxExclusive && value == top()))
return QValidator::Intermediate;
}
return QValidator::Acceptable;
}
QString JASPDoubleValidator::validationMessage(const QString& fieldName)
{
QString message = tr("The value must be ");
bool hasValidation = false;
if (!_isInf(bottom()))
{
hasValidation = true;
if (_inclusive == JASPControlBase::Inclusive::MinMax || _inclusive == JASPControlBase::Inclusive::MinOnly)
message += tr("≥ %1").arg(bottom());
else
message += tr("> %1").arg(bottom());
}
if (!_isInf(top()))
{
if (hasValidation)
message += tr(" and ");
hasValidation = true;
if (_inclusive == JASPControlBase::Inclusive::MinMax || _inclusive == JASPControlBase::Inclusive::MaxOnly)
message += tr("≤ %1").arg(top());
else
message += tr("< %1").arg(top());
}
if (!hasValidation)
message = tr("No validation error");
return message;
}
bool JASPDoubleValidator::_isInf(double value)
{
static int intInfinity = 2147483647; // 2 ^ 32 - 1
return isinf(value) || int(value) == intInfinity || int(value) == -intInfinity;
}
<|endoftext|> |
<commit_before>#ifndef __GT_MODEL_RESULT_FACTORY_HPP__
#define __GT_MODEL_RESULT_FACTORY_HPP__ 1
#include "gt/model/common.hpp"
namespace GT {
namespace Model {
/**
* @brief Used for configuring what kind of builders should be returned by ResultFactory.
*
* @author Mateusz Kubuszok
*/
enum ResultBuilderMode { PLAIN, JSON, XML };
/**
* @brief Used for configuring whether builders returned by ResultFacotry should use indentation and how.
*
* @author Mateusz Kubuszok
*/
enum ResultIndentationMode { TABS, SPACES, NONE };
/**
* @brief Creates some simple Results as well as supplies builders for more complex of them.
*
* @author Mateusz Kubuszok
*/
class ResultFactory {
public:
/**
* @brief Returns the instance of a ResultFactory.
*
* @return ResultFactory instance
*/
static ResultFactory& volatile getInstance();
/**
* @brief Returns results with predefined const content.
*
* @param content content to be contained by the Result
* @return Result with constant content
*/
Result& constResult(
const std::string &content
);
/**
* @brief Returns empty result.
*
* @return an empty result
*/
Result& emptyResult();
/**
* @brief Returns current builder mode.
*
* @return currently used builder mode
*/
ResultBuilderMode getBuilderMode();
/**
* @brief Sets current builder mode.
*
* @param builderMode new builder mode
* @return ResultsFactory for chaining
*/
ResultFactory& setBuilderMode(
ResultBuilderMode builderMode
);
/**
* @brief Returns current indentation mode.
*
* @return currently used indentation mode
*/
ResultIndentationMode getIndentationMode();
/**
* @brief Sets current indentation mode.
*
* @param indentationMode new indentation mode
* @return ResultsFactory for chaining
*/
ResultFactory& setIndentationMode(
ResultIndentationMode indentationMode
);
private:
/**
* @brief Contains pointer to a ResultFactory instance.
*/
static ResultFactory volatile *instance = 0;
/**
* @brief Contains current Builder Mode setting.
*/
ResultBuilderMode builderMode;
/**
* @brief Contains current Indentation Mode setting.
*/
ResultIndentationMode indentationMode;
/**
* @biref Private constructor.
*/
ResultFactory();
/**
* @brief Private copy constructor.
*/
ResultFactory(
const ResultFactory &resultFactory
);
/**
* @brief Private destructor.
*/
~ResultFactory();
}
} /* END namespace Model */
} /* END namepsace GT */
#endif /* #ifndef __GT_MODEL_RESULT_FACTORY_HPP__ */
<commit_msg>* Tabulation fixes.<commit_after>#ifndef __GT_MODEL_RESULT_FACTORY_HPP__
#define __GT_MODEL_RESULT_FACTORY_HPP__ 1
#include "gt/model/common.hpp"
namespace GT {
namespace Model {
/**
* @brief Used for configuring what kind of builders should be returned by ResultFactory.
*
* @author Mateusz Kubuszok
*/
enum ResultBuilderMode { PLAIN, JSON, XML };
/**
* @brief Used for configuring whether builders returned by ResultFacotry should use indentation and how.
*
* @author Mateusz Kubuszok
*/
enum ResultIndentationMode { TABS, SPACES, NONE };
/**
* @brief Creates some simple Results as well as supplies builders for more complex of them.
*
* @author Mateusz Kubuszok
*/
class ResultFactory {
public:
/**
* @brief Returns the instance of a ResultFactory.
*
* @return ResultFactory instance
*/
static ResultFactory& volatile getInstance();
/**
* @brief Returns results with predefined const content.
*
* @param content content to be contained by the Result
* @return Result with constant content
*/
Result& constResult(
const std::string &content
);
/**
* @brief Returns empty result.
*
* @return an empty result
*/
Result& emptyResult();
/**
* @brief Returns current builder mode.
*
* @return currently used builder mode
*/
ResultBuilderMode getBuilderMode();
/**
* @brief Sets current builder mode.
*
* @param builderMode new builder mode
* @return ResultsFactory for chaining
*/
ResultFactory& setBuilderMode(
ResultBuilderMode builderMode
);
/**
* @brief Returns current indentation mode.
*
* @return currently used indentation mode
*/
ResultIndentationMode getIndentationMode();
/**
* @brief Sets current indentation mode.
*
* @param indentationMode new indentation mode
* @return ResultsFactory for chaining
*/
ResultFactory& setIndentationMode(
ResultIndentationMode indentationMode
);
private:
/**
* @brief Contains pointer to a ResultFactory instance.
*/
static ResultFactory volatile *instance = 0;
/**
* @brief Contains current Builder Mode setting.
*/
ResultBuilderMode builderMode;
/**
* @brief Contains current Indentation Mode setting.
*/
ResultIndentationMode indentationMode;
/**
* @biref Private constructor.
*/
ResultFactory();
/**
* @brief Private copy constructor.
*/
ResultFactory(
const ResultFactory &resultFactory
);
/**
* @brief Private destructor.
*/
~ResultFactory();
}
} /* END namespace Model */
} /* END namepsace GT */
#endif /* #ifndef __GT_MODEL_RESULT_FACTORY_HPP__ */
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Chiyuan Zhang
* Copyright (C) 2012 Chiyuan Zhang
*/
#include <shogun/multiclass/ecoc/ECOCOVOEncoder.h>
using namespace shogun;
SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes)
{
SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true);
code_book.zero();
int32_t k=0;
for (int32_t i=0; i < num_classes; ++i)
{
for (int32_t j=0; j < num_classes; ++j)
{
code_book(k, i) = 1;
code_book(k, j) = -1;
k++;
}
}
return code_book;
}
<commit_msg>Fix bug in ECOC OvO encoder<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Chiyuan Zhang
* Copyright (C) 2012 Chiyuan Zhang
*/
#include <shogun/multiclass/ecoc/ECOCOVOEncoder.h>
using namespace shogun;
SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes)
{
SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true);
code_book.zero();
int32_t k=0;
for (int32_t i=0; i < num_classes; ++i)
{
for (int32_t j=i+1; j < num_classes; ++j)
{
code_book(k, i) = 1;
code_book(k, j) = -1;
k++;
}
}
return code_book;
}
<|endoftext|> |
<commit_before>#include "skeleton_view.h"
#include "editor/world_editor.h"
#include "graphics/render_scene.h"
SkeletonView::SkeletonView()
{
setObjectName("skeletonView");
setWindowTitle("Skeleton");
m_editor = NULL;
m_tree_widget = new QTreeWidget(this);
m_tree_widget->setHeaderLabel("Bone");
setWidget(m_tree_widget);
}
void SkeletonView::setWorldEditor(Lumix::WorldEditor& editor)
{
m_editor = &editor;
editor.entitySelected().bind<SkeletonView, &SkeletonView::entitySelected>(this);
}
void SkeletonView::entitySelected(const Lumix::Array<Lumix::Entity>& entities)
{
if (!entities.empty())
{
Lumix::Component cmp = m_editor->getComponent(entities[0], crc32("renderable"));
if (cmp.isValid())
{
Lumix::Model* model = static_cast<Lumix::RenderScene*>(cmp.scene)->getRenderableModel(cmp);
viewModel(model);
}
}
}
QTreeWidgetItem* SkeletonView::createBoneListItemWidget(Lumix::Model* model, const Lumix::Model::Bone& parent_bone)
{
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << parent_bone.name.c_str());
for (int i = 0; i < model->getBoneCount(); ++i)
{
const Lumix::Model::Bone& bone = model->getBone(i);
if (bone.parent_idx >= 0 && &model->getBone(bone.parent_idx) == &parent_bone)
{
item->addChild(createBoneListItemWidget(model, bone));
}
}
return item;
}
void SkeletonView::viewModel(Lumix::Model* model)
{
ASSERT(model);
m_tree_widget->clear();
for (int i = 0; i < model->getBoneCount(); ++i)
{
const Lumix::Model::Bone& bone = model->getBone(i);
if (bone.parent_idx < 0)
{
m_tree_widget->addTopLevelItem(createBoneListItemWidget(model, bone));
}
}
m_tree_widget->expandAll();
}<commit_msg>fixed crash when renderable component without model file is selected<commit_after>#include "skeleton_view.h"
#include "editor/world_editor.h"
#include "graphics/render_scene.h"
SkeletonView::SkeletonView()
{
setObjectName("skeletonView");
setWindowTitle("Skeleton");
m_editor = NULL;
m_tree_widget = new QTreeWidget(this);
m_tree_widget->setHeaderLabel("Bone");
setWidget(m_tree_widget);
}
void SkeletonView::setWorldEditor(Lumix::WorldEditor& editor)
{
m_editor = &editor;
editor.entitySelected().bind<SkeletonView, &SkeletonView::entitySelected>(this);
}
void SkeletonView::entitySelected(const Lumix::Array<Lumix::Entity>& entities)
{
if (!entities.empty())
{
Lumix::Component cmp = m_editor->getComponent(entities[0], crc32("renderable"));
if (cmp.isValid())
{
Lumix::Model* model = static_cast<Lumix::RenderScene*>(cmp.scene)->getRenderableModel(cmp);
if (model)
{
viewModel(model);
}
}
}
}
QTreeWidgetItem* SkeletonView::createBoneListItemWidget(Lumix::Model* model, const Lumix::Model::Bone& parent_bone)
{
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << parent_bone.name.c_str());
for (int i = 0; i < model->getBoneCount(); ++i)
{
const Lumix::Model::Bone& bone = model->getBone(i);
if (bone.parent_idx >= 0 && &model->getBone(bone.parent_idx) == &parent_bone)
{
item->addChild(createBoneListItemWidget(model, bone));
}
}
return item;
}
void SkeletonView::viewModel(Lumix::Model* model)
{
ASSERT(model);
m_tree_widget->clear();
for (int i = 0; i < model->getBoneCount(); ++i)
{
const Lumix::Model::Bone& bone = model->getBone(i);
if (bone.parent_idx < 0)
{
m_tree_widget->addTopLevelItem(createBoneListItemWidget(model, bone));
}
}
m_tree_widget->expandAll();
}<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Viktor Gal
* Copyright (C) 2012 Viktor Gal
*/
#include <shogun/lib/common.h>
#include <shogun/kernel/JensenShannonKernel.h>
#include <shogun/features/Features.h>
#include <shogun/features/SimpleFeatures.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
CJensenShannonKernel::CJensenShannonKernel()
: CDotKernel(0)
{
}
CJensenShannonKernel::CJensenShannonKernel(int32_t size)
: CDotKernel(size)
{
}
CJensenShannonKernel::CJensenShannonKernel(
CSimpleFeatures<float64_t>* l, CSimpleFeatures<float64_t>* r, int32_t size)
: CDotKernel(size)
{
init(l,r);
}
CJensenShannonKernel::~CJensenShannonKernel()
{
cleanup();
}
bool CJensenShannonKernel::init(CFeatures* l, CFeatures* r)
{
bool result=CDotKernel::init(l,r);
init_normalizer();
return result;
}
float64_t CJensenShannonKernel::compute(int32_t idx_a, int32_t idx_b)
{
int32_t alen, blen;
bool afree, bfree;
float64_t* avec=
((CSimpleFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree);
float64_t* bvec=
((CSimpleFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree);
ASSERT(alen==blen);
float64_t result=0;
/* calcualte Jensen-Shannon kernel */
for (int32_t i=0; i<alen; i++) {
float64_t a_i = 0, b_i = 0;
float64_t ab = avec[i]+bvec[i];
if (avec[i] != 0)
a_i = avec[i]/2 * CMath::log2(ab/avec[i]);
if (bvec[i] != 0)
b_i = bvec[i]/2 * CMath::log2(ab/bvec[i]);
result += a_i + b_i;
}
((CSimpleFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree);
((CSimpleFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree);
return result;
}
<commit_msg>Optimizing the Jensen-Shannon kernel computation Instead of doing two divisions switch to one multiplication<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Viktor Gal
* Copyright (C) 2012 Viktor Gal
*/
#include <shogun/lib/common.h>
#include <shogun/kernel/JensenShannonKernel.h>
#include <shogun/features/Features.h>
#include <shogun/features/SimpleFeatures.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
CJensenShannonKernel::CJensenShannonKernel()
: CDotKernel(0)
{
}
CJensenShannonKernel::CJensenShannonKernel(int32_t size)
: CDotKernel(size)
{
}
CJensenShannonKernel::CJensenShannonKernel(
CSimpleFeatures<float64_t>* l, CSimpleFeatures<float64_t>* r, int32_t size)
: CDotKernel(size)
{
init(l,r);
}
CJensenShannonKernel::~CJensenShannonKernel()
{
cleanup();
}
bool CJensenShannonKernel::init(CFeatures* l, CFeatures* r)
{
bool result=CDotKernel::init(l,r);
init_normalizer();
return result;
}
float64_t CJensenShannonKernel::compute(int32_t idx_a, int32_t idx_b)
{
int32_t alen, blen;
bool afree, bfree;
float64_t* avec=
((CSimpleFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree);
float64_t* bvec=
((CSimpleFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree);
ASSERT(alen==blen);
float64_t result=0;
/* calcualte Jensen-Shannon kernel */
for (int32_t i=0; i<alen; i++) {
float64_t a_i = 0, b_i = 0;
float64_t ab = avec[i]+bvec[i];
if (avec[i] != 0)
a_i = avec[i] * CMath::log2(ab/avec[i]);
if (bvec[i] != 0)
b_i = bvec[i] * CMath::log2(ab/bvec[i]);
result += 0.5*(a_i + b_i);
}
((CSimpleFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree);
((CSimpleFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree);
return result;
}
<|endoftext|> |
<commit_before>#include "launcher_save_data.h"
using namespace Halley;
LauncherSaveData::LauncherSaveData(std::shared_ptr<ISaveData> saveData)
: saveData(std::move(saveData))
{
}
std::vector<Path> LauncherSaveData::getProjectPaths() const
{}
void LauncherSaveData::setProjectPaths(std::vector<Path> paths)
{}
void LauncherSaveData::save()
{}
void LauncherSaveData::load()
{}
<commit_msg>...and that doesn't compile. Fixed it.<commit_after>#include "launcher_save_data.h"
using namespace Halley;
LauncherSaveData::LauncherSaveData(std::shared_ptr<ISaveData> saveData)
: saveData(std::move(saveData))
{
}
std::vector<Path> LauncherSaveData::getProjectPaths() const
{
return {};
}
void LauncherSaveData::setProjectPaths(std::vector<Path> paths)
{}
void LauncherSaveData::save()
{}
void LauncherSaveData::load()
{}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "Bitmap.h"
#include "Pixel32.h"
#include "Pixel24.h"
#include "Pixel16.h"
#include "Filtergrayscale.h"
#include "Filterfill.h"
#include "Filterflip.h"
#include "Filterfliprgb.h"
#include "Filterflipuv.h"
#include "Filter3x3.h"
#include "FilterConvol.h"
#include "HistoryPreProcessor.h"
#include "FilterHighpass.h"
#include "FilterGauss.h"
#include "FilterBlur.h"
#include "FilterBandpass.h"
#include "../base/TimeSource.h"
#include <Magick++.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace avg;
using namespace std;
void runFillI8PerformanceTest()
{
BitmapPtr pBmp = BitmapPtr(new Bitmap(IntPoint(1024,1024), I8));
long long StartTime = TimeSource::get()->getCurrentMicrosecs();
for (int i=0; i<1000; ++i) {
FilterFill<Pixel8>(Pixel8(0)).applyInPlace(pBmp);
}
long long ActiveTime = TimeSource::get()->getCurrentMicrosecs()-StartTime;
cerr << "FillI8: " << ActiveTime/1000 << " us" << endl;
}
void runFillRGBPerformanceTest()
{
BitmapPtr pBmp = BitmapPtr(new Bitmap(IntPoint(1024,1024), R8G8B8));
long long StartTime = TimeSource::get()->getCurrentMicrosecs();
for (int i=0; i<1000; ++i) {
FilterFill<Pixel24>(Pixel24(0,0,0)).applyInPlace(pBmp);
}
long long ActiveTime = TimeSource::get()->getCurrentMicrosecs()-StartTime;
cerr << "FillR8G8B8: " << ActiveTime/1000 << " us" << endl;
}
void runPerformanceTests()
{
runFillI8PerformanceTest();
runFillRGBPerformanceTest();
}
int main(int nargs, char** args)
{
runPerformanceTests();
}
<commit_msg>Fix for gcc 3.3<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "Bitmap.h"
#include "Pixel32.h"
#include "Pixel24.h"
#include "Pixel16.h"
#include "Filtergrayscale.h"
#include "Filterfill.h"
#include "Filterflip.h"
#include "Filterfliprgb.h"
#include "Filterflipuv.h"
#include "Filter3x3.h"
#include "FilterConvol.h"
#include "HistoryPreProcessor.h"
#include "FilterHighpass.h"
#include "FilterGauss.h"
#include "FilterBlur.h"
#include "FilterBandpass.h"
#include "../base/TimeSource.h"
#include <Magick++.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace avg;
using namespace std;
void runFillI8PerformanceTest()
{
BitmapPtr pBmp = BitmapPtr(new Bitmap(IntPoint(1024,1024), I8));
long long StartTime = TimeSource::get()->getCurrentMicrosecs();
for (int i=0; i<1000; ++i) {
FilterFill<Pixel8> Filter = FilterFill<Pixel8>(Pixel8(0));
Filter.applyInPlace(pBmp);
}
long long ActiveTime = TimeSource::get()->getCurrentMicrosecs()-StartTime;
cerr << "FillI8: " << ActiveTime/1000 << " us" << endl;
}
void runFillRGBPerformanceTest()
{
BitmapPtr pBmp = BitmapPtr(new Bitmap(IntPoint(1024,1024), R8G8B8));
long long StartTime = TimeSource::get()->getCurrentMicrosecs();
for (int i=0; i<1000; ++i) {
FilterFill<Pixel24> Filter = FilterFill<Pixel24>(Pixel24(0,0,0));
Filter.applyInPlace(pBmp);
}
long long ActiveTime = TimeSource::get()->getCurrentMicrosecs()-StartTime;
cerr << "FillR8G8B8: " << ActiveTime/1000 << " us" << endl;
}
void runPerformanceTests()
{
runFillI8PerformanceTest();
runFillRGBPerformanceTest();
}
int main(int nargs, char** args)
{
runPerformanceTests();
}
<|endoftext|> |
<commit_before>#include "./texture_manager.h"
#include <QLoggingCategory>
#include <vector>
#include <map>
#include <string>
#include <cassert>
#include "./texture_container.h"
#include "./texture2d.h"
#include "./gl.h"
namespace Graphics
{
QLoggingCategory tmChan("Graphics.TextureManager");
TextureManager::~TextureManager()
{
for (auto texture : textures)
delete texture;
textures.clear();
shutdown();
}
int TextureManager::addTexture(std::string path)
{
int id = textures.size();
textures.push_back(newTexture2d(path));
return id;
}
int TextureManager::addTexture(QImage *image)
{
int id = textures.size();
textures.push_back(newTexture2d(image));
return id;
}
Texture2d *
TextureManager::newTexture2d(TextureSpaceDescription spaceDescription)
{
Texture2d *texture = allocateTexture2d(spaceDescription);
texture->commit();
return texture;
}
Texture2d *TextureManager::newTexture2d(std::string path)
{
auto image = new QImage(path.c_str());
auto texture = newTexture2d(image);
delete image;
return texture;
}
Texture2d *TextureManager::newTexture2d(QImage *image)
{
try
{
auto internalformat = GL_RGBA8;
auto format = GL_BGRA;
auto type = GL_UNSIGNED_BYTE;
Texture2d *texture = allocateTexture2d(TextureSpaceDescription(
1, internalformat, image->width(), image->height()));
texture->commit();
texture->texSubImage2D(0, 0, 0, image->width(), image->height(), format,
type, image->bits());
return texture;
}
catch (std::exception &error)
{
qCCritical(tmChan) << "Error loading texture: " << error.what();
throw;
}
}
bool TextureManager::initialize(Gl *gl, bool sparse, int maxTextureArrayLevels)
{
this->gl = gl;
this->maxTextureArrayLevels = maxTextureArrayLevels;
this->isSparse = sparse;
if (maxTextureArrayLevels > 0)
return true;
if (sparse)
{
glGetIntegerv(GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB,
&maxTextureArrayLevels);
}
else
{
glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &maxTextureArrayLevels);
}
return true;
}
void TextureManager::shutdown()
{
for (auto containIt = textureContainers.begin();
containIt != textureContainers.end(); ++containIt)
{
for (auto ptrIt = containIt->second.begin();
ptrIt != containIt->second.end(); ++ptrIt)
{
delete *ptrIt;
}
}
textureContainers.clear();
}
TextureAddress TextureManager::getAddressFor(int textureId)
{
return textures[textureId]->address();
}
Texture2d *
TextureManager::allocateTexture2d(TextureSpaceDescription spaceDescription)
{
TextureContainer *memArray = nullptr;
spaceDescription.growToNextPowerOfTwo();
auto arrayIt = textureContainers.find(spaceDescription);
if (arrayIt == textureContainers.end())
{
textureContainers[spaceDescription] = std::vector<TextureContainer *>();
arrayIt = textureContainers.find(spaceDescription);
assert(arrayIt != textureContainers.end());
}
for (auto it = arrayIt->second.begin(); it != arrayIt->second.end(); ++it)
{
if ((*it)->hasRoom())
{
memArray = (*it);
break;
}
}
if (memArray == nullptr)
{
memArray = new TextureContainer(gl, isSparse, spaceDescription,
maxTextureArrayLevels);
arrayIt->second.push_back(memArray);
}
assert(memArray);
return new Texture2d(memArray, memArray->virtualAlloc());
}
} // namespace Graphics
<commit_msg>Minor: refactoring.<commit_after>#include "./texture_manager.h"
#include <QLoggingCategory>
#include <vector>
#include <map>
#include <string>
#include <cassert>
#include "./texture_container.h"
#include "./texture2d.h"
#include "./gl.h"
namespace Graphics
{
QLoggingCategory tmChan("Graphics.TextureManager");
TextureManager::~TextureManager()
{
for (auto texture : textures)
delete texture;
textures.clear();
shutdown();
}
int TextureManager::addTexture(std::string path)
{
int id = textures.size();
textures.push_back(newTexture2d(path));
return id;
}
int TextureManager::addTexture(QImage *image)
{
int id = textures.size();
textures.push_back(newTexture2d(image));
return id;
}
Texture2d *
TextureManager::newTexture2d(TextureSpaceDescription spaceDescription)
{
Texture2d *texture = allocateTexture2d(spaceDescription);
texture->commit();
return texture;
}
Texture2d *TextureManager::newTexture2d(std::string path)
{
auto image = new QImage(path.c_str());
auto texture = newTexture2d(image);
delete image;
return texture;
}
Texture2d *TextureManager::newTexture2d(QImage *image)
{
try
{
auto internalformat = GL_RGBA8;
auto format = GL_BGRA;
auto type = GL_UNSIGNED_BYTE;
Texture2d *texture = allocateTexture2d(TextureSpaceDescription(
1, internalformat, image->width(), image->height()));
texture->commit();
texture->texSubImage2D(0, 0, 0, image->width(), image->height(), format,
type, image->bits());
return texture;
}
catch (std::exception &error)
{
qCCritical(tmChan) << "Error loading texture: " << error.what();
throw;
}
}
bool TextureManager::initialize(Gl *gl, bool sparse, int maxTextureArrayLevels)
{
this->gl = gl;
this->maxTextureArrayLevels = maxTextureArrayLevels;
this->isSparse = sparse;
if (maxTextureArrayLevels > 0)
return true;
auto layersKey = sparse ? GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB
: GL_MAX_ARRAY_TEXTURE_LAYERS;
glGetIntegerv(layersKey, &maxTextureArrayLevels);
return true;
}
void TextureManager::shutdown()
{
for (auto containIt = textureContainers.begin();
containIt != textureContainers.end(); ++containIt)
{
for (auto ptrIt = containIt->second.begin();
ptrIt != containIt->second.end(); ++ptrIt)
{
delete *ptrIt;
}
}
textureContainers.clear();
}
TextureAddress TextureManager::getAddressFor(int textureId)
{
return textures[textureId]->address();
}
Texture2d *
TextureManager::allocateTexture2d(TextureSpaceDescription spaceDescription)
{
TextureContainer *memArray = nullptr;
spaceDescription.growToNextPowerOfTwo();
auto arrayIt = textureContainers.find(spaceDescription);
if (arrayIt == textureContainers.end())
{
textureContainers[spaceDescription] = std::vector<TextureContainer *>();
arrayIt = textureContainers.find(spaceDescription);
assert(arrayIt != textureContainers.end());
}
for (auto it = arrayIt->second.begin(); it != arrayIt->second.end(); ++it)
{
if ((*it)->hasRoom())
{
memArray = (*it);
break;
}
}
if (memArray == nullptr)
{
memArray = new TextureContainer(gl, isSparse, spaceDescription,
maxTextureArrayLevels);
arrayIt->second.push_back(memArray);
}
assert(memArray);
return new Texture2d(memArray, memArray->virtualAlloc());
}
} // namespace Graphics
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_PRIM_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/prim/mat/err/check_symmetric.hpp>
#ifdef STAN_OPENCL
#include <stan/math/gpu/opencl_context.hpp>
#include <stan/math/gpu/cholesky_decompose.hpp>
#include <stan/math/gpu/copy.hpp>
#endif
#include <cmath>
namespace stan {
namespace math {
/**
* Return the lower-triangular Cholesky factor (i.e., matrix
* square root) of the specified square, symmetric matrix. The return
* value \f$L\f$ will be a lower-traingular matrix such that the
* original matrix \f$A\f$ is given by
* <p>\f$A = L \times L^T\f$.
* @param m Symmetrix matrix.
* @return Square root of matrix.
* @note Because OpenCL only works on doubles there are two
* <code>cholesky_decompose</code> functions. One that works on doubles
* (this one) and another that works on all other types.
* @throw std::domain_error if m is not a symmetric matrix or
* if m is not positive definite (if m has more than 0 elements)
*/
template <>
inline Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> cholesky_decompose(
const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& m) {
check_square("cholesky_decompose", "m", m);
check_symmetric("cholesky_decompose", "m", m);
#ifdef STAN_OPENCL
if (m.rows() >= opencl_context.tuning_opts().cholesky_size_worth_transfer) {
matrix_gpu m_gpu(m);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m_chol(m.rows(),
m.cols());
m_gpu = cholesky_decompose(m_gpu);
copy(m_chol, m_gpu); // NOLINT
return m_chol;
} else {
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(
m.rows());
llt.compute(m);
check_pos_definite("cholesky_decompose", "m", llt);
return llt.matrixL();
}
#else
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(
m.rows());
llt.compute(m);
check_pos_definite("cholesky_decompose", "m", llt);
return llt.matrixL();
#endif
}
/**
* Return the lower-triangular Cholesky factor (i.e., matrix
* square root) of the specified square, symmetric matrix. The return
* value \f$L\f$ will be a lower-traingular matrix such that the
* original matrix \f$A\f$ is given by
* <p>\f$A = L \times L^T\f$.
* @param m Symmetrix matrix.
* @return Square root of matrix.
* @note Because OpenCL only works on doubles there are two
* <code>cholesky_decompose</code> functions. One that works on doubles
* and another that works on all other types (this one).
* @throw std::domain_error if m is not a symmetric matrix or
* if m is not positive definite (if m has more than 0 elements)
*/
template <typename T>
inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> cholesky_decompose(
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m) {
check_square("cholesky_decompose", "m", m);
check_symmetric("cholesky_decompose", "m", m);
Eigen::LLT<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> > llt(m.rows());
llt.compute(m);
check_pos_definite("cholesky_decompose", "m", llt);
return llt.matrixL();
}
} // namespace math
} // namespace stan
#endif
<commit_msg>the template specialization comes after the default function, rok needs to read more<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_PRIM_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/prim/mat/err/check_symmetric.hpp>
#ifdef STAN_OPENCL
#include <stan/math/gpu/opencl_context.hpp>
#include <stan/math/gpu/cholesky_decompose.hpp>
#include <stan/math/gpu/copy.hpp>
#endif
#include <cmath>
namespace stan {
namespace math {
/**
* Return the lower-triangular Cholesky factor (i.e., matrix
* square root) of the specified square, symmetric matrix. The return
* value \f$L\f$ will be a lower-traingular matrix such that the
* original matrix \f$A\f$ is given by
* <p>\f$A = L \times L^T\f$.
* @param m Symmetrix matrix.
* @return Square root of matrix.
* @note Because OpenCL only works on doubles there are two
* <code>cholesky_decompose</code> functions. One that works on doubles
* and another that works on all other types (this one).
* @throw std::domain_error if m is not a symmetric matrix or
* if m is not positive definite (if m has more than 0 elements)
*/
template <typename T>
inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> cholesky_decompose(
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m) {
check_square("cholesky_decompose", "m", m);
check_symmetric("cholesky_decompose", "m", m);
Eigen::LLT<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> > llt(m.rows());
llt.compute(m);
check_pos_definite("cholesky_decompose", "m", llt);
return llt.matrixL();
}
/**
* Return the lower-triangular Cholesky factor (i.e., matrix
* square root) of the specified square, symmetric matrix. The return
* value \f$L\f$ will be a lower-traingular matrix such that the
* original matrix \f$A\f$ is given by
* <p>\f$A = L \times L^T\f$.
* @param m Symmetrix matrix.
* @return Square root of matrix.
* @note Because OpenCL only works on doubles there are two
* <code>cholesky_decompose</code> functions. One that works on doubles
* (this one) and another that works on all other types.
* @throw std::domain_error if m is not a symmetric matrix or
* if m is not positive definite (if m has more than 0 elements)
*/
template <>
inline Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> cholesky_decompose(
const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& m) {
check_square("cholesky_decompose", "m", m);
check_symmetric("cholesky_decompose", "m", m);
#ifdef STAN_OPENCL
if (m.rows() >= opencl_context.tuning_opts().cholesky_size_worth_transfer) {
matrix_gpu m_gpu(m);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m_chol(m.rows(),
m.cols());
m_gpu = cholesky_decompose(m_gpu);
copy(m_chol, m_gpu); // NOLINT
return m_chol;
} else {
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(
m.rows());
llt.compute(m);
check_pos_definite("cholesky_decompose", "m", llt);
return llt.matrixL();
}
#else
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(
m.rows());
llt.compute(m);
check_pos_definite("cholesky_decompose", "m", llt);
return llt.matrixL();
#endif
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unogalthemeprovider.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2007-01-23 09:00:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "unogalthemeprovider.hxx"
#include "unogaltheme.hxx"
#include "gallery1.hxx"
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX_
#include <vcl/svapp.hxx>
#endif
#include <svtools/pathoptions.hxx>
#ifndef _COM_SUN_STAR_GALLERY_XGALLERYTHEME_HPP_
#include <com/sun/star/gallery/XGalleryTheme.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
using namespace ::com::sun::star;
namespace unogallery {
// --------------------
// - Helper functions -
// --------------------
uno::Reference< uno::XInterface > SAL_CALL GalleryThemeProvider_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & )
throw( uno::Exception )
{
return *( new GalleryThemeProvider() );
}
// -----------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL GalleryThemeProvider_getSupportedServiceNames()
throw()
{
return GalleryThemeProvider::getSupportedServiceNames_Static();
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL GalleryThemeProvider_getImplementationName()
throw()
{
return GalleryThemeProvider::getImplementationName_Static();
}
// -----------------
// - GalleryThemeProvider -
// -----------------
GalleryThemeProvider::GalleryThemeProvider() :
mbHiddenThemes( sal_False )
{
mpGallery = ::Gallery::GetGalleryInstance();
}
// ------------------------------------------------------------------------------
GalleryThemeProvider::~GalleryThemeProvider()
{
}
// ------------------------------------------------------------------------------
::rtl::OUString GalleryThemeProvider::getImplementationName_Static()
throw()
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.gallery.GalleryThemeProvider" ) );
}
// ------------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > GalleryThemeProvider::getSupportedServiceNames_Static()
throw()
{
uno::Sequence< ::rtl::OUString > aSeq( 1 );
aSeq.getArray()[ 0 ] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.gallery.GalleryThemeProvider" ) );
return aSeq;
}
// ------------------------------------------------------------------------------
::rtl::OUString SAL_CALL GalleryThemeProvider::getImplementationName()
throw( uno::RuntimeException )
{
return getImplementationName_Static();
}
// ------------------------------------------------------------------------------
sal_Bool SAL_CALL GalleryThemeProvider::supportsService( const ::rtl::OUString& ServiceName )
throw( uno::RuntimeException )
{
uno::Sequence< ::rtl::OUString > aSNL( getSupportedServiceNames() );
const ::rtl::OUString* pArray = aSNL.getConstArray();
for( int i = 0; i < aSNL.getLength(); i++ )
if( pArray[i] == ServiceName )
return true;
return false;
}
// ------------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL GalleryThemeProvider::getSupportedServiceNames()
throw( uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
// ------------------------------------------------------------------------------
uno::Sequence< uno::Type > SAL_CALL GalleryThemeProvider::getTypes()
throw(uno::RuntimeException)
{
uno::Sequence< uno::Type > aTypes( 6 );
uno::Type* pTypes = aTypes.getArray();
*pTypes++ = ::getCppuType((const uno::Reference< lang::XServiceInfo>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< lang::XTypeProvider>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< lang::XInitialization>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< container::XElementAccess>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< container::XNameAccess>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< gallery::XGalleryThemeProvider>*)0);
return aTypes;
}
// ------------------------------------------------------------------------------
uno::Sequence< sal_Int8 > SAL_CALL GalleryThemeProvider::getImplementationId()
throw(uno::RuntimeException)
{
const vos::OGuard aGuard( Application::GetSolarMutex() );
static uno::Sequence< sal_Int8 > aId;
if( aId.getLength() == 0 )
{
aId.realloc( 16 );
rtl_createUuid( reinterpret_cast< sal_uInt8* >( aId.getArray() ), 0, sal_True );
}
return aId;
}
// ------------------------------------------------------------------------------
void SAL_CALL GalleryThemeProvider::initialize( const uno::Sequence< uno::Any >& rArguments )
throw ( uno::Exception, uno::RuntimeException )
{
uno::Sequence< beans::PropertyValue > aParams;
sal_Int32 i;
for( i = 0; i < rArguments.getLength(); ++i )
{
if( rArguments[ i ] >>= aParams )
break;
}
for( i = 0; i < aParams.getLength(); ++i )
{
const beans::PropertyValue& rProp = aParams[ i ];
if( rProp.Name.equalsAscii( "ProvideHiddenThemes" ) )
rProp.Value >>= mbHiddenThemes;
}
}
// ------------------------------------------------------------------------------
uno::Type SAL_CALL GalleryThemeProvider::getElementType()
throw (uno::RuntimeException)
{
return ::getCppuType( (const uno::Reference< gallery::XGalleryTheme >*) 0);
}
// ------------------------------------------------------------------------------
sal_Bool SAL_CALL GalleryThemeProvider::hasElements()
throw (uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
return( ( mpGallery != NULL ) && ( mpGallery->GetThemeCount() > 0 ) );
}
// ------------------------------------------------------------------------------
uno::Any SAL_CALL GalleryThemeProvider::getByName( const ::rtl::OUString& rName )
throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
uno::Any aRet;
if( !mpGallery || !mpGallery->HasTheme( rName ) )
{
throw container::NoSuchElementException();
}
else
{
aRet = uno::makeAny( uno::Reference< gallery::XGalleryTheme >( new ::unogallery::GalleryTheme( rName ) ) );
}
return aRet;
}
// ------------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL GalleryThemeProvider::getElementNames()
throw (uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
sal_uInt32 i = 0, nCount = ( mpGallery ? mpGallery->GetThemeCount() : 0 ), nRealCount = 0;
uno::Sequence< ::rtl::OUString > aSeq( nCount );
for( ; i < nCount; ++i )
{
const GalleryThemeEntry* pEntry = mpGallery->GetThemeInfo( i );
if( mbHiddenThemes || !pEntry->IsHidden() )
aSeq[ nRealCount++ ] = pEntry->GetThemeName();
}
aSeq.realloc( nRealCount );
return aSeq;
}
// ------------------------------------------------------------------------------
sal_Bool SAL_CALL GalleryThemeProvider::hasByName( const ::rtl::OUString& rName )
throw (uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
sal_Bool bRet = sal_False;
if( mpGallery && mpGallery->HasTheme( rName ) )
bRet = ( mbHiddenThemes || !mpGallery->GetThemeInfo( rName )->IsHidden() );
return( bRet );
}
// ------------------------------------------------------------------------------
uno::Reference< gallery::XGalleryTheme > SAL_CALL GalleryThemeProvider::insertNewByName( const ::rtl::OUString& rThemeName )
throw (container::ElementExistException, uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
uno::Reference< gallery::XGalleryTheme > xRet;
if( mpGallery )
{
if( mpGallery->HasTheme( rThemeName ) )
{
throw container::ElementExistException();
}
else if( mpGallery->CreateTheme( rThemeName ) )
{
xRet = new ::unogallery::GalleryTheme( rThemeName );
}
}
return xRet;
}
// ------------------------------------------------------------------------------
void SAL_CALL GalleryThemeProvider::removeByName( const ::rtl::OUString& rName )
throw (container::NoSuchElementException, uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
if( !mpGallery ||
!mpGallery->HasTheme( rName ) ||
( !mbHiddenThemes && mpGallery->GetThemeInfo( rName )->IsHidden() ) )
{
throw container::NoSuchElementException();
}
else
{
mpGallery->RemoveTheme( rName );
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.510); FILE MERGED 2008/04/01 15:51:59 thb 1.6.510.3: #i85898# Stripping all external header guards 2008/04/01 12:50:22 thb 1.6.510.2: #i85898# Stripping all external header guards 2008/03/31 14:24:17 rt 1.6.510.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unogalthemeprovider.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "unogalthemeprovider.hxx"
#include "unogaltheme.hxx"
#include "gallery1.hxx"
#include <rtl/uuid.h>
#include <vos/mutex.hxx>
#ifndef _SV_SVAPP_HXX_
#include <vcl/svapp.hxx>
#endif
#include <svtools/pathoptions.hxx>
#include <com/sun/star/gallery/XGalleryTheme.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
using namespace ::com::sun::star;
namespace unogallery {
// --------------------
// - Helper functions -
// --------------------
uno::Reference< uno::XInterface > SAL_CALL GalleryThemeProvider_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & )
throw( uno::Exception )
{
return *( new GalleryThemeProvider() );
}
// -----------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL GalleryThemeProvider_getSupportedServiceNames()
throw()
{
return GalleryThemeProvider::getSupportedServiceNames_Static();
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL GalleryThemeProvider_getImplementationName()
throw()
{
return GalleryThemeProvider::getImplementationName_Static();
}
// -----------------
// - GalleryThemeProvider -
// -----------------
GalleryThemeProvider::GalleryThemeProvider() :
mbHiddenThemes( sal_False )
{
mpGallery = ::Gallery::GetGalleryInstance();
}
// ------------------------------------------------------------------------------
GalleryThemeProvider::~GalleryThemeProvider()
{
}
// ------------------------------------------------------------------------------
::rtl::OUString GalleryThemeProvider::getImplementationName_Static()
throw()
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.gallery.GalleryThemeProvider" ) );
}
// ------------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > GalleryThemeProvider::getSupportedServiceNames_Static()
throw()
{
uno::Sequence< ::rtl::OUString > aSeq( 1 );
aSeq.getArray()[ 0 ] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.gallery.GalleryThemeProvider" ) );
return aSeq;
}
// ------------------------------------------------------------------------------
::rtl::OUString SAL_CALL GalleryThemeProvider::getImplementationName()
throw( uno::RuntimeException )
{
return getImplementationName_Static();
}
// ------------------------------------------------------------------------------
sal_Bool SAL_CALL GalleryThemeProvider::supportsService( const ::rtl::OUString& ServiceName )
throw( uno::RuntimeException )
{
uno::Sequence< ::rtl::OUString > aSNL( getSupportedServiceNames() );
const ::rtl::OUString* pArray = aSNL.getConstArray();
for( int i = 0; i < aSNL.getLength(); i++ )
if( pArray[i] == ServiceName )
return true;
return false;
}
// ------------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL GalleryThemeProvider::getSupportedServiceNames()
throw( uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
// ------------------------------------------------------------------------------
uno::Sequence< uno::Type > SAL_CALL GalleryThemeProvider::getTypes()
throw(uno::RuntimeException)
{
uno::Sequence< uno::Type > aTypes( 6 );
uno::Type* pTypes = aTypes.getArray();
*pTypes++ = ::getCppuType((const uno::Reference< lang::XServiceInfo>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< lang::XTypeProvider>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< lang::XInitialization>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< container::XElementAccess>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< container::XNameAccess>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< gallery::XGalleryThemeProvider>*)0);
return aTypes;
}
// ------------------------------------------------------------------------------
uno::Sequence< sal_Int8 > SAL_CALL GalleryThemeProvider::getImplementationId()
throw(uno::RuntimeException)
{
const vos::OGuard aGuard( Application::GetSolarMutex() );
static uno::Sequence< sal_Int8 > aId;
if( aId.getLength() == 0 )
{
aId.realloc( 16 );
rtl_createUuid( reinterpret_cast< sal_uInt8* >( aId.getArray() ), 0, sal_True );
}
return aId;
}
// ------------------------------------------------------------------------------
void SAL_CALL GalleryThemeProvider::initialize( const uno::Sequence< uno::Any >& rArguments )
throw ( uno::Exception, uno::RuntimeException )
{
uno::Sequence< beans::PropertyValue > aParams;
sal_Int32 i;
for( i = 0; i < rArguments.getLength(); ++i )
{
if( rArguments[ i ] >>= aParams )
break;
}
for( i = 0; i < aParams.getLength(); ++i )
{
const beans::PropertyValue& rProp = aParams[ i ];
if( rProp.Name.equalsAscii( "ProvideHiddenThemes" ) )
rProp.Value >>= mbHiddenThemes;
}
}
// ------------------------------------------------------------------------------
uno::Type SAL_CALL GalleryThemeProvider::getElementType()
throw (uno::RuntimeException)
{
return ::getCppuType( (const uno::Reference< gallery::XGalleryTheme >*) 0);
}
// ------------------------------------------------------------------------------
sal_Bool SAL_CALL GalleryThemeProvider::hasElements()
throw (uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
return( ( mpGallery != NULL ) && ( mpGallery->GetThemeCount() > 0 ) );
}
// ------------------------------------------------------------------------------
uno::Any SAL_CALL GalleryThemeProvider::getByName( const ::rtl::OUString& rName )
throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
uno::Any aRet;
if( !mpGallery || !mpGallery->HasTheme( rName ) )
{
throw container::NoSuchElementException();
}
else
{
aRet = uno::makeAny( uno::Reference< gallery::XGalleryTheme >( new ::unogallery::GalleryTheme( rName ) ) );
}
return aRet;
}
// ------------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL GalleryThemeProvider::getElementNames()
throw (uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
sal_uInt32 i = 0, nCount = ( mpGallery ? mpGallery->GetThemeCount() : 0 ), nRealCount = 0;
uno::Sequence< ::rtl::OUString > aSeq( nCount );
for( ; i < nCount; ++i )
{
const GalleryThemeEntry* pEntry = mpGallery->GetThemeInfo( i );
if( mbHiddenThemes || !pEntry->IsHidden() )
aSeq[ nRealCount++ ] = pEntry->GetThemeName();
}
aSeq.realloc( nRealCount );
return aSeq;
}
// ------------------------------------------------------------------------------
sal_Bool SAL_CALL GalleryThemeProvider::hasByName( const ::rtl::OUString& rName )
throw (uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
sal_Bool bRet = sal_False;
if( mpGallery && mpGallery->HasTheme( rName ) )
bRet = ( mbHiddenThemes || !mpGallery->GetThemeInfo( rName )->IsHidden() );
return( bRet );
}
// ------------------------------------------------------------------------------
uno::Reference< gallery::XGalleryTheme > SAL_CALL GalleryThemeProvider::insertNewByName( const ::rtl::OUString& rThemeName )
throw (container::ElementExistException, uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
uno::Reference< gallery::XGalleryTheme > xRet;
if( mpGallery )
{
if( mpGallery->HasTheme( rThemeName ) )
{
throw container::ElementExistException();
}
else if( mpGallery->CreateTheme( rThemeName ) )
{
xRet = new ::unogallery::GalleryTheme( rThemeName );
}
}
return xRet;
}
// ------------------------------------------------------------------------------
void SAL_CALL GalleryThemeProvider::removeByName( const ::rtl::OUString& rName )
throw (container::NoSuchElementException, uno::RuntimeException)
{
const ::vos::OGuard aGuard( Application::GetSolarMutex() );
if( !mpGallery ||
!mpGallery->HasTheme( rName ) ||
( !mbHiddenThemes && mpGallery->GetThemeInfo( rName )->IsHidden() ) )
{
throw container::NoSuchElementException();
}
else
{
mpGallery->RemoveTheme( rName );
}
}
}
<|endoftext|> |
<commit_before>/*
*
* MIT License
*
* Copyright (c) 2016-2017 The Cats Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef CATS_CORECAT_PROMISE_HPP
#define CATS_CORECAT_PROMISE_HPP
#include <deque>
#include <functional>
#include <memory>
#include <type_traits>
#include "ExceptionWrapper.hpp"
namespace Cats {
namespace Corecat {
// Inspired by https://github.com/facebook/folly/blob/master/folly/futures/Future.h
template <typename T>
class Promise {
public:
enum class State { Pending, Resolved, Rejected };
public:
struct Void {};
template <typename U>
using NonVoidType = typename std::conditional<std::is_void<U>::value, Void, U>::type;
template <typename... U>
struct VoidTypeImpl { using Type = void; };
template <typename... U>
using VoidType = typename VoidTypeImpl<U...>::Type;
template <typename U>
using EnableIfVoid = typename std::enable_if<std::is_void<U>::value>::type;
template <typename U>
using EnableIfNotVoid = typename std::enable_if<!std::is_void<U>::value>::type;
template <typename F, typename... Arg>
struct ResultTypeImpl { using Type = decltype(std::declval<F>()(std::declval<Arg>()...)); };
template <typename F>
struct ResultTypeImpl<F, void> { using Type = decltype(std::declval<F>()()); };
template <typename F, typename... Arg>
using ResultType = typename ResultTypeImpl<F, Arg...>::Type;
template <typename F, typename Args, typename = void>
struct IsCallableImpl : public std::false_type {};
template <typename F, typename... Arg>
struct IsCallableImpl<F, std::tuple<Arg...>, VoidType<decltype(std::declval<F>()(std::declval<Arg>()...))>> : public std::true_type {};
template <typename F, typename... Arg>
struct IsCallable : public IsCallableImpl<F, std::tuple<Arg...>> {};
template <typename F>
struct IsCallable<F, void> : public IsCallableImpl<F, std::tuple<>> {};
template <typename F, typename U, typename V = NonVoidType<U>>
using ArgumentType =
typename std::conditional<std::is_void<U>::value, void,
typename std::conditional<IsCallable<F, V>::value, V,
typename std::conditional<IsCallable<F, const V&>::value, const V&,
void>::type>::type>::type;
private:
class Impl {
private:
State state = State::Pending;
std::deque<std::function<typename std::conditional<std::is_void<T>::value, void(), void(const NonVoidType<T>&)>::type>> resolvedQueue;
std::deque<std::function<void(const ExceptionWrapper&)>> rejectedQueue;
NonVoidType<T> result;
ExceptionWrapper exception;
public:
Impl(const Impl& src) = delete;
~Impl() {}
Impl() = default;
Impl& operator =(const Impl& src) = delete;
State getState() { return state; }
template <typename U = T, typename = EnableIfVoid<U>>
void resolve() {
if(state == State::Pending) {
state = State::Resolved;
for(auto& x : resolvedQueue) x();
resolvedQueue.clear();
rejectedQueue.clear();
}
}
template <typename U = T, typename = EnableIfNotVoid<U>>
void resolve(U&& u) {
if(state == State::Pending) {
state = State::Resolved;
result = std::forward<U>(u);
for(auto& x : resolvedQueue) x(result);
resolvedQueue.clear();
rejectedQueue.clear();
}
}
void reject(ExceptionWrapper&& e) {
if(state == State::Pending) {
state = State::Rejected;
exception = std::forward<ExceptionWrapper>(e);
for(auto& x : rejectedQueue) x(exception);
resolvedQueue.clear();
rejectedQueue.clear();
}
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
Promise<Res> then(F&& resolved, EnableIfVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, resolved]() {
try { resolved(); promise.resolve(); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: resolvedQueue.emplace_back(cb); break;
case State::Resolved: cb(); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
Promise<Res> then(F&& resolved, EnableIfVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, resolved]() {
try { promise.resolve(resolved()); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: resolvedQueue.emplace_back(cb); break;
case State::Resolved: cb(); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
Promise<Res> then(F&& resolved, EnableIfNotVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, resolved](const T& t) {
try { resolved(t); promise.resolve(); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: resolvedQueue.emplace_back(cb); break;
case State::Resolved: cb(result); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
Promise<Res> then(F&& resolved, EnableIfNotVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, resolved](const T& t) {
try { promise.resolve(resolved(t)); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: resolvedQueue.emplace_back(cb); break;
case State::Resolved: cb(result); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
Promise<Res> fail(F&& rejected, EnableIfVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, rejected](const ExceptionWrapper& e) {
try { rejected(); promise.resolve(); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: rejectedQueue.emplace_back(cb); break;
case State::Rejected: cb(ExceptionWrapper()); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
Promise<Res> fail(F&& rejected, EnableIfVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, rejected](const ExceptionWrapper& e) {
try { promise.resolve(rejected()); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: rejectedQueue.emplace_back(cb); break;
case State::Rejected: cb(ExceptionWrapper()); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
Promise<Res> fail(F&& rejected, EnableIfNotVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, rejected](const ExceptionWrapper& e) {
try { rejected(e); promise.resolve(); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: rejectedQueue.emplace_back(cb); break;
case State::Rejected: cb(exception); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
Promise<Res> fail(F&& rejected, EnableIfNotVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
Promise<Res> promise;
auto cb = [promise, rejected](const ExceptionWrapper& e) {
try { promise.resolve(rejected(e)); }
catch(...) {
ExceptionWrapper ew;
ew.setCurrent();
promise.reject(std::move(ew));
}
};
switch(state) {
case State::Pending: rejectedQueue.emplace_back(cb); break;
case State::Rejected: cb(exception); break;
default: break;
}
return promise;
}
};
public:
std::shared_ptr<Impl> impl;
public:
Promise(const Promise& src) : impl(src.impl) {}
Promise() : impl(std::make_shared<Impl>()) {}
Promise& operator =(const Promise& src) { impl = src.impl; return *this; }
template <typename U = T, typename = typename std::enable_if<std::is_same<U, void>::value>::type>
void resolve() const { impl->resolve(); }
template <typename U = T, typename = typename std::enable_if<!std::is_same<U, void>::value>::type>
void resolve(U&& t) const { impl->resolve(std::move(t)); }
void reject(ExceptionWrapper&& t) const { impl->reject(std::move(t)); }
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
Promise<Res> then(F&& resolved) const { return impl->then(std::forward<F>(resolved)); }
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
Promise<Res> fail(F&& rejected) const { return impl->fail(std::forward<F>(rejected)); }
public:
template <typename F>
static Promise create(F&& f) {
Promise promise;
f(promise);
return promise;
}
};
}
}
#endif
<commit_msg>Update Promise<commit_after>/*
*
* MIT License
*
* Copyright (c) 2016-2017 The Cats Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef CATS_CORECAT_PROMISE_HPP
#define CATS_CORECAT_PROMISE_HPP
#include <deque>
#include <functional>
#include <memory>
#include <type_traits>
#include "ExceptionWrapper.hpp"
namespace Cats {
namespace Corecat {
// Inspired by https://github.com/facebook/folly/blob/master/folly/futures/Future.h
template <typename T>
class Promise {
public:
enum class State { Pending, Resolved, Rejected };
public:
struct Void {};
template <typename U>
using NonVoidType = typename std::conditional<std::is_void<U>::value, Void, U>::type;
template <typename... U>
struct VoidTypeImpl { using Type = void; };
template <typename... U>
using VoidType = typename VoidTypeImpl<U...>::Type;
template <typename U>
using EnableIfVoid = typename std::enable_if<std::is_void<U>::value>::type;
template <typename U>
using EnableIfNotVoid = typename std::enable_if<!std::is_void<U>::value>::type;
template <typename F, typename... Arg>
struct ResultTypeImpl { using Type = decltype(std::declval<F>()(std::declval<Arg>()...)); };
template <typename F>
struct ResultTypeImpl<F, void> { using Type = decltype(std::declval<F>()()); };
template <typename F, typename... Arg>
using ResultType = typename ResultTypeImpl<F, Arg...>::Type;
template <typename F, typename Args, typename = void>
struct IsCallableImpl : public std::false_type {};
template <typename F, typename... Arg>
struct IsCallableImpl<F, std::tuple<Arg...>, VoidType<decltype(std::declval<F>()(std::declval<Arg>()...))>> : public std::true_type {};
template <typename F, typename... Arg>
struct IsCallable : public IsCallableImpl<F, std::tuple<Arg...>> {};
template <typename F>
struct IsCallable<F, void> : public IsCallableImpl<F, std::tuple<>> {};
template <typename F, typename U, typename V = NonVoidType<U>>
using ArgumentType =
typename std::conditional<std::is_void<U>::value, void,
typename std::conditional<IsCallable<F, V>::value, V,
typename std::conditional<IsCallable<F, const V&>::value, const V&,
void>::type>::type>::type;
private:
class Impl {
private:
State state = State::Pending;
std::deque<std::function<void()>> resolvedQueue;
std::deque<std::function<void()>> rejectedQueue;
NonVoidType<T> result;
ExceptionWrapper exception;
private:
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
void thenImpl(F&& resolved, const Promise<Res>& promise, EnableIfVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
resolved(); promise.resolve();
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
void thenImpl(F&& resolved, const Promise<Res>& promise, EnableIfNotVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
resolved(result); promise.resolve();
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
void thenImpl(F&& resolved, const Promise<Res>& promise, EnableIfVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
promise.resolve(resolved());
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
void thenImpl(F&& resolved, const Promise<Res>& promise, EnableIfNotVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
promise.resolve(resolved(result));
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
void failImpl(F&& rejected, const Promise<Res>& promise, EnableIfVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
rejected(); promise.resolve();
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
void failImpl(F&& rejected, const Promise<Res>& promise, EnableIfNotVoid<Arg>* = 0, EnableIfVoid<Res>* = 0) {
rejected(exception); promise.resolve();
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
void failImpl(F&& rejected, const Promise<Res>& promise, EnableIfVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
promise.resolve(rejected());
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
void failImpl(F&& rejected, const Promise<Res>& promise, EnableIfNotVoid<Arg>* = 0, EnableIfNotVoid<Res>* = 0) {
promise.resolve(rejected(exception));
}
public:
Impl(const Impl& src) = delete;
~Impl() {}
Impl() = default;
Impl& operator =(const Impl& src) = delete;
State getState() { return state; }
template <typename U = T, typename = EnableIfVoid<U>>
void resolve() {
if(state == State::Pending) {
state = State::Resolved;
for(auto& x : resolvedQueue) x();
resolvedQueue.clear();
rejectedQueue.clear();
}
}
template <typename U = T, typename = EnableIfNotVoid<U>>
void resolve(U&& u) {
if(state == State::Pending) {
state = State::Resolved;
result = std::forward<U>(u);
for(auto& x : resolvedQueue) x();
resolvedQueue.clear();
rejectedQueue.clear();
}
}
void reject(ExceptionWrapper&& e) {
if(state == State::Pending) {
state = State::Rejected;
exception = std::forward<ExceptionWrapper>(e);
for(auto& x : rejectedQueue) x();
resolvedQueue.clear();
rejectedQueue.clear();
}
}
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
Promise<Res> then(F&& resolved) {
Promise<Res> promise;
auto cb = [this, resolved, promise]() {
try { thenImpl(resolved, promise); }
catch(...) { promise.reject(ExceptionWrapper::current()); }
};
switch(state) {
case State::Pending: resolvedQueue.emplace_back(cb); break;
case State::Resolved: cb(); break;
default: break;
}
return promise;
}
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
Promise<Res> fail(F&& rejected) {
Promise<Res> promise;
auto cb = [this, rejected, promise]() {
try { failImpl(rejected, promise); }
catch(...) { promise.reject(ExceptionWrapper::current()); }
};
switch(state) {
case State::Pending: rejectedQueue.emplace_back(cb); break;
case State::Rejected: cb(); break;
default: break;
}
return promise;
}
};
public:
std::shared_ptr<Impl> impl;
public:
Promise(const Promise& src) : impl(src.impl) {}
Promise() : impl(std::make_shared<Impl>()) {}
Promise& operator =(const Promise& src) { impl = src.impl; return *this; }
template <typename U = T, typename = typename std::enable_if<std::is_same<U, void>::value>::type>
void resolve() const { impl->resolve(); }
template <typename U = T, typename = typename std::enable_if<!std::is_same<U, void>::value>::type>
void resolve(U&& t) const { impl->resolve(std::move(t)); }
void reject(ExceptionWrapper&& t) const { impl->reject(std::move(t)); }
template <typename F, typename Arg = ArgumentType<F, T>, typename Res = ResultType<F, Arg>>
Promise<Res> then(F&& resolved) const { return impl->then(std::forward<F>(resolved)); }
template <typename F, typename Arg = ArgumentType<F, ExceptionWrapper>, typename Res = ResultType<F, Arg>>
Promise<Res> fail(F&& rejected) const { return impl->fail(std::forward<F>(rejected)); }
public:
template <typename F>
static Promise create(F&& f) {
Promise promise;
f(promise);
return promise;
}
};
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef ALEPH_TOPOLOGY_IO_PLY_HH__
#define ALEPH_TOPOLOGY_IO_PLY_HH__
#include <aleph/utilities/String.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/filtrations/Data.hh>
#include <cassert>
#include <fstream>
#include <limits>
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace aleph
{
namespace topology
{
namespace io
{
namespace detail
{
/*
Maps PLY data types to their corresponding sizes in bytes. This is
required for parsing binary files later on.
*/
std::map<std::string, unsigned short> TypeSizeMap = {
{ "double" , 8 },
{ "float" , 4 },
{ "int" , 4 },
{ "int32" , 4 },
{ "uint" , 4 },
{ "uint32" , 4 },
{ "short" , 2 },
{ "ushort" , 2 },
{ "char" , 1 },
{ "uchar" , 1 },
{ "uint8" , 1 }
};
/*
Maps PLY data types to their 'signedness'. This is required for
parsing binary files later on.
TODO: Use this to extend parse
*/
std::map<std::string, bool> TypeSignednessMap = {
{ "double" , true },
{ "float" , true },
{ "int" , true },
{ "int32" , true },
{ "uint" , false },
{ "uint32" , false },
{ "short" , true },
{ "ushort" , false },
{ "char" , true },
{ "uchar" , false },
{ "uint8" , false }
};
/* Describes an arbitrary value of a PLY file */
union PLYValue
{
double d;
float f;
int i;
short s;
char c;
unsigned u;
unsigned short us;
unsigned char uc;
};
/*
Reads a single value from a binary input stream, reversing the storage
order if necessary.
*/
template <class T> void readValue( std::ifstream& stream,
std::size_t bytes,
bool littleEndian,
T* target )
{
if( !littleEndian || bytes == 1 )
stream.read( reinterpret_cast<char*>( target ), static_cast<std::streamsize>( bytes ) );
else
{
char* buffer = new char[bytes];
char* reversedBuffer = new char[bytes];
stream.read( buffer, static_cast<std::streamsize>( bytes ) );
for( std::size_t i = 0; i < bytes; i++ )
reversedBuffer[i] = buffer[ bytes - 1 - i ];
std::copy( reversedBuffer, reversedBuffer + bytes, target );
// FIXME: Superfluous?
#if 0
memcpy( reinterpret_cast<void*>( &target ),
reinterpret_cast<void*>( reversedBuffer ),
bytes );
#endif
delete[] reversedBuffer;
delete[] buffer;
}
}
} // namespace detail
/**
@class PLYReader
@brief Parses PLY files
This is a simple reader class for files in PLY format. It supports
reading PLY files with an arbitrary number of vertex properties. A
user may specify which property to use in order to assign the data
stored for each simplex.
*/
class PLYReader
{
public:
// Contains all descriptors for a single PLY property. The number of
// elements is somewhat superfluous when parsing ASCII files.
struct PropertyDescriptor
{
std::string name; // Property name (or list name)
unsigned index; // Offset of attribute for ASCII data
unsigned bytesOffset; // Offset of attribute for binary data
unsigned bytes; // Number of bytes
// Only used for lists: Here, both the length parameter and the
// entry parameter of a list usually have different lengths.
unsigned bytesListSize;
unsigned bytesListEntry;
};
template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K )
{
std::ifstream in( filename );
if( !in )
throw std::runtime_error( "Unable to read input file" );
this->operator()( in, K );
}
template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K )
{
// Header ------------------------------------------------------------
//
// The header needs to consist of the word "ply", followed by a "format"
// description.
std::size_t numVertices = 0; // Number of edges
std::size_t vertexSizeInBytes = 0; // Only relevant for binary files
std::size_t numFaces = 0; // Number of faces
std::size_t faceSizeInBytes = 0; // Only relevant for binary files
// Current line in file. This is required because I prefer reading the
// file line by line via `std::getline`.
std::string line;
bool headerParsed = false;
bool parseBinary = false;
bool littleEndian = false;
std::getline( in, line );
line = utilities::trim( line );
if( line != "ply" )
throw std::runtime_error( "Format error: Expecting \"ply\"" );
std::getline( in, line );
line = utilities::trim( line );
if( line.substr( 0, 6 ) != "format" )
throw std::runtime_error( "Format error: Expecting \"format\"" );
else
{
std::string format = line.substr( 6 );
format = utilities::trim( format );
if( format == "ascii 1.0" )
parseBinary = false;
else if( format == "binary_little_endian 1.0" )
{
parseBinary = true;
littleEndian = true;
}
else if( format == "binary_big_endian 1.0" )
{
parseBinary = true;
littleEndian = false;
}
else
throw std::runtime_error( "Format error: Expecting \"ascii 1.0\" or \"binary_little_endian 1.0\" or \"binary_big_endian 1.0\" " );
}
// All properties stored in the PLY file in the order in which they
// were discovered. The parse requires the existence of some of the
// properties, e.g. "x", "y", and "z" in order to work correctly.
std::vector<PropertyDescriptor> properties;
unsigned propertyIndex = 0; // Offset for properties in ASCII files
unsigned propertyOffset = 0; // Offset for properties in binary files
bool readingVertexProperties = false;
bool readingFaceProperties = false;
// Parse the rest of the header, taking care to skip any comment lines.
do
{
std::getline( in, line );
line = utilities::trim( line );
if( !in )
break;
if( line.substr( 0, 7 ) == "comment" )
continue;
else if( line.substr( 0, 7) == "element" )
{
std::string element = line.substr( 7 );
element = utilities::trim( element );
std::istringstream converter( element );
std::string name;
std::size_t numElements = 0;
converter >> name
>> numElements;
if( !converter )
throw std::runtime_error( "Element conversion error: Expecting number of elements" );
name = utilities::trim( name );
if( name == "vertex" )
{
numVertices = numElements;
readingVertexProperties = true;
}
else if( name == "face" )
{
numFaces = numElements;
readingFaceProperties = true;
}
}
else if( line.substr( 0, 8) == "property" )
{
std::string property = line.substr( 8 );
property = utilities::trim( property );
std::istringstream converter( property );
std::string dataType;
std::string name;
converter >> dataType
>> name;
dataType = utilities::trim( dataType );
name = utilities::trim( name );
PropertyDescriptor descriptor;
descriptor.index = propertyIndex;
// List of properties require a special handling. The syntax is
// "property list SIZE_TYPE ENTRY_TYPE NAME", e.g. "property
// list uint float vertex_height".
if( dataType == "list" )
{
std::string sizeType = name;
std::string entryType;
std::string listName;
converter >> entryType
>> listName;
utilities::trim( entryType );
utilities::trim( listName );
descriptor.bytesListSize = detail::TypeSizeMap.at( sizeType );
descriptor.bytesListEntry = detail::TypeSizeMap.at( entryType );
descriptor.name = listName;
}
else
{
descriptor.bytes = detail::TypeSizeMap.at( dataType );
descriptor.bytesOffset = propertyOffset;
descriptor.name = name;
}
if( !converter )
throw std::runtime_error( "Property conversion error: Expecting data type and name of property" );
if( readingFaceProperties )
faceSizeInBytes += descriptor.bytes;
else if( readingVertexProperties )
vertexSizeInBytes += descriptor.bytes;
propertyOffset += descriptor.bytes;
propertyIndex += 1;
properties.push_back( descriptor );
}
if( line == "end_header" )
{
headerParsed = true;
break;
}
}
while( !headerParsed && in );
assert( numVertices > 0 );
assert( numFaces > 0 );
using Simplex = typename SimplicialComplex::ValueType;
// Container for storing all simplices that are created while reading
// the mesh data structure.
std::vector<Simplex> simplices;
if( parseBinary )
{
simplices = this->parseBinary<Simplex>( in,
numVertices, numFaces,
littleEndian,
properties );
}
else
{
simplices = this->parseASCII<Simplex>( in,
numVertices, numFaces,
properties );
}
in.close();
K = SimplicialComplex( simplices.begin(), simplices.end() );
K.recalculateWeights();
K.sort( filtrations::Data<Simplex>() );
}
/* Sets the property to read for every simplex */
void setDataProperty( const std::string& property )
{
_property = property;
}
private:
template <class Simplex> std::vector<Simplex> parseBinary( std::ifstream& in,
std::size_t numVertices,
std::size_t numFaces,
bool littleEndian,
const std::vector<PropertyDescriptor>& properties )
{
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
// FIXME: this is just to placate the compiler
{
(void) numFaces;
VertexType v = VertexType();
(void) v;
DataType weight = DataType();
(void) weight;
}
for( std::size_t vertexIndex = 0; vertexIndex < numVertices; vertexIndex++ )
{
std::vector<double> coordinates;
for( auto&& descriptor : properties )
{
// Only faces may have lists for now...
if( descriptor.bytesListSize + descriptor.bytesListEntry != 0 )
continue;
detail::PLYValue pv;
switch( descriptor.bytes )
{
case 8:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.d );
break;
case 4:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.f );
break;
case 2:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.s );
break;
case 1:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.c );
break;
}
// FIXME: Not sure whether this is legal...
if( descriptor.name == "x" || descriptor.name == "y" || descriptor.name == "z" )
coordinates.push_back( pv.d );
}
}
for( std::size_t faceIndex = 0; faceIndex < numVertices; faceIndex++ )
{
}
return {};
}
template <class Simplex> std::vector<Simplex> parseASCII( std::ifstream& in,
std::size_t numVertices, std::size_t numFaces,
const std::vector<PropertyDescriptor>& properties )
{
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
std::vector<Simplex> simplices;
std::string line;
auto getPropertyIndex = [&properties] ( const std::string& property )
{
auto it = std::find_if( properties.begin(), properties.end(),
[&property] ( const PropertyDescriptor& descriptor )
{
return descriptor.name == property;
} );
if( it != properties.end() )
return it->index;
else
return std::numeric_limits<unsigned>::max();
};
// Read vertices -----------------------------------------------------
for( std::size_t vertexIndex = 0; vertexIndex < numVertices; vertexIndex++ )
{
std::vector<double> vertexCoordinates( 3 );
std::getline( in, line );
line = utilities::trim( line );
auto tokens = utilities::split( line );
auto ix = getPropertyIndex( "x" );
auto iy = getPropertyIndex( "y" );
auto iz = getPropertyIndex( "z" );
auto iw = getPropertyIndex( _property );
auto x = std::stod( tokens.at( ix ) );
auto y = std::stod( tokens.at( iy ) );
auto z = std::stod( tokens.at( iz ) );
_coordinates.push_back( {x,y,z} );
// No property for reading weights specified, or the specified
// property could not be found; just use the default weight of
// the simplex class.
if( _property.empty() || iw == std::numeric_limits<unsigned>::max() )
simplices.push_back( { VertexType( vertexIndex ) } );
else
{
DataType w = aleph::utilities::convert<DataType>( tokens.at(iw) );
simplices.push_back( Simplex( VertexType( vertexIndex ), w ) );
}
}
// Read faces --------------------------------------------------------
// Keep track of all edges that are encountered. This ensures that the
// simplicial complex is valid upon construction and does not have any
// missing simplices.
std::set< std::pair<VertexType, VertexType> > edges;
for( std::size_t faceIndex = 0; faceIndex < numFaces; faceIndex++ )
{
std::getline( in, line );
std::istringstream converter( line );
unsigned numEntries = 0;
converter >> numEntries;
if( !converter )
throw std::runtime_error( "Face conversion error: Expecting number of entries" );
// I can make a simplex out of a triangle, but every other shape would
// get complicated.
if( numEntries == 3 )
{
VertexType i1 = 0;
VertexType i2 = 0;
VertexType i3 = 0;
converter >> i1
>> i2
>> i3;
if( !converter )
throw std::runtime_error( "Unable to parse vertex indices" );
Simplex triangle( {i1,i2,i3} );
// Create edges ----------------------------------------------
for( auto itEdge = triangle.begin_boundary();
itEdge != triangle.end_boundary();
++itEdge )
{
// As the boundary iterator works as a filtered iterator only,
// I need this copy.
//
// Else, different calls to `begin()` and `end()` will result in
// two different copies of the simplex. The copies, in turn,
// will then not be usable as a source for vertices.
Simplex edge = *itEdge;
auto u = *( edge.begin() );
auto v = *( edge.begin() + 1 );
if( u < v )
std::swap( u, v );
auto pair = edges.insert( std::make_pair( u,v ) );
if( pair.second )
simplices.push_back( Simplex( edge.begin(), edge.end() ) );
}
simplices.push_back( triangle );
}
else
throw std::runtime_error( "Format error: Expecting triangular faces only" );
}
return simplices;
}
/** Data property to assign to new simplices */
std::string _property = "z";
/** Coordinates stored by the current run of the reader */
std::vector< std::vector<double> > _coordinates;
};
} // namespace io
} // namespace topology
} // namespace aleph
#endif
<commit_msg>Some cleaning up for `PLY` parser<commit_after>#ifndef ALEPH_TOPOLOGY_IO_PLY_HH__
#define ALEPH_TOPOLOGY_IO_PLY_HH__
#include <aleph/utilities/String.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/filtrations/Data.hh>
#include <cassert>
#include <fstream>
#include <limits>
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace aleph
{
namespace topology
{
namespace io
{
namespace detail
{
/*
Maps PLY data types to their corresponding sizes in bytes. This is
required for parsing binary files later on.
*/
std::map<std::string, unsigned short> TypeSizeMap = {
{ "double" , 8 },
{ "float" , 4 },
{ "int" , 4 },
{ "int32" , 4 },
{ "uint" , 4 },
{ "uint32" , 4 },
{ "short" , 2 },
{ "ushort" , 2 },
{ "char" , 1 },
{ "uchar" , 1 },
{ "uint8" , 1 }
};
/*
Maps PLY data types to their 'signedness'. This is required for
parsing binary files later on.
TODO: Use this to extend parser
*/
std::map<std::string, bool> TypeSignednessMap = {
{ "double" , true },
{ "float" , true },
{ "int" , true },
{ "int32" , true },
{ "uint" , false },
{ "uint32" , false },
{ "short" , true },
{ "ushort" , false },
{ "char" , true },
{ "uchar" , false },
{ "uint8" , false }
};
/* Describes an arbitrary value of a PLY file */
union PLYValue
{
double d;
float f;
int i;
short s;
char c;
unsigned u;
unsigned short us;
unsigned char uc;
};
/*
Reads a single value from a binary input stream, reversing the storage
order if necessary.
*/
template <class T> void readValue( std::ifstream& stream,
std::size_t bytes,
bool littleEndian,
T* target )
{
if( !littleEndian || bytes == 1 )
stream.read( reinterpret_cast<char*>( target ), static_cast<std::streamsize>( bytes ) );
else
{
char* buffer = new char[bytes];
char* reversedBuffer = new char[bytes];
stream.read( buffer, static_cast<std::streamsize>( bytes ) );
for( std::size_t i = 0; i < bytes; i++ )
reversedBuffer[i] = buffer[ bytes - 1 - i ];
std::copy( reversedBuffer, reversedBuffer + bytes, target );
delete[] reversedBuffer;
delete[] buffer;
}
}
} // namespace detail
/**
@class PLYReader
@brief Parses PLY files
This is a simple reader class for files in PLY format. It supports
reading PLY files with an arbitrary number of vertex properties. A
user may specify which property to use in order to assign the data
stored for each simplex.
*/
class PLYReader
{
public:
// Contains all descriptors for a single PLY property. The number of
// elements is somewhat superfluous when parsing ASCII files.
struct PropertyDescriptor
{
std::string name; // Property name (or list name)
unsigned index; // Offset of attribute for ASCII data
unsigned bytesOffset; // Offset of attribute for binary data
unsigned bytes; // Number of bytes
// Only used for lists: Here, both the length parameter and the
// entry parameter of a list usually have different lengths.
unsigned bytesListSize;
unsigned bytesListEntry;
};
template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K )
{
std::ifstream in( filename );
if( !in )
throw std::runtime_error( "Unable to read input file" );
this->operator()( in, K );
}
template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K )
{
// Header ------------------------------------------------------------
//
// The header needs to consist of the word "ply", followed by a "format"
// description.
std::size_t numVertices = 0; // Number of edges
std::size_t vertexSizeInBytes = 0; // Only relevant for binary files
std::size_t numFaces = 0; // Number of faces
std::size_t faceSizeInBytes = 0; // Only relevant for binary files
// Current line in file. This is required because I prefer reading the
// file line by line via `std::getline`.
std::string line;
bool headerParsed = false;
bool parseBinary = false;
bool littleEndian = false;
std::getline( in, line );
line = utilities::trim( line );
if( line != "ply" )
throw std::runtime_error( "Format error: Expecting \"ply\"" );
std::getline( in, line );
line = utilities::trim( line );
if( line.substr( 0, 6 ) != "format" )
throw std::runtime_error( "Format error: Expecting \"format\"" );
else
{
std::string format = line.substr( 6 );
format = utilities::trim( format );
if( format == "ascii 1.0" )
parseBinary = false;
else if( format == "binary_little_endian 1.0" )
{
parseBinary = true;
littleEndian = true;
}
else if( format == "binary_big_endian 1.0" )
{
parseBinary = true;
littleEndian = false;
}
else
throw std::runtime_error( "Format error: Expecting \"ascii 1.0\" or \"binary_little_endian 1.0\" or \"binary_big_endian 1.0\" " );
}
// All properties stored in the PLY file in the order in which they
// were discovered. The parse requires the existence of some of the
// properties, e.g. "x", "y", and "z" in order to work correctly.
std::vector<PropertyDescriptor> properties;
unsigned propertyIndex = 0; // Offset for properties in ASCII files
unsigned propertyOffset = 0; // Offset for properties in binary files
bool readingVertexProperties = false;
bool readingFaceProperties = false;
// Parse the rest of the header, taking care to skip any comment lines.
do
{
std::getline( in, line );
line = utilities::trim( line );
if( !in )
break;
if( line.substr( 0, 7 ) == "comment" )
continue;
else if( line.substr( 0, 7) == "element" )
{
std::string element = line.substr( 7 );
element = utilities::trim( element );
std::istringstream converter( element );
std::string name;
std::size_t numElements = 0;
converter >> name
>> numElements;
if( !converter )
throw std::runtime_error( "Element conversion error: Expecting number of elements" );
name = utilities::trim( name );
if( name == "vertex" )
{
numVertices = numElements;
readingVertexProperties = true;
}
else if( name == "face" )
{
numFaces = numElements;
readingFaceProperties = true;
}
}
else if( line.substr( 0, 8) == "property" )
{
std::string property = line.substr( 8 );
property = utilities::trim( property );
std::istringstream converter( property );
std::string dataType;
std::string name;
converter >> dataType
>> name;
dataType = utilities::trim( dataType );
name = utilities::trim( name );
PropertyDescriptor descriptor;
descriptor.index = propertyIndex;
// List of properties require a special handling. The syntax is
// "property list SIZE_TYPE ENTRY_TYPE NAME", e.g. "property
// list uint float vertex_height".
if( dataType == "list" )
{
std::string sizeType = name;
std::string entryType;
std::string listName;
converter >> entryType
>> listName;
utilities::trim( entryType );
utilities::trim( listName );
descriptor.bytesListSize = detail::TypeSizeMap.at( sizeType );
descriptor.bytesListEntry = detail::TypeSizeMap.at( entryType );
descriptor.name = listName;
}
else
{
descriptor.bytes = detail::TypeSizeMap.at( dataType );
descriptor.bytesOffset = propertyOffset;
descriptor.name = name;
}
if( !converter )
throw std::runtime_error( "Property conversion error: Expecting data type and name of property" );
if( readingFaceProperties )
faceSizeInBytes += descriptor.bytes;
else if( readingVertexProperties )
vertexSizeInBytes += descriptor.bytes;
propertyOffset += descriptor.bytes;
propertyIndex += 1;
properties.push_back( descriptor );
}
if( line == "end_header" )
{
headerParsed = true;
break;
}
}
while( !headerParsed && in );
assert( numVertices > 0 );
assert( numFaces > 0 );
using Simplex = typename SimplicialComplex::ValueType;
// Container for storing all simplices that are created while reading
// the mesh data structure.
std::vector<Simplex> simplices;
if( parseBinary )
{
simplices = this->parseBinary<Simplex>( in,
numVertices, numFaces,
littleEndian,
properties );
}
else
{
simplices = this->parseASCII<Simplex>( in,
numVertices, numFaces,
properties );
}
in.close();
K = SimplicialComplex( simplices.begin(), simplices.end() );
K.recalculateWeights();
K.sort( filtrations::Data<Simplex>() );
}
/* Sets the property to read for every simplex */
void setDataProperty( const std::string& property )
{
_property = property;
}
private:
template <class Simplex> std::vector<Simplex> parseBinary( std::ifstream& in,
std::size_t numVertices,
std::size_t numFaces,
bool littleEndian,
const std::vector<PropertyDescriptor>& properties )
{
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
// FIXME: this is just to placate the compiler
{
(void) numFaces;
VertexType v = VertexType();
(void) v;
DataType weight = DataType();
(void) weight;
}
for( std::size_t vertexIndex = 0; vertexIndex < numVertices; vertexIndex++ )
{
std::vector<double> coordinates;
for( auto&& descriptor : properties )
{
// Only faces may have lists for now...
if( descriptor.bytesListSize + descriptor.bytesListEntry != 0 )
continue;
detail::PLYValue pv;
switch( descriptor.bytes )
{
case 8:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.d );
break;
case 4:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.f );
break;
case 2:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.s );
break;
case 1:
detail::readValue( in, descriptor.bytes, littleEndian, &pv.c );
break;
}
// FIXME: Not sure whether this is legal...
if( descriptor.name == "x" || descriptor.name == "y" || descriptor.name == "z" )
coordinates.push_back( pv.d );
}
}
for( std::size_t faceIndex = 0; faceIndex < numVertices; faceIndex++ )
{
}
return {};
}
template <class Simplex> std::vector<Simplex> parseASCII( std::ifstream& in,
std::size_t numVertices, std::size_t numFaces,
const std::vector<PropertyDescriptor>& properties )
{
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
std::vector<Simplex> simplices;
std::string line;
auto getPropertyIndex = [&properties] ( const std::string& property )
{
auto it = std::find_if( properties.begin(), properties.end(),
[&property] ( const PropertyDescriptor& descriptor )
{
return descriptor.name == property;
} );
if( it != properties.end() )
return it->index;
else
return std::numeric_limits<unsigned>::max();
};
// Read vertices -----------------------------------------------------
for( std::size_t vertexIndex = 0; vertexIndex < numVertices; vertexIndex++ )
{
std::vector<double> vertexCoordinates( 3 );
std::getline( in, line );
line = utilities::trim( line );
auto tokens = utilities::split( line );
auto ix = getPropertyIndex( "x" );
auto iy = getPropertyIndex( "y" );
auto iz = getPropertyIndex( "z" );
auto iw = getPropertyIndex( _property );
auto x = std::stod( tokens.at( ix ) );
auto y = std::stod( tokens.at( iy ) );
auto z = std::stod( tokens.at( iz ) );
_coordinates.push_back( {x,y,z} );
// No property for reading weights specified, or the specified
// property could not be found; just use the default weight of
// the simplex class.
if( _property.empty() || iw == std::numeric_limits<unsigned>::max() )
simplices.push_back( { VertexType( vertexIndex ) } );
else
{
DataType w = aleph::utilities::convert<DataType>( tokens.at(iw) );
simplices.push_back( Simplex( VertexType( vertexIndex ), w ) );
}
}
// Read faces --------------------------------------------------------
// Keep track of all edges that are encountered. This ensures that the
// simplicial complex is valid upon construction and does not have any
// missing simplices.
std::set< std::pair<VertexType, VertexType> > edges;
for( std::size_t faceIndex = 0; faceIndex < numFaces; faceIndex++ )
{
std::getline( in, line );
std::istringstream converter( line );
unsigned numEntries = 0;
converter >> numEntries;
if( !converter )
throw std::runtime_error( "Face conversion error: Expecting number of entries" );
// I can make a simplex out of a triangle, but every other shape would
// get complicated.
if( numEntries == 3 )
{
VertexType i1 = 0;
VertexType i2 = 0;
VertexType i3 = 0;
converter >> i1
>> i2
>> i3;
if( !converter )
throw std::runtime_error( "Unable to parse vertex indices" );
Simplex triangle( {i1,i2,i3} );
// Create edges ----------------------------------------------
for( auto itEdge = triangle.begin_boundary();
itEdge != triangle.end_boundary();
++itEdge )
{
// As the boundary iterator works as a filtered iterator only,
// I need this copy.
//
// Else, different calls to `begin()` and `end()` will result in
// two different copies of the simplex. The copies, in turn,
// will then not be usable as a source for vertices.
Simplex edge = *itEdge;
auto u = *( edge.begin() );
auto v = *( edge.begin() + 1 );
if( u < v )
std::swap( u, v );
auto pair = edges.insert( std::make_pair( u,v ) );
if( pair.second )
simplices.push_back( Simplex( edge.begin(), edge.end() ) );
}
simplices.push_back( triangle );
}
else
throw std::runtime_error( "Format error: Expecting triangular faces only" );
}
return simplices;
}
/** Data property to assign to new simplices */
std::string _property = "z";
/** Coordinates stored by the current run of the reader */
std::vector< std::vector<double> > _coordinates;
};
} // namespace io
} // namespace topology
} // namespace aleph
#endif
<|endoftext|> |
<commit_before>/**
* \file
* \brief ContiguousRange template class header.
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par 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/.
*/
#ifndef ESTD_CONTIGUOUSRANGE_HPP_
#define ESTD_CONTIGUOUSRANGE_HPP_
#include <array>
namespace estd
{
/**
* \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory
*
* \tparam T is the type of data in the range
*/
template<typename T>
class ContiguousRange
{
public:
/// value_type type
using value_type = T;
/// pointer type
using pointer = value_type*;
/// const_pointer type
using const_pointer = const value_type*;
/// reference type
using reference = value_type&;
/// const_reference type
using const_reference = const value_type&;
/// iterator type
using iterator = value_type*;
/// const_iterator type
using const_iterator = const value_type*;
/// size_type type
using size_type = std::size_t;
/// difference_type type
using difference_type = std::ptrdiff_t;
/// reverse_iterator type
using reverse_iterator = std::reverse_iterator<iterator>;
/// const_reverse_iterator type
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
/**
* \brief ContiguousRange's constructor.
*
* \param [in] beginn is an iterator to first element in the range
* \param [in] endd is an iterator to "one past the last" element in the range
*/
constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept :
begin_{beginn},
end_{endd}
{
}
/**
* \brief Empty ContiguousRange's constructor.
*/
constexpr explicit ContiguousRange() noexcept :
ContiguousRange{nullptr, nullptr}
{
}
/**
* \brief ContiguousRange's constructor using C-style array.
*
* \tparam N is the number of elements in the array
*
* \param [in] array is the array used to initialize the range
*/
template<size_t N>
constexpr explicit ContiguousRange(T (& array)[N]) noexcept :
ContiguousRange{array, array + N}
{
}
/**
* \brief ContiguousRange's constructor using std::array.
*
* \tparam N is the number of elements in the array
*
* \param [in] array is the array used to initialize the range
*/
template<size_t N>
constexpr explicit ContiguousRange(std::array<T, N>& array) noexcept :
ContiguousRange{array.begin(), array.end()}
{
}
/**
* \brief ContiguousRange's constructor using const std::array.
*
* \tparam N is the number of elements in the array
*
* \param [in] array is the const array used to initialize the range
*/
template<size_t N>
constexpr explicit ContiguousRange(const std::array<typename std::remove_const<T>::type, N>& array) noexcept :
ContiguousRange{array.begin(), array.end()}
{
}
/**
* \brief ContiguousRange's constructor using single value
*
* \param [in] value is a reference to variable used to initialize the range
*/
constexpr explicit ContiguousRange(T& value) noexcept :
ContiguousRange{&value, &value + 1}
{
}
/**
* \brief ContiguousRange's copy constructor
*
* \param [in] other is a reference to source of copy
*/
constexpr explicit ContiguousRange(const ContiguousRange<typename std::remove_const<T>::type>& other) noexcept :
begin_{other.begin()},
end_{other.end()}
{
}
/**
* \return iterator to first element in the range
*/
constexpr iterator begin() const noexcept
{
return begin_;
}
/**
* \return const_iterator to first element in the range
*/
constexpr const_iterator cbegin() const noexcept
{
return begin();
}
/**
* \return const_iterator to "one past the last" element in the range
*/
constexpr const_iterator cend() const noexcept
{
return end();
}
/**
* \return iterator to "one past the last" element in the range
*/
constexpr iterator end() const noexcept
{
return end_;
}
/**
* \return number of elements in the range
*/
constexpr size_type size() const noexcept
{
return end_ - begin_;
}
/**
* \param [in] i is the index of element that will be accessed
*
* \return reference to element at given index
*/
reference operator[](const size_type i) const noexcept
{
return begin_[i];
}
private:
/// iterator to first element in the range
iterator begin_;
/// iterator to "one past the last" element in the range
iterator end_;
};
} // namespace estd
#endif // ESTD_CONTIGUOUSRANGE_HPP_
<commit_msg>Add ContiguousRange::rbegin()<commit_after>/**
* \file
* \brief ContiguousRange template class header.
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par 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/.
*/
#ifndef ESTD_CONTIGUOUSRANGE_HPP_
#define ESTD_CONTIGUOUSRANGE_HPP_
#include <array>
namespace estd
{
/**
* \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory
*
* \tparam T is the type of data in the range
*/
template<typename T>
class ContiguousRange
{
public:
/// value_type type
using value_type = T;
/// pointer type
using pointer = value_type*;
/// const_pointer type
using const_pointer = const value_type*;
/// reference type
using reference = value_type&;
/// const_reference type
using const_reference = const value_type&;
/// iterator type
using iterator = value_type*;
/// const_iterator type
using const_iterator = const value_type*;
/// size_type type
using size_type = std::size_t;
/// difference_type type
using difference_type = std::ptrdiff_t;
/// reverse_iterator type
using reverse_iterator = std::reverse_iterator<iterator>;
/// const_reverse_iterator type
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
/**
* \brief ContiguousRange's constructor.
*
* \param [in] beginn is an iterator to first element in the range
* \param [in] endd is an iterator to "one past the last" element in the range
*/
constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept :
begin_{beginn},
end_{endd}
{
}
/**
* \brief Empty ContiguousRange's constructor.
*/
constexpr explicit ContiguousRange() noexcept :
ContiguousRange{nullptr, nullptr}
{
}
/**
* \brief ContiguousRange's constructor using C-style array.
*
* \tparam N is the number of elements in the array
*
* \param [in] array is the array used to initialize the range
*/
template<size_t N>
constexpr explicit ContiguousRange(T (& array)[N]) noexcept :
ContiguousRange{array, array + N}
{
}
/**
* \brief ContiguousRange's constructor using std::array.
*
* \tparam N is the number of elements in the array
*
* \param [in] array is the array used to initialize the range
*/
template<size_t N>
constexpr explicit ContiguousRange(std::array<T, N>& array) noexcept :
ContiguousRange{array.begin(), array.end()}
{
}
/**
* \brief ContiguousRange's constructor using const std::array.
*
* \tparam N is the number of elements in the array
*
* \param [in] array is the const array used to initialize the range
*/
template<size_t N>
constexpr explicit ContiguousRange(const std::array<typename std::remove_const<T>::type, N>& array) noexcept :
ContiguousRange{array.begin(), array.end()}
{
}
/**
* \brief ContiguousRange's constructor using single value
*
* \param [in] value is a reference to variable used to initialize the range
*/
constexpr explicit ContiguousRange(T& value) noexcept :
ContiguousRange{&value, &value + 1}
{
}
/**
* \brief ContiguousRange's copy constructor
*
* \param [in] other is a reference to source of copy
*/
constexpr explicit ContiguousRange(const ContiguousRange<typename std::remove_const<T>::type>& other) noexcept :
begin_{other.begin()},
end_{other.end()}
{
}
/**
* \return iterator to first element in the range
*/
constexpr iterator begin() const noexcept
{
return begin_;
}
/**
* \return const_iterator to first element in the range
*/
constexpr const_iterator cbegin() const noexcept
{
return begin();
}
/**
* \return const_iterator to "one past the last" element in the range
*/
constexpr const_iterator cend() const noexcept
{
return end();
}
/**
* \return iterator to "one past the last" element in the range
*/
constexpr iterator end() const noexcept
{
return end_;
}
/**
* \return reverse_iterator to first element in the reversed range (last element of the non-reversed range)
*/
constexpr reverse_iterator rbegin() const noexcept
{
return reverse_iterator{end()};
}
/**
* \return number of elements in the range
*/
constexpr size_type size() const noexcept
{
return end_ - begin_;
}
/**
* \param [in] i is the index of element that will be accessed
*
* \return reference to element at given index
*/
reference operator[](const size_type i) const noexcept
{
return begin_[i];
}
private:
/// iterator to first element in the range
iterator begin_;
/// iterator to "one past the last" element in the range
iterator end_;
};
} // namespace estd
#endif // ESTD_CONTIGUOUSRANGE_HPP_
<|endoftext|> |
<commit_before>// Copyright (C) 2015 team-diana MIT license
#ifndef OCO_SDO_CLIENT_HPP
#define OCO_SDO_CLIENT_HPP
#include "hlcanopen/types.hpp"
#include "hlcanopen/sdo_error.hpp"
#include "hlcanopen/can_msg.hpp"
#include "hlcanopen/can_msg_utils.hpp"
#include "hlcanopen/utils.hpp"
#include <boost/coroutine/asymmetric_coroutine.hpp>
#include "hlcanopen/logging/easylogging++.h"
namespace hlcanopen {
enum class TransStatus {
NO_TRANS,
CONT,
END_OK,
END_ERR
};
enum {
SDO_TRANSMIT_COB_ID = 0b1011,
SDO_RECEIVE_COB_ID = 0b1100
};
template<class C> class SdoClient {
typedef boost::coroutines::asymmetric_coroutine<CanMsg> coroutine;
public:
SdoClient(NodeId nodeId, C& card) :
nodeId(nodeId),
card(card),
sdoCoroutine(nullptr),
currentTransStatus(TransStatus::NO_TRANS)
{
}
void readFromNode(SDOIndex sdoIndex) {
CanMsg readReq;
readReq.cobId = makeReqCobId();
setSdoClientCommandSpecifier(readReq, SdoClientCommandSpecifier::INITIATE_UPLOAD);
setSdoIndex(readReq, sdoIndex);
card.write(readReq);
startReadFromNodeCoroutine(sdoIndex);
}
void writeToNode(SDOIndex sdoIndex, const SdoData& data) {
if(data.size() <= 4)
writeToNodeExpedited(sdoIndex, data);
else
writeToNodeSegmented(sdoIndex, data);
}
void newMsg(CanMsg msg) {
BOOST_ASSERT_MSG(sdoCoroutine != nullptr, "coroutine was not started");
(*sdoCoroutine)(msg);
}
TransStatus getTransStatus() {
return currentTransStatus;
}
SdoError getSdoError() {
return currentSdoError;
}
std::vector<unsigned char> getResponseData() {
return receivedData;
}
void cleanForNextRequest() {
delete sdoCoroutine.release();
receivedData.clear();
currentTransStatus = TransStatus::NO_TRANS;
currentSdoError = SdoError();
}
bool transmissionIsEnded() {
return currentTransStatus == TransStatus::END_OK ||
currentTransStatus == TransStatus::END_ERR;
}
private:
void startReadFromNodeCoroutine(SDOIndex sdoIndex) {
currentTransStatus = TransStatus::CONT;
sdoCoroutine = std::make_unique<coroutine::push_type> (
[&, sdoIndex](coroutine::pull_type& in){
CanMsg startServerAns = in.get();
SdoData readData;
if(sdoExpeditedTransferIsSet(startServerAns)) {
unsigned int numberOfBytesSent = getSdoNumberOfBytesOfDataInMsg(startServerAns);
readData = getBytesAsData(startServerAns, 4, 4+numberOfBytesSent-1);
} else {
bool nextToggleBit = false;
while(true) {
CanMsg askNextSegmentMsg;
askNextSegmentMsg.cobId = makeReqCobId();
setSdoClientCommandSpecifier(askNextSegmentMsg, SdoClientCommandSpecifier::UPLOAD_SEGMENT);
setSdoIndex(askNextSegmentMsg, sdoIndex);
setSdoToggleBit(askNextSegmentMsg, nextToggleBit);
card.write(askNextSegmentMsg);
in();
CanMsg serverAns = in.get();
const unsigned int numberOfBytesSent =
getSdoNumberOfBytesOfDataInMsg(serverAns);
SdoData newData = getBytesAsData(serverAns, 1, numberOfBytesSent);
readData.insert(readData.end(), newData.begin(), newData.end());
nextToggleBit = !nextToggleBit;
if(sdoNoMoreSegmentBitIsSet(serverAns)) {
break;
}
}
}
currentTransStatus = TransStatus::END_OK;
receivedData = std::move(readData);
return;
}
);
}
void writeToNodeExpedited(const SDOIndex sdoIndex, const SdoData& data) {
CanMsg clientReq;
clientReq.cobId = makeReqCobId();
setSdoClientCommandSpecifier(clientReq, SdoClientCommandSpecifier::INITIATE_DOWNLOAD);
setSdoExpeditedTransfer(clientReq, true);
setSdoIndex(clientReq, sdoIndex);
setSdoNumberOfBytesOfDataInMsgSdoClient(clientReq, data.size(),
SdoClientCommandSpecifier::INITIATE_DOWNLOAD);
for(unsigned int i = 0; i < data.size(); i++) clientReq[4+i] = data[i];
card.write(clientReq);
startWriteToNodeExpeditedCoroutine(sdoIndex);
}
void startWriteToNodeExpeditedCoroutine(const SDOIndex ) {
currentTransStatus = TransStatus::CONT;
sdoCoroutine = std::make_unique<coroutine::push_type> (
[&](coroutine::pull_type& in){
// CanMsg ServerAns = in.get();
in.get();
// TODO: add check for confirm vs abort
currentTransStatus = TransStatus::END_OK;
}
);
}
void writeToNodeSegmented(const SDOIndex sdoIndex, const SdoData& data) {
CanMsg clientStartReq;
clientStartReq.cobId = makeReqCobId();
setSdoClientCommandSpecifier(clientStartReq, SdoClientCommandSpecifier::INITIATE_DOWNLOAD);
setSdoExpeditedTransfer(clientStartReq, false);
setSdoIndex(clientStartReq, sdoIndex);
setSdoSizeBit(clientStartReq, true);
setLast4Byte(clientStartReq, data.size());
card.write(clientStartReq);
startWriteToNodeSegmentedCoroutine(sdoIndex, data);
}
void startWriteToNodeSegmentedCoroutine(const SDOIndex sdoIndex, const SdoData& data) {
currentTransStatus = TransStatus::CONT;
sdoCoroutine = std::make_unique<coroutine::push_type> (
[&, sdoIndex, data](coroutine::pull_type& in){
bool completed = false;
bool nextToggleBit = false;
unsigned int currentByteToSend = 0;
while(true) {
CanMsg serverAns = in.get();
// TODO: add check for abort
SdoServerCommandSpecifier serverAnsComSpec = getSdoServerCommandSpecifier(serverAns);
if(serverAnsComSpec == SdoServerCommandSpecifier::ABORT_TRANSFER) {
LOG(ERROR) << "received sdo transfer abort";
currentTransStatus = TransStatus::END_ERR;
return;
}
if(!completed) {
CanMsg clientSegment;
clientSegment.cobId = makeReqCobId();
setSdoClientCommandSpecifier(clientSegment, SdoClientCommandSpecifier::DOWNLOAD_SEGMENT);
setSdoToggleBit(clientSegment, nextToggleBit);
nextToggleBit = !nextToggleBit;
int i = 0;
for(i = 0; i < 7 && currentByteToSend < data.size(); i++) {
clientSegment[1+i] = data[currentByteToSend++];
}
setSdoNumberOfBytesOfDataInMsgSdoClient(clientSegment, i, SdoClientCommandSpecifier::DOWNLOAD_SEGMENT);
if(currentByteToSend == data.size()) {
completed = true;
}
setSdoNoMoreSegmentBit(clientSegment, completed);
card.write(clientSegment);
in();
} else {
currentTransStatus = TransStatus::END_OK;
break;
}
}
}
);
}
bool isAbortMsg(CanMsg msg) {
if(msg[0] == 0x80) {
// error code in byte [4-7]
currentSdoError = SdoError(static_cast<SdoErrorCode>(msg.data & (uint32_t(-1))));
currentTransStatus = TransStatus::END_ERR;
return true;
} else return false;
}
COBId makeReqCobId() {
return COBId(nodeId, COBTypeUniqueCode::SDO_RECEIVE_UNIQUE_CODE);
}
private:
NodeId nodeId;
C& card;
std::unique_ptr<coroutine::push_type> sdoCoroutine;
SdoData receivedData;
TransStatus currentTransStatus;
SdoError currentSdoError;
};
}
#endif // OCO_SDO_CLIENT_HPP
<commit_msg>indicate size during sdo expedite<commit_after>// Copyright (C) 2015 team-diana MIT license
#ifndef OCO_SDO_CLIENT_HPP
#define OCO_SDO_CLIENT_HPP
#include "hlcanopen/types.hpp"
#include "hlcanopen/sdo_error.hpp"
#include "hlcanopen/can_msg.hpp"
#include "hlcanopen/can_msg_utils.hpp"
#include "hlcanopen/utils.hpp"
#include <boost/coroutine/asymmetric_coroutine.hpp>
#include "hlcanopen/logging/easylogging++.h"
namespace hlcanopen {
enum class TransStatus {
NO_TRANS,
CONT,
END_OK,
END_ERR
};
enum {
SDO_TRANSMIT_COB_ID = 0b1011,
SDO_RECEIVE_COB_ID = 0b1100
};
template<class C> class SdoClient {
typedef boost::coroutines::asymmetric_coroutine<CanMsg> coroutine;
public:
SdoClient(NodeId nodeId, C& card) :
nodeId(nodeId),
card(card),
sdoCoroutine(nullptr),
currentTransStatus(TransStatus::NO_TRANS)
{
}
void readFromNode(SDOIndex sdoIndex) {
CanMsg readReq;
readReq.cobId = makeReqCobId();
setSdoClientCommandSpecifier(readReq, SdoClientCommandSpecifier::INITIATE_UPLOAD);
setSdoIndex(readReq, sdoIndex);
card.write(readReq);
startReadFromNodeCoroutine(sdoIndex);
}
void writeToNode(SDOIndex sdoIndex, const SdoData& data) {
if(data.size() <= 4)
writeToNodeExpedited(sdoIndex, data);
else
writeToNodeSegmented(sdoIndex, data);
}
void newMsg(CanMsg msg) {
BOOST_ASSERT_MSG(sdoCoroutine != nullptr, "coroutine was not started");
(*sdoCoroutine)(msg);
}
TransStatus getTransStatus() {
return currentTransStatus;
}
SdoError getSdoError() {
return currentSdoError;
}
std::vector<unsigned char> getResponseData() {
return receivedData;
}
void cleanForNextRequest() {
delete sdoCoroutine.release();
receivedData.clear();
currentTransStatus = TransStatus::NO_TRANS;
currentSdoError = SdoError();
}
bool transmissionIsEnded() {
return currentTransStatus == TransStatus::END_OK ||
currentTransStatus == TransStatus::END_ERR;
}
private:
void startReadFromNodeCoroutine(SDOIndex sdoIndex) {
currentTransStatus = TransStatus::CONT;
sdoCoroutine = std::make_unique<coroutine::push_type> (
[&, sdoIndex](coroutine::pull_type& in){
CanMsg startServerAns = in.get();
SdoData readData;
if(sdoExpeditedTransferIsSet(startServerAns)) {
unsigned int numberOfBytesSent = getSdoNumberOfBytesOfDataInMsg(startServerAns);
readData = getBytesAsData(startServerAns, 4, 4+numberOfBytesSent-1);
} else {
bool nextToggleBit = false;
while(true) {
CanMsg askNextSegmentMsg;
askNextSegmentMsg.cobId = makeReqCobId();
setSdoClientCommandSpecifier(askNextSegmentMsg, SdoClientCommandSpecifier::UPLOAD_SEGMENT);
setSdoIndex(askNextSegmentMsg, sdoIndex);
setSdoToggleBit(askNextSegmentMsg, nextToggleBit);
card.write(askNextSegmentMsg);
in();
CanMsg serverAns = in.get();
const unsigned int numberOfBytesSent =
getSdoNumberOfBytesOfDataInMsg(serverAns);
SdoData newData = getBytesAsData(serverAns, 1, numberOfBytesSent);
readData.insert(readData.end(), newData.begin(), newData.end());
nextToggleBit = !nextToggleBit;
if(sdoNoMoreSegmentBitIsSet(serverAns)) {
break;
}
}
}
currentTransStatus = TransStatus::END_OK;
receivedData = std::move(readData);
return;
}
);
}
void writeToNodeExpedited(const SDOIndex sdoIndex, const SdoData& data) {
CanMsg clientReq;
clientReq.cobId = makeReqCobId();
setSdoClientCommandSpecifier(clientReq, SdoClientCommandSpecifier::INITIATE_DOWNLOAD);
setSdoExpeditedTransfer(clientReq, true);
setSdoIndex(clientReq, sdoIndex);
setSdoNumberOfBytesOfDataInMsgSdoClient(clientReq, data.size(),
SdoClientCommandSpecifier::INITIATE_DOWNLOAD);
setSdoSizeBit(clientReq, true);
for(unsigned int i = 0; i < data.size(); i++) clientReq[4+i] = data[i];
card.write(clientReq);
startWriteToNodeExpeditedCoroutine(sdoIndex);
}
void startWriteToNodeExpeditedCoroutine(const SDOIndex ) {
currentTransStatus = TransStatus::CONT;
sdoCoroutine = std::make_unique<coroutine::push_type> (
[&](coroutine::pull_type& in){
// CanMsg ServerAns = in.get();
in.get();
// TODO: add check for confirm vs abort
currentTransStatus = TransStatus::END_OK;
}
);
}
void writeToNodeSegmented(const SDOIndex sdoIndex, const SdoData& data) {
CanMsg clientStartReq;
clientStartReq.cobId = makeReqCobId();
setSdoClientCommandSpecifier(clientStartReq, SdoClientCommandSpecifier::INITIATE_DOWNLOAD);
setSdoExpeditedTransfer(clientStartReq, false);
setSdoIndex(clientStartReq, sdoIndex);
setSdoSizeBit(clientStartReq, true);
setLast4Byte(clientStartReq, data.size());
card.write(clientStartReq);
startWriteToNodeSegmentedCoroutine(sdoIndex, data);
}
void startWriteToNodeSegmentedCoroutine(const SDOIndex sdoIndex, const SdoData& data) {
currentTransStatus = TransStatus::CONT;
sdoCoroutine = std::make_unique<coroutine::push_type> (
[&, sdoIndex, data](coroutine::pull_type& in){
bool completed = false;
bool nextToggleBit = false;
unsigned int currentByteToSend = 0;
while(true) {
CanMsg serverAns = in.get();
// TODO: add check for abort
SdoServerCommandSpecifier serverAnsComSpec = getSdoServerCommandSpecifier(serverAns);
if(serverAnsComSpec == SdoServerCommandSpecifier::ABORT_TRANSFER) {
LOG(ERROR) << "received sdo transfer abort";
currentTransStatus = TransStatus::END_ERR;
return;
}
if(!completed) {
CanMsg clientSegment;
clientSegment.cobId = makeReqCobId();
setSdoClientCommandSpecifier(clientSegment, SdoClientCommandSpecifier::DOWNLOAD_SEGMENT);
setSdoToggleBit(clientSegment, nextToggleBit);
nextToggleBit = !nextToggleBit;
int i = 0;
for(i = 0; i < 7 && currentByteToSend < data.size(); i++) {
clientSegment[1+i] = data[currentByteToSend++];
}
setSdoNumberOfBytesOfDataInMsgSdoClient(clientSegment, i, SdoClientCommandSpecifier::DOWNLOAD_SEGMENT);
if(currentByteToSend == data.size()) {
completed = true;
}
setSdoNoMoreSegmentBit(clientSegment, completed);
card.write(clientSegment);
in();
} else {
currentTransStatus = TransStatus::END_OK;
break;
}
}
}
);
}
bool isAbortMsg(CanMsg msg) {
if(msg[0] == 0x80) {
// error code in byte [4-7]
currentSdoError = SdoError(static_cast<SdoErrorCode>(msg.data & (uint32_t(-1))));
currentTransStatus = TransStatus::END_ERR;
return true;
} else return false;
}
COBId makeReqCobId() {
return COBId(nodeId, COBTypeUniqueCode::SDO_RECEIVE_UNIQUE_CODE);
}
private:
NodeId nodeId;
C& card;
std::unique_ptr<coroutine::push_type> sdoCoroutine;
SdoData receivedData;
TransStatus currentTransStatus;
SdoError currentSdoError;
};
}
#endif // OCO_SDO_CLIENT_HPP
<|endoftext|> |
<commit_before>// -----------------------------------------------------------------
// libpion: a C++ framework for building lightweight HTTP interfaces
// -----------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_HTTPRESPONSE_HEADER__
#define __PION_HTTPRESPONSE_HEADER__
#include <libpion/PionConfig.hpp>
#include <libpion/PionLogger.hpp>
#include <libpion/TCPConnection.hpp>
#include <libpion/HTTPTypes.hpp>
#include <boost/asio.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/noncopyable.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <vector>
#include <string>
namespace pion { // begin namespace pion
///
/// HTTPResponse: container for HTTP response information
///
class HTTPResponse :
public boost::enable_shared_from_this<HTTPResponse>,
private boost::noncopyable
{
public:
/// creates new HTTPResponse objects
static inline boost::shared_ptr<HTTPResponse> create(void) {
return boost::shared_ptr<HTTPResponse>(new HTTPResponse);
}
/// default destructor
virtual ~HTTPResponse() {}
/**
* write text (non-binary) response content
*
* @param data the data to append to the response content
*/
template <typename T>
inline void write(const T& data) {
m_content_stream << data;
if (m_stream_is_empty) m_stream_is_empty = false;
}
/**
* write binary response content
*
* @param data points to the binary data to append to the response content
* @param length the length, in bytes, of the binary data
*/
inline void write(const void *data, size_t length) {
if (length != 0) {
flushContentStream();
m_content_buffers.push_back(m_binary_cache.add(data, length));
m_content_length += length;
}
}
/**
* write text (non-binary) response content; the data written is not copied,
* and therefore must persist until the response has finished sending
*
* @param data the data to append to the response content
*/
template <typename T>
inline void writeNoCopy(const T& data) {
std::string as_string(boost::lexical_cast<std::string>(data));
if (! as_string.empty()) {
flushContentStream();
m_content_buffers.push_back(boost::asio::buffer(as_string));
m_content_length += as_string.size();
}
}
/**
* write text (non-binary) response content; the data written is not
* copied, and therefore must persist until the response has finished
* sending; this specialization avoids lexical_cast for strings
*
* @param data the data to append to the response content
*/
inline void writeNoCopy(const std::string& data) {
if (! data.empty()) {
flushContentStream();
m_content_buffers.push_back(boost::asio::buffer(data));
m_content_length += data.size();
}
}
/**
* write binary response content; the data written is not copied, and
* therefore must persist until the response has finished sending
*
* @param data points to the binary data to append to the response content
* @param length the length, in bytes, of the binary data
*/
inline void writeNoCopy(void *data, size_t length) {
if (length > 0) {
flushContentStream();
m_content_buffers.push_back(boost::asio::buffer(data, length));
m_content_length += length;
}
}
/// adds an HTTP response header
inline void addHeader(const std::string& key, const std::string& value) {
m_response_headers.insert(std::make_pair(key, value));
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
* the cookie will be discarded by the user-agent when it closes
*
* @param name the name of the cookie
* @param value the value of the cookie
*/
inline void setCookie(const std::string& name, const std::string& value) {
std::string set_cookie_header(makeSetCookieHeader(name, value, ""));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
* the cookie will be discarded by the user-agent when it closes
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
*/
inline void setCookie(const std::string& name, const std::string& value,
const std::string& path)
{
std::string set_cookie_header(makeSetCookieHeader(name, value, path));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param max_age the life of the cookie, in seconds (0 = discard)
*/
inline void setCookie(const std::string& name, const std::string& value,
const std::string& path, const unsigned long max_age)
{
std::string set_cookie_header(makeSetCookieHeader(name, value, path, true, max_age));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param max_age the life of the cookie, in seconds (0 = discard)
*/
inline void setCookie(const std::string& name, const std::string& value,
const unsigned long max_age)
{
std::string set_cookie_header(makeSetCookieHeader(name, value, "", true, max_age));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/// deletes cookie called name by adding a Set-Cookie header (cookie has no path)
inline void deleteCookie(const std::string& name) {
std::string set_cookie_header(makeSetCookieHeader(name, "", "", true, 0));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/// deletes cookie called name by adding a Set-Cookie header (cookie has a path)
inline void deleteCookie(const std::string& name, const std::string& path) {
std::string set_cookie_header(makeSetCookieHeader(name, "", path, true, 0));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/// sets the response or status code to send
inline void setResponseCode(const unsigned int n) {
// add space character to beginning and end
m_response_code = ' ';
m_response_code += boost::lexical_cast<std::string>(n);
m_response_code += ' ';
}
/// sets the time that the response was last modified (Last-Modified)
inline void setLastModified(const unsigned long t) {
addHeader(HTTPTypes::HEADER_LAST_MODIFIED, HTTPTypes::get_date_string(t));
}
/// sets the response or status message to send
inline void setResponseMessage(const std::string& m) { m_response_message = m; }
/// sets the type of response content to be sent (Content-Type)
inline void setContentType(const std::string& t) { m_content_type = t; }
/// sets the logger to be used
inline void setLogger(PionLogger log_ptr) { m_logger = log_ptr; }
/// returns the logger currently in use
inline PionLogger getLogger(void) { return m_logger; }
/**
* sends the response
*
* @param tcp_conn TCP connection used to send the response
*/
void send(TCPConnectionPtr& tcp_conn);
protected:
/// protected constructor restricts creation of objects (use create())
HTTPResponse(void)
: m_logger(PION_GET_LOGGER("Pion.HTTPResponse")),
m_stream_is_empty(true),
m_response_message(HTTPTypes::RESPONSE_MESSAGE_OK),
m_content_type(HTTPTypes::CONTENT_TYPE_HTML),
m_content_length(0)
{
setResponseCode(HTTPTypes::RESPONSE_CODE_OK);
}
/**
* creates a "Set-Cookie" header
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param has_max_age true if the max_age value should be set
* @param max_age the life of the cookie, in seconds (0 = discard)
*
* @return the new "Set-Cookie" header
*/
std::string makeSetCookieHeader(const std::string& name, const std::string& value,
const std::string& path, const bool has_max_age = false,
const unsigned long max_age = 0);
private:
/**
* called after the response is sent
*
* @param tcp_conn TCP connection used to send the response
* @param write_error error status from the last write operation
* @param bytes_written number of bytes sent by the last write operation
* @param pipelined true if there are pipelined HTTP requests pending
*/
void handleWrite(TCPConnectionPtr tcp_conn,
const boost::system::error_code& write_error,
std::size_t bytes_written, const bool pipelined);
/// flushes any text data in the content stream after caching it in the TextCache
inline void flushContentStream(void) {
if (! m_stream_is_empty) {
std::string string_to_add(m_content_stream.str());
if (! string_to_add.empty()) {
m_content_stream.str("");
m_content_length += string_to_add.size();
m_text_cache.push_back(string_to_add);
m_content_buffers.push_back(boost::asio::buffer(m_text_cache.back()));
}
m_stream_is_empty = true;
}
}
/// used to cache binary data included within the response
class BinaryCache : public std::vector<std::pair<const char *, size_t> > {
public:
~BinaryCache() {
for (iterator i=begin(); i!=end(); ++i) {
delete[] i->first;
}
}
inline boost::asio::const_buffer add(const void *ptr, const size_t size) {
char *data_ptr = new char[size];
memcpy(data_ptr, ptr, size);
push_back( std::make_pair(data_ptr, size) );
return boost::asio::buffer(data_ptr, size);
}
};
/// used to cache text (non-binary) data included within the response
typedef std::vector<std::string> TextCache;
/// data type for I/O write buffers (these wrap existing data to be sent)
typedef std::vector<boost::asio::const_buffer> WriteBuffers;
/// primary logging interface used by this class
PionLogger m_logger;
/// I/O write buffers that wrap the response content to be written
WriteBuffers m_content_buffers;
/// caches binary data included within the response
BinaryCache m_binary_cache;
/// caches text (non-binary) data included within the response
TextCache m_text_cache;
/// incrementally creates strings of text data for the TextCache
std::ostringstream m_content_stream;
/// true if the content_stream is empty (avoids unnecessary string copies)
bool m_stream_is_empty;
/// The HTTP response headers to send
HTTPTypes::StringDictionary m_response_headers;
/// The HTTP response or status code to send (as a string wrapped with spaces)
std::string m_response_code;
/// The HTTP response or status message to send
std::string m_response_message;
/// The type of response content to be sent (Content-Type)
std::string m_content_type;
/// The length (in bytes) of the response content to be sent (Content-Length)
unsigned long m_content_length;
};
/// data type for a HTTPResponse pointer
typedef boost::shared_ptr<HTTPResponse> HTTPResponsePtr;
/// override operator<< for convenience
template <typename T>
HTTPResponsePtr& operator<<(HTTPResponsePtr& response, const T& data) {
response->write(data);
return response;
}
} // end namespace pion
#endif
<commit_msg>Removed writeNoCopy(const T& data) function since only strings make sense with writeNoCopy()<commit_after>// -----------------------------------------------------------------
// libpion: a C++ framework for building lightweight HTTP interfaces
// -----------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_HTTPRESPONSE_HEADER__
#define __PION_HTTPRESPONSE_HEADER__
#include <libpion/PionConfig.hpp>
#include <libpion/PionLogger.hpp>
#include <libpion/TCPConnection.hpp>
#include <libpion/HTTPTypes.hpp>
#include <boost/asio.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/noncopyable.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <vector>
#include <string>
namespace pion { // begin namespace pion
///
/// HTTPResponse: container for HTTP response information
///
class HTTPResponse :
public boost::enable_shared_from_this<HTTPResponse>,
private boost::noncopyable
{
public:
/// creates new HTTPResponse objects
static inline boost::shared_ptr<HTTPResponse> create(void) {
return boost::shared_ptr<HTTPResponse>(new HTTPResponse);
}
/// default destructor
virtual ~HTTPResponse() {}
/**
* write text (non-binary) response content
*
* @param data the data to append to the response content
*/
template <typename T>
inline void write(const T& data) {
m_content_stream << data;
if (m_stream_is_empty) m_stream_is_empty = false;
}
/**
* write binary response content
*
* @param data points to the binary data to append to the response content
* @param length the length, in bytes, of the binary data
*/
inline void write(const void *data, size_t length) {
if (length != 0) {
flushContentStream();
m_content_buffers.push_back(m_binary_cache.add(data, length));
m_content_length += length;
}
}
/**
* write text (non-binary) response content; the data written is not
* copied, and therefore must persist until the response has finished
* sending; this specialization avoids lexical_cast for strings
*
* @param data the data to append to the response content
*/
inline void writeNoCopy(const std::string& data) {
if (! data.empty()) {
flushContentStream();
m_content_buffers.push_back(boost::asio::buffer(data));
m_content_length += data.size();
}
}
/**
* write binary response content; the data written is not copied, and
* therefore must persist until the response has finished sending
*
* @param data points to the binary data to append to the response content
* @param length the length, in bytes, of the binary data
*/
inline void writeNoCopy(void *data, size_t length) {
if (length > 0) {
flushContentStream();
m_content_buffers.push_back(boost::asio::buffer(data, length));
m_content_length += length;
}
}
/// adds an HTTP response header
inline void addHeader(const std::string& key, const std::string& value) {
m_response_headers.insert(std::make_pair(key, value));
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
* the cookie will be discarded by the user-agent when it closes
*
* @param name the name of the cookie
* @param value the value of the cookie
*/
inline void setCookie(const std::string& name, const std::string& value) {
std::string set_cookie_header(makeSetCookieHeader(name, value, ""));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
* the cookie will be discarded by the user-agent when it closes
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
*/
inline void setCookie(const std::string& name, const std::string& value,
const std::string& path)
{
std::string set_cookie_header(makeSetCookieHeader(name, value, path));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param max_age the life of the cookie, in seconds (0 = discard)
*/
inline void setCookie(const std::string& name, const std::string& value,
const std::string& path, const unsigned long max_age)
{
std::string set_cookie_header(makeSetCookieHeader(name, value, path, true, max_age));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/**
* sets a cookie by adding a Set-Cookie header (see RFC 2109)
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param max_age the life of the cookie, in seconds (0 = discard)
*/
inline void setCookie(const std::string& name, const std::string& value,
const unsigned long max_age)
{
std::string set_cookie_header(makeSetCookieHeader(name, value, "", true, max_age));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/// deletes cookie called name by adding a Set-Cookie header (cookie has no path)
inline void deleteCookie(const std::string& name) {
std::string set_cookie_header(makeSetCookieHeader(name, "", "", true, 0));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/// deletes cookie called name by adding a Set-Cookie header (cookie has a path)
inline void deleteCookie(const std::string& name, const std::string& path) {
std::string set_cookie_header(makeSetCookieHeader(name, "", path, true, 0));
addHeader(HTTPTypes::HEADER_SET_COOKIE, set_cookie_header);
}
/// sets the response or status code to send
inline void setResponseCode(const unsigned int n) {
// add space character to beginning and end
m_response_code = ' ';
m_response_code += boost::lexical_cast<std::string>(n);
m_response_code += ' ';
}
/// sets the time that the response was last modified (Last-Modified)
inline void setLastModified(const unsigned long t) {
addHeader(HTTPTypes::HEADER_LAST_MODIFIED, HTTPTypes::get_date_string(t));
}
/// sets the response or status message to send
inline void setResponseMessage(const std::string& m) { m_response_message = m; }
/// sets the type of response content to be sent (Content-Type)
inline void setContentType(const std::string& t) { m_content_type = t; }
/// sets the logger to be used
inline void setLogger(PionLogger log_ptr) { m_logger = log_ptr; }
/// returns the logger currently in use
inline PionLogger getLogger(void) { return m_logger; }
/**
* sends the response
*
* @param tcp_conn TCP connection used to send the response
*/
void send(TCPConnectionPtr& tcp_conn);
protected:
/// protected constructor restricts creation of objects (use create())
HTTPResponse(void)
: m_logger(PION_GET_LOGGER("Pion.HTTPResponse")),
m_stream_is_empty(true),
m_response_message(HTTPTypes::RESPONSE_MESSAGE_OK),
m_content_type(HTTPTypes::CONTENT_TYPE_HTML),
m_content_length(0)
{
setResponseCode(HTTPTypes::RESPONSE_CODE_OK);
}
/**
* creates a "Set-Cookie" header
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param has_max_age true if the max_age value should be set
* @param max_age the life of the cookie, in seconds (0 = discard)
*
* @return the new "Set-Cookie" header
*/
std::string makeSetCookieHeader(const std::string& name, const std::string& value,
const std::string& path, const bool has_max_age = false,
const unsigned long max_age = 0);
private:
/**
* called after the response is sent
*
* @param tcp_conn TCP connection used to send the response
* @param write_error error status from the last write operation
* @param bytes_written number of bytes sent by the last write operation
* @param pipelined true if there are pipelined HTTP requests pending
*/
void handleWrite(TCPConnectionPtr tcp_conn,
const boost::system::error_code& write_error,
std::size_t bytes_written, const bool pipelined);
/// flushes any text data in the content stream after caching it in the TextCache
inline void flushContentStream(void) {
if (! m_stream_is_empty) {
std::string string_to_add(m_content_stream.str());
if (! string_to_add.empty()) {
m_content_stream.str("");
m_content_length += string_to_add.size();
m_text_cache.push_back(string_to_add);
m_content_buffers.push_back(boost::asio::buffer(m_text_cache.back()));
}
m_stream_is_empty = true;
}
}
/// used to cache binary data included within the response
class BinaryCache : public std::vector<std::pair<const char *, size_t> > {
public:
~BinaryCache() {
for (iterator i=begin(); i!=end(); ++i) {
delete[] i->first;
}
}
inline boost::asio::const_buffer add(const void *ptr, const size_t size) {
char *data_ptr = new char[size];
memcpy(data_ptr, ptr, size);
push_back( std::make_pair(data_ptr, size) );
return boost::asio::buffer(data_ptr, size);
}
};
/// used to cache text (non-binary) data included within the response
typedef std::vector<std::string> TextCache;
/// data type for I/O write buffers (these wrap existing data to be sent)
typedef std::vector<boost::asio::const_buffer> WriteBuffers;
/// primary logging interface used by this class
PionLogger m_logger;
/// I/O write buffers that wrap the response content to be written
WriteBuffers m_content_buffers;
/// caches binary data included within the response
BinaryCache m_binary_cache;
/// caches text (non-binary) data included within the response
TextCache m_text_cache;
/// incrementally creates strings of text data for the TextCache
std::ostringstream m_content_stream;
/// true if the content_stream is empty (avoids unnecessary string copies)
bool m_stream_is_empty;
/// The HTTP response headers to send
HTTPTypes::StringDictionary m_response_headers;
/// The HTTP response or status code to send (as a string wrapped with spaces)
std::string m_response_code;
/// The HTTP response or status message to send
std::string m_response_message;
/// The type of response content to be sent (Content-Type)
std::string m_content_type;
/// The length (in bytes) of the response content to be sent (Content-Length)
unsigned long m_content_length;
};
/// data type for a HTTPResponse pointer
typedef boost::shared_ptr<HTTPResponse> HTTPResponsePtr;
/// override operator<< for convenience
template <typename T>
HTTPResponsePtr& operator<<(HTTPResponsePtr& response, const T& data) {
response->write(data);
return response;
}
} // end namespace pion
#endif
<|endoftext|> |
<commit_before>#pragma once
#include "common.hpp"
#include "modules/backlight.hpp"
#include "modules/battery.hpp"
#include "modules/bspwm.hpp"
#include "modules/counter.hpp"
#include "modules/cpu.hpp"
#include "modules/date.hpp"
#include "modules/fs.hpp"
#include "modules/ipc.hpp"
#include "modules/memory.hpp"
#include "modules/menu.hpp"
#include "modules/meta/base.hpp"
#include "modules/script.hpp"
#if DEBUG
#include "modules/systray.hpp"
#endif
#include "modules/temperature.hpp"
#include "modules/text.hpp"
#include "modules/xbacklight.hpp"
#include "modules/xwindow.hpp"
#include "modules/xworkspaces.hpp"
#if ENABLE_I3
#include "modules/i3.hpp"
#endif
#if ENABLE_MPD
#include "modules/mpd.hpp"
#endif
#if ENABLE_NETWORK
#include "modules/network.hpp"
#endif
#if ENABLE_ALSA
#include "modules/alsa.hpp"
#endif
#if ENABLE_PULSEAUDIO
#include "modules/pulseaudio.hpp"
#endif
#if ENABLE_CURL
#include "modules/github.hpp"
#endif
#if ENABLE_XKEYBOARD
#include "modules/xkeyboard.hpp"
#endif
#if not(ENABLE_I3 && ENABLE_MPD && ENABLE_NETWORK && ENABLE_ALSA && ENABLE_PULSEAUDIO && ENABLE_CURL && ENABLE_XKEYBOARD)
#include "modules/unsupported.hpp"
#endif
POLYBAR_NS
using namespace modules;
namespace {
module_interface* make_module(string&& name, const bar_settings& bar, string module_name, const logger& m_log) {
if (name == "internal/counter") {
return new counter_module(bar, move(module_name));
} else if (name == "internal/backlight") {
return new backlight_module(bar, move(module_name));
} else if (name == "internal/battery") {
return new battery_module(bar, move(module_name));
} else if (name == "internal/bspwm") {
return new bspwm_module(bar, move(module_name));
} else if (name == "internal/cpu") {
return new cpu_module(bar, move(module_name));
} else if (name == "internal/date") {
return new date_module(bar, move(module_name));
} else if (name == "internal/github") {
return new github_module(bar, move(module_name));
} else if (name == "internal/fs") {
return new fs_module(bar, move(module_name));
} else if (name == "internal/memory") {
return new memory_module(bar, move(module_name));
} else if (name == "internal/i3") {
return new i3_module(bar, move(module_name));
} else if (name == "internal/mpd") {
return new mpd_module(bar, move(module_name));
} else if (name == "internal/volume") {
m_log.warn("internal/volume is deprecated, use internal/alsa instead");
return new alsa_module(bar, move(name));
} else if (name == "internal/alsa") {
return new alsa_module(bar, move(module_name));
} else if (name == "internal/pulseaudio") {
return new pulseaudio_module(bar, move(module_name));
} else if (name == "internal/network") {
return new network_module(bar, move(module_name));
#if DEBUG
} else if (name == "internal/systray") {
return new systray_module(bar, move(module_name));
#endif
} else if (name == "internal/temperature") {
return new temperature_module(bar, move(module_name));
} else if (name == "internal/xbacklight") {
return new xbacklight_module(bar, move(module_name));
} else if (name == "internal/xkeyboard") {
return new xkeyboard_module(bar, move(module_name));
} else if (name == "internal/xwindow") {
return new xwindow_module(bar, move(module_name));
} else if (name == "internal/xworkspaces") {
return new xworkspaces_module(bar, move(module_name));
} else if (name == "custom/text") {
return new text_module(bar, move(module_name));
} else if (name == "custom/script") {
return new script_module(bar, move(module_name));
} else if (name == "custom/menu") {
return new menu_module(bar, move(module_name));
} else if (name == "custom/ipc") {
return new ipc_module(bar, move(module_name));
} else {
throw application_error("Unknown module: " + name);
}
}
}
POLYBAR_NS_END
<commit_msg>fix(alsa): use correct module_name<commit_after>#pragma once
#include "common.hpp"
#include "modules/backlight.hpp"
#include "modules/battery.hpp"
#include "modules/bspwm.hpp"
#include "modules/counter.hpp"
#include "modules/cpu.hpp"
#include "modules/date.hpp"
#include "modules/fs.hpp"
#include "modules/ipc.hpp"
#include "modules/memory.hpp"
#include "modules/menu.hpp"
#include "modules/meta/base.hpp"
#include "modules/script.hpp"
#if DEBUG
#include "modules/systray.hpp"
#endif
#include "modules/temperature.hpp"
#include "modules/text.hpp"
#include "modules/xbacklight.hpp"
#include "modules/xwindow.hpp"
#include "modules/xworkspaces.hpp"
#if ENABLE_I3
#include "modules/i3.hpp"
#endif
#if ENABLE_MPD
#include "modules/mpd.hpp"
#endif
#if ENABLE_NETWORK
#include "modules/network.hpp"
#endif
#if ENABLE_ALSA
#include "modules/alsa.hpp"
#endif
#if ENABLE_PULSEAUDIO
#include "modules/pulseaudio.hpp"
#endif
#if ENABLE_CURL
#include "modules/github.hpp"
#endif
#if ENABLE_XKEYBOARD
#include "modules/xkeyboard.hpp"
#endif
#if not(ENABLE_I3 && ENABLE_MPD && ENABLE_NETWORK && ENABLE_ALSA && ENABLE_PULSEAUDIO && ENABLE_CURL && ENABLE_XKEYBOARD)
#include "modules/unsupported.hpp"
#endif
POLYBAR_NS
using namespace modules;
namespace {
module_interface* make_module(string&& name, const bar_settings& bar, string module_name, const logger& m_log) {
if (name == "internal/counter") {
return new counter_module(bar, move(module_name));
} else if (name == "internal/backlight") {
return new backlight_module(bar, move(module_name));
} else if (name == "internal/battery") {
return new battery_module(bar, move(module_name));
} else if (name == "internal/bspwm") {
return new bspwm_module(bar, move(module_name));
} else if (name == "internal/cpu") {
return new cpu_module(bar, move(module_name));
} else if (name == "internal/date") {
return new date_module(bar, move(module_name));
} else if (name == "internal/github") {
return new github_module(bar, move(module_name));
} else if (name == "internal/fs") {
return new fs_module(bar, move(module_name));
} else if (name == "internal/memory") {
return new memory_module(bar, move(module_name));
} else if (name == "internal/i3") {
return new i3_module(bar, move(module_name));
} else if (name == "internal/mpd") {
return new mpd_module(bar, move(module_name));
} else if (name == "internal/volume") {
m_log.warn("internal/volume is deprecated, use internal/alsa instead");
return new alsa_module(bar, move(module_name));
} else if (name == "internal/alsa") {
return new alsa_module(bar, move(module_name));
} else if (name == "internal/pulseaudio") {
return new pulseaudio_module(bar, move(module_name));
} else if (name == "internal/network") {
return new network_module(bar, move(module_name));
#if DEBUG
} else if (name == "internal/systray") {
return new systray_module(bar, move(module_name));
#endif
} else if (name == "internal/temperature") {
return new temperature_module(bar, move(module_name));
} else if (name == "internal/xbacklight") {
return new xbacklight_module(bar, move(module_name));
} else if (name == "internal/xkeyboard") {
return new xkeyboard_module(bar, move(module_name));
} else if (name == "internal/xwindow") {
return new xwindow_module(bar, move(module_name));
} else if (name == "internal/xworkspaces") {
return new xworkspaces_module(bar, move(module_name));
} else if (name == "custom/text") {
return new text_module(bar, move(module_name));
} else if (name == "custom/script") {
return new script_module(bar, move(module_name));
} else if (name == "custom/menu") {
return new menu_module(bar, move(module_name));
} else if (name == "custom/ipc") {
return new ipc_module(bar, move(module_name));
} else {
throw application_error("Unknown module: " + name);
}
}
}
POLYBAR_NS_END
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include <seastar/http/request.hh>
#include <seastar/http/common.hh>
#include <seastar/http/reply.hh>
#include <seastar/core/future-util.hh>
#include <unordered_map>
namespace seastar {
namespace httpd {
typedef const httpd::request& const_req;
/**
* handlers holds the logic for serving an incoming request.
* All handlers inherit from the base httpserver_handler and
* implement the handle method.
*
*/
class handler_base {
public:
/**
* All handlers should implement this method.
* It fill the reply according to the request.
* @param path the url path used in this call
* @param params optional parameter object
* @param req the original request
* @param rep the reply
*/
virtual future<std::unique_ptr<reply> > handle(const sstring& path,
std::unique_ptr<request> req, std::unique_ptr<reply> rep) = 0;
virtual ~handler_base() = default;
/**
* Add a mandatory parameter
* @param param a parameter name
* @return a reference to the handler
*/
handler_base& mandatory(const sstring& param) {
_mandatory_param.push_back(param);
return *this;
}
std::vector<sstring> _mandatory_param;
};
}
}
<commit_msg>doc: httpd::handler_base: remove obsolete @param params<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include <seastar/http/request.hh>
#include <seastar/http/common.hh>
#include <seastar/http/reply.hh>
#include <seastar/core/future-util.hh>
#include <unordered_map>
namespace seastar {
namespace httpd {
typedef const httpd::request& const_req;
/**
* handlers holds the logic for serving an incoming request.
* All handlers inherit from the base httpserver_handler and
* implement the handle method.
*
*/
class handler_base {
public:
/**
* All handlers should implement this method.
* It fill the reply according to the request.
* @param path the url path used in this call
* @param req the original request
* @param rep the reply
*/
virtual future<std::unique_ptr<reply> > handle(const sstring& path,
std::unique_ptr<request> req, std::unique_ptr<reply> rep) = 0;
virtual ~handler_base() = default;
/**
* Add a mandatory parameter
* @param param a parameter name
* @return a reference to the handler
*/
handler_base& mandatory(const sstring& param) {
_mandatory_param.push_back(param);
return *this;
}
std::vector<sstring> _mandatory_param;
};
}
}
<|endoftext|> |
<commit_before>/************************************************************************/
/* */
/* Copyright 1998-2002 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_ITERATORFACADE_HXX
#define VIGRA_ITERATORFACADE_HXX
namespace vigra {
class IteratorFacadeCoreAccess{
public:
template<class F>
static bool equal(const F & fa,const F & fb){
return fa.equal(fb);
}
template<class F,class REFERENCE>
static REFERENCE dereference(const F & f){
return f.dereference();
}
template<class F>
static void increment(F & f){
f.increment();
}
};
// see boost iterator facade
template<class FACADE,class VALUE_TYPE,bool IS_CONST = true>
class ForwardIteratorFacade{
private:
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename UnqualifiedType<VALUE_TYPE>::type value_type;
typedef typename IfBool<IS_CONST, value_type const * , value_type *>::type pointer;
typedef typename IfBool<IS_CONST, const value_type & , value_type &>::type reference;
typedef std::ptrdiff_t difference_type;
FACADE & operator++()
{
IteratorFacadeCoreAccess::increment(getF());
return getF();
}
FACADE operator++(int)
{
FACADE res(getF());
IteratorFacadeCoreAccess::increment(res);
return res;
}
bool operator ==(const FACADE & f)const{
return IteratorFacadeCoreAccess::equal(getF(),f);
}
bool operator !=(const FACADE & f)const{
return !IteratorFacadeCoreAccess::equal(getF(),f);
}
reference operator*()const{
return IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
pointer operator->()const{
return *IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
private:
const FACADE & getF()const{
return *static_cast<FACADE const *>(this);
}
FACADE & getF(){
return *static_cast<FACADE *>(this);
}
};
} // namespace vigra
#endif /* VIGRA_ITERATORFACADE_HXX */
<commit_msg>added missing include<commit_after>/************************************************************************/
/* */
/* Copyright 1998-2002 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_ITERATORFACADE_HXX
#define VIGRA_ITERATORFACADE_HXX
#include "metaprogramming.hxx"
namespace vigra {
// facade needs to make this class
// a friend class
class IteratorFacadeCoreAccess{
public:
template<class F>
static bool equal(const F & fa,const F & fb){
return fa.equal(fb);
}
template<class F,class REFERENCE>
static REFERENCE dereference(const F & f){
return f.dereference();
}
template<class F>
static void increment(F & f){
f.increment();
}
};
// see boost iterator facade
template<class FACADE,class VALUE_TYPE,bool IS_CONST = true>
class ForwardIteratorFacade{
private:
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename UnqualifiedType<VALUE_TYPE>::type value_type;
typedef typename IfBool<IS_CONST, value_type const * , value_type *>::type pointer;
typedef typename IfBool<IS_CONST, const value_type & , value_type &>::type reference;
typedef std::ptrdiff_t difference_type;
FACADE & operator++()
{
IteratorFacadeCoreAccess::increment(getF());
return getF();
}
FACADE operator++(int)
{
FACADE res(getF());
IteratorFacadeCoreAccess::increment(res);
return res;
}
bool operator ==(const FACADE & f)const{
return IteratorFacadeCoreAccess::equal(getF(),f);
}
bool operator !=(const FACADE & f)const{
return !IteratorFacadeCoreAccess::equal(getF(),f);
}
reference operator*()const{
return IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
pointer operator->()const{
return *IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
private:
const FACADE & getF()const{
return *static_cast<FACADE const *>(this);
}
FACADE & getF(){
return *static_cast<FACADE *>(this);
}
};
} // namespace vigra
#endif /* VIGRA_ITERATORFACADE_HXX */
<|endoftext|> |
<commit_before>/************************************************************************/
/* */
/* Copyright 2015 by Thorsten Beier */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_MULTI_BLOCKING_HXX
#define VIGRA_MULTI_BLOCKING_HXX
#include "vigra/tinyvector.hxx"
#include "vigra/box.hxx"
#include "vigra/multi_iterator.hxx"
#include "vigra/multi_convolution.hxx"
#include "vigra/transform_iterator.hxx"
namespace vigra{
// forward declaration
template<unsigned int DIM, class C>
class MultiBlocking;
/// \cond
namespace detail_multi_blocking{
template<unsigned int DIM, class C>
class BlockWithBorder{
public:
typedef C PointValue;
typedef TinyVector<PointValue, DIM> Point;
typedef Point Shape;
typedef Box<PointValue, DIM> Block;
typedef MultiCoordinateIterator< DIM> MultiCoordIter;
BlockWithBorder(const Block & core = Block(), const Block & border = Block())
: core_(core),
border_(border){
}
/// get the core block
const Block & core()const{
return core_;
}
Block localCore()const{
return core_-border_.begin();
}
const Block & border()const{
return border_;
}
bool operator == (const BlockWithBorder & rhs) const{
return core_ == rhs.core_ && border_ == rhs.border_;
}
bool operator != (const BlockWithBorder & rhs) const{
return core_ != rhs.core_ || border_ != rhs.border_;
}
private:
Block core_;
Block border_;
};
template<class VALUETYPE, unsigned int DIMENSION>
std::ostream& operator<< (std::ostream& stream, const BlockWithBorder<DIMENSION,VALUETYPE> & bwb) {
stream<<"["<<bwb.core()<<", "<<bwb.border()<<" ]";
return stream;
}
template<class MB>
class MultiCoordToBlockWithBoarder{
public:
typedef typename MB::Shape Shape;
typedef typename MB::BlockDesc BlockDesc;
typedef typename MB::BlockWithBorder result_type;
MultiCoordToBlockWithBoarder()
: mb_(NULL),
width_(){
}
MultiCoordToBlockWithBoarder(const MB & mb, const Shape & width)
: mb_(&mb),
width_(width){
}
result_type operator()(const BlockDesc & blockDesc)const{
return mb_->getBlockWithBorder(blockDesc, width_);
}
private:
const MB * mb_;
Shape width_;
};
template<class MB>
class MultiCoordToBlock{
public:
typedef typename MB::Shape Shape;
typedef typename MB::BlockDesc BlockDesc;
typedef typename MB::Block result_type;
MultiCoordToBlock()
: mb_(NULL){
}
MultiCoordToBlock(const MB & mb)
: mb_(&mb){
}
result_type operator()(const BlockDesc & blockDesc)const{
return mb_->getBlock(blockDesc);
}
private:
const MB * mb_;
};
}
/// \endcond
/**
MultiBlocking is used to split a image / volume / multiarray
into non-overlapping blocks.
These non overlapping blocks are called cores.
A border can be added to the core boxes.
These 'core+border' blocks are just called border.
The core block within the coordinate system
of the border block is called local core.
*/
template<unsigned int DIM, class C = MultiArrayIndex>
class MultiBlocking{
public:
typedef MultiBlocking<DIM, C> SelfType;
friend class detail_multi_blocking::MultiCoordToBlock<SelfType>;
friend class detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType>;
typedef C PointValue;
typedef TinyVector<PointValue, DIM> Point;
typedef Point Shape;
typedef Point BlockDesc;
typedef Box<PointValue, DIM> Block;
typedef MultiCoordinateIterator< DIM> MultiCoordIter;
typedef detail_multi_blocking::BlockWithBorder<DIM, PointValue> BlockWithBorder;
// iterators
typedef detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType> CoordToBwb;
typedef detail_multi_blocking::MultiCoordToBlock<SelfType> CoordToB;
typedef EndAwareTransformIterator<CoordToBwb, MultiCoordIter> BlockWithBorderIter;
typedef EndAwareTransformIterator<CoordToB, MultiCoordIter> BlockIter;
MultiBlocking(const Shape & shape,
const Shape & blockShape,
const Shape & roiBegin = Shape(0),
const Shape & roiEnd = Shape(0)
)
: shape_(shape),
roiBlock_(roiBegin,roiEnd == Shape(0) ? shape : roiEnd),
blockShape_(blockShape),
blocksPerAxis_(vigra::SkipInitialization),
numBlocks_(1)
{
const Shape roiShape = roiBlock_.size();
blocksPerAxis_ = roiShape / blockShape_;
// blocking
for(size_t d=0; d<DIM; ++d){
if(blocksPerAxis_[d]*blockShape_[d] < roiShape[d] ){
++blocksPerAxis_[d];
}
numBlocks_ *= blocksPerAxis_[d];
}
// total image border blocks
Shape beginCA(0),endCB(shape);
for(size_t d=0; d<DIM; ++d){
{
// fix coordinate d to zero
Shape endCA(shape);
endCA[d] = 1;
volumeBorderBlocks_.push_back(Block(beginCA,endCA));
}
{
// fix coordinate d to shape[dim]-1
Shape beginCB(shape);
beginCB[d] -= 1;
volumeBorderBlocks_.push_back(Block(beginCB,endCB));
}
}
insideVolBlock_.setBegin(Shape(1));
Shape insideVolBlockShapeEnd(shape);
insideVolBlockShapeEnd -= Shape(1);
insideVolBlock_.setEnd(insideVolBlockShapeEnd);
}
/// total number of blocks
size_t numBlocks()const{
return numBlocks_;
}
BlockWithBorderIter blockWithBorderBegin(const Shape & width)const{
return BlockWithBorderIter(MultiCoordIter(blocksPerAxis_),
CoordToBwb(*this, width));
}
BlockWithBorderIter blockWithBorderEnd(const Shape & width)const{
const MultiCoordIter beginIter(blocksPerAxis_);
return BlockWithBorderIter(beginIter.getEndIterator(),
CoordToBwb(*this, width));
}
BlockIter blockBegin()const{
return BlockIter(MultiCoordIter(blocksPerAxis_),CoordToB(*this));
}
BlockIter blockEnd()const{
const MultiCoordIter beginIter(blocksPerAxis_);
return BlockIter(beginIter.getEndIterator(),CoordToB(*this));
}
Block blockDescToBlock(const BlockDesc & blockDesc)const{
MultiCoordIter iter(blocksPerAxis_);
iter+=blockDesc;
return *BlockIter(iter,CoordToB(*this));
}
/// does this block intersect with the volume border
bool containsVolumeBorder(const Block & block) const {
return !insideVolBlock_.contains(block);
}
const Shape & roiBegin()const{
return roiBlock_.begin();
}
const Shape & roiEnd()const{
return roiBlock_.end();
}
const Shape & shape()const{
return shape_;
}
const Shape & blockShape()const{
return blockShape_;
}
const Shape & blocksPerAxis()const{
return blocksPerAxis_;
}
const std::vector<Block> & volumeBorderBlocks()const{
return volumeBorderBlocks_;
}
std::vector<UInt32> intersectingBlocks(
const Shape roiBegin,
const Shape roiEnd
)const{
size_t i=0;
std::vector<UInt32> iBlocks;
const Block testBlock(roiBegin, roiEnd);
for(BlockIter iter=blockBegin(); iter!=blockEnd(); ++iter){
if(testBlock.intersects(*iter)){
iBlocks.push_back(i);
}
++i;
}
return std::move(iBlocks);
}
private:
/// get a block with border
BlockWithBorder getBlockWithBorder(const BlockDesc & blockDesc, const Shape & width )const{
const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin());
const Point blockEnd(blockStart + blockShape_);
const Block core = Block(blockStart, blockEnd) & roiBlock_ ;
Block border = core;
border.addBorder(width);
border &= Block(shape_);
return BlockWithBorder( core, border );
}
/// get a block (without any overlap)
Block getBlock(const BlockDesc & blockDesc)const{
const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin());
const Point blockEnd(blockStart + blockShape_);
return Block(blockStart, blockEnd) & roiBlock_;
}
Shape shape_; // total shape of the input volume
Block roiBlock_; // ROI in which to compute filters/algorithms
Shape blockShape_; // shape sub-block for each thread (without border pixels)
Shape blocksPerAxis_; // how many blocks are on each axis
size_t numBlocks_; // total number of blocks
std::vector<Block> volumeBorderBlocks_;
Block insideVolBlock_;
};
}
#endif // VIGRA_MULTI_BLOCKING_HXX
<commit_msg>implemented missing method<commit_after>/************************************************************************/
/* */
/* Copyright 2015 by Thorsten Beier */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_MULTI_BLOCKING_HXX
#define VIGRA_MULTI_BLOCKING_HXX
#include "vigra/tinyvector.hxx"
#include "vigra/box.hxx"
#include "vigra/multi_iterator.hxx"
#include "vigra/multi_convolution.hxx"
#include "vigra/transform_iterator.hxx"
namespace vigra{
// forward declaration
template<unsigned int DIM, class C>
class MultiBlocking;
/// \cond
namespace detail_multi_blocking{
template<unsigned int DIM, class C>
class BlockWithBorder{
public:
typedef C PointValue;
typedef TinyVector<PointValue, DIM> Point;
typedef Point Shape;
typedef Box<PointValue, DIM> Block;
typedef MultiCoordinateIterator< DIM> MultiCoordIter;
BlockWithBorder(const Block & core = Block(), const Block & border = Block())
: core_(core),
border_(border){
}
/// get the core block
const Block & core()const{
return core_;
}
Block localCore()const{
return core_-border_.begin();
}
const Block & border()const{
return border_;
}
bool operator == (const BlockWithBorder & rhs) const{
return core_ == rhs.core_ && border_ == rhs.border_;
}
bool operator != (const BlockWithBorder & rhs) const{
return core_ != rhs.core_ || border_ != rhs.border_;
}
private:
Block core_;
Block border_;
};
template<class VALUETYPE, unsigned int DIMENSION>
std::ostream& operator<< (std::ostream& stream, const BlockWithBorder<DIMENSION,VALUETYPE> & bwb) {
stream<<"["<<bwb.core()<<", "<<bwb.border()<<" ]";
return stream;
}
template<class MB>
class MultiCoordToBlockWithBoarder{
public:
typedef typename MB::Shape Shape;
typedef typename MB::BlockDesc BlockDesc;
typedef typename MB::BlockWithBorder result_type;
MultiCoordToBlockWithBoarder()
: mb_(NULL),
width_(){
}
MultiCoordToBlockWithBoarder(const MB & mb, const Shape & width)
: mb_(&mb),
width_(width){
}
result_type operator()(const BlockDesc & blockDesc)const{
return mb_->getBlockWithBorder(blockDesc, width_);
}
private:
const MB * mb_;
Shape width_;
};
template<class MB>
class MultiCoordToBlock{
public:
typedef typename MB::Shape Shape;
typedef typename MB::BlockDesc BlockDesc;
typedef typename MB::Block result_type;
MultiCoordToBlock()
: mb_(NULL){
}
MultiCoordToBlock(const MB & mb)
: mb_(&mb){
}
result_type operator()(const BlockDesc & blockDesc)const{
return mb_->getBlock(blockDesc);
}
private:
const MB * mb_;
};
}
/// \endcond
/**
MultiBlocking is used to split a image / volume / multiarray
into non-overlapping blocks.
These non overlapping blocks are called cores.
A border can be added to the core boxes.
These 'core+border' blocks are just called border.
The core block within the coordinate system
of the border block is called local core.
*/
template<unsigned int DIM, class C = MultiArrayIndex>
class MultiBlocking{
public:
typedef MultiBlocking<DIM, C> SelfType;
friend class detail_multi_blocking::MultiCoordToBlock<SelfType>;
friend class detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType>;
typedef C PointValue;
typedef TinyVector<PointValue, DIM> Point;
typedef Point Shape;
typedef Point BlockDesc;
typedef Box<PointValue, DIM> Block;
typedef MultiCoordinateIterator< DIM> MultiCoordIter;
typedef detail_multi_blocking::BlockWithBorder<DIM, PointValue> BlockWithBorder;
// iterators
typedef detail_multi_blocking::MultiCoordToBlockWithBoarder<SelfType> CoordToBwb;
typedef detail_multi_blocking::MultiCoordToBlock<SelfType> CoordToB;
typedef EndAwareTransformIterator<CoordToBwb, MultiCoordIter> BlockWithBorderIter;
typedef EndAwareTransformIterator<CoordToB, MultiCoordIter> BlockIter;
MultiBlocking(const Shape & shape,
const Shape & blockShape,
const Shape & roiBegin = Shape(0),
const Shape & roiEnd = Shape(0)
)
: shape_(shape),
roiBlock_(roiBegin,roiEnd == Shape(0) ? shape : roiEnd),
blockShape_(blockShape),
blocksPerAxis_(vigra::SkipInitialization),
numBlocks_(1)
{
const Shape roiShape = roiBlock_.size();
blocksPerAxis_ = roiShape / blockShape_;
// blocking
for(size_t d=0; d<DIM; ++d){
if(blocksPerAxis_[d]*blockShape_[d] < roiShape[d] ){
++blocksPerAxis_[d];
}
numBlocks_ *= blocksPerAxis_[d];
}
// total image border blocks
Shape beginCA(0),endCB(shape);
for(size_t d=0; d<DIM; ++d){
{
// fix coordinate d to zero
Shape endCA(shape);
endCA[d] = 1;
volumeBorderBlocks_.push_back(Block(beginCA,endCA));
}
{
// fix coordinate d to shape[dim]-1
Shape beginCB(shape);
beginCB[d] -= 1;
volumeBorderBlocks_.push_back(Block(beginCB,endCB));
}
}
insideVolBlock_.setBegin(Shape(1));
Shape insideVolBlockShapeEnd(shape);
insideVolBlockShapeEnd -= Shape(1);
insideVolBlock_.setEnd(insideVolBlockShapeEnd);
}
/// total number of blocks
size_t numBlocks()const{
return numBlocks_;
}
BlockWithBorderIter blockWithBorderBegin(const Shape & width)const{
return BlockWithBorderIter(MultiCoordIter(blocksPerAxis_),
CoordToBwb(*this, width));
}
BlockWithBorderIter blockWithBorderEnd(const Shape & width)const{
const MultiCoordIter beginIter(blocksPerAxis_);
return BlockWithBorderIter(beginIter.getEndIterator(),
CoordToBwb(*this, width));
}
Block blockDescToBlock(const BlockDesc & desc){
MultiCoordIter beginIter(blocksPerAxis_);
beginIter+=desc;
return *BlockIter(beginIter,CoordToB(*this));
}
BlockIter blockBegin()const{
return BlockIter(MultiCoordIter(blocksPerAxis_),CoordToB(*this));
}
BlockIter blockEnd()const{
const MultiCoordIter beginIter(blocksPerAxis_);
return BlockIter(beginIter.getEndIterator(),CoordToB(*this));
}
Block blockDescToBlock(const BlockDesc & blockDesc)const{
MultiCoordIter iter(blocksPerAxis_);
iter+=blockDesc;
return *BlockIter(iter,CoordToB(*this));
}
/// does this block intersect with the volume border
bool containsVolumeBorder(const Block & block) const {
return !insideVolBlock_.contains(block);
}
const Shape & roiBegin()const{
return roiBlock_.begin();
}
const Shape & roiEnd()const{
return roiBlock_.end();
}
const Shape & shape()const{
return shape_;
}
const Shape & blockShape()const{
return blockShape_;
}
const Shape & blocksPerAxis()const{
return blocksPerAxis_;
}
const std::vector<Block> & volumeBorderBlocks()const{
return volumeBorderBlocks_;
}
std::vector<UInt32> intersectingBlocks(
const Shape roiBegin,
const Shape roiEnd
)const{
size_t i=0;
std::vector<UInt32> iBlocks;
const Block testBlock(roiBegin, roiEnd);
for(BlockIter iter=blockBegin(); iter!=blockEnd(); ++iter){
if(testBlock.intersects(*iter)){
iBlocks.push_back(i);
}
++i;
}
return std::move(iBlocks);
}
private:
/// get a block with border
BlockWithBorder getBlockWithBorder(const BlockDesc & blockDesc, const Shape & width )const{
const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin());
const Point blockEnd(blockStart + blockShape_);
const Block core = Block(blockStart, blockEnd) & roiBlock_ ;
Block border = core;
border.addBorder(width);
border &= Block(shape_);
return BlockWithBorder( core, border );
}
/// get a block (without any overlap)
Block getBlock(const BlockDesc & blockDesc)const{
const Point blockStart(blockDesc * blockShape_ + roiBlock_.begin());
const Point blockEnd(blockStart + blockShape_);
return Block(blockStart, blockEnd) & roiBlock_;
}
Shape shape_; // total shape of the input volume
Block roiBlock_; // ROI in which to compute filters/algorithms
Shape blockShape_; // shape sub-block for each thread (without border pixels)
Shape blocksPerAxis_; // how many blocks are on each axis
size_t numBlocks_; // total number of blocks
std::vector<Block> volumeBorderBlocks_;
Block insideVolBlock_;
};
}
#endif // VIGRA_MULTI_BLOCKING_HXX
<|endoftext|> |
<commit_before>/*!
@file
@author Albert Semenov
@date 08/2008
@module
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "BaseManager.h"
#include <MyGUI_OgrePlatform.h>
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
# include <windows.h>
#endif
namespace base
{
BaseManager::BaseManager() :
mGUI(nullptr),
mPlatform(nullptr),
mInfo(nullptr),
mFocusInfo(nullptr),
mRoot(nullptr),
mCamera(nullptr),
mSceneManager(nullptr),
mWindow(nullptr),
mExit(false),
mPluginCfgName("plugins.cfg"),
mResourceXMLName("resources.xml"),
mResourceFileName("core.xml"),
mNode(nullptr),
mAnimationState(nullptr)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
mResourcePath = MyGUI::helper::macBundlePath() + "/Contents/Resources/";
#else
mResourcePath = "";
#endif
}
BaseManager::~BaseManager()
{
}
bool BaseManager::create()
{
Ogre::String pluginsPath;
#ifndef OGRE_STATIC_LIB
pluginsPath = mResourcePath + mPluginCfgName;
#endif
mRoot = new Ogre::Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");
setupResources();
//
if (!mRoot->restoreConfig())
{
// ,
if (!mRoot->showConfigDialog()) return false;
}
mWindow = mRoot->initialise(true);
int width = mWindow->getWidth();
int height = mWindow->getHeight();
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
//
size_t hWnd = 0;
mWindow->getCustomAttribute("WINDOW", &hWnd);
//
char buf[MAX_PATH];
::GetModuleFileNameA(0, (LPCH)&buf, MAX_PATH);
//
HINSTANCE instance = ::GetModuleHandleA(buf);
//
HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(1001));
if (hIcon)
{
::SendMessageA((HWND)hWnd, WM_SETICON, 1, (LPARAM)hIcon);
::SendMessageA((HWND)hWnd, WM_SETICON, 0, (LPARAM)hIcon);
}
#endif
mSceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "BaseSceneManager");
mCamera = mSceneManager->createCamera("BaseCamera");
mCamera->setNearClipDistance(5);
mCamera->setPosition(400, 400, 400);
mCamera->lookAt(0, 150, 0);
// Create one viewport, entire window
Ogre::Viewport* vp = mWindow->addViewport(mCamera);
// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio((float)vp->getActualWidth() / (float)vp->getActualHeight());
// Set default mipmap level (NB some APIs ignore this)
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
mSceneManager->setAmbientLight(Ogre::ColourValue::White);
Ogre::Light* l = mSceneManager->createLight("MainLight");
l->setType(Ogre::Light::LT_DIRECTIONAL);
Ogre::Vector3 vec(-0.3, -0.3, -0.3);
vec.normalise();
l->setDirection(vec);
// Load resources
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
mRoot->addFrameListener(this);
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
createInput(handle);
windowResized(mWindow);
createGui();
createScene();
return true;
}
void BaseManager::run()
{
//
mRoot->getRenderSystem()->_initRenderTargets();
//
while (true)
{
Ogre::WindowEventUtilities::messagePump();
if (mWindow->isActive() == false)
mWindow->setActive(true);
if (!mRoot->renderOneFrame())
break;
// ,
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
::Sleep(0);
#endif
};
}
void BaseManager::destroy()
{
destroyScene();
destroyGui();
//
if (mSceneManager)
{
mSceneManager->clearScene();
mSceneManager->destroyAllCameras();
mSceneManager = nullptr;
}
destroyInput();
if (mWindow)
{
mWindow->destroy();
mWindow = nullptr;
}
if (mRoot)
{
Ogre::RenderWindow* mWindow = mRoot->getAutoCreatedWindow();
if (mWindow)
mWindow->removeAllViewports();
delete mRoot;
mRoot = nullptr;
}
}
void BaseManager::createGui()
{
mPlatform = new MyGUI::OgrePlatform();
mPlatform->initialise(mWindow, mSceneManager);
mGUI = new MyGUI::Gui();
mGUI->initialise(mResourceFileName);
mInfo = new diagnostic::StatisticInfo();
}
void BaseManager::destroyGui()
{
if (mGUI)
{
if (mInfo)
{
delete mInfo;
mInfo = nullptr;
}
if (mFocusInfo)
{
delete mFocusInfo;
mFocusInfo = nullptr;
}
mGUI->shutdown();
delete mGUI;
mGUI = nullptr;
}
if (mPlatform)
{
mPlatform->shutdown();
delete mPlatform;
mPlatform = nullptr;
}
}
void BaseManager::setupResources()
{
MyGUI::xml::Document doc;
if (!doc.open(mResourceXMLName))
doc.getLastError();
MyGUI::xml::ElementPtr root = doc.getRoot();
if (root == nullptr || root->getName() != "Paths")
return;
MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
while (node.next())
{
if (node->getName() == "Path")
{
bool root = false;
if (node->findAttribute("root") != "")
{
root = MyGUI::utility::parseBool(node->findAttribute("root"));
if (root) mRootMedia = node->getContent();
}
addResourceLocation(node->getContent());
}
}
addResourceLocation(mRootMedia + "/Common/packs/OgreCore.zip", "Bootstrap", "Zip", false);
}
bool BaseManager::frameStarted(const Ogre::FrameEvent& evt)
{
if (mExit)
return false;
if (!mGUI)
return true;
captureInput();
if (mInfo)
{
static float time = 0;
time += evt.timeSinceLastFrame;
if (time > 1)
{
time -= 1;
try
{
const Ogre::RenderTarget::FrameStats& stats = mWindow->getStatistics();
mInfo->change("FPS", (int)stats.lastFPS);
mInfo->change("triangle", stats.triangleCount);
mInfo->change("batch", stats.batchCount);
//mInfo->change("batch gui", MyGUI::RenderManager::getInstance().getBatch());
mInfo->update();
}
catch (...)
{
}
}
}
//
if (mNode)
{
mNode->yaw(Ogre::Radian(Ogre::Degree(evt.timeSinceLastFrame * 10)));
if (mAnimationState)
mAnimationState->addTime(evt.timeSinceLastFrame);
}
return true;
}
bool BaseManager::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
};
void BaseManager::windowResized(Ogre::RenderWindow* _rw)
{
int width = (int)_rw->getWidth();
int height = (int)_rw->getHeight();
setInputViewSize(width, height);
}
void BaseManager::windowClosed(Ogre::RenderWindow* _rw)
{
mExit = true;
destroyInput();
}
void BaseManager::setWindowCaption(const std::string& _text)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
::SetWindowTextA((HWND)handle, _text.c_str());
#endif
}
void BaseManager::prepare(int argc, char **argv)
{
}
void BaseManager::addResourceLocation(const std::string& _name, const std::string& _group, const std::string& _type, bool _recursive)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
// OS X does not set the working directory relative to the app, In order to make things portable on OS X we need to provide the loading with it's own bundle path location
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Ogre::String(MyGUI::helper::macBundlePath() + "/" + _name), _type, _group, _recursive);
#else
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(_name, _type, _group, _recursive);
#endif
}
void BaseManager::addResourceLocation(const std::string & _name, bool _recursive)
{
addResourceLocation(_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "FileSystem", false);
}
void BaseManager::createDefaultScene()
{
Ogre::Entity* entity = nullptr;
try
{
entity = mSceneManager->createEntity("Mikki_Mesh.mesh", "Mikki_Mesh.mesh");
mNode = mSceneManager->getRootSceneNode()->createChildSceneNode();
mNode->attachObject(entity);
}
catch (Ogre::FileNotFoundException&)
{
return;
}
try
{
if (entity)
{
mAnimationState = entity->getAnimationState("Idle");
mAnimationState->setEnabled(true);
mAnimationState->setLoop(true);
mAnimationState->setWeight(1);
}
}
catch (Ogre::ItemIdentityException&)
{
}
}
void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
{
if (!mGUI)
return;
mGUI->injectMouseMove(_absx, _absy, _absz);
}
void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMousePress(_absx, _absy, _id);
}
void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMouseRelease(_absx, _absy, _id);
}
void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
{
if (!mGUI)
return;
if (_key == MyGUI::KeyCode::Escape)
{
mExit = true;
return;
}
else if (_key == MyGUI::KeyCode::SysRq)
{
std::ifstream stream;
std::string file;
do
{
stream.close();
static size_t num = 0;
const size_t max_shot = 100;
if (num == max_shot)
{
MYGUI_LOG(Info, "The limit of screenshots is exceeded : " << max_shot);
return;
}
file = MyGUI::utility::toString("screenshot_", ++num, ".png");
stream.open(file.c_str());
}
while (stream.is_open());
mWindow->writeContentsToFile(file);
return;
}
else if (_key == MyGUI::KeyCode::F12)
{
if (mFocusInfo == nullptr)
mFocusInfo = new diagnostic::InputFocusInfo();
bool visible = mFocusInfo->getFocusVisible();
mFocusInfo->setFocusVisible(!visible);
}
mGUI->injectKeyPress(_key, _text);
}
void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
{
if (!mGUI)
return;
mGUI->injectKeyRelease(_key);
}
} // namespace base
<commit_msg>fix Ogre BaseManager<commit_after>/*!
@file
@author Albert Semenov
@date 08/2008
@module
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "BaseManager.h"
#include <MyGUI_OgrePlatform.h>
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
# include <windows.h>
#endif
namespace base
{
BaseManager::BaseManager() :
mGUI(nullptr),
mPlatform(nullptr),
mInfo(nullptr),
mFocusInfo(nullptr),
mRoot(nullptr),
mCamera(nullptr),
mSceneManager(nullptr),
mWindow(nullptr),
mExit(false),
mPluginCfgName("plugins.cfg"),
mResourceXMLName("resources.xml"),
mResourceFileName("core.xml"),
mNode(nullptr),
mAnimationState(nullptr)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
mResourcePath = MyGUI::helper::macBundlePath() + "/Contents/Resources/";
#else
mResourcePath = "";
#endif
}
BaseManager::~BaseManager()
{
}
bool BaseManager::create()
{
Ogre::String pluginsPath;
#ifndef OGRE_STATIC_LIB
pluginsPath = mResourcePath + mPluginCfgName;
#endif
mRoot = new Ogre::Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");
setupResources();
//
if (!mRoot->restoreConfig())
{
// ,
if (!mRoot->showConfigDialog()) return false;
}
mWindow = mRoot->initialise(true);
int width = mWindow->getWidth();
int height = mWindow->getHeight();
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
//
size_t hWnd = 0;
mWindow->getCustomAttribute("WINDOW", &hWnd);
//
char buf[MAX_PATH];
::GetModuleFileNameA(0, (LPCH)&buf, MAX_PATH);
//
HINSTANCE instance = ::GetModuleHandleA(buf);
//
HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(1001));
if (hIcon)
{
::SendMessageA((HWND)hWnd, WM_SETICON, 1, (LPARAM)hIcon);
::SendMessageA((HWND)hWnd, WM_SETICON, 0, (LPARAM)hIcon);
}
#endif
mSceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "BaseSceneManager");
mCamera = mSceneManager->createCamera("BaseCamera");
mCamera->setNearClipDistance(5);
mCamera->setPosition(400, 400, 400);
mCamera->lookAt(0, 150, 0);
// Create one viewport, entire window
Ogre::Viewport* vp = mWindow->addViewport(mCamera);
// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio((float)vp->getActualWidth() / (float)vp->getActualHeight());
// Set default mipmap level (NB some APIs ignore this)
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
mSceneManager->setAmbientLight(Ogre::ColourValue::White);
Ogre::Light* l = mSceneManager->createLight("MainLight");
l->setType(Ogre::Light::LT_DIRECTIONAL);
Ogre::Vector3 vec(-0.3, -0.3, -0.3);
vec.normalise();
l->setDirection(vec);
// Load resources
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
mRoot->addFrameListener(this);
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
createInput(handle);
windowResized(mWindow);
createGui();
createScene();
return true;
}
void BaseManager::run()
{
//
mRoot->getRenderSystem()->_initRenderTargets();
//
while (true)
{
Ogre::WindowEventUtilities::messagePump();
if (mWindow->isActive() == false)
mWindow->setActive(true);
if (!mRoot->renderOneFrame())
break;
// ,
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
::Sleep(0);
#endif
};
}
void BaseManager::destroy()
{
destroyScene();
destroyGui();
//
if (mSceneManager)
{
mSceneManager->clearScene();
mSceneManager->destroyAllCameras();
mSceneManager = nullptr;
}
destroyInput();
if (mWindow)
{
mWindow->destroy();
mWindow = nullptr;
}
if (mRoot)
{
Ogre::RenderWindow* mWindow = mRoot->getAutoCreatedWindow();
if (mWindow)
mWindow->removeAllViewports();
delete mRoot;
mRoot = nullptr;
}
}
void BaseManager::createGui()
{
mPlatform = new MyGUI::OgrePlatform();
mPlatform->initialise(mWindow, mSceneManager);
mGUI = new MyGUI::Gui();
mGUI->initialise(mResourceFileName);
mInfo = new diagnostic::StatisticInfo();
}
void BaseManager::destroyGui()
{
if (mGUI)
{
if (mInfo)
{
delete mInfo;
mInfo = nullptr;
}
if (mFocusInfo)
{
delete mFocusInfo;
mFocusInfo = nullptr;
}
mGUI->shutdown();
delete mGUI;
mGUI = nullptr;
}
if (mPlatform)
{
mPlatform->shutdown();
delete mPlatform;
mPlatform = nullptr;
}
}
void BaseManager::setupResources()
{
MyGUI::xml::Document doc;
if (!doc.open(mResourceXMLName))
doc.getLastError();
MyGUI::xml::ElementPtr root = doc.getRoot();
if (root == nullptr || root->getName() != "Paths")
return;
MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
while (node.next())
{
if (node->getName() == "Path")
{
bool root = false;
if (node->findAttribute("root") != "")
{
root = MyGUI::utility::parseBool(node->findAttribute("root"));
if (root) mRootMedia = node->getContent();
}
addResourceLocation(node->getContent());
}
}
addResourceLocation(mRootMedia + "/Common/packs/OgreCore.zip", "Bootstrap", "Zip", false);
}
bool BaseManager::frameStarted(const Ogre::FrameEvent& evt)
{
if (mExit)
return false;
if (!mGUI)
return true;
captureInput();
if (mInfo)
{
static float time = 0;
time += evt.timeSinceLastFrame;
if (time > 1)
{
time -= 1;
try
{
const Ogre::RenderTarget::FrameStats& stats = mWindow->getStatistics();
mInfo->change("FPS", (int)stats.lastFPS);
mInfo->change("triangle", stats.triangleCount);
mInfo->change("batch", stats.batchCount);
//mInfo->change("batch gui", MyGUI::RenderManager::getInstance().getBatch());
mInfo->update();
}
catch (...)
{
}
}
}
//
if (mNode)
{
mNode->yaw(Ogre::Radian(Ogre::Degree(evt.timeSinceLastFrame * 10)));
if (mAnimationState)
mAnimationState->addTime(evt.timeSinceLastFrame);
}
return true;
}
bool BaseManager::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
};
void BaseManager::windowResized(Ogre::RenderWindow* _rw)
{
int width = (int)_rw->getWidth();
int height = (int)_rw->getHeight();
mCamera->setAspectRatio((float)width / (float)height);
setInputViewSize(width, height);
}
void BaseManager::windowClosed(Ogre::RenderWindow* _rw)
{
mExit = true;
destroyInput();
}
void BaseManager::setWindowCaption(const std::string& _text)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
::SetWindowTextA((HWND)handle, _text.c_str());
#endif
}
void BaseManager::prepare(int argc, char **argv)
{
}
void BaseManager::addResourceLocation(const std::string& _name, const std::string& _group, const std::string& _type, bool _recursive)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
// OS X does not set the working directory relative to the app, In order to make things portable on OS X we need to provide the loading with it's own bundle path location
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Ogre::String(MyGUI::helper::macBundlePath() + "/" + _name), _type, _group, _recursive);
#else
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(_name, _type, _group, _recursive);
#endif
}
void BaseManager::addResourceLocation(const std::string & _name, bool _recursive)
{
addResourceLocation(_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "FileSystem", false);
}
void BaseManager::createDefaultScene()
{
Ogre::Entity* entity = nullptr;
try
{
entity = mSceneManager->createEntity("Mikki_Mesh.mesh", "Mikki_Mesh.mesh");
mNode = mSceneManager->getRootSceneNode()->createChildSceneNode();
mNode->attachObject(entity);
}
catch (Ogre::FileNotFoundException&)
{
return;
}
try
{
if (entity)
{
mAnimationState = entity->getAnimationState("Idle");
mAnimationState->setEnabled(true);
mAnimationState->setLoop(true);
mAnimationState->setWeight(1);
}
}
catch (Ogre::ItemIdentityException&)
{
}
}
void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
{
if (!mGUI)
return;
mGUI->injectMouseMove(_absx, _absy, _absz);
}
void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMousePress(_absx, _absy, _id);
}
void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMouseRelease(_absx, _absy, _id);
}
void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
{
if (!mGUI)
return;
if (_key == MyGUI::KeyCode::Escape)
{
mExit = true;
return;
}
else if (_key == MyGUI::KeyCode::SysRq)
{
std::ifstream stream;
std::string file;
do
{
stream.close();
static size_t num = 0;
const size_t max_shot = 100;
if (num == max_shot)
{
MYGUI_LOG(Info, "The limit of screenshots is exceeded : " << max_shot);
return;
}
file = MyGUI::utility::toString("screenshot_", ++num, ".png");
stream.open(file.c_str());
}
while (stream.is_open());
mWindow->writeContentsToFile(file);
return;
}
else if (_key == MyGUI::KeyCode::F12)
{
if (mFocusInfo == nullptr)
mFocusInfo = new diagnostic::InputFocusInfo();
bool visible = mFocusInfo->getFocusVisible();
mFocusInfo->setFocusVisible(!visible);
}
mGUI->injectKeyPress(_key, _text);
}
void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
{
if (!mGUI)
return;
mGUI->injectKeyRelease(_key);
}
} // namespace base
<|endoftext|> |
<commit_before>#include "QPlayControl.h"
#include <QToolButton>
#include <QWidget>
#include <QComboBox>
#include "flut/system/log.hpp"
QPlayControl::QPlayControl( QWidget *parent ) :
QWidget( parent ),
currentTime( 0.0 ),
skipTime( 0.01 ),
slomoFactor( 1.0 ),
minTime( 0.0 ),
maxTime( 1.0 ),
autoExtendRange( false )
{
playButton = new QToolButton( this );
playButton->setIcon( style()->standardIcon( QStyle::SP_MediaPlay ) );
connect( playButton, SIGNAL( clicked() ), this, SLOT( play() ) );
stopButton = new QToolButton( this );
stopButton->setIcon( style()->standardIcon( QStyle::SP_MediaStop ) );
connect( stopButton, SIGNAL( clicked() ), this, SLOT( stop() ) );
nextButton = new QToolButton( this );
nextButton->setIcon( style()->standardIcon( QStyle::SP_MediaSkipForward ) );
connect( nextButton, SIGNAL( clicked() ), this, SLOT( next() ) );
previousButton = new QToolButton( this );
previousButton->setIcon( style()->standardIcon( QStyle::SP_MediaSkipBackward ) );
connect( previousButton, SIGNAL( clicked() ), this, SLOT( previous() ) );
loopButton = new QToolButton( this );
loopButton->setCheckable( true );
loopButton->setIcon( style()->standardIcon( QStyle::SP_BrowserReload ) );
label = new QLCDNumber( this );
label->setDigitCount( 5 );
label->setSmallDecimalPoint( true );
label->setFrameStyle( QFrame::Box );
label->setSegmentStyle( QLCDNumber::Flat );
label->display( "0.00" );
slider = new QSlider( Qt::Horizontal, this );
slider->setSingleStep( 10 );
slider->setPageStep( 100 );
connect( slider, SIGNAL( valueChanged( int ) ), this, SLOT( updateSlider( int ) ) );
connect( slider, SIGNAL( sliderReleased() ), this, SIGNAL( sliderReleased() ) );
slowMotionBox = new QComboBox( this );
for ( int slomo = 2; slomo >= -5; --slomo )
{
QString label = slomo >= 0 ? QString().sprintf( "%d x", (int)pow( 2, slomo ) ) : QString().sprintf( "1/%d x", (int)pow( 2, -slomo ) );
slowMotionBox->addItem( label, QVariant( pow( 2, slomo ) ) );
}
slowMotionBox->setCurrentIndex( 2 );
connect( slowMotionBox, SIGNAL( activated( int ) ), SLOT( updateSlowMotion( int ) ) );
QBoxLayout *lo = new QHBoxLayout;
lo->setMargin( 0 );
lo->setSpacing( 2 );
lo->addWidget( previousButton );
lo->addWidget( playButton );
lo->addWidget( stopButton );
lo->addWidget( nextButton );
lo->addWidget( label );
lo->addWidget( slider );
lo->addWidget( loopButton );
lo->addWidget( slowMotionBox );
setLayout( lo );
connect( &qtimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );
}
void QPlayControl::setRange( double min, double max )
{
minTime = min;
maxTime = max;
slider->setRange( static_cast< int >( 1000 * minTime + 0.5 ), static_cast< int >( 1000 * maxTime + 0.5 ) );
}
void QPlayControl::setTime( double time )
{
currentTime = time;
if ( currentTime > maxTime )
{
if ( getAutoExtendRange() )
{
// adjust maximum
setRange( minTime, currentTime );
}
else if ( getLoop() )
{
// restart
currentTime = minTime;
}
else
{
// stop playing
currentTime = maxTime;
stop();
}
}
slider->blockSignals( true );
slider->setValue( int( currentTime * 1000 ) );
slider->blockSignals( false );
label->display( QString().sprintf( "%.2f", currentTime ) );
emit timeChanged( currentTime );
}
bool QPlayControl::getLoop()
{
return loopButton->isChecked();
}
bool QPlayControl::isPlaying()
{
return qtimer.isActive();
}
void QPlayControl::setLoop( bool b )
{
loopButton->setChecked( b );
}
void QPlayControl::play()
{
if ( !isPlaying() )
{
if ( currentTime >= maxTime )
reset();
qtimer.start( 10 );
timer.reset();
timer_delta.reset();
emit playTriggered();
}
}
void QPlayControl::stop()
{
if ( qtimer.isActive() )
{
qtimer.stop();
emit stopTriggered();
}
else reset();
}
void QPlayControl::toggle()
{
if ( isPlaying() )
stop();
else play();
}
void QPlayControl::reset()
{
if ( qtimer.isActive() )
qtimer.stop();
setTime( 0 );
emit resetTriggered();
}
void QPlayControl::previous()
{
setTime( currentTime - skipTime );
emit previousTriggered();
}
void QPlayControl::next()
{
setTime( currentTime + skipTime );
emit nextTriggered();
}
void QPlayControl::updateSlowMotion( int idx )
{
slomoFactor = slowMotionBox->itemData( idx ).toDouble();
emit slowMotionChanged( slowMotionBox->itemData( idx ).toInt() );
}
void QPlayControl::updateSlider( int value )
{
setTime( value / 1000.0 );
emit sliderChanged( value );
}
void QPlayControl::timeout()
{
setTime( currentTime + slomoFactor * timer_delta( timer.seconds() ) );
}
<commit_msg>PlayControl: fix issue where slider would jump to start<commit_after>#include "QPlayControl.h"
#include <QToolButton>
#include <QWidget>
#include <QComboBox>
#include "flut/system/log.hpp"
QPlayControl::QPlayControl( QWidget *parent ) :
QWidget( parent ),
currentTime( 0.0 ),
skipTime( 0.01 ),
slomoFactor( 1.0 ),
minTime( 0.0 ),
maxTime( 1.0 ),
autoExtendRange( false )
{
playButton = new QToolButton( this );
playButton->setIcon( style()->standardIcon( QStyle::SP_MediaPlay ) );
connect( playButton, SIGNAL( clicked() ), this, SLOT( play() ) );
stopButton = new QToolButton( this );
stopButton->setIcon( style()->standardIcon( QStyle::SP_MediaStop ) );
connect( stopButton, SIGNAL( clicked() ), this, SLOT( stop() ) );
nextButton = new QToolButton( this );
nextButton->setIcon( style()->standardIcon( QStyle::SP_MediaSkipForward ) );
connect( nextButton, SIGNAL( clicked() ), this, SLOT( next() ) );
previousButton = new QToolButton( this );
previousButton->setIcon( style()->standardIcon( QStyle::SP_MediaSkipBackward ) );
connect( previousButton, SIGNAL( clicked() ), this, SLOT( previous() ) );
loopButton = new QToolButton( this );
loopButton->setCheckable( true );
loopButton->setIcon( style()->standardIcon( QStyle::SP_BrowserReload ) );
label = new QLCDNumber( this );
label->setDigitCount( 5 );
label->setSmallDecimalPoint( true );
label->setFrameStyle( QFrame::Box );
label->setSegmentStyle( QLCDNumber::Flat );
label->display( "0.00" );
slider = new QSlider( Qt::Horizontal, this );
slider->setSingleStep( 10 );
slider->setPageStep( 100 );
connect( slider, SIGNAL( valueChanged( int ) ), this, SLOT( updateSlider( int ) ) );
connect( slider, SIGNAL( sliderReleased() ), this, SIGNAL( sliderReleased() ) );
slowMotionBox = new QComboBox( this );
for ( int slomo = 2; slomo >= -5; --slomo )
{
QString label = slomo >= 0 ? QString().sprintf( "%d x", (int)pow( 2, slomo ) ) : QString().sprintf( "1/%d x", (int)pow( 2, -slomo ) );
slowMotionBox->addItem( label, QVariant( pow( 2, slomo ) ) );
}
slowMotionBox->setCurrentIndex( 2 );
connect( slowMotionBox, SIGNAL( activated( int ) ), SLOT( updateSlowMotion( int ) ) );
QBoxLayout *lo = new QHBoxLayout;
lo->setMargin( 0 );
lo->setSpacing( 2 );
lo->addWidget( previousButton );
lo->addWidget( playButton );
lo->addWidget( stopButton );
lo->addWidget( nextButton );
lo->addWidget( label );
lo->addWidget( slider );
lo->addWidget( loopButton );
lo->addWidget( slowMotionBox );
setLayout( lo );
connect( &qtimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );
}
void QPlayControl::setRange( double min, double max )
{
minTime = min;
maxTime = max;
slider->setRange( static_cast< int >( 1000 * minTime + 0.5 ), static_cast< int >( 1000 * maxTime + 0.5 ) );
}
void QPlayControl::setTime( double time )
{
currentTime = time;
if ( currentTime > maxTime )
{
if ( getAutoExtendRange() )
{
// adjust maximum
setRange( minTime, currentTime );
}
else if ( isPlaying() && getLoop() )
{
// restart
currentTime = minTime;
}
else
{
// clamp to maximum and stop playing
currentTime = maxTime;
if ( isPlaying() )
stop();
}
}
slider->blockSignals( true );
slider->setValue( int( currentTime * 1000 ) );
slider->blockSignals( false );
label->display( QString().sprintf( "%.2f", currentTime ) );
emit timeChanged( currentTime );
}
bool QPlayControl::getLoop()
{
return loopButton->isChecked();
}
bool QPlayControl::isPlaying()
{
return qtimer.isActive();
}
void QPlayControl::setLoop( bool b )
{
loopButton->setChecked( b );
}
void QPlayControl::play()
{
if ( !isPlaying() )
{
if ( currentTime >= maxTime )
reset();
qtimer.start( 10 );
timer.reset();
timer_delta.reset();
emit playTriggered();
}
}
void QPlayControl::stop()
{
if ( qtimer.isActive() )
{
qtimer.stop();
emit stopTriggered();
}
else reset();
}
void QPlayControl::toggle()
{
if ( isPlaying() )
stop();
else play();
}
void QPlayControl::reset()
{
if ( qtimer.isActive() )
qtimer.stop();
setTime( 0 );
emit resetTriggered();
}
void QPlayControl::previous()
{
setTime( currentTime - skipTime );
emit previousTriggered();
}
void QPlayControl::next()
{
setTime( currentTime + skipTime );
emit nextTriggered();
}
void QPlayControl::updateSlowMotion( int idx )
{
slomoFactor = slowMotionBox->itemData( idx ).toDouble();
emit slowMotionChanged( slowMotionBox->itemData( idx ).toInt() );
}
void QPlayControl::updateSlider( int value )
{
setTime( value / 1000.0 );
emit sliderChanged( value );
}
void QPlayControl::timeout()
{
setTime( currentTime + slomoFactor * timer_delta( timer.seconds() ) );
}
<|endoftext|> |
<commit_before>#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
extern "C" {
#include <aes/aes.h>
};
#include <port.hpp>
#include <radio.hpp>
#include <interrupt/PCINT0.hpp>
#include <sensorvalue.hpp>
#include <common.hpp>
#include <packet.hpp>
#include "receiver.hpp"
#include "autoconfig.hpp"
#include "rfc2045.h"
static unsigned short magic;
static aes128_ctx_t aes_ctx;
static void txdata(unsigned char* data, unsigned char len);
void init()
{
Config config;
config.read();
radio::setup();
radio::setup_basic();
autoconfig(config);
radio::select();
for (auto c = config.radioconfig(); c->reg_ != 0xff; ++c) {
radio::set(c->reg(), c->value);
}
radio::setup_for_rx();
radio::set(CC1101::IOCFG2, 0x7);
radio::set(CC1101::IOCFG1, 0x7);
radio::release();
magic = config.magic();
aes128_init(config.key(), &aes_ctx);
}
static void txchr(unsigned char chr)
{
while (!usart::tx(chr)) {
}
}
static void txdata(unsigned char* data, unsigned char len)
{
uint8_t b64[32];
uint8_t l = RFC2045::encode(data, len, b64);
for (uint8_t i = 0; i < l; ++i) {
txchr(b64[i]);
}
txchr('\r');
txchr('\n');
}
static void receive()
{
while (radio::USI::DI::is_set()) {
radio::select();
unsigned char rxbytes = radio::status(CC1101::RXBYTES);
if (rxbytes == sizeof(Radiopacket_status)) {
Radiopacket_status packet;
radio::read_rxfifo(packet.raw, sizeof(Radiopacket_status));
aes128_dec(packet.raw, &aes_ctx);
if (packet.magic != magic) {
return;
}
unsigned char* s = packet.raw + 2;
unsigned char* e = packet.raw + packet.len;
char rssi = packet.rssi;
unsigned char lqi = packet.lqi;
e += SensorValue::RSSI::encode(static_cast<int>(rssi), e);
e += SensorValue::LQI::encode(static_cast<int>(lqi & 0x7f), e);
packet.len = e - s;
txdata(s, packet.len);
} else {
unsigned char d[rxbytes];
radio::read_rxfifo(d, rxbytes);
}
}
}
static void receive_loop()
{
radio::select();
radio::wcmd(CC1101::SRX);
radio::release();
PCINT0Interrupt::set(receive);
while(1) {
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_mode();
PCINT0Interrupt::pending();
}
}
/*{{{ uart */
ISR(USART_RX_vect)
{
usart::rx_ready();
}
ISR(USART_UDRE_vect)
{
usart::tx_ready();
}/*}}}*/
int main()
{
init();
usart::init();
PCICR |= _BV(PCIE0);
PCMSK0 |= _BV(radio::USI::DI::pin);
sei();
receive_loop();
}
template<>
usart::rxfifo_t usart::rxfifo = usart::rxfifo_t();
template<>
usart::txfifo_t usart::txfifo = usart::txfifo_t();
<commit_msg>receiver: better interrupt race handling<commit_after>#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
extern "C" {
#include <aes/aes.h>
};
#include <port.hpp>
#include <radio.hpp>
#include <interrupt/PCINT0.hpp>
#include <sensorvalue.hpp>
#include <common.hpp>
#include <packet.hpp>
#include "receiver.hpp"
#include "autoconfig.hpp"
#include "rfc2045.h"
static unsigned short magic;
static aes128_ctx_t aes_ctx;
static void txdata(unsigned char* data, unsigned char len);
void init()
{
Config config;
config.read();
radio::setup();
radio::setup_basic();
autoconfig(config);
radio::select();
for (auto c = config.radioconfig(); c->reg_ != 0xff; ++c) {
radio::set(c->reg(), c->value);
}
radio::setup_for_rx();
radio::set(CC1101::IOCFG2, 0x7);
radio::set(CC1101::IOCFG1, 0x7);
radio::release();
magic = config.magic();
aes128_init(config.key(), &aes_ctx);
}
static void txchr(unsigned char chr)
{
while (!usart::tx(chr)) {
}
}
static void txdata(unsigned char* data, unsigned char len)
{
uint8_t b64[32];
uint8_t l = RFC2045::encode(data, len, b64);
for (uint8_t i = 0; i < l; ++i) {
txchr(b64[i]);
}
txchr('\r');
txchr('\n');
}
static void receive()
{
while (radio::USI::DI::is_set()) {
radio::select();
unsigned char rxbytes = radio::status(CC1101::RXBYTES);
if (rxbytes == sizeof(Radiopacket_status)) {
Radiopacket_status packet;
radio::read_rxfifo(packet.raw, sizeof(Radiopacket_status));
aes128_dec(packet.raw, &aes_ctx);
if (packet.magic != magic) {
return;
}
unsigned char* s = packet.raw + 2;
unsigned char* e = packet.raw + packet.len;
char rssi = packet.rssi;
unsigned char lqi = packet.lqi;
e += SensorValue::RSSI::encode(static_cast<int>(rssi), e);
e += SensorValue::LQI::encode(static_cast<int>(lqi & 0x7f), e);
packet.len = e - s;
txdata(s, packet.len);
} else {
unsigned char d[rxbytes];
radio::read_rxfifo(d, rxbytes);
}
}
}
static void receive_loop()
{
radio::select();
radio::wcmd(CC1101::SRX);
radio::release();
PCINT0Interrupt::set(receive);
set_sleep_mode(SLEEP_MODE_IDLE);
while(1) {
cli();
if (PCINT0Interrupt::fire_ == false) {
sleep_enable();
sei();
sleep_cpu();
sleep_disable();
} else {
sei();
PCINT0Interrupt::pending();
}
}
}
/*{{{ uart */
ISR(USART_RX_vect)
{
usart::rx_ready();
}
ISR(USART_UDRE_vect)
{
usart::tx_ready();
}/*}}}*/
int main()
{
init();
usart::init();
PCICR |= _BV(PCIE0);
PCMSK0 |= _BV(radio::USI::DI::pin);
sei();
receive_loop();
}
template<>
usart::rxfifo_t usart::rxfifo = usart::rxfifo_t();
template<>
usart::txfifo_t usart::txfifo = usart::txfifo_t();
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <map>
#include "numhop.h"
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
// Local variable storage wrapper class
// local means local variables in this application,
// they are seen as external variables inside libnumhop
class ApplicationVariables : public numhop::ExternalVariableStorage
{
public:
// Overloaded -----
double externalValue(std::string name, bool &rFound) const
{
std::map<std::string, double>::const_iterator it = mVars.find(name);
if (it != mVars.end()) {
rFound = true;
return mVars.at(name);
}
rFound = false;
return 0;
}
bool setExternalValue(std::string name, double value)
{
std::map<std::string, double>::iterator it = mVars.find(name);
if (it != mVars.end()) {
it->second = value;
return true;
}
return false;
}
// -----
void addVariable(std::string name, double value)
{
mVars.insert(std::pair<std::string,double>(name, value));
}
double& operator[](const std::string& name)
{
return mVars[name];
}
private:
std::map<std::string, double> mVars;
};
void test_allok(const std::string &exprs, const double expected_result, numhop::VariableStorage &variableStorage){
std::list<std::string> exprlist;
numhop::extractExpressionRows(exprs, '#', exprlist);
INFO("Full expression: " << exprs);
double value_first_time, value_second_time;
std::list<std::string>::iterator it;
for (it=exprlist.begin(); it!=exprlist.end(); ++it) {
INFO("Current sub expression: " << *it);
numhop::Expression e;
bool interpretOK = numhop::interpretExpressionStringRecursive(*it, e);
REQUIRE(interpretOK == true);
bool first_eval_ok, second_eval_ok;;
value_first_time = e.evaluate(variableStorage, first_eval_ok);
REQUIRE(first_eval_ok == true);
// evaluate again, should give same result
value_second_time = e.evaluate(variableStorage, second_eval_ok);
REQUIRE(second_eval_ok == true);
REQUIRE(value_first_time == value_second_time);
}
REQUIRE(value_first_time == Approx(expected_result));
}
void test_interpret_fail(const std::string &expr)
{
INFO("Full expression: " << expr);
numhop::Expression e;
bool interpretOK = numhop::interpretExpressionStringRecursive(expr, e);
REQUIRE(interpretOK == false);
//todo what happens if e is evaluated ?
}
void test_eval_fail(const std::string &expr, numhop::VariableStorage &variableStorage)
{
INFO("Full expression: " << expr);
numhop::Expression e;
bool interpretOK = numhop::interpretExpressionStringRecursive(expr, e);
REQUIRE(interpretOK == true);
bool first_eval_ok;
double value_first_time = e.evaluate(variableStorage, first_eval_ok);
REQUIRE(first_eval_ok == false);
}
TEST_CASE("Variable Assignment") {
numhop::VariableStorage vs;
test_allok("a=5;a=8;a;", 8, vs);
test_allok("a=6;\n a=7.14\n a;", 7.14, vs);
}
TEST_CASE("External Variables") {
numhop::VariableStorage vs;
ApplicationVariables av;
av.addVariable("dog", 55);
av.addVariable("cat", 66);
vs.setExternalStorage(&av);
test_allok("dog", 55, vs);
test_allok("cat", 66, vs);
test_allok("dog=4; 1-(-2-3-(-dog-5.1))", -3.1, vs);
test_allok("-dog", -4, vs);
REQUIRE(av["dog"] == 4);
test_allok("cat \n dog \r dog=5;cat=2.1;a=3;b=dog*cat*a;b", 31.5, vs);
REQUIRE(av["cat"] == 2.1);
}
TEST_CASE("Reserved Variable") {
numhop::VariableStorage vs;
vs.reserveVariable("pi", 3.1415);
ApplicationVariables av;
vs.setExternalStorage(&av);
// Add external pi variable
av.addVariable("pi", 10000);
// Here the reserved pi should be used, not the external one
test_allok("pi", 3.1415, vs);
test_allok("a=pi*2", 6.283, vs);
// It should not be possible to change the external pi, or the reserved value
test_eval_fail("pi=123", vs);
test_allok("pi", 3.1415, vs);
REQUIRE(av["pi"] == 10000 );
}
TEST_CASE("Expression Parsing") {
numhop::VariableStorage vs;
std::string expr = " \t # \n a=5;\n # a=8\n a+1; \r\n a+2 \r a+3 \r\n #Some comment ";
// Extract individual expression rows, treat # as comment
// ; \r \n breaks lines
// The expression above contains 4 actual valid sub expressions
std::list<std::string> exprlist;
numhop::extractExpressionRows(expr, '#', exprlist);
REQUIRE(exprlist.size() == 4);
// Result should be a+3 with a = 5
test_allok(expr, 8, vs);
}
TEST_CASE("Various Math") {
numhop::VariableStorage vs;
test_allok("2^2", 4, vs);
test_allok("2^(1+1)", 4, vs);
test_allok("7/3/4/5", 0.11666667, vs);
test_allok("7/(3/(4/5))", 1.8666667, vs);
test_allok("(4/3*14*7/3/4/5*5/(4*3/2))", 1.8148148148148147, vs);
test_allok("1-2*3-3*4-4*5;", -37, vs);
test_allok("1-(-2-3-(-4-5))", -3, vs);
test_allok("-1-2-3*4-4-3", -22, vs);
test_allok("-1-(2-3)*4-4-3", -4, vs);
test_allok("-(((-2-2)-3)*4)", 28, vs);
// Test use of multiple + -
test_allok("2--3;", 5, vs);
test_allok("1+-3", -2, vs);
test_allok("1-+3", -2, vs);
test_allok("1++3", 4, vs);
test_allok("1---3", -2, vs);
test_allok("a=1;b=2;c=3;d=a+b*c;d",7, vs);
// Reuse b and a from last expression (stored in vs)
test_allok("b^b;", 4, vs);
test_allok("b^(a+a)", 4, vs);
test_allok("a-b;", -1, vs);
test_allok("a-b+a", 0, vs);
test_allok("-a+b", 1, vs);
test_allok("b-a;", 1, vs);
test_allok("(-a)+b", 1, vs);
test_allok("b+(-a);", 1, vs);
test_allok("b+(+a)", 3, vs);
test_allok("b+a", 3, vs);
test_allok("+a", 1, vs);
test_allok("0-(a-b)+b", 3, vs);
test_allok("a=1;b=2;c=3;d=4; a-b+c-d+a", -1, vs);
test_allok("a=1;b=2;c=3;d=4; a-b-c-d+a", -7, vs);
test_allok("a=1;b=2;c=3;d=4;a=(3+b)+4^2*c^(2+d)-7*(d-1)", 11648, vs);
// Reuse resulting a from last expression
test_allok("b=2;c=3;d=4;a=(3+b)+4^2*c^(2+d)-7/6/5*(d-1)", 11668.299999999999, vs);
test_allok("value=5;", 5, vs);
test_allok("value+2;", 7, vs);
test_allok("value-2", 3, vs);
test_allok("value*1e+2", 500, vs);
}
TEST_CASE("Exponential Notation") {
numhop::VariableStorage vs;
test_allok("2e-2-1E-2", 0.01, vs);
test_allok("1e+2+3E+2", 400, vs);
test_allok("1e2+1E2", 200, vs);
}
TEST_CASE("Boolean Expressions") {
numhop::VariableStorage vs;
test_allok("2<3", 1, vs);
test_allok("2<2", 0, vs);
test_allok("4.2>2.5", 1, vs);
// Note the difference on how the minus sign is interpreted
test_allok("(-4.2)>3", 0, vs);
// In this second case, the expression is treated as -(4.2>3)
test_allok("-4.2>3", -1, vs);
test_allok("1|0", 1, vs);
test_allok("0|0", 0, vs);
test_allok("0|0|0|1", 1, vs);
test_allok("1|1|1|1|1", 1, vs);
test_allok("2|3|0", 1, vs);
test_allok("(-2)|3", 1, vs);
test_allok("(-1)|(-2)", 0, vs);
test_allok("1&0", 0, vs);
test_allok("0&0", 0, vs);
test_allok("(-1)&1.5", 0, vs);
test_allok("1&1", 1, vs);
test_allok("1&1&1&0.4", 0, vs);
test_allok("1&0&1", 0, vs);
test_allok("2<3 | 4<2", 1, vs);
test_allok("2<3 & 4<2", 0, vs);
test_allok("2<3 & 4>2", 1, vs);
test_allok("x=2.5; (x>2&x<3)*1+(x>3&x<4)*2", 1, vs);
test_allok("x=3.6; (x>2&x<3)*1+(x>3&x<4)*2", 2, vs);
}
TEST_CASE("Expressions that should fail") {
numhop::VariableStorage vs;
test_interpret_fail("2*-2");
test_interpret_fail("a += 5");
test_interpret_fail("1+1-");
test_interpret_fail(" = 5");
test_eval_fail("0.5huj", vs);
}
<commit_msg>Add test for named value and valid variable name extraction<commit_after>#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <map>
#include "numhop.h"
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
// Local variable storage wrapper class
// local means local variables in this application,
// they are seen as external variables inside libnumhop
class ApplicationVariables : public numhop::ExternalVariableStorage
{
public:
// Overloaded -----
double externalValue(std::string name, bool &rFound) const
{
std::map<std::string, double>::const_iterator it = mVars.find(name);
if (it != mVars.end()) {
rFound = true;
return mVars.at(name);
}
rFound = false;
return 0;
}
bool setExternalValue(std::string name, double value)
{
std::map<std::string, double>::iterator it = mVars.find(name);
if (it != mVars.end()) {
it->second = value;
return true;
}
return false;
}
// -----
void addVariable(std::string name, double value)
{
mVars.insert(std::pair<std::string,double>(name, value));
}
double& operator[](const std::string& name)
{
return mVars[name];
}
private:
std::map<std::string, double> mVars;
};
void test_allok(const std::string &exprs, const double expected_result, numhop::VariableStorage &variableStorage){
std::list<std::string> exprlist;
numhop::extractExpressionRows(exprs, '#', exprlist);
INFO("Full expression: " << exprs);
double value_first_time, value_second_time;
std::list<std::string>::iterator it;
for (it=exprlist.begin(); it!=exprlist.end(); ++it) {
INFO("Current sub expression: " << *it);
numhop::Expression e;
bool interpretOK = numhop::interpretExpressionStringRecursive(*it, e);
REQUIRE(interpretOK == true);
bool first_eval_ok, second_eval_ok;;
value_first_time = e.evaluate(variableStorage, first_eval_ok);
REQUIRE(first_eval_ok == true);
// evaluate again, should give same result
value_second_time = e.evaluate(variableStorage, second_eval_ok);
REQUIRE(second_eval_ok == true);
REQUIRE(value_first_time == value_second_time);
}
REQUIRE(value_first_time == Approx(expected_result));
}
void test_interpret_fail(const std::string &expr)
{
INFO("Full expression: " << expr);
numhop::Expression e;
bool interpretOK = numhop::interpretExpressionStringRecursive(expr, e);
REQUIRE(interpretOK == false);
//todo what happens if e is evaluated ?
}
void test_eval_fail(const std::string &expr, numhop::VariableStorage &variableStorage)
{
INFO("Full expression: " << expr);
numhop::Expression e;
bool interpretOK = numhop::interpretExpressionStringRecursive(expr, e);
REQUIRE(interpretOK == true);
bool first_eval_ok;
double value_first_time = e.evaluate(variableStorage, first_eval_ok);
REQUIRE(first_eval_ok == false);
}
void test_extract_variablenames(const std::string &expr, numhop::VariableStorage &variableStorage, std::list<std::string> expectednames, std::list<std::string> expectedvalidvars)
{
std::set<std::string> valuenames, validvarnames;
numhop::Expression e;
bool interpretOK = numhop::interpretExpressionStringRecursive(expr, e);
REQUIRE(interpretOK == true);
e.extractNamedValues(valuenames);
std::list<std::string>::iterator it;
for (it=expectednames.begin(); it!=expectednames.end(); ++it) {
bool foundExpected = valuenames.find(*it)!=valuenames.end();
if (!foundExpected) {
std::string msg = "Did not find expected value name: ";
msg += *it;
FAIL(msg.c_str());
}
}
REQUIRE(valuenames.size() == expectednames.size());
e.extractValidVariableNames(variableStorage, validvarnames);
REQUIRE(expectedvalidvars.size() == validvarnames.size());
for (it=expectedvalidvars.begin(); it!=expectedvalidvars.end(); ++it) {
bool foundExpected = validvarnames.find(*it)!=validvarnames.end();
if (!foundExpected) {
std::string msg = "Did not find expected variable: ";
msg += *it;
FAIL(msg.c_str());
}
}
}
TEST_CASE("Variable Assignment") {
numhop::VariableStorage vs;
test_allok("a=5;a=8;a;", 8, vs);
test_allok("a=6;\n a=7.14\n a;", 7.14, vs);
}
TEST_CASE("External Variables") {
numhop::VariableStorage vs;
ApplicationVariables av;
av.addVariable("dog", 55);
av.addVariable("cat", 66);
vs.setExternalStorage(&av);
test_allok("dog", 55, vs);
test_allok("cat", 66, vs);
test_allok("dog=4; 1-(-2-3-(-dog-5.1))", -3.1, vs);
test_allok("-dog", -4, vs);
REQUIRE(av["dog"] == 4);
test_allok("cat \n dog \r dog=5;cat=2.1;a=3;b=dog*cat*a;b", 31.5, vs);
REQUIRE(av["cat"] == 2.1);
}
TEST_CASE("Reserved Variable") {
numhop::VariableStorage vs;
vs.reserveNamedValue("pi", 3.1415);
ApplicationVariables av;
vs.setExternalStorage(&av);
// Add external pi variable
av.addVariable("pi", 10000);
// Here the reserved pi should be used, not the external one
test_allok("pi", 3.1415, vs);
test_allok("a=pi*2", 6.283, vs);
// It should not be possible to change the external pi, or the reserved value
test_eval_fail("pi=123", vs);
test_allok("pi", 3.1415, vs);
REQUIRE(av["pi"] == 10000 );
}
TEST_CASE("Expression Parsing") {
numhop::VariableStorage vs;
std::string expr = " \t # \n a=5;\n # a=8\n a+1; \r\n a+2 \r a+3 \r\n #Some comment ";
// Extract individual expression rows, treat # as comment
// ; \r \n breaks lines
// The expression above contains 4 actual valid sub expressions
std::list<std::string> exprlist;
numhop::extractExpressionRows(expr, '#', exprlist);
REQUIRE(exprlist.size() == 4);
// Result should be a+3 with a = 5
test_allok(expr, 8, vs);
}
TEST_CASE("Various Math") {
numhop::VariableStorage vs;
test_allok("2^2", 4, vs);
test_allok("2^(1+1)", 4, vs);
test_allok("7/3/4/5", 0.11666667, vs);
test_allok("7/(3/(4/5))", 1.8666667, vs);
test_allok("(4/3*14*7/3/4/5*5/(4*3/2))", 1.8148148148148147, vs);
test_allok("1-2*3-3*4-4*5;", -37, vs);
test_allok("1-(-2-3-(-4-5))", -3, vs);
test_allok("-1-2-3*4-4-3", -22, vs);
test_allok("-1-(2-3)*4-4-3", -4, vs);
test_allok("-(((-2-2)-3)*4)", 28, vs);
// Test use of multiple + -
test_allok("2--3;", 5, vs);
test_allok("1+-3", -2, vs);
test_allok("1-+3", -2, vs);
test_allok("1++3", 4, vs);
test_allok("1---3", -2, vs);
test_allok("a=1;b=2;c=3;d=a+b*c;d",7, vs);
// Reuse b and a from last expression (stored in vs)
test_allok("b^b;", 4, vs);
test_allok("b^(a+a)", 4, vs);
test_allok("a-b;", -1, vs);
test_allok("a-b+a", 0, vs);
test_allok("-a+b", 1, vs);
test_allok("b-a;", 1, vs);
test_allok("(-a)+b", 1, vs);
test_allok("b+(-a);", 1, vs);
test_allok("b+(+a)", 3, vs);
test_allok("b+a", 3, vs);
test_allok("+a", 1, vs);
test_allok("0-(a-b)+b", 3, vs);
test_allok("a=1;b=2;c=3;d=4; a-b+c-d+a", -1, vs);
test_allok("a=1;b=2;c=3;d=4; a-b-c-d+a", -7, vs);
test_allok("a=1;b=2;c=3;d=4;a=(3+b)+4^2*c^(2+d)-7*(d-1)", 11648, vs);
// Reuse resulting a from last expression
test_allok("b=2;c=3;d=4;a=(3+b)+4^2*c^(2+d)-7/6/5*(d-1)", 11668.299999999999, vs);
test_allok("value=5;", 5, vs);
test_allok("value+2;", 7, vs);
test_allok("value-2", 3, vs);
test_allok("value*1e+2", 500, vs);
}
TEST_CASE("Exponential Notation") {
numhop::VariableStorage vs;
test_allok("2e-2-1E-2", 0.01, vs);
test_allok("1e+2+3E+2", 400, vs);
test_allok("1e2+1E2", 200, vs);
}
TEST_CASE("Boolean Expressions") {
numhop::VariableStorage vs;
test_allok("2<3", 1, vs);
test_allok("2<2", 0, vs);
test_allok("4.2>2.5", 1, vs);
// Note the difference on how the minus sign is interpreted
test_allok("(-4.2)>3", 0, vs);
// In this second case, the expression is treated as -(4.2>3)
test_allok("-4.2>3", -1, vs);
test_allok("1|0", 1, vs);
test_allok("0|0", 0, vs);
test_allok("0|0|0|1", 1, vs);
test_allok("1|1|1|1|1", 1, vs);
test_allok("2|3|0", 1, vs);
test_allok("(-2)|3", 1, vs);
test_allok("(-1)|(-2)", 0, vs);
test_allok("1&0", 0, vs);
test_allok("0&0", 0, vs);
test_allok("(-1)&1.5", 0, vs);
test_allok("1&1", 1, vs);
test_allok("1&1&1&0.4", 0, vs);
test_allok("1&0&1", 0, vs);
test_allok("2<3 | 4<2", 1, vs);
test_allok("2<3 & 4<2", 0, vs);
test_allok("2<3 & 4>2", 1, vs);
test_allok("x=2.5; (x>2&x<3)*1+(x>3&x<4)*2", 1, vs);
test_allok("x=3.6; (x>2&x<3)*1+(x>3&x<4)*2", 2, vs);
}
TEST_CASE("Extract variable names") {
numhop::VariableStorage vs;
vs.reserveNamedValue("pi", 3.1415);
bool setOK;
vs.setVariable("ivar1", 1, setOK);
vs.setVariable("ivar2", 2, setOK);
ApplicationVariables av;
av.addVariable("evar1", 1);
av.addVariable("evar2", 2);
vs.setExternalStorage(&av);
std::list<std::string> expectedNamedValues, expectedValidVariableNames;
expectedNamedValues.push_back("ivar1");
expectedValidVariableNames = expectedNamedValues;
test_extract_variablenames("ivar1", vs, expectedNamedValues, expectedValidVariableNames);
test_extract_variablenames("-ivar1", vs, expectedNamedValues, expectedValidVariableNames);
expectedNamedValues.push_back("ivar2");
expectedNamedValues.push_back("evar1");
expectedNamedValues.push_back("evar2");
expectedNamedValues.push_back("pi");
expectedNamedValues.push_back("invalid");
expectedValidVariableNames = expectedNamedValues;
// remove pi and invalid
expectedValidVariableNames.pop_back();
expectedValidVariableNames.pop_back();
const char* expr = "ivar2 = (ivar1 + evar1 + evar2 -3*ivar1)*pi^invalid";
test_extract_variablenames(expr, vs, expectedNamedValues, expectedValidVariableNames);
}
TEST_CASE("Expressions that should fail") {
numhop::VariableStorage vs;
test_interpret_fail("2*-2");
test_interpret_fail("a += 5");
test_interpret_fail("1+1-");
test_interpret_fail(" = 5");
test_eval_fail("0.5huj", vs);
}
<|endoftext|> |
<commit_before>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <tightdb/column.hpp>
#if defined(_MSC_VER) && defined(_DEBUG)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
int main(int argc, char* argv[])
{
bool const no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exit-staus") == 0;
#ifdef TIGHTDB_DEBUG
cout << "Running Debug unit tests\n\n";
#else
cout << "Running Release unit tests\n\n";
#endif
const int res = UnitTest::RunAllTests();
#ifdef _MSC_VER
getchar(); // wait for key
#endif
return no_error_exit_staus ? 0 : res;
}<commit_msg>...........<commit_after>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <tightdb/utilities.hpp>
#if defined(_MSC_VER) && defined(_DEBUG)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
int main(int argc, char* argv[])
{
bool const no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exit-staus") == 0;
#ifdef TIGHTDB_DEBUG
cout << "Running Debug unit tests\n";
#else
cout << "Running Release unit tests\n";
#endif
#ifdef TIGHTDB_COMPILER_SSE
cout << "Compiler supported SSE (auto detect): Yes\n";
#else
cout << "Compiler supported SSE (auto detect): No\n";
#endif
cout << "This CPU supports SSE (auto detect): " << (tightdb::cpuid_sse<42>() ? "4.2" : (tightdb::cpuid_sse<30>() ? "3.0" : "None"));
cout << "\n\n";
const int res = UnitTest::RunAllTests();
#ifdef _MSC_VER
getchar(); // wait for key
#endif
return no_error_exit_staus ? 0 : res;
}<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QAbstractItemView>
#include <QDebug>
#include <QDesktopWidget>
#include <QItemDelegate>
#include <QLayout>
#include <QMouseEvent>
#include <QMenu>
#include <QPainter>
#include <QPointer>
#include <QPushButton>
#include <QStandardItemModel>
#include <QStyle>
#include <QStyleOptionButton>
#include <QStylePainter>
#include <QToolBar>
// CTK includes
#include "ctkCheckableComboBox.h"
#include <ctkCheckableModelHelper.h>
// Similar to QComboBoxDelegate
class ctkComboBoxDelegate : public QItemDelegate
{
public:
ctkComboBoxDelegate(QObject *parent, QComboBox *cmb)
: QItemDelegate(parent), ComboBox(cmb)
{}
static bool isSeparator(const QModelIndex &index)
{
return index.data(Qt::AccessibleDescriptionRole).toString() == QLatin1String("separator");
}
static void setSeparator(QAbstractItemModel *model, const QModelIndex &index)
{
model->setData(index, QString::fromLatin1("separator"), Qt::AccessibleDescriptionRole);
if (QStandardItemModel *m = qobject_cast<QStandardItemModel*>(model))
{
if (QStandardItem *item = m->itemFromIndex(index))
{
item->setFlags(item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled));
}
}
}
protected:
void paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (isSeparator(index))
{
QRect rect = option.rect;
if (const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3*>(&option))
{
if (const QAbstractItemView *view = qobject_cast<const QAbstractItemView*>(v3->widget))
{
rect.setWidth(view->viewport()->width());
}
}
QStyleOption opt;
opt.rect = rect;
this->ComboBox->style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &opt, painter, this->ComboBox);
}
else
{
QItemDelegate::paint(painter, option, index);
}
}
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (isSeparator(index))
{
int pm = this->ComboBox->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, this->ComboBox);
return QSize(pm, pm);
}
return this->QItemDelegate::sizeHint(option, index);
}
private:
QComboBox* ComboBox;
};
//-----------------------------------------------------------------------------
class ctkCheckableComboBoxPrivate
{
Q_DECLARE_PUBLIC(ctkCheckableComboBox);
protected:
ctkCheckableComboBox* const q_ptr;
QModelIndexList checkedIndexes()const;
QModelIndexList uncheckedIndexes()const;
public:
ctkCheckableComboBoxPrivate(ctkCheckableComboBox& object);
void init();
QModelIndexList cachedCheckedIndexes()const;
void updateCheckedList();
ctkCheckableModelHelper* CheckableModelHelper;
bool MouseButtonPressed;
private:
QModelIndexList persistentIndexesToModelIndexes(
const QList<QPersistentModelIndex>& persistentModels)const;
QList<QPersistentModelIndex> modelIndexesToPersistentIndexes(
const QModelIndexList& modelIndexes)const;
mutable QList<QPersistentModelIndex> CheckedList;
};
//-----------------------------------------------------------------------------
ctkCheckableComboBoxPrivate::ctkCheckableComboBoxPrivate(ctkCheckableComboBox& object)
: q_ptr(&object)
{
this->CheckableModelHelper = 0;
this->MouseButtonPressed = false;
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBoxPrivate::init()
{
Q_Q(ctkCheckableComboBox);
this->CheckableModelHelper = new ctkCheckableModelHelper(Qt::Horizontal, q);
this->CheckableModelHelper->setForceCheckability(true);
q->setCheckableModel(q->model());
q->view()->installEventFilter(q);
q->view()->viewport()->installEventFilter(q);
// QCleanLooksStyle uses a delegate that doesn't show the checkboxes in the
// popup list.
q->setItemDelegate(new ctkComboBoxDelegate(q->view(), q));
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBoxPrivate::updateCheckedList()
{
Q_Q(ctkCheckableComboBox);
QList<QPersistentModelIndex> newCheckedPersistentList =
this->modelIndexesToPersistentIndexes(this->checkedIndexes());
if (newCheckedPersistentList == this->CheckedList)
{
return;
}
this->CheckedList = newCheckedPersistentList;
emit q->checkedIndexesChanged();
}
//-----------------------------------------------------------------------------
QList<QPersistentModelIndex> ctkCheckableComboBoxPrivate
::modelIndexesToPersistentIndexes(const QModelIndexList& indexes)const
{
QList<QPersistentModelIndex> res;
foreach(const QModelIndex& index, indexes)
{
QPersistentModelIndex persistent(index);
if (persistent.isValid())
{
res << persistent;
}
}
return res;
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate
::persistentIndexesToModelIndexes(
const QList<QPersistentModelIndex>& indexes)const
{
QModelIndexList res;
foreach(const QPersistentModelIndex& index, indexes)
{
if (index.isValid())
{
res << index;
}
}
return res;
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate::cachedCheckedIndexes()const
{
return this->persistentIndexesToModelIndexes(this->CheckedList);
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate::checkedIndexes()const
{
Q_Q(const ctkCheckableComboBox);
QModelIndex startIndex = q->model()->index(0,0, q->rootModelIndex());
return q->model()->match(
startIndex, Qt::CheckStateRole,
static_cast<int>(Qt::Checked), -1, Qt::MatchRecursive);
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate::uncheckedIndexes()const
{
Q_Q(const ctkCheckableComboBox);
QModelIndex startIndex = q->model()->index(0,0, q->rootModelIndex());
return q->model()->match(
startIndex, Qt::CheckStateRole,
static_cast<int>(Qt::Unchecked), -1, Qt::MatchRecursive);
}
//-----------------------------------------------------------------------------
ctkCheckableComboBox::ctkCheckableComboBox(QWidget* parentWidget)
: QComboBox(parentWidget)
, d_ptr(new ctkCheckableComboBoxPrivate(*this))
{
Q_D(ctkCheckableComboBox);
d->init();
}
//-----------------------------------------------------------------------------
ctkCheckableComboBox::~ctkCheckableComboBox()
{
}
//-----------------------------------------------------------------------------
bool ctkCheckableComboBox::eventFilter(QObject *o, QEvent *e)
{
Q_D(ctkCheckableComboBox);
switch (e->type())
{
case QEvent::MouseButtonPress:
{
if (this->view()->isVisible())
{
d->MouseButtonPressed = true;
}
break;
}
case QEvent::MouseButtonRelease:
{
QMouseEvent *m = static_cast<QMouseEvent *>(e);
if (this->view()->isVisible() &&
this->view()->rect().contains(m->pos()) &&
this->view()->currentIndex().isValid()
//&& !blockMouseReleaseTimer.isActive()
&& (this->view()->currentIndex().flags() & Qt::ItemIsEnabled)
&& (this->view()->currentIndex().flags() & Qt::ItemIsSelectable))
{
// The signal to open the menu is fired when the mouse button is
// pressed, we don't want to toggle the item under the mouse cursor
// when the button used to open the popup is released.
if (d->MouseButtonPressed)
{
// make the item current, it will then call QComboBox::update (and
// repaint) when the current index data is changed (checkstate
// toggled fires dataChanged signal which is observed).
this->setCurrentIndex(this->view()->currentIndex().row());
d->CheckableModelHelper->toggleCheckState(this->view()->currentIndex());
}
d->MouseButtonPressed = false;
return true;
}
d->MouseButtonPressed = false;
break;
}
default:
break;
}
return this->QComboBox::eventFilter(o, e);
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::setCheckableModel(QAbstractItemModel* newModel)
{
Q_D(ctkCheckableComboBox);
this->disconnect(this->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(onDataChanged(QModelIndex,QModelIndex)));
if (newModel != this->model())
{
this->setModel(newModel);
}
this->connect(this->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(onDataChanged(QModelIndex,QModelIndex)));
d->CheckableModelHelper->setModel(newModel);
d->updateCheckedList();
}
//-----------------------------------------------------------------------------
QAbstractItemModel* ctkCheckableComboBox::checkableModel()const
{
return this->model();
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBox::checkedIndexes()const
{
Q_D(const ctkCheckableComboBox);
return d->cachedCheckedIndexes();
}
//-----------------------------------------------------------------------------
bool ctkCheckableComboBox::allChecked()const
{
Q_D(const ctkCheckableComboBox);
return d->uncheckedIndexes().count() == 0;
}
//-----------------------------------------------------------------------------
bool ctkCheckableComboBox::noneChecked()const
{
Q_D(const ctkCheckableComboBox);
return d->cachedCheckedIndexes().count() == 0;
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::setCheckState(const QModelIndex& index, Qt::CheckState check)
{
Q_D(ctkCheckableComboBox);
return d->CheckableModelHelper->setCheckState(index, check);
}
//-----------------------------------------------------------------------------
Qt::CheckState ctkCheckableComboBox::checkState(const QModelIndex& index)const
{
Q_D(const ctkCheckableComboBox);
return d->CheckableModelHelper->checkState(index);
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::onDataChanged(const QModelIndex& start, const QModelIndex& end)
{
Q_D(ctkCheckableComboBox);
Q_UNUSED(start);
Q_UNUSED(end);
d->updateCheckedList();
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::paintEvent(QPaintEvent *)
{
Q_D(ctkCheckableComboBox);
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));
// draw the combobox frame, focusrect and selected etc.
QStyleOptionComboBox opt;
this->initStyleOption(&opt);
if (this->allChecked())
{
opt.currentText = "All";
opt.currentIcon = QIcon();
}
else if (this->noneChecked())
{
opt.currentText = "None";
opt.currentIcon = QIcon();
}
else
{
//search the checked items
QModelIndexList indexes = d->cachedCheckedIndexes();
if (indexes.count() == 1)
{
opt.currentText = this->model()->data(indexes[0], Qt::DisplayRole).toString();
opt.currentIcon = qvariant_cast<QIcon>(this->model()->data(indexes[0], Qt::DecorationRole));
}
else
{
QStringList indexesText;
foreach(QModelIndex checkedIndex, indexes)
{
indexesText << this->model()->data(checkedIndex, Qt::DisplayRole).toString();
}
opt.currentText = indexesText.join(", ");
opt.currentIcon = QIcon();
}
}
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
// draw the icon and text
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
<commit_msg>ctkCheckableComboBox: implemented missing method checkableModelHelper()<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QAbstractItemView>
#include <QDebug>
#include <QDesktopWidget>
#include <QItemDelegate>
#include <QLayout>
#include <QMouseEvent>
#include <QMenu>
#include <QPainter>
#include <QPointer>
#include <QPushButton>
#include <QStandardItemModel>
#include <QStyle>
#include <QStyleOptionButton>
#include <QStylePainter>
#include <QToolBar>
// CTK includes
#include "ctkCheckableComboBox.h"
#include <ctkCheckableModelHelper.h>
// Similar to QComboBoxDelegate
class ctkComboBoxDelegate : public QItemDelegate
{
public:
ctkComboBoxDelegate(QObject *parent, QComboBox *cmb)
: QItemDelegate(parent), ComboBox(cmb)
{}
static bool isSeparator(const QModelIndex &index)
{
return index.data(Qt::AccessibleDescriptionRole).toString() == QLatin1String("separator");
}
static void setSeparator(QAbstractItemModel *model, const QModelIndex &index)
{
model->setData(index, QString::fromLatin1("separator"), Qt::AccessibleDescriptionRole);
if (QStandardItemModel *m = qobject_cast<QStandardItemModel*>(model))
{
if (QStandardItem *item = m->itemFromIndex(index))
{
item->setFlags(item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled));
}
}
}
protected:
void paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (isSeparator(index))
{
QRect rect = option.rect;
if (const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3*>(&option))
{
if (const QAbstractItemView *view = qobject_cast<const QAbstractItemView*>(v3->widget))
{
rect.setWidth(view->viewport()->width());
}
}
QStyleOption opt;
opt.rect = rect;
this->ComboBox->style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &opt, painter, this->ComboBox);
}
else
{
QItemDelegate::paint(painter, option, index);
}
}
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (isSeparator(index))
{
int pm = this->ComboBox->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, this->ComboBox);
return QSize(pm, pm);
}
return this->QItemDelegate::sizeHint(option, index);
}
private:
QComboBox* ComboBox;
};
//-----------------------------------------------------------------------------
class ctkCheckableComboBoxPrivate
{
Q_DECLARE_PUBLIC(ctkCheckableComboBox);
protected:
ctkCheckableComboBox* const q_ptr;
QModelIndexList checkedIndexes()const;
QModelIndexList uncheckedIndexes()const;
public:
ctkCheckableComboBoxPrivate(ctkCheckableComboBox& object);
void init();
QModelIndexList cachedCheckedIndexes()const;
void updateCheckedList();
ctkCheckableModelHelper* CheckableModelHelper;
bool MouseButtonPressed;
private:
QModelIndexList persistentIndexesToModelIndexes(
const QList<QPersistentModelIndex>& persistentModels)const;
QList<QPersistentModelIndex> modelIndexesToPersistentIndexes(
const QModelIndexList& modelIndexes)const;
mutable QList<QPersistentModelIndex> CheckedList;
};
//-----------------------------------------------------------------------------
ctkCheckableComboBoxPrivate::ctkCheckableComboBoxPrivate(ctkCheckableComboBox& object)
: q_ptr(&object)
{
this->CheckableModelHelper = 0;
this->MouseButtonPressed = false;
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBoxPrivate::init()
{
Q_Q(ctkCheckableComboBox);
this->CheckableModelHelper = new ctkCheckableModelHelper(Qt::Horizontal, q);
this->CheckableModelHelper->setForceCheckability(true);
q->setCheckableModel(q->model());
q->view()->installEventFilter(q);
q->view()->viewport()->installEventFilter(q);
// QCleanLooksStyle uses a delegate that doesn't show the checkboxes in the
// popup list.
q->setItemDelegate(new ctkComboBoxDelegate(q->view(), q));
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBoxPrivate::updateCheckedList()
{
Q_Q(ctkCheckableComboBox);
QList<QPersistentModelIndex> newCheckedPersistentList =
this->modelIndexesToPersistentIndexes(this->checkedIndexes());
if (newCheckedPersistentList == this->CheckedList)
{
return;
}
this->CheckedList = newCheckedPersistentList;
emit q->checkedIndexesChanged();
}
//-----------------------------------------------------------------------------
QList<QPersistentModelIndex> ctkCheckableComboBoxPrivate
::modelIndexesToPersistentIndexes(const QModelIndexList& indexes)const
{
QList<QPersistentModelIndex> res;
foreach(const QModelIndex& index, indexes)
{
QPersistentModelIndex persistent(index);
if (persistent.isValid())
{
res << persistent;
}
}
return res;
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate
::persistentIndexesToModelIndexes(
const QList<QPersistentModelIndex>& indexes)const
{
QModelIndexList res;
foreach(const QPersistentModelIndex& index, indexes)
{
if (index.isValid())
{
res << index;
}
}
return res;
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate::cachedCheckedIndexes()const
{
return this->persistentIndexesToModelIndexes(this->CheckedList);
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate::checkedIndexes()const
{
Q_Q(const ctkCheckableComboBox);
QModelIndex startIndex = q->model()->index(0,0, q->rootModelIndex());
return q->model()->match(
startIndex, Qt::CheckStateRole,
static_cast<int>(Qt::Checked), -1, Qt::MatchRecursive);
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBoxPrivate::uncheckedIndexes()const
{
Q_Q(const ctkCheckableComboBox);
QModelIndex startIndex = q->model()->index(0,0, q->rootModelIndex());
return q->model()->match(
startIndex, Qt::CheckStateRole,
static_cast<int>(Qt::Unchecked), -1, Qt::MatchRecursive);
}
//-----------------------------------------------------------------------------
ctkCheckableComboBox::ctkCheckableComboBox(QWidget* parentWidget)
: QComboBox(parentWidget)
, d_ptr(new ctkCheckableComboBoxPrivate(*this))
{
Q_D(ctkCheckableComboBox);
d->init();
}
//-----------------------------------------------------------------------------
ctkCheckableComboBox::~ctkCheckableComboBox()
{
}
//-----------------------------------------------------------------------------
bool ctkCheckableComboBox::eventFilter(QObject *o, QEvent *e)
{
Q_D(ctkCheckableComboBox);
switch (e->type())
{
case QEvent::MouseButtonPress:
{
if (this->view()->isVisible())
{
d->MouseButtonPressed = true;
}
break;
}
case QEvent::MouseButtonRelease:
{
QMouseEvent *m = static_cast<QMouseEvent *>(e);
if (this->view()->isVisible() &&
this->view()->rect().contains(m->pos()) &&
this->view()->currentIndex().isValid()
//&& !blockMouseReleaseTimer.isActive()
&& (this->view()->currentIndex().flags() & Qt::ItemIsEnabled)
&& (this->view()->currentIndex().flags() & Qt::ItemIsSelectable))
{
// The signal to open the menu is fired when the mouse button is
// pressed, we don't want to toggle the item under the mouse cursor
// when the button used to open the popup is released.
if (d->MouseButtonPressed)
{
// make the item current, it will then call QComboBox::update (and
// repaint) when the current index data is changed (checkstate
// toggled fires dataChanged signal which is observed).
this->setCurrentIndex(this->view()->currentIndex().row());
d->CheckableModelHelper->toggleCheckState(this->view()->currentIndex());
}
d->MouseButtonPressed = false;
return true;
}
d->MouseButtonPressed = false;
break;
}
default:
break;
}
return this->QComboBox::eventFilter(o, e);
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::setCheckableModel(QAbstractItemModel* newModel)
{
Q_D(ctkCheckableComboBox);
this->disconnect(this->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(onDataChanged(QModelIndex,QModelIndex)));
if (newModel != this->model())
{
this->setModel(newModel);
}
this->connect(this->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(onDataChanged(QModelIndex,QModelIndex)));
d->CheckableModelHelper->setModel(newModel);
d->updateCheckedList();
}
//-----------------------------------------------------------------------------
QAbstractItemModel* ctkCheckableComboBox::checkableModel()const
{
return this->model();
}
//-----------------------------------------------------------------------------
QModelIndexList ctkCheckableComboBox::checkedIndexes()const
{
Q_D(const ctkCheckableComboBox);
return d->cachedCheckedIndexes();
}
//-----------------------------------------------------------------------------
bool ctkCheckableComboBox::allChecked()const
{
Q_D(const ctkCheckableComboBox);
return d->uncheckedIndexes().count() == 0;
}
//-----------------------------------------------------------------------------
bool ctkCheckableComboBox::noneChecked()const
{
Q_D(const ctkCheckableComboBox);
return d->cachedCheckedIndexes().count() == 0;
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::setCheckState(const QModelIndex& index, Qt::CheckState check)
{
Q_D(ctkCheckableComboBox);
return d->CheckableModelHelper->setCheckState(index, check);
}
//-----------------------------------------------------------------------------
Qt::CheckState ctkCheckableComboBox::checkState(const QModelIndex& index)const
{
Q_D(const ctkCheckableComboBox);
return d->CheckableModelHelper->checkState(index);
}
//-----------------------------------------------------------------------------
ctkCheckableModelHelper* ctkCheckableComboBox::checkableModelHelper()const
{
Q_D(const ctkCheckableComboBox);
return d->CheckableModelHelper;
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::onDataChanged(const QModelIndex& start, const QModelIndex& end)
{
Q_D(ctkCheckableComboBox);
Q_UNUSED(start);
Q_UNUSED(end);
d->updateCheckedList();
}
//-----------------------------------------------------------------------------
void ctkCheckableComboBox::paintEvent(QPaintEvent *)
{
Q_D(ctkCheckableComboBox);
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));
// draw the combobox frame, focusrect and selected etc.
QStyleOptionComboBox opt;
this->initStyleOption(&opt);
if (this->allChecked())
{
opt.currentText = "All";
opt.currentIcon = QIcon();
}
else if (this->noneChecked())
{
opt.currentText = "None";
opt.currentIcon = QIcon();
}
else
{
//search the checked items
QModelIndexList indexes = d->cachedCheckedIndexes();
if (indexes.count() == 1)
{
opt.currentText = this->model()->data(indexes[0], Qt::DisplayRole).toString();
opt.currentIcon = qvariant_cast<QIcon>(this->model()->data(indexes[0], Qt::DecorationRole));
}
else
{
QStringList indexesText;
foreach(QModelIndex checkedIndex, indexes)
{
indexesText << this->model()->data(checkedIndex, Qt::DisplayRole).toString();
}
opt.currentText = indexesText.join(", ");
opt.currentIcon = QIcon();
}
}
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
// draw the icon and text
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QHBoxLayout>
#include <QDoubleSpinBox>
// CTK includes
#include "ctkCoordinatesWidget.h"
// STD includes
#include <cmath>
//------------------------------------------------------------------------------
ctkCoordinatesWidget::ctkCoordinatesWidget(QWidget* _parent) :QWidget(_parent)
{
this->Decimals = 3;
this->SingleStep = 1.;
this->Minimum = -100000.;
this->Maximum = 100000.;
this->Normalized = false;
this->Dimension = 3;
this->Coordinates = new double [this->Dimension];
QHBoxLayout* hboxLayout = new QHBoxLayout(this);
this->setLayout(hboxLayout);
for (int i = 0; i < this->Dimension; ++i)
{
this->Coordinates[i] = 0.;
this->addSpinBox();
}
hboxLayout->setContentsMargins(0, 0, 0, 0);
}
//------------------------------------------------------------------------------
ctkCoordinatesWidget::~ctkCoordinatesWidget()
{
delete [] this->Coordinates;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::addSpinBox()
{
QDoubleSpinBox* spinBox = new QDoubleSpinBox(this);
spinBox->setDecimals(this->Decimals);
spinBox->setSingleStep(this->SingleStep);
spinBox->setMinimum(this->Minimum);
spinBox->setMaximum(this->Maximum);
connect( spinBox, SIGNAL(valueChanged(double)),
this, SLOT(updateCoordinate(double)));
this->layout()->addWidget(spinBox);
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setDimension(int dim)
{
if (dim < 1)
{
return;
}
double* newPos = new double[dim];
if (dim > this->Dimension)
{
memcpy(newPos, this->Coordinates, this->Dimension * sizeof(double));
for (int i = this->Dimension; i < dim; ++i)
{
newPos[i] = 0.;
this->addSpinBox();
}
}
else
{
memcpy(newPos, this->Coordinates, dim * sizeof(double));
for (int i = this->Dimension - 1 ; i >= dim; --i)
{
QLayoutItem* item = this->layout()->takeAt(i);
QWidget* widget = item ? item->widget() : 0;
delete item;
delete widget;
}
}
delete [] this->Coordinates;
this->Coordinates = newPos;
this->Dimension = dim;
this->updateGeometry();
this->updateCoordinates();
}
//------------------------------------------------------------------------------
int ctkCoordinatesWidget::dimension() const
{
return this->Dimension;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setMinimum(double min)
{
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setMinimum(min);
}
}
this->Minimum = min;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::minimum() const
{
return this->Minimum;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setMaximum(double max)
{
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setMaximum(max);
}
}
this->Maximum = max;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::maximum() const
{
return this->Maximum;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setNormalized(bool normalized)
{
this->Normalized = normalized;
if (this->Normalized)
{
double normalizedCoordinates[this->Dimension];
memcpy(normalizedCoordinates, this->Coordinates, sizeof(double)*this->Dimension);
ctkCoordinatesWidget::normalize(normalizedCoordinates, this->Dimension);
this->setMinimum(-1.);
this->setMaximum(1.);
this->setCoordinates(normalizedCoordinates);
}
}
//------------------------------------------------------------------------------
bool ctkCoordinatesWidget::isNormalized() const
{
return this->Normalized;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setDecimals(int newDecimals)
{
this->Decimals = newDecimals;
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setDecimals(newDecimals);
}
}
}
//------------------------------------------------------------------------------
int ctkCoordinatesWidget::decimals() const
{
return this->Decimals;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setSingleStep(double step)
{
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setSingleStep(step);
}
}
this->SingleStep = step;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::singleStep() const
{
return this->SingleStep;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setCoordinatesAsString(QString _pos)
{
QStringList posList = _pos.split(',');
if (posList.count() != this->Dimension)
{
return;
}
double* newPos = new double[this->Dimension];
for (int i = 0; i < this->Dimension; ++i)
{
newPos[i] = posList[i].toDouble();
}
this->setCoordinates(newPos);
delete [] newPos;
}
//------------------------------------------------------------------------------
QString ctkCoordinatesWidget::coordinatesAsString()const
{
QString res;
for (int i = 0; i < this->Dimension; ++i)
{
if (i != 0)
{
res += ",";
}
res += QString::number(this->Coordinates[i]);
}
return res;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setCoordinates(double* coordinates)
{
for (int i = 0; i < this->Dimension; ++i)
{
this->Coordinates[i] = coordinates[i];
}
if (this->Normalized)
{
this->normalize(this->Coordinates, this->Dimension);
}
bool blocked = this->blockSignals(true);
for (int i = 0; i < this->Dimension; ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox =
item ? dynamic_cast<QDoubleSpinBox*>(item->widget()) : 0;
if (spinBox)
{
spinBox->setValue(this->Coordinates[i]);
}
}
this->blockSignals(blocked);
this->updateCoordinates();
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setCoordinates(double x, double y, double z, double w)
{
double coordinates[this->Dimension];
if (this->Dimension >= 1)
{
coordinates[0] = x;
}
if (this->Dimension >= 2)
{
coordinates[1] = y;
}
if (this->Dimension >= 3)
{
coordinates[2] = z;
}
if (this->Dimension >= 4)
{
coordinates[3] = w;
}
for (int i = 4; i < this->Dimension; ++i)
{
coordinates[i] = this->Coordinates[i];
}
this->setCoordinates(coordinates);
}
//------------------------------------------------------------------------------
double const * ctkCoordinatesWidget::coordinates()const
{
return this->Coordinates;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::updateCoordinate(double coordinate)
{
double den = 0.;
int element = -1;
for (int i = 0; i < this->Dimension; ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox =
item ? qobject_cast<QDoubleSpinBox*>(item->widget()) : 0;
if ( spinBox && spinBox == this->sender())
{
this->Coordinates[i] = coordinate;
element = i;
}
else
{
den += this->Coordinates[i]*this->Coordinates[i];
}
}
Q_ASSERT(element != -1);
if (this->isNormalized())
{
// Old Values xx + yy + zz = 1
// New values: x'x' + y'y' + z'z' = 1
// Say we are changing y into y':
// x'x' + z'z' = 1 - y'y'
// Let's pose a the coef to multiply x into x' that keeps the norm to 1:
// axax + azaz = 1 - y'y'
// aa(xx + zz) = 1 - y'y'
// a = sqrt( (1 - y'y') / (xx + zz) )
bool mult = true;
if (den != 0.0)
{
mult = true;
den = sqrt( (1. - coordinate * coordinate) / den);
}
else if (this->Dimension > 1)
{
mult = false;
den = sqrt((1. - coordinate*coordinate) / (this->Dimension - 1));
}
double normalizedCoordinates[this->Dimension];
for (int i = 0; i < this->Dimension; ++i)
{
if (i != element)
{
normalizedCoordinates[i] = mult ? this->Coordinates[i] * den : den;
}
else
{
normalizedCoordinates[i] = this->Coordinates[i];
}
}
this->setCoordinates(normalizedCoordinates);
}
else
{
emit coordinatesChanged(this->Coordinates);
}
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::updateCoordinates()
{
for (int i = 0; i < this->Dimension; ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox =
item ? qobject_cast<QDoubleSpinBox*>(item->widget()) : 0;
if ( spinBox)
{
this->Coordinates[i] = spinBox->value();
}
}
emit coordinatesChanged(this->Coordinates);
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::normalize()
{
double normalizedCoordinates[this->Dimension];
memcpy(normalizedCoordinates, this->Coordinates,
sizeof(double) * this->Dimension);
ctkCoordinatesWidget::normalize(normalizedCoordinates, this->Dimension);
this->setCoordinates(normalizedCoordinates);
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::normalize(double* coordinates, int dimension)
{
double den = ctkCoordinatesWidget::norm( coordinates, dimension );
if ( den != 0.0 )
{
for (int i = 0; i < dimension; ++i)
{
coordinates[i] /= den;
}
}
return den;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::norm(double* coordinates, int dimension)
{
double sum = 0.;
for (int i = 0; i < dimension; ++i)
{
sum += coordinates[i] * coordinates[i];
}
return sqrt(sum);
}
<commit_msg>Use heap allocation for arrays with non-const length. Fixes #231.<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QHBoxLayout>
#include <QDoubleSpinBox>
// CTK includes
#include "ctkCoordinatesWidget.h"
// STD includes
#include <cmath>
//------------------------------------------------------------------------------
ctkCoordinatesWidget::ctkCoordinatesWidget(QWidget* _parent) :QWidget(_parent)
{
this->Decimals = 3;
this->SingleStep = 1.;
this->Minimum = -100000.;
this->Maximum = 100000.;
this->Normalized = false;
this->Dimension = 3;
this->Coordinates = new double [this->Dimension];
QHBoxLayout* hboxLayout = new QHBoxLayout(this);
this->setLayout(hboxLayout);
for (int i = 0; i < this->Dimension; ++i)
{
this->Coordinates[i] = 0.;
this->addSpinBox();
}
hboxLayout->setContentsMargins(0, 0, 0, 0);
}
//------------------------------------------------------------------------------
ctkCoordinatesWidget::~ctkCoordinatesWidget()
{
delete [] this->Coordinates;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::addSpinBox()
{
QDoubleSpinBox* spinBox = new QDoubleSpinBox(this);
spinBox->setDecimals(this->Decimals);
spinBox->setSingleStep(this->SingleStep);
spinBox->setMinimum(this->Minimum);
spinBox->setMaximum(this->Maximum);
connect( spinBox, SIGNAL(valueChanged(double)),
this, SLOT(updateCoordinate(double)));
this->layout()->addWidget(spinBox);
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setDimension(int dim)
{
if (dim < 1)
{
return;
}
double* newPos = new double[dim];
if (dim > this->Dimension)
{
memcpy(newPos, this->Coordinates, this->Dimension * sizeof(double));
for (int i = this->Dimension; i < dim; ++i)
{
newPos[i] = 0.;
this->addSpinBox();
}
}
else
{
memcpy(newPos, this->Coordinates, dim * sizeof(double));
for (int i = this->Dimension - 1 ; i >= dim; --i)
{
QLayoutItem* item = this->layout()->takeAt(i);
QWidget* widget = item ? item->widget() : 0;
delete item;
delete widget;
}
}
delete [] this->Coordinates;
this->Coordinates = newPos;
this->Dimension = dim;
this->updateGeometry();
this->updateCoordinates();
}
//------------------------------------------------------------------------------
int ctkCoordinatesWidget::dimension() const
{
return this->Dimension;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setMinimum(double min)
{
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setMinimum(min);
}
}
this->Minimum = min;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::minimum() const
{
return this->Minimum;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setMaximum(double max)
{
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setMaximum(max);
}
}
this->Maximum = max;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::maximum() const
{
return this->Maximum;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setNormalized(bool normalized)
{
this->Normalized = normalized;
if (this->Normalized)
{
double* normalizedCoordinates = new double[this->Dimension];
memcpy(normalizedCoordinates, this->Coordinates, sizeof(double)*this->Dimension);
ctkCoordinatesWidget::normalize(normalizedCoordinates, this->Dimension);
this->setMinimum(-1.);
this->setMaximum(1.);
this->setCoordinates(normalizedCoordinates);
delete [] normalizedCoordinates;
}
}
//------------------------------------------------------------------------------
bool ctkCoordinatesWidget::isNormalized() const
{
return this->Normalized;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setDecimals(int newDecimals)
{
this->Decimals = newDecimals;
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setDecimals(newDecimals);
}
}
}
//------------------------------------------------------------------------------
int ctkCoordinatesWidget::decimals() const
{
return this->Decimals;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setSingleStep(double step)
{
for (int i = 0; this->layout()->itemAt(i); ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox = item ? dynamic_cast<QDoubleSpinBox*>(
item->widget()) : 0;
if (spinBox)
{
spinBox->setSingleStep(step);
}
}
this->SingleStep = step;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::singleStep() const
{
return this->SingleStep;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setCoordinatesAsString(QString _pos)
{
QStringList posList = _pos.split(',');
if (posList.count() != this->Dimension)
{
return;
}
double* newPos = new double[this->Dimension];
for (int i = 0; i < this->Dimension; ++i)
{
newPos[i] = posList[i].toDouble();
}
this->setCoordinates(newPos);
delete [] newPos;
}
//------------------------------------------------------------------------------
QString ctkCoordinatesWidget::coordinatesAsString()const
{
QString res;
for (int i = 0; i < this->Dimension; ++i)
{
if (i != 0)
{
res += ",";
}
res += QString::number(this->Coordinates[i]);
}
return res;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setCoordinates(double* coordinates)
{
for (int i = 0; i < this->Dimension; ++i)
{
this->Coordinates[i] = coordinates[i];
}
if (this->Normalized)
{
this->normalize(this->Coordinates, this->Dimension);
}
bool blocked = this->blockSignals(true);
for (int i = 0; i < this->Dimension; ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox =
item ? dynamic_cast<QDoubleSpinBox*>(item->widget()) : 0;
if (spinBox)
{
spinBox->setValue(this->Coordinates[i]);
}
}
this->blockSignals(blocked);
this->updateCoordinates();
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::setCoordinates(double x, double y, double z, double w)
{
double* coordinates = new double[this->Dimension];
if (this->Dimension >= 1)
{
coordinates[0] = x;
}
if (this->Dimension >= 2)
{
coordinates[1] = y;
}
if (this->Dimension >= 3)
{
coordinates[2] = z;
}
if (this->Dimension >= 4)
{
coordinates[3] = w;
}
for (int i = 4; i < this->Dimension; ++i)
{
coordinates[i] = this->Coordinates[i];
}
this->setCoordinates(coordinates);
delete [] coordinates;
}
//------------------------------------------------------------------------------
double const * ctkCoordinatesWidget::coordinates()const
{
return this->Coordinates;
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::updateCoordinate(double coordinate)
{
double den = 0.;
int element = -1;
for (int i = 0; i < this->Dimension; ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox =
item ? qobject_cast<QDoubleSpinBox*>(item->widget()) : 0;
if ( spinBox && spinBox == this->sender())
{
this->Coordinates[i] = coordinate;
element = i;
}
else
{
den += this->Coordinates[i]*this->Coordinates[i];
}
}
Q_ASSERT(element != -1);
if (this->isNormalized())
{
// Old Values xx + yy + zz = 1
// New values: x'x' + y'y' + z'z' = 1
// Say we are changing y into y':
// x'x' + z'z' = 1 - y'y'
// Let's pose a the coef to multiply x into x' that keeps the norm to 1:
// axax + azaz = 1 - y'y'
// aa(xx + zz) = 1 - y'y'
// a = sqrt( (1 - y'y') / (xx + zz) )
bool mult = true;
if (den != 0.0)
{
mult = true;
den = sqrt( (1. - coordinate * coordinate) / den);
}
else if (this->Dimension > 1)
{
mult = false;
den = sqrt((1. - coordinate*coordinate) / (this->Dimension - 1));
}
double* normalizedCoordinates = new double[this->Dimension];
for (int i = 0; i < this->Dimension; ++i)
{
if (i != element)
{
normalizedCoordinates[i] = mult ? this->Coordinates[i] * den : den;
}
else
{
normalizedCoordinates[i] = this->Coordinates[i];
}
}
this->setCoordinates(normalizedCoordinates);
delete [] normalizedCoordinates;
}
else
{
emit coordinatesChanged(this->Coordinates);
}
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::updateCoordinates()
{
for (int i = 0; i < this->Dimension; ++i)
{
QLayoutItem* item = this->layout()->itemAt(i);
QDoubleSpinBox* spinBox =
item ? qobject_cast<QDoubleSpinBox*>(item->widget()) : 0;
if ( spinBox)
{
this->Coordinates[i] = spinBox->value();
}
}
emit coordinatesChanged(this->Coordinates);
}
//------------------------------------------------------------------------------
void ctkCoordinatesWidget::normalize()
{
double* normalizedCoordinates = new double[this->Dimension];
memcpy(normalizedCoordinates, this->Coordinates,
sizeof(double) * this->Dimension);
ctkCoordinatesWidget::normalize(normalizedCoordinates, this->Dimension);
this->setCoordinates(normalizedCoordinates);
delete [] normalizedCoordinates;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::normalize(double* coordinates, int dimension)
{
double den = ctkCoordinatesWidget::norm( coordinates, dimension );
if ( den != 0.0 )
{
for (int i = 0; i < dimension; ++i)
{
coordinates[i] /= den;
}
}
return den;
}
//------------------------------------------------------------------------------
double ctkCoordinatesWidget::norm(double* coordinates, int dimension)
{
double sum = 0.;
for (int i = 0; i < dimension; ++i)
{
sum += coordinates[i] * coordinates[i];
}
return sqrt(sum);
}
<|endoftext|> |
<commit_before>#include <QCoreApplication>
#include <QDebug>
#include <QUrl>
#include <QUrlQuery>
#include <QMessageBox>
#include "isichazamazwi.h"
#include "ui_isichazamazwi.h"
#include "nt_operations.h"
#include "db_operations.h"
isichazamazwi::isichazamazwi(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::isichazamazwi)
{
ui->setupUi(this);
ui->rbtn_google->setChecked(true);
ui->menuTranslator->addAction(tr("Exit"),this, SLOT(exit()), tr("Alt+F4"));
ui->menuTranslator->addAction(tr("Offline Mode"),this, SLOT(offline()));
ui->menuTranslator->addAction(tr("Online Mode"),this, SLOT(online()));
ui->btn_save_it->setVisible(false);
trayMenu = new QMenu(this);
trayMenu->addAction(tr("Offline Mode"),this, SLOT(offline()));
trayMenu->addAction(tr("Online Mode"),this, SLOT(online()));
trayMenu->addAction(tr("Exit"),this, SLOT(exit()));
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(QIcon("../../Files/try.png"));
trayIcon->setContextMenu(trayMenu);
trayIcon->show();
trayIcon->showMessage("isichazamazwi", "Dictionary is started!..",QSystemTrayIcon::Information, 2510);
isichazamazwi::setWindowIcon(QIcon("../../Files/try.png"));
}
isichazamazwi::~isichazamazwi()
{
delete ui;
}
void isichazamazwi::exit()
{
close();
qApp->quit();
}
void print_message_box(QString text)
{
QMessageBox Msgbox;
Msgbox.setText(text);
Msgbox.setStandardButtons(QMessageBox::Ok);
Msgbox.exec();
}
void isichazamazwi::offline()
{
if(!isichazamazwi::offlineMode)
{
isichazamazwi::offlineMode = true;
trayIcon->showMessage("isichazamazwi", "Your dictionary run offline mode!..",QSystemTrayIcon::Information, 2510);
QWidget::setWindowTitle("isichazamazwi (offline mode)");
}
}
void isichazamazwi::online()
{
if(isichazamazwi::offlineMode)
{
isichazamazwi::offlineMode = false;
trayIcon->showMessage("isichazamazwi", "Your dictionary run online mode!..",QSystemTrayIcon::Information, 2510);
QWidget::setWindowTitle("isichazamazwi");
}
}
QString parse_http(QString &src)
{
try {
src = QString("Will be come");
} catch (...) {
}
return src;
}
void isichazamazwi::on_btn_translate_clicked()
{
int type;
if(ui->rbtn_google->isChecked())
type = 0;
else if(ui->rbtn_yandex->isChecked())
type = 1;
else if (ui->rbtn_bing->isChecked())
type = 2;
else
type = -1;
if(ui->txt_source->text().isEmpty())
{
print_message_box("Please insert word to translate");
}
else
{
QString src = ui->txt_source->text();
QString dest =send_http_request(src,type);
QString tmp = parse_http(dest);
ui->txt_destination->setText(tmp);
ui->btn_save_it->setVisible(true);
ui->btn_translate->setVisible(false);
}
}
void isichazamazwi::on_btn_save_it_clicked()
{
try {
db_operations db("isichazamazwi.db");
db.insert_word(ui->txt_source->text(),ui->txt_destination->text(),2);
} catch (...) {
print_message_box("isichazamazwi.db named database not found");
return;
}
print_message_box("your word ("+ ui->txt_source->text() + ") added \nlocal dictionary!..");
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_rbtn_google_clicked()
{
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_rbtn_yandex_clicked()
{
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_rbtn_bing_clicked()
{
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_txt_source_textChanged(const QString &arg1)
{
ui->btn_translate->setVisible(true);
ui->btn_save_it->setVisible(false);
}
<commit_msg>input character control added<commit_after>#include <QCoreApplication>
#include <QDebug>
#include <QUrl>
#include <QUrlQuery>
#include <QMessageBox>
#include "isichazamazwi.h"
#include "ui_isichazamazwi.h"
#include "nt_operations.h"
#include "db_operations.h"
isichazamazwi::isichazamazwi(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::isichazamazwi)
{
ui->setupUi(this);
ui->rbtn_google->setChecked(true);
ui->menuTranslator->addAction(tr("Offline Mode"),this, SLOT(offline()));
ui->menuTranslator->addAction(tr("Online Mode"),this, SLOT(online()));
ui->menuTranslator->addAction(tr("Exit"),this, SLOT(exit()), tr("Alt+F4"));
ui->btn_save_it->setVisible(false);
trayMenu = new QMenu(this);
trayMenu->addAction(tr("Offline Mode"),this, SLOT(offline()));
trayMenu->addAction(tr("Online Mode"),this, SLOT(online()));
trayMenu->addAction(tr("Exit"),this, SLOT(exit()));
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(QIcon("../../Files/try.png"));
trayIcon->setContextMenu(trayMenu);
trayIcon->show();
trayIcon->showMessage("isichazamazwi", "Dictionary is started!..",QSystemTrayIcon::Information, 2510);
isichazamazwi::setWindowIcon(QIcon("../../Files/try.png"));
}
isichazamazwi::~isichazamazwi()
{
delete ui;
}
void isichazamazwi::exit()
{
close();
qApp->quit();
}
void print_message_box(QString text)
{
QMessageBox Msgbox;
Msgbox.setText(text);
Msgbox.setStandardButtons(QMessageBox::Ok);
Msgbox.exec();
return;
}
void isichazamazwi::offline()
{
if(!isichazamazwi::offlineMode)
{
isichazamazwi::offlineMode = true;
trayIcon->showMessage("isichazamazwi", "Your dictionary run offline mode!..",QSystemTrayIcon::Information, 2510);
QWidget::setWindowTitle("isichazamazwi (offline mode)");
return;
}
}
void isichazamazwi::online()
{
if(isichazamazwi::offlineMode)
{
isichazamazwi::offlineMode = false;
trayIcon->showMessage("isichazamazwi", "Your dictionary run online mode!..",QSystemTrayIcon::Information, 2510);
QWidget::setWindowTitle("isichazamazwi");
return;
}
}
QString parse_http(QString &src)
{
try {
src = QString("Will be come");
} catch (...) {
}
return src;
}
void isichazamazwi::on_btn_translate_clicked()
{
int type;
if(ui->rbtn_google->isChecked())
type = 0;
else if(ui->rbtn_yandex->isChecked())
type = 1;
else if (ui->rbtn_bing->isChecked())
type = 2;
else
type = -1;
if(ui->txt_source->text().isEmpty() || ui->txt_source->text().length() < 2)
{
print_message_box("Please insert word to translate");
}
else
{
QString src = ui->txt_source->text();
QRegExp re("\\b([a-zA-Z]+[a-z]*)\\b");
if(!re.exactMatch(src))
{
print_message_box("Your word include non-alphanumeric characters!");
return;
}
else
{
QString dest =send_http_request(src,type);
QString tmp = parse_http(dest);
ui->txt_destination->setText(tmp);
ui->btn_save_it->setVisible(true);
ui->btn_translate->setVisible(false);
return;
}
}
}
void isichazamazwi::on_btn_save_it_clicked()
{
try {
db_operations db("isichazamazwi.db");
db.insert_word(ui->txt_source->text(),ui->txt_destination->text(),2);
} catch (...) {
print_message_box("isichazamazwi.db named database not found");
return;
}
print_message_box("your word ("+ ui->txt_source->text() + ") added \nlocal dictionary!..");
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_rbtn_google_clicked()
{
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_rbtn_yandex_clicked()
{
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_rbtn_bing_clicked()
{
ui->btn_save_it->setVisible(false);
ui->btn_translate->setVisible(true);
return;
}
void isichazamazwi::on_txt_source_textChanged(const QString &arg1)
{
ui->txt_destination->clear();
ui->btn_translate->setVisible(true);
ui->btn_save_it->setVisible(false);
return;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
// neighbours convention
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
// hallo radius
#define R 1 // for the time been this is a fixed param.
// domain decompostion
#define Sx 2 // size in x
#define Sy 2 // size in y
// root processor
#define ROOT 0
void print(int *data, int nx, int ny) {
printf("-- Global Memory --\n");
for (int i=0; i<ny; i++) {
for (int j=0; j<nx; j++) {
printf("%3d ", data[i*nx+j]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// if number of np != Sx*Sy then terminate.
if (size != Sx*Sy){
if (rank==ROOT)
fprintf(stderr,"%s: Needs at least %d processors.\n", argv[0], Sx*Sy);
MPI_Finalize();
return 1;
}
// Testing :
// A 1x4 grid of subgrid
/*
+-----+-----+-----+-----+
| 0 | 1 | 2 | 3 |
|(0,0)|(0,1)|(0,2)|(0,3)|
+-----+-----+-----+-----+
*/
// A 1x4 grid of subgrid
/*
+-----+
| 0 |
|(0,0)|
+-----+
| 1 |
|(1,0)|
+-----+
| 2 |
|(2,0)|
+-----+
| 3 |
|(3,0)|
+-----+
*/
// A 2x2 grid of subgrid
/*
+-----+-----+
| 0 | 1 |
|(0,0)|(0,1)|
+-----+-----+
| 3 | 4 |
|(1,0)|(1,1)|
+-----+-----+
*/
MPI_Comm Comm2d;
int ndim = 2;
int dim[2] = {Sy,Sx};
int period[2] = {false,false}; // for periodic boundary conditions
int reorder = {true};
// Setup and build cartesian grid
MPI_Cart_create(MPI_COMM_WORLD,ndim,dim,period,reorder,&Comm2d);
MPI_Comm_rank(Comm2d, &rank);
// Every processor prints it rank and coordinates
int coord[2];
MPI_Cart_coords(Comm2d,rank,2,coord);
printf("P:%2d My coordinates are %d %d\n",rank,coord[0],coord[1]);
MPI_Barrier(Comm2d);
// Every processor build his neighbour map
int nbrs[4];
MPI_Cart_shift(Comm2d,0,1,&nbrs[DOWN],&nbrs[UP]);
MPI_Cart_shift(Comm2d,1,1,&nbrs[LEFT],&nbrs[RIGHT]);
MPI_Barrier(Comm2d);
// prints its neighbours
printf("P:%2d has neighbours (u,d,l,r): %2d %2d %2d %2d\n",
rank,nbrs[UP],nbrs[DOWN],nbrs[LEFT],nbrs[RIGHT]);
/* array sizes */
const int NX =8;
const int NY =8;
const int nx =NX/Sx;
const int ny =NY/Sy;
// subsizes verification
if (NX%Sx!=0 || NY%Sy!=0) {
if (rank==ROOT)
fprintf(stderr,"%s: Subdomain sizes not an integer value.\n", argv[0]);
MPI_Finalize();
return 1;
}
// build a MPI data type for a subarray in Root processor
MPI_Datatype global, myGlobal;
int bigsizes[2] = {NY,NX};
int subsizes[2] = {ny,nx};
int starts[2] = {0,0};
MPI_Type_create_subarray(2, bigsizes, subsizes, starts, MPI_ORDER_C, MPI_INT, &global);
MPI_Type_create_resized(global, 0, nx*sizeof(int), &myGlobal); // resize extend
MPI_Type_commit(&myGlobal);
// build a MPI data type for a subarray in workers
MPI_Datatype myLocal;
int bigsizes2[2] = {R+ny+R,R+nx+R};
int subsizes2[2] = {ny,nx};
int starts2[2] = {R,R};
MPI_Type_create_subarray(2, bigsizes2, subsizes2, starts2, MPI_ORDER_C, MPI_INT, &myLocal);
MPI_Type_commit(&myLocal); // now we can use this MPI costum data type
// halo data types
MPI_Datatype xSlice, ySlice;
MPI_Type_vector(nx, 1, 1 , MPI_INT, &xSlice);
MPI_Type_vector(ny, 1, nx+2*R, MPI_INT, &ySlice);
MPI_Type_commit(&xSlice);
MPI_Type_commit(&ySlice);
// Allocate 2d big-array in root processor
int i, j;
int *bigarray; // to be allocated only in root
if (rank==ROOT) {
bigarray = (int*)malloc(NX*NY*sizeof(int));
for (i=0; i<NY; i++) {
for (j=0; j<NX; j++) {
bigarray[i*NX+j] = i*NX+j;
}
}
// print the big array
print(bigarray, NX, NY);
}
// Allocte sub-array in every np
int *subarray;
subarray = (int*)malloc((R+nx+R)*(R+ny+R)*sizeof(int));
for (i=0; i<ny+2*R; i++) {
for (j=0; j<nx+2*R; j++) {
subarray[i*(nx+2*R)+j] = 0;
}
}
// build sendcounts and displacements in root processor
int sendcounts[size];
int displs[size];
if (rank==ROOT) {
for (i=0; i<size; i++) sendcounts[i]=1;
int disp = 0; // displacement counter
for (i=0; i<Sy; i++) {
for (j=0; j<Sx; j++) {
displs[i*Sx+j]=disp; disp+=1; // x-displacements
}
disp += Sx*(ny-1); // y-displacements
}
}
// scatter pieces of the big data array
MPI_Scatterv(bigarray, sendcounts, displs, myGlobal,
subarray, 1, myLocal, ROOT, Comm2d);
// Exchange x - slices with top and bottom neighbors
MPI_Sendrecv(&(subarray[ ny *(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 1,
&(subarray[ 0 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 1,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[ 1 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 2,
&(subarray[(ny+1)*(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 2,
Comm2d, MPI_STATUS_IGNORE);
// Exchange y - slices with left and right neighbors
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ nx ]), 1, ySlice, nbrs[RIGHT],3,
&(subarray[1*(nx+2*R)+ 0 ]), 1, ySlice, nbrs[LEFT] ,3,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ 1 ]), 1, ySlice, nbrs[LEFT] ,4,
&(subarray[1*(nx+2*R)+(nx+1)]), 1, ySlice, nbrs[RIGHT],4,
Comm2d, MPI_STATUS_IGNORE);
// every processor prints the subarray
for (int p=0; p<size; p++) {
if (rank == p) {
printf("Local process on rank %d is:\n", rank);
for (i=0; i<ny+2*R; i++) {
putchar('|');
for (j=0; j<nx+2*R; j++) {
printf("%3d ", subarray[i*(nx+2*R)+j]);
}
printf("|\n");
}
}
MPI_Barrier(Comm2d);
}
// gather all pieces into the big data array
MPI_Gatherv(subarray, 1, myLocal,
bigarray, sendcounts, displs, myGlobal, ROOT, Comm2d);
// print the bigarray and free array in root
if (rank==ROOT) print(bigarray, NX, NY);
// MPI types
MPI_Type_free(&xSlice);
MPI_Type_free(&ySlice);
MPI_Type_free(&myLocal);
MPI_Type_free(&myGlobal);
// free arrays in workers
if (rank==ROOT) free(bigarray);
free(subarray);
// finalize MPI
MPI_Finalize();
return 0;
}
<commit_msg>Perfect!<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
// neighbours convention
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
// hallo radius
#define R 1 // for the time been this is a fixed param.
// domain decompostion
#define Sx 2 // size in x
#define Sy 2 // size in y
// root processor
#define ROOT 0
void print(int *data, int nx, int ny) {
printf("-- Global Memory --\n");
for (int i=0; i<ny; i++) {
for (int j=0; j<nx; j++) {
printf("%3d ", data[i*nx+j]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// if number of np != Sx*Sy then terminate.
if (size != Sx*Sy){
if (rank==ROOT)
fprintf(stderr,"%s: Needs at least %d processors.\n", argv[0], Sx*Sy);
MPI_Finalize();
return 1;
}
// Testing :
// A 1x4 grid of subgrid
/*
+-----+-----+-----+-----+
| 0 | 1 | 2 | 3 |
|(0,0)|(0,1)|(0,2)|(0,3)|
+-----+-----+-----+-----+
*/
// A 1x4 grid of subgrid
/*
+-----+
| 0 |
|(0,0)|
+-----+
| 1 |
|(1,0)|
+-----+
| 2 |
|(2,0)|
+-----+
| 3 |
|(3,0)|
+-----+
*/
// A 2x2 grid of subgrid
/*
+-----+-----+
| 0 | 1 |
|(0,0)|(0,1)|
+-----+-----+
| 2 | 3 |
|(1,0)|(1,1)|
+-----+-----+
*/
MPI_Comm Comm2d;
int ndim = 2;
int dim[2] = {Sy,Sx};
int period[2] = {false,false}; // for periodic boundary conditions
int reorder = {true};
// Setup and build cartesian grid
MPI_Cart_create(MPI_COMM_WORLD,ndim,dim,period,reorder,&Comm2d);
MPI_Comm_rank(Comm2d, &rank);
// Every processor prints it rank and coordinates
int coord[2];
MPI_Cart_coords(Comm2d,rank,2,coord);
printf("P:%2d My coordinates are %d %d\n",rank,coord[0],coord[1]);
MPI_Barrier(Comm2d);
// Every processor build his neighbour map
int nbrs[4];
MPI_Cart_shift(Comm2d,0,1,&nbrs[DOWN],&nbrs[UP]);
MPI_Cart_shift(Comm2d,1,1,&nbrs[LEFT],&nbrs[RIGHT]);
MPI_Barrier(Comm2d);
// prints its neighbours
printf("P:%2d has neighbours (u,d,l,r): %2d %2d %2d %2d\n",
rank,nbrs[UP],nbrs[DOWN],nbrs[LEFT],nbrs[RIGHT]);
/* array sizes */
const int NX =8;
const int NY =8;
const int nx =NX/Sx;
const int ny =NY/Sy;
// subsizes verification
if (NX%Sx!=0 || NY%Sy!=0) {
if (rank==ROOT)
fprintf(stderr,"%s: Subdomain sizes not an integer value.\n", argv[0]);
MPI_Finalize();
return 1;
}
// build a MPI data type for a subarray in Root processor
MPI_Datatype global, myGlobal;
int bigsizes[2] = {NY,NX};
int subsizes[2] = {ny,nx};
int starts[2] = {0,0};
MPI_Type_create_subarray(2, bigsizes, subsizes, starts, MPI_ORDER_C, MPI_INT, &global);
MPI_Type_create_resized(global, 0, nx*sizeof(int), &myGlobal); // resize extend
MPI_Type_commit(&myGlobal);
// build a MPI data type for a subarray in workers
MPI_Datatype myLocal;
int bigsizes2[2] = {R+ny+R,R+nx+R};
int subsizes2[2] = {ny,nx};
int starts2[2] = {R,R};
MPI_Type_create_subarray(2, bigsizes2, subsizes2, starts2, MPI_ORDER_C, MPI_INT, &myLocal);
MPI_Type_commit(&myLocal); // now we can use this MPI costum data type
// halo data types
MPI_Datatype xSlice, ySlice;
MPI_Type_vector(nx, 1, 1 , MPI_INT, &xSlice);
MPI_Type_vector(ny, 1, nx+2*R, MPI_INT, &ySlice);
MPI_Type_commit(&xSlice);
MPI_Type_commit(&ySlice);
// Allocate 2d big-array in root processor
int i, j;
int *bigarray; // to be allocated only in root
if (rank==ROOT) {
bigarray = (int*)malloc(NX*NY*sizeof(int));
for (i=0; i<NY; i++) {
for (j=0; j<NX; j++) {
bigarray[i*NX+j] = i*NX+j;
}
}
// print the big array
print(bigarray, NX, NY);
}
// Allocte sub-array in every np
int *subarray;
subarray = (int*)malloc((R+nx+R)*(R+ny+R)*sizeof(int));
for (i=0; i<ny+2*R; i++) {
for (j=0; j<nx+2*R; j++) {
subarray[i*(nx+2*R)+j] = 0;
}
}
// build sendcounts and displacements in root processor
int sendcounts[size];
int displs[size];
if (rank==ROOT) {
for (i=0; i<size; i++) sendcounts[i]=1;
int disp = 0; // displacement counter
for (i=0; i<Sy; i++) {
for (j=0; j<Sx; j++) {
displs[i*Sx+j]=disp; disp+=1; // x-displacements
}
disp += Sx*(ny-1); // y-displacements
}
}
// scatter pieces of the big data array
MPI_Scatterv(bigarray, sendcounts, displs, myGlobal,
subarray, 1, myLocal, ROOT, Comm2d);
// Exchange x - slices with top and bottom neighbors
MPI_Sendrecv(&(subarray[ ny *(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 1,
&(subarray[ 0 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 1,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[ 1 *(nx+2*R)+1]), 1, xSlice, nbrs[DOWN], 2,
&(subarray[(ny+1)*(nx+2*R)+1]), 1, xSlice, nbrs[UP] , 2,
Comm2d, MPI_STATUS_IGNORE);
// Exchange y - slices with left and right neighbors
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ nx ]), 1, ySlice, nbrs[RIGHT],3,
&(subarray[1*(nx+2*R)+ 0 ]), 1, ySlice, nbrs[LEFT] ,3,
Comm2d, MPI_STATUS_IGNORE);
MPI_Sendrecv(&(subarray[1*(nx+2*R)+ 1 ]), 1, ySlice, nbrs[LEFT] ,4,
&(subarray[1*(nx+2*R)+(nx+1)]), 1, ySlice, nbrs[RIGHT],4,
Comm2d, MPI_STATUS_IGNORE);
// every processor prints the subarray
for (int p=0; p<size; p++) {
if (rank == p) {
printf("Local process on rank %d is:\n", rank);
for (i=0; i<ny+2*R; i++) {
putchar('|');
for (j=0; j<nx+2*R; j++) {
printf("%3d ", subarray[i*(nx+2*R)+j]);
}
printf("|\n");
}
}
MPI_Barrier(Comm2d);
}
// gather all pieces into the big data array
MPI_Gatherv(subarray, 1, myLocal,
bigarray, sendcounts, displs, myGlobal, ROOT, Comm2d);
// print the bigarray and free array in root
if (rank==ROOT) print(bigarray, NX, NY);
// MPI types
MPI_Type_free(&xSlice);
MPI_Type_free(&ySlice);
MPI_Type_free(&myLocal);
MPI_Type_free(&myGlobal);
// free arrays in workers
if (rank==ROOT) free(bigarray);
free(subarray);
// finalize MPI
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>#include "csv-reader.h"
#include <fstream>
#include <sstream>
CSV_Reader::CSV_Reader(std::string aFileLoc)
{
fileLoc = aFileLoc;
}
CSV_Reader::~CSV_Reader()
{
}
bool CSV_Reader::LoadFile()
{
if (fileLoc == "") {
return false;
} else {
std::ifstream mainFile;
mainFile.open(fileLoc.c_str());
std::stringstream strStream;
strStream << mainFile.rdbuf(); //read the file
std::string data = strStream.str(); //str holds the content of the file
GenerateCols(data);
mainFile.close();
numRows = rows.size();
}
return true;
}
int CSV_Reader::getNumRows()
{
return this->numRows;
}
int CSV_Reader::getNumCols()
{
return this->numCols;
}
/*
* This function locates the index of the *first* matching value container.
* Searches rows between: startRow and endRow and
* Columns between: startCol and endCol.
*
* Negatives values for the indices indicate no value. i.e. startRow == -1 implies startRow = 0 and
* endRow == -1 implies endRow = LAST_ROW_INDEX
*/
LocationIndex CSV_Reader::findString(std::string value, int startRow, int endRow, int startCol, int endCol)
{
if (startRow < 0) {
startRow = 0;
}
if (endRow < 0) {
endRow = this->getNumRows() - 1;
}
if (startCol < 0) {
startCol = 0;
}
if (endCol < 0) {
endCol = this->getNumCols() - 1;
}
// Search
LocationIndex index;
index.valid = false;
for (int i = startRow; i <= endRow; i++) {
for (int j = startCol; j <= endCol; j++) {
if (this->rows[i][j] == value) {
index.row = i;
index.col = j;
index.valid = true;
}
}
}
return index;
}
LocationIndex CSV_Reader::findString(std::string value)
{
return findString(value, -1, -1, -1, -1);
}
bool CSV_Reader::GenerateCols(std::string data)
{
char DOUBLE_QUOTE_CHAR = 34;
char COMMA_CHAR = 44;
char END_LINE = '\n';
std::vector< std::string > col;
std::string currentCollected = "";
bool escaping = false;
for (unsigned int i = 0; i < data.length(); i++) {
char currentChar = data.at(i);
if ((currentChar != END_LINE && currentChar != DOUBLE_QUOTE_CHAR && currentChar != COMMA_CHAR)
|| (currentChar == COMMA_CHAR && escaping)
|| (currentChar == END_LINE && escaping)) {
currentCollected += currentChar;
} else if ((currentChar == END_LINE && !escaping)) {
// End of row.
// If we didn't write out data already, write out the remainder.
col.push_back(currentCollected);
numCols = col.size();
rows.push_back(col);
col.clear();
currentCollected = "";
} else if (currentChar == COMMA_CHAR && !escaping) {
// End of cell.
col.push_back(currentCollected);
currentCollected = "";
} else if (currentChar == DOUBLE_QUOTE_CHAR && !escaping) {
// We need to start escaping.
escaping = true;
} else if (currentChar == DOUBLE_QUOTE_CHAR && escaping) {
// If the next char is also a DOUBLE_QUOTE_CHAR, then we want to push a DOUBLE_QUOTE_CHAR.
if (i < data.length() - 1 && data.at(i+1) == DOUBLE_QUOTE_CHAR) {
currentCollected += currentChar;
} else {
// If not, then this is the end of the escaping period.
escaping = false;
}
}
}
if (col.size() != 0) {
col.push_back(currentCollected);
rows.push_back(col);
}
return true;
}
<commit_msg>Fix quote indexing bug<commit_after>#include "csv-reader.h"
#include <fstream>
#include <sstream>
CSV_Reader::CSV_Reader(std::string aFileLoc)
{
fileLoc = aFileLoc;
}
CSV_Reader::~CSV_Reader()
{
}
bool CSV_Reader::LoadFile()
{
if (fileLoc == "") {
return false;
} else {
std::ifstream mainFile;
mainFile.open(fileLoc.c_str());
std::stringstream strStream;
strStream << mainFile.rdbuf(); //read the file
std::string data = strStream.str(); //str holds the content of the file
GenerateCols(data);
mainFile.close();
numRows = rows.size();
}
return true;
}
int CSV_Reader::getNumRows()
{
return this->numRows;
}
int CSV_Reader::getNumCols()
{
return this->numCols;
}
/*
* This function locates the index of the *first* matching value container.
* Searches rows between: startRow and endRow and
* Columns between: startCol and endCol.
*
* Negatives values for the indices indicate no value. i.e. startRow == -1 implies startRow = 0 and
* endRow == -1 implies endRow = LAST_ROW_INDEX
*/
LocationIndex CSV_Reader::findString(std::string value, int startRow, int endRow, int startCol, int endCol)
{
if (startRow < 0) {
startRow = 0;
}
if (endRow < 0) {
endRow = this->getNumRows() - 1;
}
if (startCol < 0) {
startCol = 0;
}
if (endCol < 0) {
endCol = this->getNumCols() - 1;
}
// Search
LocationIndex index;
index.valid = false;
for (int i = startRow; i <= endRow; i++) {
for (int j = startCol; j <= endCol; j++) {
if (this->rows[i][j] == value) {
index.row = i;
index.col = j;
index.valid = true;
}
}
}
return index;
}
LocationIndex CSV_Reader::findString(std::string value)
{
return findString(value, -1, -1, -1, -1);
}
bool CSV_Reader::GenerateCols(std::string data)
{
char DOUBLE_QUOTE_CHAR = 34;
char COMMA_CHAR = 44;
char END_LINE = '\n';
std::vector< std::string > col;
std::string currentCollected = "";
bool escaping = false;
for (unsigned int i = 0; i < data.length(); i++) {
char currentChar = data.at(i);
if ((currentChar != END_LINE && currentChar != DOUBLE_QUOTE_CHAR && currentChar != COMMA_CHAR)
|| (currentChar == COMMA_CHAR && escaping)
|| (currentChar == END_LINE && escaping)) {
currentCollected += currentChar;
} else if ((currentChar == END_LINE && !escaping)) {
// End of row.
// If we didn't write out data already, write out the remainder.
col.push_back(currentCollected);
numCols = col.size();
rows.push_back(col);
col.clear();
currentCollected = "";
} else if (currentChar == COMMA_CHAR && !escaping) {
// End of cell.
col.push_back(currentCollected);
currentCollected = "";
} else if (currentChar == DOUBLE_QUOTE_CHAR && !escaping) {
// We need to start escaping.
escaping = true;
} else if (currentChar == DOUBLE_QUOTE_CHAR && escaping) {
// If the next char is also a DOUBLE_QUOTE_CHAR, then we want to push a DOUBLE_QUOTE_CHAR.
if (i < data.length() - 1 && data.at(i+1) == DOUBLE_QUOTE_CHAR) {
currentCollected += currentChar;
i++; // Skip next quote char.
} else {
// If not, then this is the end of the escaping period.
escaping = false;
}
}
}
if (col.size() != 0) {
col.push_back(currentCollected);
rows.push_back(col);
}
return true;
}
<|endoftext|> |
<commit_before>#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <vector>
#include <math.h>
#include <iostream>
using namespace std;
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/norm.hpp>
typedef glm::mat3 mat3;
typedef glm::vec3 vec3;
const float pi = 3.14159265 ; // For portability across platforms
using namespace std;
void initCube(void);
static void redraw(void);
struct Cube {
vector<vec3> verts;
} sCube;
int partition = 20;
vec3 force_center(0,-10,0);
const float DISPLACE_PER_UNIT = 8.9;
// cube unfolding
// looking to -Z axis
// ___________
// | | |
// | 1 | 2 |
// |_____|_____|_____
// | | |
// | 3 | 4 |
// |_____|_____|_____
// | | |
// | 5 | 6 |
// |_____|_____|
//
// from - (front, left, bottom)
// to - (back, right, top)
void generatePolyCubeVerts(vec3 from, vec3 to, int face_partition, Cube &c) {
float sx = (to.x - from.x) / face_partition;
float sy = (to.y - from.y) / face_partition;
float sz = (to.z - from.z) / face_partition;
//1 (front)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, from.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, from.z));
}
//4 (back)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, to.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, to.z));
}
//2 (right)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + (pz+1) * sz));
}
// 6 (left)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + pz * sz));
}
// 5 (top)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + pz * sz));
}
return;
//3 (bottom)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + pz * sz));
}
}
void initCube(void)
{
generatePolyCubeVerts(vec3(-10,-10,-10), vec3(10,10,10), partition, sCube);
}
float calcDisplace(const vec3 &v) {
float dist = glm::gtx::norm::l2Norm(v, force_center);
// cout << "disp = " << dist*DISPLACE_PER_UNIT << endl;;
// return 0;
return DISPLACE_PER_UNIT*dist;
}
struct time_frame {
int from;
int to;
float dt;
};
time_frame timeline[] = {
{0, 100, 1},
{100, 140, 0.2},
{140, 240, 1},
{240, 260, 0.1},
{260, 360, 1},
};
float rTime(int t) {
float dt;
int tl = sizeof(timeline) / sizeof(time_frame);
dt = 1;
for (int i = 0; i < tl; i++) {
if (t > timeline[i].from && t < timeline[i].to) {
dt = timeline[i].dt;
break;
}
}
// if (dt == 5)
// cout << t+dt << endl;
return t*dt;
}
vec3 rotFunc1(const vec3 &v, vec3 axis, int t) {
vec3 rv;
float nt = t - calcDisplace(v);
if (nt < 0.01) {
return v;
}
if (nt > 360) {
return v;
}
nt = rTime(nt);
rv = glm::rotate(v, nt, axis);
return rv;
}
int maxtime = 1000;
float rSpeed = 2;
float rAccel = 0.2;
float yRot = 0;
float rUpper = 10;
float rLower = 3;
static void redraw(void)
{
static float t=0;
int a,b;
unsigned int currentVer;
if (t > maxtime)
t = 0;
t+=rSpeed;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glPushMatrix();
glTranslatef(0,0,-50);
// glRotatef(rotateBy,0,1,0.6);
glBegin(GL_QUADS);
for (int i = 0; i < sCube.verts.size(); i++) {
vec3 cv = sCube.verts[i];
cv = rotFunc1(cv, vec3(0,1,0.2), t);
cv = rotFunc1(cv, vec3(0,0.2,1), t-270);
cv = rotFunc1(cv, vec3(1,1,1), t-490);
float v[3] = {cv.x, cv.y, cv.z};
float col[3] = {(i%255)/255.0,(i%255)/255.0,(i%255)/255.0};
glColor3fv(col);
glVertex3fv(v);
// sCube.verts[i] = cv;
}
// rSpeed += rAccel;
// if (rSpeed > rUpper)
// rAccel =- rAccel;
// if (rSpeed < rLower)
// rAccel =- rAccel;
glEnd();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Vector slime demo");
glutDisplayFunc(redraw);
glMatrixMode(GL_PROJECTION); //hello
gluPerspective(45, //view angle
1.0, //aspect ratio
10.0, //near clip
10000.0);//far clip
glMatrixMode(GL_MODELVIEW);
glEnable(GL_CULL_FACE);
initCube();
glutMainLoop();
return 0;
}
<commit_msg>some improvs<commit_after>#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <vector>
#include <math.h>
#include <iostream>
using namespace std;
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/norm.hpp>
typedef glm::mat3 mat3;
typedef glm::vec3 vec3;
const float pi = 3.14159265 ; // For portability across platforms
using namespace std;
void initCube(void);
static void redraw(void);
struct Cube {
vector<vec3> verts;
} sCube;
int partition = 20;
vec3 force_center(0,-10,0);
const float DISPLACE_PER_UNIT = 6.9;
// cube unfolding
// looking to -Z axis
// ___________
// | | |
// | 1 | 2 |
// |_____|_____|_____
// | | |
// | 3 | 4 |
// |_____|_____|_____
// | | |
// | 5 | 6 |
// |_____|_____|
//
// from - (front, left, bottom)
// to - (back, right, top)
void generatePolyCubeVerts(vec3 from, vec3 to, int face_partition, Cube &c) {
float sx = (to.x - from.x) / face_partition;
float sy = (to.y - from.y) / face_partition;
float sz = (to.z - from.z) / face_partition;
//1 (front)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, from.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, from.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, from.z));
}
//4 (back)
for (int px = 0; px < face_partition; px++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x + px * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + py * sy, to.z));
c.verts.push_back( vec3(from.x + (px+1) * sx, from.y + (py+1) * sy, to.z));
c.verts.push_back( vec3(from.x + px * sx, from.y + (py+1) * sy, to.z));
}
//2 (right)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + pz * sz));
c.verts.push_back( vec3(to.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(to.x, from.y + py * sy, from.z + (pz+1) * sz));
}
// 6 (left)
for (int pz = 0; pz < face_partition; pz++)
for (int py = 0; py < face_partition; py++) {
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + pz * sz));
c.verts.push_back( vec3(from.x, from.y + py * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x, from.y + (py+1) * sy, from.z + pz * sz));
}
// 5 (top)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, to.y, from.z + pz * sz));
}
return;
//3 (bottom)
for (int pz = 0; pz < face_partition; pz++)
for (int px = 0; px < face_partition; px++) {
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + pz * sz));
c.verts.push_back( vec3(from.x + px*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + (pz+1) * sz));
c.verts.push_back( vec3(from.x + (px+1)*sx, from.y, from.z + pz * sz));
}
}
void initCube(void)
{
generatePolyCubeVerts(vec3(-10,-10,-10), vec3(10,10,10), partition, sCube);
}
float calcDisplace(const vec3 &v) {
float dist = glm::gtx::norm::l2Norm(v, force_center);
// cout << "disp = " << dist*DISPLACE_PER_UNIT << endl;;
// return 0;
return DISPLACE_PER_UNIT*dist;
}
struct time_frame {
int from;
int to;
float d1;
float d2;
};
/* time_frame timeline[] = { */
/* {0, 100, 0, 1}, */
/* {100, 140, 1, 0.2}, */
/* {140, 240, 0.2, 1}, */
/* {240, 260, 1, 0.1}, */
/* {260, 360, 0.1, 1}, */
/* }; */
time_frame timeline[] = {
{0, 100, 0, 1},
{100, 140, 1, 0.2},
{140, 240, 0.2, 1},
{240, 260, 1, 0.1},
{260, 360, 0.1, 1},
};
float rTime(int t) {
float dt;
int di = -1;
int tl = sizeof(timeline) / sizeof(time_frame);
dt = 1;
for (int i = 0; i < tl; i++) {
if (t >= timeline[i].from && t <= timeline[i].to) {
di = i;
break;
}
}
if (di == -1) {
/* cout << "out, t = " << t << endl; */
return t;
}
float len = timeline[di].to - timeline[di].from;
float step = (timeline[di].d2 - timeline[di].d1) / len;
float diff = timeline[di].d1 + (t - timeline[di].from) * step;
/* if (diff < 0) */
/* cout << "diff = " << diff << endl; */
diff = 1;
return t*diff;
}
vec3 rotFunc1(const vec3 &v, vec3 axis, int t, bool debug = false) {
vec3 rv;
/* debug = false; */
float nt = t - calcDisplace(v);
debug = false;
if (debug) {
cout << "-------------" << endl;
cout << "orig t: " << t << endl;
cout << "t': " << nt << endl;
}
if (nt < 0.01) {
return v;
}
if (nt > 360) {
return v;
}
nt = rTime(nt);
if (debug) {
cout << "nt: " << nt << endl;
cout << "----------\n" << nt << endl;
}
/* cout << nt << endl; */
rv = glm::rotate(v, nt, axis);
return rv;
}
int maxtime = 1200;
float rSpeed = 4;
float rAccel = 0.2;
float yRot = 0;
float rUpper = 10;
float rLower = 3;
static void redraw(void)
{
static float t=0;
int a,b;
unsigned int currentVer;
if (t > maxtime)
t = 0;
t+=rSpeed;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glPushMatrix();
glTranslatef(0,0,-50);
// glRotatef(rotateBy,0,1,0.6);
glBegin(GL_QUADS);
for (int i = 0; i < sCube.verts.size(); i++) {
vec3 cv = sCube.verts[i];
cv = rotFunc1(cv, vec3(0,1,0.2), t, (i == 0 ? true : false));
cv = rotFunc1(cv, vec3(0,0.2,1), t-260);
cv = rotFunc1(cv, vec3(0.2,0.5,0.2), t-520);
float v[3] = {cv.x, cv.y, cv.z};
float col[3] = {(i%255)/255.0,(i%255)/255.0,(i%255)/255.0};
if (i < 10)
col[0] = 1;
glColor3fv(col);
glVertex3fv(v);
// sCube.verts[i] = cv;
}
// rSpeed += rAccel;
// if (rSpeed > rUpper)
// rAccel =- rAccel;
// if (rSpeed < rLower)
// rAccel =- rAccel;
glEnd();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Vector slime demo");
glutDisplayFunc(redraw);
glMatrixMode(GL_PROJECTION); //hello
gluPerspective(45, //view angle
1.0, //aspect ratio
10.0, //near clip
10000.0);//far clip
glMatrixMode(GL_MODELVIEW);
// glEnable(GL_CULL_FACE);
glEnable (GL_DEPTH_TEST);
initCube();
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>15091924-2e4e-11e5-9284-b827eb9e62be<commit_msg>150e10c8-2e4e-11e5-9284-b827eb9e62be<commit_after>150e10c8-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>c7eeebf0-2e4d-11e5-9284-b827eb9e62be<commit_msg>c7f3eb6e-2e4d-11e5-9284-b827eb9e62be<commit_after>c7f3eb6e-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>378369ea-2e4f-11e5-9284-b827eb9e62be<commit_msg>378863aa-2e4f-11e5-9284-b827eb9e62be<commit_after>378863aa-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>204ba61c-2e4e-11e5-9284-b827eb9e62be<commit_msg>2050bf44-2e4e-11e5-9284-b827eb9e62be<commit_after>2050bf44-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>100f5de8-2e4e-11e5-9284-b827eb9e62be<commit_msg>10145ca8-2e4e-11e5-9284-b827eb9e62be<commit_after>10145ca8-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e5a44770-2e4e-11e5-9284-b827eb9e62be<commit_msg>e5a97344-2e4e-11e5-9284-b827eb9e62be<commit_after>e5a97344-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>be3b7334-2e4e-11e5-9284-b827eb9e62be<commit_msg>be40dbc6-2e4e-11e5-9284-b827eb9e62be<commit_after>be40dbc6-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>08ab1df2-2e4f-11e5-9284-b827eb9e62be<commit_msg>08b0bba4-2e4f-11e5-9284-b827eb9e62be<commit_after>08b0bba4-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>5dec99a0-2e4d-11e5-9284-b827eb9e62be<commit_msg>5df1a012-2e4d-11e5-9284-b827eb9e62be<commit_after>5df1a012-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>7c7fa67c-2e4e-11e5-9284-b827eb9e62be<commit_msg>7c84b400-2e4e-11e5-9284-b827eb9e62be<commit_after>7c84b400-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>09ad1698-2e4e-11e5-9284-b827eb9e62be<commit_msg>09b22ffc-2e4e-11e5-9284-b827eb9e62be<commit_after>09b22ffc-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e2efcb3c-2e4c-11e5-9284-b827eb9e62be<commit_msg>e2f4d320-2e4c-11e5-9284-b827eb9e62be<commit_after>e2f4d320-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>6eae91ca-2e4e-11e5-9284-b827eb9e62be<commit_msg>6eb38a86-2e4e-11e5-9284-b827eb9e62be<commit_after>6eb38a86-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>1a9c3dca-2e4f-11e5-9284-b827eb9e62be<commit_msg>1aa14324-2e4f-11e5-9284-b827eb9e62be<commit_after>1aa14324-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fabeeeb8-2e4d-11e5-9284-b827eb9e62be<commit_msg>fac43652-2e4d-11e5-9284-b827eb9e62be<commit_after>fac43652-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>a9725906-2e4c-11e5-9284-b827eb9e62be<commit_msg>a9775726-2e4c-11e5-9284-b827eb9e62be<commit_after>a9775726-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ac8b2b4a-2e4c-11e5-9284-b827eb9e62be<commit_msg>ac902a82-2e4c-11e5-9284-b827eb9e62be<commit_after>ac902a82-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fb77b458-2e4c-11e5-9284-b827eb9e62be<commit_msg>fb7cacc4-2e4c-11e5-9284-b827eb9e62be<commit_after>fb7cacc4-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>0d18204c-2e4f-11e5-9284-b827eb9e62be<commit_msg>0d1d1ae8-2e4f-11e5-9284-b827eb9e62be<commit_after>0d1d1ae8-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>d37f0b4a-2e4c-11e5-9284-b827eb9e62be<commit_msg>d3843354-2e4c-11e5-9284-b827eb9e62be<commit_after>d3843354-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>27eb7a0a-2e4e-11e5-9284-b827eb9e62be<commit_msg>27f08a90-2e4e-11e5-9284-b827eb9e62be<commit_after>27f08a90-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>23934d92-2e4f-11e5-9284-b827eb9e62be<commit_msg>239844c8-2e4f-11e5-9284-b827eb9e62be<commit_after>239844c8-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>47ff8d78-2e4d-11e5-9284-b827eb9e62be<commit_msg>48049520-2e4d-11e5-9284-b827eb9e62be<commit_after>48049520-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>0514a790-2e4e-11e5-9284-b827eb9e62be<commit_msg>0519b9c4-2e4e-11e5-9284-b827eb9e62be<commit_after>0519b9c4-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>35beaa18-2e4d-11e5-9284-b827eb9e62be<commit_msg>35c3da56-2e4d-11e5-9284-b827eb9e62be<commit_after>35c3da56-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>a9954c9a-2e4c-11e5-9284-b827eb9e62be<commit_msg>a99a466e-2e4c-11e5-9284-b827eb9e62be<commit_after>a99a466e-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fdc99258-2e4c-11e5-9284-b827eb9e62be<commit_msg>fdce8fa6-2e4c-11e5-9284-b827eb9e62be<commit_after>fdce8fa6-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>18c974f6-2e4d-11e5-9284-b827eb9e62be<commit_msg>18ce7992-2e4d-11e5-9284-b827eb9e62be<commit_after>18ce7992-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>5f521b9e-2e4d-11e5-9284-b827eb9e62be<commit_msg>5f573390-2e4d-11e5-9284-b827eb9e62be<commit_after>5f573390-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>a3792178-2e4d-11e5-9284-b827eb9e62be<commit_msg>a37e6656-2e4d-11e5-9284-b827eb9e62be<commit_after>a37e6656-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f26564aa-2e4c-11e5-9284-b827eb9e62be<commit_msg>f26a712a-2e4c-11e5-9284-b827eb9e62be<commit_after>f26a712a-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b24647d6-2e4c-11e5-9284-b827eb9e62be<commit_msg>b2544840-2e4c-11e5-9284-b827eb9e62be<commit_after>b2544840-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fa6351a8-2e4c-11e5-9284-b827eb9e62be<commit_msg>fa6844d8-2e4c-11e5-9284-b827eb9e62be<commit_after>fa6844d8-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b5d4ef7e-2e4c-11e5-9284-b827eb9e62be<commit_msg>b5d9f9ba-2e4c-11e5-9284-b827eb9e62be<commit_after>b5d9f9ba-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>df8dae4a-2e4d-11e5-9284-b827eb9e62be<commit_msg>df92b7fa-2e4d-11e5-9284-b827eb9e62be<commit_after>df92b7fa-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>70ef8a62-2e4d-11e5-9284-b827eb9e62be<commit_msg>70f4a7ea-2e4d-11e5-9284-b827eb9e62be<commit_after>70f4a7ea-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f38555aa-2e4e-11e5-9284-b827eb9e62be<commit_msg>f38a5816-2e4e-11e5-9284-b827eb9e62be<commit_after>f38a5816-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>d23fa950-2e4d-11e5-9284-b827eb9e62be<commit_msg>d2449c80-2e4d-11e5-9284-b827eb9e62be<commit_after>d2449c80-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>8fdbbedc-2e4d-11e5-9284-b827eb9e62be<commit_msg>8fe0c332-2e4d-11e5-9284-b827eb9e62be<commit_after>8fe0c332-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>a23db41c-2e4e-11e5-9284-b827eb9e62be<commit_msg>a242c222-2e4e-11e5-9284-b827eb9e62be<commit_after>a242c222-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ed830fbc-2e4e-11e5-9284-b827eb9e62be<commit_msg>ed880986-2e4e-11e5-9284-b827eb9e62be<commit_after>ed880986-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b14a9282-2e4d-11e5-9284-b827eb9e62be<commit_msg>b14f8e36-2e4d-11e5-9284-b827eb9e62be<commit_after>b14f8e36-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>2caa2252-2e4f-11e5-9284-b827eb9e62be<commit_msg>2caf135c-2e4f-11e5-9284-b827eb9e62be<commit_after>2caf135c-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b829fbc0-2e4c-11e5-9284-b827eb9e62be<commit_msg>b8364d08-2e4c-11e5-9284-b827eb9e62be<commit_after>b8364d08-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e423c1a2-2e4c-11e5-9284-b827eb9e62be<commit_msg>e428caa8-2e4c-11e5-9284-b827eb9e62be<commit_after>e428caa8-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>7e6cab60-2e4e-11e5-9284-b827eb9e62be<commit_msg>7e71b178-2e4e-11e5-9284-b827eb9e62be<commit_after>7e71b178-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>96c23626-2e4e-11e5-9284-b827eb9e62be<commit_msg>96c771ea-2e4e-11e5-9284-b827eb9e62be<commit_after>96c771ea-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>711ad478-2e4e-11e5-9284-b827eb9e62be<commit_msg>711fdf86-2e4e-11e5-9284-b827eb9e62be<commit_after>711fdf86-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>d9b381b6-2e4d-11e5-9284-b827eb9e62be<commit_msg>d9b87cb6-2e4d-11e5-9284-b827eb9e62be<commit_after>d9b87cb6-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>341439f6-2e4f-11e5-9284-b827eb9e62be<commit_msg>3419332a-2e4f-11e5-9284-b827eb9e62be<commit_after>3419332a-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>36c87406-2e4e-11e5-9284-b827eb9e62be<commit_msg>36cd6c22-2e4e-11e5-9284-b827eb9e62be<commit_after>36cd6c22-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>27ffba56-2e4e-11e5-9284-b827eb9e62be<commit_msg>2804cad2-2e4e-11e5-9284-b827eb9e62be<commit_after>2804cad2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>76acb33e-2e4e-11e5-9284-b827eb9e62be<commit_msg>76b1b762-2e4e-11e5-9284-b827eb9e62be<commit_after>76b1b762-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.