text
stringlengths 54
60.6k
|
|---|
<commit_before>#define DEBUG 1
/**
* File : D2.cpp
* Author : Kazune Takahashi
* Created : 6/23/2019, 5:37:29 AM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <memory>
#include <algorithm>
template <typename T, typename A = std::allocator<T>>
struct vector_base
{ // vector のためのメモリ構造
A alloc;
T *elem; // 先頭
T *space; // 拡張用領域の先頭
T *last; // 終端
vector_base(const A &a, typename A::size_type n = 0, typename A::size_type m = 0)
: alloc{a}, elem{alloc.allocate(n + m)}, space{elem + n}, last{elem + n + m} {}
~vector_base() { alloc.deallocate(elem, last - elem); }
vector_base(const vector_base &) = delete; // コピー演算は行えない
vector_base &operator=(const vector_base &) = delete; // コピー代入演算子も無効化
vector_base(vector_base &&); // ムーブ演算を行う
vector_base &operator=(vector_base &&); // ムーブ代入演算子
};
template <typename T, typename A = std::allocator<T>>
class vector
{
private:
vector_base<T, A> vb;
void destroy_elements();
public:
using size_type = typename A::size_type; // vector 要素用の型
explicit vector(size_type n = 0, const T &val = T(), const A &a = A());
~vector() { destroy_elements(); };
vector(const vector &a); // コピーコンストラクタ
vector &operator=(const vector &a); // コピー代入演算子
vector(vector &&a); // ムーブコンストラクタ
vector &operator=(vector &&a); // ムーブ代入演算子
size_type size() const { return vb.space - vb.elem; }
size_type capacity() const { return vb.last - vb.elem; }
void reserve(size_type n); // 容量を n まで増やす
void resize(size_type n, const T & = {}); // 要素数を n に変更
void clear() { resize(0); }
void push_back(const T &);
T *begin() { return vb.elem; }
T *end() { return vb.space; }
const T &operator[](const size_type t) const { return *(vb.elem + t); }
T &operator[](const size_type t) { return *(vb.elem + t); }
};
template <typename T>
void my_swap(T &a, T &b)
{
T tmp{std::move(a)};
a = std::move(b);
b = std::move(tmp);
}
template <typename T, typename A>
vector_base<T, A>::vector_base(vector_base &&a)
: alloc{a.alloc}, elem{a.elem}, space{a.space}, last{a.last}
{
a.elem = a.space = a.last = nullptr;
}
template <typename T, typename A>
vector_base<T, A> &vector_base<T, A>::operator=(vector_base &&a)
{
std::swap(*this, a);
return *this;
}
template <typename T, typename A>
void vector<T, A>::destroy_elements()
{
for (T *p = vb.elem; p != vb.space; ++p)
{
p->~T();
}
vb.space = vb.elem;
}
template <typename T, typename A>
vector<T, A>::vector(size_type n, const T &val, const A &a) : vb{a, n}
{
std::uninitialized_fill(vb.elem, vb.elem + n, val);
}
template <typename T, typename A>
vector<T, A>::vector(const vector &a) : vb{a.vb.alloc, a.size()}
{
std::uninitialized_copy(a.begin(), a.end(), vb.elem);
}
template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(const vector &a)
{
vector temp{a};
my_swap<vector<T, A>>(*this, temp);
return *this;
}
template <typename T, typename A>
vector<T, A>::vector(vector &&a) : vb{std::move(a.vb)} {}
template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector &&a)
{
my_swap<vector<T, A>>(vb, a.vb);
return *this;
}
/*
template <typename C>
using Value_type = typename C::value_type;
template <typename In, typename Out>
Out uninitialized_move(In b, In e, Out oo)
{
using T = Value_type<Out>;
for (; b != e; ++b, ++oo)
{
new (static_cast<void *>(&*oo)) T{std::move(*b)};
b->~T();
}
return oo;
}
*/
template <typename T, typename A>
void vector<T, A>::reserve(size_type new_alloc)
{
if (new_alloc <= capacity())
{
return;
}
vector_base<T, A> b{vb.alloc, new_alloc - size()};
// uninitialized_move(vb.elem, vb.elem + size(), b.elem);
T *oo = b.elem;
for (auto begin = vb.elem; begin != vb.elem + size(); ++begin, ++oo)
{
new (static_cast<void *>(&*oo)) T{std::move(*begin)};
begin->~T();
}
my_swap<vector_base<T, A>>(vb, b);
}
/*
template <typename In>
void destroy(In b, In e)
{
for (; b != e; ++b)
{
b->~Value_type<In>();
}
}
*/
template <typename T, typename A>
void vector<T, A>::resize(size_type new_size, const T &val)
{
reserve(new_size);
if (size() < new_size)
{
std::uninitialized_fill(vb.elem + size(), vb.elem + new_size, val);
}
else
{
auto b = vb.elem + new_size;
auto e = vb.elem + size();
for (; b != e; ++b)
{
b->~T();
}
}
vb.space = vb.elem + new_size;
}
template <typename T, typename A>
void vector<T, A>::push_back(const T &val)
{
if (capacity() == size())
{
reserve(size() ? 2 * size() : 8);
}
vb.alloc.construct(&vb.elem[size()], val);
++vb.space;
}
typedef long long ll;
int N;
typedef std::pair<ll, ll> work;
vector<work> V;
int main()
{
std::cin >> N;
for (auto i = 0; i < N; i++)
{
ll a, b;
std::cin >> a >> b;
V.push_back(work(b, a));
}
std::sort(V.begin(), V.end());
ll now = 0;
for (auto i = 0; i < N; i++)
{
now += V[i].first;
if (now > V[i].second)
{
std::cout << "No" << std::endl;
return 0;
}
}
std::cout << "Yes" << std::endl;
}<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1
/**
* File : D2.cpp
* Author : Kazune Takahashi
* Created : 6/23/2019, 5:37:29 AM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <memory>
#include <algorithm>
template <typename T, typename A = std::allocator<T>>
struct vector_base
{ // vector のためのメモリ構造
A alloc;
T *elem; // 先頭
T *space; // 拡張用領域の先頭
T *last; // 終端
vector_base(const A &a, typename A::size_type n = 0, typename A::size_type m = 0)
: alloc{a}, elem{alloc.allocate(n + m)}, space{elem + n}, last{elem + n + m} {}
~vector_base() { alloc.deallocate(elem, last - elem); }
vector_base(const vector_base &) = delete; // コピー演算は行えない
vector_base &operator=(const vector_base &) = delete; // コピー代入演算子も無効化
vector_base(vector_base &&); // ムーブ演算を行う
vector_base &operator=(vector_base &&); // ムーブ代入演算子
};
template <typename T, typename A = std::allocator<T>>
class vector
{
private:
vector_base<T, A> vb;
void destroy_elements();
public:
using size_type = typename A::size_type; // vector 要素用の型
explicit vector(size_type n = 0, const T &val = T(), const A &a = A());
~vector() { destroy_elements(); };
vector(const vector &a); // コピーコンストラクタ
vector &operator=(const vector &a); // コピー代入演算子
vector(vector &&a); // ムーブコンストラクタ
vector &operator=(vector &&a); // ムーブ代入演算子
size_type size() const { return vb.space - vb.elem; }
size_type capacity() const { return vb.last - vb.elem; }
void reserve(size_type n); // 容量を n まで増やす
void resize(size_type n, const T & = {}); // 要素数を n に変更
void clear() { resize(0); }
void push_back(const T &);
T *begin() { return vb.elem; }
T *end() { return vb.space; }
const T &operator[](const size_type t) const { return *(vb.elem + t); }
T &operator[](const size_type t) { return *(vb.elem + t); }
};
template <typename T, typename A>
vector_base<T, A>::vector_base(vector_base &&a)
: alloc{a.alloc}, elem{a.elem}, space{a.space}, last{a.last}
{
a.elem = a.space = a.last = nullptr;
}
template <typename T, typename A>
vector_base<T, A> &vector_base<T, A>::operator=(vector_base &&a)
{
std::swap(*this, a);
return *this;
}
template <typename T, typename A>
void vector<T, A>::destroy_elements()
{
for (T *p = vb.elem; p != vb.space; ++p)
{
p->~T();
}
vb.space = vb.elem;
}
template <typename T, typename A>
vector<T, A>::vector(size_type n, const T &val, const A &a) : vb{a, n}
{
std::uninitialized_fill(vb.elem, vb.elem + n, val);
}
template <typename T, typename A>
vector<T, A>::vector(const vector &a) : vb{a.vb.alloc, a.size()}
{
std::uninitialized_copy(a.begin(), a.end(), vb.elem);
}
template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(const vector &a)
{
vector temp{a};
std::swap(*this, temp);
return *this;
}
template <typename T, typename A>
vector<T, A>::vector(vector &&a) : vb{std::move(a.vb)} {}
template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector &&a)
{
std::swap(vb, a.vb);
return *this;
}
/*
template <typename C>
using Value_type = typename C::value_type;
template <typename In, typename Out>
Out uninitialized_move(In b, In e, Out oo)
{
using T = Value_type<Out>;
for (; b != e; ++b, ++oo)
{
new (static_cast<void *>(&*oo)) T{std::move(*b)};
b->~T();
}
return oo;
}
*/
template <typename T, typename A>
void vector<T, A>::reserve(size_type new_alloc)
{
if (new_alloc <= capacity())
{
return;
}
vector_base<T, A> b{vb.alloc, new_alloc - size()};
// uninitialized_move(vb.elem, vb.elem + size(), b.elem);
T *oo = b.elem;
for (auto begin = vb.elem; begin != vb.elem + size(); ++begin, ++oo)
{
new (static_cast<void *>(&*oo)) T{std::move(*begin)};
begin->~T();
}
vb = move(b);
}
/*
template <typename In>
void destroy(In b, In e)
{
for (; b != e; ++b)
{
b->~Value_type<In>();
}
}
*/
template <typename T, typename A>
void vector<T, A>::resize(size_type new_size, const T &val)
{
reserve(new_size);
if (size() < new_size)
{
std::uninitialized_fill(vb.elem + size(), vb.elem + new_size, val);
}
else
{
auto b = vb.elem + new_size;
auto e = vb.elem + size();
for (; b != e; ++b)
{
b->~T();
}
}
vb.space = vb.elem + new_size;
}
template <typename T, typename A>
void vector<T, A>::push_back(const T &val)
{
if (capacity() == size())
{
reserve(size() ? 2 * size() : 8);
}
vb.alloc.construct(&vb.elem[size()], val);
++vb.space;
}
typedef long long ll;
int N;
typedef std::pair<ll, ll> work;
vector<work> V;
int main()
{
std::cin >> N;
for (auto i = 0; i < N; i++)
{
ll a, b;
std::cin >> a >> b;
V.push_back(work(b, a));
}
std::sort(V.begin(), V.end());
ll now = 0;
for (auto i = 0; i < N; i++)
{
now += V[i].first;
if (now > V[i].second)
{
std::cout << "No" << std::endl;
return 0;
}
}
std::cout << "Yes" << std::endl;
}<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : D2.cpp
* Author : Kazune Takahashi
* Created : 11/13/2019, 7:24:07 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "0 1" << endl;
exit(0);
}
using Info = tuple<ll, ll>;
int main()
{
int N;
cin >> N;
vector<Info> V(N);
ll A_sum{0LL};
for (auto i = 0; i < N; i++)
{
ll A, B;
cin >> A >> B;
V[i] = Info(max(A, B), B);
A_sum += A;
}
sort(V.rbegin(), V.rend());
vector<ll> C_sum(N + 1);
C_sum[0] = 0;
for (auto i = 0; i < N; i++)
{
C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
}
if (C_sum[N] == A_sum)
{
No();
}
rational<ll> ans{0, 1};
for (auto k = 0; k < N; k++)
{
ll B_k{get<1>(V[k])};
ll ok{N}, ng{-1};
ll tmp_sum{0};
bool included{false};
while (abs(ok - ng) > 1)
{
ll t{(ok + ng) / 2};
ll tmp{C_sum[t]};
if (k < t)
{
tmp -= B_k;
}
if (tmp + B_k >= A_sum)
{
ok = t;
included = k < t;
tmp_sum = tmp;
}
else
{
ng = t;
}
}
rational<ll> r{A_sum - tmp_sum, B_k};
#if DEBUG == 1
cerr << "k = " << k << ", B_k = " << B_k << ", tmp_sum = " << tmp_sum << ", r = " << r << endl;
#endif
if (r < 0)
{
r = rational<ll>(0);
}
ll M{included ? ok + 1 : ok};
rational<ll> tmp_ans = (N - M - r) / N;
ch_max(ans, tmp_ans);
}
cout << ans.numerator() << " " << ans.denominator() << endl;
}
<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1
/**
* File : D2.cpp
* Author : Kazune Takahashi
* Created : 11/13/2019, 7:24:07 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{x % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "0 1" << endl;
exit(0);
}
using Info = tuple<ll, ll>;
int main()
{
int N;
cin >> N;
vector<Info> V(N);
ll A_sum{0LL};
for (auto i = 0; i < N; i++)
{
ll A, B;
cin >> A >> B;
V[i] = Info(max(A, B), B);
A_sum += A;
}
sort(V.rbegin(), V.rend());
vector<ll> C_sum(N + 1);
C_sum[0] = 0;
for (auto i = 0; i < N; i++)
{
C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
}
if (C_sum[N] == A_sum)
{
No();
}
rational<ll> ans{0, 1};
for (auto k = 0; k < N; k++)
{
ll B_k{get<1>(V[k])};
ll ok{N}, ng{-1};
ll tmp_sum{0};
bool included{false};
while (abs(ok - ng) > 1)
{
ll t{(ok + ng) / 2};
ll tmp{C_sum[t]};
if (k < t)
{
tmp -= B_k;
}
if (tmp + B_k >= A_sum)
{
ok = t;
included = k < t;
tmp_sum = tmp;
}
else
{
ng = t;
}
}
rational<ll> r{A_sum - tmp_sum, B_k};
#if DEBUG == 1
cerr << "k = " << k << ", B_k = " << B_k << ", tmp_sum = " << tmp_sum << ", r = " << r << endl;
#endif
if (r < 0)
{
r = rational<ll>(0);
}
ll M{included ? ok : ok};
rational<ll> tmp_ans = (N - M - r) / N;
ch_max(ans, tmp_ans);
}
cout << ans.numerator() << " " << ans.denominator() << endl;
}
<|endoftext|>
|
<commit_before>#include "texture.h"
#include "stb_image.h"
#include <iostream>
#include <cassert>
std::map<std::string, TextureData*> Texture::s_resourceMap;
TextureData::TextureData(GLenum textureTarget, int width, int height, int numTextures, unsigned char** data, GLfloat* filters, GLenum* attachments)
{
m_textureID = new GLuint[numTextures];
m_textureTarget = textureTarget;
m_numTextures = numTextures;
m_width = width;
m_height = height;
m_frameBuffer = 0;
m_renderBuffer = 0;
InitTextures(data, filters);
InitRenderTargets(attachments);
}
TextureData::~TextureData()
{
if(*m_textureID) glDeleteTextures(m_numTextures, m_textureID);
if(m_frameBuffer) glDeleteFramebuffers(1, &m_frameBuffer);
if(m_renderBuffer) glDeleteRenderbuffers(1, &m_renderBuffer);
if(m_textureID) delete[] m_textureID;
}
void TextureData::InitTextures(unsigned char** data, GLfloat* filters)
{
glGenTextures(m_numTextures, m_textureID);
for(int i = 0; i < m_numTextures; i++)
{
glBindTexture(m_textureTarget, m_textureID[i]);
glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, filters[i]);
glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, filters[i]);
glTexImage2D(m_textureTarget, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data[i]);
}
}
void TextureData::InitRenderTargets(GLenum* attachments)
{
if(attachments == 0)
return;
GLenum drawBuffers[m_numTextures];
bool hasDepth = false;
for(int i = 0; i < m_numTextures; i++)
{
if(attachments[i] == GL_DEPTH_ATTACHMENT)
{
drawBuffers[i] = GL_NONE;
hasDepth = true;
}
else
drawBuffers[i] = attachments[i];
if(attachments[i] == GL_NONE)
continue;
if(m_frameBuffer == 0)
{
glGenFramebuffers(1, &m_frameBuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_frameBuffer);
}
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachments[i], m_textureTarget, m_textureID[i], 0);
}
if(m_frameBuffer == 0)
return;
if(!hasDepth)
{
glGenRenderbuffers(1, &m_renderBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_width, m_height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_renderBuffer);
}
glDrawBuffers(m_numTextures, drawBuffers);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "Framebuffer creation failed!" << std::endl;
assert(false);
}
}
void TextureData::Bind(int textureNum)
{
glBindTexture(m_textureTarget, m_textureID[textureNum]);
}
void TextureData::BindAsRenderTarget()
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_frameBuffer);
glViewport(0, 0, m_width, m_height);
}
Texture::Texture(const std::string& fileName, GLenum textureTarget, GLfloat filter, GLenum attachment)
{
m_fileName = fileName;
std::map<std::string, TextureData*>::const_iterator it = s_resourceMap.find(fileName);
if(it != s_resourceMap.end())
{
m_textureData = it->second;
m_textureData->AddReference();
}
else
{
int x, y, bytesPerPixel;
unsigned char* data = stbi_load(("./res/textures/" + fileName).c_str(), &x, &y, &bytesPerPixel, 4);
if(data == NULL)
{
std::cerr << "Unable to load texture: " << fileName << std::endl;
}
m_textureData = new TextureData(textureTarget, x, y, 1, &data, &filter, &attachment);
stbi_image_free(data);
s_resourceMap.insert(std::pair<std::string, TextureData*>(fileName, m_textureData));
}
}
Texture::Texture(int width, int height, unsigned char* data, GLenum textureTarget, GLfloat filter, GLenum attachment)
{
m_fileName = "";
m_textureData = new TextureData(textureTarget, width, height, 1, &data, &filter, &attachment);
}
Texture::~Texture()
{
if(m_textureData && m_textureData->RemoveReference())
{
if(m_fileName.length() > 0)
s_resourceMap.erase(m_fileName);
delete m_textureData;
}
}
void Texture::Bind(unsigned int unit) const
{
assert(unit >= 0 && unit <= 31);
glActiveTexture(GL_TEXTURE0 + unit);
m_textureData->Bind(0);
}
void Texture::BindAsRenderTarget()
{
m_textureData->BindAsRenderTarget();
}
<commit_msg>Fixed drawBuffer issue<commit_after>#include "texture.h"
#include "stb_image.h"
#include <iostream>
#include <cassert>
std::map<std::string, TextureData*> Texture::s_resourceMap;
TextureData::TextureData(GLenum textureTarget, int width, int height, int numTextures, unsigned char** data, GLfloat* filters, GLenum* attachments)
{
m_textureID = new GLuint[numTextures];
m_textureTarget = textureTarget;
m_numTextures = numTextures;
m_width = width;
m_height = height;
m_frameBuffer = 0;
m_renderBuffer = 0;
InitTextures(data, filters);
InitRenderTargets(attachments);
}
TextureData::~TextureData()
{
if(*m_textureID) glDeleteTextures(m_numTextures, m_textureID);
if(m_frameBuffer) glDeleteFramebuffers(1, &m_frameBuffer);
if(m_renderBuffer) glDeleteRenderbuffers(1, &m_renderBuffer);
if(m_textureID) delete[] m_textureID;
}
void TextureData::InitTextures(unsigned char** data, GLfloat* filters)
{
glGenTextures(m_numTextures, m_textureID);
for(int i = 0; i < m_numTextures; i++)
{
glBindTexture(m_textureTarget, m_textureID[i]);
glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, filters[i]);
glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, filters[i]);
glTexImage2D(m_textureTarget, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data[i]);
}
}
void TextureData::InitRenderTargets(GLenum* attachments)
{
if(attachments == 0)
return;
GLenum drawBuffers[32]; //32 is the max number of bound textures in OpenGL
assert(m_numTextures <= 32); //Assert to be sure no buffer overrun should occur
bool hasDepth = false;
for(int i = 0; i < m_numTextures; i++)
{
if(attachments[i] == GL_DEPTH_ATTACHMENT)
{
drawBuffers[i] = GL_NONE;
hasDepth = true;
}
else
drawBuffers[i] = attachments[i];
if(attachments[i] == GL_NONE)
continue;
if(m_frameBuffer == 0)
{
glGenFramebuffers(1, &m_frameBuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_frameBuffer);
}
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachments[i], m_textureTarget, m_textureID[i], 0);
}
if(m_frameBuffer == 0)
return;
if(!hasDepth)
{
glGenRenderbuffers(1, &m_renderBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_width, m_height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_renderBuffer);
}
glDrawBuffers(m_numTextures, drawBuffers);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "Framebuffer creation failed!" << std::endl;
assert(false);
}
}
void TextureData::Bind(int textureNum)
{
glBindTexture(m_textureTarget, m_textureID[textureNum]);
}
void TextureData::BindAsRenderTarget()
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_frameBuffer);
glViewport(0, 0, m_width, m_height);
}
Texture::Texture(const std::string& fileName, GLenum textureTarget, GLfloat filter, GLenum attachment)
{
m_fileName = fileName;
std::map<std::string, TextureData*>::const_iterator it = s_resourceMap.find(fileName);
if(it != s_resourceMap.end())
{
m_textureData = it->second;
m_textureData->AddReference();
}
else
{
int x, y, bytesPerPixel;
unsigned char* data = stbi_load(("./res/textures/" + fileName).c_str(), &x, &y, &bytesPerPixel, 4);
if(data == NULL)
{
std::cerr << "Unable to load texture: " << fileName << std::endl;
}
m_textureData = new TextureData(textureTarget, x, y, 1, &data, &filter, &attachment);
stbi_image_free(data);
s_resourceMap.insert(std::pair<std::string, TextureData*>(fileName, m_textureData));
}
}
Texture::Texture(int width, int height, unsigned char* data, GLenum textureTarget, GLfloat filter, GLenum attachment)
{
m_fileName = "";
m_textureData = new TextureData(textureTarget, width, height, 1, &data, &filter, &attachment);
}
Texture::~Texture()
{
if(m_textureData && m_textureData->RemoveReference())
{
if(m_fileName.length() > 0)
s_resourceMap.erase(m_fileName);
delete m_textureData;
}
}
void Texture::Bind(unsigned int unit) const
{
assert(unit >= 0 && unit <= 31);
glActiveTexture(GL_TEXTURE0 + unit);
m_textureData->Bind(0);
}
void Texture::BindAsRenderTarget()
{
m_textureData->BindAsRenderTarget();
}
<|endoftext|>
|
<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Get hostname for an IP. Hostnames are checked with reverse name lookup and
checked that they doesn't resemble an ip.
*/
#include "mysql_priv.h"
#include "hash_filo.h"
#include <m_ctype.h>
#ifdef __cplusplus
extern "C" { // Because of SCO 3.2V4.2
#endif
#if !defined( __WIN__) && !defined(OS2)
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#include <netdb.h>
#include <sys/utsname.h>
#endif // __WIN__
#ifdef __cplusplus
}
#endif
class host_entry :public hash_filo_element
{
public:
char ip[sizeof(((struct in_addr *) 0)->s_addr)];
uint errors;
char *hostname;
};
static hash_filo *hostname_cache;
static pthread_mutex_t LOCK_hostname;
void hostname_cache_refresh()
{
hostname_cache->clear();
}
bool hostname_cache_init()
{
host_entry tmp;
uint offset= (uint) ((char*) (&tmp.ip) - (char*) &tmp);
if (!(hostname_cache=new hash_filo(HOST_CACHE_SIZE, offset,
sizeof(struct in_addr),NULL,
(hash_free_key) free,
&my_charset_latin1)))
return 1;
hostname_cache->clear();
(void) pthread_mutex_init(&LOCK_hostname,MY_MUTEX_INIT_SLOW);
return 0;
}
void hostname_cache_free()
{
if (hostname_cache)
{
(void) pthread_mutex_destroy(&LOCK_hostname);
delete hostname_cache;
hostname_cache= 0;
}
}
static void add_hostname(struct in_addr *in,const char *name)
{
if (!(specialflag & SPECIAL_NO_HOST_CACHE))
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
host_entry *entry;
if (!(entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
{
uint length=name ? (uint) strlen(name) : 0;
if ((entry=(host_entry*) malloc(sizeof(host_entry)+length+1)))
{
char *new_name;
memcpy_fixed(&entry->ip, &in->s_addr, sizeof(in->s_addr));
if (length)
memcpy(new_name= (char *) (entry+1), name, length+1);
else
new_name=0;
entry->hostname=new_name;
entry->errors=0;
(void) hostname_cache->add(entry);
}
}
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
}
inline void add_wrong_ip(struct in_addr *in)
{
add_hostname(in,NullS);
}
void inc_host_errors(struct in_addr *in)
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
host_entry *entry;
if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
entry->errors++;
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
void reset_host_errors(struct in_addr *in)
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
host_entry *entry;
if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
entry->errors=0;
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
/* Deal with systems that don't defined INADDR_LOOPBACK */
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK 0x7f000001UL
#endif
my_string ip_to_hostname(struct in_addr *in, uint *errors)
{
uint i;
host_entry *entry;
DBUG_ENTER("ip_to_hostname");
*errors=0;
/* We always treat the loopback address as "localhost". */
if (in->s_addr == INADDR_LOOPBACK)
return (char *)my_localhost;
/* Check first if we have name in cache */
if (!(specialflag & SPECIAL_NO_HOST_CACHE))
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
{
char *name;
if (!entry->hostname)
name=0; // Don't allow connection
else
name=my_strdup(entry->hostname,MYF(0));
*errors= entry->errors;
VOID(pthread_mutex_unlock(&hostname_cache->lock));
DBUG_RETURN(name);
}
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
struct hostent *hp, *check;
char *name;
LINT_INIT(check);
#if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST)
char buff[GETHOSTBYADDR_BUFF_SIZE],buff2[GETHOSTBYNAME_BUFF_SIZE];
int tmp_errno;
struct hostent tmp_hostent, tmp_hostent2;
#ifdef HAVE_purify
bzero(buff,sizeof(buff)); // Bug in purify
#endif
if (!(hp=gethostbyaddr_r((char*) in,sizeof(*in),
AF_INET,
&tmp_hostent,buff,sizeof(buff),&tmp_errno)))
{
DBUG_PRINT("error",("gethostbyaddr_r returned %d",tmp_errno));
return 0;
}
if (!(check=my_gethostbyname_r(hp->h_name,&tmp_hostent2,buff2,sizeof(buff2),
&tmp_errno)))
{
DBUG_PRINT("error",("gethostbyname_r returned %d",tmp_errno));
/*
Don't cache responses when the DSN server is down, as otherwise
transient DNS failure may leave any number of clients (those
that attempted to connect during the outage) unable to connect
indefinitely.
*/
if (tmp_errno == HOST_NOT_FOUND || tmp_errno == NO_DATA)
add_wrong_ip(in);
my_gethostbyname_r_free();
DBUG_RETURN(0);
}
if (!hp->h_name[0])
{
DBUG_PRINT("error",("Got an empty hostname"));
add_wrong_ip(in);
my_gethostbyname_r_free();
DBUG_RETURN(0); // Don't allow empty hostnames
}
if (!(name=my_strdup(hp->h_name,MYF(0))))
{
my_gethostbyname_r_free();
DBUG_RETURN(0); // out of memory
}
my_gethostbyname_r_free();
#else
VOID(pthread_mutex_lock(&LOCK_hostname));
if (!(hp=gethostbyaddr((char*) in,sizeof(*in), AF_INET)))
{
VOID(pthread_mutex_unlock(&LOCK_hostname));
DBUG_PRINT("error",("gethostbyaddr returned %d",errno));
if (errno == HOST_NOT_FOUND || errno == NO_DATA)
goto add_wrong_ip_and_return;
/* Failure, don't cache responce */
DBUG_RETURN(0);
}
if (!hp->h_name[0]) // Don't allow empty hostnames
{
VOID(pthread_mutex_unlock(&LOCK_hostname));
DBUG_PRINT("error",("Got an empty hostname"));
goto add_wrong_ip_and_return;
}
if (!(name=my_strdup(hp->h_name,MYF(0))))
{
VOID(pthread_mutex_unlock(&LOCK_hostname));
DBUG_RETURN(0); // out of memory
}
check=gethostbyname(name);
VOID(pthread_mutex_unlock(&LOCK_hostname));
if (!check)
{
DBUG_PRINT("error",("gethostbyname returned %d",errno));
my_free(name,MYF(0));
DBUG_RETURN(0);
}
#endif
/* Don't accept hostnames that starts with digits because they may be
false ip:s */
if (my_isdigit(&my_charset_latin1,name[0]))
{
char *pos;
for (pos= name+1 ; my_isdigit(&my_charset_latin1,*pos); pos++) ;
if (*pos == '.')
{
DBUG_PRINT("error",("mysqld doesn't accept hostnames that starts with a number followed by a '.'"));
my_free(name,MYF(0));
goto add_wrong_ip_and_return;
}
}
/* Check that 'gethostbyname' returned the used ip */
for (i=0; check->h_addr_list[i]; i++)
{
if (*(uint32*)(check->h_addr_list)[i] == in->s_addr)
{
add_hostname(in,name);
DBUG_RETURN(name);
}
}
DBUG_PRINT("error",("Couldn't verify hostname with gethostbyname"));
my_free(name,MYF(0));
add_wrong_ip_and_return:
add_wrong_ip(in);
DBUG_RETURN(0);
}
<commit_msg>Fix shortcircuit of 127.0.0.1 -> localhost lookup on little-endian machines. (Bug #11822)<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Get hostname for an IP. Hostnames are checked with reverse name lookup and
checked that they doesn't resemble an ip.
*/
#include "mysql_priv.h"
#include "hash_filo.h"
#include <m_ctype.h>
#ifdef __cplusplus
extern "C" { // Because of SCO 3.2V4.2
#endif
#if !defined( __WIN__) && !defined(OS2)
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#include <netdb.h>
#include <sys/utsname.h>
#endif // __WIN__
#ifdef __cplusplus
}
#endif
class host_entry :public hash_filo_element
{
public:
char ip[sizeof(((struct in_addr *) 0)->s_addr)];
uint errors;
char *hostname;
};
static hash_filo *hostname_cache;
static pthread_mutex_t LOCK_hostname;
void hostname_cache_refresh()
{
hostname_cache->clear();
}
bool hostname_cache_init()
{
host_entry tmp;
uint offset= (uint) ((char*) (&tmp.ip) - (char*) &tmp);
if (!(hostname_cache=new hash_filo(HOST_CACHE_SIZE, offset,
sizeof(struct in_addr),NULL,
(hash_free_key) free,
&my_charset_latin1)))
return 1;
hostname_cache->clear();
(void) pthread_mutex_init(&LOCK_hostname,MY_MUTEX_INIT_SLOW);
return 0;
}
void hostname_cache_free()
{
if (hostname_cache)
{
(void) pthread_mutex_destroy(&LOCK_hostname);
delete hostname_cache;
hostname_cache= 0;
}
}
static void add_hostname(struct in_addr *in,const char *name)
{
if (!(specialflag & SPECIAL_NO_HOST_CACHE))
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
host_entry *entry;
if (!(entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
{
uint length=name ? (uint) strlen(name) : 0;
if ((entry=(host_entry*) malloc(sizeof(host_entry)+length+1)))
{
char *new_name;
memcpy_fixed(&entry->ip, &in->s_addr, sizeof(in->s_addr));
if (length)
memcpy(new_name= (char *) (entry+1), name, length+1);
else
new_name=0;
entry->hostname=new_name;
entry->errors=0;
(void) hostname_cache->add(entry);
}
}
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
}
inline void add_wrong_ip(struct in_addr *in)
{
add_hostname(in,NullS);
}
void inc_host_errors(struct in_addr *in)
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
host_entry *entry;
if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
entry->errors++;
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
void reset_host_errors(struct in_addr *in)
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
host_entry *entry;
if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
entry->errors=0;
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
/* Deal with systems that don't defined INADDR_LOOPBACK */
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK 0x7f000001UL
#endif
my_string ip_to_hostname(struct in_addr *in, uint *errors)
{
uint i;
host_entry *entry;
DBUG_ENTER("ip_to_hostname");
*errors=0;
/* We always treat the loopback address as "localhost". */
if (in->s_addr == htonl(INADDR_LOOPBACK))
DBUG_RETURN((char *)my_localhost);
/* Check first if we have name in cache */
if (!(specialflag & SPECIAL_NO_HOST_CACHE))
{
VOID(pthread_mutex_lock(&hostname_cache->lock));
if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0)))
{
char *name;
if (!entry->hostname)
name=0; // Don't allow connection
else
name=my_strdup(entry->hostname,MYF(0));
*errors= entry->errors;
VOID(pthread_mutex_unlock(&hostname_cache->lock));
DBUG_RETURN(name);
}
VOID(pthread_mutex_unlock(&hostname_cache->lock));
}
struct hostent *hp, *check;
char *name;
LINT_INIT(check);
#if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST)
char buff[GETHOSTBYADDR_BUFF_SIZE],buff2[GETHOSTBYNAME_BUFF_SIZE];
int tmp_errno;
struct hostent tmp_hostent, tmp_hostent2;
#ifdef HAVE_purify
bzero(buff,sizeof(buff)); // Bug in purify
#endif
if (!(hp=gethostbyaddr_r((char*) in,sizeof(*in),
AF_INET,
&tmp_hostent,buff,sizeof(buff),&tmp_errno)))
{
DBUG_PRINT("error",("gethostbyaddr_r returned %d",tmp_errno));
return 0;
}
if (!(check=my_gethostbyname_r(hp->h_name,&tmp_hostent2,buff2,sizeof(buff2),
&tmp_errno)))
{
DBUG_PRINT("error",("gethostbyname_r returned %d",tmp_errno));
/*
Don't cache responses when the DSN server is down, as otherwise
transient DNS failure may leave any number of clients (those
that attempted to connect during the outage) unable to connect
indefinitely.
*/
if (tmp_errno == HOST_NOT_FOUND || tmp_errno == NO_DATA)
add_wrong_ip(in);
my_gethostbyname_r_free();
DBUG_RETURN(0);
}
if (!hp->h_name[0])
{
DBUG_PRINT("error",("Got an empty hostname"));
add_wrong_ip(in);
my_gethostbyname_r_free();
DBUG_RETURN(0); // Don't allow empty hostnames
}
if (!(name=my_strdup(hp->h_name,MYF(0))))
{
my_gethostbyname_r_free();
DBUG_RETURN(0); // out of memory
}
my_gethostbyname_r_free();
#else
VOID(pthread_mutex_lock(&LOCK_hostname));
if (!(hp=gethostbyaddr((char*) in,sizeof(*in), AF_INET)))
{
VOID(pthread_mutex_unlock(&LOCK_hostname));
DBUG_PRINT("error",("gethostbyaddr returned %d",errno));
if (errno == HOST_NOT_FOUND || errno == NO_DATA)
goto add_wrong_ip_and_return;
/* Failure, don't cache responce */
DBUG_RETURN(0);
}
if (!hp->h_name[0]) // Don't allow empty hostnames
{
VOID(pthread_mutex_unlock(&LOCK_hostname));
DBUG_PRINT("error",("Got an empty hostname"));
goto add_wrong_ip_and_return;
}
if (!(name=my_strdup(hp->h_name,MYF(0))))
{
VOID(pthread_mutex_unlock(&LOCK_hostname));
DBUG_RETURN(0); // out of memory
}
check=gethostbyname(name);
VOID(pthread_mutex_unlock(&LOCK_hostname));
if (!check)
{
DBUG_PRINT("error",("gethostbyname returned %d",errno));
my_free(name,MYF(0));
DBUG_RETURN(0);
}
#endif
/* Don't accept hostnames that starts with digits because they may be
false ip:s */
if (my_isdigit(&my_charset_latin1,name[0]))
{
char *pos;
for (pos= name+1 ; my_isdigit(&my_charset_latin1,*pos); pos++) ;
if (*pos == '.')
{
DBUG_PRINT("error",("mysqld doesn't accept hostnames that starts with a number followed by a '.'"));
my_free(name,MYF(0));
goto add_wrong_ip_and_return;
}
}
/* Check that 'gethostbyname' returned the used ip */
for (i=0; check->h_addr_list[i]; i++)
{
if (*(uint32*)(check->h_addr_list)[i] == in->s_addr)
{
add_hostname(in,name);
DBUG_RETURN(name);
}
}
DBUG_PRINT("error",("Couldn't verify hostname with gethostbyname"));
my_free(name,MYF(0));
add_wrong_ip_and_return:
add_wrong_ip(in);
DBUG_RETURN(0);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbCommandLineArgumentParser.h"
#include "otbMacro.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbGCPsToRPCSensorModelImageFilter.h"
#include "otbGenericRSTransform.h"
#include "otbGeoInformationConversion.h"
#include "otbGeographicalDistance.h"
int otbGCPsToRPCSensorModelImageFilterCheckRpcModel(int argc, char* argv[])
{
// Set command line arguments
typedef otb::CommandLineArgumentParser ParserType;
ParserType::Pointer parser = ParserType::New();
parser->AddInputImage();
parser->AddOption("--DEMDirectory", "Path to the DEM directory ", "-dem", 1, false);
parser->AddOptionNParams("--GroudControlPoints",
"Ground Control Points to estimate sensor model a1x a1y b1x b1y b1z ... aNx aNy aNz bNx bNy bNz",
"-gcp", true);
parser->AddOption("--ErrorAllowed", "Error allowed to declare a point not good ", "-err", 1, false);
// Parse the command line
typedef otb::CommandLineArgumentParseResult ParserResultType;
ParserResultType::Pointer parseResult = ParserResultType::New();
try
{
parser->ParseCommandLine(argc, argv, parseResult);
}
catch ( itk::ExceptionObject & err )
{
std::string descriptionException = err.GetDescription();
if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
{
return EXIT_SUCCESS;
}
if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
// Check if the number of gcp pairs point is consistent
unsigned int nbPoints = parseResult->GetNumberOfParameters("--GroudControlPoints");
if (nbPoints % 5 != 0)
{
std::cerr << "Inconsistent GCPs description!" << std::endl;
return EXIT_FAILURE;
}
typedef otb::VectorImage<float, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::GCPsToRPCSensorModelImageFilter<ImageType> GCPsToSensorModelFilterType;
typedef GCPsToSensorModelFilterType::Point2DType Point2DType;
typedef GCPsToSensorModelFilterType::Point3DType Point3DType;
typedef otb::GenericRSTransform<double, 2, 2> GenericRSTransformType;
typedef otb::GeographicalDistance<ImageType::PointType> GeoDistanceType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(parseResult->GetInputImage());
reader->UpdateOutputInformation();
GCPsToSensorModelFilterType::Pointer rpcEstimator = GCPsToSensorModelFilterType::New();
rpcEstimator->SetInput(reader->GetOutput());
unsigned int nbGCPs = nbPoints / 5;
std::cout << "Receiving " << nbPoints << " from command line." << std::endl;
for (unsigned int gcpId = 0; gcpId < nbGCPs; ++gcpId)
{
Point2DType sensorPoint;
sensorPoint[0] = parseResult->GetParameterFloat("--GroudControlPoints", gcpId * 5);
sensorPoint[1] = parseResult->GetParameterFloat("--GroudControlPoints", 1 + gcpId * 5);
Point3DType geoPoint;
geoPoint[0] = parseResult->GetParameterFloat("--GroudControlPoints", 2 + gcpId * 5);
geoPoint[1] = parseResult->GetParameterFloat("--GroudControlPoints", 3 + gcpId * 5);
geoPoint[2] = parseResult->GetParameterFloat("--GroudControlPoints", 4 + gcpId * 5);
std::cout << "Adding GCP sensor: " << sensorPoint << " <-> geo: " << geoPoint << std::endl;
rpcEstimator->AddGCP(sensorPoint, geoPoint);
}
// Estimate the rpc model
rpcEstimator->GetOutput()->UpdateOutputInformation();
// Instancicate a GenericRSTransform in order to transform the
// indexes, using the rpcModel estimated, into geographical
// coordiantes.
// The test will check for nan coordinates, and the distance between
// geographical coordinates.
GenericRSTransformType::Pointer grsTrasnform = GenericRSTransformType::New();
grsTrasnform->SetInputKeywordList(rpcEstimator->GetKeywordlist());
grsTrasnform->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));
// Set the DEM Directory if any
if(parseResult->IsOptionPresent("--DEMDirectory"))
{
grsTrasnform->SetDEMDirectory(parseResult->GetParameterString("--DEMDirectory"));
}
grsTrasnform->InstanciateTransform();
// Test
GeoDistanceType::Pointer geoDistance = GeoDistanceType::New();
bool isErrorDetected = false;
for (unsigned int gcpId = 0; gcpId < nbGCPs; ++gcpId)
{
ImageType::IndexType index;
index[0] = parseResult->GetParameterFloat("--GroudControlPoints", gcpId * 5);
index[1] = parseResult->GetParameterFloat("--GroudControlPoints", 1 + gcpId * 5);
ImageType::PointType point, transformedPoint;
reader->GetOutput()->TransformIndexToPhysicalPoint(index, point);
transformedPoint = grsTrasnform->TransformPoint(point);
// reference point
ImageType::PointType geoPoint;
geoPoint[0] = parseResult->GetParameterFloat("--GroudControlPoints", 2 + gcpId * 5);
geoPoint[1] = parseResult->GetParameterFloat("--GroudControlPoints", 3 + gcpId * 5);
// Search for nans
if ( vnl_math_isnan(transformedPoint[0]) || vnl_math_isnan(transformedPoint[1]) )
{
std::cout << "Reference : "<< geoPoint
<<" --> Result of the reprojection using the estimated RpcModel "<< transformedPoint
<< std::endl;
std::cout<<"The result of the projection is nan, there is a problem with the estimated RpcModel "
<< std::endl<<std::endl;
isErrorDetected = true;
}
// Search for wrong projection results
double residual = geoDistance->Evaluate(geoPoint, transformedPoint);
if( residual > parseResult->GetParameterFloat("--ErrorAllowed"))
{
std::cout << "Reference : "<< geoPoint
<<" --> Result of the reprojection using the estimated RpcModel "
<< grsTrasnform->TransformPoint(point)
<< std::endl
<< " Residual ["<< residual << "] is higher than the tolerance ["
<< parseResult->GetParameterFloat("--ErrorAllowed")
<<"], there is a problem with the estimated RpcModel"
<<std::endl<<std::endl;
isErrorDetected = true;
}
}
// Is there an error
if ( isErrorDetected )
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<commit_msg>ENH: add average elevation<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbCommandLineArgumentParser.h"
#include "otbMacro.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbGCPsToRPCSensorModelImageFilter.h"
#include "otbGenericRSTransform.h"
#include "otbGeoInformationConversion.h"
#include "otbGeographicalDistance.h"
int otbGCPsToRPCSensorModelImageFilterCheckRpcModel(int argc, char* argv[])
{
// Set command line arguments
typedef otb::CommandLineArgumentParser ParserType;
ParserType::Pointer parser = ParserType::New();
parser->AddInputImage();
parser->AddOption("--DEMDirectory", "Path to the DEM directory ", "-dem", 1, false);
parser->AddOptionNParams("--GroudControlPoints",
"Ground Control Points to estimate sensor model a1x a1y b1x b1y b1z ... aNx aNy aNz bNx bNy bNz",
"-gcp", true);
parser->AddOption("--ErrorAllowed", "Error allowed to declare a point not good ", "-err", 1, false);
// Parse the command line
typedef otb::CommandLineArgumentParseResult ParserResultType;
ParserResultType::Pointer parseResult = ParserResultType::New();
try
{
parser->ParseCommandLine(argc, argv, parseResult);
}
catch ( itk::ExceptionObject & err )
{
std::string descriptionException = err.GetDescription();
if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
{
return EXIT_SUCCESS;
}
if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
{
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
// Check if the number of gcp pairs point is consistent
unsigned int nbPoints = parseResult->GetNumberOfParameters("--GroudControlPoints");
if (nbPoints % 5 != 0)
{
std::cerr << "Inconsistent GCPs description!" << std::endl;
return EXIT_FAILURE;
}
typedef otb::VectorImage<float, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::GCPsToRPCSensorModelImageFilter<ImageType> GCPsToSensorModelFilterType;
typedef GCPsToSensorModelFilterType::Point2DType Point2DType;
typedef GCPsToSensorModelFilterType::Point3DType Point3DType;
typedef otb::GenericRSTransform<double, 2, 2> GenericRSTransformType;
typedef otb::GeographicalDistance<ImageType::PointType> GeoDistanceType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(parseResult->GetInputImage());
reader->UpdateOutputInformation();
GCPsToSensorModelFilterType::Pointer rpcEstimator = GCPsToSensorModelFilterType::New();
rpcEstimator->SetInput(reader->GetOutput());
unsigned int nbGCPs = nbPoints / 5;
std::cout << "Receiving " << nbPoints << " from command line." << std::endl;
for (unsigned int gcpId = 0; gcpId < nbGCPs; ++gcpId)
{
Point2DType sensorPoint;
sensorPoint[0] = parseResult->GetParameterFloat("--GroudControlPoints", gcpId * 5);
sensorPoint[1] = parseResult->GetParameterFloat("--GroudControlPoints", 1 + gcpId * 5);
Point3DType geoPoint;
geoPoint[0] = parseResult->GetParameterFloat("--GroudControlPoints", 2 + gcpId * 5);
geoPoint[1] = parseResult->GetParameterFloat("--GroudControlPoints", 3 + gcpId * 5);
geoPoint[2] = parseResult->GetParameterFloat("--GroudControlPoints", 4 + gcpId * 5);
std::cout << "Adding GCP sensor: " << sensorPoint << " <-> geo: " << geoPoint << std::endl;
rpcEstimator->AddGCP(sensorPoint, geoPoint);
}
// Estimate the rpc model
rpcEstimator->GetOutput()->UpdateOutputInformation();
// Instancicate a GenericRSTransform in order to transform the
// indexes, using the rpcModel estimated, into geographical
// coordiantes.
// The test will check for nan coordinates, and the distance between
// geographical coordinates.
GenericRSTransformType::Pointer grsTrasnform = GenericRSTransformType::New();
grsTrasnform->SetInputKeywordList(rpcEstimator->GetKeywordlist());
grsTrasnform->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));
// Set the DEM Directory if any
if(parseResult->IsOptionPresent("--DEMDirectory"))
{
grsTrasnform->SetDEMDirectory(parseResult->GetParameterString("--DEMDirectory"));
}
else
{
grsTrasnform->SetAverageElevation(0);
}
grsTrasnform->InstanciateTransform();
// Test
GeoDistanceType::Pointer geoDistance = GeoDistanceType::New();
bool isErrorDetected = false;
for (unsigned int gcpId = 0; gcpId < nbGCPs; ++gcpId)
{
ImageType::IndexType index;
index[0] = parseResult->GetParameterFloat("--GroudControlPoints", gcpId * 5);
index[1] = parseResult->GetParameterFloat("--GroudControlPoints", 1 + gcpId * 5);
ImageType::PointType point, transformedPoint;
reader->GetOutput()->TransformIndexToPhysicalPoint(index, point);
transformedPoint = grsTrasnform->TransformPoint(point);
// reference point
ImageType::PointType geoPoint;
geoPoint[0] = parseResult->GetParameterFloat("--GroudControlPoints", 2 + gcpId * 5);
geoPoint[1] = parseResult->GetParameterFloat("--GroudControlPoints", 3 + gcpId * 5);
// Search for nans
if ( vnl_math_isnan(transformedPoint[0]) || vnl_math_isnan(transformedPoint[1]) )
{
std::cout << "Reference : "<< geoPoint
<<" --> Result of the reprojection using the estimated RpcModel "<< transformedPoint
<< std::endl;
std::cout<<"The result of the projection is nan, there is a problem with the estimated RpcModel "
<< std::endl<<std::endl;
isErrorDetected = true;
}
// Search for wrong projection results
double residual = geoDistance->Evaluate(geoPoint, transformedPoint);
if( residual > parseResult->GetParameterFloat("--ErrorAllowed"))
{
std::cout << "Reference : "<< geoPoint
<<" --> Result of the reprojection using the estimated RpcModel "
<< grsTrasnform->TransformPoint(point)
<< std::endl
<< " Residual ["<< residual << "] is higher than the tolerance ["
<< parseResult->GetParameterFloat("--ErrorAllowed")
<<"], there is a problem with the estimated RpcModel"
<<std::endl<<std::endl;
isErrorDetected = true;
}
}
// Is there an error
if ( isErrorDetected )
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <unicode/coll.h>
const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor ICUBridgeCollationCompareFunctor::s_defaultFunctor;
ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
m_isValid(false),
m_collator(0)
{
UErrorCode theStatus = U_ZERO_ERROR;
m_collator = Collator::createInstance(theStatus);
if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR)
{
m_isValid = true;
}
}
ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
delete m_collator;
}
static UChar dummy = 0;
int
ICUBridgeCollationCompareFunctor::operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const
{
if (isValid() == false)
{
return s_defaultFunctor(theLHS, theRHS);
}
else
{
assert(m_collator != 0);
#if defined(XALAN_USE_XERCES_DOMSTRING)
// $$$ ToDo: This code is necessary because DOMStrings can
// have a null representation.
const XalanDOMChar* const lhs = theLHS == 0 ? &dummy : theLHS;
const XalanDOMChar* const rhs = theRHS == 0 ? &dummy : theRHS;
return m_collator->compare(
lhs,
length(lhs),
rhs,
length(rhs));
#else
return m_collator->compare(
theLHS,
length(theLHS),
theRHS,
length(theRHS));
#endif
}
}
<commit_msg>Removed support for Xerces' DOMString.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <unicode/coll.h>
const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor ICUBridgeCollationCompareFunctor::s_defaultFunctor;
ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
m_isValid(false),
m_collator(0)
{
UErrorCode theStatus = U_ZERO_ERROR;
m_collator = Collator::createInstance(theStatus);
if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR)
{
m_isValid = true;
}
}
ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
delete m_collator;
}
static UChar dummy = 0;
int
ICUBridgeCollationCompareFunctor::operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const
{
if (isValid() == false)
{
return s_defaultFunctor(theLHS, theRHS);
}
else
{
assert(m_collator != 0);
return m_collator->compare(
theLHS,
length(theLHS),
theRHS,
length(theRHS));
}
}
<|endoftext|>
|
<commit_before>/*
* Servo.cpp
*
* Created: 07/05/2012 12:46:20 PM
* Author: teastman
*/
#include "Servo.h"
Servo::Servo(){
m_minPulseWidth = 600;
m_maxPulseWidth = 2400;
m_maxVelocity = 500;
m_limitVelocity = 100;
m_pulseVelocity = pulseVelocity(100);
m_currentPulse = 1500;
m_destinationPulse = 1500;
m_nextPulse = 1500;
m_minPulse = 600;
m_maxPulse = 2400;
m_invert = false;
m_normalize = false;
m_applyVelocityLimit = false;
}
Servo::~Servo(){
// Destroy things
}
void Servo::rotateTo(uint8_t angle){
rotateTo(angle, m_limitVelocity);
}
void Servo::rotateTo(uint8_t angle, uint8_t velocity){
angle = (angle>180) ? 180 : angle;
m_destinationPulse = degreesToMicros(angle);
m_destinationPulse = (m_destinationPulse>m_maxPulse) ? m_maxPulse : m_destinationPulse;
m_destinationPulse = (m_destinationPulse<m_minPulse) ? m_minPulse : m_destinationPulse;
m_pulseVelocity = pulseVelocity(velocity);
m_applyVelocityLimit = true;
}
uint16_t Servo::calculateNextPulse(){
m_currentPulse = m_nextPulse;
if(m_applyVelocityLimit)
{
if(m_currentPulse == m_destinationPulse)
{
// Calculated first because it is the most common scenario.
// do nothing;
}
else if(m_destinationPulse > m_currentPulse)
{
m_nextPulse = m_pulseVelocity + m_currentPulse;
if(m_nextPulse > m_destinationPulse)
m_nextPulse = m_destinationPulse;
}
else
{
m_nextPulse = m_currentPulse - m_pulseVelocity;
if(m_nextPulse < m_destinationPulse)
m_nextPulse = m_destinationPulse;
}
}
else
{
m_nextPulse = m_destinationPulse;
}
return m_nextPulse;
}
uint8_t Servo::currentAngle() const{
return microsToDegrees(m_currentPulse);
}
uint8_t Servo::destinationAngle() const{
return microsToDegrees(m_destinationPulse);
}
uint8_t Servo::nextAngle() const{
return microsToDegrees(m_nextPulse);
}
uint16_t Servo::currentPulse() const{
return m_currentPulse;
}
uint16_t Servo::destinationPulse() const{
return m_destinationPulse;
}
uint16_t Servo::nextPulse() const{
return m_nextPulse;
}
uint16_t Servo::minPulseWidth(){
return m_minPulseWidth;
}
void Servo::minPulseWidth(uint16_t pulse){
m_minPulseWidth = pulse;
}
uint16_t Servo::maxPulseWidth(){
return m_maxPulseWidth;
}
void Servo::maxPulseWidth(uint16_t pulse){
m_maxPulseWidth = pulse;
}
uint16_t Servo::maxVelocity() const{
return m_maxVelocity;
}
void Servo::maxVelocity(uint16_t maxVelocity){
m_maxVelocity = maxVelocity;
}
uint8_t Servo::limitVelocity() const{
return m_limitVelocity;
}
void Servo::limitVelocity(uint8_t velocity){
velocity = (velocity>100) ? 100 : velocity;
m_limitVelocity = velocity;
m_pulseVelocity = pulseVelocity(velocity);
m_applyVelocityLimit = true;
}
void Servo::unlimitVelocity(){
m_applyVelocityLimit = false;
}
bool Servo::isLimited(){
return m_applyVelocityLimit;
}
void Servo::limit(uint8_t minAngle, uint8_t maxAngle){
m_minPulse = degreesToMicros(minAngle);
m_maxPulse = degreesToMicros(maxAngle);
}
uint8_t Servo::minAngle() const{
return microsToDegrees(m_minPulse);
}
void Servo::minAngle(uint8_t minAngle){
m_minPulse = degreesToMicros(minAngle);
}
uint8_t Servo::maxAngle() const{
return microsToDegrees(m_maxPulse);
}
void Servo::maxAngle(uint8_t maxAngle){
m_maxPulse = degreesToMicros(maxAngle);
}
bool Servo::invert() const{
return m_invert;
}
void Servo::invert(bool invert){
m_invert = invert;
}
bool Servo::normalize() const{
return m_normalize;
}
void Servo::normalize(bool normalize){
m_normalize = normalize;
}
// the / 50 is to translate the max velocity from per second to per update.
// The updates are being sent out at a rate of 50 Hz or once every 20us
uint16_t Servo::pulseVelocity(uint8_t velocity) const{
velocity = (velocity>100) ? 100 : velocity;
return degreesToMicros((m_maxVelocity / 50) * ((double)velocity / 100.0));
}
uint16_t Servo::degreesToMicros(uint8_t val) const{
return (m_maxPulseWidth - m_minPulseWidth) / 180 * val + m_minPulseWidth;
}
uint8_t Servo::microsToDegrees(uint16_t val) const{
return (uint8_t)(180.0 / (double)(m_maxPulseWidth - m_minPulseWidth) * (val - m_minPulseWidth));
}<commit_msg>Fixed pulse velocity method<commit_after>/*
* Servo.cpp
*
* Created: 07/05/2012 12:46:20 PM
* Author: teastman
*/
#include "Servo.h"
Servo::Servo(){
m_minPulseWidth = 600;
m_maxPulseWidth = 2400;
m_maxVelocity = 500;
m_limitVelocity = 100;
m_pulseVelocity = pulseVelocity(100);
m_currentPulse = 1500;
m_destinationPulse = 1500;
m_nextPulse = 1500;
m_minPulse = 600;
m_maxPulse = 2400;
m_invert = false;
m_normalize = false;
m_applyVelocityLimit = false;
}
Servo::~Servo(){
// Destroy things
}
void Servo::rotateTo(uint8_t angle){
rotateTo(angle, m_limitVelocity);
}
void Servo::rotateTo(uint8_t angle, uint8_t velocity){
angle = (angle>180) ? 180 : angle;
m_destinationPulse = degreesToMicros(angle);
m_destinationPulse = (m_destinationPulse>m_maxPulse) ? m_maxPulse : m_destinationPulse;
m_destinationPulse = (m_destinationPulse<m_minPulse) ? m_minPulse : m_destinationPulse;
m_pulseVelocity = pulseVelocity(velocity);
m_applyVelocityLimit = true;
}
uint16_t Servo::calculateNextPulse(){
m_currentPulse = m_nextPulse;
if(m_applyVelocityLimit)
{
if(m_currentPulse == m_destinationPulse)
{
// Calculated first because it is the most common scenario.
// do nothing;
}
else if(m_destinationPulse > m_currentPulse)
{
m_nextPulse = m_pulseVelocity + m_currentPulse;
if(m_nextPulse > m_destinationPulse)
m_nextPulse = m_destinationPulse;
}
else
{
m_nextPulse = m_currentPulse - m_pulseVelocity;
if(m_nextPulse < m_destinationPulse)
m_nextPulse = m_destinationPulse;
}
}
else
{
m_nextPulse = m_destinationPulse;
}
return m_nextPulse;
}
uint8_t Servo::currentAngle() const{
return microsToDegrees(m_currentPulse);
}
uint8_t Servo::destinationAngle() const{
return microsToDegrees(m_destinationPulse);
}
uint8_t Servo::nextAngle() const{
return microsToDegrees(m_nextPulse);
}
uint16_t Servo::currentPulse() const{
return m_currentPulse;
}
uint16_t Servo::destinationPulse() const{
return m_destinationPulse;
}
uint16_t Servo::nextPulse() const{
return m_nextPulse;
}
uint16_t Servo::minPulseWidth(){
return m_minPulseWidth;
}
void Servo::minPulseWidth(uint16_t pulse){
m_minPulseWidth = pulse;
}
uint16_t Servo::maxPulseWidth(){
return m_maxPulseWidth;
}
void Servo::maxPulseWidth(uint16_t pulse){
m_maxPulseWidth = pulse;
}
uint16_t Servo::maxVelocity() const{
return m_maxVelocity;
}
void Servo::maxVelocity(uint16_t maxVelocity){
m_maxVelocity = maxVelocity;
}
uint8_t Servo::limitVelocity() const{
return m_limitVelocity;
}
void Servo::limitVelocity(uint8_t velocity){
velocity = (velocity>100) ? 100 : velocity;
m_limitVelocity = velocity;
m_pulseVelocity = pulseVelocity(velocity);
m_applyVelocityLimit = true;
}
void Servo::unlimitVelocity(){
m_applyVelocityLimit = false;
}
bool Servo::isLimited(){
return m_applyVelocityLimit;
}
void Servo::limit(uint8_t minAngle, uint8_t maxAngle){
m_minPulse = degreesToMicros(minAngle);
m_maxPulse = degreesToMicros(maxAngle);
}
uint8_t Servo::minAngle() const{
return microsToDegrees(m_minPulse);
}
void Servo::minAngle(uint8_t minAngle){
m_minPulse = degreesToMicros(minAngle);
}
uint8_t Servo::maxAngle() const{
return microsToDegrees(m_maxPulse);
}
void Servo::maxAngle(uint8_t maxAngle){
m_maxPulse = degreesToMicros(maxAngle);
}
bool Servo::invert() const{
return m_invert;
}
void Servo::invert(bool invert){
m_invert = invert;
}
bool Servo::normalize() const{
return m_normalize;
}
void Servo::normalize(bool normalize){
m_normalize = normalize;
}
// the / 50 is to translate the max velocity from per second to per update.
// The updates are being sent out at a rate of 50 Hz or once every 20us
uint16_t Servo::pulseVelocity(uint8_t velocity) const{
velocity = (velocity>100) ? 100 : velocity;
return (uint16_t)(((double)m_maxVelocity / 50.0) * ((double)velocity / 100.0) * ((double)(m_maxPulseWidth - m_minPulseWidth) / 180.0));
}
// Converts a give angle to the appropriate microsecond burst.
uint16_t Servo::degreesToMicros(uint8_t val) const{
return (m_maxPulseWidth - m_minPulseWidth) / 180 * val + m_minPulseWidth;
}
// Converts a microsecond burst into an angle.
uint8_t Servo::microsToDegrees(uint16_t val) const{
return (uint8_t)(180.0 / (double)(m_maxPulseWidth - m_minPulseWidth) * (val - m_minPulseWidth));
}<|endoftext|>
|
<commit_before>
/******************************************************************************
*
* file: CmdLine.cpp
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#include <tclap/CommandLine.h>
using namespace std;
namespace TCLAP {
CmdLine::CmdLine(const string& n, const string& m, const string& v )
: _progName(n),
_message(m),
_version(v),
_numRequired(0),
_delimiter(' ')
{
_constructor();
}
CmdLine::CmdLine(const string& m, char delim, const string& v )
: _progName("not_set_yet"),
_message(m),
_version(v),
_numRequired(0),
_delimiter(delim)
{
_constructor();
}
void CmdLine::_constructor()
{
Arg::setDelimiter( _delimiter );
SwitchArg* help = new SwitchArg("h","help",
"Displays usage information and exits.",
false, new HelpVisitor( this ) );
add( *help );
SwitchArg* vers = new SwitchArg("v","version",
"Displays version information and exits.",
false, new VersionVisitor( this ) );
add( *vers );
SwitchArg* ignore = new SwitchArg(Arg::flagStartString,
Arg::ignoreNameString,
"Ignores the rest of the labeled arguments following this flag.",
false, new IgnoreRestVisitor() );
add( *ignore );
}
void CmdLine::xorAdd( vector<Arg*>& ors )
{
_xorHandler.add( ors );
for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++)
{
(*it)->forceRequired();
(*it)->setRequireLabel( "OR required" );
add( *it );
}
}
void CmdLine::xorAdd( Arg& a, Arg& b )
{
vector<Arg*> ors;
ors.push_back( &a );
ors.push_back( &b );
xorAdd( ors );
}
void CmdLine::add( Arg& a )
{
add( &a );
}
void CmdLine::add( Arg* a )
{
if ( find(_argList.begin(),_argList.end(), a) != _argList.end() )
{
cerr << "ADD ERROR: Argument with same flag/name already exists: "
<< a->toString() << " Ignoring!" << endl;
return;
}
a->addToList( _argList );
if ( a->isRequired() ) _numRequired++;
}
void CmdLine::version(int exitVal)
{
cout << endl << _progName << " version: " << _version << endl << endl;
exit( exitVal );
}
void CmdLine::_shortUsage( ostream& os )
{
string s = _progName + " " + _xorHandler.shortUsage();
for (ArgIterator it = _argList.begin(); it != _argList.end(); it++)
if ( !_xorHandler.contains( (*it) ) )
s += " " + (*it)->shortID();
spacePrint( os, s, 75, 3, _progName.length() + 2 );
}
void CmdLine::_longUsage( ostream& os )
{
_xorHandler.printLongUsage( os );
for (ArgIterator it = _argList.begin(); it != _argList.end(); it++)
if ( !_xorHandler.contains( (*it) ) )
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
os << endl;
}
os << endl;
spacePrint( os, _message, 75, 3, 0 );
}
void CmdLine::usage( int exitVal )
{
cout << endl << "USAGE: " << endl << endl;
_shortUsage( cout );
cout << endl << endl << "Where: " << endl << endl;
_longUsage( cout );
cout << endl;
exit( exitVal );
}
void CmdLine::parse(int argc, char** argv)
{
try {
_progName = argv[0];
// this step is necessary so that we have easy access to mutable strings.
vector<string> args;
for (int i = 1; i < argc; i++)
args.push_back(argv[i]);
int requiredCount = 0;
for (int i = 0; (unsigned int)i < args.size(); i++)
{
bool matched = false;
for (ArgIterator it = _argList.begin(); it != _argList.end(); it++)
{
if ( (*it)->processArg( &i, args ) )
{
requiredCount += _xorHandler.check( *it );
matched = true;
break;
}
}
// checks to see if the argument is an empty combined switch ...
// and if so, then we've actually matched it
if ( !matched && _emptyCombined( args[i] ) )
matched = true;
if ( !matched && !Arg::ignoreRest() )
throw( ArgException("Couldn't find match for argument",args[i]));
}
if ( requiredCount < _numRequired )
throw( ArgException("One or more required arguments missing!") );
if ( requiredCount > _numRequired )
throw( ArgException("Too many arguments!") );
} catch ( ArgException e )
{
cerr << "PARSE ERROR: " << e.argId() << endl
<< " " << e.error() << endl << endl;
cerr << "Brief USAGE: " << endl;
_shortUsage( cerr );
cerr << endl << "For complete USAGE and HELP type: "
<< endl << " " << _progName << " --help" << endl << endl;
exit(1);
}
}
bool CmdLine::_emptyCombined(const string& s)
{
if ( s[0] != Arg::flagStartChar )
return false;
for ( int i = 1; (unsigned int)i < s.length(); i++ )
if ( s[i] != Arg::blankChar )
return false;
return true;
}
}
<commit_msg>now throws exception on matching names/flags/desc<commit_after>
/******************************************************************************
*
* file: CmdLine.cpp
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#include <tclap/CommandLine.h>
using namespace std;
namespace TCLAP {
CmdLine::CmdLine(const string& n, const string& m, const string& v )
: _progName(n),
_message(m),
_version(v),
_numRequired(0),
_delimiter(' ')
{
_constructor();
}
CmdLine::CmdLine(const string& m, char delim, const string& v )
: _progName("not_set_yet"),
_message(m),
_version(v),
_numRequired(0),
_delimiter(delim)
{
_constructor();
}
void CmdLine::_constructor()
{
Arg::setDelimiter( _delimiter );
SwitchArg* help = new SwitchArg("h","help",
"Displays usage information and exits.",
false, new HelpVisitor( this ) );
add( *help );
SwitchArg* vers = new SwitchArg("v","version",
"Displays version information and exits.",
false, new VersionVisitor( this ) );
add( *vers );
SwitchArg* ignore = new SwitchArg(Arg::flagStartString,
Arg::ignoreNameString,
"Ignores the rest of the labeled arguments following this flag.",
false, new IgnoreRestVisitor() );
add( *ignore );
}
void CmdLine::xorAdd( vector<Arg*>& ors )
{
_xorHandler.add( ors );
for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++)
{
(*it)->forceRequired();
(*it)->setRequireLabel( "OR required" );
add( *it );
}
}
void CmdLine::xorAdd( Arg& a, Arg& b )
{
vector<Arg*> ors;
ors.push_back( &a );
ors.push_back( &b );
xorAdd( ors );
}
void CmdLine::add( Arg& a )
{
add( &a );
}
void CmdLine::add( Arg* a )
{
for( ArgIterator iter = _argList.begin(); iter != _argList.end(); iter++ )
if ( *a == *(*iter) )
throw( ArgException( "Argument with same flag/name already exists!",
a->longID() ) );
a->addToList( _argList );
if ( a->isRequired() ) _numRequired++;
}
void CmdLine::version(int exitVal)
{
cout << endl << _progName << " version: " << _version << endl << endl;
exit( exitVal );
}
void CmdLine::_shortUsage( ostream& os )
{
string s = _progName + " " + _xorHandler.shortUsage();
for (ArgIterator it = _argList.begin(); it != _argList.end(); it++)
if ( !_xorHandler.contains( (*it) ) )
s += " " + (*it)->shortID();
spacePrint( os, s, 75, 3, _progName.length() + 2 );
}
void CmdLine::_longUsage( ostream& os )
{
_xorHandler.printLongUsage( os );
for (ArgIterator it = _argList.begin(); it != _argList.end(); it++)
if ( !_xorHandler.contains( (*it) ) )
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
os << endl;
}
os << endl;
spacePrint( os, _message, 75, 3, 0 );
}
void CmdLine::usage( int exitVal )
{
cout << endl << "USAGE: " << endl << endl;
_shortUsage( cout );
cout << endl << endl << "Where: " << endl << endl;
_longUsage( cout );
cout << endl;
exit( exitVal );
}
void CmdLine::parse(int argc, char** argv)
{
try {
_progName = argv[0];
// this step is necessary so that we have easy access to mutable strings.
vector<string> args;
for (int i = 1; i < argc; i++)
args.push_back(argv[i]);
int requiredCount = 0;
for (int i = 0; (unsigned int)i < args.size(); i++)
{
bool matched = false;
for (ArgIterator it = _argList.begin(); it != _argList.end(); it++)
{
if ( (*it)->processArg( &i, args ) )
{
requiredCount += _xorHandler.check( *it );
matched = true;
break;
}
}
// checks to see if the argument is an empty combined switch ...
// and if so, then we've actually matched it
if ( !matched && _emptyCombined( args[i] ) )
matched = true;
if ( !matched && !Arg::ignoreRest() )
throw( ArgException("Couldn't find match for argument",args[i]));
}
if ( requiredCount < _numRequired )
throw( ArgException("One or more required arguments missing!") );
if ( requiredCount > _numRequired )
throw( ArgException("Too many arguments!") );
} catch ( ArgException e )
{
cerr << "PARSE ERROR: " << e.argId() << endl
<< " " << e.error() << endl << endl;
cerr << "Brief USAGE: " << endl;
_shortUsage( cerr );
cerr << endl << "For complete USAGE and HELP type: "
<< endl << " " << _progName << " --help" << endl << endl;
exit(1);
}
}
bool CmdLine::_emptyCombined(const string& s)
{
if ( s[0] != Arg::flagStartChar )
return false;
for ( int i = 1; (unsigned int)i < s.length(); i++ )
if ( s[i] != Arg::blankChar )
return false;
return true;
}
}
<|endoftext|>
|
<commit_before>#include <Context.h>
#include <cmath>
#include <iostream>
using namespace std;
using namespace canvas;
void
Context::resize(unsigned int _width, unsigned int _height) {
getDefaultSurface().resize(_width, _height, (unsigned int)(_width * getDisplayScale()), (unsigned int)(_height * getDisplayScale()), getDefaultSurface().getFormat());
hit_regions.clear();
}
Context &
Context::fillRect(double x, double y, double w, double h) {
beginPath().rect(x, y, w, h);
return fill();
}
Context &
Context::strokeRect(double x, double y, double w, double h) {
beginPath().rect(x, y, w, h);
return stroke();
}
Context &
Context::clearRect(double x, double y, double w, double h) {
Path path;
path.rect(x, y, w, h);
Style style(this);
style = Color(0.0f, 0.0f, 0.0f, 0.0f);
return renderPath(FILL, path, style, COPY);
}
Context &
Context::renderText(RenderMode mode, const Style & style, const std::string & text, double x, double y, Operator op) {
if (hasNativeShadows()) {
getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, x, y, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath);
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
int bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
Style shadow_style(this);
shadow_style = shadowColor.getValue();
shadow_style.color.alpha = 1.0f;
shadow->renderText(mode, font, shadow_style, textBaseline.getValue(), textAlign.getValue(), text, x + shadowOffsetX.getValue() + bi, y + shadowOffsetY.getValue() + bi, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath);
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, x, y, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath);
}
return *this;
}
Context &
Context::renderPath(RenderMode mode, const Path & path, const Style & style, Operator op) {
if (hasNativeShadows()) {
getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath);
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
float bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
Style shadow_style(this);
shadow_style = shadowColor.getValue();
Path tmp_path = path, tmp_clipPath = clipPath;
tmp_path.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi);
tmp_clipPath.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi);
shadow->renderPath(mode, tmp_path, shadow_style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), tmp_clipPath);
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), clipPath);
}
return *this;
}
Context &
Context::drawImage(Surface & img, double x, double y, double w, double h) {
if (hasNativeShadows()) {
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled);
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
float bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled);
// shadow->colorFill(shadowColor.getValue());
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled);
}
return *this;
}
Context &
Context::drawImage(const Image & img, double x, double y, double w, double h) {
if (hasNativeShadows()) {
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled);
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
float bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled);
// shadow->colorFill(shadowColor.getValue());
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled);
}
return *this;
}
Context &
Context::save() {
restore_stack.push_back(*this);
return *this;
}
Context &
Context::restore() {
if (!restore_stack.empty()) {
*this = restore_stack.back();
restore_stack.pop_back();
}
return *this;
}
<commit_msg>fix imageSmoothingEnabled usage<commit_after>#include <Context.h>
#include <cmath>
#include <iostream>
using namespace std;
using namespace canvas;
void
Context::resize(unsigned int _width, unsigned int _height) {
getDefaultSurface().resize(_width, _height, (unsigned int)(_width * getDisplayScale()), (unsigned int)(_height * getDisplayScale()), getDefaultSurface().getFormat());
hit_regions.clear();
}
Context &
Context::fillRect(double x, double y, double w, double h) {
beginPath().rect(x, y, w, h);
return fill();
}
Context &
Context::strokeRect(double x, double y, double w, double h) {
beginPath().rect(x, y, w, h);
return stroke();
}
Context &
Context::clearRect(double x, double y, double w, double h) {
Path path;
path.rect(x, y, w, h);
Style style(this);
style = Color(0.0f, 0.0f, 0.0f, 0.0f);
return renderPath(FILL, path, style, COPY);
}
Context &
Context::renderText(RenderMode mode, const Style & style, const std::string & text, double x, double y, Operator op) {
if (hasNativeShadows()) {
getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, x, y, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath);
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
int bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
Style shadow_style(this);
shadow_style = shadowColor.getValue();
shadow_style.color.alpha = 1.0f;
shadow->renderText(mode, font, shadow_style, textBaseline.getValue(), textAlign.getValue(), text, x + shadowOffsetX.getValue() + bi, y + shadowOffsetY.getValue() + bi, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath);
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, x, y, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath);
}
return *this;
}
Context &
Context::renderPath(RenderMode mode, const Path & path, const Style & style, Operator op) {
if (hasNativeShadows()) {
getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath);
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
float bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
Style shadow_style(this);
shadow_style = shadowColor.getValue();
Path tmp_path = path, tmp_clipPath = clipPath;
tmp_path.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi);
tmp_clipPath.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi);
shadow->renderPath(mode, tmp_path, shadow_style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), tmp_clipPath);
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), clipPath);
}
return *this;
}
Context &
Context::drawImage(Surface & img, double x, double y, double w, double h) {
if (hasNativeShadows()) {
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue());
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
float bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue());
// shadow->colorFill(shadowColor.getValue());
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue());
}
return *this;
}
Context &
Context::drawImage(const Image & img, double x, double y, double w, double h) {
if (hasNativeShadows()) {
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue());
} else {
if (hasShadow()) {
float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale();
float bi = int(ceil(b));
auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8);
auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8);
shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue());
// shadow->colorFill(shadowColor.getValue());
#if 1
shadow->slowBlur(bs, bs);
#else
shadow->blur(bs);
#endif
shadow->colorize(shadowColor.getValue(), *shadow2);
getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path(), false);
}
getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue());
}
return *this;
}
Context &
Context::save() {
restore_stack.push_back(*this);
return *this;
}
Context &
Context::restore() {
if (!restore_stack.empty()) {
*this = restore_stack.back();
restore_stack.pop_back();
}
return *this;
}
<|endoftext|>
|
<commit_before>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->lstat(path, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
// TODO Check if necessary
if (path.native() == "/") {
return getattr(path, stbuf);
}
try {
_device->fstat(fileinfo->fh, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
UNUSED(mode);
UNUSED(path);
printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return ENOSYS;
}
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
try {
_device->mkdir(path, mode);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
try {
_device->unlink(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::rmdir(const path &path) {
try {
_device->rmdir(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::symlink(const path &from, const path &to) {
printf("NOT IMPLEMENTED: symlink(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::symlink(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
try {
_device->rename(from, to);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::link(const path &from, const path &to) {
printf("NOT IMPLEMENTED: link(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::link(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chmod(const path &path, mode_t mode) {
printf("NOT IMPLEMENTED: chmod(%s, %d)\n", path.c_str(), mode);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chmod(real_path.c_str(), mode);
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
printf("NOT IMPLEMENTED: chown(%s, %d, %d)\n", path.c_str(), uid, gid);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chown(real_path.c_str(), uid, gid);
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
try {
_device->truncate(path, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
UNUSED(path);
try {
_device->ftruncate(fileinfo->fh, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
try {
_device->utimens(path, times);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openFile(path, fileinfo->flags);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeFile(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
//printf("Reading from file %d\n", fileinfo->fh);
//fflush(stdout);
return _device->read(fileinfo->fh, buf, size, offset);
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
_device->write(fileinfo->fh, buf, size, offset);
return size;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
try {
_device->statfs(path, fsstat);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
UNUSED(path);
UNUSED(fileinfo);
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
UNUSED(path);
try {
if (datasync) {
_device->fdatasync(fileinfo->fh);
} else {
_device->fsync(fileinfo->fh);
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openDir(path);
return 0;
} catch(CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
UNUSED(path);
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
UNUSED(offset);
try {
auto entries = _device->readDir(fileinfo->fh);
for (const auto &entry : *entries) {
//TODO Also give file attributes (third param of filler)
if (filler(buf, entry.c_str(), nullptr, 0) != 0) {
return -ENOMEM;
}
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeDir(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
UNUSED(datasync);
UNUSED(path);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
try {
_device->access(path, mask);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
try {
fileinfo->fh = _device->createAndOpenFile(path, mode);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
} /* namespace cryfs */
<commit_msg>Removed todo<commit_after>#include "CryFuse.h"
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <cassert>
#include "cryfs_lib/CryNode.h"
#include "cryfs_lib/CryErrnoException.h"
#define UNUSED(expr) (void)(expr)
using fusepp::path;
namespace cryfs {
CryFuse::CryFuse(CryDevice *device)
:_device(device) {
}
int CryFuse::getattr(const path &path, struct stat *stbuf) {
try {
_device->lstat(path, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {
//printf("fgetattr(%s, _, _)\n", path.c_str());
// On FreeBSD, trying to do anything with the mountpoint ends up
// opening it, and then using the FD for an fgetattr. So in the
// special case of a path of "/", I need to do a getattr on the
// underlying root directory instead of doing the fgetattr().
// TODO Check if necessary
if (path.native() == "/") {
return getattr(path, stbuf);
}
try {
_device->fstat(fileinfo->fh, stbuf);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::readlink(const path &path, char *buf, size_t size) {
//printf("readlink(%s, _, %zu)\n", path.c_str(), size);
auto real_path = _device->RootDir() / path;
//size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,
//but the posix version does not and also doesn't append one.
int real_size = ::readlink(real_path.c_str(), buf, size-1);
if (real_size < 0) {
return -errno;
}
//Terminate the string
buf[real_size] = '\0';
return 0;
}
int CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {
UNUSED(rdev);
UNUSED(mode);
UNUSED(path);
printf("Called non-implemented mknod(%s, %d, _)\n", path.c_str(), mode);
return ENOSYS;
}
int CryFuse::mkdir(const path &path, mode_t mode) {
//printf("mkdir(%s, %d)\n", path.c_str(), mode);
try {
_device->mkdir(path, mode);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::unlink(const path &path) {
//printf("unlink(%s)\n", path.c_str());
try {
_device->unlink(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::rmdir(const path &path) {
try {
_device->rmdir(path);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::symlink(const path &from, const path &to) {
printf("NOT IMPLEMENTED: symlink(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::symlink(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::rename(const path &from, const path &to) {
//printf("rename(%s, %s)\n", from.c_str(), to.c_str());
try {
_device->rename(from, to);
return 0;
} catch(cryfs::CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::link(const path &from, const path &to) {
printf("NOT IMPLEMENTED: link(%s, %s)\n", from.c_str(), to.c_str());
//auto real_from = _device->RootDir() / from;
//auto real_to = _device->RootDir() / to;
//int retstat = ::link(real_from.c_str(), real_to.c_str());
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chmod(const path &path, mode_t mode) {
printf("NOT IMPLEMENTED: chmod(%s, %d)\n", path.c_str(), mode);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chmod(real_path.c_str(), mode);
//return errcode_map(retstat);
return ENOSYS;
}
//TODO
int CryFuse::chown(const path &path, uid_t uid, gid_t gid) {
printf("NOT IMPLEMENTED: chown(%s, %d, %d)\n", path.c_str(), uid, gid);
//auto real_path = _device->RootDir() / path;
//int retstat = ::chown(real_path.c_str(), uid, gid);
//return errcode_map(retstat);
return ENOSYS;
}
int CryFuse::truncate(const path &path, off_t size) {
//printf("truncate(%s, %zu)\n", path.c_str(), size);
try {
_device->truncate(path, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {
//printf("ftruncate(%s, %zu, _)\n", path.c_str(), size);
UNUSED(path);
try {
_device->ftruncate(fileinfo->fh, size);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::utimens(const path &path, const timespec times[2]) {
//printf("utimens(%s, _)\n", path.c_str());
try {
_device->utimens(path, times);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::open(const path &path, fuse_file_info *fileinfo) {
//printf("open(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openFile(path, fileinfo->flags);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::release(const path &path, fuse_file_info *fileinfo) {
//printf("release(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeFile(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("read(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
//printf("Reading from file %d\n", fileinfo->fh);
//fflush(stdout);
return _device->read(fileinfo->fh, buf, size, offset);
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {
//printf("write(%s, _, %zu, %zu, _)\n", path.c_str(), size, offset);
UNUSED(path);
try {
_device->write(fileinfo->fh, buf, size, offset);
return size;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::statfs(const path &path, struct statvfs *fsstat) {
//printf("statfs(%s, _)\n", path.c_str());
try {
_device->statfs(path, fsstat);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::flush(const path &path, fuse_file_info *fileinfo) {
//printf("Called non-implemented flush(%s, _)\n", path.c_str());
UNUSED(path);
UNUSED(fileinfo);
return 0;
}
int CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {
//printf("fsync(%s, %d, _)\n", path.c_str(), datasync);
UNUSED(path);
try {
if (datasync) {
_device->fdatasync(fileinfo->fh);
} else {
_device->fsync(fileinfo->fh);
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {
//printf("opendir(%s, _)\n", path.c_str());
try {
fileinfo->fh = _device->openDir(path);
return 0;
} catch(CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {
UNUSED(path);
//printf("readdir(%s, _, _, %zu, _)\n", path.c_str(), offset);
UNUSED(offset);
try {
auto entries = _device->readDir(fileinfo->fh);
for (const auto &entry : *entries) {
if (filler(buf, entry.c_str(), nullptr, 0) != 0) {
return -ENOMEM;
}
}
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {
//printf("releasedir(%s, _)\n", path.c_str());
UNUSED(path);
try {
_device->closeDir(fileinfo->fh);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
//TODO
int CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {
UNUSED(fileinfo);
UNUSED(datasync);
UNUSED(path);
//printf("Called non-implemented fsyncdir(%s, %d, _)\n", path.c_str(), datasync);
return 0;
}
void CryFuse::init(fuse_conn_info *conn) {
UNUSED(conn);
//printf("init()\n");
}
void CryFuse::destroy() {
//printf("destroy()\n");
}
int CryFuse::access(const path &path, int mask) {
//printf("access(%s, %d)\n", path.c_str(), mask);
try {
_device->access(path, mask);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
int CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {
//printf("create(%s, %d, _)\n", path.c_str(), mode);
try {
fileinfo->fh = _device->createAndOpenFile(path, mode);
return 0;
} catch (CryErrnoException &e) {
return -e.getErrno();
}
}
} /* namespace cryfs */
<|endoftext|>
|
<commit_before>//
// EigenJS.cpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// 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/.
//
#include <cstdlib>
#include <ctime>
#include "Complex.hpp"
#include "Matrix.hpp"
#include "CMatrix.hpp"
#include "Vector.hpp"
#include "CVector.hpp"
namespace EigenJS {
void Init(v8::Handle<v8::Object> exports) {
std::srand(static_cast<unsigned int>(std::time(0)));
std::rand();
Complex<>::Init(exports);
Matrix<>::Init(exports);
CMatrix<>::Init(exports);
Vector<>::Init(exports);
CVector<>::Init(exports);
}
} // namespace EigenJS
NODE_MODULE(eigen, EigenJS::Init)
<commit_msg>src: using RowVector<commit_after>//
// EigenJS.cpp
// ~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// 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/.
//
#include <cstdlib>
#include <ctime>
#include "Complex.hpp"
#include "Matrix.hpp"
#include "CMatrix.hpp"
#include "Vector.hpp"
#include "CVector.hpp"
#include "RowVector.hpp"
namespace EigenJS {
void Init(v8::Handle<v8::Object> exports) {
std::srand(static_cast<unsigned int>(std::time(0)));
std::rand();
Complex<>::Init(exports);
Matrix<>::Init(exports);
CMatrix<>::Init(exports);
Vector<>::Init(exports);
CVector<>::Init(exports);
RowVector<>::Init(exports);
}
} // namespace EigenJS
NODE_MODULE(eigen, EigenJS::Init)
<|endoftext|>
|
<commit_before>/// @file
/// @author Boris Mikic
/// @version 2.1
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#include <hltypes/hmap.h>
#include <hltypes/hstring.h>
#include "Factory.h"
#include "Serializable.h"
namespace liteser
{
// this approach is used because there is a massive problem with static linking
hmap<hstr, Serializable* (*)()>* __lsConstructors;
Factory::Factory()
{
}
Factory::~Factory()
{
}
Serializable* Factory::create(chstr name)
{
Serializable* (*constructor)() = __lsConstructors->try_get_by_key(name, NULL);
if (constructor == NULL)
{
throw hl_exception("Detected class not registered as a Serializable: " + name);
}
return (*constructor)();
}
void Factory::_register(chstr name, Serializable* (*constructor)())
{
if (__lsConstructors == NULL)
{
__lsConstructors = new hmap<hstr, Serializable* (*)()>();
}
__lsConstructors->operator[](name) = constructor;
}
}
<commit_msg>- small static lib fix<commit_after>/// @file
/// @author Boris Mikic
/// @version 2.1
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#include <hltypes/hmap.h>
#include <hltypes/hstring.h>
#include <hltypes/hlog.h>
#include "Factory.h"
#include "Serializable.h"
namespace liteser
{
// this approach is used because there is a massive problem with static linking
static hmap<hstr, Serializable* (*)()>* __lsConstructors = NULL;
Factory::Factory()
{
}
Factory::~Factory()
{
}
Serializable* Factory::create(chstr name)
{
Serializable* (*constructor)() = __lsConstructors->try_get_by_key(name, NULL);
if (constructor == NULL)
{
throw hl_exception("Detected class not registered as a Serializable: " + name);
}
return (*constructor)();
}
void Factory::_register(chstr name, Serializable* (*constructor)())
{
if (__lsConstructors == NULL)
{
__lsConstructors = new hmap<hstr, Serializable* (*)()>();
}
hlog::debug(liteser::logTag, "Registering class: " + name);
__lsConstructors->operator[](name) = constructor;
}
}
<|endoftext|>
|
<commit_before>// SciTE - Scintilla based Text Editor
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
//
// NAME
// LexConf.cxx - lexer for Apache Configuration Files
// AUTHOR
// first working version contributed by Ahmad Zawawi <zeus_go64@hotmail.com> on October 28, 2000
// DESCRIPTION
// i created this lexer because i needed something pretty when dealing
// when Apache Configuration files...
//
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler)
{
int state = SCE_CONF_DEFAULT;
char chNext = styler[startPos];
int lengthDoc = startPos + length;
// create a buffer large enough to take the largest chunk...
char *buffer = new char[length];
int bufferCount = 0;
// this assumes that we have 2 keyword list in conf.properties
WordList &directives = *keywordLists[0];
WordList ¶ms = *keywordLists[1];
// go through all provided text segment
// using the hand-written state machine shown below
styler.StartAt(startPos);
styler.StartSegment(startPos);
for (int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
i++;
continue;
}
switch(state) {
case SCE_CONF_DEFAULT:
if( ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') {
// whitespace is simply ignored here...
styler.ColourTo(i,SCE_CONF_DEFAULT);
break;
} else if( ch == '#' ) {
// signals the start of a comment...
state = SCE_CONF_COMMENT;
styler.ColourTo(i,SCE_CONF_COMMENT);
} else if( ch == '.' /*|| ch == '/'*/) {
// signals the start of a file...
state = SCE_CONF_EXTENSION;
styler.ColourTo(i,SCE_CONF_EXTENSION);
} else if( ch == '"') {
state = SCE_CONF_STRING;
styler.ColourTo(i,SCE_CONF_STRING);
} else if( ispunct(ch) ) {
// signals an operator...
// no state jump necessary for this
// simple case...
styler.ColourTo(i,SCE_CONF_OPERATOR);
} else if( isalpha(ch) ) {
// signals the start of an identifier
bufferCount = 0;
buffer[bufferCount++] = tolower(ch);
state = SCE_CONF_IDENTIFIER;
} else if( isdigit(ch) ) {
// signals the start of a number
bufferCount = 0;
buffer[bufferCount++] = ch;
//styler.ColourTo(i,SCE_CONF_NUMBER);
state = SCE_CONF_NUMBER;
} else {
// style it the default style..
styler.ColourTo(i,SCE_CONF_DEFAULT);
}
break;
case SCE_CONF_COMMENT:
// if we find a newline here,
// we simply go to default state
// else continue to work on it...
if( ch == '\n' || ch == '\r' ) {
state = SCE_CONF_DEFAULT;
} else {
styler.ColourTo(i,SCE_CONF_COMMENT);
}
break;
case SCE_CONF_EXTENSION:
// if we find a non-alphanumeric char,
// we simply go to default state
// else we're still dealing with an extension...
if( isalnum(ch) || (ch == '_') ||
(ch == '-') || (ch == '$') ||
(ch == '/') || (ch == '.') || (ch == '*') )
{
styler.ColourTo(i,SCE_CONF_EXTENSION);
} else {
state = SCE_CONF_DEFAULT;
chNext = styler[i--];
}
break;
case SCE_CONF_STRING:
// if we find the end of a string char, we simply go to default state
// else we're still dealing with an string...
if( (ch == '"' && styler.SafeGetCharAt(i-1)!='\\') || (ch == '\n') || (ch == '\r') ) {
state = SCE_CONF_DEFAULT;
}
styler.ColourTo(i,SCE_CONF_STRING);
break;
case SCE_CONF_IDENTIFIER:
// stay in CONF_IDENTIFIER state until we find a non-alphanumeric
if( isalnum(ch) || (ch == '_') || (ch == '-') || (ch == '/') || (ch == '$') || (ch == '.') || (ch == '*')) {
buffer[bufferCount++] = tolower(ch);
} else {
state = SCE_CONF_DEFAULT;
buffer[bufferCount] = '\0';
// check if the buffer contains a keyword, and highlight it if it is a keyword...
if(directives.InList(buffer)) {
styler.ColourTo(i-1,SCE_CONF_DIRECTIVE );
} else if(params.InList(buffer)) {
styler.ColourTo(i-1,SCE_CONF_PARAMETER );
} else if(strchr(buffer,'/') || strchr(buffer,'.')) {
styler.ColourTo(i-1,SCE_CONF_EXTENSION);
} else {
styler.ColourTo(i-1,SCE_CONF_DEFAULT);
}
// push back the faulty character
chNext = styler[i--];
}
break;
case SCE_CONF_NUMBER:
// stay in CONF_NUMBER state until we find a non-numeric
if( isdigit(ch) || ch == '.') {
buffer[bufferCount++] = ch;
} else {
state = SCE_CONF_DEFAULT;
buffer[bufferCount] = '\0';
// Colourize here...
if( strchr(buffer,'.') ) {
// it is an IP address...
styler.ColourTo(i-1,SCE_CONF_IP);
} else {
// normal number
styler.ColourTo(i-1,SCE_CONF_NUMBER);
}
// push back a character
chNext = styler[i--];
}
break;
}
}
}
LexerModule lmConf(SCLEX_CONF, ColouriseConfDoc);
<commit_msg>Added static_cast to hush Borland C++.<commit_after>// SciTE - Scintilla based Text Editor
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
//
// NAME
// LexConf.cxx - lexer for Apache Configuration Files
// AUTHOR
// first working version contributed by Ahmad Zawawi <zeus_go64@hotmail.com> on October 28, 2000
// DESCRIPTION
// i created this lexer because i needed something pretty when dealing
// when Apache Configuration files...
//
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler)
{
int state = SCE_CONF_DEFAULT;
char chNext = styler[startPos];
int lengthDoc = startPos + length;
// create a buffer large enough to take the largest chunk...
char *buffer = new char[length];
int bufferCount = 0;
// this assumes that we have 2 keyword list in conf.properties
WordList &directives = *keywordLists[0];
WordList ¶ms = *keywordLists[1];
// go through all provided text segment
// using the hand-written state machine shown below
styler.StartAt(startPos);
styler.StartSegment(startPos);
for (int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
i++;
continue;
}
switch(state) {
case SCE_CONF_DEFAULT:
if( ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') {
// whitespace is simply ignored here...
styler.ColourTo(i,SCE_CONF_DEFAULT);
break;
} else if( ch == '#' ) {
// signals the start of a comment...
state = SCE_CONF_COMMENT;
styler.ColourTo(i,SCE_CONF_COMMENT);
} else if( ch == '.' /*|| ch == '/'*/) {
// signals the start of a file...
state = SCE_CONF_EXTENSION;
styler.ColourTo(i,SCE_CONF_EXTENSION);
} else if( ch == '"') {
state = SCE_CONF_STRING;
styler.ColourTo(i,SCE_CONF_STRING);
} else if( ispunct(ch) ) {
// signals an operator...
// no state jump necessary for this
// simple case...
styler.ColourTo(i,SCE_CONF_OPERATOR);
} else if( isalpha(ch) ) {
// signals the start of an identifier
bufferCount = 0;
buffer[bufferCount++] = static_cast<char>(tolower(ch));
state = SCE_CONF_IDENTIFIER;
} else if( isdigit(ch) ) {
// signals the start of a number
bufferCount = 0;
buffer[bufferCount++] = ch;
//styler.ColourTo(i,SCE_CONF_NUMBER);
state = SCE_CONF_NUMBER;
} else {
// style it the default style..
styler.ColourTo(i,SCE_CONF_DEFAULT);
}
break;
case SCE_CONF_COMMENT:
// if we find a newline here,
// we simply go to default state
// else continue to work on it...
if( ch == '\n' || ch == '\r' ) {
state = SCE_CONF_DEFAULT;
} else {
styler.ColourTo(i,SCE_CONF_COMMENT);
}
break;
case SCE_CONF_EXTENSION:
// if we find a non-alphanumeric char,
// we simply go to default state
// else we're still dealing with an extension...
if( isalnum(ch) || (ch == '_') ||
(ch == '-') || (ch == '$') ||
(ch == '/') || (ch == '.') || (ch == '*') )
{
styler.ColourTo(i,SCE_CONF_EXTENSION);
} else {
state = SCE_CONF_DEFAULT;
chNext = styler[i--];
}
break;
case SCE_CONF_STRING:
// if we find the end of a string char, we simply go to default state
// else we're still dealing with an string...
if( (ch == '"' && styler.SafeGetCharAt(i-1)!='\\') || (ch == '\n') || (ch == '\r') ) {
state = SCE_CONF_DEFAULT;
}
styler.ColourTo(i,SCE_CONF_STRING);
break;
case SCE_CONF_IDENTIFIER:
// stay in CONF_IDENTIFIER state until we find a non-alphanumeric
if( isalnum(ch) || (ch == '_') || (ch == '-') || (ch == '/') || (ch == '$') || (ch == '.') || (ch == '*')) {
buffer[bufferCount++] = static_cast<char>(tolower(ch));
} else {
state = SCE_CONF_DEFAULT;
buffer[bufferCount] = '\0';
// check if the buffer contains a keyword, and highlight it if it is a keyword...
if(directives.InList(buffer)) {
styler.ColourTo(i-1,SCE_CONF_DIRECTIVE );
} else if(params.InList(buffer)) {
styler.ColourTo(i-1,SCE_CONF_PARAMETER );
} else if(strchr(buffer,'/') || strchr(buffer,'.')) {
styler.ColourTo(i-1,SCE_CONF_EXTENSION);
} else {
styler.ColourTo(i-1,SCE_CONF_DEFAULT);
}
// push back the faulty character
chNext = styler[i--];
}
break;
case SCE_CONF_NUMBER:
// stay in CONF_NUMBER state until we find a non-numeric
if( isdigit(ch) || ch == '.') {
buffer[bufferCount++] = ch;
} else {
state = SCE_CONF_DEFAULT;
buffer[bufferCount] = '\0';
// Colourize here...
if( strchr(buffer,'.') ) {
// it is an IP address...
styler.ColourTo(i-1,SCE_CONF_IP);
} else {
// normal number
styler.ColourTo(i-1,SCE_CONF_NUMBER);
}
// push back a character
chNext = styler[i--];
}
break;
}
}
}
LexerModule lmConf(SCLEX_CONF, ColouriseConfDoc);
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <stan/model/model_base.hpp>
#include <stan/model/model_base_crtp.hpp>
#include <ostream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
struct mock_model : public stan::model::model_base_crtp<mock_model> {
mock_model(size_t n) : model_base_crtp(n) {}
virtual ~mock_model() {}
std::string model_name() const override { return "mock_model"; }
std::vector<std::string> model_compile_info() const {
std::vector<std::string> stanc_info;
stanc_info.push_back("stanc_version = stanc3");
return stanc_info;
}
void get_param_names(std::vector<std::string>& names) const override {}
void get_dims(std::vector<std::vector<size_t> >& dimss) const override {}
void constrained_param_names(std::vector<std::string>& param_names,
bool include_tparams,
bool include_gqs) const override {}
void unconstrained_param_names(std::vector<std::string>& param_names,
bool include_tparams,
bool include_gqs) const override {}
template <bool propto, bool jacobian, typename T>
T log_prob(Eigen::Matrix<T, -1, 1>& params_r, std::ostream* msgs) const {
if (std::is_same<T, double>::value) {
if (!propto && !jacobian)
return 1;
else if (!propto && jacobian)
return 3;
else if (propto && !jacobian)
return 5;
else
return 7;
} else {
if (!propto && !jacobian)
return 2;
else if (!propto && jacobian)
return 4;
else if (propto && !jacobian)
return 6;
else
return 8;
}
}
void transform_inits(const stan::io::var_context& context,
Eigen::VectorXd& params_r,
std::ostream* msgs) const override {}
template <typename RNG>
void write_array(RNG& base_rng, Eigen::VectorXd& params_r,
Eigen::VectorXd& params_constrained_r, bool include_tparams,
bool include_gqs, std::ostream* msgs) const {}
template <bool propto, bool jacobian, typename T>
T log_prob(std::vector<T>& params_r, std::vector<int>& params_i,
std::ostream* msgs) const {
if (std::is_same<T, double>::value) {
if (!propto && !jacobian)
return 1;
else if (!propto && jacobian)
return 3;
else if (propto && !jacobian)
return 5;
else
return 7;
} else {
if (!propto && !jacobian)
return 2;
else if (!propto && jacobian)
return 4;
else if (propto && !jacobian)
return 6;
else
return 8;
}
}
void transform_inits(const stan::io::var_context& context,
std::vector<int>& params_i,
std::vector<double>& params_r,
std::ostream* msgs) const override {}
template <typename RNG>
void write_array(RNG& base_rng, std::vector<double>& params_r,
std::vector<int>& params_i,
std::vector<double>& params_r_constrained,
bool include_tparams, bool include_gqs,
std::ostream* msgs) const {}
};
TEST(model, modelBaseInheritance) {
// check that base_model and prob_grad inheritance works
mock_model m(17);
EXPECT_EQ(17u, m.num_params_r());
EXPECT_EQ(0u, m.num_params_i());
EXPECT_THROW(m.param_range_i(0), std::out_of_range);
}
TEST(model, modelTemplateLogProb) {
mock_model m(17);
stan::model::model_base& bm = m;
Eigen::VectorXd params_r(2);
Eigen::Matrix<stan::math::var, -1, 1> params_r_v(3);
std::stringstream ss;
std::ostream* msgs = &ss;
// test from base class reference
EXPECT_FLOAT_EQ(1, bm.log_prob(params_r, msgs));
EXPECT_FLOAT_EQ(2, bm.log_prob(params_r_v, msgs).val());
EXPECT_FLOAT_EQ(3, bm.log_prob_jacobian(params_r, msgs));
EXPECT_FLOAT_EQ(4, bm.log_prob_jacobian(params_r_v, msgs).val());
EXPECT_FLOAT_EQ(5, bm.log_prob_propto(params_r, msgs));
EXPECT_FLOAT_EQ(6, bm.log_prob_propto(params_r_v, msgs).val());
EXPECT_FLOAT_EQ(7, bm.log_prob_propto_jacobian(params_r, msgs));
EXPECT_FLOAT_EQ(8, bm.log_prob_propto_jacobian(params_r_v, msgs).val());
// test template version from base class reference
// long form assignment avoids test macro parse error with multi tparams
double v1 = bm.template log_prob<false, false>(params_r, msgs);
EXPECT_FLOAT_EQ(1, v1);
double v2 = bm.template log_prob<false, false>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(2, v2);
double v3 = bm.template log_prob<false, true>(params_r, msgs);
EXPECT_FLOAT_EQ(3, v3);
double v4 = bm.template log_prob<false, true>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(4, v4);
double v5 = bm.template log_prob<true, false>(params_r, msgs);
EXPECT_FLOAT_EQ(5, v5);
double v6 = bm.template log_prob<true, false>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(6, v6);
double v7 = bm.template log_prob<true, true>(params_r, msgs);
EXPECT_FLOAT_EQ(7, v7);
double v8 = bm.template log_prob<true, true>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(8, v8);
}
<commit_msg>fix override for model_crtp test<commit_after>#include <gtest/gtest.h>
#include <stan/model/model_base.hpp>
#include <stan/model/model_base_crtp.hpp>
#include <ostream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
struct mock_model : public stan::model::model_base_crtp<mock_model> {
mock_model(size_t n) : model_base_crtp(n) {}
virtual ~mock_model() {}
std::string model_name() const override { return "mock_model"; }
std::vector<std::string> model_compile_info() const override {
std::vector<std::string> stanc_info;
stanc_info.push_back("stanc_version = stanc3");
return stanc_info;
}
void get_param_names(std::vector<std::string>& names) const override {}
void get_dims(std::vector<std::vector<size_t> >& dimss) const override {}
void constrained_param_names(std::vector<std::string>& param_names,
bool include_tparams,
bool include_gqs) const override {}
void unconstrained_param_names(std::vector<std::string>& param_names,
bool include_tparams,
bool include_gqs) const override {}
template <bool propto, bool jacobian, typename T>
T log_prob(Eigen::Matrix<T, -1, 1>& params_r, std::ostream* msgs) const {
if (std::is_same<T, double>::value) {
if (!propto && !jacobian)
return 1;
else if (!propto && jacobian)
return 3;
else if (propto && !jacobian)
return 5;
else
return 7;
} else {
if (!propto && !jacobian)
return 2;
else if (!propto && jacobian)
return 4;
else if (propto && !jacobian)
return 6;
else
return 8;
}
}
void transform_inits(const stan::io::var_context& context,
Eigen::VectorXd& params_r,
std::ostream* msgs) const override {}
template <typename RNG>
void write_array(RNG& base_rng, Eigen::VectorXd& params_r,
Eigen::VectorXd& params_constrained_r, bool include_tparams,
bool include_gqs, std::ostream* msgs) const {}
template <bool propto, bool jacobian, typename T>
T log_prob(std::vector<T>& params_r, std::vector<int>& params_i,
std::ostream* msgs) const {
if (std::is_same<T, double>::value) {
if (!propto && !jacobian)
return 1;
else if (!propto && jacobian)
return 3;
else if (propto && !jacobian)
return 5;
else
return 7;
} else {
if (!propto && !jacobian)
return 2;
else if (!propto && jacobian)
return 4;
else if (propto && !jacobian)
return 6;
else
return 8;
}
}
void transform_inits(const stan::io::var_context& context,
std::vector<int>& params_i,
std::vector<double>& params_r,
std::ostream* msgs) const override {}
template <typename RNG>
void write_array(RNG& base_rng, std::vector<double>& params_r,
std::vector<int>& params_i,
std::vector<double>& params_r_constrained,
bool include_tparams, bool include_gqs,
std::ostream* msgs) const {}
};
TEST(model, modelBaseInheritance) {
// check that base_model and prob_grad inheritance works
mock_model m(17);
EXPECT_EQ(17u, m.num_params_r());
EXPECT_EQ(0u, m.num_params_i());
EXPECT_THROW(m.param_range_i(0), std::out_of_range);
}
TEST(model, modelTemplateLogProb) {
mock_model m(17);
stan::model::model_base& bm = m;
Eigen::VectorXd params_r(2);
Eigen::Matrix<stan::math::var, -1, 1> params_r_v(3);
std::stringstream ss;
std::ostream* msgs = &ss;
// test from base class reference
EXPECT_FLOAT_EQ(1, bm.log_prob(params_r, msgs));
EXPECT_FLOAT_EQ(2, bm.log_prob(params_r_v, msgs).val());
EXPECT_FLOAT_EQ(3, bm.log_prob_jacobian(params_r, msgs));
EXPECT_FLOAT_EQ(4, bm.log_prob_jacobian(params_r_v, msgs).val());
EXPECT_FLOAT_EQ(5, bm.log_prob_propto(params_r, msgs));
EXPECT_FLOAT_EQ(6, bm.log_prob_propto(params_r_v, msgs).val());
EXPECT_FLOAT_EQ(7, bm.log_prob_propto_jacobian(params_r, msgs));
EXPECT_FLOAT_EQ(8, bm.log_prob_propto_jacobian(params_r_v, msgs).val());
// test template version from base class reference
// long form assignment avoids test macro parse error with multi tparams
double v1 = bm.template log_prob<false, false>(params_r, msgs);
EXPECT_FLOAT_EQ(1, v1);
double v2 = bm.template log_prob<false, false>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(2, v2);
double v3 = bm.template log_prob<false, true>(params_r, msgs);
EXPECT_FLOAT_EQ(3, v3);
double v4 = bm.template log_prob<false, true>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(4, v4);
double v5 = bm.template log_prob<true, false>(params_r, msgs);
EXPECT_FLOAT_EQ(5, v5);
double v6 = bm.template log_prob<true, false>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(6, v6);
double v7 = bm.template log_prob<true, true>(params_r, msgs);
EXPECT_FLOAT_EQ(7, v7);
double v8 = bm.template log_prob<true, true>(params_r_v, msgs).val();
EXPECT_FLOAT_EQ(8, v8);
}
<|endoftext|>
|
<commit_before>#include "LDLTSolver.h"
#include <sofa/core/ObjectFactory.h>
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include <Eigen/LU>
#include <Eigen/Cholesky>
#include <Eigen/SVD>
namespace sofa {
namespace component {
namespace linearsolver {
SOFA_DECL_CLASS(LDLTSolver);
int LDLTSolverClass = core::RegisterObject("Direct LDLT solver").add< LDLTSolver >();
typedef AssembledSystem::vec vec;
LDLTSolver::LDLTSolver()
: damping( initData(&damping, 0.0, "damping", "damping lol") )
, pimpl()
{
}
LDLTSolver::~LDLTSolver() {
}
void LDLTSolver::factor(const AssembledSystem& sys) {
pimpl->Hinv.compute( sys.H );
if( pimpl->Hinv.info() == Eigen::NumericalIssue ) {
std::cerr << "H is not psd :-/" << std::endl;
std::cerr << pimpl->H << std::endl;
}
pimpl->dt = sys.dt;
pimpl->m = sys.m;
pimpl->n = sys.n;
if( sys.n ) {
pimpl_type::cmat schur(sys.n, sys.n);
pimpl_type::cmat PJT = sys.P.transpose() * sys.J.transpose();
pimpl->HinvPJT.resize(sys.m, sys.n);
pimpl->HinvPJT = pimpl->Hinv.solve( PJT );
schur = (sys.C.transpose() + (PJT.transpose() * pimpl->HinvPJT )).selfadjointView<Eigen::Upper>();
pimpl->schur.compute( schur );
if( pimpl->schur.info() == Eigen::NumericalIssue ) {
std::cerr << "schur is not psd :-/" << std::endl;
std::cerr << schur << std::endl;
}
} else {
// nothing lol
}
}
void LDLTSolver::solve(AssembledSystem::vec& res,
const AssembledSystem& sys,
const AssembledSystem::vec& rhs) const {
assert( res.size() == sys.size() );
assert( rhs.size() == sys.size() );
SReal alpha = 1.0 / ( 1.0 + damping.getValue() * pimpl->dt );
vec tmp = alpha * (sys.P * rhs.head(sys.m));
// in place solve
tmp = pimpl->Hinv.solve(tmp);
res.head( sys.m ) = sys.P * tmp;
if( sys.n ) {
vec tmp = rhs.tail( sys.n ) - sys.P * (pimpl->HinvPJT.transpose() * rhs.head( sys.m ));
// lambdas
res.tail( sys.n ) = pimpl->schur.solve( tmp );
// constraint forces
res.head( sys.m ) += sys.P * (pimpl->HinvPJT * res.tail( sys.n));
}
}
}
}
}
<commit_msg>r10081/sofa : Compliant: fixed LDLT solver (yay!). Incidentally, CompliantCloth.scn works again.<commit_after>#include "LDLTSolver.h"
#include <sofa/core/ObjectFactory.h>
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include <Eigen/LU>
#include <Eigen/Cholesky>
#include <Eigen/SVD>
namespace sofa {
namespace component {
namespace linearsolver {
SOFA_DECL_CLASS(LDLTSolver);
int LDLTSolverClass = core::RegisterObject("Direct LDLT solver").add< LDLTSolver >();
typedef AssembledSystem::vec vec;
LDLTSolver::LDLTSolver()
: damping( initData(&damping, 0.0, "damping", "damping lol") )
, pimpl()
{
}
LDLTSolver::~LDLTSolver() {
}
void LDLTSolver::factor(const AssembledSystem& sys) {
pimpl->Hinv.compute( sys.H );
if( pimpl->Hinv.info() == Eigen::NumericalIssue ) {
std::cerr << "H is not psd :-/" << std::endl;
std::cerr << pimpl->H << std::endl;
}
pimpl->dt = sys.dt;
pimpl->m = sys.m;
pimpl->n = sys.n;
if( sys.n ) {
pimpl_type::cmat schur(sys.n, sys.n);
pimpl_type::cmat PJT = sys.P.transpose() * sys.J.transpose();
pimpl->HinvPJT.resize(sys.m, sys.n);
pimpl->HinvPJT = pimpl->Hinv.solve( PJT );
schur = (sys.C.transpose() + (PJT.transpose() * pimpl->HinvPJT )).selfadjointView<Eigen::Upper>();
pimpl->schur.compute( schur );
if( pimpl->schur.info() == Eigen::NumericalIssue ) {
std::cerr << "schur is not psd :-/" << std::endl;
std::cerr << schur << std::endl;
}
} else {
// nothing lol
}
}
void LDLTSolver::solve(AssembledSystem::vec& res,
const AssembledSystem& sys,
const AssembledSystem::vec& rhs) const {
assert( res.size() == sys.size() );
assert( rhs.size() == sys.size() );
vec Pv = (sys.P * rhs.head(sys.m));
// in place solve
Pv = pimpl->Hinv.solve( Pv );
res.head( sys.m ) = sys.P * Pv;
if( sys.n ) {
vec tmp = rhs.tail( sys.n ) - pimpl->HinvPJT.transpose() * rhs.head( sys.m );
// lambdas
res.tail( sys.n ) = pimpl->schur.solve( tmp );
// constraint forces
res.head( sys.m ) += sys.P * (pimpl->HinvPJT * res.tail( sys.n));
}
}
}
}
}
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// RoboSimian on granular terrain
//
// =============================================================================
#include <cmath>
#include <cstdio>
#include <vector>
#include "chrono/core/ChFileutils.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_parallel/physics/ChSystemParallel.h"
#include "chrono_vehicle/terrain/GranularTerrain.h"
#include "chrono_opengl/ChOpenGLWindow.h"
#include "robosimian.h"
using namespace chrono;
using namespace chrono::collision;
// Integration step size
double step_size = 1e-4;
// OpenGL rendering?
bool render = true;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
// Drop the robot on terrain
bool drop = true;
// Timed events
double time_create_terrain = 0.5;
double duration_settle_terrain = 1.0;
double time_release = time_create_terrain + duration_settle_terrain;
double duration_settle_robot = 0.5;
double time_offset = time_release + duration_settle_robot;
double duration_sim = 10;
double time_end = time_offset + duration_sim;
// Output directories
const std::string out_dir = GetChronoOutputPath() + "ROBOSIMIAN_PAR";
const std::string pov_dir = out_dir + "/POVRAY";
// POV-Ray output
bool povray_output = false;
// =============================================================================
class RobotDriverCallback : public robosimian::Driver::PhaseChangeCallback {
public:
RobotDriverCallback(robosimian::RoboSimian* robot) : m_robot(robot), m_start_x(0), m_start_time(0) {}
virtual void OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) override;
double GetDistance() const { return m_robot->GetChassisPos().x() - m_start_x; }
double GetDuration() const { return m_robot->GetSystem()->GetChTime() - m_start_time; }
double GetAvgSpeed() const { return GetDistance() / GetDuration(); }
double m_start_x;
double m_start_time;
private:
robosimian::RoboSimian* m_robot;
};
void RobotDriverCallback::OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) {
if (new_phase == robosimian::Driver::CYCLE && old_phase != robosimian::Driver::CYCLE) {
m_start_x = m_robot->GetChassisPos().x();
m_start_time = m_robot->GetSystem()->GetChTime();
}
}
// =============================================================================
double CreateTerrain(ChSystem& sys, double x, double z) {
double r_g = 0.0075;
double rho_g = 2000;
double coh = 400e3;
double area = CH_C_PI * r_g * r_g;
double coh_force = area * coh;
double coh_g = coh_force * step_size;
std::cout << "x = " << x << " z = " << z << std::endl;
double length = 6;
double width = 3;
unsigned int num_layers = 5;
ChVector<> center(length / 2 + x - 1.5, 0, z - num_layers * 2.1 * r_g);
vehicle::GranularTerrain terrain(&sys);
terrain.SetContactFrictionCoefficient(0.7f);
terrain.SetContactCohesion((float)coh_g);
terrain.SetCollisionEnvelope(0.1 * r_g / 5);
terrain.EnableVisualization(true);
terrain.Initialize(center, length, width, num_layers, r_g, rho_g);
std::cout << "Generated " << terrain.GetNumParticles() << " particles";
return (length + x - 2 * 1.5);
}
// =============================================================================
int main(int argc, char* argv[]) {
// -------------
// Create system
// -------------
////ChSystemParallelSMC my_sys;
ChSystemParallelNSC my_sys;
my_sys.Set_G_acc(ChVector<double>(0, 0, -9.8));
////my_sys.Set_G_acc(ChVector<double>(0, 0, 0));
int threads = 2;
int max_threads = CHOMPfunctions::GetNumProcs();
if (threads > max_threads)
threads = max_threads;
my_sys.SetParallelThreadNumber(threads);
CHOMPfunctions::SetNumThreads(threads);
my_sys.GetSettings()->solver.tolerance = 1e-3;
my_sys.GetSettings()->solver.solver_mode = SolverMode::SLIDING;
my_sys.GetSettings()->solver.max_iteration_normal = 0;
my_sys.GetSettings()->solver.max_iteration_sliding = 100;
my_sys.GetSettings()->solver.max_iteration_spinning = 0;
my_sys.GetSettings()->solver.max_iteration_bilateral = 100;
my_sys.GetSettings()->solver.compute_N = false;
my_sys.GetSettings()->solver.alpha = 0;
my_sys.GetSettings()->solver.cache_step_length = true;
my_sys.GetSettings()->solver.use_full_inertia_tensor = false;
my_sys.GetSettings()->solver.contact_recovery_speed = 1000;
my_sys.GetSettings()->solver.bilateral_clamp_speed = 1e8;
my_sys.GetSettings()->min_threads = threads;
my_sys.GetSettings()->collision.collision_envelope = 0.01;
my_sys.GetSettings()->collision.narrowphase_algorithm = NarrowPhaseType::NARROWPHASE_HYBRID_MPR;
my_sys.ChangeSolverType(SolverType::BB);
// -----------------------
// Create RoboSimian robot
// -----------------------
robosimian::RoboSimian robot(&my_sys, true, true);
// Ensure wheels are actuated in ANGLE mode (required for Chrono::Parallel)
robot.SetMotorActuationMode(robosimian::ActuationMode::ANGLE);
////robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), QUNIT));
robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI)));
robot.SetVisualizationTypeChassis(robosimian::VisualizationType::MESH);
robot.SetVisualizationTypeSled(robosimian::VisualizationType::MESH);
robot.SetVisualizationTypeLimbs(robosimian::VisualizationType::MESH);
// -----------------------------------
// Create a driver and attach to robot
// -----------------------------------
////auto driver = std::make_shared<robosimian::Driver>(
//// "", // start input file
//// GetChronoDataFile("robosimian/actuation/walking_cycle.txt"), // cycle input file
//// "", // stop input file
//// true);
////auto driver = std::make_shared<robosimian::Driver>(
//// GetChronoDataFile("robosimian/actuation/sculling_start.txt"), // start input file
//// GetChronoDataFile("robosimian/actuation/sculling_cycle.txt"), // cycle input file
//// GetChronoDataFile("robosimian/actuation/sculling_stop.txt"), // stop input file
//// true);
////auto driver = std::make_shared<robosimian::Driver>(
//// GetChronoDataFile("robosimian/actuation/inchworming_start.txt"), // start input file
//// GetChronoDataFile("robosimian/actuation/inchworming_cycle.txt"), // cycle input file
//// GetChronoDataFile("robosimian/actuation/inchworming_stop.txt"), // stop input file
//// true);
auto driver = std::make_shared<robosimian::Driver>(
GetChronoDataFile("robosimian/actuation/driving_start.txt"), // start input file
GetChronoDataFile("robosimian/actuation/driving_cycle.txt"), // cycle input file
GetChronoDataFile("robosimian/actuation/driving_stop.txt"), // stop input file
true);
RobotDriverCallback cbk(&robot);
driver->RegisterPhaseChangeCallback(&cbk);
driver->SetOffset(time_offset);
robot.SetDriver(driver);
// -----------------
// Initialize OpenGL
// -----------------
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "RoboSimian", &my_sys);
gl_window.SetCamera(ChVector<>(2, -2, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 0.05f);
gl_window.SetRenderMode(opengl::WIREFRAME);
}
// -----------------------------
// Initialize output directories
// -----------------------------
if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if (povray_output) {
if (ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
}
// ---------------------------------
// Run simulation for specified time
// ---------------------------------
int render_steps = (int)std::ceil(render_step_size / step_size);
int sim_frame = 0;
int render_frame = 0;
bool terrain_created = false;
bool robot_released = false;
double x_max = 0;
while (true) {
double time = my_sys.GetChTime();
double x = robot.GetChassisPos().x();
if (time >= time_end) {
std::cout << "Reached final time: " << time << std::endl;
break;
}
if (drop) {
if (!terrain_created && time > time_create_terrain) {
// Robot position and bottom point
double z = robot.GetWheelPos(robosimian::FR).z() - 0.15;
// Create terrain
std::cout << "Time: " << time << " CREATE TERRAIN" << std::endl;
x_max = CreateTerrain(my_sys, x, z);
terrain_created = true;
}
if (!robot_released && time > time_release) {
std::cout << "Time: " << time << " RELEASE ROBOT" << std::endl;
robot.GetChassis()->GetBody()->SetBodyFixed(false);
robot_released = true;
}
if (robot_released && x > x_max) {
std::cout << "Time: " << time << " Reached maximum distance" << std::endl;
break;
}
}
// Output POV-Ray data
if (povray_output && sim_frame % render_steps == 0) {
char filename[100];
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&my_sys, filename);
render_frame++;
}
////double time = my_sys.GetChTime();
////double A = CH_C_PI / 6;
////double freq = 2;
////double val = 0.5 * A * (1 - std::cos(CH_C_2PI * freq * time));
////robot.Activate(robosimian::FR, "joint2", time, val);
////robot.Activate(robosimian::RL, "joint5", time, val);
////robot.Activate(robosimian::FL, "joint8", time, -0.4 * time);
robot.DoStepDynamics(step_size);
////if (my_sys.GetNcontacts() > 0) {
//// robot.ReportContacts();
////}
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
if (gl_window.Active()) {
gl_window.Render();
} else {
break;
}
}
sim_frame++;
}
return 0;
}
<commit_msg>Properly set number of bins and collision envelope for RoboSimian parallel test<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// RoboSimian on granular terrain
//
// =============================================================================
#include <cmath>
#include <cstdio>
#include <vector>
#include "chrono/core/ChFileutils.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_parallel/physics/ChSystemParallel.h"
#include "chrono_vehicle/terrain/GranularTerrain.h"
#include "chrono_opengl/ChOpenGLWindow.h"
#include "robosimian.h"
using namespace chrono;
using namespace chrono::collision;
// Integration step size
double step_size = 1e-4;
// OpenGL rendering?
bool render = true;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
// Drop the robot on terrain
bool drop = true;
// Timed events
double time_create_terrain = 0.5;
double duration_settle_terrain = 1.0;
double time_release = time_create_terrain + duration_settle_terrain;
double duration_settle_robot = 0.5;
double time_offset = time_release + duration_settle_robot;
double duration_sim = 10;
double time_end = time_offset + duration_sim;
// Output directories
const std::string out_dir = GetChronoOutputPath() + "ROBOSIMIAN_PAR";
const std::string pov_dir = out_dir + "/POVRAY";
// POV-Ray output
bool povray_output = false;
// =============================================================================
class RobotDriverCallback : public robosimian::Driver::PhaseChangeCallback {
public:
RobotDriverCallback(robosimian::RoboSimian* robot) : m_robot(robot), m_start_x(0), m_start_time(0) {}
virtual void OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) override;
double GetDistance() const { return m_robot->GetChassisPos().x() - m_start_x; }
double GetDuration() const { return m_robot->GetSystem()->GetChTime() - m_start_time; }
double GetAvgSpeed() const { return GetDistance() / GetDuration(); }
double m_start_x;
double m_start_time;
private:
robosimian::RoboSimian* m_robot;
};
void RobotDriverCallback::OnPhaseChange(robosimian::Driver::Phase old_phase, robosimian::Driver::Phase new_phase) {
if (new_phase == robosimian::Driver::CYCLE && old_phase != robosimian::Driver::CYCLE) {
m_start_x = m_robot->GetChassisPos().x();
m_start_time = m_robot->GetSystem()->GetChTime();
}
}
// =============================================================================
double CreateTerrain(ChSystemParallel& sys, double x, double z) {
double r_g = 0.0075;
double rho_g = 2000;
double coh = 400e3;
double area = CH_C_PI * r_g * r_g;
double coh_force = area * coh;
double coh_g = coh_force * step_size;
std::cout << "x = " << x << " z = " << z << std::endl;
double length = 6;
double width = 3;
unsigned int num_layers = 5;
ChVector<> center(length / 2 + x - 1.5, 0, z - num_layers * 2.1 * r_g);
vehicle::GranularTerrain terrain(&sys);
terrain.SetContactFrictionCoefficient(0.7f);
terrain.SetContactCohesion((float)coh_g);
terrain.SetCollisionEnvelope(0.1 * r_g / 5);
terrain.EnableVisualization(true);
terrain.Initialize(center, length, width, num_layers, r_g, rho_g);
std::cout << "Generated " << terrain.GetNumParticles() << " particles" << std::endl;
// Estimate number of bins for collision detection
int factor = 2;
int binsX = (int)std::ceil((0.5 * length) / r_g) / factor;
int binsY = (int)std::ceil((0.5 * width) / r_g) / factor;
int binsZ = 1;
sys.GetSettings()->collision.bins_per_axis = vec3(binsX, binsY, binsZ);
std::cout << " broad-phase bins: " << binsX << " x " << binsY << " x " << binsZ << std::endl;
// Set collision envelope
sys.GetSettings()->collision.collision_envelope = 0.1 * r_g / 5;
return (length + x - 2 * 1.5);
}
// =============================================================================
int main(int argc, char* argv[]) {
// -------------
// Create system
// -------------
////ChSystemParallelSMC my_sys;
ChSystemParallelNSC my_sys;
my_sys.Set_G_acc(ChVector<double>(0, 0, -9.8));
////my_sys.Set_G_acc(ChVector<double>(0, 0, 0));
int threads = 2;
int max_threads = CHOMPfunctions::GetNumProcs();
if (threads > max_threads)
threads = max_threads;
my_sys.SetParallelThreadNumber(threads);
CHOMPfunctions::SetNumThreads(threads);
my_sys.GetSettings()->solver.tolerance = 1e-3;
my_sys.GetSettings()->solver.solver_mode = SolverMode::SLIDING;
my_sys.GetSettings()->solver.max_iteration_normal = 0;
my_sys.GetSettings()->solver.max_iteration_sliding = 100;
my_sys.GetSettings()->solver.max_iteration_spinning = 0;
my_sys.GetSettings()->solver.max_iteration_bilateral = 100;
my_sys.GetSettings()->solver.compute_N = false;
my_sys.GetSettings()->solver.alpha = 0;
my_sys.GetSettings()->solver.cache_step_length = true;
my_sys.GetSettings()->solver.use_full_inertia_tensor = false;
my_sys.GetSettings()->solver.contact_recovery_speed = 1000;
my_sys.GetSettings()->solver.bilateral_clamp_speed = 1e8;
my_sys.GetSettings()->min_threads = threads;
my_sys.GetSettings()->collision.collision_envelope = 0.01;
my_sys.GetSettings()->collision.narrowphase_algorithm = NarrowPhaseType::NARROWPHASE_HYBRID_MPR;
my_sys.ChangeSolverType(SolverType::BB);
// -----------------------
// Create RoboSimian robot
// -----------------------
robosimian::RoboSimian robot(&my_sys, true, true);
// Ensure wheels are actuated in ANGLE mode (required for Chrono::Parallel)
robot.SetMotorActuationMode(robosimian::ActuationMode::ANGLE);
////robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), QUNIT));
robot.Initialize(ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI)));
robot.SetVisualizationTypeChassis(robosimian::VisualizationType::MESH);
robot.SetVisualizationTypeSled(robosimian::VisualizationType::MESH);
robot.SetVisualizationTypeLimbs(robosimian::VisualizationType::MESH);
// -----------------------------------
// Create a driver and attach to robot
// -----------------------------------
////auto driver = std::make_shared<robosimian::Driver>(
//// "", // start input file
//// GetChronoDataFile("robosimian/actuation/walking_cycle.txt"), // cycle input file
//// "", // stop input file
//// true);
////auto driver = std::make_shared<robosimian::Driver>(
//// GetChronoDataFile("robosimian/actuation/sculling_start.txt"), // start input file
//// GetChronoDataFile("robosimian/actuation/sculling_cycle.txt"), // cycle input file
//// GetChronoDataFile("robosimian/actuation/sculling_stop.txt"), // stop input file
//// true);
////auto driver = std::make_shared<robosimian::Driver>(
//// GetChronoDataFile("robosimian/actuation/inchworming_start.txt"), // start input file
//// GetChronoDataFile("robosimian/actuation/inchworming_cycle.txt"), // cycle input file
//// GetChronoDataFile("robosimian/actuation/inchworming_stop.txt"), // stop input file
//// true);
auto driver = std::make_shared<robosimian::Driver>(
GetChronoDataFile("robosimian/actuation/driving_start.txt"), // start input file
GetChronoDataFile("robosimian/actuation/driving_cycle.txt"), // cycle input file
GetChronoDataFile("robosimian/actuation/driving_stop.txt"), // stop input file
true);
RobotDriverCallback cbk(&robot);
driver->RegisterPhaseChangeCallback(&cbk);
driver->SetOffset(time_offset);
robot.SetDriver(driver);
// -----------------
// Initialize OpenGL
// -----------------
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "RoboSimian", &my_sys);
gl_window.SetCamera(ChVector<>(2, -2, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 0.05f);
gl_window.SetRenderMode(opengl::WIREFRAME);
}
// -----------------------------
// Initialize output directories
// -----------------------------
if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if (povray_output) {
if (ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
}
// ---------------------------------
// Run simulation for specified time
// ---------------------------------
int render_steps = (int)std::ceil(render_step_size / step_size);
int sim_frame = 0;
int render_frame = 0;
bool terrain_created = false;
bool robot_released = false;
double x_max = 0;
while (true) {
double time = my_sys.GetChTime();
double x = robot.GetChassisPos().x();
if (time >= time_end) {
std::cout << "Reached final time: " << time << std::endl;
break;
}
if (drop) {
if (!terrain_created && time > time_create_terrain) {
// Robot position and bottom point
double z = robot.GetWheelPos(robosimian::FR).z() - 0.15;
// Create terrain
std::cout << "Time: " << time << " CREATE TERRAIN" << std::endl;
x_max = CreateTerrain(my_sys, x, z);
terrain_created = true;
}
if (!robot_released && time > time_release) {
std::cout << "Time: " << time << " RELEASE ROBOT" << std::endl;
robot.GetChassis()->GetBody()->SetBodyFixed(false);
robot_released = true;
}
if (robot_released && x > x_max) {
std::cout << "Time: " << time << " Reached maximum distance" << std::endl;
break;
}
}
// Output POV-Ray data
if (povray_output && sim_frame % render_steps == 0) {
char filename[100];
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&my_sys, filename);
render_frame++;
}
////double time = my_sys.GetChTime();
////double A = CH_C_PI / 6;
////double freq = 2;
////double val = 0.5 * A * (1 - std::cos(CH_C_2PI * freq * time));
////robot.Activate(robosimian::FR, "joint2", time, val);
////robot.Activate(robosimian::RL, "joint5", time, val);
////robot.Activate(robosimian::FL, "joint8", time, -0.4 * time);
robot.DoStepDynamics(step_size);
////if (my_sys.GetNcontacts() > 0) {
//// robot.ReportContacts();
////}
if (render) {
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
if (gl_window.Active()) {
gl_window.Render();
} else {
break;
}
}
sim_frame++;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexLisp.cxx
** Lexer for Lisp.
** Written by Alexey Yutkin.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool isLispoperator(char ch) {
if (isascii(ch) && isalnum(ch))
return false;
if (ch == '\'' || ch == '(' || ch == ')' )
return true;
return false;
}
static inline bool isLispwordstart(char ch) {
return isascii(ch) && ch != ';' && !isspacechar(ch) && !isLispoperator(ch) &&
ch != '\n' && ch != '\r' && ch != '\"';
}
static void classifyWordLisp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
PLATFORM_ASSERT(end >= start);
char s[100];
unsigned int i;
bool digit_flag = true;
for (i = 0; (i < end - start + 1) && (i < 99); i++) {
s[i] = styler[start + i];
s[i + 1] = '\0';
if (!isdigit(s[i]) && (s[i] != '.')) digit_flag = false;
}
char chAttr = SCE_LISP_IDENTIFIER;
if(digit_flag) chAttr = SCE_LISP_NUMBER;
else {
if (keywords.InList(s)) {
chAttr = SCE_LISP_KEYWORD;
}
}
styler.ColourTo(end, chAttr);
return;
}
static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
int state = initStyle;
char chNext = styler[startPos];
unsigned int lengthDoc = startPos + length;
styler.StartSegment(startPos);
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
i += 1;
continue;
}
if (state == SCE_LISP_DEFAULT) {
if (isLispwordstart(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_LISP_IDENTIFIER;
}
else if (ch == ';') {
styler.ColourTo(i - 1, state);
state = SCE_LISP_COMMENT;
}
else if (isLispoperator(ch) || ch=='\'') {
styler.ColourTo(i - 1, state);
styler.ColourTo(i, SCE_LISP_OPERATOR);
}
else if (ch == '\"') {
styler.ColourTo(i - 1, state);
state = SCE_LISP_STRING;
}
} else if (state == SCE_LISP_IDENTIFIER) {
if (!isLispwordstart(ch)) {
classifyWordLisp(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_LISP_DEFAULT;
} /*else*/
if (isLispoperator(ch) || ch=='\'') {
styler.ColourTo(i - 1, state);
styler.ColourTo(i, SCE_LISP_OPERATOR);
}
} else {
if (state == SCE_LISP_COMMENT) {
if (atEOL) {
styler.ColourTo(i - 1, state);
state = SCE_LISP_DEFAULT;
}
} else if (state == SCE_LISP_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_LISP_DEFAULT;
}
}
}
}
styler.ColourTo(lengthDoc - 1, state);
}
static void FoldLispDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LISP_OPERATOR) {
if (ch == '(') {
levelCurrent++;
} else if (ch == ')') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const lispWordListDesc[] = {
"Keywords",
0
};
LexerModule lmLISP(SCLEX_LISP, ColouriseLispDoc, "lisp", FoldLispDoc, lispWordListDesc);
<commit_msg>Patch from Michael Goffioul to Lisp adds SYMBOL, SPECIAL, and MULTI_COMMENT states and a second keyword set.<commit_after>// Scintilla source code edit control
/** @file LexLisp.cxx
** Lexer for Lisp.
** Written by Alexey Yutkin.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "StyleContext.h"
#define SCE_LISP_CHARACTER 29
#define SCE_LISP_MACRO 30
#define SCE_LISP_MACRO_DISPATCH 31
static inline bool isLispoperator(char ch) {
if (isascii(ch) && isalnum(ch))
return false;
if (ch == '\'' || ch == '`' || ch == '(' || ch == ')' )
return true;
return false;
}
static inline bool isLispwordstart(char ch) {
return isascii(ch) && ch != ';' && !isspacechar(ch) && !isLispoperator(ch) &&
ch != '\n' && ch != '\r' && ch != '\"';
}
static void classifyWordLisp(unsigned int start, unsigned int end, WordList &keywords, WordList &keywords_kw, Accessor &styler) {
PLATFORM_ASSERT(end >= start);
char s[100];
unsigned int i;
bool digit_flag = true;
for (i = 0; (i < end - start + 1) && (i < 99); i++) {
s[i] = styler[start + i];
s[i + 1] = '\0';
if (!isdigit(s[i]) && (s[i] != '.')) digit_flag = false;
}
char chAttr = SCE_LISP_IDENTIFIER;
if(digit_flag) chAttr = SCE_LISP_NUMBER;
else {
if (keywords.InList(s)) {
chAttr = SCE_LISP_KEYWORD;
} else if (keywords_kw.InList(s)) {
chAttr = SCE_LISP_KEYWORD_KW;
} else if ((s[0] == '*' && s[i-1] == '*') ||
(s[0] == '+' && s[i-1] == '+')) {
chAttr = SCE_LISP_SPECIAL;
}
}
styler.ColourTo(end, chAttr);
return;
}
static void ColouriseLispDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords_kw = *keywordlists[1];
styler.StartAt(startPos);
int state = initStyle, radix = -1;
char chNext = styler[startPos];
unsigned int lengthDoc = startPos + length;
styler.StartSegment(startPos);
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
i += 1;
continue;
}
if (state == SCE_LISP_DEFAULT) {
if (ch == '#') {
styler.ColourTo(i - 1, state);
radix = -1;
state = SCE_LISP_MACRO_DISPATCH;
} else if (isLispwordstart(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_LISP_IDENTIFIER;
}
else if (ch == ';') {
styler.ColourTo(i - 1, state);
state = SCE_LISP_COMMENT;
}
else if (isLispoperator(ch) || ch=='\'') {
styler.ColourTo(i - 1, state);
styler.ColourTo(i, SCE_LISP_OPERATOR);
if (ch=='\'' && isLispwordstart(chNext)) {
state = SCE_LISP_SYMBOL;
}
}
else if (ch == '\"') {
styler.ColourTo(i - 1, state);
state = SCE_LISP_STRING;
}
} else if (state == SCE_LISP_IDENTIFIER || state == SCE_LISP_SYMBOL) {
if (!isLispwordstart(ch)) {
if (state == SCE_LISP_IDENTIFIER) {
classifyWordLisp(styler.GetStartSegment(), i - 1, keywords, keywords_kw, styler);
} else {
styler.ColourTo(i - 1, state);
}
state = SCE_LISP_DEFAULT;
} /*else*/
if (isLispoperator(ch) || ch=='\'') {
styler.ColourTo(i - 1, state);
styler.ColourTo(i, SCE_LISP_OPERATOR);
if (ch=='\'' && isLispwordstart(chNext)) {
state = SCE_LISP_SYMBOL;
}
}
} else if (state == SCE_LISP_MACRO_DISPATCH) {
if (!isdigit(ch)) {
if (ch != 'r' && ch != 'R' && (i - styler.GetStartSegment()) > 1) {
state = SCE_LISP_DEFAULT;
} else {
switch (ch) {
case '|': state = SCE_LISP_MULTI_COMMENT; break;
case 'o':
case 'O': radix = 8; state = SCE_LISP_MACRO; break;
case 'x':
case 'X': radix = 16; state = SCE_LISP_MACRO; break;
case 'b':
case 'B': radix = 2; state = SCE_LISP_MACRO; break;
case '\\': state = SCE_LISP_CHARACTER; break;
case ':':
case '-':
case '+': state = SCE_LISP_MACRO; break;
case '\'': if (isLispwordstart(chNext)) {
state = SCE_LISP_SPECIAL;
} else {
styler.ColourTo(i - 1, SCE_LISP_DEFAULT);
styler.ColourTo(i, SCE_LISP_OPERATOR);
state = SCE_LISP_DEFAULT;
}
break;
default: if (isLispoperator(ch)) {
styler.ColourTo(i - 1, SCE_LISP_DEFAULT);
styler.ColourTo(i, SCE_LISP_OPERATOR);
}
state = SCE_LISP_DEFAULT;
break;
}
}
}
} else if (state == SCE_LISP_MACRO) {
if (isLispwordstart(ch) && (radix == -1 || IsADigit(ch, radix))) {
state = SCE_LISP_SPECIAL;
} else {
state = SCE_LISP_DEFAULT;
}
} else if (state == SCE_LISP_CHARACTER) {
if (isLispoperator(ch)) {
styler.ColourTo(i, SCE_LISP_SPECIAL);
state = SCE_LISP_DEFAULT;
} else if (isLispwordstart(ch)) {
styler.ColourTo(i, SCE_LISP_SPECIAL);
state = SCE_LISP_SPECIAL;
} else {
state = SCE_LISP_DEFAULT;
}
} else if (state == SCE_LISP_SPECIAL) {
if (!isLispwordstart(ch) || (radix != -1 && !IsADigit(ch, radix))) {
styler.ColourTo(i - 1, state);
state = SCE_LISP_DEFAULT;
}
if (isLispoperator(ch) || ch=='\'') {
styler.ColourTo(i - 1, state);
styler.ColourTo(i, SCE_LISP_OPERATOR);
if (ch=='\'' && isLispwordstart(chNext)) {
state = SCE_LISP_SYMBOL;
}
}
} else {
if (state == SCE_LISP_COMMENT) {
if (atEOL) {
styler.ColourTo(i - 1, state);
state = SCE_LISP_DEFAULT;
}
} else if (state == SCE_LISP_MULTI_COMMENT) {
if (ch == '|' && chNext == '#') {
i++;
chNext = styler.SafeGetCharAt(i + 1);
styler.ColourTo(i, state);
state = SCE_LISP_DEFAULT;
}
} else if (state == SCE_LISP_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_LISP_DEFAULT;
}
}
}
}
styler.ColourTo(lengthDoc - 1, state);
}
static void FoldLispDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LISP_OPERATOR) {
if (ch == '(') {
levelCurrent++;
} else if (ch == ')') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const lispWordListDesc[] = {
"Functions and special operators",
"Keywords",
0
};
LexerModule lmLISP(SCLEX_LISP, ColouriseLispDoc, "lisp", FoldLispDoc, lispWordListDesc);
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Library
Module: MergePts.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "MergePts.hh"
// Description:
// Merge points together if they are exactly coincident. Return a list
// that maps unmerged point ids into new point ids. User is responsible
// for freeing list (use delete []).
int *vlMergePoints::MergePoints()
{
float *bounds;
int ptId, i, j;
int numPts;
int *index;
int newPtId;
float *pt, *p;
int ijk[3];
int cno;
vlIdList *ptIds;
vlDebugMacro(<<"Merging points");
if ( this->Points == NULL ||
(numPts=this->Points->GetNumberOfPoints()) < 1 ) return NULL;
this->SubDivide(); // subdivides if necessary
bounds = this->Points->GetBounds();
index = new int[numPts];
for (i=0; i < numPts; i++) index[i] = -1;
newPtId = 0; // renumbering points
//
// Traverse each point, find bucket that point is in, check the list of
// points in that bucket for merging. Also need to search all
// neighboring buckets within the tolerance. The number and level of
// neighbors to search depends upon the tolerance and the bucket width.
//
for ( i=0; i < numPts; i++ ) //loop over all points
{
// Only try to merge the point if it hasn't yet been merged.
if ( index[i] == -1 )
{
p = this->Points->GetPoint(i);
index[i] = newPtId;
for (j=0; j<3; j++)
ijk[j] = (int) ((float)((p[j] - bounds[2*j])*0.999 /
(bounds[2*j+1] - bounds[2*j])) * this->Divisions[j]);
cno = ijk[0] + ijk[1]*this->Divisions[0] +
ijk[2]*this->Divisions[0]*this->Divisions[1];
if ( (ptIds = this->HashTable[cno]) != NULL )
{
for (j=0; j < ptIds->GetNumberOfIds(); j++)
{
ptId = ptIds->GetId(j);
pt = this->Points->GetPoint(ptId);
if ( index[ptId] == -1 && pt[0] == p[0] && pt[1] == p[1]
&& pt[2] == p[2] )
{
index[ptId] = newPtId;
}
}
}
newPtId++;
} // if point hasn't been merged
} // for all points
return index;
}
// Description:
// Incrementally insert a point into search structure, merging the point
// with pre-inserted point (if precisely coincident). If point is merged
// with pre-inserted point, pre-inserted point id is returned. Otherwise,
// new point id is returned. Before using this method you must make sure
// that newPts have been supplied, the bounds has been set properly, and
// that divs are properly set. (See InitPointInsertion()).
int vlMergePoints::InsertPoint(float x[3])
{
int i, ijk[3];
int idx;
vlIdList *bucket;
//
// Locate bucket that point is in.
//
for (i=0; i<3; i++)
{
ijk[i] = (int) ((float) ((x[i] - this->Bounds[2*i])*0.999 /
(this->Bounds[2*i+1] - this->Bounds[2*i])) * this->Divisions[i]);
}
idx = ijk[0] + ijk[1]*this->Divisions[0] +
ijk[2]*this->Divisions[0]*this->Divisions[1];
bucket = this->HashTable[idx];
if ( ! bucket )
{
bucket = new vlIdList(this->NumberOfPointsInBucket/2);
this->HashTable[idx] = bucket;
}
else // see whether we've got duplicate point
{
//
// Check the list of points in that bucket.
//
int ptId;
float *pt;
for (i=0; i < bucket->GetNumberOfIds(); i++)
{
ptId = bucket->GetId(i);
pt = this->Points->GetPoint(ptId);
if ( x[0] == pt[0] && x[1] == pt[1] && x[2] == pt[2] ) return ptId;
}
}
bucket->InsertNextId(this->InsertionPointId);
this->Points->InsertPoint(this->InsertionPointId,x);
return this->InsertionPointId++;
}
<commit_msg>ERR: Fixed zero width bug<commit_after>/*=========================================================================
Program: Visualization Library
Module: MergePts.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "MergePts.hh"
// Description:
// Merge points together if they are exactly coincident. Return a list
// that maps unmerged point ids into new point ids. User is responsible
// for freeing list (use delete []).
int *vlMergePoints::MergePoints()
{
int ptId, i, j;
int numPts;
int *index;
int newPtId;
float *pt, *p;
int ijk[3];
int cno;
vlIdList *ptIds;
vlDebugMacro(<<"Merging points");
if ( this->Points == NULL ||
(numPts=this->Points->GetNumberOfPoints()) < 1 ) return NULL;
this->SubDivide(); // subdivides if necessary
index = new int[numPts];
for (i=0; i < numPts; i++) index[i] = -1;
newPtId = 0; // renumbering points
//
// Traverse each point, find bucket that point is in, check the list of
// points in that bucket for merging. Also need to search all
// neighboring buckets within the tolerance. The number and level of
// neighbors to search depends upon the tolerance and the bucket width.
//
for ( i=0; i < numPts; i++ ) //loop over all points
{
// Only try to merge the point if it hasn't yet been merged.
if ( index[i] == -1 )
{
p = this->Points->GetPoint(i);
index[i] = newPtId;
for (j=0; j<3; j++)
ijk[j] = (int) ((float)((p[j] - this->Bounds[2*j])*0.999 /
(this->Bounds[2*j+1] - this->Bounds[2*j])) * this->Divisions[j]);
cno = ijk[0] + ijk[1]*this->Divisions[0] +
ijk[2]*this->Divisions[0]*this->Divisions[1];
if ( (ptIds = this->HashTable[cno]) != NULL )
{
for (j=0; j < ptIds->GetNumberOfIds(); j++)
{
ptId = ptIds->GetId(j);
pt = this->Points->GetPoint(ptId);
if ( index[ptId] == -1 && pt[0] == p[0] && pt[1] == p[1]
&& pt[2] == p[2] )
{
index[ptId] = newPtId;
}
}
}
newPtId++;
} // if point hasn't been merged
} // for all points
return index;
}
// Description:
// Incrementally insert a point into search structure, merging the point
// with pre-inserted point (if precisely coincident). If point is merged
// with pre-inserted point, pre-inserted point id is returned. Otherwise,
// new point id is returned. Before using this method you must make sure
// that newPts have been supplied, the bounds has been set properly, and
// that divs are properly set. (See InitPointInsertion()).
int vlMergePoints::InsertPoint(float x[3])
{
int i, ijk[3];
int idx;
vlIdList *bucket;
//
// Locate bucket that point is in.
//
for (i=0; i<3; i++)
{
ijk[i] = (int) ((float) ((x[i] - this->Bounds[2*i])*0.999 /
(this->Bounds[2*i+1] - this->Bounds[2*i])) * this->Divisions[i]);
}
idx = ijk[0] + ijk[1]*this->Divisions[0] +
ijk[2]*this->Divisions[0]*this->Divisions[1];
bucket = this->HashTable[idx];
if ( ! bucket )
{
bucket = new vlIdList(this->NumberOfPointsInBucket/2);
this->HashTable[idx] = bucket;
}
else // see whether we've got duplicate point
{
//
// Check the list of points in that bucket.
//
int ptId;
float *pt;
for (i=0; i < bucket->GetNumberOfIds(); i++)
{
ptId = bucket->GetId(i);
pt = this->Points->GetPoint(ptId);
if ( x[0] == pt[0] && x[1] == pt[1] && x[2] == pt[2] ) return ptId;
}
}
bucket->InsertNextId(this->InsertionPointId);
this->Points->InsertPoint(this->InsertionPointId,x);
return this->InsertionPointId++;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#pragma once
#include "streaming/messages/stream_message.hh"
namespace streaming {
namespace messages {
class session_failed_message : public stream_message {
#if 0
public static Serializer<SessionFailedMessage> serializer = new Serializer<SessionFailedMessage>()
{
public SessionFailedMessage deserialize(ReadableByteChannel in, int version, StreamSession session) throws IOException
{
return new SessionFailedMessage();
}
public void serialize(SessionFailedMessage message, DataOutputStreamAndChannel out, int version, StreamSession session) throws IOException {}
};
public SessionFailedMessage()
{
super(Type.SESSION_FAILED);
}
@Override
public String toString()
{
return "Session Failed";
}
#endif
public:
void serialize(bytes::iterator& out) const {
}
static session_failed_message deserialize(bytes_view& v) {
return session_failed_message();
}
size_t serialized_size() const {
return 0;
}
};
} // namespace messages
} // namespace streaming
<commit_msg>streaming: Add message type for session_failed_message<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#pragma once
#include "streaming/messages/stream_message.hh"
namespace streaming {
namespace messages {
class session_failed_message : public stream_message {
#if 0
public static Serializer<SessionFailedMessage> serializer = new Serializer<SessionFailedMessage>()
{
public SessionFailedMessage deserialize(ReadableByteChannel in, int version, StreamSession session) throws IOException
{
return new SessionFailedMessage();
}
public void serialize(SessionFailedMessage message, DataOutputStreamAndChannel out, int version, StreamSession session) throws IOException {}
};
#endif
session_failed_message() : stream_message(stream_message::Type::SESSION_FAILED) { }
#if 0
@Override
public String toString()
{
return "Session Failed";
}
#endif
public:
void serialize(bytes::iterator& out) const {
}
static session_failed_message deserialize(bytes_view& v) {
return session_failed_message();
}
size_t serialized_size() const {
return 0;
}
};
} // namespace messages
} // namespace streaming
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: resourceprovider.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: tra $ $Date: 2001-06-26 18:36:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif
#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#include "filedlghelper.hrc"
//------------------------------------------------------------
//
//------------------------------------------------------------
#define RES_NAME sfx
// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100
//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------
using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;
//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------
struct _Entry
{
sal_Int32 ctrlId;
sal_Int16 resId;
};
_Entry CtrlIdToResIdTable[] = {
{ CHECKBOX_AUTOEXTENSION, STR_CB_AUTO_EXTENSION },
{ CHECKBOX_PASSWORD, STR_CB_PASSWORD },
{ CHECKBOX_FILTEROPTIONS, STR_CB_FILTER_OPTIONS },
{ CHECKBOX_READONLY, STR_CB_READONLY },
{ CHECKBOX_LINK, STR_CB_INSERT_AS_LINK },
{ CHECKBOX_PREVIEW, STR_CB_SHOW_PREVIEW },
{ PUSHBUTTON_PLAY, STR_PB_PLAY },
{ LISTBOX_VERSION + LB_LABEL_OFFSET, STR_LB_VERSION },
{ LISTBOX_TEMPLATE + LB_LABEL_OFFSET, STR_LB_TEMPLATES },
{ LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_LB_IMAGE_TEMPLATE },
{ CHECKBOX_SELECTION, STR_CB_SELECTION },
};
const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );
//------------------------------------------------------------
//
//------------------------------------------------------------
sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
sal_Int16 aResId = -1;
for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
{
if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
{
aResId = CtrlIdToResIdTable[i].resId;
break;
}
}
return aResId;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
class CResourceProvider_Impl
{
public:
//-------------------------------------
//
//-------------------------------------
CResourceProvider_Impl( )
{
m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
}
//-------------------------------------
//
//-------------------------------------
~CResourceProvider_Impl( )
{
delete m_ResMgr;
}
//-------------------------------------
//
//-------------------------------------
OUString getResString( sal_Int16 aId )
{
String aResString;
OUString aResOUString;
try
{
OSL_ASSERT( m_ResMgr );
// translate the control id to a resource id
sal_Int16 aResId = CtrlIdToResId( aId );
if ( aResId > -1 )
{
aResString = String( ResId( aResId, m_ResMgr ) );
aResOUString = OUString( aResString );
// filter ~
#pragma message( "#########################" )
#pragma message( "implement filter ~" )
#pragma message( "#########################" )
}
}
catch(...)
{
}
return aResOUString;
}
public:
ResMgr* m_ResMgr;
};
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::CResourceProvider( ) :
m_pImpl( new CResourceProvider_Impl() )
{
}
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::~CResourceProvider( )
{
delete m_pImpl;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
OUString CResourceProvider::getResString( sal_Int32 aId )
{
return m_pImpl->getResString( aId );
}<commit_msg>#86986#removing tilde signes from control labels<commit_after>/*************************************************************************
*
* $RCSfile: resourceprovider.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: tra $ $Date: 2001-06-27 07:16:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif
#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#include "filedlghelper.hrc"
//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------
using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;
//------------------------------------------------------------
//
//------------------------------------------------------------
#define RES_NAME sfx
// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100
const rtl::OUString TILDE = OUString::createFromAscii( "~" );
const sal_Unicode TILDE_SIGN = L'~';
//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------
struct _Entry
{
sal_Int32 ctrlId;
sal_Int16 resId;
};
_Entry CtrlIdToResIdTable[] = {
{ CHECKBOX_AUTOEXTENSION, STR_CB_AUTO_EXTENSION },
{ CHECKBOX_PASSWORD, STR_CB_PASSWORD },
{ CHECKBOX_FILTEROPTIONS, STR_CB_FILTER_OPTIONS },
{ CHECKBOX_READONLY, STR_CB_READONLY },
{ CHECKBOX_LINK, STR_CB_INSERT_AS_LINK },
{ CHECKBOX_PREVIEW, STR_CB_SHOW_PREVIEW },
{ PUSHBUTTON_PLAY, STR_PB_PLAY },
{ LISTBOX_VERSION + LB_LABEL_OFFSET, STR_LB_VERSION },
{ LISTBOX_TEMPLATE + LB_LABEL_OFFSET, STR_LB_TEMPLATES },
{ LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_LB_IMAGE_TEMPLATE },
{ CHECKBOX_SELECTION, STR_CB_SELECTION },
};
const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );
//------------------------------------------------------------
//
//------------------------------------------------------------
sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
sal_Int16 aResId = -1;
for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
{
if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
{
aResId = CtrlIdToResIdTable[i].resId;
break;
}
}
return aResId;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
class CResourceProvider_Impl
{
public:
//-------------------------------------
//
//-------------------------------------
CResourceProvider_Impl( )
{
m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
}
//-------------------------------------
//
//-------------------------------------
~CResourceProvider_Impl( )
{
delete m_ResMgr;
}
//-------------------------------------
//
//-------------------------------------
OUString getResString( sal_Int16 aId )
{
String aResString;
OUString aResOUString;
try
{
OSL_ASSERT( m_ResMgr );
// translate the control id to a resource id
sal_Int16 aResId = CtrlIdToResId( aId );
if ( aResId > -1 )
{
aResString = String( ResId( aResId, m_ResMgr ) );
aResOUString = OUString( aResString );
// remove '~' signs, if there are two '~' signs
// in a row we remove only one of them
if ( aResOUString.indexOf( TILDE ) > -1 )
{
sal_Int32 nStrLen = aResOUString.getLength( );
rtl::OUStringBuffer aBuffer( nStrLen );
sal_Int32 i = 0;
const sal_Unicode* pPos = aResOUString.getStr( );
const sal_Unicode* pNext = aResOUString.getStr( ) + 1;
const sal_Unicode* pEnd = aResOUString.getStr( ) + nStrLen;
while( pPos < pEnd )
{
// we insert the next character only if the current character
// in not a '~' or the following character is also a '~'
if ( (*pPos != TILDE_SIGN) ||
((*pPos == TILDE_SIGN) && (pNext < pEnd) && (*pNext == TILDE_SIGN)) )
{
aBuffer.insert( i, *pPos );
i++;
}
pPos++;
pNext++;
}
aResOUString = aBuffer.makeStringAndClear( );
}
}
}
catch(...)
{
}
return aResOUString;
}
public:
ResMgr* m_ResMgr;
};
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::CResourceProvider( ) :
m_pImpl( new CResourceProvider_Impl() )
{
}
//------------------------------------------------------------
//
//------------------------------------------------------------
CResourceProvider::~CResourceProvider( )
{
delete m_pImpl;
}
//------------------------------------------------------------
//
//------------------------------------------------------------
OUString CResourceProvider::getResString( sal_Int32 aId )
{
return m_pImpl->getResString( aId );
}<|endoftext|>
|
<commit_before>#include "DynamicPacker.h"
#include "ShaderMgr.h"
#include "common/Exception.h"
#include "common/Vector.h"
#include "common/config.h"
#include "common/SettingData.h"
#include "dataset/TPNode.h"
#include "render/PrimitiveDraw.h"
#include "render/style_config.h"
#include <gl/glew.h>
#include <wx/wx.h>
// debug
#include <dtex.h>
namespace d2d
{
DynamicPacker::DynamicPacker(int width, int height, int padding, int extrude)
: m_width(width)
, m_height(height)
, m_padding(padding)
, m_extrude(extrude)
{
//initOpenGLExtensions();
InitTexture();
InitFBO();
InitRoot();
}
DynamicPacker::~DynamicPacker()
{
glDeleteTextures(1, &m_tex);
glDeleteFramebuffersEXT(1, &m_fbo);
delete m_root;
}
void DynamicPacker::ReloadTexture()
{
wxLogDebug(_T("DynamicPacker ReloadTexture"));
InitTexture(m_tex);
InitFBO(m_fbo);
ReloadPixels();
}
void DynamicPacker::DebugDrawStatic() const
{
ShaderMgr* shader = ShaderMgr::Instance();
shader->SetFBO(0);
shader->sprite();
shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));
float vb[16];
vb[0] = 0, vb[1] = 0;
vb[2] = 0, vb[3] = 0;
vb[4] = 0, vb[5] = 1;
vb[6] = 0, vb[7] = 1;
vb[8] = 1, vb[9] = 1;
vb[10] = 1, vb[11] = 1;
vb[12] = 1, vb[13] = 0;
vb[14] = 1, vb[15] = 0;
ShaderMgr::Instance()->Draw(vb, m_tex);
}
void DynamicPacker::DebugDraw() const
{
const int EDGE = 1024;
Vector vertices[4];
vertices[0].set(0, 0);
vertices[1].set(0, EDGE);
vertices[2].set(EDGE, EDGE);
vertices[3].set(EDGE, 0);
ShaderMgr* shader = ShaderMgr::Instance();
shader->sprite();
shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));
shader->SetSpriteColorTrans(Colorf(1, 0, 0, 0), Colorf(0, 1, 0, 0), Colorf(0, 0, 1, 0));
float vb[16];
vb[0] = vertices[0].x, vb[1] = vertices[0].y;
vb[2] = 0, vb[3] = 0;
vb[4] = vertices[1].x, vb[5] = vertices[1].y;
vb[6] = 0, vb[7] = 1;
vb[8] = vertices[2].x, vb[9] = vertices[2].y;
vb[10] = 1, vb[11] = 1;
vb[12] = vertices[3].x, vb[13] = vertices[3].y;
vb[14] = 1, vb[15] = 0;
if (dtex_cg* cg = dtexf_get_cg()) {
int id = dtex_cg_get_texid(cg);
// int id = m_tex;
shader->Draw(vb, id);
}
PrimitiveDraw::rect(Vector(0, 0), Vector(EDGE, EDGE), LIGHT_RED_THIN_LINE);
}
void DynamicPacker::InitTexture(int tex_id)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
if (tex_id == 0) {
glGenTextures(1, (GLuint*)&tex_id);
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_id);
if (Config::Instance()->GetSettings().linear_filter) {
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
} else {
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
}
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)m_width, (GLsizei)m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// uint8_t* empty_data = new uint8_t[m_width*m_height*4];
// memset(empty_data, 0, m_width*m_height*4);
// glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)m_width, (GLsizei)m_height, GL_RGBA, GL_UNSIGNED_BYTE, &empty_data[0]);
// delete[] empty_data;
m_tex = tex_id;
// ClearTexture();
}
void DynamicPacker::InitFBO(int fbo_id)
{
ShaderMgr* shader = ShaderMgr::Instance();
if (fbo_id == 0) {
glGenFramebuffersEXT(1, (GLuint*)&fbo_id);
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_id);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_tex, 0);
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
throw Exception("Create FBO error: %d", status);
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShaderMgr::Instance()->GetFboID());
m_fbo = fbo_id;
}
void DynamicPacker::InitRoot()
{
m_root = new TPNode(m_width, m_height);
TPNode* c = new TPNode(m_width, m_height);
m_root->SetChild(c);
}
void DynamicPacker::ClearTexture()
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
glBindTexture(GL_TEXTURE_2D, m_tex);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
ShaderMgr* shader = ShaderMgr::Instance();
glBindTexture(GL_TEXTURE_2D, shader->GetTexID());
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, shader->GetFboID());
}
}<commit_msg>debug draw<commit_after>#include "DynamicPacker.h"
#include "ShaderMgr.h"
#include "common/Exception.h"
#include "common/Vector.h"
#include "common/config.h"
#include "common/SettingData.h"
#include "dataset/TPNode.h"
#include "render/PrimitiveDraw.h"
#include "render/style_config.h"
#include <gl/glew.h>
#include <wx/wx.h>
// debug
#include <dtex.h>
namespace d2d
{
DynamicPacker::DynamicPacker(int width, int height, int padding, int extrude)
: m_width(width)
, m_height(height)
, m_padding(padding)
, m_extrude(extrude)
{
//initOpenGLExtensions();
InitTexture();
InitFBO();
InitRoot();
}
DynamicPacker::~DynamicPacker()
{
glDeleteTextures(1, &m_tex);
glDeleteFramebuffersEXT(1, &m_fbo);
delete m_root;
}
void DynamicPacker::ReloadTexture()
{
wxLogDebug(_T("DynamicPacker ReloadTexture"));
InitTexture(m_tex);
InitFBO(m_fbo);
ReloadPixels();
}
void DynamicPacker::DebugDrawStatic() const
{
ShaderMgr* shader = ShaderMgr::Instance();
shader->SetFBO(0);
shader->sprite();
shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));
float vb[16];
vb[0] = 0, vb[1] = 0;
vb[2] = 0, vb[3] = 0;
vb[4] = 0, vb[5] = 1;
vb[6] = 0, vb[7] = 1;
vb[8] = 1, vb[9] = 1;
vb[10] = 1, vb[11] = 1;
vb[12] = 1, vb[13] = 0;
vb[14] = 1, vb[15] = 0;
ShaderMgr::Instance()->Draw(vb, m_tex);
}
void DynamicPacker::DebugDraw() const
{
const int EDGE = 1024;
Vector vertices[4];
vertices[0].set(0, 0);
vertices[1].set(0, EDGE);
vertices[2].set(EDGE, EDGE);
vertices[3].set(EDGE, 0);
ShaderMgr* shader = ShaderMgr::Instance();
shader->sprite();
shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));
shader->SetSpriteColorTrans(Colorf(1, 0, 0, 0), Colorf(0, 1, 0, 0), Colorf(0, 0, 1, 0));
float vb[16];
vb[0] = vertices[0].x, vb[1] = vertices[0].y;
vb[2] = 0, vb[3] = 0;
vb[4] = vertices[1].x, vb[5] = vertices[1].y;
vb[6] = 0, vb[7] = 1;
vb[8] = vertices[2].x, vb[9] = vertices[2].y;
vb[10] = 1, vb[11] = 1;
vb[12] = vertices[3].x, vb[13] = vertices[3].y;
vb[14] = 1, vb[15] = 0;
if (dtex_cg* cg = dtexf_get_cg()) {
int id = dtex_cg_get_texid(cg);
shader->Draw(vb, id);
}
// int id = m_tex;
// shader->Draw(vb, id);
PrimitiveDraw::rect(Vector(0, 0), Vector(EDGE, EDGE), LIGHT_RED_THIN_LINE);
}
void DynamicPacker::InitTexture(int tex_id)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
if (tex_id == 0) {
glGenTextures(1, (GLuint*)&tex_id);
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_id);
if (Config::Instance()->GetSettings().linear_filter) {
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
} else {
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
}
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)m_width, (GLsizei)m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// uint8_t* empty_data = new uint8_t[m_width*m_height*4];
// memset(empty_data, 0, m_width*m_height*4);
// glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)m_width, (GLsizei)m_height, GL_RGBA, GL_UNSIGNED_BYTE, &empty_data[0]);
// delete[] empty_data;
m_tex = tex_id;
// ClearTexture();
}
void DynamicPacker::InitFBO(int fbo_id)
{
ShaderMgr* shader = ShaderMgr::Instance();
if (fbo_id == 0) {
glGenFramebuffersEXT(1, (GLuint*)&fbo_id);
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_id);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_tex, 0);
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
throw Exception("Create FBO error: %d", status);
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShaderMgr::Instance()->GetFboID());
m_fbo = fbo_id;
}
void DynamicPacker::InitRoot()
{
m_root = new TPNode(m_width, m_height);
TPNode* c = new TPNode(m_width, m_height);
m_root->SetChild(c);
}
void DynamicPacker::ClearTexture()
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
glBindTexture(GL_TEXTURE_2D, m_tex);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
ShaderMgr* shader = ShaderMgr::Instance();
glBindTexture(GL_TEXTURE_2D, shader->GetTexID());
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, shader->GetFboID());
}
}<|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/python/grappler/model_analyzer.h"
#include <iomanip>
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/grappler/grappler_item.h"
namespace tensorflow {
namespace grappler {
ModelAnalyzer::ModelAnalyzer(const GrapplerItem& item) : item_(item) {}
Status ModelAnalyzer::GenerateReport(std::ostream& os) {
GraphProperties properties(item_);
TF_RETURN_IF_ERROR(properties.InferStatically());
for (const auto& node : item_.MainOpsFanin()) {
PrintNodeInfo(node, properties, os);
}
for (const auto& node : item_.EnqueueOpsFanin()) {
PrintNodeInfo(node, properties, os);
}
return Status::OK();
}
void ModelAnalyzer::PrintNodeInfo(const NodeDef* node,
const GraphProperties& properties,
std::ostream& os) const {
os << node->name() << " [" << node->op() << "]" << std::endl;
if (properties.HasOutputProperties(node->name())) {
std::vector<OpInfo::TensorProperties> props =
properties.GetOutputProperties(node->name());
for (int i = 0; i < props.size(); ++i) {
const OpInfo::TensorProperties& prop = props[i];
os << "\t"
<< "output " << i << " (" << DataTypeString(prop.dtype())
<< ") has shape ";
if (prop.shape().unknown_rank()) {
os << "?";
} else {
os << "[";
for (int i = 0; i < prop.shape().dim_size(); ++i) {
if (i > 0) {
os << ", ";
}
if (prop.shape().dim(i).size() < 0) {
os << "?";
} else {
os << prop.shape().dim(i).size();
}
}
os << "]";
}
os << std::endl;
}
}
}
} // end namespace grappler
} // end namespace tensorflow
<commit_msg>Improved the reporting of dimensions<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/python/grappler/model_analyzer.h"
#include <iomanip>
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/grappler/grappler_item.h"
namespace tensorflow {
namespace grappler {
ModelAnalyzer::ModelAnalyzer(const GrapplerItem& item) : item_(item) {}
Status ModelAnalyzer::GenerateReport(std::ostream& os) {
GraphProperties properties(item_);
TF_RETURN_IF_ERROR(properties.InferStatically());
for (const auto& node : item_.MainOpsFanin()) {
PrintNodeInfo(node, properties, os);
}
for (const auto& node : item_.EnqueueOpsFanin()) {
PrintNodeInfo(node, properties, os);
}
return Status::OK();
}
void ModelAnalyzer::PrintNodeInfo(const NodeDef* node,
const GraphProperties& properties,
std::ostream& os) const {
os << node->name() << " [" << node->op() << "]" << std::endl;
if (properties.HasOutputProperties(node->name())) {
std::vector<OpInfo::TensorProperties> props =
properties.GetOutputProperties(node->name());
for (int i = 0; i < props.size(); ++i) {
const OpInfo::TensorProperties& prop = props[i];
os << "\t"
<< "output " << i << " (" << DataTypeString(prop.dtype())
<< ") has shape ";
if (prop.shape().unknown_rank()) {
os << "?";
} else {
os << "[";
for (int i = 0; i < prop.shape().dim_size(); ++i) {
if (i > 0) {
os << ", ";
}
if (prop.shape().dim(i).size() >= 0) {
// Print the actual dimension.
os << prop.shape().dim(i).size();
} else if (prop.shape().dim(i).size() == -1) {
// We don't know anything about the dimension.
os << "?";
} else {
// Symbolic dimension.
os << "x" << -prop.shape().dim(i).size();
}
}
os << "]";
}
os << std::endl;
}
}
}
} // end namespace grappler
} // end namespace tensorflow
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2014 - 2017)
// Rene Milk (2014, 2016 - 2017)
// Tobias Leibner (2014)
#ifndef DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
#define DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/dd/subdomains/grid.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
namespace Dune {
namespace GDT {
template <class LocalSpaceImp>
class BlockMapper;
namespace internal {
template <class LocalSpaceType>
class BlockMapperTraits
{
static_assert(is_space<LocalSpaceType>::value, "LocalSpaceType has to be derived from SpaceInterface!");
public:
typedef BlockMapper<LocalSpaceType> derived_type;
typedef typename LocalSpaceType::EntityType EntityType;
typedef std::vector<std::shared_ptr<const LocalSpaceType>> BackendType;
}; // class BlockMapperTraits
} // namespace internal
template <class LocalSpaceImp>
class BlockMapper : public MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>>
{
typedef MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>> BaseType;
typedef BlockMapper<LocalSpaceImp> ThisType;
public:
typedef internal::BlockMapperTraits<LocalSpaceImp> Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
typedef LocalSpaceImp LocalSpaceType;
typedef XT::Grid::DD::SubdomainGrid<XT::Grid::extract_grid_t<typename LocalSpaceType::GridLayerType>>
DdSubdomainsGridType;
private:
typedef typename DdSubdomainsGridType::GlobalGridPartType GridLayerType;
typedef typename DdSubdomainsGridType::EntityToSubdomainMapType EntityToSubdomainMapType;
template <class L, class E>
class Compute
{
static_assert(AlwaysFalse<L>::value, "Not implemented for this kind of entity (only codim 0)!");
};
template <class L>
class Compute<L, typename DdSubdomainsGridType::EntityType>
{
typedef typename DdSubdomainsGridType::EntityType Comdim0EntityType;
public:
static size_t numDofs(const ThisType& self, const Comdim0EntityType& entity)
{
const size_t block = find_block_of(self, entity);
if (self.backend()[block] == nullptr)
DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
return self.backend()[block]->mapper().numDofs(entity);
}
static void globalIndices(const ThisType& self, const Comdim0EntityType& entity, Dune::DynamicVector<size_t>& ret)
{
const size_t block = find_block_of(self, entity);
if (self.backend()[block] == nullptr)
DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
self.backend()[block]->mapper().globalIndices(entity, ret);
const size_t num_dofs = self.backend()[block]->mapper().numDofs(entity);
assert(ret.size() >= num_dofs);
for (size_t ii = 0; ii < num_dofs; ++ii)
ret[ii] += self.global_start_indices_[block];
}
static size_t mapToGlobal(const ThisType& self, const Comdim0EntityType& entity, const size_t& localIndex)
{
const size_t block = find_block_of(self, entity);
if (self.backend()[block] == nullptr)
DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
const size_t block_local_index = self.backend()[block]->mapper().mapToGlobal(entity, localIndex);
return self.global_start_indices_[block] + block_local_index;
}
private:
static size_t find_block_of(const ThisType& self, const Comdim0EntityType& entity)
{
const auto global_entity_index = self.global_grid_part_->indexSet().index(entity);
const auto result = self.entity_to_subdomain_map_->find(global_entity_index);
#ifndef NDEBUG
if (result == self.entity_to_subdomain_map_->end())
DUNE_THROW(XT::Common::Exceptions::internal_error,
"Entity " << global_entity_index
<< " of the global grid part was not found in the dd subdomain grid!");
#endif // NDEBUG
const size_t subdomain = result->second;
#ifndef NDEBUG
if (subdomain >= self.num_blocks_)
DUNE_THROW(XT::Common::Exceptions::internal_error,
"The DD subdomains grid is corrupted!\nIt reports Entity " << global_entity_index
<< " to be in subdomain "
<< subdomain
<< " while only having "
<< self.num_blocks_
<< " subdomains!");
#endif // NDEBUG
return subdomain;
} // ... find_block_of(...)
}; // class Compute< ..., EntityType >
public:
BlockMapper(const DdSubdomainsGridType& dd_grid,
const std::shared_ptr<GridLayerType> grid_layer,
const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces)
: global_grid_part_(grid_layer)
, entity_to_subdomain_map_(dd_grid.entityToSubdomainMap())
, local_spaces_(local_spaces)
, num_blocks_(local_spaces_->size())
, size_(0)
, max_num_dofs_(0)
{
if (local_spaces_->size() != dd_grid.size())
DUNE_THROW(XT::Common::Exceptions::shapes_do_not_match,
"You have to provide a local space for each subdomain of the DD subdomains grid!\n"
<< " Number of subdomains: "
<< dd_grid.size()
<< "\n"
<< " Number of local spaces given: "
<< local_spaces_->size());
for (size_t bb = 0; bb < num_blocks_; ++bb) {
if (backend()[bb] != nullptr) {
max_num_dofs_ = std::max(max_num_dofs_, backend()[bb]->mapper().maxNumDofs());
global_start_indices_.push_back(size_);
size_ += backend()[bb]->mapper().size();
} else {
global_start_indices_.push_back(size_);
}
}
} // BlockMapper(...)
BlockMapper(const ThisType& other) = default;
BlockMapper(ThisType&& source) = default;
ThisType& operator=(const ThisType& other) = delete;
ThisType& operator=(ThisType&& source) = delete;
size_t numBlocks() const
{
return num_blocks_;
}
size_t localSize(const size_t block) const
{
assert(block < num_blocks_);
return backend()[block]->mapper().size();
}
size_t mapToGlobal(const size_t block, const size_t localIndex) const
{
assert(block < num_blocks_);
return global_start_indices_[block] + localIndex;
}
const BackendType& backend() const
{
return *local_spaces_;
}
size_t size() const
{
return size_;
}
size_t maxNumDofs() const
{
return max_num_dofs_;
}
size_t numDofs(const EntityType& entity) const
{
return Compute<LocalSpaceType, EntityType>::numDofs(*this, entity);
}
void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
{
Compute<LocalSpaceType, EntityType>::globalIndices(*this, entity, ret);
}
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
return Compute<LocalSpaceType, EntityType>::mapToGlobal(*this, entity, localIndex);
}
private:
template <class L, class E>
friend class Compute;
const std::shared_ptr<GridLayerType> global_grid_part_;
const std::shared_ptr<const typename DdSubdomainsGridType::EntityToSubdomainMapType> entity_to_subdomain_map_;
const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces_;
size_t num_blocks_;
size_t size_;
size_t max_num_dofs_;
std::vector<size_t> global_start_indices_;
}; // class BlockMapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
<commit_msg>[spaces.mapper.block] do not hide convenience method from base<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2014 - 2017)
// Rene Milk (2014, 2016 - 2017)
// Tobias Leibner (2014)
#ifndef DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
#define DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/dd/subdomains/grid.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
namespace Dune {
namespace GDT {
template <class LocalSpaceImp>
class BlockMapper;
namespace internal {
template <class LocalSpaceType>
class BlockMapperTraits
{
static_assert(is_space<LocalSpaceType>::value, "LocalSpaceType has to be derived from SpaceInterface!");
public:
typedef BlockMapper<LocalSpaceType> derived_type;
typedef typename LocalSpaceType::EntityType EntityType;
typedef std::vector<std::shared_ptr<const LocalSpaceType>> BackendType;
}; // class BlockMapperTraits
} // namespace internal
template <class LocalSpaceImp>
class BlockMapper : public MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>>
{
typedef MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>> BaseType;
typedef BlockMapper<LocalSpaceImp> ThisType;
public:
typedef internal::BlockMapperTraits<LocalSpaceImp> Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
typedef LocalSpaceImp LocalSpaceType;
typedef XT::Grid::DD::SubdomainGrid<XT::Grid::extract_grid_t<typename LocalSpaceType::GridLayerType>>
DdSubdomainsGridType;
private:
typedef typename DdSubdomainsGridType::GlobalGridPartType GridLayerType;
typedef typename DdSubdomainsGridType::EntityToSubdomainMapType EntityToSubdomainMapType;
template <class L, class E>
class Compute
{
static_assert(AlwaysFalse<L>::value, "Not implemented for this kind of entity (only codim 0)!");
};
template <class L>
class Compute<L, typename DdSubdomainsGridType::EntityType>
{
typedef typename DdSubdomainsGridType::EntityType Comdim0EntityType;
public:
static size_t numDofs(const ThisType& self, const Comdim0EntityType& entity)
{
const size_t block = find_block_of(self, entity);
if (self.backend()[block] == nullptr)
DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
return self.backend()[block]->mapper().numDofs(entity);
}
static void globalIndices(const ThisType& self, const Comdim0EntityType& entity, Dune::DynamicVector<size_t>& ret)
{
const size_t block = find_block_of(self, entity);
if (self.backend()[block] == nullptr)
DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
self.backend()[block]->mapper().globalIndices(entity, ret);
const size_t num_dofs = self.backend()[block]->mapper().numDofs(entity);
assert(ret.size() >= num_dofs);
for (size_t ii = 0; ii < num_dofs; ++ii)
ret[ii] += self.global_start_indices_[block];
}
static size_t mapToGlobal(const ThisType& self, const Comdim0EntityType& entity, const size_t& localIndex)
{
const size_t block = find_block_of(self, entity);
if (self.backend()[block] == nullptr)
DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
const size_t block_local_index = self.backend()[block]->mapper().mapToGlobal(entity, localIndex);
return self.global_start_indices_[block] + block_local_index;
}
private:
static size_t find_block_of(const ThisType& self, const Comdim0EntityType& entity)
{
const auto global_entity_index = self.global_grid_part_->indexSet().index(entity);
const auto result = self.entity_to_subdomain_map_->find(global_entity_index);
#ifndef NDEBUG
if (result == self.entity_to_subdomain_map_->end())
DUNE_THROW(XT::Common::Exceptions::internal_error,
"Entity " << global_entity_index
<< " of the global grid part was not found in the dd subdomain grid!");
#endif // NDEBUG
const size_t subdomain = result->second;
#ifndef NDEBUG
if (subdomain >= self.num_blocks_)
DUNE_THROW(XT::Common::Exceptions::internal_error,
"The DD subdomains grid is corrupted!\nIt reports Entity " << global_entity_index
<< " to be in subdomain "
<< subdomain
<< " while only having "
<< self.num_blocks_
<< " subdomains!");
#endif // NDEBUG
return subdomain;
} // ... find_block_of(...)
}; // class Compute< ..., EntityType >
public:
BlockMapper(const DdSubdomainsGridType& dd_grid,
const std::shared_ptr<GridLayerType> grid_layer,
const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces)
: global_grid_part_(grid_layer)
, entity_to_subdomain_map_(dd_grid.entityToSubdomainMap())
, local_spaces_(local_spaces)
, num_blocks_(local_spaces_->size())
, size_(0)
, max_num_dofs_(0)
{
if (local_spaces_->size() != dd_grid.size())
DUNE_THROW(XT::Common::Exceptions::shapes_do_not_match,
"You have to provide a local space for each subdomain of the DD subdomains grid!\n"
<< " Number of subdomains: "
<< dd_grid.size()
<< "\n"
<< " Number of local spaces given: "
<< local_spaces_->size());
for (size_t bb = 0; bb < num_blocks_; ++bb) {
if (backend()[bb] != nullptr) {
max_num_dofs_ = std::max(max_num_dofs_, backend()[bb]->mapper().maxNumDofs());
global_start_indices_.push_back(size_);
size_ += backend()[bb]->mapper().size();
} else {
global_start_indices_.push_back(size_);
}
}
} // BlockMapper(...)
BlockMapper(const ThisType& other) = default;
BlockMapper(ThisType&& source) = default;
ThisType& operator=(const ThisType& other) = delete;
ThisType& operator=(ThisType&& source) = delete;
size_t numBlocks() const
{
return num_blocks_;
}
size_t localSize(const size_t block) const
{
assert(block < num_blocks_);
return backend()[block]->mapper().size();
}
size_t mapToGlobal(const size_t block, const size_t localIndex) const
{
assert(block < num_blocks_);
return global_start_indices_[block] + localIndex;
}
const BackendType& backend() const
{
return *local_spaces_;
}
size_t size() const
{
return size_;
}
size_t maxNumDofs() const
{
return max_num_dofs_;
}
size_t numDofs(const EntityType& entity) const
{
return Compute<LocalSpaceType, EntityType>::numDofs(*this, entity);
}
using BaseType::globalIndices;
void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
{
Compute<LocalSpaceType, EntityType>::globalIndices(*this, entity, ret);
}
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
return Compute<LocalSpaceType, EntityType>::mapToGlobal(*this, entity, localIndex);
}
private:
template <class L, class E>
friend class Compute;
const std::shared_ptr<GridLayerType> global_grid_part_;
const std::shared_ptr<const typename DdSubdomainsGridType::EntityToSubdomainMapType> entity_to_subdomain_map_;
const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces_;
size_t num_blocks_;
size_t size_;
size_t max_num_dofs_;
std::vector<size_t> global_start_indices_;
}; // class BlockMapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#include <type_traits>
#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>
#include <dune/stuff/common/disable_warnings.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/geometry/genericreferenceelements.hh>
#endif
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/exceptions.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
// forward, to allow for specialization
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class ContinuousLagrangeBase
{
static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!");
};
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim>
class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits>
{
typedef SpaceInterface<ImpTraits> BaseType;
typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType;
static constexpr RangeFieldImp compare_tolerance_ = 1e-13;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
virtual ~ContinuousLagrangeBase()
{
}
using BaseType::compute_pattern;
template <class G, class S>
PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
}
virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, this->tmp_basis_values_);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
local_vertices[jj] = local_vertex;
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points(...)
virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view()->indexSet().contains(entity));
// prepare
std::set<size_t> localDirichletDofs;
std::vector<DomainType> dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view()->iend(entity);
for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
// actual dirichlet intersections + process boundaries for parallel runs
if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
localDirichletDofs.insert(jj);
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs(...)
private:
template <class T, bool set_row>
void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
const size_t numRows = localDirichletDofs.size();
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.set_size(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows_);
other.mapper().globalIndices(entity, tmpMappedCols_);
size_t localRow = 0;
const RangeFieldType zero(0);
for (const size_t& localDirichletDofIndex : localDirichletDofs) {
ret.global_row(localRow) = tmpMappedRows_[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.global_col(jj) = tmpMappedCols_[jj];
if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
ret.value(localRow, jj) = set_row ? RangeFieldType(1) : RangeFieldType(0);
else
ret.value(localRow, jj) = zero;
}
++localRow;
}
} else {
ret.set_size(0, 0);
}
} // ... compute_local_constraints(..., Dirichlet< ..., true >)
public:
using BaseType::local_constraints;
template <bool set>
void local_constraints(const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, set>& ret) const
{
local_constraints(*this, entity, ret);
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const
{
compute_local_constraints(other, entity, ret);
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const
{
compute_local_constraints(other, entity, ret);
}
protected:
mutable Dune::DynamicVector<size_t> tmpMappedRows_;
mutable Dune::DynamicVector<size_t> tmpMappedCols_;
}; // class ContinuousLagrangeBase
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
<commit_msg>[spaces.cg.bsae] updated constraints<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#include <type_traits>
#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>
#include <dune/stuff/common/disable_warnings.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/geometry/genericreferenceelements.hh>
#endif
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/exceptions.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
// forward, to allow for specialization
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class ContinuousLagrangeBase
{
static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!");
};
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim>
class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits>
{
typedef SpaceInterface<ImpTraits> BaseType;
typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType;
static constexpr RangeFieldImp compare_tolerance_ = 1e-13;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
virtual ~ContinuousLagrangeBase()
{
}
using BaseType::compute_pattern;
template <class G, class S>
PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
}
virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, this->tmp_basis_values_);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
local_vertices[jj] = local_vertex;
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points(...)
virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view()->indexSet().contains(entity));
// prepare
std::set<size_t> localDirichletDofs;
std::vector<DomainType> dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view()->iend(entity);
for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
// actual dirichlet intersections + process boundaries for parallel runs
if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
localDirichletDofs.insert(jj);
++ones;
} else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs(...)
private:
template <class T, bool set_row>
void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
const size_t numRows = localDirichletDofs.size();
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.set_size(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows_);
other.mapper().globalIndices(entity, tmpMappedCols_);
size_t localRow = 0;
const RangeFieldType zero(0);
for (const size_t& localDirichletDofIndex : localDirichletDofs) {
ret.global_row(localRow) = tmpMappedRows_[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.global_col(jj) = tmpMappedCols_[jj];
if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
ret.value(localRow, jj) = set_row ? RangeFieldType(1) : RangeFieldType(0);
else
ret.value(localRow, jj) = zero;
}
++localRow;
}
} else {
ret.set_size(0, 0);
}
} // ... compute_local_constraints(..., Dirichlet< ..., true >)
public:
using BaseType::local_constraints;
template <class C, class R>
void local_constraints(const ThisType& /*other*/, const EntityType& /*entity*/,
ConstraintsInterface<C, R>& /*ret*/) const
{
static_assert(AlwaysFalse<C>::value, "Not implemented for arbitrary constraints!");
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const
{
compute_local_constraints(other, entity, ret);
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const
{
compute_local_constraints(other, entity, ret);
}
protected:
mutable Dune::DynamicVector<size_t> tmpMappedRows_;
mutable Dune::DynamicVector<size_t> tmpMappedCols_;
}; // class ContinuousLagrangeBase
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
<|endoftext|>
|
<commit_before>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "escher/shaders/material/material_shader.h"
#include "escher/shaders/glsl_generator.h"
namespace escher {
namespace {
constexpr char g_decls[] = R"GLSL(
#define BINDING_NONE 0
#define BINDING_CONSTANT 1
#define MASK_NONE 0
#define MASK_CIRCULAR 1
)GLSL";
constexpr char g_vertex_shader[] = R"GLSL(
attribute vec3 a_position;
uniform mat4 u_matrix;
#if MASK == MASK_CIRCULAR
attribute vec2 a_mask_uv;
varying vec2 v_mask_uv;
void mask() {
v_mask_uv = a_mask_uv;
}
#else
void mask() {}
#endif
void main() {
gl_Position = u_matrix * vec4(a_position, 1.0);
mask();
}
)GLSL";
constexpr char g_fragment_shader[] = R"GLSL(
precision mediump float;
#if COLOR_BINDING == BINDING_NONE
vec4 color() {
return vec4(0.0, 0.0, 0.0, 1.0); // should alpha be 0?
}
#elif COLOR_BINDING == BINDING_CONSTANT
uniform vec4 u_color;
vec4 color() {
return u_color;
}
#endif
#if MASK == MASK_CIRCULAR
varying vec2 v_mask_uv;
bool mask() {
return v_mask_uv.x * v_mask_uv.x + v_mask_uv.y * v_mask_uv.y <= 1.0;
}
#else
bool mask() { return true; }
#endif
void main() {
if (!mask()) discard; // FIXME(jeffbrown): inefficient!
gl_FragColor = color();
}
)GLSL";
void DefineBindingSymbol(GLSLGenerator& generator,
const std::string& symbol,
BindingType binding_type) {
switch (binding_type) {
case BindingType::kNone:
generator.DefineSymbol(symbol, "BINDING_NONE");
break;
case BindingType::kConstant:
generator.DefineSymbol(symbol, "BINDING_CONSTANT");
break;
}
}
void DefineMaskSymbol(GLSLGenerator& generator, Modifier::Mask mask) {
switch (mask) {
case Modifier::Mask::kNone:
generator.DefineSymbol("MASK", "MASK_NONE");
break;
case Modifier::Mask::kCircular:
generator.DefineSymbol("MASK", "MASK_CIRCULAR");
break;
}
}
} // namespace
MaterialShader::MaterialShader(const MaterialShaderDescriptor& descriptor)
: descriptor_(descriptor) {}
MaterialShader::~MaterialShader() {}
void MaterialShader::Use(const glm::mat4& matrix) const {
glUseProgram(program_.id());
glEnableVertexAttribArray(position_);
if (descriptor_.mask == Modifier::Mask::kCircular)
glEnableVertexAttribArray(mask_uv_);
glUniformMatrix4fv(matrix_, 1, GL_FALSE, &matrix[0][0]);
}
void MaterialShader::Bind(const Material& material,
const Modifier& modifier) const {
if (descriptor_.color_binding_type == BindingType::kConstant) {
const glm::vec4& color = material.color().constant_value();
glUniform4fv(color_, 1, &color[0]);
}
}
bool MaterialShader::Compile() {
std::string prologue = GeneratePrologue();
std::vector<std::string> vertex_shader_sources{g_decls, prologue,
g_vertex_shader};
std::vector<std::string> fragment_shader_sources{g_decls, prologue,
g_fragment_shader};
UniqueShader vertex_shader =
MakeUniqueShader(GL_VERTEX_SHADER, vertex_shader_sources);
UniqueShader fragment_shader =
MakeUniqueShader(GL_FRAGMENT_SHADER, fragment_shader_sources);
if (!vertex_shader || !fragment_shader)
return false;
program_ =
MakeUniqueProgram(std::move(vertex_shader), std::move(fragment_shader));
if (!program_)
return false;
matrix_ = glGetUniformLocation(program_.id(), "u_matrix");
ESCHER_DCHECK(matrix_ != -1);
if (descriptor_.color_binding_type == BindingType::kConstant) {
color_ = glGetUniformLocation(program_.id(), "u_color");
ESCHER_DCHECK(color_ != -1);
}
if (descriptor_.mask == Modifier::Mask::kCircular) {
mask_uv_ = glGetAttribLocation(program_.id(), "a_mask_uv");
ESCHER_DCHECK(mask_uv_ != -1);
}
return true;
}
std::string MaterialShader::GeneratePrologue() {
GLSLGenerator generator;
DefineBindingSymbol(generator, "COLOR_BINDING",
descriptor_.color_binding_type);
DefineMaskSymbol(generator, descriptor_.mask);
return generator.GenerateCode();
}
} // namespace escher
<commit_msg>Use dot() operator (#19)<commit_after>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "escher/shaders/material/material_shader.h"
#include "escher/shaders/glsl_generator.h"
namespace escher {
namespace {
constexpr char g_decls[] = R"GLSL(
#define BINDING_NONE 0
#define BINDING_CONSTANT 1
#define MASK_NONE 0
#define MASK_CIRCULAR 1
)GLSL";
constexpr char g_vertex_shader[] = R"GLSL(
attribute vec3 a_position;
uniform mat4 u_matrix;
#if MASK == MASK_CIRCULAR
attribute vec2 a_mask_uv;
varying vec2 v_mask_uv;
void mask() {
v_mask_uv = a_mask_uv;
}
#else
void mask() {}
#endif
void main() {
gl_Position = u_matrix * vec4(a_position, 1.0);
mask();
}
)GLSL";
constexpr char g_fragment_shader[] = R"GLSL(
precision mediump float;
#if COLOR_BINDING == BINDING_NONE
vec4 color() {
return vec4(0.0, 0.0, 0.0, 1.0); // should alpha be 0?
}
#elif COLOR_BINDING == BINDING_CONSTANT
uniform vec4 u_color;
vec4 color() {
return u_color;
}
#endif
#if MASK == MASK_CIRCULAR
varying vec2 v_mask_uv;
bool mask() {
return dot(v_mask_uv, v_mask_uv) <= 1.0;
}
#else
bool mask() { return true; }
#endif
void main() {
if (!mask()) discard; // FIXME(jeffbrown): inefficient!
gl_FragColor = color();
}
)GLSL";
void DefineBindingSymbol(GLSLGenerator& generator,
const std::string& symbol,
BindingType binding_type) {
switch (binding_type) {
case BindingType::kNone:
generator.DefineSymbol(symbol, "BINDING_NONE");
break;
case BindingType::kConstant:
generator.DefineSymbol(symbol, "BINDING_CONSTANT");
break;
}
}
void DefineMaskSymbol(GLSLGenerator& generator, Modifier::Mask mask) {
switch (mask) {
case Modifier::Mask::kNone:
generator.DefineSymbol("MASK", "MASK_NONE");
break;
case Modifier::Mask::kCircular:
generator.DefineSymbol("MASK", "MASK_CIRCULAR");
break;
}
}
} // namespace
MaterialShader::MaterialShader(const MaterialShaderDescriptor& descriptor)
: descriptor_(descriptor) {}
MaterialShader::~MaterialShader() {}
void MaterialShader::Use(const glm::mat4& matrix) const {
glUseProgram(program_.id());
glEnableVertexAttribArray(position_);
if (descriptor_.mask == Modifier::Mask::kCircular)
glEnableVertexAttribArray(mask_uv_);
glUniformMatrix4fv(matrix_, 1, GL_FALSE, &matrix[0][0]);
}
void MaterialShader::Bind(const Material& material,
const Modifier& modifier) const {
if (descriptor_.color_binding_type == BindingType::kConstant) {
const glm::vec4& color = material.color().constant_value();
glUniform4fv(color_, 1, &color[0]);
}
}
bool MaterialShader::Compile() {
std::string prologue = GeneratePrologue();
std::vector<std::string> vertex_shader_sources{g_decls, prologue,
g_vertex_shader};
std::vector<std::string> fragment_shader_sources{g_decls, prologue,
g_fragment_shader};
UniqueShader vertex_shader =
MakeUniqueShader(GL_VERTEX_SHADER, vertex_shader_sources);
UniqueShader fragment_shader =
MakeUniqueShader(GL_FRAGMENT_SHADER, fragment_shader_sources);
if (!vertex_shader || !fragment_shader)
return false;
program_ =
MakeUniqueProgram(std::move(vertex_shader), std::move(fragment_shader));
if (!program_)
return false;
matrix_ = glGetUniformLocation(program_.id(), "u_matrix");
ESCHER_DCHECK(matrix_ != -1);
if (descriptor_.color_binding_type == BindingType::kConstant) {
color_ = glGetUniformLocation(program_.id(), "u_color");
ESCHER_DCHECK(color_ != -1);
}
if (descriptor_.mask == Modifier::Mask::kCircular) {
mask_uv_ = glGetAttribLocation(program_.id(), "a_mask_uv");
ESCHER_DCHECK(mask_uv_ != -1);
}
return true;
}
std::string MaterialShader::GeneratePrologue() {
GLSLGenerator generator;
DefineBindingSymbol(generator, "COLOR_BINDING",
descriptor_.color_binding_type);
DefineMaskSymbol(generator, descriptor_.mask);
return generator.GenerateCode();
}
} // namespace escher
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#include <memory>
#include <type_traits>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/la/container/interface.hh>
#include <dune/gdt/space/interface.hh>
#include "local.hh"
namespace Dune {
namespace GDT {
template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
: public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ElementType>::value,
"Types do not match!");
typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainFieldType DomainFieldType;
typedef typename BaseType::DomainType DomainType;
static const unsigned int dimRange = BaseType::dimRange;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeFieldType RangeFieldType;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;
ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
const std::string nm = "dune.gdt.constdiscretefunction")
: space_(sp)
, vector_(vec)
, name_(nm)
{
assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
}
ConstDiscreteFunction(const ThisType& other)
: space_(other.space_)
, vector_(other.vector_)
, name_(other.name_)
{
}
ConstDiscreteFunction(ThisType&& source)
: space_(source.space_)
, vector_(source.vector_)
, name_(std::move(source.name_))
{
}
ThisType& operator=(const ThisType& other) = delete;
~ConstDiscreteFunction()
{
}
virtual ThisType* copy() const DS_OVERRIDE
{
return new ThisType(*this);
}
virtual std::string name() const DS_OVERRIDE
{
return name_;
}
const SpaceType& space() const
{
return space_;
}
const VectorType& vector() const
{
return vector_;
}
ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
{
assert(space_.gridPart()->indexSet().contains(entity));
return ConstLocalDiscreteFunctionType(space_, vector_, entity);
}
virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE
{
return std::unique_ptr<ConstLocalDiscreteFunctionType>(
new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
}
void visualize(const std::string filename) const
{
typedef typename SpaceType::GridPartType::GridViewType GridViewType;
if (filename.empty())
DUNE_THROW(RangeError, "Empty filename given!");
auto adapter = std::make_shared<Stuff::Function::VisualizationAdapter<GridViewType, dimRange>>(*this);
VTKWriter<GridViewType> vtk_writer(space_.gridPart()->gridView(), VTK::nonconforming);
vtk_writer.addVertexData(adapter);
vtk_writer.write(filename);
} // ... visualize(...)
protected:
const SpaceType& space_;
private:
const VectorType& vector_;
const std::string name_;
}; // class ConstDiscreteFunction
template <class SpaceImp, class VectorImp>
class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;
DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
: BaseType(sp, vec, nm)
, vector_(vec)
{
}
DiscreteFunction(const ThisType& other)
: BaseType(other)
, vector_(other.vector_)
{
}
DiscreteFunction(ThisType&& source)
: BaseType(std::move(source))
, vector_(source.vector_)
{
}
ThisType& operator=(const ThisType& other) = delete;
~DiscreteFunction()
{
}
virtual ThisType* copy() const DS_OVERRIDE
{
return new ThisType(*this);
}
VectorType& vector()
{
return vector_;
}
LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
{
assert(space_.gridPart()->indexSet().contains(entity));
return LocalDiscreteFunctionType(space_, vector_, entity);
}
private:
using BaseType::space_;
VectorType& vector_;
}; // class DiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[discretefunction.default] use SubsamplingVTKWriter<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#include <memory>
#include <type_traits>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
#include <dune/grid/io/file/vtk.hh>
#include <dune/stuff/la/container/interface.hh>
#include <dune/gdt/space/interface.hh>
#include "local.hh"
namespace Dune {
namespace GDT {
template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
: public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ElementType>::value,
"Types do not match!");
typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainFieldType DomainFieldType;
typedef typename BaseType::DomainType DomainType;
static const unsigned int dimRange = BaseType::dimRange;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeFieldType RangeFieldType;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;
ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
const std::string nm = "dune.gdt.constdiscretefunction")
: space_(sp)
, vector_(vec)
, name_(nm)
{
assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
}
ConstDiscreteFunction(const ThisType& other)
: space_(other.space_)
, vector_(other.vector_)
, name_(other.name_)
{
}
ConstDiscreteFunction(ThisType&& source)
: space_(source.space_)
, vector_(source.vector_)
, name_(std::move(source.name_))
{
}
ThisType& operator=(const ThisType& other) = delete;
~ConstDiscreteFunction()
{
}
virtual ThisType* copy() const DS_OVERRIDE
{
return new ThisType(*this);
}
virtual std::string name() const DS_OVERRIDE
{
return name_;
}
const SpaceType& space() const
{
return space_;
}
const VectorType& vector() const
{
return vector_;
}
ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
{
assert(space_.gridPart()->indexSet().contains(entity));
return ConstLocalDiscreteFunctionType(space_, vector_, entity);
}
virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE
{
return std::unique_ptr<ConstLocalDiscreteFunctionType>(
new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
}
void visualize(const std::string filename) const
{
typedef typename SpaceType::GridPartType::GridViewType GridViewType;
if (filename.empty())
DUNE_THROW(RangeError, "Empty filename given!");
auto adapter = std::make_shared<Stuff::Function::VisualizationAdapter<GridViewType, dimRange>>(*this);
SubsamplingVTKWriter<GridViewType> vtk_writer(space_.gridPart()->gridView(), VTK::nonconforming);
vtk_writer.addVertexData(adapter);
vtk_writer.write(filename);
} // ... visualize(...)
protected:
const SpaceType& space_;
private:
const VectorType& vector_;
const std::string name_;
}; // class ConstDiscreteFunction
template <class SpaceImp, class VectorImp>
class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;
DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
: BaseType(sp, vec, nm)
, vector_(vec)
{
}
DiscreteFunction(const ThisType& other)
: BaseType(other)
, vector_(other.vector_)
{
}
DiscreteFunction(ThisType&& source)
: BaseType(std::move(source))
, vector_(source.vector_)
{
}
ThisType& operator=(const ThisType& other) = delete;
~DiscreteFunction()
{
}
virtual ThisType* copy() const DS_OVERRIDE
{
return new ThisType(*this);
}
VectorType& vector()
{
return vector_;
}
LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
{
assert(space_.gridPart()->indexSet().contains(entity));
return LocalDiscreteFunctionType(space_, vector_, entity);
}
private:
using BaseType::space_;
VectorType& vector_;
}; // class DiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#include <memory>
#include <type_traits>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
#include <dune/grid/io/file/vtk.hh>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/gdt/spaces/interface.hh>
#include "local.hh"
namespace Dune {
namespace GDT {
template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
: public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
static_assert(is_space<SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!");
static_assert(Stuff::LA::is_vector<VectorImp>::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
"Types do not match!");
typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;
ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec, const std::string nm = "gdt.constdiscretefunction")
: space_(sp)
, vector_(vec)
, name_(nm)
{
assert(vector_.size() == space_->mapper().size() && "Given vector has wrong size!");
}
ConstDiscreteFunction(const ThisType& other)
: space_(other.space())
, vector_(other.vector_)
, name_(other.name_)
{
}
ConstDiscreteFunction(ThisType&& source)
: space_(source.space())
, vector_(source.vector_)
, name_(source.name_)
{
}
virtual ~ConstDiscreteFunction()
{
}
ThisType& operator=(const ThisType& other) = delete;
virtual ThisType* copy() const override
{
return new ThisType(*this);
}
virtual std::string name() const override
{
return name_;
}
const SpaceType& space() const
{
return *space_;
}
const VectorType& vector() const
{
return vector_;
}
std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function(const EntityType& entity) const
{
assert(space_->grid_view().indexSet().contains(entity));
return DSC::make_unique<ConstLocalDiscreteFunctionType>(*space_, vector_, entity);
}
virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const override
{
return local_discrete_function(entity);
}
void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1),
VTK::OutputType vtk_output_type = VTK::appendedraw) const
{
BaseType::template visualize<typename SpaceType::GridViewType>(
space().grid_view(), filename, subsampling, vtk_output_type);
} // ... visualize(...)
bool dofs_valid() const
{
return vector().valid();
}
protected:
const DS::PerThreadValue<SpaceType> space_;
private:
const VectorType& vector_;
const std::string name_;
}; // class ConstDiscreteFunction
template <class SpaceImp, class VectorImp>
class DiscreteFunction : Stuff::Common::StorageProvider<VectorImp>, public ConstDiscreteFunction<SpaceImp, VectorImp>
{
typedef Stuff::Common::StorageProvider<VectorImp> VectorProviderBaseType;
typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;
DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "gdt.discretefunction")
: VectorProviderBaseType(vec)
, BaseType(sp, VectorProviderBaseType::storage_access(), nm)
{
}
DiscreteFunction(const SpaceType& sp, VectorType&& vec, const std::string nm = "gdt.discretefunction")
: VectorProviderBaseType(vec)
, BaseType(sp, VectorProviderBaseType::storage_access(), nm)
{
}
DiscreteFunction(const SpaceType& sp, const std::string nm = "gdt.discretefunction")
: VectorProviderBaseType(new VectorType(sp.mapper().size()))
, BaseType(sp, VectorProviderBaseType::storage_access(), nm)
{
}
// manual copy ctor needed bc. of the storage provider
DiscreteFunction(const ThisType& other)
: VectorProviderBaseType(new VectorType(other.vector()))
, BaseType(other.space(), VectorProviderBaseType::storage_access(), other.name())
{
}
// manual move ctor needed bc. of the storage provider
DiscreteFunction(ThisType&& source)
: VectorProviderBaseType(new VectorType(source.vector()))
, BaseType(source.space(), VectorProviderBaseType::storage_access(), source.name())
{
}
virtual ~DiscreteFunction()
{
}
ThisType& operator=(const ThisType& other) = delete;
virtual ThisType* copy() const override
{
return new ThisType(*this);
}
using BaseType::vector;
VectorType& vector()
{
return this->storage_access();
}
using BaseType::local_discrete_function;
std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function(const EntityType& entity)
{
assert(space_->grid_view().indexSet().contains(entity));
return DSC::make_unique<LocalDiscreteFunctionType>(*space_, this->storage_access(), entity);
}
private:
using BaseType::space_;
}; // class DiscreteFunction
template <class SpaceType, class VectorType>
ConstDiscreteFunction<SpaceType, VectorType>
make_const_discrete_function(const SpaceType& space, const VectorType& vector,
const std::string nm = "gdt.constdiscretefunction")
{
return ConstDiscreteFunction<SpaceType, VectorType>(space, vector, nm);
}
template <class SpaceType, class VectorType>
DiscreteFunction<SpaceType, VectorType> make_discrete_function(const SpaceType& space, VectorType& vector,
const std::string nm = "gdt.discretefunction")
{
return DiscreteFunction<SpaceType, VectorType>(space, vector, nm);
}
template <class VectorType, class SpaceType>
DiscreteFunction<SpaceType, VectorType> make_discrete_function(const SpaceType& space,
const std::string nm = "gdt.discretefunction")
{
return DiscreteFunction<SpaceType, VectorType>(space, nm);
}
namespace internal {
template <class D>
struct is_const_discrete_function_helper
{
DSC_has_typedef_initialize_once(SpaceType) DSC_has_typedef_initialize_once(VectorType)
static const bool is_candidate = DSC_has_typedef(SpaceType)<D>::value && DSC_has_typedef(SpaceType)<D>::value;
};
} // namespace internal
template <class D, bool candidate = internal::is_const_discrete_function_helper<D>::is_candidate>
struct is_const_discrete_function
: public std::is_base_of<ConstDiscreteFunction<typename D::SpaceType, typename D::VectorType>, D>
{
};
template <class D>
struct is_const_discrete_function<D, false> : public std::false_type
{
};
template <class D, bool candidate = internal::is_const_discrete_function_helper<D>::is_candidate>
struct is_discrete_function : public std::is_base_of<DiscreteFunction<typename D::SpaceType, typename D::VectorType>, D>
{
};
template <class D>
struct is_discrete_function<D, false> : public std::false_type
{
};
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[discretefunction.default] minor update and a little docu<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#include <memory>
#include <type_traits>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>
#include <dune/grid/io/file/vtk.hh>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/gdt/spaces/interface.hh>
#include "local.hh"
namespace Dune {
namespace GDT {
template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
: public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
static_assert(is_space<SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!");
static_assert(Stuff::LA::is_vector<VectorImp>::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
"Types do not match!");
typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;
ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec, const std::string nm = "gdt.constdiscretefunction")
: space_(sp)
, vector_(vec)
, name_(nm)
{
assert(vector_.size() == space_->mapper().size() && "Given vector has wrong size!");
}
ConstDiscreteFunction(const ThisType& other)
: space_(other.space())
, vector_(other.vector_)
, name_(other.name_)
{
}
ConstDiscreteFunction(ThisType&& source)
: space_(source.space())
, vector_(source.vector_)
, name_(source.name_)
{
}
virtual ~ConstDiscreteFunction()
{
}
ThisType& operator=(const ThisType& other) = delete;
virtual ThisType* copy() const override
{
return new ThisType(*this);
}
virtual std::string name() const override
{
return name_;
}
const SpaceType& space() const
{
return *space_;
}
const VectorType& vector() const
{
return vector_;
}
std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function(const EntityType& entity) const
{
assert(space_->grid_view().indexSet().contains(entity));
return DSC::make_unique<ConstLocalDiscreteFunctionType>(*space_, vector_, entity);
}
virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const override
{
return local_discrete_function(entity);
}
void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1),
const VTK::OutputType vtk_output_type = VTK::appendedraw) const
{
BaseType::template visualize<typename SpaceType::GridViewType>(
space().grid_view(), filename, subsampling, vtk_output_type);
} // ... visualize(...)
bool dofs_valid() const
{
return vector().valid();
}
protected:
const DS::PerThreadValue<SpaceType> space_;
private:
const VectorType& vector_;
const std::string name_;
}; // class ConstDiscreteFunction
template <class SpaceImp, class VectorImp>
class DiscreteFunction : Stuff::Common::StorageProvider<VectorImp>, public ConstDiscreteFunction<SpaceImp, VectorImp>
{
typedef Stuff::Common::StorageProvider<VectorImp> VectorProviderBaseType;
typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;
DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "gdt.discretefunction")
: VectorProviderBaseType(vec)
, BaseType(sp, VectorProviderBaseType::storage_access(), nm)
{
}
DiscreteFunction(const SpaceType& sp, VectorType&& vec, const std::string nm = "gdt.discretefunction")
: VectorProviderBaseType(vec)
, BaseType(sp, VectorProviderBaseType::storage_access(), nm)
{
}
DiscreteFunction(const SpaceType& sp, const std::string nm = "gdt.discretefunction")
: VectorProviderBaseType(new VectorType(sp.mapper().size()))
, BaseType(sp, VectorProviderBaseType::storage_access(), nm)
{
}
// manual copy ctor needed bc. of the storage provider
DiscreteFunction(const ThisType& other)
: VectorProviderBaseType(new VectorType(other.vector()))
, BaseType(other.space(), VectorProviderBaseType::storage_access(), other.name())
{
}
// manual move ctor needed bc. of the storage provider
DiscreteFunction(ThisType&& source)
: VectorProviderBaseType(new VectorType(source.vector()))
, BaseType(source.space(), VectorProviderBaseType::storage_access(), source.name())
{
}
virtual ~DiscreteFunction()
{
}
ThisType& operator=(const ThisType& other) = delete;
virtual ThisType* copy() const override
{
return new ThisType(*this);
}
using BaseType::vector;
VectorType& vector()
{
return this->storage_access();
}
using BaseType::local_discrete_function;
std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function(const EntityType& entity)
{
assert(space_->grid_view().indexSet().contains(entity));
return DSC::make_unique<LocalDiscreteFunctionType>(*space_, this->storage_access(), entity);
}
private:
using BaseType::space_;
}; // class DiscreteFunction
template <class SpaceType, class VectorType>
ConstDiscreteFunction<SpaceType, VectorType>
make_const_discrete_function(const SpaceType& space, const VectorType& vector,
const std::string nm = "gdt.constdiscretefunction")
{
return ConstDiscreteFunction<SpaceType, VectorType>(space, vector, nm);
}
template <class SpaceType, class VectorType>
typename std::enable_if<is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value,
DiscreteFunction<SpaceType, VectorType>>::type
make_discrete_function(const SpaceType& space, VectorType& vector, const std::string nm = "gdt.discretefunction")
{
return DiscreteFunction<SpaceType, VectorType>(space, vector, nm);
}
/**
* This can be used like \code
auto discrete_function = make_discrete_function< VectorType >(space);
\endcode
*/
template <class VectorType, class SpaceType>
DiscreteFunction<SpaceType, VectorType> make_discrete_function(const SpaceType& space,
const std::string nm = "gdt.discretefunction")
{
return DiscreteFunction<SpaceType, VectorType>(space, nm);
}
namespace internal {
template <class D>
struct is_const_discrete_function_helper
{
DSC_has_typedef_initialize_once(SpaceType) DSC_has_typedef_initialize_once(VectorType)
static const bool is_candidate = DSC_has_typedef(SpaceType)<D>::value && DSC_has_typedef(SpaceType)<D>::value;
};
} // namespace internal
template <class D, bool candidate = internal::is_const_discrete_function_helper<D>::is_candidate>
struct is_const_discrete_function
: public std::is_base_of<ConstDiscreteFunction<typename D::SpaceType, typename D::VectorType>, D>
{
};
template <class D>
struct is_const_discrete_function<D, false> : public std::false_type
{
};
template <class D, bool candidate = internal::is_const_discrete_function_helper<D>::is_candidate>
struct is_discrete_function : public std::is_base_of<DiscreteFunction<typename D::SpaceType, typename D::VectorType>, D>
{
};
template <class D>
struct is_discrete_function<D, false> : public std::false_type
{
};
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_LOCALOPERATOR_INTERFACES_HH
#define DUNE_GDT_LOCALOPERATOR_INTERFACES_HH
#include <vector>
#include <dune/common/dynmatrix.hh>
#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/gdt/discretefunction/local.hh>
namespace Dune {
namespace GDT {
template <class Traits>
class LocalOperatorInterface : public Stuff::CRTPInterface<LocalOperatorInterface<Traits>, Traits>
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Applies the local operator.
* \param source Should be a Stuff::LocalizableFunctionInterface or a ConstDiscreteFunction.
*/
template <class SourceType, class RangeSpaceType, class VectorType>
void apply(const SourceType& source, LocalDiscreteFunction<RangeSpaceType, VectorType>& local_range) const
{
CHECK_AND_CALL_CRTP(this->as_imp().apply(source, local_range));
}
}; // class LocalVolumeTwoFormInterface
template <class Traits>
class LocalVolumeTwoFormInterface : public Stuff::CRTPInterface<LocalVolumeTwoFormInterface<Traits>, Traits>
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Applies the local operator as a two-form.
* \tparam T Traits of the test Stuff::LocalfunctionSetInterface implementation
* \tparam A Traits of the ansatz Stuff::LocalfunctionSetInterface implementation
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the of the {test_base,ansatz_base}
* \tparam rC{T,a} dimRangeCols of the {test_base,ansatz_base}
*/
template <class T, class A, class D, size_t d, class R, size_t rT, size_t rCT, size_t rA, size_t rCA>
void apply2(const Stuff::LocalfunctionSetInterface<T, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<A, D, d, R, rA, rCA>& ansatz_base,
Dune::DynamicMatrix<R>& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp().apply2(test_base, ansatz_base, ret));
}
}; // class LocalVolumeTwoFormInterface
template <class Traits>
class LocalCouplingTwoFormInterface : public Stuff::CRTPInterface<LocalCouplingTwoFormInterface<Traits>, Traits>
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Applies the local operator associated with inner faces as a two-form.
* \tparam TE Traits of the entity test Stuff::LocalfunctionSetInterface implementation
* \tparam AE Traits of the entity ansatz Stuff::LocalfunctionSetInterface implementation
* \tparam TN Traits of the neighbor test Stuff::LocalfunctionSetInterface implementation
* \tparam AN Traits of the neighbor ansatz Stuff::LocalfunctionSetInterface implementation
* \tparam IntersectionType
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the of the {test_base*,ansatz_base*}
* \tparam rC{T,a} dimRangeCols of the {test_base*,ansatz_base*}
*/
template <class TE, class AE, class TN, class AN, class IntersectionType, class D, size_t d, class R, size_t rT,
size_t rCT, size_t rA, size_t rCA>
void apply2(const Stuff::LocalfunctionSetInterface<TE, D, d, R, rT, rCT>& test_base_entity,
const Stuff::LocalfunctionSetInterface<AE, D, d, R, rA, rCA>& ansatz_base_entity,
const Stuff::LocalfunctionSetInterface<TN, D, d, R, rT, rCT>& test_base_neighbor,
const Stuff::LocalfunctionSetInterface<AN, D, d, R, rA, rCA>& ansatz_base_neighbor,
const IntersectionType& intersection, Dune::DynamicMatrix<R>& entityEntityRet,
Dune::DynamicMatrix<R>& neighborNeighborRet, Dune::DynamicMatrix<R>& entityNeighborRet,
Dune::DynamicMatrix<R>& neighborEntityRet) const
{
CHECK_AND_CALL_CRTP(this->as_imp().apply2(test_base_entity,
ansatz_base_entity,
test_base_neighbor,
ansatz_base_neighbor,
intersection,
entityEntityRet,
neighborNeighborRet,
entityNeighborRet,
neighborEntityRet));
}
}; // class LocalCouplingTwoFormInterface
namespace internal {
template <class Tt>
struct is_local_operator_helper
{
DSC_has_typedef_initialize_once(Traits)
static const bool is_candidate = DSC_has_typedef(Traits)<Tt>::value;
};
template <class Tt>
struct is_local_volume_twoform_helper
{
DSC_has_typedef_initialize_once(Traits)
static const bool is_candidate = DSC_has_typedef(Traits)<Tt>::value;
};
} // namespace internal
template <class T, bool candidate = internal::is_local_operator_helper<T>::is_candidate>
struct is_local_operator : public std::is_base_of<LocalOperatorInterface<typename T::Traits>, T>
{
};
template <class T>
struct is_local_operator<T, false> : public std::false_type
{
};
template <class T, bool candidate = internal::is_local_volume_twoform_helper<T>::is_candidate>
struct is_local_volume_twoform : public std::is_base_of<LocalVolumeTwoFormInterface<typename T::Traits>, T>
{
};
template <class T>
struct is_local_volume_twoform<T, false> : public std::false_type
{
};
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCALOPERATOR_INTERFACES_HH
<commit_msg>[localoperator.interfaces] add first draft of LocalBoundaryTwoFormInterface<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_LOCALOPERATOR_INTERFACES_HH
#define DUNE_GDT_LOCALOPERATOR_INTERFACES_HH
#include <vector>
#include <dune/common/dynmatrix.hh>
#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/gdt/discretefunction/local.hh>
namespace Dune {
namespace GDT {
template <class Traits>
class LocalOperatorInterface : public Stuff::CRTPInterface<LocalOperatorInterface<Traits>, Traits>
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Applies the local operator.
* \param source Should be a Stuff::LocalizableFunctionInterface or a ConstDiscreteFunction.
*/
template <class SourceType, class RangeSpaceType, class VectorType>
void apply(const SourceType& source, LocalDiscreteFunction<RangeSpaceType, VectorType>& local_range) const
{
CHECK_AND_CALL_CRTP(this->as_imp().apply(source, local_range));
}
}; // class LocalVolumeTwoFormInterface
template <class Traits>
class LocalVolumeTwoFormInterface : public Stuff::CRTPInterface<LocalVolumeTwoFormInterface<Traits>, Traits>
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Applies the local operator as a two-form.
* \tparam T Traits of the test Stuff::LocalfunctionSetInterface implementation
* \tparam A Traits of the ansatz Stuff::LocalfunctionSetInterface implementation
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the of the {test_base,ansatz_base}
* \tparam rC{T,a} dimRangeCols of the {test_base,ansatz_base}
*/
template <class T, class A, class D, size_t d, class R, size_t rT, size_t rCT, size_t rA, size_t rCA>
void apply2(const Stuff::LocalfunctionSetInterface<T, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<A, D, d, R, rA, rCA>& ansatz_base,
Dune::DynamicMatrix<R>& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp().apply2(test_base, ansatz_base, ret));
}
}; // class LocalVolumeTwoFormInterface
template <class Traits>
class LocalCouplingTwoFormInterface : public Stuff::CRTPInterface<LocalCouplingTwoFormInterface<Traits>, Traits>
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Applies the local operator associated with inner faces as a two-form.
* \tparam TE Traits of the entity test Stuff::LocalfunctionSetInterface implementation
* \tparam AE Traits of the entity ansatz Stuff::LocalfunctionSetInterface implementation
* \tparam TN Traits of the neighbor test Stuff::LocalfunctionSetInterface implementation
* \tparam AN Traits of the neighbor ansatz Stuff::LocalfunctionSetInterface implementation
* \tparam IntersectionType
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the of the {test_base*,ansatz_base*}
* \tparam rC{T,a} dimRangeCols of the {test_base*,ansatz_base*}
*/
template <class TE, class AE, class TN, class AN, class IntersectionType, class D, size_t d, class R, size_t rT,
size_t rCT, size_t rA, size_t rCA>
void apply2(const Stuff::LocalfunctionSetInterface<TE, D, d, R, rT, rCT>& test_base_entity,
const Stuff::LocalfunctionSetInterface<AE, D, d, R, rA, rCA>& ansatz_base_entity,
const Stuff::LocalfunctionSetInterface<TN, D, d, R, rT, rCT>& test_base_neighbor,
const Stuff::LocalfunctionSetInterface<AN, D, d, R, rA, rCA>& ansatz_base_neighbor,
const IntersectionType& intersection, Dune::DynamicMatrix<R>& entityEntityRet,
Dune::DynamicMatrix<R>& neighborNeighborRet, Dune::DynamicMatrix<R>& entityNeighborRet,
Dune::DynamicMatrix<R>& neighborEntityRet) const
{
CHECK_AND_CALL_CRTP(this->as_imp().apply2(test_base_entity,
ansatz_base_entity,
test_base_neighbor,
ansatz_base_neighbor,
intersection,
entityEntityRet,
neighborNeighborRet,
entityNeighborRet,
neighborEntityRet));
}
}; // class LocalCouplingTwoFormInterface
template <class Traits>
class LocalBoundaryTwoFormInterface : public Stuff::CRTPInterface<LocalBoundaryTwoFormInterface<Traits>, Traits>
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Applies the local operator associated with boundary faces as a two-form.
* \tparam T Traits of the test Stuff::LocalfunctionSetInterface implementation
* \tparam A Traits of the ansatz Stuff::LocalfunctionSetInterface implementation
* \tparam IntersectionType
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the of the {test_base,ansatz_base}
* \tparam rC{T,a} dimRangeCols of the {test_base,ansatz_base}
*/
template <class T, class A, class IntersectionType, class D, size_t d, class R, size_t rT, size_t rCT, size_t rA,
size_t rCA>
void apply2(const Stuff::LocalfunctionSetInterface<T, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<A, D, d, R, rA, rCA>& ansatz_base,
const IntersectionType& intersection, Dune::DynamicMatrix<R>& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp().apply2(test_base, ansatz_base, intersection, ret));
}
}; // class LocalBoundaryTwoFormInterface
namespace internal {
template <class Tt>
struct is_local_operator_helper
{
DSC_has_typedef_initialize_once(Traits)
static const bool is_candidate = DSC_has_typedef(Traits)<Tt>::value;
};
template <class Tt>
struct is_local_volume_twoform_helper
{
DSC_has_typedef_initialize_once(Traits)
static const bool is_candidate = DSC_has_typedef(Traits)<Tt>::value;
};
} // namespace internal
template <class T, bool candidate = internal::is_local_operator_helper<T>::is_candidate>
struct is_local_operator : public std::is_base_of<LocalOperatorInterface<typename T::Traits>, T>
{
};
template <class T>
struct is_local_operator<T, false> : public std::false_type
{
};
template <class T, bool candidate = internal::is_local_volume_twoform_helper<T>::is_candidate>
struct is_local_volume_twoform : public std::is_base_of<LocalVolumeTwoFormInterface<typename T::Traits>, T>
{
};
template <class T>
struct is_local_volume_twoform<T, false> : public std::false_type
{
};
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCALOPERATOR_INTERFACES_HH
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_DEFAULT_PRODUCTFV_HH
#define DUNE_GDT_MAPPER_DEFAULT_PRODUCTFV_HH
#include <dune/common/dynvector.hh>
#include <dune/stuff/common/debug.hh>
#include <dune/stuff/common/type_utils.hh>
#include "../../mapper/interface.hh"
#include "fv.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
// forward
template <class GridViewImp, size_t rangeDim = 1, size_t rangeDimCols = 1>
class ProductFiniteVolume
{
static_assert(AlwaysFalse<GridViewImp>::value, "Not available for these dimensions!");
};
namespace internal {
template <class GridViewImp, size_t rangeDim, size_t rangeDimCols>
class ProductFiniteVolumeTraits : internal::FiniteVolumeTraits<GridViewImp, rangeDim, rangeDimCols>
{
public:
typedef ProductFiniteVolume<GridViewType, rangeDim, rangeDimCols> derived_type;
};
} // namespace internal
template <class GridViewImp, size_t rangeDim>
class ProductFiniteVolume<GridViewImp, rangeDim, 1>
: public ProductMapperInterface<internal::ProductFiniteVolumeTraits<GridViewImp, rangeDim, 1>>,
public FiniteVolume<GridViewImp, rangeDim, 1>
{
typedef ProductMapperInterface<internal::ProductFiniteVolumeTraits<GridViewImp, rangeDim, 1>> InterfaceType;
typedef FiniteVolume<GridViewImp, rangeDim, 1> BaseType;
static const size_t dimRange = rangeDim;
public:
typedef internal::ProductFiniteVolumeTraits<GridViewImp, rangeDim, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
ProductFiniteVolume(const GridViewType& grid_view)
: BaseType(grid_view)
{
}
using BaseType::backend;
using BaseType::size;
using BaseType::numDofs;
using BaseType::maxNumDofs;
using BaseType::globalIndices;
Dune::DynamicVector<size_t> globalIndices(const size_t factor_index, const EntityType& entity) const
{
Dune::DynamicVector<size_t> ret(numDofs(entity), 0);
globalIndices(factor_index, entity, ret);
return ret;
}
size_t mapToGlobal(const size_t factor_index, const EntityType& entity,
const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
{
assert(localIndex == 0);
assert(factor_index < numDofs(entity));
return (dimRange * (backend_.index(entity))) + factor_index;
}
}; // class ProductFiniteVolume< ..., rangeDim, 1 >
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_DEFAULT_PRODUCTFV_HH
<commit_msg>[mapper.default.productvf] minor fixes<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_DEFAULT_PRODUCTFV_HH
#define DUNE_GDT_MAPPER_DEFAULT_PRODUCTFV_HH
#include <dune/common/dynvector.hh>
#include <dune/stuff/common/debug.hh>
#include <dune/stuff/common/type_utils.hh>
#include "../../mapper/interface.hh"
#include "fv.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
// forward
template <class GridViewImp, size_t rangeDim = 1, size_t rangeDimCols = 1>
class ProductFiniteVolume
{
static_assert(AlwaysFalse<GridViewImp>::value, "Not available for these dimensions!");
};
namespace internal {
template <class GridViewImp, size_t rangeDim, size_t rangeDimCols>
class ProductFiniteVolumeTraits : internal::FiniteVolumeTraits<GridViewImp, rangeDim, rangeDimCols>
{
public:
typedef ProductFiniteVolume<GridViewImp, rangeDim, rangeDimCols> derived_type;
};
} // namespace internal
template <class GridViewImp, size_t rangeDim>
class ProductFiniteVolume<GridViewImp, rangeDim, 1>
: public ProductMapperInterface<internal::ProductFiniteVolumeTraits<GridViewImp, rangeDim, 1>>,
public FiniteVolume<GridViewImp, rangeDim, 1>
{
typedef ProductMapperInterface<internal::ProductFiniteVolumeTraits<GridViewImp, rangeDim, 1>> InterfaceType;
typedef FiniteVolume<GridViewImp, rangeDim, 1> BaseType;
using BaseType::dimRange;
public:
typedef internal::ProductFiniteVolumeTraits<GridViewImp, rangeDim, 1> Traits;
using typename BaseType::GridViewType;
using typename BaseType::EntityType;
ProductFiniteVolume(const GridViewType& grid_view)
: BaseType(grid_view)
{
}
using BaseType::numDofs;
using BaseType::globalIndices;
Dune::DynamicVector<size_t> globalIndices(const size_t factor_index, const EntityType& entity) const
{
Dune::DynamicVector<size_t> ret(numDofs(entity), 0);
globalIndices(factor_index, entity, ret);
return ret;
}
size_t mapToGlobal(const size_t factor_index, const EntityType& entity,
const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
{
assert(localIndex == 0);
assert(factor_index < numDofs(entity));
return (dimRange * (backend_.index(entity))) + factor_index;
}
private:
using BaseType::backend_;
}; // class ProductFiniteVolume< ..., rangeDim, 1 >
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_DEFAULT_PRODUCTFV_HH
<|endoftext|>
|
<commit_before>#include <config.h>
#include "error_calc.hh"
#include <assert.h>
#include <boost/filesystem/fstream.hpp>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/common/grid_creation.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/msfem/localsolution_proxy.hh>
#include <dune/multiscale/msfem/proxygridview.hh>
#include <dune/multiscale/msfem/fem_solver.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/misc/outputparameter.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/discretefunction/projection/heterogenous.hh>
using namespace Dune::Multiscale;
void solution_output(const CommonTraits::DiscreteFunctionType& msfem_solution) {
using namespace Dune;
Dune::Multiscale::OutputParameters outputparam;
outputparam.set_prefix("msfem_solution_");
msfem_solution.visualize(outputparam.fullpath(msfem_solution.name()));
}
void data_output(const CommonTraits::GridViewType& gridPart) {
using namespace Dune;
Dune::Multiscale::OutputParameters outputparam;
if (Problem::getModelData()->hasExactSolution()) {
const auto& u = Dune::Multiscale::Problem::getExactSolution();
outputparam.set_prefix("exact_solution");
u->visualize(gridPart, outputparam.fullpath(u->name()));
}
}
Dune::Multiscale::ErrorCalculator::ErrorCalculator(const std::unique_ptr<LocalsolutionProxy>& msfem_solution,
CommonTraits::ConstDiscreteFunctionType* fem_solution)
: msfem_solution_(msfem_solution)
, fem_solution_(fem_solution)
{
assert(fem_solution_);
}
ErrorCalculator::ErrorCalculator(const std::unique_ptr<LocalsolutionProxy> &msfem_solution)
: msfem_solution_(msfem_solution)
, fem_solution_(nullptr)
{
assert(msfem_solution_);
if (DSC_CONFIG_GET("msfem.fem_comparison", false)) {
fem_solver_ = DSC::make_unique<Elliptic_FEM_Solver>();
fem_solution_ = &fem_solver_->solve();
}
}
std::map<std::string, double> Dune::Multiscale::ErrorCalculator::print(std::ostream& out) {
using namespace Dune::GDT::Products;
out << std::endl << "The L2 errors:" << std::endl << std::endl;
const size_t over_integrate = 0; // <- would let the product use a higher quadrature order than needed
typedef Stuff::Functions::Difference<Problem::ExactSolutionType, CommonTraits::ConstDiscreteFunctionType>
DifferenceType;
/// TODO only call assemble once
const auto fine_grid = make_grids().second;
CommonTraits::GridProviderType fine_grid_provider(*fine_grid);
const CommonTraits::GdtSpaceType fine_space =
CommonTraits::SpaceProviderType::create(fine_grid_provider, CommonTraits::st_gdt_grid_level);
GDT::SystemAssembler<CommonTraits::SpaceType> system_assembler(fine_space);
const auto& grid_view = fine_space.grid_view();
std::map<std::string, double> csv;
CommonTraits::DiscreteFunctionType fine_msfem_solution(fine_space, "MsFEM_Solution");
if (msfem_solution_) {
DS::MsFEMProjection::project(*msfem_solution_, fine_msfem_solution, msfem_solution_->search());
if (DSC_CONFIG_GET("global.vtk_output", false)) {
DSC_LOG_INFO_0 << "Solution output for MsFEM Solution." << std::endl;
data_output(*fine_space.grid_view());
solution_output(fine_msfem_solution);
}
}
//! ----------------- compute L2- and H1- errors -------------------
if (Problem::getModelData()->hasExactSolution()) {
const auto& u = *DMP::getExactSolution();
if (msfem_solution_) {
const DifferenceType difference(u, fine_msfem_solution);
L2Localizable<CommonTraits::GridViewType, DifferenceType> l2_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(l2_error_product);
H1SemiLocalizable<CommonTraits::GridViewType, DifferenceType> h1_semi_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(h1_semi_error_product);
system_assembler.tbb_assemble();
const auto msfem_error = std::sqrt(l2_error_product.apply2());
out << "|| u_msfem - u_exact ||_L2 = " << msfem_error << std::endl;
const auto h1_msfem_error = std::sqrt(h1_semi_error_product.apply2());
out << "|| u_msfem - u_exact ||_H1s = " << h1_msfem_error << std::endl << std::endl;
csv["msfem_exact_L2"] = msfem_error;
csv["msfem_exact_H1s"] = h1_msfem_error;
}
if (fem_solution_) {
const DifferenceType difference(u, *fem_solution_);
L2Localizable<CommonTraits::GridViewType, DifferenceType> l2_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(l2_error_product);
H1SemiLocalizable<CommonTraits::GridViewType, DifferenceType> h1_semi_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(h1_semi_error_product);
system_assembler.tbb_assemble();
const auto fem_error = std::sqrt(l2_error_product.apply2());
out << "|| u_fem - u_exact ||_L2 = " << fem_error << std::endl;
const auto h1_fem_error = std::sqrt(h1_semi_error_product.apply2());
out << "|| u_fem - u_exact ||_H1s = " << h1_fem_error << std::endl << std::endl;
csv["fem_exact_L2"] = fem_error;
csv["fem_exact_H1s"] = h1_fem_error;
}
}
if (msfem_solution_ && fem_solution_) {
typedef Stuff::Functions::Difference<CommonTraits::ConstDiscreteFunctionType,
CommonTraits::ConstDiscreteFunctionType> DiscreteDifferenceType;
const DiscreteDifferenceType difference(fine_msfem_solution, *fem_solution_);
L2Localizable<CommonTraits::GridViewType, DiscreteDifferenceType> l2_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(l2_error_product);
L2Localizable<CommonTraits::GridViewType, CommonTraits::ConstDiscreteFunctionType> l2_msfem(
*grid_view, fine_msfem_solution, over_integrate);
system_assembler.add(l2_msfem);
H1SemiLocalizable<CommonTraits::GridViewType, DiscreteDifferenceType> h1_semi_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(h1_semi_error_product);
system_assembler.tbb_assemble();
const auto approx_msfem_error = std::sqrt(l2_error_product.apply2());
const auto no = std::sqrt(l2_msfem.apply2());
if (std::abs(no) > 1e-12)
out << "|| u_msfem - u_fem ||_L2 / || u_msfem ||_L2 = " << approx_msfem_error / no << std::endl;
else
out << "|| u_msfem - u_fem ||_L2 = " << approx_msfem_error << std::endl;
const auto h1_approx_msfem_error = std::sqrt(h1_semi_error_product.apply2());
out << "|| u_msfem - u_fem ||_H1s = " << h1_approx_msfem_error << std::endl << std::endl;
csv["msfem_fem_L2"] = approx_msfem_error;
csv["msfem_fem_H1s"] = h1_approx_msfem_error;
}
std::unique_ptr<boost::filesystem::ofstream> csvfile(
DSC::make_ofstream(std::string(DSC_CONFIG_GET("global.datadir", "data/")) + std::string("/errors.csv")));
const std::string sep(",");
for (const auto& key_val : csv) {
*csvfile << key_val.first << sep;
}
*csvfile << std::endl;
for (const auto& key_val : csv) {
*csvfile << key_val.second << sep;
}
*csvfile << std::endl;
return csv;
}
<commit_msg>makes error clac usable w. and w/o fem solution again<commit_after>#include <config.h>
#include "error_calc.hh"
#include <assert.h>
#include <boost/filesystem/fstream.hpp>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/common/grid_creation.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/msfem/localsolution_proxy.hh>
#include <dune/multiscale/msfem/proxygridview.hh>
#include <dune/multiscale/msfem/fem_solver.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/misc/outputparameter.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/discretefunction/projection/heterogenous.hh>
using namespace Dune::Multiscale;
void solution_output(const CommonTraits::DiscreteFunctionType& msfem_solution) {
using namespace Dune;
Dune::Multiscale::OutputParameters outputparam;
outputparam.set_prefix("msfem_solution_");
msfem_solution.visualize(outputparam.fullpath(msfem_solution.name()));
}
void data_output(const CommonTraits::GridViewType& gridPart) {
using namespace Dune;
Dune::Multiscale::OutputParameters outputparam;
if (Problem::getModelData()->hasExactSolution()) {
const auto& u = Dune::Multiscale::Problem::getExactSolution();
outputparam.set_prefix("exact_solution");
u->visualize(gridPart, outputparam.fullpath(u->name()));
}
}
Dune::Multiscale::ErrorCalculator::ErrorCalculator(const std::unique_ptr<LocalsolutionProxy>& msfem_solution,
CommonTraits::ConstDiscreteFunctionType* fem_solution)
: msfem_solution_(msfem_solution)
, fem_solution_(fem_solution)
{
assert(fem_solution_);
}
ErrorCalculator::ErrorCalculator(const std::unique_ptr<LocalsolutionProxy> &msfem_solution)
: msfem_solution_(msfem_solution)
, fem_solution_(nullptr)
{
assert(msfem_solution_);
if (DSC_CONFIG_GET("msfem.fem_comparison", false)) {
fem_solver_ = DSC::make_unique<Elliptic_FEM_Solver>();
fem_solution_ = &fem_solver_->solve();
}
}
std::map<std::string, double> Dune::Multiscale::ErrorCalculator::print(std::ostream& out) {
using namespace Dune::GDT::Products;
out << std::endl << "The L2 errors:" << std::endl << std::endl;
const size_t over_integrate = 0; // <- would let the product use a higher quadrature order than needed
typedef Stuff::Functions::Difference<Problem::ExactSolutionType, CommonTraits::ConstDiscreteFunctionType>
DifferenceType;
/// TODO only call assemble once
const auto fine_grid = make_grids().second;
CommonTraits::GridProviderType fine_grid_provider(*fine_grid);
const auto fine_space_ptr = //fem_solution_->space();
CommonTraits::SpaceProviderType::create(fine_grid_provider, CommonTraits::st_gdt_grid_level);
const auto& fine_space = fem_solution_ ? fem_solution_->space() : *fine_space_ptr;
GDT::SystemAssembler<CommonTraits::SpaceType> system_assembler(fine_space);
const auto& grid_view = fine_space.grid_view();
std::map<std::string, double> csv;
CommonTraits::DiscreteFunctionType fine_msfem_solution(fine_space, "MsFEM_Solution");
if (msfem_solution_) {
DS::MsFEMProjection::project(*msfem_solution_, fine_msfem_solution, msfem_solution_->search());
if (DSC_CONFIG_GET("global.vtk_output", false)) {
DSC_LOG_INFO_0 << "Solution output for MsFEM Solution." << std::endl;
data_output(*fine_space.grid_view());
solution_output(fine_msfem_solution);
}
}
//! ----------------- compute L2- and H1- errors -------------------
if (Problem::getModelData()->hasExactSolution()) {
const auto& u = *DMP::getExactSolution();
if (msfem_solution_) {
const DifferenceType difference(u, fine_msfem_solution);
L2Localizable<CommonTraits::GridViewType, DifferenceType> l2_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(l2_error_product);
H1SemiLocalizable<CommonTraits::GridViewType, DifferenceType> h1_semi_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(h1_semi_error_product);
system_assembler.tbb_assemble();
const auto msfem_error = std::sqrt(l2_error_product.apply2());
out << "|| u_msfem - u_exact ||_L2 = " << msfem_error << std::endl;
const auto h1_msfem_error = std::sqrt(h1_semi_error_product.apply2());
out << "|| u_msfem - u_exact ||_H1s = " << h1_msfem_error << std::endl << std::endl;
csv["msfem_exact_L2"] = msfem_error;
csv["msfem_exact_H1s"] = h1_msfem_error;
}
if (fem_solution_) {
const DifferenceType difference(u, *fem_solution_);
L2Localizable<CommonTraits::GridViewType, DifferenceType> l2_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(l2_error_product);
H1SemiLocalizable<CommonTraits::GridViewType, DifferenceType> h1_semi_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(h1_semi_error_product);
system_assembler.tbb_assemble();
const auto fem_error = std::sqrt(l2_error_product.apply2());
out << "|| u_fem - u_exact ||_L2 = " << fem_error << std::endl;
const auto h1_fem_error = std::sqrt(h1_semi_error_product.apply2());
out << "|| u_fem - u_exact ||_H1s = " << h1_fem_error << std::endl << std::endl;
csv["fem_exact_L2"] = fem_error;
csv["fem_exact_H1s"] = h1_fem_error;
}
}
if (msfem_solution_ && fem_solution_) {
typedef Stuff::Functions::Difference<CommonTraits::ConstDiscreteFunctionType,
CommonTraits::ConstDiscreteFunctionType> DiscreteDifferenceType;
const DiscreteDifferenceType difference(fine_msfem_solution, *fem_solution_);
L2Localizable<CommonTraits::GridViewType, DiscreteDifferenceType> l2_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(l2_error_product);
L2Localizable<CommonTraits::GridViewType, CommonTraits::ConstDiscreteFunctionType> l2_msfem(
*grid_view, fine_msfem_solution, over_integrate);
system_assembler.add(l2_msfem);
H1SemiLocalizable<CommonTraits::GridViewType, DiscreteDifferenceType> h1_semi_error_product(*grid_view, difference,
over_integrate);
system_assembler.add(h1_semi_error_product);
system_assembler.tbb_assemble();
const auto approx_msfem_error = std::sqrt(l2_error_product.apply2());
const auto no = std::sqrt(l2_msfem.apply2());
if (std::abs(no) > 1e-12)
out << "|| u_msfem - u_fem ||_L2 / || u_msfem ||_L2 = " << approx_msfem_error / no << std::endl;
else
out << "|| u_msfem - u_fem ||_L2 = " << approx_msfem_error << std::endl;
const auto h1_approx_msfem_error = std::sqrt(h1_semi_error_product.apply2());
out << "|| u_msfem - u_fem ||_H1s = " << h1_approx_msfem_error << std::endl << std::endl;
csv["msfem_fem_L2"] = approx_msfem_error;
csv["msfem_fem_H1s"] = h1_approx_msfem_error;
}
std::unique_ptr<boost::filesystem::ofstream> csvfile(
DSC::make_ofstream(std::string(DSC_CONFIG_GET("global.datadir", "data/")) + std::string("/errors.csv")));
const std::string sep(",");
for (const auto& key_val : csv) {
*csvfile << key_val.first << sep;
}
*csvfile << std::endl;
for (const auto& key_val : csv) {
*csvfile << key_val.second << sep;
}
*csvfile << std::endl;
return csv;
}
<|endoftext|>
|
<commit_before>
#include "Object.h"
namespace Atlas
{
void Object::walkTree(int nest, string name, const Object& list)
{
}
void Object::dump(const Object& msg)
{
}
/** (List) insert an Object at this index */
bool Object::insert(size_t ndx, const Object& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert( ((VVec*)obj)->vv.begin()+ndx , val.obj );
val.obj->incref();
return true;
}
/** (List) insert an Int at this index */
bool Object::insert(size_t ndx, int val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert(((VVec*)obj)->vv.begin()+ndx, new VNum(val));
return true;
}
/** (List) insert an Long at this index */
bool Object::insert(size_t ndx, long val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert( ((VVec*)obj)->vv.begin()+ndx, new VNum(val) );
return true;
}
/** (List) insert a Float at this index */
bool Object::insert(size_t ndx, double val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert(((VVec*)obj)->vv.begin()+ndx, new VNum(val));
return true;
}
/** (List) insert a String at this index */
bool Object::insert(size_t ndx, const string& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert(((VVec*)obj)->vv.begin()+ndx, new VStr(val));
return true;
}
/** (List) append an Object */
bool Object::append(const Object& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(val.obj);
val.obj->incref();
return true;
}
/** (List) append an Int */
bool Object::append(int val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VNum(val));
return true;
}
/** (List) append an Long */
bool Object::append(long val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VNum(val));
return true;
}
/** (List) append a Float */
bool Object::append(double val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VNum(val));
return true;
}
/** (List) append a String */
bool Object::append(const string& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VStr(val));
return true;
}
/** (List) replace an Object at this index */
bool Object::set(size_t ndx, const Object& src)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = src.obj;
src.obj->incref();
return true;
}
/** (List) replace an Int at this index */
bool Object::set(size_t ndx, int val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VNum(val);
return true;
}
/** (List) replace an Long at this index */
bool Object::set(size_t ndx, long val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VNum(val);
return true;
}
/** (List) replace a Float at this index */
bool Object::set(size_t ndx, double val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VNum(val);
return true;
}
/** (List) replace a String at this index */
bool Object::set(size_t ndx, const string& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VStr(val);
return true;
}
/** (List) get an Object from this index */
bool Object::get(size_t ndx, Object& src) const
{
if (obj->rt != List) return false;
src.obj->decref();
src.obj = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
src.obj->incref();
return true;
}
/** (List) get an Int from this index */
bool Object::get(size_t ndx, int& val) const
{
if (obj->rt != List) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt !=Int) return false;
val = ((VNum*)tmp)->lv;
return true;
}
/** (List) get an Long from this index */
bool Object::get(size_t ndx, long& val) const
{
if (obj->rt != List) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt !=Int) return false;
val = ((VNum*)tmp)->lv;
return true;
}
/** (List) get a Float from this index */
bool Object::get(size_t ndx, double& val) const
{
if (obj->rt != List) return false;
//if ((VVec*)obj->vv.size() <= ndx) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt != Float) return false;
val = ((VNum*)tmp)->dv;
return true;
}
/** (List) get a String from this index */
bool Object::get(size_t ndx, string& val) const
{
if (obj->rt != List) return false;
//if ((VVec*)obj->vv.size() <= ndx) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt !=String) return false;
val = ((VStr*)tmp)->st;
return true;
}
/** (List) get an Object from this index with default */
bool Object::get(size_t ndx, Object& val, Object& def) const
{
val = def;
return get(ndx,val);
}
/** (List) get an Int from this index */
bool Object::get(size_t ndx, int& val, int def) const
{
val = def;
return get(ndx,val);
}
/** (List) get an Long from this index */
bool Object::get(size_t ndx, long& val, long def) const
{
val = def;
return get(ndx,val);
}
/** (List) get a Float from this index */
bool Object::get(size_t ndx, double& val, double def) const
{
val = def;
return get(ndx,val);
}
/** (List) get a String from this index */
bool Object::get(size_t ndx, string& val, string& def) const
{
val = def;
return get(ndx,val);
}
} // end namespace atlas
<commit_msg>Atlas::Object more list handling fixes<commit_after>
#include "Object.h"
namespace Atlas
{
void Object::walkTree(int nest, string name, const Object& list)
{
}
void Object::dump(const Object& msg)
{
}
/** (List) insert an Object at this index */
bool Object::insert(size_t ndx, const Object& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert( ((VVec*)obj)->vv.begin()+ndx , val.obj );
val.obj->incref();
return true;
}
/** (List) insert an Int at this index */
bool Object::insert(size_t ndx, int val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert(((VVec*)obj)->vv.begin()+ndx, new VNum(val));
return true;
}
/** (List) insert an Long at this index */
bool Object::insert(size_t ndx, long val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert( ((VVec*)obj)->vv.begin()+ndx, new VNum(val) );
return true;
}
/** (List) insert a Float at this index */
bool Object::insert(size_t ndx, double val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert(((VVec*)obj)->vv.begin()+ndx, new VNum(val));
return true;
}
/** (List) insert a String at this index */
bool Object::insert(size_t ndx, const string& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.insert(((VVec*)obj)->vv.begin()+ndx, new VStr(val));
return true;
}
/** (List) append an Object */
bool Object::append(const Object& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(val.obj);
val.obj->incref();
return true;
}
/** (List) append an Int */
bool Object::append(int val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VNum(val));
return true;
}
/** (List) append an Long */
bool Object::append(long val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VNum(val));
return true;
}
/** (List) append a Float */
bool Object::append(double val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VNum(val));
return true;
}
/** (List) append a String */
bool Object::append(const string& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv.push_back(new VStr(val));
return true;
}
/** (List) replace an Object at this index */
bool Object::set(size_t ndx, const Object& src)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = src.obj;
src.obj->incref();
return true;
}
/** (List) replace an Int at this index */
bool Object::set(size_t ndx, int val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VNum(val);
return true;
}
/** (List) replace an Long at this index */
bool Object::set(size_t ndx, long val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VNum(val);
return true;
}
/** (List) replace a Float at this index */
bool Object::set(size_t ndx, double val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VNum(val);
return true;
}
/** (List) replace a String at this index */
bool Object::set(size_t ndx, const string& val)
{
if (obj->rt != List) return false;
((VVec*)obj)->vv[ndx] = new VStr(val);
return true;
}
/** (List) get an Object from this index */
bool Object::get(size_t ndx, Object& src) const
{
if (obj->rt != List) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
src.obj->decref();
src.obj = tmp;
src.obj->incref();
return true;
}
/** (List) get an Int from this index */
bool Object::get(size_t ndx, int& val) const
{
if (obj->rt != List) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt !=Int) return false;
val = ((VNum*)tmp)->lv;
return true;
}
/** (List) get an Long from this index */
bool Object::get(size_t ndx, long& val) const
{
if (obj->rt != List) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt !=Int) return false;
val = ((VNum*)tmp)->lv;
return true;
}
/** (List) get a Float from this index */
bool Object::get(size_t ndx, double& val) const
{
if (obj->rt != List) return false;
//if ((VVec*)obj->vv.size() <= ndx) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt != Float) return false;
val = ((VNum*)tmp)->dv;
return true;
}
/** (List) get a String from this index */
bool Object::get(size_t ndx, string& val) const
{
if (obj->rt != List) return false;
//if ((VVec*)obj->vv.size() <= ndx) return false;
Variant* tmp = ((VVec*)obj)->vv[ndx];
if (tmp == NULL) return false;
if (tmp->rt !=String) return false;
val = ((VStr*)tmp)->st;
return true;
}
/** (List) get an Object from this index with default */
bool Object::get(size_t ndx, Object& val, Object& def) const
{
val = def;
return get(ndx,val);
}
/** (List) get an Int from this index */
bool Object::get(size_t ndx, int& val, int def) const
{
val = def;
return get(ndx,val);
}
/** (List) get an Long from this index */
bool Object::get(size_t ndx, long& val, long def) const
{
val = def;
return get(ndx,val);
}
/** (List) get a Float from this index */
bool Object::get(size_t ndx, double& val, double def) const
{
val = def;
return get(ndx,val);
}
/** (List) get a String from this index */
bool Object::get(size_t ndx, string& val, string& def) const
{
val = def;
return get(ndx,val);
}
} // end namespace atlas
<|endoftext|>
|
<commit_before>#include "Halide.h"
#include "copy_2_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <chrono>
#define NN 10
using namespace std;
using namespace std::chrono;
int main(int, char **)
{
// Declare vector input and initialize it with 3
Halide::Buffer<uint8_t> input(NN);
init_buffer(input, (uint8_t)3);
Halide::Buffer<uint8_t> output(NN);
// TRAMISU CODE EXECUTION STARTS:
auto start1 = std::chrono::high_resolution_clock::now();
copy(input.raw_buffer(), output.raw_buffer());
auto end1 = std::chrono::high_resolution_clock::now();
auto duration1 =duration_cast<microseconds>(end1 - start1);
// TRAMISU CODE EXECUTION ENDS.
// REFERENCE Output buffer
Halide::Buffer<uint8_t> expected(NN);
// REFERENCE C++ CODE EXECUTION STARTS
auto start2 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < NN; i++)
{
expected(i) = input(i);
}
// REFERENCE C++ CODE EXECUTION ENDS.
auto end2 = std::chrono::high_resolution_clock::now();
auto duration2 =duration_cast<microseconds>(end2 - start2);
//===== printing REFERECE EXEC TIME: =====
std::cout << "\n REF RESOLUTION TIME : " << duration2.count() << "microseconds";
//===== printing TIRAMISU EXEC TIME: =====
std::cout << "\n TIRAMISU RESOLUTION TIME : " << duration1.count() << "microseconds";
printf("\n");
compare_buffers("copy", output, expected);
return 0;
}
<commit_msg>Delete copy_2_wrapper.cpp<commit_after><|endoftext|>
|
<commit_before>#include <tiramisu/tiramisu.h>
using namespace tiramisu;
#define N 1024
#define M 1024
/**
* Implementation of SYMM Benchmark in Tiramisu :
*
* result = alpha*A*B + beta*C
* or result = alpha*B*A + beta*C with A is symetric
*
* A : a symmetric N by N matrix
* B, C : a N by M matrix
* alpha, beta : scalars
*
*
* The C code is as follow:
* for (i = 0; i < N; i++){
* for (j = 0; j < M; j++){
* temp = 0;
* for (k = 0; k < j - 1; k++){
* C[k][j] += alpha * A[k][i] * B[i][j];
* temp += B[k][j] * A[k][i];
* }
* Result[i][j] = beta * C[i][j] + alpha * A[i][i] * B[i][j] + alpha * temp;
* }
* }
*
**/
int main(int argc, char **argv)
{
tiramisu::init("symm");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// Constants
constant N("N", expr((int32_t) N));
constant M("M", expr((int32_t) M))
// Iteration variables
var i("i", 0, N), j("j", 0, M), k("k", 0, j);
// Scalars
computation alpha("{alpha[0]}", expr());
computation beta("{beta[0]}", expr());
constant a("a", alpha(0));
constant b("b", beta(0));
// Matrix
input B("B", {"k", "j"}, {N, M}, p_float64);
input A("A", {"i", "k"}, {N, N}, p_float64);
input C_0("C_0", {"i", "j"}, {N, M}, p_float64);
// Computations
// Initialisation à 0
computation init("init", {i,j}, expr((p_float64) 0));
// A * B
computation mat_mul_a_b("mat_mul_a_b", {i,j,k}, p_float64);
// a * temp
computation mult_alpha("mult_alpha", {i,j,k}, p_float64);
// Reduction on C
computation C_1("C_1", {i,j,k}, C_0(k-1,j) + mult_alpha(i,j,k));
// B * A
computation mat_mul_b_a("mat_mul_b_a", {i,j,k}, p_float64);
computation mat_mul_a_b_e("mat_mul_a_b_e", {i,j}, p_float64);
computation mult_alpha_k("mult_alpha_k", {i,j}, p_float64);
computation mult_beta("mult_beta", {i,j}, p_float64);
computation add_all("add_all", {i,j}, p_float64);
mat_mul_a_b.set_expression(expr(mat_mul_a_b(i, j, k-1) + A(k, i) * B(i, j)));
mult_alpha.set_expression(expr(alpha(0) * mat_mul_a_b(i, j , j-1)));
mat_mul_b_a.set_expression(expr(mat_mul_b_a(i, j, k-1) + B(k, j) * A(k, i)));
mat_mul_a_b_e.set_expression(expr(A(i, i) * B(i, j)));
mult_alpha_k.set_expression(expr(alpha(0) * mat_mul_a_b_e(i, j)));
mult_beta.set_expression(expr(beta(0) * C_1(i,j, j-1)));
add_all.set_expression(expr(add_all(i,j-1) + mat_mul_a_b_e(i, j) + mult_alpha(i,j, j-1) + mult_beta(i,j)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
add_all.after(mult_beta, j);
mult_beta.after(mult_alpha_k, j);
mult_alpha_k.after(mat_mul_a_b_e, j );
mat_mul_a_b_e.after(mat_mul_b_a, j);
mat_mul_b_a.after(mult_alpha, k);
mult_alpha.after(mat_mul_a_b,k);
mat_mul_a_b.after(init, j);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer buf_A("buf_A", {N,N}, p_float64, a_input);
buffer buf_B("buf_B", {N,M}, p_float64, a_input);
buffer buf_C("buf_C", {N,M}, p_float64, a_input);
buffer buf_alpha("buf_alpha", {1}, p_float64, a_input);
buffer buf_beta("buf_beta", {1}, p_float64, a_input);
buffer buf_result("buf_result", {N,M}, p_float64, a_output);
//Store inputs
A.store_in(&buf_A);
B.store_in(&buf_B);
C_0.store_in(&buf_C);
alpha.store_in(&buf_alpha[0]);
beta.store_in(&buf_beta[0]);
init.store_in(&buf_result, {i,j});
add_all.store_in(&buf_result, {i,j});
C_1.store_in(&buf_result, {i,j});
mult_beta.store_in(&buf_result, {i,j});
mat_mul_a_b_e.store_in(&buf_result, {i,j});
mat_mul_b_a.store_in(&buf_result, {i,j});
mult_alpha.store_in(&buf_result, {i,j});
mat_mul_a_b.store_in(&buf_result, {i,j});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&buf_A, &buf_B, &buf_C, &buf_alpha, &buf_beta, &buf_result}, "generated_symm.o");
return 0;
}
<commit_msg>Remove additional spaces<commit_after>#include <tiramisu/tiramisu.h>
using namespace tiramisu;
/**
* Implementation of SYMM Benchmark in Tiramisu :
*
* result = alpha*A*B + beta*C
* or result = alpha*B*A + beta*C with A is symetric
*
* A : a symmetric N by N matrix
* B, C : a N by M matrix
* alpha, beta : scalars
*
*
* The C code is as follow:
* for (i = 0; i < N; i++){
* for (j = 0; j < M; j++){
* temp = 0;
* for (k = 0; k < j - 1; k++){
* C[k][j] += alpha * A[k][i] * B[i][j];
* temp += B[k][j] * A[k][i];
* }
* Result[i][j] = beta * C[i][j] + alpha * A[i][i] * B[i][j] + alpha * temp;
* }
* }
*
**/
int main(int argc, char **argv)
{
tiramisu::init("symm");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// Constants
constant N("N", expr((int32_t) N));
constant M("M", expr((int32_t) M));
// Iteration variables
var i("i", 0, N), j("j", 0, M), k("k", 0, j);
// Scalars
computation alpha("{alpha[0]}", expr());
computation beta("{beta[0]}", expr());
constant a("a", alpha(0));
constant b("b", beta(0));
// Matrix
input B("B", {"k", "j"}, {N, M}, p_float64);
input A("A", {"i", "k"}, {N, N}, p_float64);
input C_0("C_0", {"i", "j"}, {N, M}, p_float64);
// Computations
// Initialisation à 0
computation init("init", {i,j}, expr((p_float64) 0));
// A * B
computation mat_mul_a_b("mat_mul_a_b", {i,j,k}, p_float64);
// a * temp
computation mult_alpha("mult_alpha", {i,j,k}, p_float64);
// Reduction on C
computation C_1("C_1", {i,j,k}, C_0(k-1,j) + mult_alpha(i,j,k));
// B * A
computation mat_mul_b_a("mat_mul_b_a", {i,j,k}, p_float64);
computation mat_mul_a_b_e("mat_mul_a_b_e", {i,j}, p_float64);
computation mult_alpha_k("mult_alpha_k", {i,j}, p_float64);
computation mult_beta("mult_beta", {i,j}, p_float64);
computation add_all("add_all", {i,j}, p_float64);
mat_mul_a_b.set_expression(expr(mat_mul_a_b(i, j, k-1) + A(k, i) * B(i, j)));
mult_alpha.set_expression(expr(alpha(0) * mat_mul_a_b(i, j , j-1)));
mat_mul_b_a.set_expression(expr(mat_mul_b_a(i, j, k-1) + B(k, j) * A(k, i)));
mat_mul_a_b_e.set_expression(expr(A(i, i) * B(i, j)));
mult_alpha_k.set_expression(expr(alpha(0) * mat_mul_a_b_e(i, j)));
mult_beta.set_expression(expr(beta(0) * C_1(i,j, j-1)));
add_all.set_expression(expr(add_all(i,j-1) + mat_mul_a_b_e(i, j) + mult_alpha(i,j, j-1) + mult_beta(i,j)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
add_all.after(mult_beta, j);
mult_beta.after(mult_alpha_k, j);
mult_alpha_k.after(mat_mul_a_b_e, j);
mat_mul_a_b_e.after(mat_mul_b_a, j);
mat_mul_b_a.after(mult_alpha, k);
mult_alpha.after(mat_mul_a_b,k);
mat_mul_a_b.after(init, j);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer buf_A("buf_A", {N,N}, p_float64, a_input);
buffer buf_B("buf_B", {N,M}, p_float64, a_input);
buffer buf_C("buf_C", {N,M}, p_float64, a_input);
buffer buf_alpha("buf_alpha", {1}, p_float64, a_input);
buffer buf_beta("buf_beta", {1}, p_float64, a_input);
buffer buf_result("buf_result", {N,M}, p_float64, a_output);
//Store inputs
A.store_in(&buf_A);
B.store_in(&buf_B);
C_0.store_in(&buf_C);
alpha.store_in(&buf_alpha[0]);
beta.store_in(&buf_beta[0]);
init.store_in(&buf_result, {i,j});
add_all.store_in(&buf_result, {i,j});
C_1.store_in(&buf_result, {i,j});
mult_beta.store_in(&buf_result, {i,j});
mat_mul_a_b_e.store_in(&buf_result, {i,j});
mat_mul_b_a.store_in(&buf_result, {i,j});
mult_alpha.store_in(&buf_result, {i,j});
mat_mul_a_b.store_in(&buf_result, {i,j});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&buf_A, &buf_B, &buf_C, &buf_alpha, &buf_beta, &buf_result}, "generated_symm.o");
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
#include <string>
#include "ignition/transport/config.hh"
#include "ignition/transport/NetUtils.hh"
#ifdef HAVE_IFADDRS
# include <ifaddrs.h>
#endif
using namespace ignition;
//////////////////////////////////////////////////
bool transport::isPrivateIP(const char *ip)
{
bool b = !strncmp("192.168", ip, 7) || !strncmp("10.", ip, 3) ||
!strncmp("169.254", ip, 7);
return b;
}
//////////////////////////////////////////////////
int transport::hostname_to_ip(char * hostname, std::string &_ip)
{
struct hostent *he;
struct in_addr **addr_list;
int i;
if ((he = gethostbyname(hostname)) == nullptr)
{
// get the host info
herror("gethostbyname");
return 1;
}
addr_list = (struct in_addr **) he->h_addr_list;
for (i = 0; addr_list[i] != nullptr; ++i)
{
// Return the first one;
_ip = std::string(inet_ntoa(*addr_list[i]));
return 0;
}
return 1;
}
//////////////////////////////////////////////////
std::string transport::DetermineHost()
{
char *ip_env;
// First, did the user set DZMQ_IP?
ip_env = std::getenv("DZMQ_IP");
if (ip_env)
{
if (strlen(ip_env) != 0)
return ip_env;
else
std::cerr << "invalid DZMQ_IP (an empty string)" << std::endl;
}
// Second, try the hostname
char host[1024];
memset(host, 0, sizeof(host));
if (gethostname(host, sizeof(host) - 1) != 0)
std::cerr << "determineIP: gethostname failed" << std::endl;
// We don't want localhost to be our ip
else if (strlen(host) && strcmp("localhost", host))
{
std::string hostIP;
strcat(host, ".local");
if (hostname_to_ip(host, hostIP) == 0)
{
return std::string(hostIP);
}
}
// Third, fall back on interface search, which will yield an IP address
#ifdef HAVE_IFADDRS_H
struct ifaddrs *ifa = nullptr, *ifp = NULL;
int rc;
if ((rc = getifaddrs(&ifp)) < 0)
{
std::cerr << "error in getifaddrs: " << strerror(rc) << std::endl;
exit(-1);
}
char preferred_ip[200] = {0};
for (ifa = ifp; ifa; ifa = ifa->ifa_next)
{
char ip_[200];
socklen_t salen;
if (!ifa->ifa_addr)
continue; // evidently this interface has no ip address
if (ifa->ifa_addr->sa_family == AF_INET)
salen = sizeof(struct sockaddr_in);
else if (ifa->ifa_addr->sa_family == AF_INET6)
salen = sizeof(struct sockaddr_in6);
else
continue;
if (getnameinfo(ifa->ifa_addr, salen, ip_, sizeof(ip_), nullptr, 0,
NI_NUMERICHOST) < 0)
{
std::cout << "getnameinfo couldn't get the ip of interface " <<
ifa->ifa_name << std::endl;
continue;
}
// prefer non-private IPs over private IPs
if (!strcmp("127.0.0.1", ip_) || strchr(ip_, ':'))
continue; // ignore loopback unless we have no other choice
if (ifa->ifa_addr->sa_family == AF_INET6 && !preferred_ip[0])
strcpy(preferred_ip, ip_);
else if (isPrivateIP(ip_) && !preferred_ip[0])
strcpy(preferred_ip, ip_);
else if (!isPrivateIP(ip_) &&
(isPrivateIP(preferred_ip) || !preferred_ip[0]))
strcpy(preferred_ip, ip_);
}
freeifaddrs(ifp);
if (!preferred_ip[0])
{
std::cerr <<
"Couldn't find a preferred IP via the getifaddrs() call; "
"I'm assuming that your IP "
"address is 127.0.0.1. This should work for local processes, "
"but will almost certainly not work if you have remote processes."
"Report to the disc-zmq development team to seek a fix." << std::endl;
return std::string("127.0.0.1");
}
return std::string(preferred_ip);
#else
// @todo Fix IP determination in the case where getifaddrs() isn't
// available.
std::cerr <<
"You don't have the getifaddrs() call; I'm assuming that your IP "
"address is 127.0.0.1. This should work for local processes, "
"but will almost certainly not work if you have remote processes."
"Report to the disc-zmq development team to seek a fix." << std::endl;
return std::string("127.0.0.1");
#endif
}
<commit_msg>Tweaking #ifdef<commit_after>/*
* Copyright (C) 2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
#include <string>
#include "ignition/transport/config.hh"
#include "ignition/transport/NetUtils.hh"
#ifdef HAVE_IFADDRS
# include <ifaddrs.h>
#endif
using namespace ignition;
//////////////////////////////////////////////////
bool transport::isPrivateIP(const char *ip)
{
bool b = !strncmp("192.168", ip, 7) || !strncmp("10.", ip, 3) ||
!strncmp("169.254", ip, 7);
return b;
}
//////////////////////////////////////////////////
int transport::hostname_to_ip(char * hostname, std::string &_ip)
{
struct hostent *he;
struct in_addr **addr_list;
int i;
if ((he = gethostbyname(hostname)) == nullptr)
{
// get the host info
herror("gethostbyname");
return 1;
}
addr_list = (struct in_addr **) he->h_addr_list;
for (i = 0; addr_list[i] != nullptr; ++i)
{
// Return the first one;
_ip = std::string(inet_ntoa(*addr_list[i]));
return 0;
}
return 1;
}
//////////////////////////////////////////////////
std::string transport::DetermineHost()
{
char *ip_env;
// First, did the user set DZMQ_IP?
ip_env = std::getenv("DZMQ_IP");
if (ip_env)
{
if (strlen(ip_env) != 0)
return ip_env;
else
std::cerr << "invalid DZMQ_IP (an empty string)" << std::endl;
}
// Second, try the hostname
char host[1024];
memset(host, 0, sizeof(host));
if (gethostname(host, sizeof(host) - 1) != 0)
std::cerr << "determineIP: gethostname failed" << std::endl;
// We don't want localhost to be our ip
else if (strlen(host) && strcmp("localhost", host))
{
std::string hostIP;
strcat(host, ".local");
if (hostname_to_ip(host, hostIP) == 0)
{
return std::string(hostIP);
}
}
// Third, fall back on interface search, which will yield an IP address
#ifdef HAVE_IFADDRS
struct ifaddrs *ifa = nullptr, *ifp = NULL;
int rc;
if ((rc = getifaddrs(&ifp)) < 0)
{
std::cerr << "error in getifaddrs: " << strerror(rc) << std::endl;
exit(-1);
}
char preferred_ip[200] = {0};
for (ifa = ifp; ifa; ifa = ifa->ifa_next)
{
char ip_[200];
socklen_t salen;
if (!ifa->ifa_addr)
continue; // evidently this interface has no ip address
if (ifa->ifa_addr->sa_family == AF_INET)
salen = sizeof(struct sockaddr_in);
else if (ifa->ifa_addr->sa_family == AF_INET6)
salen = sizeof(struct sockaddr_in6);
else
continue;
if (getnameinfo(ifa->ifa_addr, salen, ip_, sizeof(ip_), nullptr, 0,
NI_NUMERICHOST) < 0)
{
std::cout << "getnameinfo couldn't get the ip of interface " <<
ifa->ifa_name << std::endl;
continue;
}
// prefer non-private IPs over private IPs
if (!strcmp("127.0.0.1", ip_) || strchr(ip_, ':'))
continue; // ignore loopback unless we have no other choice
if (ifa->ifa_addr->sa_family == AF_INET6 && !preferred_ip[0])
strcpy(preferred_ip, ip_);
else if (isPrivateIP(ip_) && !preferred_ip[0])
strcpy(preferred_ip, ip_);
else if (!isPrivateIP(ip_) &&
(isPrivateIP(preferred_ip) || !preferred_ip[0]))
strcpy(preferred_ip, ip_);
}
freeifaddrs(ifp);
if (!preferred_ip[0])
{
std::cerr <<
"Couldn't find a preferred IP via the getifaddrs() call; "
"I'm assuming that your IP "
"address is 127.0.0.1. This should work for local processes, "
"but will almost certainly not work if you have remote processes."
"Report to the disc-zmq development team to seek a fix." << std::endl;
return std::string("127.0.0.1");
}
return std::string(preferred_ip);
#else
// @todo Fix IP determination in the case where getifaddrs() isn't
// available.
std::cerr <<
"You don't have the getifaddrs() call; I'm assuming that your IP "
"address is 127.0.0.1. This should work for local processes, "
"but will almost certainly not work if you have remote processes."
"Report to the disc-zmq development team to seek a fix." << std::endl;
return std::string("127.0.0.1");
#endif
}
<|endoftext|>
|
<commit_before>/**
* @author : xiaozhuai
* @date : 17/1/3
*/
#include "../include/Request.h"
namespace CXXUrl {
Request::Request() :
followLocation(true),
contentOutput(NULL),
headerOutput(NULL),
maxRedirs(-1),
form(NULL),
referer(""),
header(NULL) {
userAgent = string("") + "CXXUrl/" + CXX_URL_VERSION + " " + curl_version();
}
Request::~Request() {
}
size_t Request::writeContent(char *buffer, size_t size, size_t count, void *stream) {
((ostream *) stream)->write(buffer, size * count);
// printf("data recieved: %d,%s\n", size*count, buffer);
return size * count;
}
size_t Request::writeHeader(char *buffer, size_t size, size_t count, void *stream) {
((ostream *) stream)->write(buffer, size * count);
return size * count;
}
void Request::setContentOutput(ostream *stream) {
contentOutput = stream;
}
void Request::setHeaderOutput(ostream *stream) {
headerOutput = stream;
}
ostream *Request::getContentOutput() {
return contentOutput;
}
ostream *Request::getHeaderOutput() {
return headerOutput;
}
void Request::setUrl(string url) {
this->url = url;
}
string Request::getUrl() {
return url;
}
void Request::setFollowLocation(bool followLocation) {
this->followLocation = followLocation;
}
bool Request::getFollowLocation() {
return followLocation;
}
void Request::setMaxRedirs(int maxRedirs) {
this->maxRedirs = maxRedirs;
}
int Request::getMaxRedirs() {
return maxRedirs;
}
void Request::setForm(Form *form) {
this->form = form;
}
Form *Request::getForm() {
return form;
}
void Request::setUserAgent(string userAgent) {
this->userAgent = userAgent;
}
string Request::getUserAgent() {
return userAgent;
}
void Request::setReferer(string referer) {
this->referer = referer;
}
string Request::getReferer() {
return referer;
}
void Request::setHeader(Header *header) {
this->header = header;
}
Header* Request::getHeader() {
return header;
}
CURLcode Request::get() {
return exec(GET);
}
CURLcode Request::post() {
return exec(POST);
}
CURLcode Request::exec(METHOD_TYPE method) {
curl = curl_easy_init();
SET_CURL_OPT(CURLOPT_URL, url.c_str());
// SET_CURL_OPT(CURLOPT_VERBOSE, 1);
if (method == POST) {
SET_CURL_OPT(CURLOPT_POST, 1);
if (form == NULL)
SET_CURL_OPT(CURLOPT_POSTFIELDS, "");
else {
switch (form->type){
case Form::SIMPLE: {
SimpleForm *simpleForm = (SimpleForm *) form;
SET_CURL_OPT(CURLOPT_POSTFIELDS, simpleForm->getData());
SET_CURL_OPT(CURLOPT_POSTFIELDSIZE, simpleForm->length());
break;
}
case Form::MULTIPART: {
MultipartForm *multipartForm = (MultipartForm *) form;
SET_CURL_OPT(CURLOPT_HTTPPOST, multipartForm->getData());
break;
}
case Form::RAW: {
RawForm *rawForm = (RawForm *) form;
SET_CURL_OPT(CURLOPT_POSTFIELDS, rawForm->getData());
SET_CURL_OPT(CURLOPT_POSTFIELDSIZE, rawForm->length());
break;
}
default:
cerr << "form type unknown" << endl;
break;
}
}
}
SET_CURL_OPT(CURLOPT_FOLLOWLOCATION, followLocation);
SET_CURL_OPT(CURLOPT_USERAGENT, userAgent.c_str());
if(referer!=""){
SET_CURL_OPT(CURLOPT_REFERER, referer.c_str());
}
if(header!=NULL){
SET_CURL_OPT(CURLOPT_HTTPHEADER, header->getHeaders());
}
if (maxRedirs != -1)
SET_CURL_OPT(CURLOPT_MAXREDIRS, maxRedirs);
if (contentOutput != NULL) {
SET_CURL_OPT(CURLOPT_WRITEFUNCTION, writeContent);
SET_CURL_OPT(CURLOPT_WRITEDATA, contentOutput);
}
if (headerOutput != NULL) {
SET_CURL_OPT(CURLOPT_HEADERFUNCTION, writeHeader);
SET_CURL_OPT(CURLOPT_HEADERDATA, headerOutput);
}
CURLcode res;
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
}<commit_msg>method choose<commit_after>/**
* @author : xiaozhuai
* @date : 17/1/3
*/
#include "../include/Request.h"
namespace CXXUrl {
Request::Request() :
followLocation(true),
contentOutput(NULL),
headerOutput(NULL),
maxRedirs(-1),
form(NULL),
referer(""),
header(NULL) {
userAgent = string("") + "CXXUrl/" + CXX_URL_VERSION + " " + curl_version();
}
Request::~Request() {
}
size_t Request::writeContent(char *buffer, size_t size, size_t count, void *stream) {
((ostream *) stream)->write(buffer, size * count);
// printf("data recieved: %d,%s\n", size*count, buffer);
return size * count;
}
size_t Request::writeHeader(char *buffer, size_t size, size_t count, void *stream) {
((ostream *) stream)->write(buffer, size * count);
return size * count;
}
void Request::setContentOutput(ostream *stream) {
contentOutput = stream;
}
void Request::setHeaderOutput(ostream *stream) {
headerOutput = stream;
}
ostream *Request::getContentOutput() {
return contentOutput;
}
ostream *Request::getHeaderOutput() {
return headerOutput;
}
void Request::setUrl(string url) {
this->url = url;
}
string Request::getUrl() {
return url;
}
void Request::setFollowLocation(bool followLocation) {
this->followLocation = followLocation;
}
bool Request::getFollowLocation() {
return followLocation;
}
void Request::setMaxRedirs(int maxRedirs) {
this->maxRedirs = maxRedirs;
}
int Request::getMaxRedirs() {
return maxRedirs;
}
void Request::setForm(Form *form) {
this->form = form;
}
Form *Request::getForm() {
return form;
}
void Request::setUserAgent(string userAgent) {
this->userAgent = userAgent;
}
string Request::getUserAgent() {
return userAgent;
}
void Request::setReferer(string referer) {
this->referer = referer;
}
string Request::getReferer() {
return referer;
}
void Request::setHeader(Header *header) {
this->header = header;
}
Header* Request::getHeader() {
return header;
}
CURLcode Request::get() {
return exec(GET);
}
CURLcode Request::post() {
return exec(POST);
}
CURLcode Request::exec(METHOD_TYPE method) {
curl = curl_easy_init();
SET_CURL_OPT(CURLOPT_URL, url.c_str());
// SET_CURL_OPT(CURLOPT_VERBOSE, 1);
switch (method){
case GET: {
SET_CURL_OPT(CURLOPT_HTTPGET, 1);
break;
}
case POST: {
SET_CURL_OPT(CURLOPT_POST, 1);
if (form == NULL) {
SET_CURL_OPT(CURLOPT_POSTFIELDS, "");
SET_CURL_OPT(CURLOPT_POSTFIELDSIZE, 0);
} else {
switch (form->type){
case Form::SIMPLE: {
SimpleForm *simpleForm = (SimpleForm *) form;
SET_CURL_OPT(CURLOPT_POSTFIELDS, simpleForm->getData());
SET_CURL_OPT(CURLOPT_POSTFIELDSIZE, simpleForm->length());
break;
}
case Form::MULTIPART: {
MultipartForm *multipartForm = (MultipartForm *) form;
SET_CURL_OPT(CURLOPT_HTTPPOST, multipartForm->getData());
break;
}
case Form::RAW: {
RawForm *rawForm = (RawForm *) form;
SET_CURL_OPT(CURLOPT_POSTFIELDS, rawForm->getData());
SET_CURL_OPT(CURLOPT_POSTFIELDSIZE, rawForm->length());
break;
}
default:
cerr << "form type unknown" << endl;
break;
}
}
break;
}
default:
cerr << "unknown method" << endl;
}
SET_CURL_OPT(CURLOPT_FOLLOWLOCATION, followLocation);
SET_CURL_OPT(CURLOPT_USERAGENT, userAgent.c_str());
if(referer!=""){
SET_CURL_OPT(CURLOPT_REFERER, referer.c_str());
}
if(header!=NULL){
SET_CURL_OPT(CURLOPT_HTTPHEADER, header->getHeaders());
}
if (maxRedirs != -1)
SET_CURL_OPT(CURLOPT_MAXREDIRS, maxRedirs);
if (contentOutput != NULL) {
SET_CURL_OPT(CURLOPT_WRITEFUNCTION, writeContent);
SET_CURL_OPT(CURLOPT_WRITEDATA, contentOutput);
}
if (headerOutput != NULL) {
SET_CURL_OPT(CURLOPT_HEADERFUNCTION, writeHeader);
SET_CURL_OPT(CURLOPT_HEADERDATA, headerOutput);
}
CURLcode res;
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
}<|endoftext|>
|
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <list>
#include <algorithm>
#include <nix/Section.hpp>
using namespace std;
using namespace nix;
Section::Section()
: NamedEntity()
{
}
Section::Section(nullptr_t ptr)
: NamedEntity()
{
}
Section::Section(const Section &other)
: NamedEntity(other.impl())
{
}
Section::Section(const shared_ptr<base::ISection> &p_impl)
: NamedEntity(p_impl)
{
}
Section::Section(shared_ptr<base::ISection> &&ptr)
: NamedEntity(std::move(ptr))
{
}
void Section::link(const Section &link) {
if (link == none) {
backend()->link(none);
} else {
backend()->link(link.id());
}
}
//-----------------------------------------------------
// Methods concerning child sections
//-----------------------------------------------------
bool Section::hasSection(const Section §ion) const {
if (section == none) {
throw std::runtime_error("Section::hasSection: Empty Section entity given!");
}
return backend()->hasSection(section.id());
}
bool Section::deleteSection(const Section §ion) {
if (section == none) {
throw std::runtime_error("Section::deleteSection: Empty Section entity given!");
}
return backend()->deleteSection(section.id());
}
/*
* Helper struct for {@link findSections}.
*/
struct SectionCont {
SectionCont(Section s, size_t d = 0)
: entity(s), depth(d)
{}
Section entity;
size_t depth;
};
std::vector<Section> Section::sections(const util::Filter<Section>::type &filter) const {
auto f = [this] (size_t i) { return getSection(i); };
return getEntities<Section>(f,
sectionCount(),
filter);
}
std::vector<Section> Section::findSections(const util::Filter<Section>::type &filter,
size_t max_depth) const
{
std::vector<Section> results;
std::list<SectionCont> todo;
todo.push_back(SectionCont(*this));
while (todo.size() > 0)
{
SectionCont current = todo.front();
todo.pop_front();
bool filter_ok = filter(current.entity);
if (filter_ok) {
results.push_back(current.entity);
}
if (current.depth < max_depth) {
std::vector<Section> children = current.entity.sections();
size_t next_depth = current.depth + 1;
for (auto it = children.begin(); it != children.end(); ++it) {
todo.push_back(SectionCont(*it, next_depth));
}
}
}
return results;
}
static inline auto erase_section_with_id(vector<Section> §ions, const string &my_id)
-> decltype(sections.size())
{
sections.erase(remove_if(sections.begin(),
sections.end(),
[&my_id](const Section §ion) {
return my_id == section.id();
}),
sections.end());
return sections.size();
}
std::vector<Section> Section::findRelated(const util::Filter<Section>::type &filter) const
{
std::vector<Section> results = findDownstream(filter);
const string &my_id = id();
//This checking of results can be removed if we decide not to include this in findSection
auto results_size = erase_section_with_id(results, my_id);
if (results_size == 0) {
results = findUpstream(filter);
}
//This checking of results can be removed if we decide not to include this in findSection
results_size = erase_section_with_id(results, my_id);
if (results_size == 0) {
results = findSideways(filter, id());
}
return results;
}
//-----------------------------------------------------
// Methods for property access
//-----------------------------------------------------
bool Section::hasProperty(const Property &property) const {
if (property == none) {
throw std::runtime_error("Section::hasProperty: Empty Property entity given!");
}
return backend()->hasProperty(property.id());
}
std::vector<Property> Section::properties(const util::Filter<Property>::type &filter) const {
auto f = [this] (size_t i) { return getProperty(i); };
return getEntities<Property>(f,
propertyCount(),
filter);
}
bool Section::deleteProperty(const Property &property) {
if (property == none) {
throw std::runtime_error("Section::deleteProperty: Empty Property entity given!");
}
return backend()->deleteProperty(property.id());
}
vector<Property> Section::inheritedProperties() const {
vector<Property> own = properties();
if (link() == nullptr)
return own;
const vector<Property> linked = link().properties();
copy_if (linked.begin(), linked.end(),
back_inserter(own),
[&own](const Property &linked_prop) {
return find_if (own.begin(), own.end(),
[&linked_prop](const Property &own_prop) {
return linked_prop.name() == own_prop.name();
}) == own.end();
});
return own;
}
//------------------------------------------------------
// Operators and other functions
//------------------------------------------------------
size_t Section::tree_depth() const{
const vector<Section> children = sections();
size_t depth = 0;
if (children.size() > 0) {
for (auto &child : children) {
depth = max(depth, child.tree_depth());
}
depth += 1;
}
return depth;
}
vector<Section> Section::findDownstream(const std::function<bool(Section)> &filter) const{
vector<Section> results;
size_t max_depth = tree_depth();
size_t actual_depth = 1;
while (results.size() == 0 && actual_depth <= max_depth) {
results = findSections(filter, actual_depth);
actual_depth += 1;
}
return results;
}
vector<Section> Section::findUpstream(const std::function<bool(Section)> &filter) const{
vector<Section> results;
Section p = parent();
if (p != nullptr) {
results = p.findSections(filter,1);
if (results.size() > 0) {
return results;
}
return p.findUpstream(filter);
}
return results;
}
vector<Section> Section::findSideways(const std::function<bool(Section)> &filter, const string &caller_id) const{
vector<Section> results;
Section p = parent();
if (p != nullptr) {
results = p.findSections(filter,1);
if (results.size() > 0) {
results.erase(remove_if(results.begin(),
results.end(),
[&caller_id](const Section §ion) {
return section.id() == caller_id;
}),
results.end());
return results;
}
return p.findSideways(filter, caller_id);
}
return results;
}
std::ostream& nix::operator<<(ostream &out, const Section &ent) {
out << "Section: {name = " << ent.name();
out << ", type = " << ent.type();
out << ", id = " << ent.id() << "}";
return out;
}
<commit_msg>Section: add <iterator> include<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <list>
#include <algorithm>
#include <iterator>
#include <nix/Section.hpp>
using namespace std;
using namespace nix;
Section::Section()
: NamedEntity()
{
}
Section::Section(nullptr_t ptr)
: NamedEntity()
{
}
Section::Section(const Section &other)
: NamedEntity(other.impl())
{
}
Section::Section(const shared_ptr<base::ISection> &p_impl)
: NamedEntity(p_impl)
{
}
Section::Section(shared_ptr<base::ISection> &&ptr)
: NamedEntity(std::move(ptr))
{
}
void Section::link(const Section &link) {
if (link == none) {
backend()->link(none);
} else {
backend()->link(link.id());
}
}
//-----------------------------------------------------
// Methods concerning child sections
//-----------------------------------------------------
bool Section::hasSection(const Section §ion) const {
if (section == none) {
throw std::runtime_error("Section::hasSection: Empty Section entity given!");
}
return backend()->hasSection(section.id());
}
bool Section::deleteSection(const Section §ion) {
if (section == none) {
throw std::runtime_error("Section::deleteSection: Empty Section entity given!");
}
return backend()->deleteSection(section.id());
}
/*
* Helper struct for {@link findSections}.
*/
struct SectionCont {
SectionCont(Section s, size_t d = 0)
: entity(s), depth(d)
{}
Section entity;
size_t depth;
};
std::vector<Section> Section::sections(const util::Filter<Section>::type &filter) const {
auto f = [this] (size_t i) { return getSection(i); };
return getEntities<Section>(f,
sectionCount(),
filter);
}
std::vector<Section> Section::findSections(const util::Filter<Section>::type &filter,
size_t max_depth) const
{
std::vector<Section> results;
std::list<SectionCont> todo;
todo.push_back(SectionCont(*this));
while (todo.size() > 0)
{
SectionCont current = todo.front();
todo.pop_front();
bool filter_ok = filter(current.entity);
if (filter_ok) {
results.push_back(current.entity);
}
if (current.depth < max_depth) {
std::vector<Section> children = current.entity.sections();
size_t next_depth = current.depth + 1;
for (auto it = children.begin(); it != children.end(); ++it) {
todo.push_back(SectionCont(*it, next_depth));
}
}
}
return results;
}
static inline auto erase_section_with_id(vector<Section> §ions, const string &my_id)
-> decltype(sections.size())
{
sections.erase(remove_if(sections.begin(),
sections.end(),
[&my_id](const Section §ion) {
return my_id == section.id();
}),
sections.end());
return sections.size();
}
std::vector<Section> Section::findRelated(const util::Filter<Section>::type &filter) const
{
std::vector<Section> results = findDownstream(filter);
const string &my_id = id();
//This checking of results can be removed if we decide not to include this in findSection
auto results_size = erase_section_with_id(results, my_id);
if (results_size == 0) {
results = findUpstream(filter);
}
//This checking of results can be removed if we decide not to include this in findSection
results_size = erase_section_with_id(results, my_id);
if (results_size == 0) {
results = findSideways(filter, id());
}
return results;
}
//-----------------------------------------------------
// Methods for property access
//-----------------------------------------------------
bool Section::hasProperty(const Property &property) const {
if (property == none) {
throw std::runtime_error("Section::hasProperty: Empty Property entity given!");
}
return backend()->hasProperty(property.id());
}
std::vector<Property> Section::properties(const util::Filter<Property>::type &filter) const {
auto f = [this] (size_t i) { return getProperty(i); };
return getEntities<Property>(f,
propertyCount(),
filter);
}
bool Section::deleteProperty(const Property &property) {
if (property == none) {
throw std::runtime_error("Section::deleteProperty: Empty Property entity given!");
}
return backend()->deleteProperty(property.id());
}
vector<Property> Section::inheritedProperties() const {
vector<Property> own = properties();
if (link() == nullptr)
return own;
const vector<Property> linked = link().properties();
copy_if (linked.begin(), linked.end(),
back_inserter(own),
[&own](const Property &linked_prop) {
return find_if (own.begin(), own.end(),
[&linked_prop](const Property &own_prop) {
return linked_prop.name() == own_prop.name();
}) == own.end();
});
return own;
}
//------------------------------------------------------
// Operators and other functions
//------------------------------------------------------
size_t Section::tree_depth() const{
const vector<Section> children = sections();
size_t depth = 0;
if (children.size() > 0) {
for (auto &child : children) {
depth = max(depth, child.tree_depth());
}
depth += 1;
}
return depth;
}
vector<Section> Section::findDownstream(const std::function<bool(Section)> &filter) const{
vector<Section> results;
size_t max_depth = tree_depth();
size_t actual_depth = 1;
while (results.size() == 0 && actual_depth <= max_depth) {
results = findSections(filter, actual_depth);
actual_depth += 1;
}
return results;
}
vector<Section> Section::findUpstream(const std::function<bool(Section)> &filter) const{
vector<Section> results;
Section p = parent();
if (p != nullptr) {
results = p.findSections(filter,1);
if (results.size() > 0) {
return results;
}
return p.findUpstream(filter);
}
return results;
}
vector<Section> Section::findSideways(const std::function<bool(Section)> &filter, const string &caller_id) const{
vector<Section> results;
Section p = parent();
if (p != nullptr) {
results = p.findSections(filter,1);
if (results.size() > 0) {
results.erase(remove_if(results.begin(),
results.end(),
[&caller_id](const Section §ion) {
return section.id() == caller_id;
}),
results.end());
return results;
}
return p.findSideways(filter, caller_id);
}
return results;
}
std::ostream& nix::operator<<(ostream &out, const Section &ent) {
out << "Section: {name = " << ent.name();
out << ", type = " << ent.type();
out << ", id = " << ent.id() << "}";
return out;
}
<|endoftext|>
|
<commit_before>#include "../header/int/Texture.h"
#include "../header/ext/EasyBMP.h"
Texture::Texture(){
fileName = "";
this->pixelData = NULL;
}
Texture::Texture(int _width, int _height){
fileName = "";
width = _width;
height = _height;
textureTarget = GL_TEXTURE_2D;
pixelData = new RGBApixel[width*height];
glGenTextures(1, &textureObj);
Apply();
}
Texture::Texture(GLenum TextureTarget, const std::string& _fileName){
textureTarget = TextureTarget;
fileName = _fileName;
pixelData = NULL;
}
//Requires OpenGL context
void Texture::Load(void){
BMP image;
image.ReadFromFile(fileName.c_str());
width = image.TellWidth();
height = image.TellHeight();
pixelData = new RGBApixel[width*height];
for(int j = 0; j < height; j++){
for(int i = 0; i < width; i++){
pixelData[j*width+i] = image.GetPixel(i,j);
}
}
glGenTextures(1, &textureObj);
Apply();
}
void Texture::SetPixel(int x, int y, float r, float g, float b){
RGBApixel pix;
pix.Red = (unsigned char)(255*r);
pix.Green = (unsigned char)(255*g);
pix.Blue = (unsigned char)(255*b);
pix.Alpha = 255;
int index = y * width + x;
pixelData[index] = pix;
}
void Texture::SetPixel(int x, int y, RGBApixel col){
int index = y * width + x;
pixelData[index] = col;
}
void Texture::GetPixel(int x, int y){
//Not implemented yet.
}
void Texture::Apply(){
if(pixelData != NULL){
glBindTexture(textureTarget, textureObj);
glTexImage2D(textureTarget, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelData);
glTexParameterf(textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
void Texture::Bind(GLenum TextureUnit){
glActiveTexture(TextureUnit);
glBindTexture(textureTarget, textureObj);
}
Texture::~Texture(){
fileName="";
if(pixelData != NULL){
delete[] pixelData;
}
}<commit_msg>Changed texture import from RGBA to BGRA.<commit_after>#include "../header/int/Texture.h"
#include "../header/ext/EasyBMP.h"
Texture::Texture(){
fileName = "";
this->pixelData = NULL;
}
Texture::Texture(int _width, int _height){
fileName = "";
width = _width;
height = _height;
textureTarget = GL_TEXTURE_2D;
pixelData = new RGBApixel[width*height];
glGenTextures(1, &textureObj);
Apply();
}
Texture::Texture(GLenum TextureTarget, const std::string& _fileName){
textureTarget = TextureTarget;
fileName = _fileName;
pixelData = NULL;
}
//Requires OpenGL context
void Texture::Load(void){
BMP image;
image.ReadFromFile(fileName.c_str());
width = image.TellWidth();
height = image.TellHeight();
pixelData = new RGBApixel[width*height];
for(int j = 0; j < height; j++){
for(int i = 0; i < width; i++){
pixelData[j*width+i] = image.GetPixel(i,j);
}
}
glGenTextures(1, &textureObj);
Apply();
}
void Texture::SetPixel(int x, int y, float r, float g, float b){
RGBApixel pix;
pix.Red = (unsigned char)(255*r);
pix.Green = (unsigned char)(255*g);
pix.Blue = (unsigned char)(255*b);
pix.Alpha = 255;
int index = y * width + x;
pixelData[index] = pix;
}
void Texture::SetPixel(int x, int y, RGBApixel col){
int index = y * width + x;
pixelData[index] = col;
}
void Texture::GetPixel(int x, int y){
//Not implemented yet.
}
void Texture::Apply(){
if(pixelData != NULL){
glBindTexture(textureTarget, textureObj);
glTexImage2D(textureTarget, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, pixelData);
glTexParameterf(textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
void Texture::Bind(GLenum TextureUnit){
glActiveTexture(TextureUnit);
glBindTexture(textureTarget, textureObj);
}
Texture::~Texture(){
fileName="";
if(pixelData != NULL){
delete[] pixelData;
}
}<|endoftext|>
|
<commit_before>/**
* @file attrmap.cpp
* @brief Class for manipulating node attributes
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/attrmap.h"
namespace mega {
// approximate raw storage size of serialized AttrMap, not taking JSON escaping
// or name length into account
unsigned AttrMap::storagesize(int perrecord) const
{
assert(perrecord >= 0);
unsigned t = 0;
for (attr_map::const_iterator it = map.begin(); it != map.end(); it++)
{
t += static_cast<unsigned>(perrecord + it->second.size());
}
return t;
}
int AttrMap::nameid2string(nameid id, char* buf)
{
char* ptr = buf;
for (int i = 64; (i -= 8) >= 0;)
{
if ((*ptr = static_cast<char>( (id >> i) & 0xff)))
{
ptr++;
}
}
return static_cast<int>(ptr - buf);
}
string AttrMap::nameid2string(nameid id)
{
string s;
s.resize(10);
s.resize(nameid2string(id, const_cast<char*>(s.data())));
return s;
}
nameid AttrMap::string2nameid(const char *a)
{
if (!a)
{
return 0;
}
size_t len = strlen(a);
if (len > 8)
{
return 0;
}
switch (len)
{
case 1:
return *a;
case 2:
return MAKENAMEID2(a[0], a[1]);
case 3:
return MAKENAMEID3(a[0], a[1], a[2]);
case 4:
return MAKENAMEID4(a[0], a[1], a[2], a[3]);
case 5:
return MAKENAMEID5(a[0], a[1], a[2], a[3], a[4]);
case 6:
return MAKENAMEID6(a[0], a[1], a[2], a[3], a[4], a[5]);
case 7:
return MAKENAMEID7(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
case 8:
return MAKENAMEID8(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
default:
break;
}
return 0;
}
// generate binary serialize of attr_map name-value pairs
void AttrMap::serialize(string* d) const
{
char buf[8];
unsigned char l;
unsigned short ll;
for (attr_map::const_iterator it = map.begin(); it != map.end(); it++)
{
if ((l = (unsigned char)nameid2string(it->first, buf)))
{
d->append((char*)&l, sizeof l);
d->append(buf, l);
ll = (unsigned short)it->second.size();
d->append((char*)&ll, sizeof ll);
d->append(it->second.data(), ll);
}
}
d->append("", 1);
}
// read binary serialize, return final offset
const char* AttrMap::unserialize(const char* ptr , const char *end)
{
unsigned char l;
unsigned short ll;
nameid id;
while ((ptr < end) && (l = *ptr++))
{
id = 0;
if (ptr + l + sizeof ll > end)
{
return NULL;
}
while (l--)
{
id = (id << 8) + (unsigned char)*ptr++;
}
ll = MemAccess::get<short>(ptr);
ptr += sizeof ll;
if (ptr + ll > end)
{
return NULL;
}
map[id].assign(ptr, ll);
ptr += ll;
}
return ptr;
}
bool AttrMap::hasUpdate(const attr_map& updates, nameid attrId) const
{
auto curIt = map.find(attrId);
auto updIt = updates.find(attrId);
return curIt != map.end() && (updIt == updates.end() || curIt->second != updIt->second);
}
void AttrMap::applyUpdates(const attr_map& updates)
{
for (auto& u : updates)
{
if (u.second.empty()) map.erase(u.first);
else map[u.first] = u.second;
}
}
// generate JSON object containing attr_map
void AttrMap::getjson(string* s) const
{
nameid id;
char buf[8];
const char* ptr;
const char* pptr;
// reserve estimated size of final string
s->erase();
s->reserve(storagesize(20));
for (attr_map::const_iterator it = map.begin(); it != map.end(); it++)
{
s->append(s->size() ? ",\"" : "\"");
if ((id = it->first))
{
// no JSON escaping here, as no escape characters are allowed in
// attribute names
s->append(buf, nameid2string(id, buf));
s->append("\":\"");
// JSON-escape value
pptr = it->second.c_str();
ptr = it->second.c_str();
for (int i = static_cast<int>(it->second.size()); i-- >= 0; ptr++)
{
if ((i < 0) || ((*(const signed char*)ptr >= 0) && (*ptr < ' ')) || (*ptr == '"') || (*ptr == '\\'))
{
if (ptr > pptr)
{
s->append(pptr, ptr - pptr);
}
if (i >= 0)
{
s->append("\\");
switch (*ptr)
{
case '"':
s->append("\"");
break;
case '\\':
s->append("\\");
break;
case '\n':
s->append("n");
break;
case '\r':
s->append("r");
break;
case '\b':
s->append("b");
break;
case '\f':
s->append("f");
break;
case '\t':
s->append("t");
break;
default:
s->append("u00");
sprintf(buf, "%02x", (unsigned char)*ptr);
s->append(buf);
}
pptr = ptr + 1;
}
}
}
s->append("\"");
}
}
}
} // namespace
<commit_msg>Add comment to explain confusing update of AttrMap<commit_after>/**
* @file attrmap.cpp
* @brief Class for manipulating node attributes
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/attrmap.h"
namespace mega {
// approximate raw storage size of serialized AttrMap, not taking JSON escaping
// or name length into account
unsigned AttrMap::storagesize(int perrecord) const
{
assert(perrecord >= 0);
unsigned t = 0;
for (attr_map::const_iterator it = map.begin(); it != map.end(); it++)
{
t += static_cast<unsigned>(perrecord + it->second.size());
}
return t;
}
int AttrMap::nameid2string(nameid id, char* buf)
{
char* ptr = buf;
for (int i = 64; (i -= 8) >= 0;)
{
if ((*ptr = static_cast<char>( (id >> i) & 0xff)))
{
ptr++;
}
}
return static_cast<int>(ptr - buf);
}
string AttrMap::nameid2string(nameid id)
{
string s;
s.resize(10);
s.resize(nameid2string(id, const_cast<char*>(s.data())));
return s;
}
nameid AttrMap::string2nameid(const char *a)
{
if (!a)
{
return 0;
}
size_t len = strlen(a);
if (len > 8)
{
return 0;
}
switch (len)
{
case 1:
return *a;
case 2:
return MAKENAMEID2(a[0], a[1]);
case 3:
return MAKENAMEID3(a[0], a[1], a[2]);
case 4:
return MAKENAMEID4(a[0], a[1], a[2], a[3]);
case 5:
return MAKENAMEID5(a[0], a[1], a[2], a[3], a[4]);
case 6:
return MAKENAMEID6(a[0], a[1], a[2], a[3], a[4], a[5]);
case 7:
return MAKENAMEID7(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
case 8:
return MAKENAMEID8(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
default:
break;
}
return 0;
}
// generate binary serialize of attr_map name-value pairs
void AttrMap::serialize(string* d) const
{
char buf[8];
unsigned char l;
unsigned short ll;
for (attr_map::const_iterator it = map.begin(); it != map.end(); it++)
{
if ((l = (unsigned char)nameid2string(it->first, buf)))
{
d->append((char*)&l, sizeof l);
d->append(buf, l);
ll = (unsigned short)it->second.size();
d->append((char*)&ll, sizeof ll);
d->append(it->second.data(), ll);
}
}
d->append("", 1);
}
// read binary serialize, return final offset
const char* AttrMap::unserialize(const char* ptr , const char *end)
{
unsigned char l;
unsigned short ll;
nameid id;
while ((ptr < end) && (l = *ptr++))
{
id = 0;
if (ptr + l + sizeof ll > end)
{
return NULL;
}
while (l--)
{
id = (id << 8) + (unsigned char)*ptr++;
}
ll = MemAccess::get<short>(ptr);
ptr += sizeof ll;
if (ptr + ll > end)
{
return NULL;
}
map[id].assign(ptr, ll);
ptr += ll;
}
return ptr;
}
bool AttrMap::hasUpdate(const attr_map& updates, nameid attrId) const
{
// An attribute will only be touched if it was included in `updates` map.
// Even for removing it, it should be present there with an empty value.
auto curIt = map.find(attrId);
auto updIt = updates.find(attrId);
return curIt != map.end() && (updIt == updates.end() || curIt->second != updIt->second);
}
void AttrMap::applyUpdates(const attr_map& updates)
{
for (auto& u : updates)
{
if (u.second.empty()) map.erase(u.first);
else map[u.first] = u.second;
}
}
// generate JSON object containing attr_map
void AttrMap::getjson(string* s) const
{
nameid id;
char buf[8];
const char* ptr;
const char* pptr;
// reserve estimated size of final string
s->erase();
s->reserve(storagesize(20));
for (attr_map::const_iterator it = map.begin(); it != map.end(); it++)
{
s->append(s->size() ? ",\"" : "\"");
if ((id = it->first))
{
// no JSON escaping here, as no escape characters are allowed in
// attribute names
s->append(buf, nameid2string(id, buf));
s->append("\":\"");
// JSON-escape value
pptr = it->second.c_str();
ptr = it->second.c_str();
for (int i = static_cast<int>(it->second.size()); i-- >= 0; ptr++)
{
if ((i < 0) || ((*(const signed char*)ptr >= 0) && (*ptr < ' ')) || (*ptr == '"') || (*ptr == '\\'))
{
if (ptr > pptr)
{
s->append(pptr, ptr - pptr);
}
if (i >= 0)
{
s->append("\\");
switch (*ptr)
{
case '"':
s->append("\"");
break;
case '\\':
s->append("\\");
break;
case '\n':
s->append("n");
break;
case '\r':
s->append("r");
break;
case '\b':
s->append("b");
break;
case '\f':
s->append("f");
break;
case '\t':
s->append("t");
break;
default:
s->append("u00");
sprintf(buf, "%02x", (unsigned char)*ptr);
s->append(buf);
}
pptr = ptr + 1;
}
}
}
s->append("\"");
}
}
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright 2010, Camilo Aguilar. Cloudescape, LLC.
#include "bindings.h"
/* size of the event structure, not counting name */
#define EVENT_SIZE (sizeof (struct inotify_event))
/* reasonable guess as to size of 1024 events */
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
namespace NodeInotify {
static Persistent<String> path_sym;
static Persistent<String> watch_for_sym;
static Persistent<String> callback_sym;
static Persistent<String> persistent_sym;
static Persistent<String> watch_sym;
static Persistent<String> mask_sym;
static Persistent<String> cookie_sym;
static Persistent<String> name_sym;
void Inotify::Initialize(Handle<Object> target) {
Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New);
t->Inherit(EventEmitter::constructor_template);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "addWatch",
Inotify::AddWatch);
NODE_SET_PROTOTYPE_METHOD(t, "removeWatch",
Inotify::RemoveWatch);
NODE_SET_PROTOTYPE_METHOD(t, "close",
Inotify::Close);
//Constants initialization
NODE_DEFINE_CONSTANT(t, IN_ACCESS); //File was accessed (read)
NODE_DEFINE_CONSTANT(t, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps,
//extended attributes, link count (since Linux 2.6.25),
//UID, GID, etc.
NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); //File opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); //File not opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CREATE); //File/directory created in watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE); //File/directory deleted from watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); //Watched file/directory was itself deleted
NODE_DEFINE_CONSTANT(t, IN_MODIFY); //File was modified
NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); //Watched file/directory was itself moved
NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); //File moved out of watched directory
NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); //File moved into watched directory
NODE_DEFINE_CONSTANT(t, IN_OPEN); //File was opened
NODE_DEFINE_CONSTANT(t, IN_IGNORED); // Watch was removed explicitly (inotify.watch.rm) or
//automatically (file was deleted, or file system was
//unmounted)
NODE_DEFINE_CONSTANT(t, IN_ISDIR); //Subject of this event is a directory
NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event)
NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); //File system containing watched object was unmounted
NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS);
NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); // Only watch the path if it is a directory.
NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); // Do not follow a sym link
NODE_DEFINE_CONSTANT(t, IN_ONESHOT); // Only send event once
NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it
//already exists (instead of replacing mask).
NODE_DEFINE_CONSTANT(t, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close
NODE_DEFINE_CONSTANT(t, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves
path_sym = NODE_PSYMBOL("path");
watch_for_sym = NODE_PSYMBOL("watch_for");
callback_sym = NODE_PSYMBOL("callback");
persistent_sym = NODE_PSYMBOL("persistent");
watch_sym = NODE_PSYMBOL("watch");
mask_sym = NODE_PSYMBOL("mask");
cookie_sym = NODE_PSYMBOL("cookie");
name_sym = NODE_PSYMBOL("name");
Local<ObjectTemplate> object_tmpl = t->InstanceTemplate();
object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent);
t->SetClassName(String::NewSymbol("Inotify"));
target->Set(String::NewSymbol("Inotify"), t->GetFunction());
}
Inotify::Inotify() : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = true;
}
Inotify::Inotify(bool nonpersistent) : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = nonpersistent;
}
Inotify::~Inotify() {
if(!persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &read_watcher);
assert(!ev_is_active(&read_watcher));
assert(!ev_is_pending(&read_watcher));
}
Handle<Value> Inotify::New(const Arguments& args) {
HandleScope scope;
Inotify *inotify = NULL;
if(args.Length() == 1 && args[0]->IsBoolean()) {
inotify = new Inotify(args[0]->IsTrue());
} else {
inotify = new Inotify();
}
inotify->fd = inotify_init();
if(inotify->fd == -1) {
ThrowException(String::New(strerror(errno)));
return Null();
}
int flags = fcntl(inotify->fd, F_GETFL);
if(flags == -1) {
flags = 0;
}
fcntl(inotify->fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ);
ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher);
Local<Object> obj = args.This();
inotify->Wrap(obj);
if(!inotify->persistent) {
ev_unref(EV_DEFAULT_UC);
}
/*Increment object references to avoid be GCed while
I'm waiting for inotify events in th ev_pool.
Also, the object is not weak anymore */
inotify->Ref();
return scope.Close(obj);
}
Handle<Value> Inotify::AddWatch(const Arguments& args) {
HandleScope scope;
uint32_t mask = 0;
int watch_descriptor = 0;
if(args.Length() < 1 || !args[0]->IsObject()) {
return ThrowException(Exception::TypeError(
String::New("You must specify an object as first argument")));
}
Local<Object> args_ = args[0]->ToObject();
if(!args_->Has(path_sym)) {
return ThrowException(Exception::TypeError(
String::New("You must specify a path to watch for events")));
}
if(!args_->Has(callback_sym) ||
!args_->Get(callback_sym)->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a callback function")));
}
if(!args_->Has(watch_for_sym)) {
mask |= IN_ALL_EVENTS;
} else {
if(!args_->Get(watch_for_sym)->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
mask |= args_->Get(watch_for_sym)->Int32Value();
if(mask == 0) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
}
String::Utf8Value path(args_->Get(path_sym));
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
/* add watch */
watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask);
Local<Integer> descriptor = Integer::New(watch_descriptor);
//Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym));
inotify->handle_->Set(descriptor, args_->Get(callback_sym));
return scope.Close(descriptor);
}
Handle<Value> Inotify::RemoveWatch(const Arguments& args) {
HandleScope scope;
uint32_t watch = 0;
int ret = -1;
if(args.Length() == 0 || !args[0]->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a valid watcher descriptor as argument")));
}
watch = args[0]->Int32Value();
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = inotify_rm_watch(inotify->fd, watch);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
return True();
}
Handle<Value> Inotify::Close(const Arguments& args) {
HandleScope scope;
int ret = -1;
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = close(inotify->fd);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
if(!inotify->persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher);
/*Eliminating reference created inside of Inotify::New.
The object is also weak again.
Now v8 can do its stuff and GC the object.
*/
inotify->Unref();
return True();
}
void Inotify::Callback(EV_P_ ev_io *watcher, int revents) {
HandleScope scope;
Inotify *inotify = static_cast<Inotify*>(watcher->data);
assert(watcher == &inotify->read_watcher);
char buffer[BUF_LEN];
//int length = read(inotify->fd, buffer, BUF_LEN);
Local<Value> argv[1];
TryCatch try_catch;
int i = 0;
while (i < read(inotify->fd, buffer, BUF_LEN)) {
struct inotify_event *event;
event = (struct inotify_event *) &buffer[i];
Local<Object> obj = Object::New();
obj->Set(watch_sym, Integer::New(event->wd));
obj->Set(mask_sym, Integer::New(event->mask));
obj->Set(cookie_sym, Integer::New(event->cookie));
if(event->len) {
obj->Set(name_sym, String::New(event->name));
}
argv[0] = obj;
inotify->Ref();
Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd));
Local<Function> callback = Local<Function>::Cast(callback_);
callback->Call(inotify->handle_, 1, argv);
inotify->Unref();
if(event->mask & IN_IGNORED) {
//deleting callback because the watch was removed
Local<Value> wd = Integer::New(event->wd);
inotify->handle_->Delete(wd->ToString());
}
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
i += EVENT_SIZE + event->len;
}
}
Handle<Value> Inotify::GetPersistent(Local<String> property,
const AccessorInfo& info) {
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This());
return inotify->persistent ? True() : False();
}
}//namespace NodeInotify
<commit_msg>adds compatibility with kernels versions under 2.6.23, O_CLOEXEC is not important in nodejs context since there is always just one thread accessing files.<commit_after>// Copyright 2010, Camilo Aguilar. Cloudescape, LLC.
#include "bindings.h"
/* size of the event structure, not counting name */
#define EVENT_SIZE (sizeof (struct inotify_event))
/* reasonable guess as to size of 1024 events */
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
namespace NodeInotify {
static Persistent<String> path_sym;
static Persistent<String> watch_for_sym;
static Persistent<String> callback_sym;
static Persistent<String> persistent_sym;
static Persistent<String> watch_sym;
static Persistent<String> mask_sym;
static Persistent<String> cookie_sym;
static Persistent<String> name_sym;
void Inotify::Initialize(Handle<Object> target) {
Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New);
t->Inherit(EventEmitter::constructor_template);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "addWatch",
Inotify::AddWatch);
NODE_SET_PROTOTYPE_METHOD(t, "removeWatch",
Inotify::RemoveWatch);
NODE_SET_PROTOTYPE_METHOD(t, "close",
Inotify::Close);
//Constants initialization
NODE_DEFINE_CONSTANT(t, IN_ACCESS); //File was accessed (read)
NODE_DEFINE_CONSTANT(t, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps,
//extended attributes, link count (since Linux 2.6.25),
//UID, GID, etc.
NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); //File opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); //File not opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CREATE); //File/directory created in watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE); //File/directory deleted from watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); //Watched file/directory was itself deleted
NODE_DEFINE_CONSTANT(t, IN_MODIFY); //File was modified
NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); //Watched file/directory was itself moved
NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); //File moved out of watched directory
NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); //File moved into watched directory
NODE_DEFINE_CONSTANT(t, IN_OPEN); //File was opened
NODE_DEFINE_CONSTANT(t, IN_IGNORED); // Watch was removed explicitly (inotify.watch.rm) or
//automatically (file was deleted, or file system was
//unmounted)
NODE_DEFINE_CONSTANT(t, IN_ISDIR); //Subject of this event is a directory
NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event)
NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); //File system containing watched object was unmounted
NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS);
NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); // Only watch the path if it is a directory.
NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); // Do not follow a sym link
NODE_DEFINE_CONSTANT(t, IN_ONESHOT); // Only send event once
NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it
//already exists (instead of replacing mask).
NODE_DEFINE_CONSTANT(t, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close
NODE_DEFINE_CONSTANT(t, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves
path_sym = NODE_PSYMBOL("path");
watch_for_sym = NODE_PSYMBOL("watch_for");
callback_sym = NODE_PSYMBOL("callback");
persistent_sym = NODE_PSYMBOL("persistent");
watch_sym = NODE_PSYMBOL("watch");
mask_sym = NODE_PSYMBOL("mask");
cookie_sym = NODE_PSYMBOL("cookie");
name_sym = NODE_PSYMBOL("name");
Local<ObjectTemplate> object_tmpl = t->InstanceTemplate();
object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent);
t->SetClassName(String::NewSymbol("Inotify"));
target->Set(String::NewSymbol("Inotify"), t->GetFunction());
}
Inotify::Inotify() : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = true;
}
Inotify::Inotify(bool nonpersistent) : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = nonpersistent;
}
Inotify::~Inotify() {
if(!persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &read_watcher);
assert(!ev_is_active(&read_watcher));
assert(!ev_is_pending(&read_watcher));
}
Handle<Value> Inotify::New(const Arguments& args) {
HandleScope scope;
Inotify *inotify = NULL;
if(args.Length() == 1 && args[0]->IsBoolean()) {
inotify = new Inotify(args[0]->IsTrue());
} else {
inotify = new Inotify();
}
inotify->fd = inotify_init();
if(inotify->fd == -1) {
ThrowException(String::New(strerror(errno)));
return Null();
}
int flags = fcntl(inotify->fd, F_GETFL);
if(flags == -1) {
flags = 0;
}
fcntl(inotify->fd, F_SETFL, flags | O_NONBLOCK);
ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ);
ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher);
Local<Object> obj = args.This();
inotify->Wrap(obj);
if(!inotify->persistent) {
ev_unref(EV_DEFAULT_UC);
}
/*Increment object references to avoid be GCed while
I'm waiting for inotify events in th ev_pool.
Also, the object is not weak anymore */
inotify->Ref();
return scope.Close(obj);
}
Handle<Value> Inotify::AddWatch(const Arguments& args) {
HandleScope scope;
uint32_t mask = 0;
int watch_descriptor = 0;
if(args.Length() < 1 || !args[0]->IsObject()) {
return ThrowException(Exception::TypeError(
String::New("You must specify an object as first argument")));
}
Local<Object> args_ = args[0]->ToObject();
if(!args_->Has(path_sym)) {
return ThrowException(Exception::TypeError(
String::New("You must specify a path to watch for events")));
}
if(!args_->Has(callback_sym) ||
!args_->Get(callback_sym)->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a callback function")));
}
if(!args_->Has(watch_for_sym)) {
mask |= IN_ALL_EVENTS;
} else {
if(!args_->Get(watch_for_sym)->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
mask |= args_->Get(watch_for_sym)->Int32Value();
if(mask == 0) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
}
String::Utf8Value path(args_->Get(path_sym));
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
/* add watch */
watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask);
Local<Integer> descriptor = Integer::New(watch_descriptor);
//Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym));
inotify->handle_->Set(descriptor, args_->Get(callback_sym));
return scope.Close(descriptor);
}
Handle<Value> Inotify::RemoveWatch(const Arguments& args) {
HandleScope scope;
uint32_t watch = 0;
int ret = -1;
if(args.Length() == 0 || !args[0]->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a valid watcher descriptor as argument")));
}
watch = args[0]->Int32Value();
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = inotify_rm_watch(inotify->fd, watch);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
return True();
}
Handle<Value> Inotify::Close(const Arguments& args) {
HandleScope scope;
int ret = -1;
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = close(inotify->fd);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
if(!inotify->persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher);
/*Eliminating reference created inside of Inotify::New.
The object is also weak again.
Now v8 can do its stuff and GC the object.
*/
inotify->Unref();
return True();
}
void Inotify::Callback(EV_P_ ev_io *watcher, int revents) {
HandleScope scope;
Inotify *inotify = static_cast<Inotify*>(watcher->data);
assert(watcher == &inotify->read_watcher);
char buffer[BUF_LEN];
//int length = read(inotify->fd, buffer, BUF_LEN);
Local<Value> argv[1];
TryCatch try_catch;
int i = 0;
while (i < read(inotify->fd, buffer, BUF_LEN)) {
struct inotify_event *event;
event = (struct inotify_event *) &buffer[i];
Local<Object> obj = Object::New();
obj->Set(watch_sym, Integer::New(event->wd));
obj->Set(mask_sym, Integer::New(event->mask));
obj->Set(cookie_sym, Integer::New(event->cookie));
if(event->len) {
obj->Set(name_sym, String::New(event->name));
}
argv[0] = obj;
inotify->Ref();
Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd));
Local<Function> callback = Local<Function>::Cast(callback_);
callback->Call(inotify->handle_, 1, argv);
inotify->Unref();
if(event->mask & IN_IGNORED) {
//deleting callback because the watch was removed
Local<Value> wd = Integer::New(event->wd);
inotify->handle_->Delete(wd->ToString());
}
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
i += EVENT_SIZE + event->len;
}
}
Handle<Value> Inotify::GetPersistent(Local<String> property,
const AccessorInfo& info) {
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This());
return inotify->persistent ? True() : False();
}
}//namespace NodeInotify
<|endoftext|>
|
<commit_before>#ifndef _C4_LIST_HPP_
#define _C4_LIST_HPP_
#include "c4/config.hpp"
#include "c4/error.hpp"
#include "c4/storage/raw.hpp"
#include <iterator>
C4_BEGIN_NAMESPACE(c4)
template< class T, class I=C4_SIZE_TYPE >
using default_list_storage = stg::raw_paged_rt< T, I >;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class split_list;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class split_fwd_list;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class flat_list;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class flat_fwd_list;
template< class T, class I=C4_SIZE_TYPE > struct flat_list_elm;
template< class T, class I=C4_SIZE_TYPE > struct flat_fwd_list_elm;
//-----------------------------------------------------------------------------
template< class T, class I >
struct flat_list_elm
{
T elm;
I prev;
I next;
};
template< class T, class I >
struct flat_fwd_list_elm
{
T elm;
I next;
};
//-----------------------------------------------------------------------------
template< class T, class List >
struct fwd_list_iterator : public std::iterator< std::forward_iterator_tag, typename List::value_type >
{
using I = typename List::size_type;
List *list;
I i;
fwd_list_iterator(List *l, I i_) : list(l), i(i_) {}
C4_ALWAYS_INLINE T* operator-> () { return &list->elm(i); }
C4_ALWAYS_INLINE T& operator* () { return list->elm(i); }
C4_ALWAYS_INLINE fwd_list_iterator& operator++ ( ) noexcept { i = list->next(i); return *this; }
C4_ALWAYS_INLINE fwd_list_iterator& operator++ (int) noexcept { fwd_list_iterator it = *this; i = list->next(i); return it; }
C4_ALWAYS_INLINE bool operator== (fwd_list_iterator const& that) const noexcept { return i == that.i && list == that.list; }
C4_ALWAYS_INLINE bool operator!= (fwd_list_iterator const& that) const noexcept { return i != that.i || list != that.list; }
};
template< class T, class List >
struct list_iterator : public std::iterator< std::bidirectional_iterator_tag, typename List::value_type >
{
using I = typename List::size_type;
List *list;
I i;
list_iterator(List *l, I i_) : list(l), i(i_) {}
C4_ALWAYS_INLINE T& operator* () { return list->elm(i); }
C4_ALWAYS_INLINE T* operator-> () { return &list->elm(i); }
C4_ALWAYS_INLINE list_iterator& operator++ ( ) noexcept { i = list->next(i); return *this; }
C4_ALWAYS_INLINE list_iterator& operator++ (int) noexcept { list_iterator it = *this; i = list->next(i); return it; }
C4_ALWAYS_INLINE list_iterator& operator-- ( ) noexcept { i = list->prev(i); return *this; }
C4_ALWAYS_INLINE list_iterator& operator-- (int) noexcept { list_iterator it = *this; i = list->prev(i); return it; }
C4_ALWAYS_INLINE bool operator== (list_iterator const& that) const noexcept { return i == that.i && list == that.list; }
C4_ALWAYS_INLINE bool operator!= (list_iterator const& that) const noexcept { return i != that.i || list != that.list; }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class split_list
{
public:
RawStorage< T, I > m_elm;
RawStorage< I, I > m_prev;
RawStorage< I, I > m_next;
I m_head;
I m_tail;
I m_size;
I m_fhead;
enum : I { npos = static_cast< I >(-1) };
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, split_list >;
using const_iterator = list_iterator< const T, const split_list >;
public:
split_list() : m_elm(), m_prev(), m_next(), m_head(0), m_tail(0), m_size(0), m_fhead(0) {}
void _init_seq()
{
C4_ASSERT(m_elm.capacity() == m_prev.capacity() && m_elm.capacity() == m_next.capacity());
I cap = m_elm.capacity();
if(cap == 0) return;
m_prev[0] = npos;
for(I i = 1; i < cap-1; ++i)
{
m_prev[i] = i - 1;
}
m_next[0] = 1;
for(I i = 1; i < cap-1; ++i)
{
m_next[i] = i + 1;
}
if(cap < 2) return;
m_prev[cap - 1] = cap - 2;
m_next[cap - 1] = npos;
}
void _growto(I next_cap)
{
}
public:
C4_ALWAYS_INLINE I size() const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elm.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE I prev(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_prev[i]; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_next[i]; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
public:
void push_back(T const& var)
{
I cap = capacity();
if(size() == cap)
{
_growto(cap, cap+1);
}
I pos = m_fhead;
C4_XASSERT(pos != npos && pos < m_size);
c4::construct(&m_elm[pos], var);
m_prev[pos] = m_tail;
m_next[pos] = npos;
m_tail = pos;
C4_XASSERT(m_fhead != npos);
m_fhead = m_next[m_fhead];
++m_size;
}
void push_front(T const& var)
{
}
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class flat_list
{
public:
RawStorage< flat_list_elm<T, I>, I > m_elms;
I m_head;
I m_tail;
I m_size;
I m_fhead;
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, flat_list >;
using const_iterator = list_iterator< const T, const flat_list >;
public:
flat_list() : m_elms(), m_head(0), m_tail(0), m_size(0), m_fhead(0) {}
public:
C4_ALWAYS_INLINE I size() const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elms.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].elm; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].elm; }
C4_ALWAYS_INLINE I prev(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].prev; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].next; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class split_fwd_list
{
public:
RawStorage< T, I > m_elm;
RawStorage< I, I > m_next;
I m_head;
I m_tail;
I m_size;
I m_fhead;
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, split_fwd_list >;
using const_iterator = list_iterator< const T, const split_fwd_list >;
public:
split_fwd_list() : m_elm(), m_next(), m_head(0), m_tail(0), m_size(0), m_fhead(0) {}
public:
C4_ALWAYS_INLINE I size() const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elm.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_next[i]; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class flat_fwd_list
{
public:
RawStorage< flat_fwd_list_elm<T, I>, I > m_elms;
I m_head;
I m_tail;
I m_size;
I m_fhead;
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, flat_fwd_list >;
using const_iterator = list_iterator< const T, const flat_fwd_list >;
public:
flat_fwd_list() : m_elms(), m_head(0), m_tail(0), m_size(0), m_fhead(0) {}
public:
C4_ALWAYS_INLINE I size() const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elm.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_elm.size()); return m_elms[i].elm; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_elm.size()); return m_elms[i].elm; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_next.size()); return m_next[i].next; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
};
C4_END_NAMESPACE(c4)
#endif /* _C4_LIST_HPP_ */
<commit_msg>list: change the order to (flat, split)x(doubly,fwd)<commit_after>#ifndef _C4_LIST_HPP_
#define _C4_LIST_HPP_
#include "c4/config.hpp"
#include "c4/error.hpp"
#include "c4/storage/raw.hpp"
#include <iterator>
C4_BEGIN_NAMESPACE(c4)
template< class T, class I=C4_SIZE_TYPE >
using default_list_storage = stg::raw_paged_rt< T, I >;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class split_list;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class split_fwd_list;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class flat_list;
template< class T, class I=C4_SIZE_TYPE, template< class T_, class I_ > class LinearStorage=default_list_storage >
class flat_fwd_list;
template< class T, class I=C4_SIZE_TYPE > struct flat_list_elm;
template< class T, class I=C4_SIZE_TYPE > struct flat_fwd_list_elm;
//-----------------------------------------------------------------------------
template< class T, class I >
struct flat_list_elm
{
T elm;
I prev;
I next;
};
template< class T, class I >
struct flat_fwd_list_elm
{
T elm;
I next;
};
//-----------------------------------------------------------------------------
template< class T, class List >
struct list_iterator : public std::iterator< std::bidirectional_iterator_tag, typename List::value_type >
{
using I = typename List::size_type;
List *list;
I i;
list_iterator(List *l, I i_) : list(l), i(i_) {}
C4_ALWAYS_INLINE T& operator* () { return list->elm(i); }
C4_ALWAYS_INLINE T* operator-> () { return &list->elm(i); }
C4_ALWAYS_INLINE list_iterator& operator++ ( ) noexcept { i = list->next(i); return *this; }
C4_ALWAYS_INLINE list_iterator& operator++ (int) noexcept { list_iterator it = *this; i = list->next(i); return it; }
C4_ALWAYS_INLINE list_iterator& operator-- ( ) noexcept { i = list->prev(i); return *this; }
C4_ALWAYS_INLINE list_iterator& operator-- (int) noexcept { list_iterator it = *this; i = list->prev(i); return it; }
C4_ALWAYS_INLINE bool operator== (list_iterator const& that) const noexcept { return i == that.i && list == that.list; }
C4_ALWAYS_INLINE bool operator!= (list_iterator const& that) const noexcept { return i != that.i || list != that.list; }
};
template< class T, class List >
struct fwd_list_iterator : public std::iterator< std::forward_iterator_tag, typename List::value_type >
{
using I = typename List::size_type;
List *list;
I i;
fwd_list_iterator(List *l, I i_) : list(l), i(i_) {}
C4_ALWAYS_INLINE T* operator-> () { return &list->elm(i); }
C4_ALWAYS_INLINE T& operator* () { return list->elm(i); }
C4_ALWAYS_INLINE fwd_list_iterator& operator++ ( ) noexcept { i = list->next(i); return *this; }
C4_ALWAYS_INLINE fwd_list_iterator& operator++ (int) noexcept { fwd_list_iterator it = *this; i = list->next(i); return it; }
C4_ALWAYS_INLINE bool operator== (fwd_list_iterator const& that) const noexcept { return i == that.i && list == that.list; }
C4_ALWAYS_INLINE bool operator!= (fwd_list_iterator const& that) const noexcept { return i != that.i || list != that.list; }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class flat_list
{
public:
RawStorage< flat_list_elm<T, I>, I > m_elms;
I m_head;
I m_tail;
I m_size;
I m_fhead;
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, flat_list >;
using const_iterator = list_iterator< const T, const flat_list >;
public:
flat_list() : m_elms(), m_head(0), m_tail(0), m_size(0), m_fhead(0) {}
public:
C4_ALWAYS_INLINE I size () const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elms.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].elm; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].elm; }
C4_ALWAYS_INLINE I prev(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].prev; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i].next; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class split_list
{
public:
RawStorage< T, I > m_elm;
RawStorage< I, I > m_prev;
RawStorage< I, I > m_next;
I m_head;
I m_tail;
I m_size;
I m_fhead; //< the head of the free list (the list containing free elements)
enum : I { npos = static_cast< I >(-1) };
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, split_list >;
using const_iterator = list_iterator< const T, const split_list >;
public:
split_list() : m_elm(), m_prev(), m_next(), m_head(0), m_tail(0), m_size(0), m_fhead(0)
{
_init_seq(0, capacity());
}
split_list(c4::with_capacity_t, I cap) : m_elm(cap), m_prev(cap), m_next(cap), m_head(0), m_tail(0), m_size(0), m_fhead(0)
{
_init_seq(0, capacity());
}
split_list(c4::aggregate_t, std::initializer_list< T > il) : m_elm(szconv< I >(il.size())), m_prev(szconv< I >(il.size())), m_next(szconv< I >(il.size())), m_head(0), m_tail(0), m_size(0), m_fhead(0)
{
_init_seq(0, capacity());
}
void _growto(I next_cap)
{
I curr = capacity();
m_elm._raw_reserve(next_cap);
m_prev._raw_reserve(next_cap);
m_next._raw_reserve(next_cap);
_init_seq(curr, next_cap);
}
void _init_seq(I first, I last)
{
C4_ASSERT(m_elm.capacity() == m_prev.capacity() && m_elm.capacity() == m_next.capacity());
I cap = m_elm.capacity();
if(cap == 0) return;
m_prev[0] = npos;
for(I i = 1; i < cap; ++i)
{
m_prev[i] = i - 1;
}
for(I i = 0; i < cap-1; ++i) // cap must be > 0 at this point
{
m_next[i] = i + 1;
}
m_next[cap - 1] = npos;
}
public:
C4_ALWAYS_INLINE I size() const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elm.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE I prev(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_prev[i]; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_next[i]; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
public:
void push_back(T const& var)
{
I cap = capacity();
if(size() == cap)
{
_growto(cap, cap+1);
}
I pos = m_fhead;
C4_XASSERT(pos != npos && pos < m_size);
c4::construct(&m_elm[pos], var);
m_prev[pos] = m_tail;
m_next[pos] = npos;
m_tail = pos;
C4_XASSERT(m_fhead != npos);
m_fhead = m_next[m_fhead];
++m_size;
}
void push_front(T const& var)
{
}
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class flat_fwd_list
{
public:
RawStorage< flat_fwd_list_elm<T, I>, I > m_elms;
I m_head;
I m_tail;
I m_size;
I m_fhead;
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, flat_fwd_list >;
using const_iterator = list_iterator< const T, const flat_fwd_list >;
public:
flat_fwd_list() : m_elms(), m_head(0), m_tail(0), m_size(0), m_fhead(0) {}
public:
C4_ALWAYS_INLINE I size() const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elm.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_elm.size()); return m_elms[i].elm; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_elm.size()); return m_elms[i].elm; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_next.size()); return m_next[i].next; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template< class T, class I, template< class T, class I > class RawStorage >
class split_fwd_list
{
public:
RawStorage< T, I > m_elm;
RawStorage< I, I > m_next;
I m_head;
I m_tail;
I m_size;
I m_fhead;
public:
using value_type = T;
using size_type = I;
using iterator = list_iterator< T, split_fwd_list >;
using const_iterator = list_iterator< const T, const split_fwd_list >;
public:
split_fwd_list() : m_elm(), m_next(), m_head(0), m_tail(0), m_size(0), m_fhead(0) {}
public:
C4_ALWAYS_INLINE I size() const noexcept { return m_size; }
C4_ALWAYS_INLINE I capacity() const noexcept { return m_elm.capacity(); }
C4_ALWAYS_INLINE T & elm(I i) C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE T const& elm(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_elms[i]; }
C4_ALWAYS_INLINE I next(I i) const C4_NOEXCEPT_X { C4_XASSERT(i < m_size); return m_next[i]; }
C4_ALWAYS_INLINE iterator begin() noexcept { return iterator(this, m_head); }
C4_ALWAYS_INLINE iterator end () noexcept { return iterator(this, m_tail); }
C4_ALWAYS_INLINE const_iterator begin() const noexcept { return const_iterator(this, m_head); }
C4_ALWAYS_INLINE const_iterator end () const noexcept { return const_iterator(this, m_tail); }
};
C4_END_NAMESPACE(c4)
#endif /* _C4_LIST_HPP_ */
<|endoftext|>
|
<commit_before>#include "canread.h"
#include <stdlib.h>
float decodeCanSignal(CanSignal* signal, uint64_t data) {
uint64_t rawValue = getBitField(data, signal->bitPosition,
signal->bitSize);
return rawValue * signal->factor + signal->offset;
}
float passthroughHandler(CanSignal* signal, CanSignal* signals, int signalCount,
float value, bool* send) {
return value;
}
bool booleanHandler(CanSignal* signal, CanSignal* signals, int signalCount,
float value, bool* send) {
return value == 0.0 ? false : true;
}
float ignoreHandler(CanSignal* signal, CanSignal* signals, int signalCount,
float value, bool* send) {
*send = false;
return value;
}
const char* stateHandler(CanSignal* signal, CanSignal* signals,
int signalCount, float value, bool* send) {
CanSignalState* signalState = lookupSignalState(value, signal, signals,
signalCount);
if(signalState != NULL) {
return signalState->name;
}
*send = false;
return NULL;
}
/* Private: Serialize the root JSON object to a string (ending with a newline)
* and send it to the listener.
*
* root - The JSON object to send.
* listener - The listener device to send on.
*/
void sendJSON(cJSON* root, Listener* listener) {
char* message = cJSON_PrintUnformatted(root);
sendMessage(listener, (uint8_t*) message, strlen(message));
cJSON_Delete(root);
free(message);
}
/* Private: Combine the given name and value into a JSON object (conforming to
* the OpenXC standard) and send it out to the listener.
*
* name - The value for the name field of the OpenXC message.
* value - The numerical, string or booelan for the value field of the OpenXC
* message.
* event - (Optional) The event for the event field of the OpenXC message.
* listener - The listener device to send on.
*/
void sendJSONMessage(const char* name, cJSON* value, cJSON* event,
Listener* listener) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, NAME_FIELD_NAME, name);
cJSON_AddItemToObject(root, VALUE_FIELD_NAME, value);
if(event != NULL) {
cJSON_AddItemToObject(root, EVENT_FIELD_NAME, event);
}
sendJSON(root, listener);
}
void sendNumericalMessage(const char* name, float value, Listener* listener) {
sendJSONMessage(name, cJSON_CreateNumber(value), NULL, listener);
}
void sendBooleanMessage(const char* name, bool value, Listener* listener) {
sendJSONMessage(name, cJSON_CreateBool(value), NULL, listener);
}
void sendStringMessage(const char* name, const char* value,
Listener* listener) {
sendJSONMessage(name, cJSON_CreateString(value), NULL, listener);
}
void sendEventedBooleanMessage(const char* name, const char* value, bool event,
Listener* listener) {
sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateBool(event),
listener);
}
void sendEventedStringMessage(const char* name, const char* value,
const char* event, Listener* listener) {
sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateString(event),
listener);
}
void passthroughCanMessage(Listener* listener, int id, uint64_t data) {
cJSON *root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, ID_FIELD_NAME, id);
char encodedData[67];
union {
uint64_t whole;
uint8_t bytes[8];
} combined;
combined.whole = data;
sprintf(encodedData, "0x%02x %02x %02x %02x %02x %02x %02x %02x",
combined.bytes[0],
combined.bytes[1],
combined.bytes[2],
combined.bytes[3],
combined.bytes[4],
combined.bytes[5],
combined.bytes[6],
combined.bytes[7]);
cJSON_AddStringToObject(root, NAME_FIELD_NAME, encodedData);
sendJSON(root, listener);
}
// TODO there is lots of duplicated code in these functions, but I don't see an
// obvious way to share code and still keep the different data types returned
// by the handlers.
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data,
float (*handler)(CanSignal*, CanSignal*, int, float, bool*),
CanSignal* signals, int signalCount) {
float value = decodeCanSignal(signal, data);
bool send = true;
float processedValue = handler(signal, signals, signalCount, value, &send);
if(signal->sendClock == signal->sendFrequency) {
if(send && (signal->sendSame || !signal->received ||
value != signal->lastValue)) {
signal->received = true;
sendNumericalMessage(signal->genericName, processedValue, listener);
}
signal->sendClock = 0;
} else {
++signal->sendClock;
}
signal->lastValue = value;
}
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data,
const char* (*handler)(CanSignal*, CanSignal*, int, float, bool*),
CanSignal* signals, int signalCount) {
float value = decodeCanSignal(signal, data);
bool send = true;
const char* stringValue = handler(signal, signals, signalCount, value,
&send);
if(signal->sendClock == signal->sendFrequency) {
if(send && (signal->sendSame || !signal->received ||
value != signal->lastValue)) {
signal->received = true;
sendStringMessage(signal->genericName, stringValue, listener);
}
signal->sendClock = 0;
} else {
++signal->sendClock;
}
signal->lastValue = value;
}
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data,
bool (*handler)(CanSignal*, CanSignal*, int, float, bool*),
CanSignal* signals, int signalCount) {
float value = decodeCanSignal(signal, data);
bool send = true;
bool booleanValue = handler(signal, signals, signalCount, value, &send);
if(signal->sendClock == signal->sendFrequency) {
if(send && (signal->sendSame || !signal->received ||
value != signal->lastValue)) {
signal->received = true;
sendBooleanMessage(signal->genericName, booleanValue, listener);
}
signal->sendClock = 0;
} else {
++signal->sendClock;
}
signal->lastValue = value;
}
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data, CanSignal* signals, int signalCount) {
translateCanSignal(listener, signal, data, passthroughHandler, signals,
signalCount);
}
<commit_msg>Remove spaces from output in passthrough handlers. Works with mpide-newlib.<commit_after>#include "canread.h"
#include <stdlib.h>
float decodeCanSignal(CanSignal* signal, uint64_t data) {
uint64_t rawValue = getBitField(data, signal->bitPosition,
signal->bitSize);
return rawValue * signal->factor + signal->offset;
}
float passthroughHandler(CanSignal* signal, CanSignal* signals, int signalCount,
float value, bool* send) {
return value;
}
bool booleanHandler(CanSignal* signal, CanSignal* signals, int signalCount,
float value, bool* send) {
return value == 0.0 ? false : true;
}
float ignoreHandler(CanSignal* signal, CanSignal* signals, int signalCount,
float value, bool* send) {
*send = false;
return value;
}
const char* stateHandler(CanSignal* signal, CanSignal* signals,
int signalCount, float value, bool* send) {
CanSignalState* signalState = lookupSignalState(value, signal, signals,
signalCount);
if(signalState != NULL) {
return signalState->name;
}
*send = false;
return NULL;
}
/* Private: Serialize the root JSON object to a string (ending with a newline)
* and send it to the listener.
*
* root - The JSON object to send.
* listener - The listener device to send on.
*/
void sendJSON(cJSON* root, Listener* listener) {
char* message = cJSON_PrintUnformatted(root);
sendMessage(listener, (uint8_t*) message, strlen(message));
cJSON_Delete(root);
free(message);
}
/* Private: Combine the given name and value into a JSON object (conforming to
* the OpenXC standard) and send it out to the listener.
*
* name - The value for the name field of the OpenXC message.
* value - The numerical, string or booelan for the value field of the OpenXC
* message.
* event - (Optional) The event for the event field of the OpenXC message.
* listener - The listener device to send on.
*/
void sendJSONMessage(const char* name, cJSON* value, cJSON* event,
Listener* listener) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, NAME_FIELD_NAME, name);
cJSON_AddItemToObject(root, VALUE_FIELD_NAME, value);
if(event != NULL) {
cJSON_AddItemToObject(root, EVENT_FIELD_NAME, event);
}
sendJSON(root, listener);
}
void sendNumericalMessage(const char* name, float value, Listener* listener) {
sendJSONMessage(name, cJSON_CreateNumber(value), NULL, listener);
}
void sendBooleanMessage(const char* name, bool value, Listener* listener) {
sendJSONMessage(name, cJSON_CreateBool(value), NULL, listener);
}
void sendStringMessage(const char* name, const char* value,
Listener* listener) {
sendJSONMessage(name, cJSON_CreateString(value), NULL, listener);
}
void sendEventedBooleanMessage(const char* name, const char* value, bool event,
Listener* listener) {
sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateBool(event),
listener);
}
void sendEventedStringMessage(const char* name, const char* value,
const char* event, Listener* listener) {
sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateString(event),
listener);
}
void passthroughCanMessage(Listener* listener, int id, uint64_t data) {
cJSON *root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, ID_FIELD_NAME, id);
char encodedData[67];
union {
uint64_t whole;
uint8_t bytes[8];
} combined;
combined.whole = data;
sprintf(encodedData, "0x%02x%02x%02x%02x%02x%02x%02x%02x",
combined.bytes[0],
combined.bytes[1],
combined.bytes[2],
combined.bytes[3],
combined.bytes[4],
combined.bytes[5],
combined.bytes[6],
combined.bytes[7]);
cJSON_AddStringToObject(root, NAME_FIELD_NAME, encodedData);
sendJSON(root, listener);
}
// TODO there is lots of duplicated code in these functions, but I don't see an
// obvious way to share code and still keep the different data types returned
// by the handlers.
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data,
float (*handler)(CanSignal*, CanSignal*, int, float, bool*),
CanSignal* signals, int signalCount) {
float value = decodeCanSignal(signal, data);
bool send = true;
float processedValue = handler(signal, signals, signalCount, value, &send);
if(signal->sendClock == signal->sendFrequency) {
if(send && (signal->sendSame || !signal->received ||
value != signal->lastValue)) {
signal->received = true;
sendNumericalMessage(signal->genericName, processedValue, listener);
}
signal->sendClock = 0;
} else {
++signal->sendClock;
}
signal->lastValue = value;
}
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data,
const char* (*handler)(CanSignal*, CanSignal*, int, float, bool*),
CanSignal* signals, int signalCount) {
float value = decodeCanSignal(signal, data);
bool send = true;
const char* stringValue = handler(signal, signals, signalCount, value,
&send);
if(signal->sendClock == signal->sendFrequency) {
if(send && (signal->sendSame || !signal->received ||
value != signal->lastValue)) {
signal->received = true;
sendStringMessage(signal->genericName, stringValue, listener);
}
signal->sendClock = 0;
} else {
++signal->sendClock;
}
signal->lastValue = value;
}
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data,
bool (*handler)(CanSignal*, CanSignal*, int, float, bool*),
CanSignal* signals, int signalCount) {
float value = decodeCanSignal(signal, data);
bool send = true;
bool booleanValue = handler(signal, signals, signalCount, value, &send);
if(signal->sendClock == signal->sendFrequency) {
if(send && (signal->sendSame || !signal->received ||
value != signal->lastValue)) {
signal->received = true;
sendBooleanMessage(signal->genericName, booleanValue, listener);
}
signal->sendClock = 0;
} else {
++signal->sendClock;
}
signal->lastValue = value;
}
void translateCanSignal(Listener* listener, CanSignal* signal,
uint64_t data, CanSignal* signals, int signalCount) {
translateCanSignal(listener, signal, data, passthroughHandler, signals,
signalCount);
}
<|endoftext|>
|
<commit_before>/*************************************************
* CAST-128 Source File *
* (C) 1999-2006 The Botan Project *
*************************************************/
#include <botan/cast128.h>
#include <botan/bit_ops.h>
namespace Botan {
namespace {
/*************************************************
* CAST-128 Round Type 1 *
*************************************************/
inline void R1(u32bit& L, u32bit R, u32bit MK, u32bit RK)
{
u32bit T = rotate_left(MK + R, RK);
L ^= (CAST_SBOX1[get_byte(0, T)] ^ CAST_SBOX2[get_byte(1, T)]) -
CAST_SBOX3[get_byte(2, T)] + CAST_SBOX4[get_byte(3, T)];
}
/*************************************************
* CAST-128 Round Type 2 *
*************************************************/
inline void R2(u32bit& L, u32bit R, u32bit MK, u32bit RK)
{
u32bit T = rotate_left(MK ^ R, RK);
L ^= (CAST_SBOX1[get_byte(0, T)] - CAST_SBOX2[get_byte(1, T)] +
CAST_SBOX3[get_byte(2, T)]) ^ CAST_SBOX4[get_byte(3, T)];
}
/*************************************************
* CAST-128 Round Type 3 *
*************************************************/
inline void R3(u32bit& L, u32bit R, u32bit MK, u32bit RK)
{
u32bit T = rotate_left(MK - R, RK);
L ^= ((CAST_SBOX1[get_byte(0, T)] + CAST_SBOX2[get_byte(1, T)]) ^
CAST_SBOX3[get_byte(2, T)]) - CAST_SBOX4[get_byte(3, T)];
}
}
/*************************************************
* CAST-128 Encryption *
*************************************************/
void CAST_128::enc(const byte in[], byte out[]) const
{
u32bit L = make_u32bit(in[0], in[1], in[2], in[3]),
R = make_u32bit(in[4], in[5], in[6], in[7]);
R1(L, R, MK[ 0], RK[ 0]);
R2(R, L, MK[ 1], RK[ 1]);
R3(L, R, MK[ 2], RK[ 2]);
R1(R, L, MK[ 3], RK[ 3]);
R2(L, R, MK[ 4], RK[ 4]);
R3(R, L, MK[ 5], RK[ 5]);
R1(L, R, MK[ 6], RK[ 6]);
R2(R, L, MK[ 7], RK[ 7]);
R3(L, R, MK[ 8], RK[ 8]);
R1(R, L, MK[ 9], RK[ 9]);
R2(L, R, MK[10], RK[10]);
R3(R, L, MK[11], RK[11]);
R1(L, R, MK[12], RK[12]);
R2(R, L, MK[13], RK[13]);
R3(L, R, MK[14], RK[14]);
R1(R, L, MK[15], RK[15]);
out[0] = get_byte(0, R); out[1] = get_byte(1, R);
out[2] = get_byte(2, R); out[3] = get_byte(3, R);
out[4] = get_byte(0, L); out[5] = get_byte(1, L);
out[6] = get_byte(2, L); out[7] = get_byte(3, L);
}
/*************************************************
* CAST-128 Decryption *
*************************************************/
void CAST_128::dec(const byte in[], byte out[]) const
{
u32bit L = make_u32bit(in[0], in[1], in[2], in[3]),
R = make_u32bit(in[4], in[5], in[6], in[7]);
R1(L, R, MK[15], RK[15]);
R3(R, L, MK[14], RK[14]);
R2(L, R, MK[13], RK[13]);
R1(R, L, MK[12], RK[12]);
R3(L, R, MK[11], RK[11]);
R2(R, L, MK[10], RK[10]);
R1(L, R, MK[ 9], RK[ 9]);
R3(R, L, MK[ 8], RK[ 8]);
R2(L, R, MK[ 7], RK[ 7]);
R1(R, L, MK[ 6], RK[ 6]);
R3(L, R, MK[ 5], RK[ 5]);
R2(R, L, MK[ 4], RK[ 4]);
R1(L, R, MK[ 3], RK[ 3]);
R3(R, L, MK[ 2], RK[ 2]);
R2(L, R, MK[ 1], RK[ 1]);
R1(R, L, MK[ 0], RK[ 0]);
out[0] = get_byte(0, R); out[1] = get_byte(1, R);
out[2] = get_byte(2, R); out[3] = get_byte(3, R);
out[4] = get_byte(0, L); out[5] = get_byte(1, L);
out[6] = get_byte(2, L); out[7] = get_byte(3, L);
}
/*************************************************
* CAST-128 Key Schedule *
*************************************************/
void CAST_128::key(const byte key[], u32bit length)
{
clear();
SecureBuffer<u32bit, 4> X;
for(u32bit j = 0; j != length; ++j)
X[j/4] = (X[j/4] << 8) + key[j];
key_schedule(MK, X);
key_schedule(RK, X);
for(u32bit j = 0; j != 16; ++j)
RK[j] %= 32;
}
/*************************************************
* S-Box Based Key Expansion *
*************************************************/
void CAST_128::key_schedule(u32bit K[16], u32bit X[4])
{
class ByteReader
{
public:
byte operator()(u32bit i) { return (X[i/4] >> (8*(3 - (i%4)))); }
ByteReader(u32bit* x) : X(x) {}
private:
u32bit* X;
};
SecureBuffer<u32bit, 4> Z;
ByteReader x(X), z(Z);
Z[0] = X[0] ^ S5[x(13)] ^ S6[x(15)] ^ S7[x(12)] ^ S8[x(14)] ^ S7[x( 8)];
Z[1] = X[2] ^ S5[z( 0)] ^ S6[z( 2)] ^ S7[z( 1)] ^ S8[z( 3)] ^ S8[x(10)];
Z[2] = X[3] ^ S5[z( 7)] ^ S6[z( 6)] ^ S7[z( 5)] ^ S8[z( 4)] ^ S5[x( 9)];
Z[3] = X[1] ^ S5[z(10)] ^ S6[z( 9)] ^ S7[z(11)] ^ S8[z( 8)] ^ S6[x(11)];
K[ 0] = S5[z( 8)] ^ S6[z( 9)] ^ S7[z( 7)] ^ S8[z( 6)] ^ S5[z( 2)];
K[ 1] = S5[z(10)] ^ S6[z(11)] ^ S7[z( 5)] ^ S8[z( 4)] ^ S6[z( 6)];
K[ 2] = S5[z(12)] ^ S6[z(13)] ^ S7[z( 3)] ^ S8[z( 2)] ^ S7[z( 9)];
K[ 3] = S5[z(14)] ^ S6[z(15)] ^ S7[z( 1)] ^ S8[z( 0)] ^ S8[z(12)];
X[0] = Z[2] ^ S5[z( 5)] ^ S6[z( 7)] ^ S7[z( 4)] ^ S8[z( 6)] ^ S7[z( 0)];
X[1] = Z[0] ^ S5[x( 0)] ^ S6[x( 2)] ^ S7[x( 1)] ^ S8[x( 3)] ^ S8[z( 2)];
X[2] = Z[1] ^ S5[x( 7)] ^ S6[x( 6)] ^ S7[x( 5)] ^ S8[x( 4)] ^ S5[z( 1)];
X[3] = Z[3] ^ S5[x(10)] ^ S6[x( 9)] ^ S7[x(11)] ^ S8[x( 8)] ^ S6[z( 3)];
K[ 4] = S5[x( 3)] ^ S6[x( 2)] ^ S7[x(12)] ^ S8[x(13)] ^ S5[x( 8)];
K[ 5] = S5[x( 1)] ^ S6[x( 0)] ^ S7[x(14)] ^ S8[x(15)] ^ S6[x(13)];
K[ 6] = S5[x( 7)] ^ S6[x( 6)] ^ S7[x( 8)] ^ S8[x( 9)] ^ S7[x( 3)];
K[ 7] = S5[x( 5)] ^ S6[x( 4)] ^ S7[x(10)] ^ S8[x(11)] ^ S8[x( 7)];
Z[0] = X[0] ^ S5[x(13)] ^ S6[x(15)] ^ S7[x(12)] ^ S8[x(14)] ^ S7[x( 8)];
Z[1] = X[2] ^ S5[z( 0)] ^ S6[z( 2)] ^ S7[z( 1)] ^ S8[z( 3)] ^ S8[x(10)];
Z[2] = X[3] ^ S5[z( 7)] ^ S6[z( 6)] ^ S7[z( 5)] ^ S8[z( 4)] ^ S5[x( 9)];
Z[3] = X[1] ^ S5[z(10)] ^ S6[z( 9)] ^ S7[z(11)] ^ S8[z( 8)] ^ S6[x(11)];
K[ 8] = S5[z( 3)] ^ S6[z( 2)] ^ S7[z(12)] ^ S8[z(13)] ^ S5[z( 9)];
K[ 9] = S5[z( 1)] ^ S6[z( 0)] ^ S7[z(14)] ^ S8[z(15)] ^ S6[z(12)];
K[10] = S5[z( 7)] ^ S6[z( 6)] ^ S7[z( 8)] ^ S8[z( 9)] ^ S7[z( 2)];
K[11] = S5[z( 5)] ^ S6[z( 4)] ^ S7[z(10)] ^ S8[z(11)] ^ S8[z( 6)];
X[0] = Z[2] ^ S5[z( 5)] ^ S6[z( 7)] ^ S7[z( 4)] ^ S8[z( 6)] ^ S7[z( 0)];
X[1] = Z[0] ^ S5[x( 0)] ^ S6[x( 2)] ^ S7[x( 1)] ^ S8[x( 3)] ^ S8[z( 2)];
X[2] = Z[1] ^ S5[x( 7)] ^ S6[x( 6)] ^ S7[x( 5)] ^ S8[x( 4)] ^ S5[z( 1)];
X[3] = Z[3] ^ S5[x(10)] ^ S6[x( 9)] ^ S7[x(11)] ^ S8[x( 8)] ^ S6[z( 3)];
K[12] = S5[x( 8)] ^ S6[x( 9)] ^ S7[x( 7)] ^ S8[x( 6)] ^ S5[x( 3)];
K[13] = S5[x(10)] ^ S6[x(11)] ^ S7[x( 5)] ^ S8[x( 4)] ^ S6[x( 7)];
K[14] = S5[x(12)] ^ S6[x(13)] ^ S7[x( 3)] ^ S8[x( 2)] ^ S7[x( 8)];
K[15] = S5[x(14)] ^ S6[x(15)] ^ S7[x( 1)] ^ S8[x( 0)] ^ S8[x(13)];
}
}
<commit_msg>Make the ByteReader class in CAST_128::key_schedule only manipulate const pointers, as it doesn't actually need write access to anything.<commit_after>/*************************************************
* CAST-128 Source File *
* (C) 1999-2006 The Botan Project *
*************************************************/
#include <botan/cast128.h>
#include <botan/bit_ops.h>
namespace Botan {
namespace {
/*************************************************
* CAST-128 Round Type 1 *
*************************************************/
inline void R1(u32bit& L, u32bit R, u32bit MK, u32bit RK)
{
u32bit T = rotate_left(MK + R, RK);
L ^= (CAST_SBOX1[get_byte(0, T)] ^ CAST_SBOX2[get_byte(1, T)]) -
CAST_SBOX3[get_byte(2, T)] + CAST_SBOX4[get_byte(3, T)];
}
/*************************************************
* CAST-128 Round Type 2 *
*************************************************/
inline void R2(u32bit& L, u32bit R, u32bit MK, u32bit RK)
{
u32bit T = rotate_left(MK ^ R, RK);
L ^= (CAST_SBOX1[get_byte(0, T)] - CAST_SBOX2[get_byte(1, T)] +
CAST_SBOX3[get_byte(2, T)]) ^ CAST_SBOX4[get_byte(3, T)];
}
/*************************************************
* CAST-128 Round Type 3 *
*************************************************/
inline void R3(u32bit& L, u32bit R, u32bit MK, u32bit RK)
{
u32bit T = rotate_left(MK - R, RK);
L ^= ((CAST_SBOX1[get_byte(0, T)] + CAST_SBOX2[get_byte(1, T)]) ^
CAST_SBOX3[get_byte(2, T)]) - CAST_SBOX4[get_byte(3, T)];
}
}
/*************************************************
* CAST-128 Encryption *
*************************************************/
void CAST_128::enc(const byte in[], byte out[]) const
{
u32bit L = make_u32bit(in[0], in[1], in[2], in[3]),
R = make_u32bit(in[4], in[5], in[6], in[7]);
R1(L, R, MK[ 0], RK[ 0]);
R2(R, L, MK[ 1], RK[ 1]);
R3(L, R, MK[ 2], RK[ 2]);
R1(R, L, MK[ 3], RK[ 3]);
R2(L, R, MK[ 4], RK[ 4]);
R3(R, L, MK[ 5], RK[ 5]);
R1(L, R, MK[ 6], RK[ 6]);
R2(R, L, MK[ 7], RK[ 7]);
R3(L, R, MK[ 8], RK[ 8]);
R1(R, L, MK[ 9], RK[ 9]);
R2(L, R, MK[10], RK[10]);
R3(R, L, MK[11], RK[11]);
R1(L, R, MK[12], RK[12]);
R2(R, L, MK[13], RK[13]);
R3(L, R, MK[14], RK[14]);
R1(R, L, MK[15], RK[15]);
out[0] = get_byte(0, R); out[1] = get_byte(1, R);
out[2] = get_byte(2, R); out[3] = get_byte(3, R);
out[4] = get_byte(0, L); out[5] = get_byte(1, L);
out[6] = get_byte(2, L); out[7] = get_byte(3, L);
}
/*************************************************
* CAST-128 Decryption *
*************************************************/
void CAST_128::dec(const byte in[], byte out[]) const
{
u32bit L = make_u32bit(in[0], in[1], in[2], in[3]),
R = make_u32bit(in[4], in[5], in[6], in[7]);
R1(L, R, MK[15], RK[15]);
R3(R, L, MK[14], RK[14]);
R2(L, R, MK[13], RK[13]);
R1(R, L, MK[12], RK[12]);
R3(L, R, MK[11], RK[11]);
R2(R, L, MK[10], RK[10]);
R1(L, R, MK[ 9], RK[ 9]);
R3(R, L, MK[ 8], RK[ 8]);
R2(L, R, MK[ 7], RK[ 7]);
R1(R, L, MK[ 6], RK[ 6]);
R3(L, R, MK[ 5], RK[ 5]);
R2(R, L, MK[ 4], RK[ 4]);
R1(L, R, MK[ 3], RK[ 3]);
R3(R, L, MK[ 2], RK[ 2]);
R2(L, R, MK[ 1], RK[ 1]);
R1(R, L, MK[ 0], RK[ 0]);
out[0] = get_byte(0, R); out[1] = get_byte(1, R);
out[2] = get_byte(2, R); out[3] = get_byte(3, R);
out[4] = get_byte(0, L); out[5] = get_byte(1, L);
out[6] = get_byte(2, L); out[7] = get_byte(3, L);
}
/*************************************************
* CAST-128 Key Schedule *
*************************************************/
void CAST_128::key(const byte key[], u32bit length)
{
clear();
SecureBuffer<u32bit, 4> X;
for(u32bit j = 0; j != length; ++j)
X[j/4] = (X[j/4] << 8) + key[j];
key_schedule(MK, X);
key_schedule(RK, X);
for(u32bit j = 0; j != 16; ++j)
RK[j] %= 32;
}
/*************************************************
* S-Box Based Key Expansion *
*************************************************/
void CAST_128::key_schedule(u32bit K[16], u32bit X[4])
{
class ByteReader
{
public:
byte operator()(u32bit i) { return (X[i/4] >> (8*(3 - (i%4)))); }
ByteReader(const u32bit* x) : X(x) {}
private:
const u32bit* X;
};
SecureBuffer<u32bit, 4> Z;
ByteReader x(X), z(Z);
Z[0] = X[0] ^ S5[x(13)] ^ S6[x(15)] ^ S7[x(12)] ^ S8[x(14)] ^ S7[x( 8)];
Z[1] = X[2] ^ S5[z( 0)] ^ S6[z( 2)] ^ S7[z( 1)] ^ S8[z( 3)] ^ S8[x(10)];
Z[2] = X[3] ^ S5[z( 7)] ^ S6[z( 6)] ^ S7[z( 5)] ^ S8[z( 4)] ^ S5[x( 9)];
Z[3] = X[1] ^ S5[z(10)] ^ S6[z( 9)] ^ S7[z(11)] ^ S8[z( 8)] ^ S6[x(11)];
K[ 0] = S5[z( 8)] ^ S6[z( 9)] ^ S7[z( 7)] ^ S8[z( 6)] ^ S5[z( 2)];
K[ 1] = S5[z(10)] ^ S6[z(11)] ^ S7[z( 5)] ^ S8[z( 4)] ^ S6[z( 6)];
K[ 2] = S5[z(12)] ^ S6[z(13)] ^ S7[z( 3)] ^ S8[z( 2)] ^ S7[z( 9)];
K[ 3] = S5[z(14)] ^ S6[z(15)] ^ S7[z( 1)] ^ S8[z( 0)] ^ S8[z(12)];
X[0] = Z[2] ^ S5[z( 5)] ^ S6[z( 7)] ^ S7[z( 4)] ^ S8[z( 6)] ^ S7[z( 0)];
X[1] = Z[0] ^ S5[x( 0)] ^ S6[x( 2)] ^ S7[x( 1)] ^ S8[x( 3)] ^ S8[z( 2)];
X[2] = Z[1] ^ S5[x( 7)] ^ S6[x( 6)] ^ S7[x( 5)] ^ S8[x( 4)] ^ S5[z( 1)];
X[3] = Z[3] ^ S5[x(10)] ^ S6[x( 9)] ^ S7[x(11)] ^ S8[x( 8)] ^ S6[z( 3)];
K[ 4] = S5[x( 3)] ^ S6[x( 2)] ^ S7[x(12)] ^ S8[x(13)] ^ S5[x( 8)];
K[ 5] = S5[x( 1)] ^ S6[x( 0)] ^ S7[x(14)] ^ S8[x(15)] ^ S6[x(13)];
K[ 6] = S5[x( 7)] ^ S6[x( 6)] ^ S7[x( 8)] ^ S8[x( 9)] ^ S7[x( 3)];
K[ 7] = S5[x( 5)] ^ S6[x( 4)] ^ S7[x(10)] ^ S8[x(11)] ^ S8[x( 7)];
Z[0] = X[0] ^ S5[x(13)] ^ S6[x(15)] ^ S7[x(12)] ^ S8[x(14)] ^ S7[x( 8)];
Z[1] = X[2] ^ S5[z( 0)] ^ S6[z( 2)] ^ S7[z( 1)] ^ S8[z( 3)] ^ S8[x(10)];
Z[2] = X[3] ^ S5[z( 7)] ^ S6[z( 6)] ^ S7[z( 5)] ^ S8[z( 4)] ^ S5[x( 9)];
Z[3] = X[1] ^ S5[z(10)] ^ S6[z( 9)] ^ S7[z(11)] ^ S8[z( 8)] ^ S6[x(11)];
K[ 8] = S5[z( 3)] ^ S6[z( 2)] ^ S7[z(12)] ^ S8[z(13)] ^ S5[z( 9)];
K[ 9] = S5[z( 1)] ^ S6[z( 0)] ^ S7[z(14)] ^ S8[z(15)] ^ S6[z(12)];
K[10] = S5[z( 7)] ^ S6[z( 6)] ^ S7[z( 8)] ^ S8[z( 9)] ^ S7[z( 2)];
K[11] = S5[z( 5)] ^ S6[z( 4)] ^ S7[z(10)] ^ S8[z(11)] ^ S8[z( 6)];
X[0] = Z[2] ^ S5[z( 5)] ^ S6[z( 7)] ^ S7[z( 4)] ^ S8[z( 6)] ^ S7[z( 0)];
X[1] = Z[0] ^ S5[x( 0)] ^ S6[x( 2)] ^ S7[x( 1)] ^ S8[x( 3)] ^ S8[z( 2)];
X[2] = Z[1] ^ S5[x( 7)] ^ S6[x( 6)] ^ S7[x( 5)] ^ S8[x( 4)] ^ S5[z( 1)];
X[3] = Z[3] ^ S5[x(10)] ^ S6[x( 9)] ^ S7[x(11)] ^ S8[x( 8)] ^ S6[z( 3)];
K[12] = S5[x( 8)] ^ S6[x( 9)] ^ S7[x( 7)] ^ S8[x( 6)] ^ S5[x( 3)];
K[13] = S5[x(10)] ^ S6[x(11)] ^ S7[x( 5)] ^ S8[x( 4)] ^ S6[x( 7)];
K[14] = S5[x(12)] ^ S6[x(13)] ^ S7[x( 3)] ^ S8[x( 2)] ^ S7[x( 8)];
K[15] = S5[x(14)] ^ S6[x(15)] ^ S7[x( 1)] ^ S8[x( 0)] ^ S8[x(13)];
}
}
<|endoftext|>
|
<commit_before><commit_msg>Fix confusion about filetype of auto-corrected POTs<commit_after><|endoftext|>
|
<commit_before>/* cclive
* Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com>
*
* This file is part of cclive <http://cclive.sourceforge.net/>.
*
* 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 <ccinternal>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/exception/errinfo_file_name.hpp>
#include <boost/exception/get_error_info.hpp>
#include <boost/exception/errinfo_errno.hpp>
#include <stdexcept>
#include <iostream>
#include <clocale>
#include <ccapplication>
#include <ccquvi>
#include <ccutil>
using namespace cc;
static application::exit_status print(const boost::exception& x)
{
std::clog << "error: ";
if (std::string const *s =
boost::get_error_info<boost::errinfo_file_name>(x))
{
std::clog << *s << ": ";
}
bool have_strerror = false;
if (int const *n =
boost::get_error_info<boost::errinfo_errno>(x))
{
std::clog << cc::perror() << " (" << *n << ")";
have_strerror = true;
}
try
{
throw;
}
catch (const std::exception& x)
{
if (!have_strerror)
std::clog << x.what();
}
catch (...)
{
std::clog << boost::diagnostic_information(x);
}
std::clog << std::endl;
return application::error;
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "");
application::exit_status es = application::ok;
application app;
try
{
es = app.exec(argc, argv);
}
// Thrown by quvi::query constructor (e.g. quvi_init, quvi_new).
catch (const quvi::error& e)
{
std::clog << "libquvi: error: " << e.what() << std::endl;
es = application::error;
}
// Thrown by boost (e.g. cc::go_background failure).
catch (const std::runtime_error& e)
{
std::clog << "error: " << e.what() << std::endl;
es = application::error;
}
// Thrown by boost::program_options (cc::options).
catch (const boost::exception& x)
{
es = print(x);
}
return es;
}
// vim: set ts=2 sw=2 tw=72 expandtab:
<commit_msg>main: Use cc::error, catch cc::options::exit_program<commit_after>/* cclive
* Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com>
*
* This file is part of cclive <http://cclive.sourceforge.net/>.
*
* 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 <ccinternal>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/exception/errinfo_file_name.hpp>
#include <boost/exception/get_error_info.hpp>
#include <boost/exception/errinfo_errno.hpp>
#include <stdexcept>
#include <iostream>
#include <clocale>
#include <ccapplication>
#include <ccquvi>
#include <ccoptions>
#include <ccutil>
using namespace cc;
int main(int const argc, char const **argv)
{
setlocale(LC_ALL, "");
application::exit_status es = application::ok;
application app;
try
{
es = app.exec(argc, argv);
}
// --version, --help, etc.
catch (const cc::options::exit_program&)
{
// Fall through.
}
// Thrown by quvi::query constructor (e.g. quvi_init, quvi_new).
catch (const quvi::error& e)
{
std::clog << "libquvi: error: " << e.what() << std::endl;
es = application::error;
}
// Thrown by boost (e.g. cc::go_background failure).
catch (const std::runtime_error& e)
{
std::clog << "error: " << e.what() << std::endl;
es = application::error;
}
// Thrown by boost::program_options (cc::options).
catch (const boost::exception& x)
{
es = static_cast<application::exit_status>(cc::error::print(x));
}
return es;
}
// vim: set ts=2 sw=2 tw=72 expandtab:
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <string>
#include <regex>
#include <iostream>
#include <fstream>
#include <sstream>
#include <astar\AStar.h>
namespace han {
namespace ap {
namespace cli {
enum arg_options {
output_file,
pretty_output
};
uint32_t find_arg_code(std::string arg_) {
if (arg_ == "-o") return arg_options::output_file;
if (arg_ == "-p") return arg_options::pretty_output;
return -1;
}
}
}
}
int main(int argc, char **argv) {
uint32_t arg_index = 1;
if (argc < 2) {
std::cout << "Usage: cli.exe [-p] [-o output.sqf] input.sqf\n";
// return 0;
}
HAN::NodePtrs nodes;
for (int i = 0; i <= 17; ++i) {
for (int j = 0; j <= 17; ++j) {
HAN::NodePtr node = std::shared_ptr<HAN::Node>(new HAN::Node(i, j));
if (j == 1 && i < 5)
node->accessable = false;
nodes.push_back(node);
}
}
HAN::Grid grid = HAN::Grid("My Grid name", nodes);
HAN::AStar aStar = HAN::AStar(grid);
HAN::NodePtr start = HAN::NodePtr(new HAN::Node(0, 0));
HAN::NodePtr goal = HAN::NodePtr(new HAN::Node(10, 15));
auto path = aStar.Calculate(start, goal);
grid.print(path);
return 0;
}
<commit_msg>Add better examples being printed in the cli<commit_after>#include <stdio.h>
#include <string>
#include <regex>
#include <iostream>
#include <fstream>
#include <sstream>
#include <astar\AStar.h>
namespace han {
namespace ap {
namespace cli {
enum arg_options {
output_file,
pretty_output
};
uint32_t find_arg_code(std::string arg_) {
if (arg_ == "-o") return arg_options::output_file;
if (arg_ == "-p") return arg_options::pretty_output;
return -1;
}
}
}
}
int main(int argc, char **argv) {
uint32_t arg_index = 1;
if (argc < 2) {
std::cout << "Usage: cli.exe [-p] [-o output.sqf] input.sqf\n";
// return 0;
}
HAN::NodePtrs nodes;
for (int i = 0; i <= 30; ++i) {
for (int j = 0; j <= 17; ++j) {
HAN::NodePtr node = std::shared_ptr<HAN::Node>(new HAN::Node(i, j));
if (j == 12 && i > 3 && i < 15)
node->accessable = false;
if (j == 5 && i > 2 && i < 15)
node->accessable = false;
if (i == 15 && j < 15)
node->accessable = false;
if (i == 20 && j > 10)
node->accessable = false;
nodes.push_back(node);
}
}
HAN::Grid grid = HAN::Grid("My Grid name", nodes);
HAN::AStar aStar = HAN::AStar(grid);
HAN::NodePtr start = HAN::NodePtr(new HAN::Node(0, 0));
HAN::NodePtr goal = HAN::NodePtr(new HAN::Node(27, 16));
auto path = aStar.Calculate(start, goal);
grid.print(path);
grid.print(aStar.Calculate(HAN::NodePtr(new HAN::Node(0, 0)), HAN::NodePtr(new HAN::Node(25, 2))));
grid.print(aStar.Calculate(HAN::NodePtr(new HAN::Node(10, 10)), HAN::NodePtr(new HAN::Node(0, 0))));
grid.print(aStar.Calculate(HAN::NodePtr(new HAN::Node(14, 4)), HAN::NodePtr(new HAN::Node(0, 0))));
aStar.SetHeuristic(7);
grid.print(aStar.Calculate(HAN::NodePtr(new HAN::Node(14, 4)), HAN::NodePtr(new HAN::Node(0, 0))));
return 0;
}
<|endoftext|>
|
<commit_before>#include "internal.hpp"
namespace CaDiCaL {
/*------------------------------------------------------------------------*/
// Returns positive number 1 ( > 0) if the given clause is root level
// satisfied or the negative number -1 ( < 0) if it is not root level
// satisfied but contains a root level falsified literal and 0 otherwise, if
// it does not contain a root level fixed literal.
int Internal::clause_contains_fixed_literal (Clause * c) {
const const_literal_iterator end = c->end ();
const_literal_iterator i = c->begin ();
int res = 0;
while (res <= 0 && i != end) {
const int lit = *i++, tmp = fixed (lit);
if (tmp > 0) {
LOG (c, "root level satisfied literal %d in", lit);
res = 1;
} else if (!res && tmp < 0) {
LOG (c, "root level falsified literal %d in", lit);
res = -1;
}
}
return res;
}
// Assume that the clause is not root level satisfied but contains a literal
// set to false (root level falsified literal), so it can be shrunken. The
// clause data is not actually reallocated at this point to avoid dealing
// with issues of special policies for watching binary clauses or whether a
// clause is extended or not. Only its size field is adjusted accordingly
// after flushing out root level falsified literals.
void Internal::remove_falsified_literals (Clause * c) {
const const_literal_iterator end = c->end ();
const_literal_iterator i;
int num_non_false = 0;
for (i = c->begin (); num_non_false < 2 && i != end; i++)
if (fixed (*i) >= 0) num_non_false++;
if (num_non_false < 2) return;
if (proof) proof->trace_flushing_clause (c);
literal_iterator j = c->begin ();
for (i = j; i != end; i++) {
const int lit = *j++ = *i, tmp = fixed (lit);
assert (tmp <= 0);
if (tmp >= 0) continue;
LOG ("flushing %d", lit);
j--;
}
stats.collected += shrink_clause_size (c, j - c->begin ());
if (likely_to_be_kept_clause (c)) mark_added (c);
}
// If there are new units (fixed variables) since the last garbage
// collection we go over all clauses, mark satisfied ones as garbage and
// flush falsified literals. Otherwise if no new units have been generated
// since the last garbage collection just skip this step.
void Internal::mark_satisfied_clauses_as_garbage () {
if (lim.fixed_at_last_collect >= stats.all.fixed) return;
lim.fixed_at_last_collect = stats.all.fixed;
LOG ("marking satisfied clauses and removing falsified literals");
const_clause_iterator i;
for (i = clauses.begin (); i != clauses.end (); i++) {
Clause * c = *i;
if (c->garbage) continue;
const int tmp = clause_contains_fixed_literal (c);
if (tmp > 0) mark_garbage (c);
else if (tmp < 0) remove_falsified_literals (c);
}
}
/*------------------------------------------------------------------------*/
// Update occurrence lists before deleting garbage clauses in the context of
// preprocessing, e.g., during bounded variable elimination 'elim'. The
// result is the number of remaining clauses, which in this context means
// the number of non-garbage clauses.
size_t Internal::flush_occs (int lit) {
Occs & os = occs (lit);
const const_occs_iterator end = os.end ();
occs_iterator j = os.begin ();
const_occs_iterator i;
size_t res = 0;
Clause * c;
for (i = j; i != end; i++) {
c = *i;
if (c->collect ()) continue;
*j++ = c->moved ? c->copy : c;
assert (!c->redundant);
res++;
}
os.resize (j - os.begin ());
shrink_occs (os);
return res;
}
// Update watch lists before deleting garbage clauses in the context of
// 'reduce' where we watch and no occurrence lists. We have to protect
// reason clauses not be collected and thus we have this additional check
// hidden in 'Clause.collect', which for the root level context of
// preprocessing is actually redundant.
inline void Internal::flush_watches (int lit, Watches & saved) {
assert (saved.empty ());
Watches & ws = watches (lit);
const_watch_iterator end = ws.end ();
watch_iterator j = ws.begin ();
const_watch_iterator i;
for (i = j; i != end; i++) {
Watch w = *i;
Clause * c = w.clause;
if (c->collect ()) continue;
if (c->moved) c = w.clause = c->copy;
if (c->size == 2 && !w.binary) w.binary = true;
const int new_blit_pos = (c->literals[0] == lit);
assert (c->literals[!new_blit_pos] == lit);
w.blit = c->literals[new_blit_pos];
if (w.binary) *j++ = w;
else saved.push_back (w);
}
ws.resize (j - ws.begin ());
end = saved.end ();
for (i = saved.begin (); i != end; i++)
ws.push_back (*i);
saved.clear ();
shrink_watches (ws);
}
void Internal::flush_all_occs_and_watches () {
if (occs ())
for (int idx = 1; idx <= max_var; idx++)
flush_occs (idx), flush_occs (-idx);
if (watches ()) {
Watches tmp;
for (int idx = 1; idx <= max_var; idx++)
flush_watches (idx, tmp), flush_watches (-idx, tmp);
}
}
/*------------------------------------------------------------------------*/
// This is a simple garbage collector which does not move clauses. It needs
// less space than the arena based clause allocator, but is not as cache
// efficient, since the copying garbage collector can put clauses together
// which are likely accessed after each other.
void Internal::delete_garbage_clauses () {
flush_all_occs_and_watches ();
LOG ("deleting garbage clauses");
long collected_bytes = 0, collected_clauses = 0;
const const_clause_iterator end = clauses.end ();
clause_iterator j = clauses.begin ();
const_clause_iterator i = j;
while (i != end) {
Clause * c = *j++ = *i++;
if (!c->collect ()) continue;
collected_bytes += c->bytes ();
collected_clauses++;
delete_clause (c);
j--;
}
clauses.resize (j - clauses.begin ());
shrink_vector (clauses);
VRB ("collect", stats.collections,
"collected %ld bytes of %ld garbage clauses",
collected_bytes, collected_clauses);
}
/*------------------------------------------------------------------------*/
// This is the start of the copying garbage collector using the arena. At
// the core is the following function, which copies a clause to the 'to'
// space of the arena. Be careful if this clause is a reason of an
// assignment. In that case update the reason reference.
//
void Internal::copy_clause (Clause * c) {
LOG (c, "moving");
assert (!c->moved);
char * p = c->start (), * q = arena.copy (p, c->bytes ());
assert (aligned (q, 8));
Clause * d = c->copy = (Clause *) (q - c->offset ());
if (d->reason) var (d->literals[val (d->literals[1]) > 0]).reason = d;
c->moved = true;
}
// This is the moving garbage collector.
void Internal::copy_non_garbage_clauses () {
Clause * c;
size_t collected_clauses = 0, collected_bytes = 0;
size_t moved_clauses = 0, moved_bytes = 0;
// First determine 'moved_bytes' and 'collected_bytes'.
//
const const_clause_iterator end = clauses.end ();
const_clause_iterator i;
for (i = clauses.begin (); i != end; i++)
if (!(c = *i)->collect ()) moved_bytes += c->bytes (), moved_clauses++;
else collected_bytes += c->bytes (), collected_clauses++;
VRB ("collect", stats.collections,
"moving %ld bytes %.0f%% of %ld non garbage clauses",
(long) moved_bytes,
percent (moved_bytes, collected_bytes + moved_bytes),
(long) moved_clauses);
// Prepare 'to' space of size 'moved_bytes'.
//
arena.prepare (moved_bytes);
if (opts.arena == 1 || !watches ()) {
// Localize according to current clause order.
// If the option 'opts.arena == 1' is set, then this means the solver
// uses the original order of clauses. If there are no watches, we can
// not use the watched based copying policies below. This happens if
// garbage collection is triggered during bounded variable elimination.
// Copy clauses according to the order of calling 'copy_clause', which
// in essence just gives a compacting garbage collector, since their
// relative order is kept, and actually already gives the largest
// benefit due to better cache locality.
for (i = clauses.begin (); i != end; i++)
if (!(c = *i)->collect ()) copy_clause (c);
} else if (opts.arena == 2) {
// Localize according to (original) variable order.
// This is almost the version used by MiniSAT and descendants and seems
// to work best for search. Our version uses saved phases.
for (int sign = -1; sign <= 1; sign += 2) {
for (int idx = 1; idx <= max_var; idx++) {
const Watches & ws = watches (sign * phases[idx] * idx);
const const_watch_iterator ew = ws.end ();
for (const_watch_iterator i = ws.begin (); i != ew; i++)
if (!(c = i->clause)->moved && !c->collect ()) copy_clause (c);
}
}
} else {
// Localize according to decision queue order.
// This is second best for search. It allocates clauses in the order of
// the decision queue. It also uses saved phases. Intuitively it
// should be faster than MiniSAT version, but it seems that using the
// original variable order ('opts.arena==2') gives a small benefit.
assert (opts.arena == 3);
for (int sign = -1; sign <= 1; sign += 2) {
for (int idx = queue.last; idx; idx = link (idx).prev) {
const Watches & ws = watches (sign * phases[idx] * idx);
const const_watch_iterator ew = ws.end ();
for (const_watch_iterator i = ws.begin (); i != ew; i++)
if (!(c = i->clause)->moved && !c->collect ()) copy_clause (c);
}
}
}
// Do not forget to move clauses which are not watched, which happened in
// a rare situation, and now is only left as defensive code.
//
for (i = clauses.begin (); i != end; i++)
if (!(c = *i)->collect () && !c->moved) copy_clause (c);
// Updates watches or occurrence lists.
//
flush_all_occs_and_watches ();
// Replace and flush clause references in 'clauses'.
//
clause_iterator j = clauses.begin ();
assert (end == clauses.end ());
for (i = j; i != end; i++) {
if ((c = *i)->collect ()) delete_clause (c);
else assert (c->moved), *j++ = c->copy, deallocate_clause (c);
}
clauses.resize (j - clauses.begin ());
if (clauses.size () < clauses.capacity ()/2) shrink_vector (clauses);
// Replace and flush references in the vivification schedule.
// Release 'from' space completely and then swap 'to' with 'from'.
//
arena.swap ();
VRB ("collect", stats.collections,
"collected %ld bytes %.0f%% of %ld garbage clauses",
(long) collected_bytes,
percent (collected_bytes, collected_bytes + moved_bytes),
(long) collected_clauses);
}
/*------------------------------------------------------------------------*/
// Maintaining clause statistics is complex and error prone but necessary
// for proper scheduling of garbage collection, particularly during bounded
// variable elimination. With this function we can check whether these
// statistics are updated correctly.
void Internal::check_clause_stats () {
#ifndef NDEBUG
long irredundant = 0, redundant = 0, irrbytes = 0;
const const_clause_iterator end = clauses.end ();
const_clause_iterator i;
for (i = clauses.begin (); i != end; i++) {
Clause * c = *i;
if (c->garbage) continue;
if (c->redundant) redundant++; else irredundant++;
if (!c->redundant) irrbytes += c->bytes ();
}
assert (stats.irredundant == irredundant);
assert (stats.redundant == redundant);
assert (stats.irrbytes == irrbytes);
#endif
}
/*------------------------------------------------------------------------*/
bool Internal::arenaing () {
return opts.arena && (stats.collections > 1); // TODO more sophisticated
}
void Internal::garbage_collection () {
if (unsat) return;
START (collect);
report ('G', 1);
stats.collections++;
mark_satisfied_clauses_as_garbage ();
if (arenaing ()) copy_non_garbage_clauses ();
else delete_garbage_clauses ();
check_clause_stats ();
check_var_stats ();
report ('C', 1);
STOP (collect);
}
};
<commit_msg>fixed comments<commit_after>#include "internal.hpp"
namespace CaDiCaL {
/*------------------------------------------------------------------------*/
// Returns positive number 1 ( > 0) if the given clause is root level
// satisfied or the negative number -1 ( < 0) if it is not root level
// satisfied but contains a root level falsified literal and 0 otherwise, if
// it does not contain a root level fixed literal.
int Internal::clause_contains_fixed_literal (Clause * c) {
const const_literal_iterator end = c->end ();
const_literal_iterator i = c->begin ();
int res = 0;
while (res <= 0 && i != end) {
const int lit = *i++, tmp = fixed (lit);
if (tmp > 0) {
LOG (c, "root level satisfied literal %d in", lit);
res = 1;
} else if (!res && tmp < 0) {
LOG (c, "root level falsified literal %d in", lit);
res = -1;
}
}
return res;
}
// Assume that the clause is not root level satisfied but contains a literal
// set to false (root level falsified literal), so it can be shrunken. The
// clause data is not actually reallocated at this point to avoid dealing
// with issues of special policies for watching binary clauses or whether a
// clause is extended or not. Only its size field is adjusted accordingly
// after flushing out root level falsified literals.
void Internal::remove_falsified_literals (Clause * c) {
const const_literal_iterator end = c->end ();
const_literal_iterator i;
int num_non_false = 0;
for (i = c->begin (); num_non_false < 2 && i != end; i++)
if (fixed (*i) >= 0) num_non_false++;
if (num_non_false < 2) return;
if (proof) proof->trace_flushing_clause (c);
literal_iterator j = c->begin ();
for (i = j; i != end; i++) {
const int lit = *j++ = *i, tmp = fixed (lit);
assert (tmp <= 0);
if (tmp >= 0) continue;
LOG ("flushing %d", lit);
j--;
}
stats.collected += shrink_clause_size (c, j - c->begin ());
if (likely_to_be_kept_clause (c)) mark_added (c);
}
// If there are new units (fixed variables) since the last garbage
// collection we go over all clauses, mark satisfied ones as garbage and
// flush falsified literals. Otherwise if no new units have been generated
// since the last garbage collection just skip this step.
void Internal::mark_satisfied_clauses_as_garbage () {
if (lim.fixed_at_last_collect >= stats.all.fixed) return;
lim.fixed_at_last_collect = stats.all.fixed;
LOG ("marking satisfied clauses and removing falsified literals");
const_clause_iterator i;
for (i = clauses.begin (); i != clauses.end (); i++) {
Clause * c = *i;
if (c->garbage) continue;
const int tmp = clause_contains_fixed_literal (c);
if (tmp > 0) mark_garbage (c);
else if (tmp < 0) remove_falsified_literals (c);
}
}
/*------------------------------------------------------------------------*/
// Update occurrence lists before deleting garbage clauses in the context of
// preprocessing, e.g., during bounded variable elimination 'elim'. The
// result is the number of remaining clauses, which in this context means
// the number of non-garbage clauses.
size_t Internal::flush_occs (int lit) {
Occs & os = occs (lit);
const const_occs_iterator end = os.end ();
occs_iterator j = os.begin ();
const_occs_iterator i;
size_t res = 0;
Clause * c;
for (i = j; i != end; i++) {
c = *i;
if (c->collect ()) continue;
*j++ = c->moved ? c->copy : c;
assert (!c->redundant);
res++;
}
os.resize (j - os.begin ());
shrink_occs (os);
return res;
}
// Update watch lists before deleting garbage clauses in the context of
// 'reduce' where we watch and no occurrence lists. We have to protect
// reason clauses not be collected and thus we have this additional check
// hidden in 'Clause.collect', which for the root level context of
// preprocessing is actually redundant.
inline void Internal::flush_watches (int lit, Watches & saved) {
assert (saved.empty ());
Watches & ws = watches (lit);
const_watch_iterator end = ws.end ();
watch_iterator j = ws.begin ();
const_watch_iterator i;
for (i = j; i != end; i++) {
Watch w = *i;
Clause * c = w.clause;
if (c->collect ()) continue;
if (c->moved) c = w.clause = c->copy;
if (c->size == 2 && !w.binary) w.binary = true;
const int new_blit_pos = (c->literals[0] == lit);
assert (c->literals[!new_blit_pos] == lit);
w.blit = c->literals[new_blit_pos];
if (w.binary) *j++ = w;
else saved.push_back (w);
}
ws.resize (j - ws.begin ());
end = saved.end ();
for (i = saved.begin (); i != end; i++)
ws.push_back (*i);
saved.clear ();
shrink_watches (ws);
}
void Internal::flush_all_occs_and_watches () {
if (occs ())
for (int idx = 1; idx <= max_var; idx++)
flush_occs (idx), flush_occs (-idx);
if (watches ()) {
Watches tmp;
for (int idx = 1; idx <= max_var; idx++)
flush_watches (idx, tmp), flush_watches (-idx, tmp);
}
}
/*------------------------------------------------------------------------*/
// This is a simple garbage collector which does not move clauses. It needs
// less space than the arena based clause allocator, but is not as cache
// efficient, since the copying garbage collector can put clauses together
// which are likely accessed after each other.
void Internal::delete_garbage_clauses () {
flush_all_occs_and_watches ();
LOG ("deleting garbage clauses");
long collected_bytes = 0, collected_clauses = 0;
const const_clause_iterator end = clauses.end ();
clause_iterator j = clauses.begin ();
const_clause_iterator i = j;
while (i != end) {
Clause * c = *j++ = *i++;
if (!c->collect ()) continue;
collected_bytes += c->bytes ();
collected_clauses++;
delete_clause (c);
j--;
}
clauses.resize (j - clauses.begin ());
shrink_vector (clauses);
VRB ("collect", stats.collections,
"collected %ld bytes of %ld garbage clauses",
collected_bytes, collected_clauses);
}
/*------------------------------------------------------------------------*/
// This is the start of the copying garbage collector using the arena. At
// the core is the following function, which copies a clause to the 'to'
// space of the arena. Be careful if this clause is a reason of an
// assignment. In that case update the reason reference.
//
void Internal::copy_clause (Clause * c) {
LOG (c, "moving");
assert (!c->moved);
char * p = c->start (), * q = arena.copy (p, c->bytes ());
assert (aligned (q, 8));
Clause * d = c->copy = (Clause *) (q - c->offset ());
if (d->reason) var (d->literals[val (d->literals[1]) > 0]).reason = d;
c->moved = true;
}
// This is the moving garbage collector.
void Internal::copy_non_garbage_clauses () {
Clause * c;
size_t collected_clauses = 0, collected_bytes = 0;
size_t moved_clauses = 0, moved_bytes = 0;
// First determine 'moved_bytes' and 'collected_bytes'.
//
const const_clause_iterator end = clauses.end ();
const_clause_iterator i;
for (i = clauses.begin (); i != end; i++)
if (!(c = *i)->collect ()) moved_bytes += c->bytes (), moved_clauses++;
else collected_bytes += c->bytes (), collected_clauses++;
VRB ("collect", stats.collections,
"moving %ld bytes %.0f%% of %ld non garbage clauses",
(long) moved_bytes,
percent (moved_bytes, collected_bytes + moved_bytes),
(long) moved_clauses);
// Prepare 'to' space of size 'moved_bytes'.
//
arena.prepare (moved_bytes);
if (opts.arena == 1 || !watches ()) {
// Localize according to current clause order.
// If the option 'opts.arena == 1' is set, then this means the solver
// uses the original order of clauses. If there are no watches, we can
// not use the watched based copying policies below. This happens if
// garbage collection is triggered during bounded variable elimination.
// Copy clauses according to the order of calling 'copy_clause', which
// in essence just gives a compacting garbage collector, since their
// relative order is kept, and actually already gives the largest
// benefit due to better cache locality.
for (i = clauses.begin (); i != end; i++)
if (!(c = *i)->collect ()) copy_clause (c);
} else if (opts.arena == 2) {
// Localize according to (original) variable order.
// This is almost the version used by MiniSAT and descendants and seems
// to work best for search. Our version uses saved phases.
for (int sign = -1; sign <= 1; sign += 2) {
for (int idx = 1; idx <= max_var; idx++) {
const Watches & ws = watches (sign * phases[idx] * idx);
const const_watch_iterator ew = ws.end ();
for (const_watch_iterator i = ws.begin (); i != ew; i++)
if (!(c = i->clause)->moved && !c->collect ()) copy_clause (c);
}
}
} else {
// Localize according to decision queue order.
// This is the default for search. It allocates clauses in the order of
// the decision queue. It also uses saved phases. It seems slightly
// faster than the MiniSAT version and thus we keep 'opts.arena == 3'.
assert (opts.arena == 3);
for (int sign = -1; sign <= 1; sign += 2) {
for (int idx = queue.last; idx; idx = link (idx).prev) {
const Watches & ws = watches (sign * phases[idx] * idx);
const const_watch_iterator ew = ws.end ();
for (const_watch_iterator i = ws.begin (); i != ew; i++)
if (!(c = i->clause)->moved && !c->collect ()) copy_clause (c);
}
}
}
// Do not forget to move clauses which are not watched, which happened in
// a rare situation, and now is only left as defensive code.
//
for (i = clauses.begin (); i != end; i++)
if (!(c = *i)->collect () && !c->moved) copy_clause (c);
// Update watches or occurrence lists.
//
flush_all_occs_and_watches ();
// Replace and flush clause references in 'clauses'.
//
clause_iterator j = clauses.begin ();
assert (end == clauses.end ());
for (i = j; i != end; i++) {
if ((c = *i)->collect ()) delete_clause (c);
else assert (c->moved), *j++ = c->copy, deallocate_clause (c);
}
clauses.resize (j - clauses.begin ());
if (clauses.size () < clauses.capacity ()/2) shrink_vector (clauses);
// Release 'from' space completely and then swap 'to' with 'from'.
//
arena.swap ();
VRB ("collect", stats.collections,
"collected %ld bytes %.0f%% of %ld garbage clauses",
(long) collected_bytes,
percent (collected_bytes, collected_bytes + moved_bytes),
(long) collected_clauses);
}
/*------------------------------------------------------------------------*/
// Maintaining clause statistics is complex and error prone but necessary
// for proper scheduling of garbage collection, particularly during bounded
// variable elimination. With this function we can check whether these
// statistics are updated correctly.
void Internal::check_clause_stats () {
#ifndef NDEBUG
long irredundant = 0, redundant = 0, irrbytes = 0;
const const_clause_iterator end = clauses.end ();
const_clause_iterator i;
for (i = clauses.begin (); i != end; i++) {
Clause * c = *i;
if (c->garbage) continue;
if (c->redundant) redundant++; else irredundant++;
if (!c->redundant) irrbytes += c->bytes ();
}
assert (stats.irredundant == irredundant);
assert (stats.redundant == redundant);
assert (stats.irrbytes == irrbytes);
#endif
}
/*------------------------------------------------------------------------*/
bool Internal::arenaing () {
return opts.arena && (stats.collections > 1); // TODO more sophisticated
}
void Internal::garbage_collection () {
if (unsat) return;
START (collect);
report ('G', 1);
stats.collections++;
mark_satisfied_clauses_as_garbage ();
if (arenaing ()) copy_non_garbage_clauses ();
else delete_garbage_clauses ();
check_clause_stats ();
check_var_stats ();
report ('C', 1);
STOP (collect);
}
};
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
#include <sys/stat.h>
using namespace std;
class command{
protected:
vector<string> commandlist;
bool commandPass;
bool prevCommandPass;
string commandType;
bool allCount;
bool forceExit;
string nextConnector;
public:
command(){}
command(vector<string> c){
commandlist = c;
commandType = ";";
allCount = true;
prevCommandPass = true;
nextConnector = ";";
forceExit = false;
}
command(vector<string> c, string t){
commandlist = c;
commandType = t;
prevCommandPass = true;
forceExit = false;
allCount = true;
nextConnector = ";";
}
bool getPass(){
return commandPass;
}
string getType(){
return commandType;
}
void runCommand(vector<string> com){
char* argv[1024];
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
pid_t pid;
int status;
pid = fork();
if (pid == 0){
prevCommandPass = true;
execvp(argv[0], argv);
perror("execvp failed: ");
exit(-1);
}
else{
if (waitpid(pid, &status, 0) == -1){
perror("Wait: ");
}
if (WIFEXITED(status) && WEXITSTATUS(status) != 0){
prevCommandPass = false;
}
}
}
void runAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(i)){
//Exit check
if (commandlist.at(i) == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
_Exit(0);
}
// Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
runCommand(commandsublist);
return;
}
if (commandlist.at(i) == "["){
i++;
cout << "detected";
commandsublist.push_back(commandlist.at(i));
if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "-d"){
i++;
commandsublist.push_back(commandlist.at(i));
}
else{
i++;
}
if (commandlist.at(i) == "]"){
i++;
if (checkTest(commandsublist)){
cout << "(True)" << endl;
}
else{
cout << "(False)" << endl;
}
commandsublist.clear();
}
else{
cout << "Error: Missing close bracket." << endl;
_exit(1);
}
break;
}
if (commandlist.at(i) == "test"){
i++;
commandsublist.push_back(commandlist.at(i));
if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){
i++;
commandsublist.push_back(commandlist.at(i));
}
else{
i++;
}
if (checkTest(commandsublist)){
cout << "(True)" << endl;
}
else{
cout << "(False)" << endl;
}
commandsublist.clear();
break;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
i++;
j++;
if (i == commandlist.size()){
runCommand(commandsublist);
return;
}
}
if (commandsublist.size() > 0){
runCommand(commandsublist);
commandsublist.clear();
}
if (checkBreaker(i)){
if (nextConnector == "||"){
if (allCount == true){
prevCommandPass = true;
}
else{
if (prevCommandPass == false){
allCount = false;
}
else{
allCount = true;
}
}
}
else if (nextConnector == "&&"){
if (allCount == true){
if (prevCommandPass == false){
allCount = false;
}
}
else{
allCount = false;
prevCommandPass = false;
}
}
else if (nextConnector == ";"){
if (prevCommandPass == true){
allCount = true;
}
else{
allCount = false;
}
}
if (commandlist.at(i) == "|"){
nextConnector = "||";
}
else if (commandlist.at(i) == "&"){
nextConnector = "&&";
}
else if (commandlist.at(i) == ";"){
nextConnector = ";";
}
i++;
}
i++;
}
else{
i++;
}
}
}
// Checks if there is a '#' at the front of the string
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false;
}
// Checks if the string is a breaker
bool checkBreaker(int i){
if ( (unsigned)i < commandlist.size() + 1){
if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){
return true;
}
else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){
return true;
}
else if (commandlist.at(i) == ";"){
return true;
}
else{
return false;
}
}
else if( (unsigned)i == commandlist.size() + 1){
if(commandlist.at(i) == ";"){
return true;
}
return false;
}
else{
return false;
}
}
// Checks if the next command should be run
bool checkCommandRun(){
if (nextConnector == "||"){
if(allCount == true){
return false;
}
else{
return true;
}
}
else if (nextConnector == "&&"){
if(allCount == true){
return true;
}
return false;
}
else if (nextConnector == ";"){
return true;
}
return false;
}
bool checkTest(vector<string> temp){
if (temp.at(0) == "-e"){
return fileExists(temp.at(1));
}
else if (temp.at(0) == "-f"){
return regFileExists(temp.at(1));
}
else if (temp.at(0) == "-d"){
return dirExists(temp.at(1));
}
else{
return fileExists(temp.at(1));
}
}
bool fileExists(string& path){
struct stat buffer;
return (stat(path.c_str(), &buffer) == 0);
}
bool dirExists(string& path){
struct stat buffer;
if (stat(path.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode)){
return true;
}
return false;
}
bool regFileExists(string& path){
struct stat buffer;
if (stat(path.c_str(), &buffer) == 0 && S_ISREG(buffer.st_mode)){
return true;
}
return false;
}
void execute(bool prevCommand){
if (prevCommand){
if (commandType == "&&"){
runAllCommands();
if (allCount){
commandPass = true;
}
else{
commandPass = false;
}
}
else if (commandType == "||"){
commandPass = true;
}
else if (commandType == ";"){
runAllCommands();
commandPass = true;
}
}
else{
if (commandType == "&&"){
commandPass = false;
}
else if (commandType == "||"){
runAllCommands();
if (allCount){
commandPass = true;
}
else{
commandPass = false;
}
}
else if (commandType == ";"){
runAllCommands();
commandPass = true;
}
}
}
};
<commit_msg>Fixed test functions<commit_after>#include <string>
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
#include <sys/stat.h>
using namespace std;
class command{
protected:
vector<string> commandlist;
bool commandPass;
bool prevCommandPass;
string commandType;
bool allCount;
bool forceExit;
string nextConnector;
public:
command(){}
command(vector<string> c){
commandlist = c;
commandType = ";";
allCount = true;
prevCommandPass = true;
nextConnector = ";";
forceExit = false;
}
command(vector<string> c, string t){
commandlist = c;
commandType = t;
prevCommandPass = true;
forceExit = false;
allCount = true;
nextConnector = ";";
}
bool getPass(){
return commandPass;
}
string getType(){
return commandType;
}
void runCommand(vector<string> com){
char* argv[1024];
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
pid_t pid;
int status;
pid = fork();
if (pid == 0){
prevCommandPass = true;
execvp(argv[0], argv);
perror("execvp failed: ");
exit(-1);
}
else{
if (waitpid(pid, &status, 0) == -1){
perror("Wait: ");
}
if (WIFEXITED(status) && WEXITSTATUS(status) != 0){
prevCommandPass = false;
}
}
}
void runAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(i)){
//Exit check
if (commandlist.at(i) == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
_Exit(0);
}
// Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
runCommand(commandsublist);
return;
}
if (commandlist.at(i) == "["){
i++;
commandsublist.push_back(commandlist.at(i));
if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "-d"){
i++;
commandsublist.push_back(commandlist.at(i));
}
i++;
if (commandlist.at(i) == "]"){
i++;
if (checkTest(commandsublist)){
cout << "(True)" << endl;
}
else{
cout << "(False)" << endl;
}
commandsublist.clear();
}
else{
cout << "Error: Missing close bracket." << endl;
_exit(1);
}
break;
}
else if (commandlist.at(i) == "test"){
i++;
commandsublist.push_back(commandlist.at(i));
if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "-d"){
i++;
commandsublist.push_back(commandlist.at(i));
}
if (checkTest(commandsublist)){
cout << "(True)" << endl;
}
else{
cout << "(False)" << endl;
}
commandsublist.clear();
break;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
i++;
j++;
if (i == commandlist.size()){
runCommand(commandsublist);
return;
}
}
if (commandsublist.size() > 0){
runCommand(commandsublist);
commandsublist.clear();
}
if (i >= commandlist.size()){
return;
}
if (checkBreaker(i)){
if (nextConnector == "||"){
if (allCount == true){
prevCommandPass = true;
}
else{
if (prevCommandPass == false){
allCount = false;
}
else{
allCount = true;
}
}
}
else if (nextConnector == "&&"){
if (allCount == true){
if (prevCommandPass == false){
allCount = false;
}
}
else{
allCount = false;
prevCommandPass = false;
}
}
else if (nextConnector == ";"){
if (prevCommandPass == true){
allCount = true;
}
else{
allCount = false;
}
}
if (commandlist.at(i) == "|"){
nextConnector = "||";
}
else if (commandlist.at(i) == "&"){
nextConnector = "&&";
}
else if (commandlist.at(i) == ";"){
nextConnector = ";";
}
i++;
}
i++;
}
else{
i++;
}
}
}
// Checks if there is a '#' at the front of the string
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false;
}
// Checks if the string is a breaker
bool checkBreaker(int i){
if ( (unsigned)i < commandlist.size() + 1){
if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){
return true;
}
else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){
return true;
}
else if (commandlist.at(i) == ";"){
return true;
}
else{
return false;
}
}
else if( (unsigned)i == commandlist.size() + 1){
if(commandlist.at(i) == ";"){
return true;
}
return false;
}
else{
return false;
}
}
// Checks if the next command should be run
bool checkCommandRun(){
if (nextConnector == "||"){
if(allCount == true){
return false;
}
else{
return true;
}
}
else if (nextConnector == "&&"){
if(allCount == true){
return true;
}
return false;
}
else if (nextConnector == ";"){
return true;
}
return false;
}
bool checkTest(vector<string> temp){
if (temp.at(0) == "-e"){
return fileExists(temp.at(1));
}
else if (temp.at(0) == "-f"){
return regFileExists(temp.at(1));
}
else if (temp.at(0) == "-d"){
return dirExists(temp.at(1));
}
else{
return fileExists(temp.at(0));
}
}
bool fileExists(string& path){
struct stat buffer;
return (stat(path.c_str(), &buffer) == 0);
}
bool dirExists(string& path){
struct stat buffer;
if (stat(path.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode)){
return true;
}
return false;
}
bool regFileExists(string& path){
struct stat buffer;
if (stat(path.c_str(), &buffer) == 0 && S_ISREG(buffer.st_mode)){
return true;
}
return false;
}
void execute(bool prevCommand){
if (prevCommand){
if (commandType == "&&"){
runAllCommands();
if (allCount){
commandPass = true;
}
else{
commandPass = false;
}
}
else if (commandType == "||"){
commandPass = true;
}
else if (commandType == ";"){
runAllCommands();
commandPass = true;
}
}
else{
if (commandType == "&&"){
commandPass = false;
}
else if (commandType == "||"){
runAllCommands();
if (allCount){
commandPass = true;
}
else{
commandPass = false;
}
}
else if (commandType == ";"){
runAllCommands();
commandPass = true;
}
}
}
};
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "native_menu_model.h"
#include "command_callbacks.h"
//id of the existing window menu item
#define WINDOW_MENUITEMTAG 4999
#if defined(OS_WIN)
const ExtensionString WINDOW_COMMAND = L"window";
#else
const ExtensionString WINDOW_COMMAND = "window";
#endif
// map of menuParent --> NativeMenuModel instance
typedef std::map<void*, NativeMenuModel*> menuModelMap;
menuModelMap instanceMap;
NativeMenuModel& NativeMenuModel::getInstance(void* menuParent, bool reset)
{
menuModelMap::iterator foundItem = instanceMap.find(menuParent);
if (foundItem != instanceMap.end()) {
return *(foundItem->second);
}
menu m;
NativeMenuModel* instance = new NativeMenuModel(m);
instance->setTag(WINDOW_COMMAND, WINDOW_MENUITEMTAG);
instanceMap[menuParent] = instance;
return *(instance);
}
bool NativeMenuModel::isMenuItemEnabled(int tag) {
menu::iterator foundItem = menuItems.find(tag);
if(foundItem == menuItems.end()) {
//return enabled
return true;
}
return foundItem->second.enabled;
}
bool NativeMenuModel::isMenuItemChecked(int tag) {
menu::iterator foundItem = menuItems.find(tag);
if(foundItem == menuItems.end()) {
return false;
}
return foundItem->second.checked;
}
int NativeMenuModel::setMenuItemState (ExtensionString command, bool enabled, bool checked) {
//woo turning O(log n) into O(n) however, the important look up is the tag -> menu so making sure that is faster as it will impact user performance.
menu::iterator it;
for ( it=menuItems.begin() ; it != menuItems.end(); it++ ) {
if(it->second.commandId.compare(command) == 0) {
it->second.enabled = enabled;
it->second.checked = checked;
return NO_ERROR;
}
}
return ERR_NOT_FOUND;
}
ExtensionString NativeMenuModel::getCommandId(int tag) {
return menuItems[tag].commandId;
}
int NativeMenuModel::getOrCreateTag(ExtensionString command)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
commandMap[command] = ++tagCount;
menuItems[tagCount] = NativeMenuItemModel(command, true, false);
return tagCount;
}
return foundItem->second;
}
int NativeMenuModel::setTag(ExtensionString command, int tag)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
commandMap[command] = tag;
menuItems[tag] = NativeMenuItemModel(command, true, false);
return tagCount;
}
return foundItem->second;
}
int NativeMenuModel::getTag(ExtensionString command)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
return -1;
}
return foundItem->second;
}
void NativeMenuModel::setOsItem (int tag, void* theItem) {
menuItems[tag].osItem = theItem;
}
void* NativeMenuModel::getOsItem (int tag) {
return menuItems[tag].osItem;
}
int NativeMenuModel::removeMenuItem(const ExtensionString& command)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
return ERR_NOT_FOUND;
}
menuItems.erase(foundItem->second);
commandMap.erase(foundItem);
return NO_ERROR;
}
<commit_msg>More review comments.<commit_after>/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "native_menu_model.h"
#include "command_callbacks.h"
//id of the existing window menu item
#define WINDOW_MENUITEMTAG 4999
#if defined(OS_WIN)
const ExtensionString WINDOW_COMMAND = L"window";
#else
const ExtensionString WINDOW_COMMAND = "window";
#endif
// map of menuParent --> NativeMenuModel instance
typedef std::map<void*, NativeMenuModel*> menuModelMap;
menuModelMap instanceMap;
NativeMenuModel& NativeMenuModel::getInstance(void* menuParent, bool reset)
{
menuModelMap::iterator foundItem = instanceMap.find(menuParent);
if (foundItem != instanceMap.end()) {
return *(foundItem->second);
}
menu m;
NativeMenuModel* instance = new NativeMenuModel(m);
instance->setTag(WINDOW_COMMAND, WINDOW_MENUITEMTAG);
instanceMap[menuParent] = instance;
return *(instance);
}
bool NativeMenuModel::isMenuItemEnabled(int tag) {
menu::iterator foundItem = menuItems.find(tag);
if(foundItem == menuItems.end()) {
//return enabled
return true;
}
return foundItem->second.enabled;
}
bool NativeMenuModel::isMenuItemChecked(int tag) {
menu::iterator foundItem = menuItems.find(tag);
if(foundItem == menuItems.end()) {
return false;
}
return foundItem->second.checked;
}
int NativeMenuModel::setMenuItemState (ExtensionString command, bool enabled, bool checked) {
//woo turning O(log n) into O(n) however, the important look up is the tag -> menu so making sure that is faster as it will impact user performance.
menu::iterator it;
for ( it=menuItems.begin() ; it != menuItems.end(); it++ ) {
if(it->second.commandId.compare(command) == 0) {
it->second.enabled = enabled;
it->second.checked = checked;
return NO_ERROR;
}
}
return ERR_NOT_FOUND;
}
ExtensionString NativeMenuModel::getCommandId(int tag) {
menu::iterator foundItem = menuItems.find(tag);
if(foundItem == menuItems.end()) {
return "";
}
return menuItems[tag].commandId;
}
int NativeMenuModel::getOrCreateTag(ExtensionString command)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
commandMap[command] = ++tagCount;
menuItems[tagCount] = NativeMenuItemModel(command, true, false);
return tagCount;
}
return foundItem->second;
}
int NativeMenuModel::setTag(ExtensionString command, int tag)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
commandMap[command] = tag;
menuItems[tag] = NativeMenuItemModel(command, true, false);
return tagCount;
}
return foundItem->second;
}
int NativeMenuModel::getTag(ExtensionString command)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
return -1;
}
return foundItem->second;
}
void NativeMenuModel::setOsItem (int tag, void* theItem) {
menu::iterator foundItem = menuItems.find(tag);
if(foundItem == menuItems.end()) {
return;
}
menuItems[tag].osItem = theItem;
}
void* NativeMenuModel::getOsItem (int tag) {
menu::iterator foundItem = menuItems.find(tag);
if(foundItem == menuItems.end()) {
return NULL;
}
return menuItems[tag].osItem;
}
int NativeMenuModel::removeMenuItem(const ExtensionString& command)
{
menuTag::iterator foundItem = commandMap.find(command);
if(foundItem == commandMap.end()) {
return ERR_NOT_FOUND;
}
menuItems.erase(foundItem->second);
commandMap.erase(foundItem);
return NO_ERROR;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "BasicsC/common.h"
#include <stdio.h>
#include <iomanip>
#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/random.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/string-buffer.h"
#include "BasicsC/terminal-utils.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient;
////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////
static atomic<int> Started;
////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////
Mutex StartMutex;
////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////
static bool Async = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////
static int BatchSize = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////
static string Collection = "ArangoBenchmark";
////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////
static uint64_t Complexity = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////
static int Concurrency = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////
static bool Delay = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////
static bool KeepAlive = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////
static int Operations = 1000;
////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////
static string TestCase = "version";
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////
#include "Benchmark/test-cases.h"
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////
static void UpdateStartCounter () {
++Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////
static int GetStartCounter () {
return Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////
static void Status (const string& value) {
if (! BaseClient.quiet()) {
cout << value << endl;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription description("STANDARD options");
description
("async", &Async, "send asychronous requests")
("concurrency", &Concurrency, "number of parallel connections")
("requests", &Operations, "total number of operations")
("batch-size", &BatchSize, "number of operations in one batch (0 disables batching)")
("keep-alive", &KeepAlive, "use HTTP keep-alive")
("collection", &Collection, "collection name to use in tests")
("test-case", &TestCase, "test case to use")
("complexity", &Complexity, "complexity parameter for the test")
("delay", &Delay, "use a startup delay (necessary only when run in series)")
("progress", &Progress, "show progress")
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, "--concurrency <concurrency> --requests <request> --test-case <case> ...", argc, argv, "arangob.conf");
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief startup and exit functions
////////////////////////////////////////////////////////////////////////////////
static void arangobEntryFunction ();
static void arangobExitFunction (int, void*);
#ifdef _WIN32
// .............................................................................
// Call this function to do various initialisations for windows only
// .............................................................................
void arangobEntryFunction () {
int maxOpenFiles = 1024;
int res = 0;
// ...........................................................................
// Uncomment this to call this for extended debug information.
// If you familiar with valgrind ... then this is not like that, however
// you do get some similar functionality.
// ...........................................................................
//res = initialiseWindows(TRI_WIN_INITIAL_SET_DEBUG_FLAG, 0);
res = initialiseWindows(TRI_WIN_INITIAL_SET_INVALID_HANLE_HANDLER, 0);
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_SET_MAX_STD_IO,(const char*)(&maxOpenFiles));
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
_exit(1);
}
TRI_Application_Exit_SetExit(arangobExitFunction);
}
static void arangobExitFunction (int exitCode, void* data) {
int res = 0;
// ...........................................................................
// TODO: need a terminate function for windows to be called and cleanup
// any windows specific stuff.
// ...........................................................................
res = finaliseWindows(TRI_WIN_FINAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
exit(1);
}
exit(exitCode);
}
#else
static void arangobEntryFunction () {
}
static void arangobExitFunction (int exitCode, void* data) {
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int ret = EXIT_SUCCESS;
arangobEntryFunction();
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == 0) {
LOG_FATAL_AND_EXIT("invalid value for --server.endpoint ('%s')", BaseClient.endpointString().c_str());
}
BenchmarkOperation* testCase = GetTestCase(TestCase);
if (testCase == 0) {
LOG_FATAL_AND_EXIT("invalid test case name '%s'", TestCase.c_str());
return EXIT_FAILURE; // will not be reached
}
Status("starting threads...");
BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
ConditionVariable startCondition;
vector<Endpoint*> endpoints;
vector<BenchmarkThread*> threads;
const double stepSize = (double) Operations / (double) Concurrency;
int64_t realStep = (int64_t) stepSize;
if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
realStep++;
}
if (realStep % 1000 != 0) {
realStep += 1000 - (realStep % 1000);
}
// add some more offset so we don't get into trouble with threads of different speed
realStep += 10000;
// start client threads
for (int i = 0; i < Concurrency; ++i) {
Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
endpoints.push_back(endpoint);
BenchmarkThread* thread = new BenchmarkThread(testCase,
&startCondition,
&UpdateStartCounter,
i,
(unsigned long) BatchSize,
&operationsCounter,
endpoint,
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
BaseClient.sslProtocol(),
KeepAlive,
Async);
threads.push_back(thread);
thread->setOffset((size_t) (i * realStep));
thread->start();
}
// give all threads a chance to start so they will not miss the broadcast
while (GetStartCounter() < Concurrency) {
usleep(5000);
}
if (Delay) {
Status("sleeping (startup delay)...");
sleep(10);
}
Status("executing tests...");
double start = TRI_microtime();
// broadcast the start signal to all threads
{
ConditionLocker guard(&startCondition);
guard.broadcast();
}
const size_t stepValue = (Operations / 20);
size_t nextReportValue = stepValue;
if (nextReportValue < 100) {
nextReportValue = 100;
}
while (1) {
const size_t numOperations = operationsCounter.getValue();
if (numOperations >= (size_t) Operations) {
break;
}
if (Progress && numOperations >= nextReportValue) {
LOG_INFO("number of operations: %d", (int) nextReportValue);
nextReportValue += stepValue;
}
usleep(20000);
}
double time = TRI_microtime() - start;
double requestTime = 0.0;
for (int i = 0; i < Concurrency; ++i) {
requestTime += threads[i]->getTime();
}
size_t failures = operationsCounter.failures();
cout << endl;
cout << "Total number of operations: " << Operations <<
", keep alive: " << (KeepAlive ? "yes" : "no") <<
", async: " << (Async ? "yes" : "no") <<
", batch size: " << BatchSize <<
", concurrency level (threads): " << Concurrency <<
endl;
cout << "Test case: " << TestCase <<
", complexity: " << Complexity <<
", database: '" << BaseClient.databaseName() <<
"', collection: '" << Collection << "'" <<
endl;
cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) Concurrency) << " s" << endl;
cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) Concurrency) << " s" << endl;
cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;
if (failures > 0) {
cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
}
testCase->tearDown();
for (int i = 0; i < Concurrency; ++i) {
threads[i]->join();
delete threads[i];
delete endpoints[i];
}
delete testCase;
TRIAGENS_REST_SHUTDOWN;
if (failures > 0) {
ret = EXIT_FAILURE;
}
arangobExitFunction(ret, NULL);
return ret;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>included correct init header<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief arango benchmark tool
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include <stdio.h>
#include "ArangoShell/ArangoClient.h"
#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Basics/ProgramOptions.h"
#include "Basics/ProgramOptionsDescription.h"
#include "Basics/StringUtils.h"
#include "BasicsC/init.h"
#include "BasicsC/logging.h"
#include "BasicsC/random.h"
#include "BasicsC/tri-strings.h"
#include "BasicsC/string-buffer.h"
#include "BasicsC/terminal-utils.h"
#include "Rest/Endpoint.h"
#include "Rest/HttpRequest.h"
#include "Rest/InitialiseRest.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Benchmark/BenchmarkCounter.h"
#include "Benchmark/BenchmarkOperation.h"
#include "Benchmark/BenchmarkThread.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::rest;
using namespace triagens::arango;
using namespace triagens::arangob;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief base class for clients
////////////////////////////////////////////////////////////////////////////////
ArangoClient BaseClient;
////////////////////////////////////////////////////////////////////////////////
/// @brief started counter
////////////////////////////////////////////////////////////////////////////////
static atomic<int> Started;
////////////////////////////////////////////////////////////////////////////////
/// @brief mutex for start counter
////////////////////////////////////////////////////////////////////////////////
Mutex StartMutex;
////////////////////////////////////////////////////////////////////////////////
/// @brief send asychronous requests
////////////////////////////////////////////////////////////////////////////////
static bool Async = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations in one batch
////////////////////////////////////////////////////////////////////////////////
static int BatchSize = 0;
////////////////////////////////////////////////////////////////////////////////
/// @brief collection to use
////////////////////////////////////////////////////////////////////////////////
static string Collection = "ArangoBenchmark";
////////////////////////////////////////////////////////////////////////////////
/// @brief complexity parameter for tests
////////////////////////////////////////////////////////////////////////////////
static uint64_t Complexity = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief concurrency
////////////////////////////////////////////////////////////////////////////////
static int Concurrency = 1;
////////////////////////////////////////////////////////////////////////////////
/// @brief use a startup delay
////////////////////////////////////////////////////////////////////////////////
static bool Delay = false;
////////////////////////////////////////////////////////////////////////////////
/// @brief use HTTP keep-alive
////////////////////////////////////////////////////////////////////////////////
static bool KeepAlive = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief number of operations to perform
////////////////////////////////////////////////////////////////////////////////
static int Operations = 1000;
////////////////////////////////////////////////////////////////////////////////
/// @brief display progress
////////////////////////////////////////////////////////////////////////////////
static bool Progress = true;
////////////////////////////////////////////////////////////////////////////////
/// @brief test case to use
////////////////////////////////////////////////////////////////////////////////
static string TestCase = "version";
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief includes all the test cases
////////////////////////////////////////////////////////////////////////////////
#include "Benchmark/test-cases.h"
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief update the number of ready threads. this is a callback function
/// that is called by each thread after it is created
////////////////////////////////////////////////////////////////////////////////
static void UpdateStartCounter () {
++Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the value of the number of started threads counter
////////////////////////////////////////////////////////////////////////////////
static int GetStartCounter () {
return Started;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief print a status line (if ! quiet)
////////////////////////////////////////////////////////////////////////////////
static void Status (const string& value) {
if (! BaseClient.quiet()) {
cout << value << endl;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief parses the program options
////////////////////////////////////////////////////////////////////////////////
static void ParseProgramOptions (int argc, char* argv[]) {
ProgramOptionsDescription description("STANDARD options");
description
("async", &Async, "send asychronous requests")
("concurrency", &Concurrency, "number of parallel connections")
("requests", &Operations, "total number of operations")
("batch-size", &BatchSize, "number of operations in one batch (0 disables batching)")
("keep-alive", &KeepAlive, "use HTTP keep-alive")
("collection", &Collection, "collection name to use in tests")
("test-case", &TestCase, "test case to use")
("complexity", &Complexity, "complexity parameter for the test")
("delay", &Delay, "use a startup delay (necessary only when run in series)")
("progress", &Progress, "show progress")
;
BaseClient.setupGeneral(description);
BaseClient.setupServer(description);
vector<string> arguments;
description.arguments(&arguments);
ProgramOptions options;
BaseClient.parse(options, description, "--concurrency <concurrency> --requests <request> --test-case <case> ...", argc, argv, "arangob.conf");
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Benchmark
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief startup and exit functions
////////////////////////////////////////////////////////////////////////////////
static void arangobEntryFunction ();
static void arangobExitFunction (int, void*);
#ifdef _WIN32
// .............................................................................
// Call this function to do various initialisations for windows only
// .............................................................................
void arangobEntryFunction () {
int maxOpenFiles = 1024;
int res = 0;
// ...........................................................................
// Uncomment this to call this for extended debug information.
// If you familiar with valgrind ... then this is not like that, however
// you do get some similar functionality.
// ...........................................................................
//res = initialiseWindows(TRI_WIN_INITIAL_SET_DEBUG_FLAG, 0);
res = initialiseWindows(TRI_WIN_INITIAL_SET_INVALID_HANLE_HANDLER, 0);
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_SET_MAX_STD_IO,(const char*)(&maxOpenFiles));
if (res != 0) {
_exit(1);
}
res = initialiseWindows(TRI_WIN_INITIAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
_exit(1);
}
TRI_Application_Exit_SetExit(arangobExitFunction);
}
static void arangobExitFunction (int exitCode, void* data) {
int res = 0;
// ...........................................................................
// TODO: need a terminate function for windows to be called and cleanup
// any windows specific stuff.
// ...........................................................................
res = finaliseWindows(TRI_WIN_FINAL_WSASTARTUP_FUNCTION_CALL, 0);
if (res != 0) {
exit(1);
}
exit(exitCode);
}
#else
static void arangobEntryFunction () {
}
static void arangobExitFunction (int exitCode, void* data) {
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief main
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int ret = EXIT_SUCCESS;
arangobEntryFunction();
TRIAGENS_C_INITIALISE(argc, argv);
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseLogging(false);
BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());
// .............................................................................
// parse the program options
// .............................................................................
ParseProgramOptions(argc, argv);
// .............................................................................
// set-up client connection
// .............................................................................
BaseClient.createEndpoint();
if (BaseClient.endpointServer() == 0) {
LOG_FATAL_AND_EXIT("invalid value for --server.endpoint ('%s')", BaseClient.endpointString().c_str());
}
BenchmarkOperation* testCase = GetTestCase(TestCase);
if (testCase == 0) {
LOG_FATAL_AND_EXIT("invalid test case name '%s'", TestCase.c_str());
return EXIT_FAILURE; // will not be reached
}
Status("starting threads...");
BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);
ConditionVariable startCondition;
vector<Endpoint*> endpoints;
vector<BenchmarkThread*> threads;
const double stepSize = (double) Operations / (double) Concurrency;
int64_t realStep = (int64_t) stepSize;
if (stepSize - (double) ((int64_t) stepSize) > 0.0) {
realStep++;
}
if (realStep % 1000 != 0) {
realStep += 1000 - (realStep % 1000);
}
// add some more offset so we don't get into trouble with threads of different speed
realStep += 10000;
// start client threads
for (int i = 0; i < Concurrency; ++i) {
Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());
endpoints.push_back(endpoint);
BenchmarkThread* thread = new BenchmarkThread(testCase,
&startCondition,
&UpdateStartCounter,
i,
(unsigned long) BatchSize,
&operationsCounter,
endpoint,
BaseClient.databaseName(),
BaseClient.username(),
BaseClient.password(),
BaseClient.requestTimeout(),
BaseClient.connectTimeout(),
BaseClient.sslProtocol(),
KeepAlive,
Async);
threads.push_back(thread);
thread->setOffset((size_t) (i * realStep));
thread->start();
}
// give all threads a chance to start so they will not miss the broadcast
while (GetStartCounter() < Concurrency) {
usleep(5000);
}
if (Delay) {
Status("sleeping (startup delay)...");
sleep(10);
}
Status("executing tests...");
double start = TRI_microtime();
// broadcast the start signal to all threads
{
ConditionLocker guard(&startCondition);
guard.broadcast();
}
const size_t stepValue = (Operations / 20);
size_t nextReportValue = stepValue;
if (nextReportValue < 100) {
nextReportValue = 100;
}
while (1) {
const size_t numOperations = operationsCounter.getValue();
if (numOperations >= (size_t) Operations) {
break;
}
if (Progress && numOperations >= nextReportValue) {
LOG_INFO("number of operations: %d", (int) nextReportValue);
nextReportValue += stepValue;
}
usleep(20000);
}
double time = TRI_microtime() - start;
double requestTime = 0.0;
for (int i = 0; i < Concurrency; ++i) {
requestTime += threads[i]->getTime();
}
size_t failures = operationsCounter.failures();
cout << endl;
cout << "Total number of operations: " << Operations <<
", keep alive: " << (KeepAlive ? "yes" : "no") <<
", async: " << (Async ? "yes" : "no") <<
", batch size: " << BatchSize <<
", concurrency level (threads): " << Concurrency <<
endl;
cout << "Test case: " << TestCase <<
", complexity: " << Complexity <<
", database: '" << BaseClient.databaseName() <<
"', collection: '" << Collection << "'" <<
endl;
cout << "Total request/response duration (sum of all threads): " << fixed << requestTime << " s" << endl;
cout << "Request/response duration (per thread): " << fixed << (requestTime / (double) Concurrency) << " s" << endl;
cout << "Time needed per operation: " << fixed << (time / Operations) << " s" << endl;
cout << "Time needed per operation per thread: " << fixed << (time / (double) Operations * (double) Concurrency) << " s" << endl;
cout << "Operations per second rate: " << fixed << ((double) Operations / time) << endl;
cout << "Elapsed time since start: " << fixed << time << " s" << endl << endl;
if (failures > 0) {
cerr << "WARNING: " << failures << " arangob request(s) failed!!" << endl;
}
testCase->tearDown();
for (int i = 0; i < Concurrency; ++i) {
threads[i]->join();
delete threads[i];
delete endpoints[i];
}
delete testCase;
TRIAGENS_REST_SHUTDOWN;
if (failures > 0) {
ret = EXIT_FAILURE;
}
arangobExitFunction(ret, NULL);
return ret;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>
|
<commit_before>/*
* Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.
*/
#include "FunctionBuilder.h"
#include "ModuleBuilder.h"
#include "Manager.h"
#include <Fabric/Core/CG/OverloadNames.h>
#include <Fabric/Core/RT/Manager.h>
#include <llvm/Module.h>
#include <llvm/Function.h>
#include <llvm/Analysis/Verifier.h>
namespace Fabric
{
namespace CG
{
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
std::string const &pencilName,
std::string const &symbolName,
RC::ConstHandle<Adapter> const &returnAdapter,
ParamVector const ¶ms,
size_t flags,
size_t cost
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
build( pencilName, symbolName, returnAdapter, params, flags, cost );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
std::string const &pencilName,
std::string const &symbolName,
std::string const ¶mLayout,
size_t flags
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
RC::Handle<CG::Manager> manager = moduleBuilder.getManager();
CG::ParamVector paramList;
RC::ConstHandle<Adapter> returnAdapter;
if( !paramLayout.empty() )
{
// The parameter layout is defined thus "{=,<,>}[Type]:[Name]"
// E.g.: "=Scalar,<Integer:num,>Integer:tex"
// corresponds to the following KL function:
/// Scalar foo( in Integer num, io/out Integer tex );
size_t start, end;
start = 0;
do
{
end = paramLayout.find( ',', start + 1 );
CG::Usage usage = CG::USAGE_UNSPECIFIED;
if ( paramLayout[ start ] == '<' )
usage = CG::USAGE_RVALUE;
else if ( paramLayout[ start ] == '>' )
usage = CG::USAGE_LVALUE;
else if ( paramLayout[ start ] == '=' )
{
if ( returnAdapter )
throw Exception( "Malformed function param layout string. Return type already specified: " + paramLayout );
std::string rtype = paramLayout.substr( start + 1, end - start - 1 );
RC::ConstHandle<RT::Desc> typeDesc = manager->getRTManager()->getDesc( rtype );
returnAdapter = manager->getAdapter( typeDesc );
}
else
throw Exception( "Malformed function param layout string. Missing in/out marker: " + paramLayout.substr( start, end - start ) );
if ( usage != CG::USAGE_UNSPECIFIED )
{
size_t split = paramLayout.find( ' ', start + 2 );
if ( split > end )
throw Exception( "Malformed function param layout string. Missing type: " + paramLayout.substr( start, end - start ) );
std::string ptype = paramLayout.substr( start + 1, split - start - 1 );
RC::ConstHandle<RT::Desc> typeDesc = manager->getRTManager()->getDesc( ptype );
RC::ConstHandle<CG::Adapter> typeAdapter = manager->getAdapter( typeDesc );
std::string pname = paramLayout.substr( split + 1, end - split - 1 );
if ( pname.empty() )
throw Exception( "Malformed function param layout string. Missing param name: " + paramLayout.substr( start, end - start ) );
paramList.push_back( CG::FunctionParam( pname, typeAdapter, usage ) );
}
start = end + 1;
} while( end != std::string::npos );
}
build( pencilName, symbolName, returnAdapter, paramList, flags );
}
void FunctionBuilder::build(
std::string const &pencilName,
std::string const &symbolName,
RC::ConstHandle<Adapter> const &returnAdapter,
ParamVector const ¶ms,
size_t flags,
size_t cost
)
{
RC::Handle<Context> context = getContext();
llvm::Type const *llvmReturnType = 0;
std::vector<llvm::Type const *> llvmParamTypes;
if ( flags & DirectlyReturnLValue )
{
m_haveHiddenReturnLValue = false;
llvmReturnType = returnAdapter->llvmLType( context );
}
else if ( flags & DirectlyReturnRValue )
{
m_haveHiddenReturnLValue = false;
llvmReturnType = returnAdapter->llvmRType( context );
}
else if ( returnAdapter )
{
if ( returnAdapter->usesReturnLValue() )
{
m_haveHiddenReturnLValue = true;
llvmReturnType = llvm::Type::getVoidTy( context->getLLVMContext() );
llvmParamTypes.push_back( returnAdapter->llvmLType( context ) );
}
else
{
m_haveHiddenReturnLValue = false;
llvmReturnType = returnAdapter->llvmRType( context );
}
}
else
{
m_haveHiddenReturnLValue = false;
llvmReturnType = llvm::Type::getVoidTy( context->getLLVMContext() );
}
for ( size_t i=0; i<params.size(); ++i )
llvmParamTypes.push_back( params[i].getLLVMType( context ) );
m_llvmFunctionType = llvm::FunctionType::get( llvmReturnType, llvmParamTypes, false );
llvm::AttributeWithIndex AWI[1];
AWI[0] = llvm::AttributeWithIndex::get( ~0u, llvm::Attribute::InlineHint );
llvm::AttrListPtr attrListPtr = llvm::AttrListPtr::get(AWI, 1);
llvm::Function *existingLLVMFunction = m_moduleBuilder->getFunction( symbolName.c_str() );
if ( existingLLVMFunction )
{
// [pzion 20110825] FIXME: should verify sanity here through asserts on types, attributes
// and linkage
m_llvmFunction = existingLLVMFunction;
}
else
{
m_llvmFunction = llvm::cast<llvm::Function>( m_moduleBuilder->getOrInsertFunction( symbolName.c_str(), m_llvmFunctionType, attrListPtr ) );
m_llvmFunction->setLinkage( (flags & ExportSymbol)? llvm::GlobalValue::ExternalLinkage: llvm::GlobalValue::PrivateLinkage );
}
llvm::Function::arg_iterator ai = m_llvmFunction->arg_begin();
ReturnInfo returnInfo( ExprType( returnAdapter, (flags & DirectlyReturnLValue)? USAGE_LVALUE: USAGE_RVALUE ) );
if ( m_haveHiddenReturnLValue )
{
ai->setName( "resultLValue" );
ai->addAttr( llvm::Attribute::NoCapture );
ai->addAttr( llvm::Attribute::NoAlias );
ai->addAttr( llvm::Attribute::StructRet );
returnInfo = ReturnInfo( ExprType( returnAdapter, USAGE_LVALUE ), ai );
++ai;
}
m_functionScope = new FunctionScope( m_moduleBuilder.getScope(), returnInfo );
for ( size_t i=0; i<params.size(); ++i, ++ai )
{
FunctionParam const ¶m = params[i];
ai->setName( param.getName() );
if ( param.getUsage() == USAGE_LVALUE
|| param.getAdapter()->isPassByReference() )
{
ai->addAttr( llvm::Attribute::NoCapture );
ai->addAttr( llvm::Attribute::NoAlias );
}
m_functionScope->put( param.getName(), ParameterSymbol::Create( CG::ExprValue( param.getExprType(), context, ai ) ) );
}
if ( !pencilName.empty() )
m_pencil = m_moduleBuilder.addFunction( pencilName, Function( m_llvmFunction, returnInfo, params, cost ) );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
llvm::FunctionType const *llvmFunctionType,
llvm::Function *llvmFunction
)
: m_moduleBuilder( moduleBuilder )
, m_llvmFunctionType( llvmFunctionType )
, m_llvmFunction( llvmFunction )
, m_haveHiddenReturnLValue( false )
{
ReturnInfo returnInfo( ExprType() );
m_functionScope = new FunctionScope( m_moduleBuilder.getScope(), returnInfo );
}
ModuleBuilder &FunctionBuilder::getModuleBuilder()
{
return m_moduleBuilder;
}
RC::Handle<Manager> FunctionBuilder::getManager()
{
return m_moduleBuilder.getManager();
}
RC::Handle<Context> FunctionBuilder::getContext()
{
return m_moduleBuilder.getContext();
}
llvm::Function *FunctionBuilder::operator ->()
{
return m_llvmFunction;
}
llvm::Function *FunctionBuilder::getLLVMFunction()
{
return m_llvmFunction;
}
FunctionBuilder::~FunctionBuilder()
{
delete m_functionScope;
}
llvm::Argument *FunctionBuilder::operator[]( size_t index )
{
llvm::Function::ArgumentListType &argumentList = m_llvmFunction->getArgumentList();
llvm::Function::ArgumentListType::iterator it = argumentList.begin();
// Skip the 'hidden' return value.
if ( m_haveHiddenReturnLValue )
++it;
while ( index-- )
++it;
return it;
}
llvm::BasicBlock *FunctionBuilder::createBasicBlock( std::string const &name )
{
return llvm::BasicBlock::Create( getContext()->getLLVMContext(), name, m_llvmFunction );
}
FunctionScope &FunctionBuilder::getScope()
{
FABRIC_ASSERT( m_functionScope );
return *m_functionScope;
}
RC::ConstHandle<Adapter> FunctionBuilder::maybeGetAdapter( std::string const &userName ) const
{
return m_moduleBuilder.maybeGetAdapter( userName );
}
RC::ConstHandle<Adapter> FunctionBuilder::getAdapter( std::string const &userName, CG::Location const &location ) const
{
return m_moduleBuilder.getAdapter( userName, location );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
RC::ConstHandle<CG::Adapter> const &returnAdapter,
std::string const &functionName,
std::string const ¶m1Name,
RC::ConstHandle<CG::Adapter> const ¶m1Adapter,
Usage param1Usage,
size_t flags
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
ParamVector params;
params.push_back( FriendlyFunctionParam( param1Name, param1Adapter, param1Usage ) );
std::string pencilName = FunctionPencilName( functionName );
std::string symbolName = FunctionDefaultSymbolName( functionName, params.getTypes() );
build( pencilName, symbolName, returnAdapter, params, flags );
getModuleBuilder().getScope().put( functionName, getPencil() );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
RC::ConstHandle<CG::Adapter> const &returnAdapter,
std::string const &functionName,
std::string const ¶m1Name,
RC::ConstHandle<CG::Adapter> const ¶m1Adapter,
Usage param1Usage,
std::string const ¶m2Name,
RC::ConstHandle<CG::Adapter> const ¶m2Adapter,
Usage param2Usage,
size_t flags
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
ParamVector params;
params.push_back( FriendlyFunctionParam( param1Name, param1Adapter, param1Usage ) );
params.push_back( FriendlyFunctionParam( param2Name, param2Adapter, param2Usage ) );
std::string pencilName = FunctionPencilName( functionName );
std::string symbolName = FunctionDefaultSymbolName( functionName, params.getTypes() );
build( pencilName, symbolName, returnAdapter, params, flags );
getModuleBuilder().getScope().put( functionName, getPencil() );
}
RC::ConstHandle<PencilSymbol> FunctionBuilder::getPencil() const
{
return m_pencil;
}
}
}
<commit_msg>Accidentally checked in wrong FunctionBuilder, fixing.<commit_after>/*
* Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.
*/
#include "FunctionBuilder.h"
#include "ModuleBuilder.h"
#include "Manager.h"
#include <Fabric/Core/CG/OverloadNames.h>
#include <Fabric/Core/RT/Manager.h>
#include <llvm/Module.h>
#include <llvm/Function.h>
#include <llvm/Analysis/Verifier.h>
namespace Fabric
{
namespace CG
{
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
std::string const &pencilName,
std::string const &symbolName,
RC::ConstHandle<Adapter> const &returnAdapter,
ParamVector const ¶ms,
size_t flags,
size_t cost
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
build( pencilName, symbolName, returnAdapter, params, flags, cost );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
std::string const &pencilName,
std::string const &symbolName,
std::string const ¶mLayout,
size_t flags
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
RC::Handle<CG::Manager> manager = moduleBuilder.getManager();
CG::ParamVector paramList;
RC::ConstHandle<Adapter> returnAdapter;
if( !paramLayout.empty() )
{
// The parameter layout is defined thus "{=,<,>}[Type]:[Name]"
// E.g.: "=Scalar,<Integer:num,>Integer:tex"
// corresponds to the following KL function:
/// Scalar foo( in Integer num, io/out Integer tex );
size_t start, end;
start = 0;
do
{
end = paramLayout.find( ',', start + 1 );
CG::Usage usage = CG::USAGE_UNSPECIFIED;
if ( paramLayout[ start ] == '<' )
usage = CG::USAGE_RVALUE;
else if ( paramLayout[ start ] == '>' )
usage = CG::USAGE_LVALUE;
else if ( paramLayout[ start ] == '=' )
{
if ( returnAdapter )
throw Exception( "Malformed function param layout string. Return type already specified: " + paramLayout );
std::string rtype = paramLayout.substr( start + 1, end - start - 1 );
RC::ConstHandle<RT::Desc> typeDesc = manager->getRTManager()->getDesc( rtype );
returnAdapter = manager->getAdapter( typeDesc );
}
else
throw Exception( "Malformed function param layout string. Missing in/out marker: " + paramLayout.substr( start, end - start ) );
if ( usage != CG::USAGE_UNSPECIFIED )
{
size_t split = paramLayout.find( ' ', start + 2 );
if ( split > end )
throw Exception( "Malformed function param layout string. Missing type: " + paramLayout.substr( start, end - start ) );
std::string ptype = paramLayout.substr( start + 1, split - start - 1 );
RC::ConstHandle<RT::Desc> typeDesc = manager->getRTManager()->getDesc( ptype );
RC::ConstHandle<CG::Adapter> typeAdapter = manager->getAdapter( typeDesc );
std::string pname = paramLayout.substr( split + 1, end - split - 1 );
if ( pname.empty() )
throw Exception( "Malformed function param layout string. Missing param name: " + paramLayout.substr( start, end - start ) );
paramList.push_back( CG::FunctionParam( pname, typeAdapter, usage ) );
}
start = end + 1;
} while( end != std::string::npos );
}
build( pencilName, symbolName, returnAdapter, paramList, flags );
}
void FunctionBuilder::build(
std::string const &pencilName,
std::string const &symbolName,
RC::ConstHandle<Adapter> const &returnAdapter,
ParamVector const ¶ms,
size_t flags,
size_t cost
)
{
RC::Handle<Context> context = getContext();
llvm::Type const *llvmReturnType = 0;
std::vector<llvm::Type const *> llvmParamTypes;
if ( flags & DirectlyReturnLValue )
{
m_haveHiddenReturnLValue = false;
llvmReturnType = returnAdapter->llvmLType( context );
}
else if ( flags & DirectlyReturnRValue )
{
m_haveHiddenReturnLValue = false;
llvmReturnType = returnAdapter->llvmRType( context );
}
else if ( returnAdapter )
{
if ( returnAdapter->usesReturnLValue() )
{
m_haveHiddenReturnLValue = true;
llvmReturnType = llvm::Type::getVoidTy( context->getLLVMContext() );
llvmParamTypes.push_back( returnAdapter->llvmLType( context ) );
}
else
{
m_haveHiddenReturnLValue = false;
llvmReturnType = returnAdapter->llvmRType( context );
}
}
else
{
m_haveHiddenReturnLValue = false;
llvmReturnType = llvm::Type::getVoidTy( context->getLLVMContext() );
}
for ( size_t i=0; i<params.size(); ++i )
llvmParamTypes.push_back( params[i].getLLVMType( context ) );
m_llvmFunctionType = llvm::FunctionType::get( llvmReturnType, llvmParamTypes, false );
llvm::AttributeWithIndex AWI[1];
AWI[0] = llvm::AttributeWithIndex::get( ~0u, llvm::Attribute::InlineHint );
llvm::AttrListPtr attrListPtr = llvm::AttrListPtr::get(AWI, 1);
llvm::Function *existingLLVMFunction = m_moduleBuilder->getFunction( symbolName.c_str() );
if ( existingLLVMFunction )
{
// [pzion 20110825] FIXME: should verify sanity here through asserts on types, attributes
// and linkage
m_llvmFunction = existingLLVMFunction;
}
else
{
m_llvmFunction = llvm::cast<llvm::Function>( m_moduleBuilder->getOrInsertFunction( symbolName.c_str(), m_llvmFunctionType, attrListPtr ) );
m_llvmFunction->setLinkage( (flags & ExportSymbol)? llvm::GlobalValue::ExternalLinkage: llvm::GlobalValue::PrivateLinkage );
}
llvm::Function::arg_iterator ai = m_llvmFunction->arg_begin();
ReturnInfo returnInfo( ExprType( returnAdapter, (flags & DirectlyReturnLValue)? USAGE_LVALUE: USAGE_RVALUE ) );
if ( m_haveHiddenReturnLValue )
{
ai->setName( "resultLValue" );
ai->addAttr( llvm::Attribute::NoCapture );
ai->addAttr( llvm::Attribute::NoAlias );
ai->addAttr( llvm::Attribute::StructRet );
returnInfo = ReturnInfo( ExprType( returnAdapter, USAGE_LVALUE ), ai );
++ai;
}
m_functionScope = new FunctionScope( m_moduleBuilder.getScope(), returnInfo );
for ( size_t i=0; i<params.size(); ++i, ++ai )
{
FunctionParam const ¶m = params[i];
ai->setName( param.getName() );
if ( param.getUsage() == USAGE_LVALUE
|| param.getAdapter()->isPassByReference() )
{
ai->addAttr( llvm::Attribute::NoCapture );
ai->addAttr( llvm::Attribute::NoAlias );
}
m_functionScope->put( param.getName(), ParameterSymbol::Create( CG::ExprValue( param.getExprType(), context, ai ) ) );
}
if ( !pencilName.empty() )
m_pencil = m_moduleBuilder.addFunction( pencilName, Function( m_llvmFunction, returnInfo, params, cost ) );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
llvm::FunctionType const *llvmFunctionType,
llvm::Function *llvmFunction
)
: m_moduleBuilder( moduleBuilder )
, m_llvmFunctionType( llvmFunctionType )
, m_llvmFunction( llvmFunction )
, m_haveHiddenReturnLValue( false )
{
ReturnInfo returnInfo( ExprType(), 0 );
m_functionScope = new FunctionScope( m_moduleBuilder.getScope(), returnInfo );
}
ModuleBuilder &FunctionBuilder::getModuleBuilder()
{
return m_moduleBuilder;
}
RC::Handle<Manager> FunctionBuilder::getManager()
{
return m_moduleBuilder.getManager();
}
RC::Handle<Context> FunctionBuilder::getContext()
{
return m_moduleBuilder.getContext();
}
llvm::Function *FunctionBuilder::operator ->()
{
return m_llvmFunction;
}
llvm::Function *FunctionBuilder::getLLVMFunction()
{
return m_llvmFunction;
}
FunctionBuilder::~FunctionBuilder()
{
delete m_functionScope;
}
llvm::Argument *FunctionBuilder::operator[]( size_t index )
{
llvm::Function::ArgumentListType &argumentList = m_llvmFunction->getArgumentList();
llvm::Function::ArgumentListType::iterator it = argumentList.begin();
// Skip the 'hidden' return value.
if ( m_haveHiddenReturnLValue )
++it;
while ( index-- )
++it;
return it;
}
llvm::BasicBlock *FunctionBuilder::createBasicBlock( std::string const &name )
{
return llvm::BasicBlock::Create( getContext()->getLLVMContext(), name, m_llvmFunction );
}
FunctionScope &FunctionBuilder::getScope()
{
FABRIC_ASSERT( m_functionScope );
return *m_functionScope;
}
RC::ConstHandle<Adapter> FunctionBuilder::maybeGetAdapter( std::string const &userName ) const
{
return m_moduleBuilder.maybeGetAdapter( userName );
}
RC::ConstHandle<Adapter> FunctionBuilder::getAdapter( std::string const &userName, CG::Location const &location ) const
{
return m_moduleBuilder.getAdapter( userName, location );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
RC::ConstHandle<CG::Adapter> const &returnAdapter,
std::string const &functionName,
std::string const ¶m1Name,
RC::ConstHandle<CG::Adapter> const ¶m1Adapter,
Usage param1Usage,
size_t flags
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
ParamVector params;
params.push_back( FriendlyFunctionParam( param1Name, param1Adapter, param1Usage ) );
std::string pencilName = FunctionPencilName( functionName );
std::string symbolName = FunctionDefaultSymbolName( functionName, params.getTypes() );
build( pencilName, symbolName, returnAdapter, params, flags );
getModuleBuilder().getScope().put( functionName, getPencil() );
}
FunctionBuilder::FunctionBuilder(
ModuleBuilder &moduleBuilder,
RC::ConstHandle<CG::Adapter> const &returnAdapter,
std::string const &functionName,
std::string const ¶m1Name,
RC::ConstHandle<CG::Adapter> const ¶m1Adapter,
Usage param1Usage,
std::string const ¶m2Name,
RC::ConstHandle<CG::Adapter> const ¶m2Adapter,
Usage param2Usage,
size_t flags
)
: m_moduleBuilder( moduleBuilder )
, m_functionScope( NULL )
{
ParamVector params;
params.push_back( FriendlyFunctionParam( param1Name, param1Adapter, param1Usage ) );
params.push_back( FriendlyFunctionParam( param2Name, param2Adapter, param2Usage ) );
std::string pencilName = FunctionPencilName( functionName );
std::string symbolName = FunctionDefaultSymbolName( functionName, params.getTypes() );
build( pencilName, symbolName, returnAdapter, params, flags );
getModuleBuilder().getScope().put( functionName, getPencil() );
}
RC::ConstHandle<PencilSymbol> FunctionBuilder::getPencil() const
{
return m_pencil;
}
}
}
<|endoftext|>
|
<commit_before>// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
/**
* @param A an integer array
* @param start an integer
* @param end an integer
* @return the number of possible answer
*/
int subarraySumII(vector<int>& A, int start, int end) {
// sum_from_start[i] denotes sum for 0 ~ i - 1.
vector<int> sum_from_start(A.size() + 1);
partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1);
int result = 0;
for (int i = 0, j = 0; j < A.size(); ++j) {
if (sum_from_start[j + 1] >= start) {
auto l = lower_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1,
sum_from_start[j + 1] - end);
auto r = upper_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1,
sum_from_start[j + 1] - start);
if (l != sum_from_start.begin() + j + 1) {
result += (r - sum_from_start.begin()) - (l - sum_from_start.begin());
}
}
}
return result;
}
};
// Time: O(n^2)
// Space: O(n)
class Solution2 {
public:
/**
* @param A an integer array
* @param start an integer
* @param end an integer
* @return the number of possible answer
*/
int subarraySumII(vector<int>& A, int start, int end) {
// sum_from_start[i] denotes sum for 0 ~ i - 1.
vector<int> sum_from_start(A.size() + 1);
partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1);
int result = 0;
for (int i = 0, j = 0; j < A.size(); ++j) {
int k = i;
while (k <= j) {
if (sum_from_start[j + 1] - sum_from_start[k] >= start &&
sum_from_start[j + 1] - sum_from_start[k] <= end) {
++result;
}
++k;
}
}
return result;
}
};
<commit_msg>Update subarray-sum-ii.cpp<commit_after>// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
/**
* @param A an integer array
* @param start an integer
* @param end an integer
* @return the number of possible answer
*/
int subarraySumII(vector<int>& A, int start, int end) {
// sum_from_start[i] denotes sum for 0 ~ i - 1.
vector<int> sum_from_start(A.size() + 1);
partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1);
int result = 0;
for (int i = 0, j = 0; j < A.size(); ++j) {
auto l = lower_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1,
sum_from_start[j + 1] - end);
auto r = upper_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1,
sum_from_start[j + 1] - start);
result += (r - sum_from_start.begin()) - (l - sum_from_start.begin());
}
return result;
}
};
// Time: O(n^2)
// Space: O(n)
class Solution2 {
public:
/**
* @param A an integer array
* @param start an integer
* @param end an integer
* @return the number of possible answer
*/
int subarraySumII(vector<int>& A, int start, int end) {
// sum_from_start[i] denotes sum for 0 ~ i - 1.
vector<int> sum_from_start(A.size() + 1);
partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1);
int result = 0;
for (int i = 0, j = 0; j < A.size(); ++j) {
int k = i;
while (k <= j) {
if (sum_from_start[j + 1] - sum_from_start[k] >= start &&
sum_from_start[j + 1] - sum_from_start[k] <= end) {
++result;
}
++k;
}
}
return result;
}
};
<|endoftext|>
|
<commit_before>#include "ScalarType.h"
#include "Utils.h"
#include <cassert>
ScalarType::ScalarType()
{
}
ScalarType::ScalarType(double value)
:value(value)
{
}
ScalarType::ScalarType(double value, double tb)
:value(value)
,tiebreaker(tiebreaker)
{
assert(tiebreaker > 0. && tiebreaker < 1.);
}
void ScalarType::from_prior(RNG& rng)
{
tiebreaker = rng.rand();
}
double ScalarType::perturb(RNG& rng)
{
tiebreaker += rng.randh();
wrap(tiebreaker, 0., 1.);
return 0.;
}
bool operator < (const ScalarType& s1, const ScalarType& s2)
{
bool result = false;
if(s1.value < s2.value)
result = true;
else if(s1.value == s2.value && s1.tiebreaker < s2.tiebreaker)
result = true;
return result;
}
bool operator <= (const ScalarType& s1, const ScalarType& s2)
{
bool result = false;
if(s1.value < s2.value)
result = true;
else if(s1.value == s2.value && s1.tiebreaker <= s2.tiebreaker)
result = true;
return result;
}
<commit_msg>Fixed bug<commit_after>#include "ScalarType.h"
#include "Utils.h"
#include <cassert>
ScalarType::ScalarType()
{
}
ScalarType::ScalarType(double value)
:value(value)
{
}
ScalarType::ScalarType(double value, double tb)
:value(value)
,tiebreaker(tb)
{
assert(tiebreaker > 0. && tiebreaker < 1.);
}
void ScalarType::from_prior(RNG& rng)
{
tiebreaker = rng.rand();
}
double ScalarType::perturb(RNG& rng)
{
tiebreaker += rng.randh();
wrap(tiebreaker, 0., 1.);
return 0.;
}
bool operator < (const ScalarType& s1, const ScalarType& s2)
{
bool result = false;
if(s1.value < s2.value)
result = true;
else if(s1.value == s2.value && s1.tiebreaker < s2.tiebreaker)
result = true;
return result;
}
bool operator <= (const ScalarType& s1, const ScalarType& s2)
{
bool result = false;
if(s1.value < s2.value)
result = true;
else if(s1.value == s2.value && s1.tiebreaker <= s2.tiebreaker)
result = true;
return result;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_screen.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "chrome/browser/chromeos/login/authenticator.h"
#include "chrome/browser/chromeos/login/screen_observer.h"
#include "chrome/browser/policy/auto_enrollment_client.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud_policy_data_store.h"
#include "chrome/browser/policy/enterprise_metrics.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
namespace chromeos {
namespace {
// Retry for InstallAttrs initialization every 500ms.
const int kLockRetryIntervalMs = 500;
} // namespace
EnterpriseEnrollmentScreen::EnterpriseEnrollmentScreen(
ScreenObserver* observer,
EnterpriseEnrollmentScreenActor* actor)
: WizardScreen(observer),
actor_(actor),
is_auto_enrollment_(false),
is_showing_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
actor_->SetController(this);
// Init the TPM if it has not been done until now (in debug build we might
// have not done that yet).
chromeos::CryptohomeLibrary* cryptohome =
chromeos::CrosLibrary::Get()->GetCryptohomeLibrary();
if (cryptohome &&
cryptohome->TpmIsEnabled() &&
!cryptohome->TpmIsBeingOwned() &&
!cryptohome->TpmIsOwned()) {
cryptohome->TpmCanAttemptOwnership();
}
}
EnterpriseEnrollmentScreen::~EnterpriseEnrollmentScreen() {}
void EnterpriseEnrollmentScreen::SetParameters(bool is_auto_enrollment,
const std::string& user) {
is_auto_enrollment_ = is_auto_enrollment;
user_ = user.empty() ? user : Authenticator::Canonicalize(user);
}
void EnterpriseEnrollmentScreen::PrepareToShow() {
actor_->PrepareToShow();
}
void EnterpriseEnrollmentScreen::Show() {
is_showing_ = true;
actor_->Show();
}
void EnterpriseEnrollmentScreen::Hide() {
is_showing_ = false;
actor_->Hide();
}
void EnterpriseEnrollmentScreen::OnOAuthTokenAvailable(
const std::string& user,
const std::string& token) {
user_ = Authenticator::Canonicalize(user);
RegisterForDevicePolicy(token);
}
void EnterpriseEnrollmentScreen::OnConfirmationClosed(bool go_back_to_signin) {
// If the machine has been put in KIOSK mode we have to restart the session
// here to go in the proper KIOSK mode login screen.
policy::BrowserPolicyConnector* policy_connector =
g_browser_process->browser_policy_connector();
if (policy_connector && policy_connector->GetDeviceCloudPolicyDataStore() &&
policy_connector->GetDeviceCloudPolicyDataStore()->device_mode() ==
policy::DEVICE_MODE_KIOSK) {
DBusThreadManager::Get()->GetSessionManagerClient()->StopSession();
return;
}
get_screen_observer()->OnExit(go_back_to_signin ?
ScreenObserver::ENTERPRISE_ENROLLMENT_COMPLETED :
ScreenObserver::ENTERPRISE_AUTO_MAGIC_ENROLLMENT_COMPLETED);
}
bool EnterpriseEnrollmentScreen::IsAutoEnrollment(std::string* user) {
if (is_auto_enrollment_)
*user = user_;
return is_auto_enrollment_;
}
void EnterpriseEnrollmentScreen::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
if (is_showing_) {
switch (state) {
case policy::CloudPolicySubsystem::UNENROLLED:
switch (error_details) {
case policy::CloudPolicySubsystem::BAD_SERIAL_NUMBER:
actor_->ShowSerialNumberError();
break;
case policy::CloudPolicySubsystem::BAD_ENROLLMENT_MODE:
actor_->ShowEnrollmentModeError();
break;
default: // Still working...
return;
}
break;
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
actor_->ShowFatalEnrollmentError();
break;
case policy::CloudPolicySubsystem::UNMANAGED:
actor_->ShowAccountError();
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
actor_->ShowNetworkEnrollmentError();
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
if (!is_auto_enrollment_ ||
g_browser_process->browser_policy_connector()->
GetDeviceCloudPolicyDataStore()->device_mode() ==
policy::DEVICE_MODE_ENTERPRISE) {
WriteInstallAttributesData();
return;
} else {
LOG(ERROR) << "Enrollment can not proceed because Auto-enrollment is "
<< "not supported for non-enterprise enrollment modes.";
policy::AutoEnrollmentClient::CancelAutoEnrollment();
is_auto_enrollment_ = false;
actor_->ShowAutoEnrollmentError();
// Set the error state to something distinguishable in the logs.
state = policy::CloudPolicySubsystem::LOCAL_ERROR;
error_details = policy::CloudPolicySubsystem::AUTO_ENROLLMENT_ERROR;
}
break;
case policy::CloudPolicySubsystem::SUCCESS:
// Success!
registrar_.reset();
actor_->ShowConfirmationScreen();
return;
}
// We have an error.
if (!is_auto_enrollment_) {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentPolicyFailed,
policy::kMetricEnrollmentSize);
}
LOG(WARNING) << "Policy subsystem error during enrollment: " << state
<< " details: " << error_details;
}
// Stop the policy infrastructure.
registrar_.reset();
g_browser_process->browser_policy_connector()->ResetDevicePolicy();
}
void EnterpriseEnrollmentScreen::WriteInstallAttributesData() {
// Since this method is also called directly.
weak_ptr_factory_.InvalidateWeakPtrs();
switch (g_browser_process->browser_policy_connector()->LockDevice(user_)) {
case policy::EnterpriseInstallAttributes::LOCK_SUCCESS: {
// Proceed with policy fetch.
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
connector->FetchCloudPolicy();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_NOT_READY: {
// InstallAttributes not ready yet, retry later.
LOG(WARNING) << "Install Attributes not ready yet will retry in "
<< kLockRetryIntervalMs << "ms.";
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&EnterpriseEnrollmentScreen::WriteInstallAttributesData,
weak_ptr_factory_.GetWeakPtr()),
kLockRetryIntervalMs);
return;
}
case policy::EnterpriseInstallAttributes::LOCK_BACKEND_ERROR: {
actor_->ShowFatalEnrollmentError();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_WRONG_USER: {
LOG(ERROR) << "Enrollment can not proceed because the InstallAttrs "
<< "has been locked already!";
actor_->ShowFatalEnrollmentError();
return;
}
}
NOTREACHED();
}
void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
LOG(ERROR) << "Cloud policy subsystem not initialized.";
} else if (connector->IsEnterpriseManaged()) {
LOG(ERROR) << "Device is already enterprise managed!";
} else if (connector->device_cloud_policy_subsystem()->state() ==
policy::CloudPolicySubsystem::SUCCESS) {
LOG(ERROR) << "A previous enrollment already succeeded!";
} else {
// Make sure the device policy subsystem is in a clean slate.
connector->ResetDevicePolicy();
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
// Push the credentials to the policy infrastructure. It'll start enrollment
// and notify us of progress through CloudPolicySubsystem::Observer.
connector->RegisterForDevicePolicy(user_, token, is_auto_enrollment_);
return;
}
NOTREACHED();
if (is_showing_)
actor_->ShowFatalEnrollmentError();
}
} // namespace chromeos
<commit_msg>Update uses of TimeDelta in enrollment screen code.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_screen.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "chrome/browser/chromeos/login/authenticator.h"
#include "chrome/browser/chromeos/login/screen_observer.h"
#include "chrome/browser/policy/auto_enrollment_client.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud_policy_data_store.h"
#include "chrome/browser/policy/enterprise_metrics.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
namespace chromeos {
namespace {
// Retry for InstallAttrs initialization every 500ms.
const int kLockRetryIntervalMs = 500;
} // namespace
EnterpriseEnrollmentScreen::EnterpriseEnrollmentScreen(
ScreenObserver* observer,
EnterpriseEnrollmentScreenActor* actor)
: WizardScreen(observer),
actor_(actor),
is_auto_enrollment_(false),
is_showing_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
actor_->SetController(this);
// Init the TPM if it has not been done until now (in debug build we might
// have not done that yet).
chromeos::CryptohomeLibrary* cryptohome =
chromeos::CrosLibrary::Get()->GetCryptohomeLibrary();
if (cryptohome &&
cryptohome->TpmIsEnabled() &&
!cryptohome->TpmIsBeingOwned() &&
!cryptohome->TpmIsOwned()) {
cryptohome->TpmCanAttemptOwnership();
}
}
EnterpriseEnrollmentScreen::~EnterpriseEnrollmentScreen() {}
void EnterpriseEnrollmentScreen::SetParameters(bool is_auto_enrollment,
const std::string& user) {
is_auto_enrollment_ = is_auto_enrollment;
user_ = user.empty() ? user : Authenticator::Canonicalize(user);
}
void EnterpriseEnrollmentScreen::PrepareToShow() {
actor_->PrepareToShow();
}
void EnterpriseEnrollmentScreen::Show() {
is_showing_ = true;
actor_->Show();
}
void EnterpriseEnrollmentScreen::Hide() {
is_showing_ = false;
actor_->Hide();
}
void EnterpriseEnrollmentScreen::OnOAuthTokenAvailable(
const std::string& user,
const std::string& token) {
user_ = Authenticator::Canonicalize(user);
RegisterForDevicePolicy(token);
}
void EnterpriseEnrollmentScreen::OnConfirmationClosed(bool go_back_to_signin) {
// If the machine has been put in KIOSK mode we have to restart the session
// here to go in the proper KIOSK mode login screen.
policy::BrowserPolicyConnector* policy_connector =
g_browser_process->browser_policy_connector();
if (policy_connector && policy_connector->GetDeviceCloudPolicyDataStore() &&
policy_connector->GetDeviceCloudPolicyDataStore()->device_mode() ==
policy::DEVICE_MODE_KIOSK) {
DBusThreadManager::Get()->GetSessionManagerClient()->StopSession();
return;
}
get_screen_observer()->OnExit(go_back_to_signin ?
ScreenObserver::ENTERPRISE_ENROLLMENT_COMPLETED :
ScreenObserver::ENTERPRISE_AUTO_MAGIC_ENROLLMENT_COMPLETED);
}
bool EnterpriseEnrollmentScreen::IsAutoEnrollment(std::string* user) {
if (is_auto_enrollment_)
*user = user_;
return is_auto_enrollment_;
}
void EnterpriseEnrollmentScreen::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
if (is_showing_) {
switch (state) {
case policy::CloudPolicySubsystem::UNENROLLED:
switch (error_details) {
case policy::CloudPolicySubsystem::BAD_SERIAL_NUMBER:
actor_->ShowSerialNumberError();
break;
case policy::CloudPolicySubsystem::BAD_ENROLLMENT_MODE:
actor_->ShowEnrollmentModeError();
break;
default: // Still working...
return;
}
break;
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
actor_->ShowFatalEnrollmentError();
break;
case policy::CloudPolicySubsystem::UNMANAGED:
actor_->ShowAccountError();
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
actor_->ShowNetworkEnrollmentError();
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
if (!is_auto_enrollment_ ||
g_browser_process->browser_policy_connector()->
GetDeviceCloudPolicyDataStore()->device_mode() ==
policy::DEVICE_MODE_ENTERPRISE) {
WriteInstallAttributesData();
return;
} else {
LOG(ERROR) << "Enrollment can not proceed because Auto-enrollment is "
<< "not supported for non-enterprise enrollment modes.";
policy::AutoEnrollmentClient::CancelAutoEnrollment();
is_auto_enrollment_ = false;
actor_->ShowAutoEnrollmentError();
// Set the error state to something distinguishable in the logs.
state = policy::CloudPolicySubsystem::LOCAL_ERROR;
error_details = policy::CloudPolicySubsystem::AUTO_ENROLLMENT_ERROR;
}
break;
case policy::CloudPolicySubsystem::SUCCESS:
// Success!
registrar_.reset();
actor_->ShowConfirmationScreen();
return;
}
// We have an error.
if (!is_auto_enrollment_) {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentPolicyFailed,
policy::kMetricEnrollmentSize);
}
LOG(WARNING) << "Policy subsystem error during enrollment: " << state
<< " details: " << error_details;
}
// Stop the policy infrastructure.
registrar_.reset();
g_browser_process->browser_policy_connector()->ResetDevicePolicy();
}
void EnterpriseEnrollmentScreen::WriteInstallAttributesData() {
// Since this method is also called directly.
weak_ptr_factory_.InvalidateWeakPtrs();
switch (g_browser_process->browser_policy_connector()->LockDevice(user_)) {
case policy::EnterpriseInstallAttributes::LOCK_SUCCESS: {
// Proceed with policy fetch.
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
connector->FetchCloudPolicy();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_NOT_READY: {
// InstallAttributes not ready yet, retry later.
LOG(WARNING) << "Install Attributes not ready yet will retry in "
<< kLockRetryIntervalMs << "ms.";
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&EnterpriseEnrollmentScreen::WriteInstallAttributesData,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kLockRetryIntervalMs));
return;
}
case policy::EnterpriseInstallAttributes::LOCK_BACKEND_ERROR: {
actor_->ShowFatalEnrollmentError();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_WRONG_USER: {
LOG(ERROR) << "Enrollment can not proceed because the InstallAttrs "
<< "has been locked already!";
actor_->ShowFatalEnrollmentError();
return;
}
}
NOTREACHED();
}
void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
LOG(ERROR) << "Cloud policy subsystem not initialized.";
} else if (connector->IsEnterpriseManaged()) {
LOG(ERROR) << "Device is already enterprise managed!";
} else if (connector->device_cloud_policy_subsystem()->state() ==
policy::CloudPolicySubsystem::SUCCESS) {
LOG(ERROR) << "A previous enrollment already succeeded!";
} else {
// Make sure the device policy subsystem is in a clean slate.
connector->ResetDevicePolicy();
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
// Push the credentials to the policy infrastructure. It'll start enrollment
// and notify us of progress through CloudPolicySubsystem::Observer.
connector->RegisterForDevicePolicy(user_, token, is_auto_enrollment_);
return;
}
NOTREACHED();
if (is_showing_)
actor_->ShowFatalEnrollmentError();
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/filter_host.h"
#include "media/filters/null_audio_renderer.h"
namespace media {
// The number of reads to perform during initialization for preroll purposes.
static const size_t kInitialReads = 16;
// The number of buffers we consume before sleeping. By doing so we can sleep
// for longer, reducing CPU load and avoiding situations where audio samples
// are so short that the OS sleeps our thread for too long.
static const size_t kBuffersPerSleep = 4;
NullAudioRenderer::NullAudioRenderer()
: decoder_(NULL),
playback_rate_(0.0f),
thread_(NULL),
initialized_(false),
shutdown_(false) {
}
NullAudioRenderer::~NullAudioRenderer() {
Stop();
}
// static
bool NullAudioRenderer::IsMediaFormatSupported(
const MediaFormat* media_format) {
DCHECK(media_format);
std::string mime_type;
return media_format->GetAsString(MediaFormat::kMimeType, &mime_type) &&
mime_type.compare(mime_type::kUncompressedAudio) == 0;
}
void NullAudioRenderer::Stop() {
shutdown_ = true;
if (thread_)
PlatformThread::Join(thread_);
}
void NullAudioRenderer::SetPlaybackRate(float playback_rate) {
playback_rate_ = playback_rate;
}
bool NullAudioRenderer::Initialize(AudioDecoder* decoder) {
DCHECK(decoder);
decoder_ = decoder;
// It's safe to start the thread now because it simply sleeps when playback
// rate is 0.0f.
if (!PlatformThread::Create(0, this, &thread_))
return false;
// Schedule our initial reads.
for (size_t i = 0; i < kInitialReads; ++i) {
ScheduleRead();
}
// Defer initialization until all scheduled reads have completed.
return true;
}
void NullAudioRenderer::SetVolume(float volume) {
// Do nothing.
}
void NullAudioRenderer::OnAssignment(Buffer* buffer_in) {
bool initialized = false;
{
AutoLock auto_lock(input_lock_);
buffer_in->AddRef();
input_queue_.push_back(buffer_in);
DCHECK(input_queue_.size() <= kInitialReads);
// See if we're finally initialized.
// TODO(scherkus): handle end of stream.
initialized = !initialized_ && input_queue_.size() == kInitialReads;
}
if (initialized) {
initialized_ = true;
host_->InitializationComplete();
}
}
void NullAudioRenderer::ThreadMain() {
// Loop until we're signaled to stop.
while (!shutdown_) {
base::TimeDelta timestamp;
base::TimeDelta duration;
int sleep_ms = 0;
int released_buffers = 0;
// Only consume buffers when actually playing.
if (playback_rate_ > 0.0f) {
AutoLock auto_lock(input_lock_);
for (size_t i = 0; i < kBuffersPerSleep && !input_queue_.empty(); ++i) {
scoped_refptr<Buffer> buffer = input_queue_.front();
input_queue_.pop_front();
buffer->Release();
timestamp = buffer->GetTimestamp();
duration += buffer->GetDuration();
++released_buffers;
}
// Apply the playback rate to our sleep duration.
sleep_ms =
static_cast<int>(floor(duration.InMillisecondsF() / playback_rate_));
}
// Schedule reads for every released buffer to maintain "playback".
for (int i = 0; i < released_buffers; ++i) {
ScheduleRead();
}
// Sleep and update the clock when we wake up.
PlatformThread::Sleep(sleep_ms);
if (timestamp.InMicroseconds() > 0) {
host_->SetTime(timestamp);
}
}
}
void NullAudioRenderer::ScheduleRead() {
host_->PostTask(NewRunnableMethod(decoder_, &AudioDecoder::Read,
new AssignableBuffer<NullAudioRenderer, Buffer>(this)));
}
} // namespace media
<commit_msg>Fixed NullAudioRenderer gcc break due to not including <cmath>.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cmath>
#include "media/base/filter_host.h"
#include "media/filters/null_audio_renderer.h"
namespace media {
// The number of reads to perform during initialization for preroll purposes.
static const size_t kInitialReads = 16;
// The number of buffers we consume before sleeping. By doing so we can sleep
// for longer, reducing CPU load and avoiding situations where audio samples
// are so short that the OS sleeps our thread for too long.
static const size_t kBuffersPerSleep = 4;
NullAudioRenderer::NullAudioRenderer()
: decoder_(NULL),
playback_rate_(0.0f),
thread_(NULL),
initialized_(false),
shutdown_(false) {
}
NullAudioRenderer::~NullAudioRenderer() {
Stop();
}
// static
bool NullAudioRenderer::IsMediaFormatSupported(
const MediaFormat* media_format) {
DCHECK(media_format);
std::string mime_type;
return media_format->GetAsString(MediaFormat::kMimeType, &mime_type) &&
mime_type.compare(mime_type::kUncompressedAudio) == 0;
}
void NullAudioRenderer::Stop() {
shutdown_ = true;
if (thread_)
PlatformThread::Join(thread_);
}
void NullAudioRenderer::SetPlaybackRate(float playback_rate) {
playback_rate_ = playback_rate;
}
bool NullAudioRenderer::Initialize(AudioDecoder* decoder) {
DCHECK(decoder);
decoder_ = decoder;
// It's safe to start the thread now because it simply sleeps when playback
// rate is 0.0f.
if (!PlatformThread::Create(0, this, &thread_))
return false;
// Schedule our initial reads.
for (size_t i = 0; i < kInitialReads; ++i) {
ScheduleRead();
}
// Defer initialization until all scheduled reads have completed.
return true;
}
void NullAudioRenderer::SetVolume(float volume) {
// Do nothing.
}
void NullAudioRenderer::OnAssignment(Buffer* buffer_in) {
bool initialized = false;
{
AutoLock auto_lock(input_lock_);
buffer_in->AddRef();
input_queue_.push_back(buffer_in);
DCHECK(input_queue_.size() <= kInitialReads);
// See if we're finally initialized.
// TODO(scherkus): handle end of stream.
initialized = !initialized_ && input_queue_.size() == kInitialReads;
}
if (initialized) {
initialized_ = true;
host_->InitializationComplete();
}
}
void NullAudioRenderer::ThreadMain() {
// Loop until we're signaled to stop.
while (!shutdown_) {
base::TimeDelta timestamp;
base::TimeDelta duration;
int sleep_ms = 0;
int released_buffers = 0;
// Only consume buffers when actually playing.
if (playback_rate_ > 0.0f) {
AutoLock auto_lock(input_lock_);
for (size_t i = 0; i < kBuffersPerSleep && !input_queue_.empty(); ++i) {
scoped_refptr<Buffer> buffer = input_queue_.front();
input_queue_.pop_front();
buffer->Release();
timestamp = buffer->GetTimestamp();
duration += buffer->GetDuration();
++released_buffers;
}
// Apply the playback rate to our sleep duration.
sleep_ms =
static_cast<int>(floor(duration.InMillisecondsF() / playback_rate_));
}
// Schedule reads for every released buffer to maintain "playback".
for (int i = 0; i < released_buffers; ++i) {
ScheduleRead();
}
// Sleep and update the clock when we wake up.
PlatformThread::Sleep(sleep_ms);
if (timestamp.InMicroseconds() > 0) {
host_->SetTime(timestamp);
}
}
}
void NullAudioRenderer::ScheduleRead() {
host_->PostTask(NewRunnableMethod(decoder_, &AudioDecoder::Read,
new AssignableBuffer<NullAudioRenderer, Buffer>(this)));
}
} // namespace media
<|endoftext|>
|
<commit_before>/************************************************************************
filename: CEGuiSample.cpp
created: 24/9/2004
author: Paul D Turner
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGuiSample.h"
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "CEGUIConfig.h"
// includes for renderer selector classes
#if defined( __WIN32__ ) || defined( _WIN32 )
# include "Win32CEGuiRendererSelector.h"
#elif defined(linux)
# ifdef CEGUI_SAMPLES_USE_GTK2
# include "GTK2CEGuiRendererSelector.h"
# else
# include "CLICEGuiRendererSelector.h"
# endif
#endif
// includes for application types
#ifdef CEGUI_SAMPLES_USE_OGRE
# include "CEGuiOgreBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
# include "CEGuiOpenGLBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
# include "CEGuiIrrlichtBaseApplication.h"
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
# include "CEGuiD3D81BaseApplication.h"
# include "CEGuiD3D9BaseApplication.h"
#endif
// now we include the base CEGuiBaseApplication just in case someone has managed to
// get this far without any of the renderers. This ensures the framework will build,
// although there will be no renderers available for selection in the samples.
#include "CEGuiBaseApplication.h"
/*************************************************************************
Constructor
*************************************************************************/
CEGuiSample::CEGuiSample() :
d_rendererSelector(0),
d_sampleApp(0)
{}
/*************************************************************************
Destructor
*************************************************************************/
CEGuiSample::~CEGuiSample()
{
if (d_sampleApp)
{
d_sampleApp->cleanup();
delete d_sampleApp;
}
if (d_rendererSelector)
{
delete d_rendererSelector;
}
}
/*************************************************************************
Application entry point
*************************************************************************/
int CEGuiSample::run()
{
if (initialise())
{
cleanup();
}
return 0;
}
/*************************************************************************
Initialise the sample application
*************************************************************************/
bool CEGuiSample::initialise()
{
// Setup renderer selection dialog for Win32
#if defined( __WIN32__ ) || defined( _WIN32 )
d_rendererSelector = new Win32CEGuiRendererSelector;
// enable renderer types supported for Win32
d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType);
d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType);
#elif defined(linux)
// decide which method to use for renderer selection
# ifdef CEGUI_SAMPLES_USE_GTK2
d_rendererSelector = new GTK2CEGuiRendererSelector();
# else
d_rendererSelector = new CLICEGuiRendererSelector();
# endif
#endif
// enable available renderer types
#ifdef CEGUI_SAMPLES_USE_OGRE
d_rendererSelector->setRendererAvailability(OgreGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType);
#endif
// get selection from user
if (d_rendererSelector->inkokeDialog())
{
// create appropriate application type based upon users selection
switch(d_rendererSelector->getSelectedRendererType())
{
#ifdef CEGUI_SAMPLES_USE_OGRE
case OgreGuiRendererType:
d_sampleApp = new CEGuiOgreBaseApplication();
break;
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
case Direct3D81GuiRendererType:
d_sampleApp = new CEGuiD3D81BaseApplication();
break;
case Direct3D9GuiRendererType:
d_sampleApp = new CEGuiD3D9BaseApplication();
break;
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
case OpenGLGuiRendererType:
d_sampleApp = new CEGuiOpenGLBaseApplication();
break;
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
case IrrlichtGuiRendererType:
d_sampleApp = new CEGuiIrrlichtBaseApplication();
break;
#endif
default:
// TODO: Throw exception or something!
break;
}
// execute the base application (which sets up the demo via 'this' and runs it.
if (d_sampleApp->execute(this))
{
// signal that app initialised and ran
return true;
}
// sample app did not initialise, delete the object.
delete d_sampleApp;
d_sampleApp = 0;
}
// delete renderer selector object
delete d_rendererSelector;
d_rendererSelector = 0;
// signal app did not initialise and run.
return false;
}
/*************************************************************************
Cleanup the sample application.
*************************************************************************/
void CEGuiSample::cleanup()
{
if (d_sampleApp)
{
d_sampleApp->cleanup();
delete d_sampleApp;
d_sampleApp = 0;
}
if (d_rendererSelector)
{
delete d_rendererSelector;
d_rendererSelector = 0;
}
}
<commit_msg>Unified tests for linux platform to test for the same preprocessor define (that being __linux__).<commit_after>/************************************************************************
filename: CEGuiSample.cpp
created: 24/9/2004
author: Paul D Turner
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGuiSample.h"
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "CEGUIConfig.h"
// includes for renderer selector classes
#if defined( __WIN32__ ) || defined( _WIN32 )
# include "Win32CEGuiRendererSelector.h"
#elif defined(__linux__)
# ifdef CEGUI_SAMPLES_USE_GTK2
# include "GTK2CEGuiRendererSelector.h"
# else
# include "CLICEGuiRendererSelector.h"
# endif
#endif
// includes for application types
#ifdef CEGUI_SAMPLES_USE_OGRE
# include "CEGuiOgreBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
# include "CEGuiOpenGLBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
# include "CEGuiIrrlichtBaseApplication.h"
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
# include "CEGuiD3D81BaseApplication.h"
# include "CEGuiD3D9BaseApplication.h"
#endif
// now we include the base CEGuiBaseApplication just in case someone has managed to
// get this far without any of the renderers. This ensures the framework will build,
// although there will be no renderers available for selection in the samples.
#include "CEGuiBaseApplication.h"
/*************************************************************************
Constructor
*************************************************************************/
CEGuiSample::CEGuiSample() :
d_rendererSelector(0),
d_sampleApp(0)
{}
/*************************************************************************
Destructor
*************************************************************************/
CEGuiSample::~CEGuiSample()
{
if (d_sampleApp)
{
d_sampleApp->cleanup();
delete d_sampleApp;
}
if (d_rendererSelector)
{
delete d_rendererSelector;
}
}
/*************************************************************************
Application entry point
*************************************************************************/
int CEGuiSample::run()
{
if (initialise())
{
cleanup();
}
return 0;
}
/*************************************************************************
Initialise the sample application
*************************************************************************/
bool CEGuiSample::initialise()
{
// Setup renderer selection dialog for Win32
#if defined( __WIN32__ ) || defined( _WIN32 )
d_rendererSelector = new Win32CEGuiRendererSelector;
// enable renderer types supported for Win32
d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType);
d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType);
#elif defined(__linux__)
// decide which method to use for renderer selection
# ifdef CEGUI_SAMPLES_USE_GTK2
d_rendererSelector = new GTK2CEGuiRendererSelector();
# else
d_rendererSelector = new CLICEGuiRendererSelector();
# endif
#endif
// enable available renderer types
#ifdef CEGUI_SAMPLES_USE_OGRE
d_rendererSelector->setRendererAvailability(OgreGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType);
#endif
// get selection from user
if (d_rendererSelector->inkokeDialog())
{
// create appropriate application type based upon users selection
switch(d_rendererSelector->getSelectedRendererType())
{
#ifdef CEGUI_SAMPLES_USE_OGRE
case OgreGuiRendererType:
d_sampleApp = new CEGuiOgreBaseApplication();
break;
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
case Direct3D81GuiRendererType:
d_sampleApp = new CEGuiD3D81BaseApplication();
break;
case Direct3D9GuiRendererType:
d_sampleApp = new CEGuiD3D9BaseApplication();
break;
#endif
#ifdef CEGUI_SAMPLES_USE_OPENGL
case OpenGLGuiRendererType:
d_sampleApp = new CEGuiOpenGLBaseApplication();
break;
#endif
#ifdef CEGUI_SAMPLES_USE_IRRLICHT
case IrrlichtGuiRendererType:
d_sampleApp = new CEGuiIrrlichtBaseApplication();
break;
#endif
default:
// TODO: Throw exception or something!
break;
}
// execute the base application (which sets up the demo via 'this' and runs it.
if (d_sampleApp->execute(this))
{
// signal that app initialised and ran
return true;
}
// sample app did not initialise, delete the object.
delete d_sampleApp;
d_sampleApp = 0;
}
// delete renderer selector object
delete d_rendererSelector;
d_rendererSelector = 0;
// signal app did not initialise and run.
return false;
}
/*************************************************************************
Cleanup the sample application.
*************************************************************************/
void CEGuiSample::cleanup()
{
if (d_sampleApp)
{
d_sampleApp->cleanup();
delete d_sampleApp;
d_sampleApp = 0;
}
if (d_rendererSelector)
{
delete d_rendererSelector;
d_rendererSelector = 0;
}
}
<|endoftext|>
|
<commit_before>#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>
#include <string>
#include <memory>
#include <iostream>
int main(int, char**) {
std::cout << "=== optional and iteration example ===" << std::endl;
struct thing {
int a = 20;
thing() = default;
thing(int a) : a(a) {}
};
struct super_thing : thing {
int b = 40;
};
struct unrelated {
};
sol::state lua;
// Comment out the new_usertype call
// to prevent derived class "super_thing"
// from being picked up and cast to its base
// class
lua.new_usertype<super_thing>("super_thing",
sol::base_classes, sol::bases<thing>()
);
// Make a few things
lua["t1"] = thing{};
lua["t2"] = super_thing{};
lua["t3"] = unrelated{};
// And a table
lua["container"] = lua.create_table_with(
0, thing{50},
1, unrelated{},
4, super_thing{}
);
std::vector<std::reference_wrapper<thing>> things;
// Our recursive function
// We use some lambda techniques and pass the function itself itself so we can recurse,
// but a regular function would work too!
auto fx = [&lua, &things](auto& f, auto& tbl) -> void {
// You can iterate through a table: it has
// begin() and end()
// like standard containers
for (auto key_value_pair : tbl) {
// Note that iterators are extremely frail
// and should not be used outside of
// well-constructed for loops
// that use pre-increment ++,
// or C++ ranged-for loops
const sol::object& key = key_value_pair.first;
const sol::object& value = key_value_pair.second;
sol::type t = value.get_type();
switch (t) {
case sol::type::table:
f(f, value.as<sol::table>());
break;
case sol::type::userdata: {
// This allows us to check if a userdata is
// a specific class type
sol::optional<thing&> maybe_thing = value.as<sol::optional<thing&>>();
if (maybe_thing) {
thing& the_thing = maybe_thing.value();
if (key.is<std::string>()) {
std::cout << "key " << key.as<std::string>() << " is a thing -- ";
}
else if (key.is<int>()) {
std::cout << "key " << key.as<int>() << " is a thing -- ";
}
std::cout << "thing.a ==" << the_thing.a << std::endl;
things.push_back(the_thing);
}
}
break;
default:
break;
}
}
};
fx(fx, lua);
std::cout << std::endl;
return 0;
}
<commit_msg>This references thing is really going to hurt me from VC++ one day in production<commit_after>#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>
#include <string>
#include <memory>
#include <iostream>
int main(int, char**) {
std::cout << "=== optional and iteration example ===" << std::endl;
struct thing {
int a = 20;
thing() = default;
thing(int a) : a(a) {}
};
struct super_thing : thing {
int b = 40;
};
struct unrelated {
};
sol::state lua;
// Comment out the new_usertype call
// to prevent derived class "super_thing"
// from being picked up and cast to its base
// class
lua.new_usertype<super_thing>("super_thing",
sol::base_classes, sol::bases<thing>()
);
// Make a few things
lua["t1"] = thing{};
lua["t2"] = super_thing{};
lua["t3"] = unrelated{};
// And a table
lua["container"] = lua.create_table_with(
0, thing{50},
1, unrelated{},
4, super_thing{}
);
std::vector<std::reference_wrapper<thing>> things;
// Our recursive function
// We use some lambda techniques and pass the function itself itself so we can recurse,
// but a regular function would work too!
auto fx = [&lua, &things](auto& f, auto tbl) -> void {
// You can iterate through a table: it has
// begin() and end()
// like standard containers
for (auto key_value_pair : tbl) {
// Note that iterators are extremely frail
// and should not be used outside of
// well-constructed for loops
// that use pre-increment ++,
// or C++ ranged-for loops
const sol::object& key = key_value_pair.first;
const sol::object& value = key_value_pair.second;
sol::type t = value.get_type();
switch (t) {
case sol::type::table:
f(f, value.as<sol::table>());
break;
case sol::type::userdata: {
// This allows us to check if a userdata is
// a specific class type
sol::optional<thing&> maybe_thing = value.as<sol::optional<thing&>>();
if (maybe_thing) {
thing& the_thing = maybe_thing.value();
if (key.is<std::string>()) {
std::cout << "key " << key.as<std::string>() << " is a thing -- ";
}
else if (key.is<int>()) {
std::cout << "key " << key.as<int>() << " is a thing -- ";
}
std::cout << "thing.a ==" << the_thing.a << std::endl;
things.push_back(the_thing);
}
}
break;
default:
break;
}
}
};
fx(fx, lua);
std::cout << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/* OpenSceneGraph example, osganimate.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Notify>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
int main( int argc, char **argv )
{
osg::ArgumentParser arguments(&argc,argv);
// initialize the viewer.
osgViewer::Viewer viewer(arguments);
osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
if (!model)
{
OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl;
return 1;
}
viewer.setSceneData(model.get());
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
return viewer.run();
}
<commit_msg>Experiments with modifying the projection matrix to provide keystoning.<commit_after>/* OpenSceneGraph example, osganimate.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Notify>
#include <osg/io_utils>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
int main( int argc, char **argv )
{
osg::ArgumentParser arguments(&argc,argv);
// initialize the viewer.
osgViewer::Viewer viewer(arguments);
osg::Vec2d translate(0.0,0.0);
osg::Vec2d scale(1.0,1.0);
osg::Vec2d taper(1.0,1.0);
double angle = 0; // osg::inDegrees(45.0);
if (arguments.read("-a",angle)) { OSG_NOTICE<<"angle = "<<angle<<std::endl; angle = osg::inDegrees(angle); }
if (arguments.read("-t",translate.x(), translate.y())) { OSG_NOTICE<<"translate = "<<translate<<std::endl;}
if (arguments.read("-s",scale.x(), scale.y())) { OSG_NOTICE<<"scale = "<<scale<<std::endl;}
if (arguments.read("-k",taper.x(), taper.y())) { OSG_NOTICE<<"taper = "<<taper<<std::endl;}
osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
if (!model)
{
OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl;
return 1;
}
viewer.setSceneData(model.get());
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
viewer.realize();
viewer.getCamera()->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
osg::Matrixd& pm = viewer.getCamera()->getProjectionMatrix();
pm.postMultRotate(osg::Quat(angle, osg::Vec3d(0.0,0.0,1.0)));
pm.postMultScale(osg::Vec3d(scale.x(),scale.y(),1.0));
pm.postMultTranslate(osg::Vec3d(translate.x(),translate.y(),0.0));
if (taper.x()!=1.0)
{
double x0 = (1.0+taper.x())/(1-taper.x());
OSG_NOTICE<<"x0 = "<<x0<<std::endl;
pm.postMult(osg::Matrixd(1.0-x0, 0.0, 0.0, 1.0,
0.0, 1.0-x0, 0.0, 0.0,
0.0, 0.0, (1.0-x0)*0.5, 0.0,
0.0, 0.0, 0.0, -x0));
}
return viewer.run();
}
<|endoftext|>
|
<commit_before>/*
* @file opencog/embodiment/Control/OperationalAvatarController/PatternMiningAgent.cc
*
* @author Shujing Ke <rainkekekeke@gmail.com>
* @date 2014-04-11
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/spacetime/TimeServer.h>
#include <opencog/util/Config.h>
#include <opencog/guile/load-file.h>
#include "OAC.h"
#include "PatternMiningAgent.h"
using namespace opencog::oac;
PatternMiningAgent::~PatternMiningAgent()
{
}
PatternMiningAgent::PatternMiningAgent(CogServer& cs) : Agent(cs)
{
this->cycleCount = 0;
// Force the Agent initialize itself during its first cycle.
this->forceInitNextCycle();
}
void PatternMiningAgent::init()
{
logger().debug( "PatternMiningAgent::%s - Initialize the Agent [cycle = %d]",
__FUNCTION__, this->cycleCount);
// Get OAC
OAC* oac = dynamic_cast<OAC*>(&_cogserver);
OC_ASSERT(oac, "Did not get an OAC server");
// Get AtomSpace
corpusAtomSpace = new AtomSpace();
// load test corpus
if ( load_scm_file( *(this->corpusAtomSpace), "pm_test_corpus.scm" ) == 0 )
logger().info( "PatternMiningAgent::%s - Loaded pattern miner test corpus file: '%s'",
__FUNCTION__,
"pm_test_corpus.scm"
);
else
logger().error( "PatternMiningAgent::%s - Failed to load pattern miner test corpus file: '%s'",
__FUNCTION__,
"pm_test_corpus.scm"
);
cout << "PatternMiningAgent: init: loaded test corpus into corpusAtomSpace \n ";
// create a pattern miner
this->patternMiner = new PatternMiner(corpusAtomSpace,config().get_int("PATTERN_MAX_GRAM"));
// Avoid initialize during next cycle
this->bInitialized = true;
cout << "PatternMiningAgent: init finished!\n ";
}
void PatternMiningAgent::run()
{
this->cycleCount = _cogserver.getCycleCount();
logger().debug( "PatternMiningAgent::%s - Executing run %d times",
__FUNCTION__, this->cycleCount);
// Get OAC
OAC* oac = dynamic_cast<OAC*>(&_cogserver);
OC_ASSERT(oac, "Did not get an OAC server!");
// Initialize the Agent (demandList etc)
if ( !this->bInitialized )
this->init();
// test, only run once
static bool hasRun = false;
if (hasRun)
return;
this->patternMiner->runPatternMiner();
hasRun = true;
}
<commit_msg>Added the necessary pre-load scm files into corpus Atomspace.<commit_after>/*
* @file opencog/embodiment/Control/OperationalAvatarController/PatternMiningAgent.cc
*
* @author Shujing Ke <rainkekekeke@gmail.com>
* @date 2014-04-11
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/spacetime/TimeServer.h>
#include <opencog/util/Config.h>
#include <opencog/guile/load-file.h>
#include <opencog/guile/SchemeEval.h>
#include <opencog/embodiment/AtomSpaceExtensions/atom_types.h>
#include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h>
#include "OAC.h"
#include "PatternMiningAgent.h"
using namespace opencog::oac;
PatternMiningAgent::~PatternMiningAgent()
{
}
PatternMiningAgent::PatternMiningAgent(CogServer& cs) : Agent(cs)
{
this->cycleCount = 0;
// Force the Agent initialize itself during its first cycle.
this->forceInitNextCycle();
}
void PatternMiningAgent::init()
{
sleep(15);
logger().debug( "PatternMiningAgent::%s - Initialize the Agent [cycle = %d]",
__FUNCTION__, this->cycleCount);
// Get OAC
OAC* oac = dynamic_cast<OAC*>(&_cogserver);
OC_ASSERT(oac, "Did not get an OAC server");
// create corpus AtomSpace
corpusAtomSpace = new AtomSpace();
// pre-load scm files:
// SCM_PRELOAD = scm/core_types.scm,
// scm/spacetime_types.scm,
// scm/nlp_types.scm,
// scm/attention_types.scm,
// scm/embodiment_types.scm,
// scm/persistence.scm,
// scm/utilities.scm,
// scm/file-utils.scm,
// scm/debug.scm,
load_scm_file( *(this->corpusAtomSpace), "./scm/core_types.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/spacetime_types.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/nlp_types.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/attention_types.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/embodiment_types.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/persistence.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/utilities.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/file-utils.scm" );
load_scm_file( *(this->corpusAtomSpace), "./scm/debug.scm" );
// load test corpus
if ( load_scm_file( *(this->corpusAtomSpace), "./pm_test_corpus.scm" ) == 0 )
logger().info( "PatternMiningAgent::%s - Loaded pattern miner test corpus file: '%s'",
__FUNCTION__,
"pm_test_corpus.scm"
);
else
logger().error( "PatternMiningAgent::%s - Failed to load pattern miner test corpus file: '%s'",
__FUNCTION__,
"pm_test_corpus.scm"
);
cout << "PatternMiningAgent: init: loaded test corpus into corpusAtomSpace \n ";
// create a pattern miner
this->patternMiner = new PatternMiner(corpusAtomSpace,config().get_int("PATTERN_MAX_GRAM"));
// Avoid initialize during next cycle
this->bInitialized = true;
cout << "PatternMiningAgent: init finished!\n ";
}
void PatternMiningAgent::run()
{
this->cycleCount = _cogserver.getCycleCount();
logger().debug( "PatternMiningAgent::%s - Executing run %d times",
__FUNCTION__, this->cycleCount);
// Get OAC
OAC* oac = dynamic_cast<OAC*>(&_cogserver);
OC_ASSERT(oac, "Did not get an OAC server!");
// Initialize the Agent (demandList etc)
if ( !this->bInitialized )
this->init();
// test, only run once
static bool hasRun = false;
if (hasRun)
return;
this->patternMiner->runPatternMiner();
hasRun = true;
}
<|endoftext|>
|
<commit_before><commit_msg>CUDA/CPU test for NegativeLogLikelihoodLoss(12) function based loss operator. (#3793)<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/logging/CustomLogFormatter.h>
#include <folly/Format.h>
#include <folly/logging/LogLevel.h>
#include <folly/logging/LogMessage.h>
#include <folly/portability/Time.h>
#include <algorithm>
namespace {
using folly::LogLevel;
using folly::StringPiece;
StringPiece getGlogLevelName(LogLevel level) {
if (level < LogLevel::INFO) {
return "VERBOSE";
} else if (level < LogLevel::WARN) {
return "INFO";
} else if (level < LogLevel::ERR) {
return "WARNING";
} else if (level < LogLevel::CRITICAL) {
return "ERROR";
} else if (level < LogLevel::DFATAL) {
return "CRITICAL";
}
return "FATAL";
}
StringPiece getResetSequence(LogLevel level) {
if (level >= LogLevel::INFO && level < LogLevel::WARN) {
return "\e[0m";
} else {
return "";
}
}
StringPiece getColorSequence(LogLevel level) {
if (level < LogLevel::INFO) {
return "\e[1;30m"; // BOLD/BRIGHT BLACK ~ GREY
} else if (level < LogLevel::WARN) {
return ""; // NO COLOR
} else if (level < LogLevel::ERR) {
return "\e[33m"; // YELLOW
} else if (level < LogLevel::CRITICAL) {
return "\e[31m"; // RED
}
return "\e[1;41m"; // BOLD ON RED BACKGROUND
}
struct FormatKeys {
const StringPiece key;
const std::size_t argIndex;
const std::size_t width;
constexpr FormatKeys(
StringPiece key_,
std::size_t argIndex_,
std::size_t width_ = 0)
: key(key_), argIndex(argIndex_), width(width_) {}
};
/**
* The first part of pairs in this array are the key names and the second part
* of the pairs are the argument index for folly::format().
*
* NOTE: This array must be sorted by key name, since we use std::lower_bound
* to search in it.
*
* TODO: Support including thread names and thread context info.
*/
constexpr std::array<FormatKeys, 11> formatKeys{{
FormatKeys(/* key */ "D", /* argIndex */ 2, /* width */ 2),
FormatKeys(/* key */ "FILE", /* argIndex */ 8),
FormatKeys(/* key */ "FUN", /* argIndex */ 9),
FormatKeys(/* key */ "H", /* argIndex */ 3, /* width */ 2),
FormatKeys(/* key */ "L", /* argIndex */ 0, /* width */ 1),
FormatKeys(/* key */ "LINE", /* argIndex */ 10, /* width */ 4),
FormatKeys(/* key */ "M", /* argIndex */ 4, /* width */ 2),
FormatKeys(/* key */ "S", /* argIndex */ 5, /* width */ 2),
FormatKeys(/* key */ "THREAD", /* argIndex */ 7, /* width */ 5),
FormatKeys(/* key */ "USECS", /* argIndex */ 6, /* width */ 6),
FormatKeys(/* key */ "m", /* argIndex */ 1, /* width */ 2),
}};
constexpr int messageIndex = formatKeys.size();
} // namespace
namespace folly {
CustomLogFormatter::CustomLogFormatter(StringPiece format, bool colored)
: colored_(colored) {
parseFormatString(format);
}
void CustomLogFormatter::parseFormatString(StringPiece input) {
std::size_t estimatedWidth = 0;
functionNameCount_ = 0;
fileNameCount_ = 0;
// Replace all format keys to numbers to improve performance and to use
// varying value types (which is not possible using folly::vformat()).
std::string output;
output.reserve(input.size());
const char* varNameStart = nullptr;
enum StateEnum {
LITERAL,
FMT_NAME,
FMT_MODIFIERS,
} state = LITERAL;
for (const char* p = input.begin(); p < input.end(); ++p) {
switch (state) {
case LITERAL:
output.append(p, 1);
// In case of `{{` or `}}`, copy it as it is and only increment the
// estimatedWidth once as it will result to a single character in
// output.
if ((p + 1) != input.end() /* ensure not last character */ &&
(0 == memcmp(p, "}}", 2) || 0 == memcmp(p, "{{", 2))) {
output.append(p + 1, 1);
estimatedWidth++;
p++;
}
// If we see a single open curly brace, it denotes a start of a format
// name and so we change the state to FMT_NAME and do not increment
// estimatedWidth as it won't be in the output.
else if (*p == '{') {
varNameStart = p + 1;
state = FMT_NAME;
}
// In case it is just a regular literal, just increment estimatedWidth
// by one and move on to the next character.
else {
estimatedWidth++;
}
break;
// In case we have started processing a format name/key
case FMT_NAME:
// Unless it is the end of the format name/key, do nothing and scan over
// the name/key. When it is the end of the format name/key, look up
// the argIndex for it and replace the name/key with that index.
if (*p == ':' || *p == '}') {
StringPiece varName(varNameStart, p);
auto item = std::lower_bound(
formatKeys.begin(),
formatKeys.end(),
varName,
[](const auto& a, const auto& b) { return a.key < b; });
if (UNLIKELY(item == formatKeys.end() || item->key != varName)) {
throw std::runtime_error(folly::to<std::string>(
"unknown format argument \"", varName, "\""));
}
output.append(folly::to<std::string>(item->argIndex));
output.append(p, 1);
// Based on the format key, increment estimatedWidth with the
// estimate of how many characters long the value of the format key
// will be. If it is a FILE or a FUN, the width will be variable
// depending on the values of those fields.
estimatedWidth += item->width;
if (item->key == "FILE") {
fileNameCount_++;
} else if (item->key == "FUN") {
functionNameCount_++;
}
// Figure out if there are modifiers that follow the key or if we
// continue processing literals.
if (*p == ':') {
state = FMT_MODIFIERS;
} else {
state = LITERAL;
}
}
break;
// In case we have started processing a format modifier (after :)
case FMT_MODIFIERS:
// Modifiers are just copied as is and are not considered to determine
// the estimatedWidth.
output.append(p, 1);
if (*p == '}') {
state = LITERAL;
}
break;
}
}
if (state != LITERAL) {
throw std::runtime_error("unterminated format string");
}
// Append a single space after the header format if header is not empty.
if (!output.empty()) {
output.append(" ");
estimatedWidth++;
}
logFormat_ = output;
staticEstimatedWidth_ = estimatedWidth;
// populate singleLineLogFormat_ with the padded line format.
if (colored_) {
singleLineLogFormat_ = folly::to<std::string>(
"{",
messageIndex + 1,
"}",
logFormat_,
"{",
messageIndex,
"}{",
messageIndex + 2,
"}\n");
} else {
singleLineLogFormat_ =
folly::to<std::string>(logFormat_, "{", messageIndex, "}\n");
}
}
std::string CustomLogFormatter::formatMessage(
const LogMessage& message,
const LogCategory* /* handlerCategory */) {
// Get the local time info
struct tm ltime;
auto timeSinceEpoch = message.getTimestamp().time_since_epoch();
auto epochSeconds =
std::chrono::duration_cast<std::chrono::seconds>(timeSinceEpoch);
std::chrono::microseconds usecs =
std::chrono::duration_cast<std::chrono::microseconds>(timeSinceEpoch) -
epochSeconds;
time_t unixTimestamp = epochSeconds.count();
if (!localtime_r(&unixTimestamp, <ime)) {
memset(<ime, 0, sizeof(ltime));
}
auto basename = message.getFileBaseName();
// Most common logs will be single line logs and so we can format the entire
// log string including the message at once.
if (!message.containsNewlines()) {
return folly::sformat(
singleLineLogFormat_,
getGlogLevelName(message.getLevel())[0],
ltime.tm_mon + 1,
ltime.tm_mday,
ltime.tm_hour,
ltime.tm_min,
ltime.tm_sec,
usecs.count(),
message.getThreadID(),
basename,
message.getFunctionName(),
message.getLineNumber(),
// NOTE: THE FOLLOWING ARGUMENTS ALWAYS NEED TO BE THE LAST 3:
message.getMessage(),
// If colored logs are enabled, the singleLineLogFormat_ will contain
// placeholders for the color and the reset sequences. If not, then
// the following params will just be ignored by the folly::sformat().
getColorSequence(message.getLevel()),
getResetSequence(message.getLevel()));
}
// If the message contains multiple lines, ensure that the log header is
// prepended before each message line.
else {
const auto headerFormatter = folly::format(
logFormat_,
getGlogLevelName(message.getLevel())[0],
ltime.tm_mon + 1,
ltime.tm_mday,
ltime.tm_hour,
ltime.tm_min,
ltime.tm_sec,
usecs.count(),
message.getThreadID(),
basename,
message.getFunctionName(),
message.getLineNumber());
// Estimate header length. If this still isn't long enough the string will
// grow as necessary, so the code will still be correct, but just slightly
// less efficient than if we had allocated a large enough buffer the first
// time around.
size_t headerLengthGuess = staticEstimatedWidth_ +
(fileNameCount_ * basename.size()) +
(functionNameCount_ * message.getFunctionName().size());
// Format the data into a buffer.
std::string buffer;
// If colored logging is supported, then process the color based on
// the level of the message.
if (colored_) {
buffer.append(getColorSequence(message.getLevel()).toString());
}
StringPiece msgData{message.getMessage()};
// Make a guess at how many lines will be in the message, just to make an
// initial buffer allocation. If the guess is too small then the string
// will reallocate and grow as necessary, it will just be slightly less
// efficient than if we had guessed enough space.
size_t numLinesGuess = 4;
buffer.reserve((headerLengthGuess * numLinesGuess) + msgData.size());
size_t idx = 0;
while (true) {
auto end = msgData.find('\n', idx);
if (end == StringPiece::npos) {
end = msgData.size();
}
auto line = msgData.subpiece(idx, end - idx);
headerFormatter.appendTo(buffer);
buffer.append(line.data(), line.size());
buffer.push_back('\n');
if (end == msgData.size()) {
break;
}
idx = end + 1;
}
// If colored logging is supported and the current message is a color other
// than the default, then RESET colors after printing message.
if (colored_) {
buffer.append(getResetSequence(message.getLevel()).toString());
}
return buffer;
}
}
} // namespace folly
<commit_msg>Escape the escape sequences in CustomLogFormatter<commit_after>/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/logging/CustomLogFormatter.h>
#include <folly/Format.h>
#include <folly/logging/LogLevel.h>
#include <folly/logging/LogMessage.h>
#include <folly/portability/Time.h>
#include <algorithm>
namespace {
using folly::LogLevel;
using folly::StringPiece;
StringPiece getGlogLevelName(LogLevel level) {
if (level < LogLevel::INFO) {
return "VERBOSE";
} else if (level < LogLevel::WARN) {
return "INFO";
} else if (level < LogLevel::ERR) {
return "WARNING";
} else if (level < LogLevel::CRITICAL) {
return "ERROR";
} else if (level < LogLevel::DFATAL) {
return "CRITICAL";
}
return "FATAL";
}
StringPiece getResetSequence(LogLevel level) {
if (level >= LogLevel::INFO && level < LogLevel::WARN) {
return "\033[0m";
} else {
return "";
}
}
StringPiece getColorSequence(LogLevel level) {
if (level < LogLevel::INFO) {
return "\033[1;30m"; // BOLD/BRIGHT BLACK ~ GREY
} else if (level < LogLevel::WARN) {
return ""; // NO COLOR
} else if (level < LogLevel::ERR) {
return "\033[33m"; // YELLOW
} else if (level < LogLevel::CRITICAL) {
return "\033[31m"; // RED
}
return "\033[1;41m"; // BOLD ON RED BACKGROUND
}
struct FormatKeys {
const StringPiece key;
const std::size_t argIndex;
const std::size_t width;
constexpr FormatKeys(
StringPiece key_,
std::size_t argIndex_,
std::size_t width_ = 0)
: key(key_), argIndex(argIndex_), width(width_) {}
};
/**
* The first part of pairs in this array are the key names and the second part
* of the pairs are the argument index for folly::format().
*
* NOTE: This array must be sorted by key name, since we use std::lower_bound
* to search in it.
*
* TODO: Support including thread names and thread context info.
*/
constexpr std::array<FormatKeys, 11> formatKeys{{
FormatKeys(/* key */ "D", /* argIndex */ 2, /* width */ 2),
FormatKeys(/* key */ "FILE", /* argIndex */ 8),
FormatKeys(/* key */ "FUN", /* argIndex */ 9),
FormatKeys(/* key */ "H", /* argIndex */ 3, /* width */ 2),
FormatKeys(/* key */ "L", /* argIndex */ 0, /* width */ 1),
FormatKeys(/* key */ "LINE", /* argIndex */ 10, /* width */ 4),
FormatKeys(/* key */ "M", /* argIndex */ 4, /* width */ 2),
FormatKeys(/* key */ "S", /* argIndex */ 5, /* width */ 2),
FormatKeys(/* key */ "THREAD", /* argIndex */ 7, /* width */ 5),
FormatKeys(/* key */ "USECS", /* argIndex */ 6, /* width */ 6),
FormatKeys(/* key */ "m", /* argIndex */ 1, /* width */ 2),
}};
constexpr int messageIndex = formatKeys.size();
} // namespace
namespace folly {
CustomLogFormatter::CustomLogFormatter(StringPiece format, bool colored)
: colored_(colored) {
parseFormatString(format);
}
void CustomLogFormatter::parseFormatString(StringPiece input) {
std::size_t estimatedWidth = 0;
functionNameCount_ = 0;
fileNameCount_ = 0;
// Replace all format keys to numbers to improve performance and to use
// varying value types (which is not possible using folly::vformat()).
std::string output;
output.reserve(input.size());
const char* varNameStart = nullptr;
enum StateEnum {
LITERAL,
FMT_NAME,
FMT_MODIFIERS,
} state = LITERAL;
for (const char* p = input.begin(); p < input.end(); ++p) {
switch (state) {
case LITERAL:
output.append(p, 1);
// In case of `{{` or `}}`, copy it as it is and only increment the
// estimatedWidth once as it will result to a single character in
// output.
if ((p + 1) != input.end() /* ensure not last character */ &&
(0 == memcmp(p, "}}", 2) || 0 == memcmp(p, "{{", 2))) {
output.append(p + 1, 1);
estimatedWidth++;
p++;
}
// If we see a single open curly brace, it denotes a start of a format
// name and so we change the state to FMT_NAME and do not increment
// estimatedWidth as it won't be in the output.
else if (*p == '{') {
varNameStart = p + 1;
state = FMT_NAME;
}
// In case it is just a regular literal, just increment estimatedWidth
// by one and move on to the next character.
else {
estimatedWidth++;
}
break;
// In case we have started processing a format name/key
case FMT_NAME:
// Unless it is the end of the format name/key, do nothing and scan over
// the name/key. When it is the end of the format name/key, look up
// the argIndex for it and replace the name/key with that index.
if (*p == ':' || *p == '}') {
StringPiece varName(varNameStart, p);
auto item = std::lower_bound(
formatKeys.begin(),
formatKeys.end(),
varName,
[](const auto& a, const auto& b) { return a.key < b; });
if (UNLIKELY(item == formatKeys.end() || item->key != varName)) {
throw std::runtime_error(folly::to<std::string>(
"unknown format argument \"", varName, "\""));
}
output.append(folly::to<std::string>(item->argIndex));
output.append(p, 1);
// Based on the format key, increment estimatedWidth with the
// estimate of how many characters long the value of the format key
// will be. If it is a FILE or a FUN, the width will be variable
// depending on the values of those fields.
estimatedWidth += item->width;
if (item->key == "FILE") {
fileNameCount_++;
} else if (item->key == "FUN") {
functionNameCount_++;
}
// Figure out if there are modifiers that follow the key or if we
// continue processing literals.
if (*p == ':') {
state = FMT_MODIFIERS;
} else {
state = LITERAL;
}
}
break;
// In case we have started processing a format modifier (after :)
case FMT_MODIFIERS:
// Modifiers are just copied as is and are not considered to determine
// the estimatedWidth.
output.append(p, 1);
if (*p == '}') {
state = LITERAL;
}
break;
}
}
if (state != LITERAL) {
throw std::runtime_error("unterminated format string");
}
// Append a single space after the header format if header is not empty.
if (!output.empty()) {
output.append(" ");
estimatedWidth++;
}
logFormat_ = output;
staticEstimatedWidth_ = estimatedWidth;
// populate singleLineLogFormat_ with the padded line format.
if (colored_) {
singleLineLogFormat_ = folly::to<std::string>(
"{",
messageIndex + 1,
"}",
logFormat_,
"{",
messageIndex,
"}{",
messageIndex + 2,
"}\n");
} else {
singleLineLogFormat_ =
folly::to<std::string>(logFormat_, "{", messageIndex, "}\n");
}
}
std::string CustomLogFormatter::formatMessage(
const LogMessage& message,
const LogCategory* /* handlerCategory */) {
// Get the local time info
struct tm ltime;
auto timeSinceEpoch = message.getTimestamp().time_since_epoch();
auto epochSeconds =
std::chrono::duration_cast<std::chrono::seconds>(timeSinceEpoch);
std::chrono::microseconds usecs =
std::chrono::duration_cast<std::chrono::microseconds>(timeSinceEpoch) -
epochSeconds;
time_t unixTimestamp = epochSeconds.count();
if (!localtime_r(&unixTimestamp, <ime)) {
memset(<ime, 0, sizeof(ltime));
}
auto basename = message.getFileBaseName();
// Most common logs will be single line logs and so we can format the entire
// log string including the message at once.
if (!message.containsNewlines()) {
return folly::sformat(
singleLineLogFormat_,
getGlogLevelName(message.getLevel())[0],
ltime.tm_mon + 1,
ltime.tm_mday,
ltime.tm_hour,
ltime.tm_min,
ltime.tm_sec,
usecs.count(),
message.getThreadID(),
basename,
message.getFunctionName(),
message.getLineNumber(),
// NOTE: THE FOLLOWING ARGUMENTS ALWAYS NEED TO BE THE LAST 3:
message.getMessage(),
// If colored logs are enabled, the singleLineLogFormat_ will contain
// placeholders for the color and the reset sequences. If not, then
// the following params will just be ignored by the folly::sformat().
getColorSequence(message.getLevel()),
getResetSequence(message.getLevel()));
}
// If the message contains multiple lines, ensure that the log header is
// prepended before each message line.
else {
const auto headerFormatter = folly::format(
logFormat_,
getGlogLevelName(message.getLevel())[0],
ltime.tm_mon + 1,
ltime.tm_mday,
ltime.tm_hour,
ltime.tm_min,
ltime.tm_sec,
usecs.count(),
message.getThreadID(),
basename,
message.getFunctionName(),
message.getLineNumber());
// Estimate header length. If this still isn't long enough the string will
// grow as necessary, so the code will still be correct, but just slightly
// less efficient than if we had allocated a large enough buffer the first
// time around.
size_t headerLengthGuess = staticEstimatedWidth_ +
(fileNameCount_ * basename.size()) +
(functionNameCount_ * message.getFunctionName().size());
// Format the data into a buffer.
std::string buffer;
// If colored logging is supported, then process the color based on
// the level of the message.
if (colored_) {
buffer.append(getColorSequence(message.getLevel()).toString());
}
StringPiece msgData{message.getMessage()};
// Make a guess at how many lines will be in the message, just to make an
// initial buffer allocation. If the guess is too small then the string
// will reallocate and grow as necessary, it will just be slightly less
// efficient than if we had guessed enough space.
size_t numLinesGuess = 4;
buffer.reserve((headerLengthGuess * numLinesGuess) + msgData.size());
size_t idx = 0;
while (true) {
auto end = msgData.find('\n', idx);
if (end == StringPiece::npos) {
end = msgData.size();
}
auto line = msgData.subpiece(idx, end - idx);
headerFormatter.appendTo(buffer);
buffer.append(line.data(), line.size());
buffer.push_back('\n');
if (end == msgData.size()) {
break;
}
idx = end + 1;
}
// If colored logging is supported and the current message is a color other
// than the default, then RESET colors after printing message.
if (colored_) {
buffer.append(getResetSequence(message.getLevel()).toString());
}
return buffer;
}
}
} // namespace folly
<|endoftext|>
|
<commit_before>/* Copyright (c) 2011 Cody Miller, Daniel Norris, Brett Hitchcock.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*****************************************************************************/
#include "Application.h"
#include <CEGUI.h>
#include "Application/NullLogger.h"
#include <RendererModules/Ogre/CEGUIOgreRenderer.h>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
Application::Application()
: resource_path_ (getResourcePath()),
config_path_ (getConfigPath())
{
// Initialize the root system
root_.reset(initializeRoot(resource_path_, config_path_, resource_path_));
// Initialize the window
window_ = initializeWindow();
// Set up references to all the resources
initializeResources();
// Set up the scene manager
scene_manager_ = initializeSceneManager();
// Create a new camera
Graphics::instance()->constructCamera();
// Constructs the viewports
initializeViewport();
// Initialize the input subsystem
input_system_.reset(initializeInput(root_.get(), window_));
// Set default mipmap level
TextureManager::getSingleton().setDefaultNumMipmaps(5);
// Create any resource listeners (for loading screens)
//createResourceListener();
// Load resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// Create the scene
Graphics::instance()->setup();
// Add event listeners
root_->addFrameListener(Engine::instance());
// Give the Engine what it needs to function
Engine::instance()->setWindow( window_ );
Engine::instance()->bindCamera( false ); //Active camera.
// Initialize the user interface
//initializeInterface();
// Connect to the remote server if we're able to
initializeNetwork();
// Add event handling functions
handler_mappings["LocalMovePlayer"] = &Engine::handleLocalMovePlayer;
handler_mappings["LocalRotatePlayer"] = &Engine::handleLocalRotatePlayer;
handler_mappings["LocalUDCamera"] = &Engine::handleLocalUDCamera;
handler_mappings["LocalLRCamera"] = &Engine::handleLocalLRCamera;
handler_mappings["LocalZoomCamera"] = &Engine::handleLocalZoomCamera;
handler_mappings["LocalFireCannon"] = &Engine::handleLocalFireCannon;
handler_mappings["NetworkCreateEntity"] = &Engine::handleNetworkCreateEntity;
handler_mappings["NetworkDestroyEntity"]= &Engine::handleNetworkDestroyEntity;
handler_mappings["NetworkMoveEntity"] = &Engine::handleNetworkMoveEntity;
handler_mappings["NetworkRotateEntity"] = &Engine::handleNetworkRotateEntity;
handler_mappings["NetworkSetAmbient"] = &Engine::handleNetworkSetAmbient;
}
Application::~Application()
{
// The boost::shared_ptrs free what needs to be freed here.
}
bool Application::handleQuit(const CEGUI::EventArgs& args)
{
exit(1);
// Graphics::instance()->rotateCamera(0.01, 0.0);
}
void Application::go()
{
root_->startRendering();
// clean up
//destroyScene();
}
Ogre::Root* Application::initializeRoot(const Ogre::String& plugin,
const Ogre::String& config,
const Ogre::String& log)
{
Ogre::Root *r = OGRE_NEW Root( plugin + "plugins.cfg", config + "ogre.cfg", log + "Ogre.log");
if (r == 0)
throw "Could not initialize Ogre::Root!";
return r;
}
void Application::initializeNetwork()
{
Ogre::ConfigFile *network_config = new Ogre::ConfigFile;
network_config->load(getConfigPath() + "network.cfg");
const Ogre::String address = network_config->getSetting("Address");
const Ogre::String port = network_config->getSetting("Port");
Network::instance()->connect(address.c_str(), port.c_str());
// This is necessary to have the networking branch off on its own thread.
thread_ = boost::thread(boost::bind(&asio::io_service::run, &Network::service()));
}
Ogre::RenderWindow* Application::initializeWindow()
{
Ogre::RenderWindow* win = NULL;
if (root_->showConfigDialog())
win = root_->initialise(true);
// The case that the user didn't want to configure/wanted to quit
if (win == 0)
closeApplication();
return win;
}
void Application::closeApplication()
{
Network::instance()->disconnect();
}
void Application::initializeResources()
{
Ogre::ConfigFile config;
Ogre::String section, type, arch;
config.load(resource_path_ + "resources.cfg");
Ogre::ConfigFile::SectionIterator itr = config.getSectionIterator();
while (itr.hasMoreElements()) {
section = itr.peekNextKey();
Ogre::ConfigFile::SettingsMultiMap* settings = itr.getNext();
Ogre::ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i) {
type = i->first;
arch = i->second;
#if OGRE_PLATFORM == OGRE_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
if (!Ogre::StringUtil::startsWith(arch, "/", false))
arch = String(macBundlePath() + "/" + arch);
#endif
ResourceGroupManager::getSingleton().addResourceLocation(arch, type, section);
}
}
}
Input* Application::initializeInput(Ogre::Root* root, Ogre::RenderWindow* window)
{
Input* i = new Input(window);
root->addFrameListener(i);
return i;
}
Ogre::SceneManager* Application::initializeSceneManager()
{
Ogre::SceneManager *mgr = root_->createSceneManager(ST_GENERIC, "ExampleSMInstance");
Graphics::instance()->setSceneManager(mgr);
Engine::instance()->setSceneManager(mgr);
return mgr;
}
void Application::initializeViewport()
{
// Create one viewport, entire window
Viewport* vp = window_->addViewport(Graphics::instance()->camera());
vp->setBackgroundColour(ColourValue(0,0,0));
// Alter the camera aspect ratio to match the viewport
Graphics::instance()->camera()->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
}
Ogre::String Application::getResourcePath()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
return macBundlePath() + "/Contents/Resources/";
#else
return "";
#endif
}
Ogre::String Application::getConfigPath()
{
return getResourcePath();
}
void Application::initializeInterface()
{
// Prevent a nasty Mac OS X bug with setLogFilename.
new NullLogger;
// Initialize the GUI system.
CEGUI::OgreRenderer &renderer = CEGUI::OgreRenderer::bootstrapSystem(*window_);
CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme");
CEGUI::FontManager::getSingleton().create("DejaVuSans-10.font");
CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
CEGUI::Window *root = CEGUI::WindowManager::getSingleton().loadWindowLayout("gui/test.layout");
CEGUI::System::getSingleton().setGUISheet(root);
CEGUI::Window *quitButton = CEGUI::WindowManager::getSingleton().getWindow("quitButton");
quitButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Application::handleQuit, this));
}
<commit_msg>Test.<commit_after>/* Copyright (c) 2011 Cody Miller, Daniel Norris, Brett Hitchcock.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*****************************************************************************/
#include "Application.h"
#include <CEGUI.h>
#include "Application/NullLogger.h"
#include <RendererModules/Ogre/CEGUIOgreRenderer.h>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
Application::Application()
: resource_path_ (getResourcePath()),
config_path_ (getConfigPath())
{
// Initialize the root system
root_.reset(initializeRoot(resource_path_, config_path_, resource_path_));
// Initialize the window
window_ = initializeWindow();
// Set up references to all the resources
initializeResources();
// Set up the scene manager
scene_manager_ = initializeSceneManager();
// Create a new camera
Graphics::instance()->constructCamera();
// Constructs the viewports
initializeViewport();
// Initialize the input subsystem
input_system_.reset(initializeInput(root_.get(), window_));
// Set default mipmap level
TextureManager::getSingleton().setDefaultNumMipmaps(5);
// Create any resource listeners (for loading screens)
//createResourceListener();
// Load resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// Create the scene
Graphics::instance()->setup();
// Add event listeners
root_->addFrameListener(Engine::instance());
// Give the Engine what it needs to function
Engine::instance()->setWindow( window_ );
Engine::instance()->bindCamera( false ); //Active camera.
// Initialize the user interface
//initializeInterface();
// Connect to the remote server if we're able to
//initializeNetwork();
// Add event handling functions
handler_mappings["LocalMovePlayer"] = &Engine::handleLocalMovePlayer;
handler_mappings["LocalRotatePlayer"] = &Engine::handleLocalRotatePlayer;
handler_mappings["LocalUDCamera"] = &Engine::handleLocalUDCamera;
handler_mappings["LocalLRCamera"] = &Engine::handleLocalLRCamera;
handler_mappings["LocalZoomCamera"] = &Engine::handleLocalZoomCamera;
handler_mappings["LocalFireCannon"] = &Engine::handleLocalFireCannon;
handler_mappings["NetworkCreateEntity"] = &Engine::handleNetworkCreateEntity;
handler_mappings["NetworkDestroyEntity"]= &Engine::handleNetworkDestroyEntity;
handler_mappings["NetworkMoveEntity"] = &Engine::handleNetworkMoveEntity;
handler_mappings["NetworkRotateEntity"] = &Engine::handleNetworkRotateEntity;
handler_mappings["NetworkDamagePlayer"] = &Engine::handleNetworkDamagePlayer;
handler_mappings["NetworkSetAmbient"] = &Engine::handleNetworkSetAmbient;
}
Application::~Application()
{
// The boost::shared_ptrs free what needs to be freed here.
}
bool Application::handleQuit(const CEGUI::EventArgs& args)
{
exit(1);
// Graphics::instance()->rotateCamera(0.01, 0.0);
}
void Application::go()
{
root_->startRendering();
// clean up
//destroyScene();
}
Ogre::Root* Application::initializeRoot(const Ogre::String& plugin,
const Ogre::String& config,
const Ogre::String& log)
{
Ogre::Root *r = OGRE_NEW Root( plugin + "plugins.cfg", config + "ogre.cfg", log + "Ogre.log");
if (r == 0)
throw "Could not initialize Ogre::Root!";
return r;
}
void Application::initializeNetwork()
{
Ogre::ConfigFile *network_config = new Ogre::ConfigFile;
network_config->load(getConfigPath() + "network.cfg");
const Ogre::String address = network_config->getSetting("Address");
const Ogre::String port = network_config->getSetting("Port");
Network::instance()->connect(address.c_str(), port.c_str());
// This is necessary to have the networking branch off on its own thread.
thread_ = boost::thread(boost::bind(&asio::io_service::run, &Network::service()));
}
Ogre::RenderWindow* Application::initializeWindow()
{
Ogre::RenderWindow* win = NULL;
if (root_->showConfigDialog())
win = root_->initialise(true);
// The case that the user didn't want to configure/wanted to quit
if (win == 0)
closeApplication();
return win;
}
void Application::closeApplication()
{
Network::instance()->disconnect();
}
void Application::initializeResources()
{
Ogre::ConfigFile config;
Ogre::String section, type, arch;
config.load(resource_path_ + "resources.cfg");
Ogre::ConfigFile::SectionIterator itr = config.getSectionIterator();
while (itr.hasMoreElements()) {
section = itr.peekNextKey();
Ogre::ConfigFile::SettingsMultiMap* settings = itr.getNext();
Ogre::ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i) {
type = i->first;
arch = i->second;
#if OGRE_PLATFORM == OGRE_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
if (!Ogre::StringUtil::startsWith(arch, "/", false))
arch = String(macBundlePath() + "/" + arch);
#endif
ResourceGroupManager::getSingleton().addResourceLocation(arch, type, section);
}
}
}
Input* Application::initializeInput(Ogre::Root* root, Ogre::RenderWindow* window)
{
Input* i = new Input(window);
root->addFrameListener(i);
return i;
}
Ogre::SceneManager* Application::initializeSceneManager()
{
Ogre::SceneManager *mgr = root_->createSceneManager(ST_GENERIC, "ExampleSMInstance");
Graphics::instance()->setSceneManager(mgr);
Engine::instance()->setSceneManager(mgr);
return mgr;
}
void Application::initializeViewport()
{
// Create one viewport, entire window
Viewport* vp = window_->addViewport(Graphics::instance()->camera());
vp->setBackgroundColour(ColourValue(0,0,0));
// Alter the camera aspect ratio to match the viewport
Graphics::instance()->camera()->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
}
Ogre::String Application::getResourcePath()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
return macBundlePath() + "/Contents/Resources/";
#else
return "";
#endif
}
Ogre::String Application::getConfigPath()
{
return getResourcePath();
}
void Application::initializeInterface()
{
// Prevent a nasty Mac OS X bug with setLogFilename.
new NullLogger;
// Initialize the GUI system.
CEGUI::OgreRenderer &renderer = CEGUI::OgreRenderer::bootstrapSystem(*window_);
CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme");
CEGUI::FontManager::getSingleton().create("DejaVuSans-10.font");
CEGUI::System::getSingleton().setDefaultMouseCursor("TaharezLook", "MouseArrow");
CEGUI::Window *root = CEGUI::WindowManager::getSingleton().loadWindowLayout("gui/test.layout");
CEGUI::System::getSingleton().setGUISheet(root);
CEGUI::Window *quitButton = CEGUI::WindowManager::getSingleton().getWindow("quitButton");
quitButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Application::handleQuit, this));
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Lexer for the pretty CellML format
//==============================================================================
#include "prettycellmlviewlexer.h"
#include "qscintillawidget.h"
//==============================================================================
#include <QRegularExpression>
//==============================================================================
namespace OpenCOR {
namespace PrettyCellMLView {
//==============================================================================
PrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :
QsciLexerCustom(pParent),
mFullText(QString()),
mEolString(QString())
{
// Some initialisations
mKeywordsRegEx = QRegularExpression(
"\\b("
"as|base|comp|def|enddef|group|import|map|model|"
"unit|var"
")\\b");
mCellmlKeywordsRegEx = QRegularExpression(
"\\b("
// Standard units
"ampere|becquerel|candela|celsius|coulomb|"
"dimensionless|farad|gram|gray|henry|hertz|"
"joule|katal|kelvin|kilogram|liter|litre|"
"lumen|lux|meter|metre|mole|newton|ohm|"
"pascal|radian|second|siemens|sievert|"
"steradian|tesla|volt|watt|weber"
")\\b");
mParameterKeywordsRegEx = QRegularExpression(
"\\b("
// Unit keywords
"pref|expo|mult|off|"
// Variable keywords
"init|pub|priv"
")\\b");
mParameterValueKeywordsRegEx = QRegularExpression(
"\\b("
// Unit prefixes
"yotta|zetta|exa|peta|tera|giga|"
"mega|kilo|hecto|deka|deci|centi|"
"milli|micro|nano|pico|femto|atto|"
"zepto|yocto|"
// Public/private interfaces
"in|out|none"
")\\b");
mNumberRegEx = QRegularExpression("\\b\\d*\\.?\\d+([eE][+-]?\\d+)?\\b");
}
//==============================================================================
const char * PrettyCellmlViewLexer::language() const
{
// Return the language for our lexer
return "Pretty CellML";
}
//==============================================================================
QString PrettyCellmlViewLexer::description(int pStyle) const
{
// Return the given style's description
switch (pStyle) {
case Default:
return QObject::tr("Default");
case Comment:
return QObject::tr("Comment");
case Keyword:
return QObject::tr("Keyword");
case CellmlKeyword:
return QObject::tr("CellML keyword");
case Number:
return QObject::tr("Number");
case ParameterGroup:
return QObject::tr("Parameter group");
case ParameterKeyword:
return QObject::tr("Parameter keyword");
case ParameterValueKeyword:
return QObject::tr("Parameter value keyword");
case ParameterNumber:
return QObject::tr("Parameter number");
}
return QString();
}
//==============================================================================
QColor PrettyCellmlViewLexer::color(int pStyle) const
{
// Return the given style's colour
switch (pStyle) {
case Default:
case ParameterGroup:
return QColor(0x1f, 0x1f, 0x1f);
case Comment:
return QColor(0x00, 0x7f, 0x00);
case Keyword:
case ParameterKeyword:
return QColor(0x00, 0x00, 0x7f);
case CellmlKeyword:
case ParameterValueKeyword:
return QColor(0x7f, 0x00, 0x7f);
case Number:
case ParameterNumber:
return QColor(0x00, 0x7f, 0x7f);
}
return QsciLexerCustom::color(pStyle);
}
//==============================================================================
QFont PrettyCellmlViewLexer::font(int pStyle) const
{
// Return the given style's colour
QFont res = QsciLexer::font(pStyle);
switch (pStyle) {
case ParameterGroup:
case ParameterKeyword:
case ParameterValueKeyword:
case ParameterNumber:
res.setItalic(true);
break;
}
return res;
}
//==============================================================================
void PrettyCellmlViewLexer::styleText(int pStart, int pEnd)
{
// Make sure that we have an editor
if (!editor())
return;
// Retrieve the text to style
char *data = new char[pEnd-pStart+1];
editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);
QString text = QString(data);
delete[] data;
if (text.trimmed().isEmpty())
return;
// Effectively style our text
mFullText = editor()->text();
mEolString = qobject_cast<QScintillaSupport::QScintillaWidget *>(editor())->eolString();
doStyleText(pStart, pEnd, text, false);
// Let QScintilla know that we are done with the styling of our text
// Note: indeed, QScintilla uses the end position of the last bit of text
// that we styled (in our call to doStyleText()) to determine the
// position (pStart) of the next bit of text to style (see
// QsciLexerCustom::handleStyleNeeded()). Now, depending on how we do
// the styling, that end position may not be optimal at all. So, here,
// we set that value to pEnd, which is what end position would be if
// we were to style sequentially...
startStyling(pEnd);
}
//==============================================================================
static const auto CommentString = QStringLiteral("//");
static const int CommentStringLength = CommentString.length();
//==============================================================================
static const auto StartCommentString = QStringLiteral("/*");
static const auto EndCommentString = QStringLiteral("*/");
static const int StartCommentLength = StartCommentString.length();
static const int EndCommentLength = EndCommentString.length();
//==============================================================================
static const auto StartParameterGroupString = QStringLiteral("{");
static const auto EndParameterGroupString = QStringLiteral("}");
static const int StartParameterGroupLength = StartParameterGroupString.length();
static const int EndParameterGroupLength = EndParameterGroupString.length();
//==============================================================================
void PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,
bool pParameterGroup)
{
// Make sure that we are given some text to style
if (pText.trimmed().isEmpty())
return;
// Check whether a /* XXX */ comment started before or at the beginning of
// the given text
int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength-1);
if (commentStartPosition != -1) {
// A /* XXX */ comment started before or at the beginning of the given
// text, so now look for where it ends
int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);
if (commentEndPosition == -1) {
// The comment doesn't end as such, so consider that it 'ends' at
// the of the full text
commentEndPosition = mFullText.length();
}
if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {
// The beginning of the given text is a comment, so style it
int realEnd = commentEndPosition+EndCommentLength;
int end = qMin(pEnd, realEnd);
startStyling(pStart);
setStyling(end-pStart, Comment);
// Get ready to style everything that is behind the comment, if
// anything
if (end == realEnd) {
pStart = end;
pText = pText.right(pEnd-end);
} else {
return;
}
}
}
// Check whether a parameter group started before or at the beginning of the
// given text
int parameterGroupStartPosition = findString(StartParameterGroupString, pStart+StartParameterGroupLength-1, false);
if (parameterGroupStartPosition != -1) {
// A parameter group started before or at the beginning of the given
// text, so now look for where it ends
int parameterGroupEndPosition = findString(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);
if (parameterGroupEndPosition == -1)
parameterGroupEndPosition = mFullText.length();
if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {
// The beginning of the given text is a parameter group, so style
// everything that is behind the parameter group, if anything
int realEnd = parameterGroupEndPosition+EndParameterGroupLength;
int end = qMin(pEnd, realEnd);
bool hasEnd = end == realEnd;
if (hasEnd)
doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);
// If possible, style the beginning and/or the end of the parameter
// group
bool hasBeginning = parameterGroupStartPosition == pStart;
if (hasBeginning) {
startStyling(pStart);
setStyling(StartParameterGroupLength, ParameterGroup);
}
if (hasEnd) {
startStyling(end-EndParameterGroupLength);
setStyling(EndParameterGroupLength, ParameterGroup);
}
// Now style the contents of the parameter group
int newStart = pStart+(hasBeginning?StartParameterGroupLength:0);
int newEnd = end-(hasEnd?EndParameterGroupLength:0);
pText = pText.mid(newStart-pStart, newEnd-newStart);
pStart = newStart;
pEnd = newEnd;
pParameterGroup = true;
}
}
// Check whether the given text contains a // comment
int commentPosition = pText.indexOf(CommentString);
if (commentPosition != -1) {
// There is a // comment to style, so first style everything that is
// before it
doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),
pParameterGroup);
// Now, style everything that is after the // comment, if anything, by
// looking for the end of the line on which the // comment is
int eolPosition = pText.indexOf(mEolString, commentPosition+CommentStringLength);
if (eolPosition != -1) {
int start = pStart+eolPosition+mEolString.length();
doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);
}
// Style the // comment itself
int start = pStart+commentPosition;
startStyling(start);
setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);
return;
}
// Check whether the given text contains a /* XXX */ comment
commentStartPosition = pText.indexOf(StartCommentString);
if (commentStartPosition != -1) {
// There is a /* XXX */ comment to style, so first style everything that
// is before it
doStyleText(pStart, pStart+commentStartPosition,
pText.left(commentStartPosition), pParameterGroup);
// Now style everything from the comment onwards
// Note: to style everything from the comment onwards means that we will
// find that a /* XXX */ comment starts at the beginning of the
// 'new' given text...
doStyleText(pStart+commentStartPosition, pEnd,
pText.right(pEnd-pStart-commentStartPosition),
pParameterGroup);
return;
}
// Check whether the given text contains a parameter group
parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);
if (parameterGroupStartPosition != -1) {
// There is a parameter group, so first style everything that is before
// it
doStyleText(pStart, pStart+parameterGroupStartPosition,
pText.left(parameterGroupStartPosition), pParameterGroup);
// Now style everything from the parameter group onwards
// Note: to style everything from the parameter group onwards means that
// we will find that a parameter group starts at the beginning of
// the 'new' given text...
doStyleText(pStart+parameterGroupStartPosition, pEnd,
pText.right(pEnd-pStart-parameterGroupStartPosition),
pParameterGroup);
return;
}
// Use a default style for the given text
startStyling(pStart);
setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);
// Check whether the given text contains keywords from various categories
doStyleTextKeyword(pStart, pText, mKeywordsRegEx, pParameterGroup?ParameterGroup:Keyword);
doStyleTextKeyword(pStart, pText, mCellmlKeywordsRegEx, pParameterGroup?ParameterGroup:CellmlKeyword);
doStyleTextKeyword(pStart, pText, mParameterKeywordsRegEx, pParameterGroup?ParameterKeyword:Default);
doStyleTextKeyword(pStart, pText, mParameterValueKeywordsRegEx, pParameterGroup?ParameterValueKeyword:Default);
// Check whether the given text contains some numbers
doStyleTextNumber(pStart, pText, pParameterGroup?ParameterNumber:Number);
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,
const QString &pText,
const QRegularExpression &pKeywordsRegEx,
const int &pKeywordStyle)
{
// Style the given text with the given keyword style in the cases where a
// match for the given regular expression is found
QRegularExpressionMatchIterator regExMatchIter = pKeywordsRegEx.globalMatch(pText);
QRegularExpressionMatch regExMatch;
while (regExMatchIter.hasNext()) {
regExMatch = regExMatchIter.next();
// We found a keyword, so style it as such
startStyling(pStart+regExMatch.capturedStart());
setStyling(regExMatch.capturedLength(), pKeywordStyle);
}
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleTextNumber(int pStart, const QString &pText,
const int &pNumberStyle)
{
// Check whether the given text contains some numbers
QRegularExpressionMatchIterator regExMatchIter = mNumberRegEx.globalMatch(pText);
QRegularExpressionMatch regExMatch;
while (regExMatchIter.hasNext()) {
regExMatch = regExMatchIter.next();
// We found a number, so style it as such
startStyling(pStart+regExMatch.capturedStart());
setStyling(regExMatch.capturedLength(), pNumberStyle);
}
}
//==============================================================================
bool PrettyCellmlViewLexer::stringWithinComment(const int &pFrom,
const int &pTo) const
{
// Return whether the given string located at the given location is within
// a comment
// Check whether we are within a /* XXX */ comment
int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pFrom);
if (commentStartPosition != -1) {
int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);
if (commentEndPosition == -1)
commentEndPosition = mFullText.length();
if ((commentStartPosition < pFrom) && (pTo < commentEndPosition))
return true;
}
// Check whether we are within a // comment
int commentPosition = mFullText.lastIndexOf(CommentString, pFrom);
if (commentPosition != -1) {
int eolPosition = mFullText.indexOf(mEolString, commentPosition+CommentStringLength);
if (eolPosition == -1)
eolPosition = mFullText.length();
if ((commentPosition < pFrom) && (pTo < eolPosition))
return true;
}
return false;
}
//==============================================================================
int PrettyCellmlViewLexer::findString(const QString &pString, int pFrom,
const bool &pForward)
{
// Find forward/backward the given string starting from the given position
int stringLength = pString.length();
int res = pForward?pFrom-stringLength:pFrom+1;
do {
pFrom = pForward?res+stringLength:res-1;
res = pForward?mFullText.indexOf(pString, pFrom):mFullText.lastIndexOf(pString, pFrom);
} while ((res != -1) && stringWithinComment(res, res+stringLength-1));
return res;
}
//==============================================================================
} // namespace PrettyCellMLView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Pretty CellML view: some work on providing syntax highlighting for the pretty CellML format (#530) [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Lexer for the pretty CellML format
//==============================================================================
#include "prettycellmlviewlexer.h"
#include "qscintillawidget.h"
//==============================================================================
#include <QRegularExpression>
//==============================================================================
namespace OpenCOR {
namespace PrettyCellMLView {
//==============================================================================
PrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :
QsciLexerCustom(pParent),
mFullText(QString()),
mEolString(QString())
{
// Some initialisations
mKeywordsRegEx = QRegularExpression(
"\\b("
"as|base|comp|def|enddef|for|group|import|map|"
"model|unit|using|var"
")\\b");
mCellmlKeywordsRegEx = QRegularExpression(
"\\b("
// Standard units
"ampere|becquerel|candela|celsius|coulomb|"
"dimensionless|farad|gram|gray|henry|hertz|"
"joule|katal|kelvin|kilogram|liter|litre|"
"lumen|lux|meter|metre|mole|newton|ohm|"
"pascal|radian|second|siemens|sievert|"
"steradian|tesla|volt|watt|weber"
")\\b");
mParameterKeywordsRegEx = QRegularExpression(
"\\b("
// Unit keywords
"pref|expo|mult|off|"
// Variable keywords
"init|pub|priv"
")\\b");
mParameterValueKeywordsRegEx = QRegularExpression(
"\\b("
// Unit prefixes
"yotta|zetta|exa|peta|tera|giga|"
"mega|kilo|hecto|deka|deci|centi|"
"milli|micro|nano|pico|femto|atto|"
"zepto|yocto|"
// Public/private interfaces
"in|out|none"
")\\b");
mNumberRegEx = QRegularExpression("\\b\\d*\\.?\\d+([eE][+-]?\\d+)?\\b");
}
//==============================================================================
const char * PrettyCellmlViewLexer::language() const
{
// Return the language for our lexer
return "Pretty CellML";
}
//==============================================================================
QString PrettyCellmlViewLexer::description(int pStyle) const
{
// Return the given style's description
switch (pStyle) {
case Default:
return QObject::tr("Default");
case Comment:
return QObject::tr("Comment");
case Keyword:
return QObject::tr("Keyword");
case CellmlKeyword:
return QObject::tr("CellML keyword");
case Number:
return QObject::tr("Number");
case ParameterGroup:
return QObject::tr("Parameter group");
case ParameterKeyword:
return QObject::tr("Parameter keyword");
case ParameterValueKeyword:
return QObject::tr("Parameter value keyword");
case ParameterNumber:
return QObject::tr("Parameter number");
}
return QString();
}
//==============================================================================
QColor PrettyCellmlViewLexer::color(int pStyle) const
{
// Return the given style's colour
switch (pStyle) {
case Default:
case ParameterGroup:
return QColor(0x1f, 0x1f, 0x1f);
case Comment:
return QColor(0x00, 0x7f, 0x00);
case Keyword:
case ParameterKeyword:
return QColor(0x00, 0x00, 0x7f);
case CellmlKeyword:
case ParameterValueKeyword:
return QColor(0x7f, 0x00, 0x7f);
case Number:
case ParameterNumber:
return QColor(0x00, 0x7f, 0x7f);
}
return QsciLexerCustom::color(pStyle);
}
//==============================================================================
QFont PrettyCellmlViewLexer::font(int pStyle) const
{
// Return the given style's colour
QFont res = QsciLexer::font(pStyle);
switch (pStyle) {
case ParameterGroup:
case ParameterKeyword:
case ParameterValueKeyword:
case ParameterNumber:
res.setItalic(true);
break;
}
return res;
}
//==============================================================================
void PrettyCellmlViewLexer::styleText(int pStart, int pEnd)
{
// Make sure that we have an editor
if (!editor())
return;
// Retrieve the text to style
char *data = new char[pEnd-pStart+1];
editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);
QString text = QString(data);
delete[] data;
if (text.trimmed().isEmpty())
return;
// Effectively style our text
mFullText = editor()->text();
mEolString = qobject_cast<QScintillaSupport::QScintillaWidget *>(editor())->eolString();
doStyleText(pStart, pEnd, text, false);
// Let QScintilla know that we are done with the styling of our text
// Note: indeed, QScintilla uses the end position of the last bit of text
// that we styled (in our call to doStyleText()) to determine the
// position (pStart) of the next bit of text to style (see
// QsciLexerCustom::handleStyleNeeded()). Now, depending on how we do
// the styling, that end position may not be optimal at all. So, here,
// we set that value to pEnd, which is what end position would be if
// we were to style sequentially...
startStyling(pEnd);
}
//==============================================================================
static const auto CommentString = QStringLiteral("//");
static const int CommentStringLength = CommentString.length();
//==============================================================================
static const auto StartCommentString = QStringLiteral("/*");
static const auto EndCommentString = QStringLiteral("*/");
static const int StartCommentLength = StartCommentString.length();
static const int EndCommentLength = EndCommentString.length();
//==============================================================================
static const auto StartParameterGroupString = QStringLiteral("{");
static const auto EndParameterGroupString = QStringLiteral("}");
static const int StartParameterGroupLength = StartParameterGroupString.length();
static const int EndParameterGroupLength = EndParameterGroupString.length();
//==============================================================================
void PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,
bool pParameterGroup)
{
// Make sure that we are given some text to style
if (pText.trimmed().isEmpty())
return;
// Check whether a /* XXX */ comment started before or at the beginning of
// the given text
int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength-1);
if (commentStartPosition != -1) {
// A /* XXX */ comment started before or at the beginning of the given
// text, so now look for where it ends
int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);
if (commentEndPosition == -1) {
// The comment doesn't end as such, so consider that it 'ends' at
// the of the full text
commentEndPosition = mFullText.length();
}
if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {
// The beginning of the given text is a comment, so style it
int realEnd = commentEndPosition+EndCommentLength;
int end = qMin(pEnd, realEnd);
startStyling(pStart);
setStyling(end-pStart, Comment);
// Get ready to style everything that is behind the comment, if
// anything
if (end == realEnd) {
pStart = end;
pText = pText.right(pEnd-end);
} else {
return;
}
}
}
// Check whether a parameter group started before or at the beginning of the
// given text
int parameterGroupStartPosition = findString(StartParameterGroupString, pStart+StartParameterGroupLength-1, false);
if (parameterGroupStartPosition != -1) {
// A parameter group started before or at the beginning of the given
// text, so now look for where it ends
int parameterGroupEndPosition = findString(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);
if (parameterGroupEndPosition == -1)
parameterGroupEndPosition = mFullText.length();
if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {
// The beginning of the given text is a parameter group, so style
// everything that is behind the parameter group, if anything
int realEnd = parameterGroupEndPosition+EndParameterGroupLength;
int end = qMin(pEnd, realEnd);
bool hasEnd = end == realEnd;
if (hasEnd)
doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);
// If possible, style the beginning and/or the end of the parameter
// group
bool hasBeginning = parameterGroupStartPosition == pStart;
if (hasBeginning) {
startStyling(pStart);
setStyling(StartParameterGroupLength, ParameterGroup);
}
if (hasEnd) {
startStyling(end-EndParameterGroupLength);
setStyling(EndParameterGroupLength, ParameterGroup);
}
// Now style the contents of the parameter group
int newStart = pStart+(hasBeginning?StartParameterGroupLength:0);
int newEnd = end-(hasEnd?EndParameterGroupLength:0);
pText = pText.mid(newStart-pStart, newEnd-newStart);
pStart = newStart;
pEnd = newEnd;
pParameterGroup = true;
}
}
// Check whether the given text contains a // comment
int commentPosition = pText.indexOf(CommentString);
if (commentPosition != -1) {
// There is a // comment to style, so first style everything that is
// before it
doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),
pParameterGroup);
// Now, style everything that is after the // comment, if anything, by
// looking for the end of the line on which the // comment is
int eolPosition = pText.indexOf(mEolString, commentPosition+CommentStringLength);
if (eolPosition != -1) {
int start = pStart+eolPosition+mEolString.length();
doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);
}
// Style the // comment itself
int start = pStart+commentPosition;
startStyling(start);
setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);
return;
}
// Check whether the given text contains a /* XXX */ comment
commentStartPosition = pText.indexOf(StartCommentString);
if (commentStartPosition != -1) {
// There is a /* XXX */ comment to style, so first style everything that
// is before it
doStyleText(pStart, pStart+commentStartPosition,
pText.left(commentStartPosition), pParameterGroup);
// Now style everything from the comment onwards
// Note: to style everything from the comment onwards means that we will
// find that a /* XXX */ comment starts at the beginning of the
// 'new' given text...
doStyleText(pStart+commentStartPosition, pEnd,
pText.right(pEnd-pStart-commentStartPosition),
pParameterGroup);
return;
}
// Check whether the given text contains a parameter group
parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);
if (parameterGroupStartPosition != -1) {
// There is a parameter group, so first style everything that is before
// it
doStyleText(pStart, pStart+parameterGroupStartPosition,
pText.left(parameterGroupStartPosition), pParameterGroup);
// Now style everything from the parameter group onwards
// Note: to style everything from the parameter group onwards means that
// we will find that a parameter group starts at the beginning of
// the 'new' given text...
doStyleText(pStart+parameterGroupStartPosition, pEnd,
pText.right(pEnd-pStart-parameterGroupStartPosition),
pParameterGroup);
return;
}
// Use a default style for the given text
startStyling(pStart);
setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);
// Check whether the given text contains keywords from various categories
doStyleTextKeyword(pStart, pText, mKeywordsRegEx, pParameterGroup?ParameterGroup:Keyword);
doStyleTextKeyword(pStart, pText, mCellmlKeywordsRegEx, pParameterGroup?ParameterGroup:CellmlKeyword);
doStyleTextKeyword(pStart, pText, mParameterKeywordsRegEx, pParameterGroup?ParameterKeyword:Default);
doStyleTextKeyword(pStart, pText, mParameterValueKeywordsRegEx, pParameterGroup?ParameterValueKeyword:Default);
// Check whether the given text contains some numbers
doStyleTextNumber(pStart, pText, pParameterGroup?ParameterNumber:Number);
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,
const QString &pText,
const QRegularExpression &pKeywordsRegEx,
const int &pKeywordStyle)
{
// Style the given text with the given keyword style in the cases where a
// match for the given regular expression is found
QRegularExpressionMatchIterator regExMatchIter = pKeywordsRegEx.globalMatch(pText);
QRegularExpressionMatch regExMatch;
while (regExMatchIter.hasNext()) {
regExMatch = regExMatchIter.next();
// We found a keyword, so style it as such
startStyling(pStart+regExMatch.capturedStart());
setStyling(regExMatch.capturedLength(), pKeywordStyle);
}
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleTextNumber(int pStart, const QString &pText,
const int &pNumberStyle)
{
// Check whether the given text contains some numbers
QRegularExpressionMatchIterator regExMatchIter = mNumberRegEx.globalMatch(pText);
QRegularExpressionMatch regExMatch;
while (regExMatchIter.hasNext()) {
regExMatch = regExMatchIter.next();
// We found a number, so style it as such
startStyling(pStart+regExMatch.capturedStart());
setStyling(regExMatch.capturedLength(), pNumberStyle);
}
}
//==============================================================================
bool PrettyCellmlViewLexer::stringWithinComment(const int &pFrom,
const int &pTo) const
{
// Return whether the given string located at the given location is within
// a comment
// Check whether we are within a /* XXX */ comment
int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pFrom);
if (commentStartPosition != -1) {
int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);
if (commentEndPosition == -1)
commentEndPosition = mFullText.length();
if ((commentStartPosition < pFrom) && (pTo < commentEndPosition))
return true;
}
// Check whether we are within a // comment
int commentPosition = mFullText.lastIndexOf(CommentString, pFrom);
if (commentPosition != -1) {
int eolPosition = mFullText.indexOf(mEolString, commentPosition+CommentStringLength);
if (eolPosition == -1)
eolPosition = mFullText.length();
if ((commentPosition < pFrom) && (pTo < eolPosition))
return true;
}
return false;
}
//==============================================================================
int PrettyCellmlViewLexer::findString(const QString &pString, int pFrom,
const bool &pForward)
{
// Find forward/backward the given string starting from the given position
int stringLength = pString.length();
int res = pForward?pFrom-stringLength:pFrom+1;
do {
pFrom = pForward?res+stringLength:res-1;
res = pForward?mFullText.indexOf(pString, pFrom):mFullText.lastIndexOf(pString, pFrom);
} while ((res != -1) && stringWithinComment(res, res+stringLength-1));
return res;
}
//==============================================================================
} // namespace PrettyCellMLView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before><commit_msg>patch accessing_xhr.response_as_arraybuffer_from_node_context<commit_after><|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <vector>
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/proto/pauli_sum.pb.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;
class TfqSimulateSampledExpectationOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateSampledExpectationOp(
tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
const int num_inputs = context->num_inputs();
OP_REQUIRES(context, num_inputs == 5,
tensorflow::errors::InvalidArgument(absl::StrCat(
"Expected 5 inputs, got ", num_inputs, " inputs.")));
// Create the output Tensor.
const int output_dim_batch_size = context->input(0).dim_size(0);
const int output_dim_op_size = context->input(3).dim_size(1);
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_batch_size);
output_shape.AddDim(output_dim_op_size);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<float>();
std::vector<Program> programs;
std::vector<int> num_qubits;
std::vector<std::vector<PauliSum>> pauli_sums;
OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs,
&num_qubits, &pauli_sums));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(context, pauli_sums.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and PauliSums do not match. Got ",
programs.size(), " circuits and ", pauli_sums.size(),
" paulisums.")));
std::vector<std::vector<unsigned int>> num_samples;
OP_REQUIRES_OK(context, GetNumSamples(context, &num_samples));
OP_REQUIRES(context, num_samples.size() == pauli_sums.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Dimension 0 of num_samples and pauli_sums do not match.",
"Got ", num_samples.size(), " lists of sample sizes and ",
pauli_sums.size(), " lists of pauli sums.")));
auto DoWork = [&](int start, int end) {
int old_batch_index = -2;
int cur_batch_index = -1;
int old_num_qubits = -2;
int cur_op_index;
std::unique_ptr<StateSpace> test_state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
std::unique_ptr<StateSpace> scratch_state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
for (int i = start; i < end; i++) {
cur_batch_index = i / output_dim_op_size;
cur_op_index = i % output_dim_op_size;
// (#679) Just ignore empty program
if (programs[cur_batch_index].circuit().moments().empty()) {
output_tensor(cur_batch_index, cur_op_index) = -2.0;
continue;
}
if (cur_batch_index != old_batch_index) {
// We've run into a new wavefunction we must compute.
// Only compute a new wavefunction when we have to.
Program program = programs[cur_batch_index];
const int num = num_qubits[cur_batch_index];
OP_REQUIRES_OK(context,
ResolveSymbols(maps[cur_batch_index], &program));
Circuit circuit;
OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));
// TODO(mbbrough): Update this allocation hack so that a StateSpace
// object can grow it's memory dynamically to larger and larger size
// without ever having to call free (until very end). This is tricky
// to implement because right now certain statespaces can't simulate
// all states and we use StateSpaceSlow for smaller circuits.
if (num != old_num_qubits) {
test_state.reset(GetStateSpace(num, 1));
test_state->CreateState();
// Also re-allocate scratch state for expectation calculations.
scratch_state.reset(GetStateSpace(num, 1));
scratch_state->CreateState();
}
// no need to update scratch_state since ComputeExpectation
// will take care of things for us.
test_state->SetStateZero();
OP_REQUIRES_OK(context, test_state->Update(circuit));
old_num_qubits = num;
}
float expectation = 0.0;
OP_REQUIRES_OK(
context,
test_state->ComputeSampledExpectation(
pauli_sums[cur_batch_index][cur_op_index], scratch_state.get(),
&expectation, num_samples[cur_batch_index][cur_op_index]));
output_tensor(cur_batch_index, cur_op_index) = expectation;
old_batch_index = cur_batch_index;
}
};
const int block_size =
GetBlockSize(context, output_dim_batch_size * output_dim_op_size);
context->device()
->tensorflow_cpu_worker_threads()
->workers->TransformRangeConcurrently(
block_size, output_dim_batch_size * output_dim_op_size, DoWork);
}
};
REGISTER_KERNEL_BUILDER(
Name("TfqSimulateSampledExpectation").Device(tensorflow::DEVICE_CPU),
TfqSimulateSampledExpectationOp);
REGISTER_OP("TfqSimulateSampledExpectation")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Input("pauli_sums: string")
.Input("num_samples: uint32")
.Output("expectations: float")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
tensorflow::shape_inference::ShapeHandle pauli_sums_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape));
tensorflow::shape_inference::ShapeHandle num_samples_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &num_samples_shape));
tensorflow::shape_inference::DimensionHandle output_rows =
c->Dim(programs_shape, 0);
tensorflow::shape_inference::DimensionHandle output_cols =
c->Dim(pauli_sums_shape, 1);
c->set_output(0, c->Matrix(output_rows, output_cols));
return tensorflow::Status::OK();
});
} // namespace tfq
<commit_msg>Update to pointer<commit_after>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <vector>
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/proto/pauli_sum.pb.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;
class TfqSimulateSampledExpectationOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateSampledExpectationOp(
tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
const int num_inputs = context->num_inputs();
OP_REQUIRES(context, num_inputs == 5,
tensorflow::errors::InvalidArgument(absl::StrCat(
"Expected 5 inputs, got ", num_inputs, " inputs.")));
// Create the output Tensor.
const int output_dim_batch_size = context->input(0).dim_size(0);
const int output_dim_op_size = context->input(3).dim_size(1);
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_batch_size);
output_shape.AddDim(output_dim_op_size);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<float>();
std::vector<Program> programs;
std::vector<int> num_qubits;
std::vector<std::vector<PauliSum>> pauli_sums;
OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs,
&num_qubits, &pauli_sums));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(context, pauli_sums.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and PauliSums do not match. Got ",
programs.size(), " circuits and ", pauli_sums.size(),
" paulisums.")));
std::vector<std::vector<unsigned int>> num_samples;
OP_REQUIRES_OK(context, GetNumSamples(context, &num_samples));
OP_REQUIRES(context, num_samples.size() == pauli_sums.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Dimension 0 of num_samples and pauli_sums do not match.",
"Got ", num_samples.size(), " lists of sample sizes and ",
pauli_sums.size(), " lists of pauli sums.")));
auto DoWork = [&](int start, int end) {
int old_batch_index = -2;
int cur_batch_index = -1;
int old_num_qubits = -2;
int cur_op_index;
std::unique_ptr<StateSpace> test_state = GetStateSpace(1, 1);
std::unique_ptr<StateSpace> scratch_state = GetStateSpace(1, 1);
for (int i = start; i < end; i++) {
cur_batch_index = i / output_dim_op_size;
cur_op_index = i % output_dim_op_size;
// (#679) Just ignore empty program
if (programs[cur_batch_index].circuit().moments().empty()) {
output_tensor(cur_batch_index, cur_op_index) = -2.0;
continue;
}
if (cur_batch_index != old_batch_index) {
// We've run into a new wavefunction we must compute.
// Only compute a new wavefunction when we have to.
Program program = programs[cur_batch_index];
const int num = num_qubits[cur_batch_index];
OP_REQUIRES_OK(context,
ResolveSymbols(maps[cur_batch_index], &program));
Circuit circuit;
OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));
// TODO(mbbrough): Update this allocation hack so that a StateSpace
// object can grow it's memory dynamically to larger and larger size
// without ever having to call free (until very end). This is tricky
// to implement because right now certain statespaces can't simulate
// all states and we use StateSpaceSlow for smaller circuits.
if (num != old_num_qubits) {
test_state = GetStateSpace(num, 1);
test_state->CreateState();
// Also re-allocate scratch state for expectation calculations.
scratch_state = GetStateSpace(num, 1);
scratch_state->CreateState();
}
// no need to update scratch_state since ComputeExpectation
// will take care of things for us.
test_state->SetStateZero();
OP_REQUIRES_OK(context, test_state->Update(circuit));
old_num_qubits = num;
}
float expectation = 0.0;
OP_REQUIRES_OK(
context,
test_state->ComputeSampledExpectation(
pauli_sums[cur_batch_index][cur_op_index], scratch_state.get(),
&expectation, num_samples[cur_batch_index][cur_op_index]));
output_tensor(cur_batch_index, cur_op_index) = expectation;
old_batch_index = cur_batch_index;
}
};
const int block_size =
GetBlockSize(context, output_dim_batch_size * output_dim_op_size);
context->device()
->tensorflow_cpu_worker_threads()
->workers->TransformRangeConcurrently(
block_size, output_dim_batch_size * output_dim_op_size, DoWork);
}
};
REGISTER_KERNEL_BUILDER(
Name("TfqSimulateSampledExpectation").Device(tensorflow::DEVICE_CPU),
TfqSimulateSampledExpectationOp);
REGISTER_OP("TfqSimulateSampledExpectation")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Input("pauli_sums: string")
.Input("num_samples: uint32")
.Output("expectations: float")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
tensorflow::shape_inference::ShapeHandle pauli_sums_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape));
tensorflow::shape_inference::ShapeHandle num_samples_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &num_samples_shape));
tensorflow::shape_inference::DimensionHandle output_rows =
c->Dim(programs_shape, 0);
tensorflow::shape_inference::DimensionHandle output_cols =
c->Dim(pauli_sums_shape, 1);
c->set_output(0, c->Matrix(output_rows, output_cols));
return tensorflow::Status::OK();
});
} // namespace tfq
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* 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. *
**************************************************************************/
/* $Id$ */
//--------------------------------------------------------------------
// Options for the TPC Reconstruction in rec.C
//
// 4 options can be set to change the input for TPC reconstruction
// which overwrites the usage of fUseHLTClusters of the AliTPCRecoParam
//
// 1) useRAW - use RAW, if not present -> do nothing
// 2) useRAWorHLT - use RAW, if not present -> use HLT clusters
// 3) useHLT - use HLT clusters, if not present -> do nothing
// 4) useHLTorRAW - use HLT clusters, if not present -> use RAW
//
// -> The current default is useHLTorRAW
//--------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// //
// class for TPC reconstruction //
// //
///////////////////////////////////////////////////////////////////////////////
#include <TObject.h>
#include <TString.h>
#include <TObjString.h>
#include <TObjArray.h>
#include <TFile.h>
#include <AliLog.h>
#include <AliPID.h>
#include <AliESDpid.h>
#include <AliTPCPIDResponse.h>
#include "AliTPCReconstructor.h"
#include "AliRunLoader.h"
#include "AliRun.h"
#include "AliRawReader.h"
#include "AliTPCclusterer.h"
#include "AliTPCtracker.h"
#include "AliTPCParam.h"
#include "AliTPCParamSR.h"
#include "AliTPCcalibDB.h"
#include "AliTracker.h"
#include "AliMagF.h"
#include "TTreeStream.h"
ClassImp(AliTPCReconstructor)
Int_t AliTPCReconstructor::fgStreamLevel = 0; // stream (debug) level
AliTPCAltroEmulator * AliTPCReconstructor::fAltroEmulator=0; // ALTRO emulator
TTreeSRedirector * AliTPCReconstructor::fgDebugStreamer=0; // NOTE - AliTPCReconstructor is not an owner of the streamer
TString AliTPCReconstructor::fgPIDRespnonsePath="$ALICE_PHYSICS/OADB/COMMON/PID/data/TPCPIDResponse.root";
TVectorD * AliTPCReconstructor::fSystematicErrors=0;
TVectorD * AliTPCReconstructor::fSystematicErrorClusters=0;
TVectorD * AliTPCReconstructor::fgExtendedRoads=0;
TVectorD * AliTPCReconstructor::fgPrimaryDCACut=0;
Double_t AliTPCReconstructor::fgPrimaryZ2XCut = 0;
Double_t AliTPCReconstructor::fgZOutSectorCut = 0;
Bool_t AliTPCReconstructor::fgCompactClusters = kFALSE;
Bool_t AliTPCReconstructor::fgCountMCTrackClusters = kFALSE;
AliTPCReconstructor::AliTPCReconstructor():
AliReconstructor(),
fClusterer(NULL),
fArrSplines(NULL)
{
//
// default constructor
//
//
//
AliTPCcalibDB * calib = AliTPCcalibDB::Instance();
const AliMagF * field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
calib->SetExBField(field);
AliTPCParam* param = GetTPCParam();
if (!param) {
AliWarning("Loading default TPC parameters !");
param = new AliTPCParamSR;
}
fClusterer = new AliTPCclusterer(param);
}
AliTPCReconstructor::AliTPCReconstructor(const AliTPCReconstructor& /*rec*/):
AliReconstructor(),
fClusterer(NULL),
fArrSplines(NULL)
{
//
// Dummy copu constructor
//
}
AliTPCReconstructor& AliTPCReconstructor::operator=(const AliTPCReconstructor&){
//
// dummy operator
//
return *this;
}
//_____________________________________________________________________________
AliTPCReconstructor::~AliTPCReconstructor()
{
if (fClusterer) delete fClusterer;
delete fArrSplines;
delete AliTPCcalibDB::Instance();
}
//_____________________________________________________________________________
void AliTPCReconstructor::Reconstruct(TTree* digitsTree, TTree* clustersTree) const {
// single event local reconstruction
// of TPC data
fClusterer->SetTimeStamp(GetTimeStamp());
fClusterer->SetInput(digitsTree);
fClusterer->SetOutput(clustersTree);
fClusterer->Digits2Clusters();
}
//_____________________________________________________________________________
void AliTPCReconstructor::Reconstruct(AliRawReader* rawReader, TTree* clustersTree) const {
// single event local reconstruction
// of TPC data starting from raw data
fClusterer->SetTimeStamp(GetTimeStamp());
fClusterer->SetOutput(clustersTree);
fClusterer->Digits2Clusters(rawReader);
}
//_____________________________________________________________________________
AliTracker* AliTPCReconstructor::CreateTracker() const
{
// create a TPC tracker
AliTPCParam* param = GetTPCParam();
if (!param) {
AliWarning("Loading default TPC parameters !");
param = new AliTPCParamSR;
}
param->ReadGeoMatrices();
AliTPCtracker* tracker = new AliTPCtracker(param);
ParseOptions(tracker);
return tracker;
}
//_____________________________________________________________________________
void AliTPCReconstructor::FillESD(TTree */*digitsTree*/, TTree */*clustersTree*/,
AliESDEvent* /*esd*/) const
{
// make PID
/* Now done in AliESDpid
Double_t parTPC[] = {50., 0.07, 5.}; // MIP nnormalized to channel 50 -MI
AliTPCpidESD tpcPID(parTPC);
tpcPID.MakePID(esd);
*/
}
//_____________________________________________________________________________
AliTPCParam* AliTPCReconstructor::GetTPCParam() const
{
// get the TPC parameters
AliTPCParam* param = AliTPCcalibDB::Instance()->GetParameters();
return param;
}
//_____________________________________________________________________________
void AliTPCReconstructor::SetSplinesFromOADB(const char* tmplt, AliESDpid *esdPID)
{
//
// load splines from the OADB using 'template'
//
// only load splines if not already set
if (!fArrSplines) {
fArrSplines=new TObjArray(Int_t(AliPID::kSPECIES));
fArrSplines->SetOwner();
TString stemplate(tmplt);
TFile f(GetPIDRespnonsePath());
TObjArray *arrPidResponseMaster=0x0;
if (f.IsOpen() && !f.IsZombie()){
arrPidResponseMaster=dynamic_cast<TObjArray*>(f.Get("TPCPIDResponse"));
}
f.Close();
if (!arrPidResponseMaster){
AliError("PID response array not found, cannot assign proper splines");
return;
}
for (Int_t ispec=0; ispec<AliPID::kSPECIES; ++ispec)
{
Int_t ispec2=ispec;
if (ispec==Int_t(AliPID::kMuon)) ispec2=Int_t(AliPID::kPion);
TString particle=AliPID::ParticleName(ispec2);
particle.ToUpper();
TString splineName;
splineName.Form(stemplate.Data(),particle.Data());
TObject *spline=arrPidResponseMaster->FindObject(splineName.Data());
if (!spline) {
AliError(Form("No spline found for '%s'", splineName.Data()));
continue;
};
AliInfo(Form("Adding Response function %d:%s",ispec,splineName.Data()));
fArrSplines->AddAt(spline->Clone(), ispec);
}
arrPidResponseMaster->Delete();
delete arrPidResponseMaster;
if (fArrSplines->GetEntries()!=Int_t(AliPID::kSPECIES)) {
AliError("Splines not found for all species, cannot use proper PID");
delete fArrSplines;
fArrSplines=NULL;
return;
}
}
for (Int_t ispec=0; ispec<AliPID::kSPECIES; ++ispec)
{
esdPID->GetTPCResponse().SetResponseFunction( (AliPID::EParticleType)ispec, fArrSplines->UncheckedAt(ispec) );
}
esdPID->GetTPCResponse().SetUseDatabase(kTRUE);
}
//_____________________________________________________________________________
void AliTPCReconstructor::GetPidSettings(AliESDpid *esdPID)
{
//
// Get TPC pid splines. They should be written to the OCDB during the CPass
// the splines themselves are owned by the OCDB object
//
// parse options
TString allopt(GetOption());
TObjArray *optArray=allopt.Tokenize(";");
// defines whether the pid was set via a specific option in the rec.C
Bool_t pidSetInOptions = kFALSE;
for (Int_t iopt=0; iopt<optArray->GetEntriesFast(); ++iopt){
if (!optArray->At(iopt)) continue;
TString option(static_cast<TObjString*>(optArray->At(iopt))->GetString().Strip(TString::kBoth,' '));
if (!option.BeginsWith("PID.")) continue;
// remove 'PID.' identifyer
option.Remove(0,4);
// parse PID type
if (option.BeginsWith("Static=")){
option.Remove(0,option.First('=')+1);
if (option.Contains("LHC13b2_fix_PID")) {
esdPID->GetTPCResponse().SetBetheBlochParameters(0.0320981, 19.9768, 2.52666e-16, 2.72123, 6.08092);
esdPID->GetTPCResponse().SetMip(53.4968);
pidSetInOptions=kTRUE;
}
} else if (option.BeginsWith("OADB=")) {
option.Remove(0,option.First('=')+1);
AliInfo(Form("Setting splines From OADB using template: '%s'",option.Data()));
SetSplinesFromOADB(option, esdPID);
pidSetInOptions=kTRUE;
} else if (option.BeginsWith("OCDB=")){
option.Remove(0,option.First('=')+1);
// not yet implemented
}
}
delete optArray;
//
// Initialisation of BB parameters from the OCDB.
// They are stored in the AliTPCParam
//
if (!pidSetInOptions) {
AliTPCParam* param = AliTPCcalibDB::Instance()->GetParameters();
if (param) {
TVectorD *paramBB=param->GetBetheBlochParameters();
const Float_t maxnSigmaRange = param->GetSigmaRangePIDinTracking();
if (paramBB){
esdPID->GetTPCResponse().SetBetheBlochParameters((*paramBB)(0),(*paramBB)(1),(*paramBB)(2),(*paramBB)(3),(*paramBB)(4));
AliInfo(Form("Setting BB parameters from OCDB (AliTPCParam): %.2g, %.2g, %.2g, %.2g, %.2g",
(*paramBB)(0),(*paramBB)(1),(*paramBB)(2),(*paramBB)(3),(*paramBB)(4)));
AliInfoF("Setting max sigma PID range to %.2f", maxnSigmaRange);
esdPID->SetProbabilityRangeNsigma(maxnSigmaRange);
} else {
AliError("Couldn't get BB parameters from OCDB, the old default values will be used instead");
}
} else {
AliError("Couldn't get TPC parameters");
}
}
/*
AliTPCcalibDB * calib = AliTPCcalibDB::Instance();
//Get pid splines array
TObjArray *arrSplines=calib->GetPidResponse();
if (!arrSplines) return;
AliTPCPIDResponse &tpcPID=esdPID->GetTPCResponse();
tpcPID.SetUseDatabase(kTRUE);
// check if parametrisations are already set.
// since this is uniq for one run, we don't have to reload them
if (tpcPID.GetResponseFunction(AliPID::kPion)) return;
// get the default object
TObject *defaultPID=arrSplines->At(AliPID::kUnknown);
// loop over all particle species and set the response functions
for (Int_t ispec=0; ispec<AliPID::kUnknown; ++ispec){
TObject *pidSpline=arrSplines->At(ispec);
if (!pidSpline) pidSpline=defaultPID;
tpcPID.SetResponseFunction((AliPID::EParticleType)ispec,pidSpline);
}
*/
}
//_____________________________________________________________________________
void AliTPCReconstructor::ParseOptions( AliTPCtracker* tracker ) const
{
// parse options from rec.C and set in clusterer and tracker
TString option = GetOption();
Int_t useHLTClusters = 3;
if (option.Contains("use")) {
AliInfo(Form("Overide TPC RecoParam with option %s",option.Data()));
if (option.Contains("useRAW")) {
useHLTClusters = 1;
if (option.Contains("useRAWorHLT"))
useHLTClusters = 2;
}
else if (option.Contains("useHLT")) {
useHLTClusters = 3;
if (option.Contains("useHLTorRAW"))
useHLTClusters = 4;
}
}
else {
const AliTPCRecoParam* param = GetRecoParam();
useHLTClusters = param->GetUseHLTClusters();
}
AliInfo(Form("Usage of HLT clusters in TPC reconstruction : %d", useHLTClusters));
fClusterer->SetUseHLTClusters(useHLTClusters);
tracker->SetUseHLTClusters(useHLTClusters);
return;
}
//_____________________________________________________________________________
void AliTPCReconstructor::SetSystematicErrorCluster( TVectorD *vec )
{
// set clusters syst.errors which will override persistent data member from AliTPCRecoParam::fSystematicErrors
fSystematicErrorClusters=vec;
AliTPCRecoParam::SetSystematicErrorClusterCustom(vec);
}
//_____________________________________________________________________________
void AliTPCReconstructor::SetPrimaryDCACut( TVectorD *dcacut )
{
// set clusters syst.errors which will override persistent data member from AliTPCRecoParam::fSystematicErrors
fgPrimaryDCACut=dcacut;
AliTPCRecoParam::SetPrimaryDCACut(dcacut);
}
<commit_msg>fix typo in comment<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* 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. *
**************************************************************************/
/* $Id$ */
//--------------------------------------------------------------------
// Options for the TPC Reconstruction in rec.C
//
// 4 options can be set to change the input for TPC reconstruction
// which overwrites the usage of fUseHLTClusters of the AliTPCRecoParam
//
// 1) useRAW - use RAW, if not present -> do nothing
// 2) useRAWorHLT - use RAW, if not present -> use HLT clusters
// 3) useHLT - use HLT clusters, if not present -> do nothing
// 4) useHLTorRAW - use HLT clusters, if not present -> use RAW
//
// -> The current default is useHLTorRAW
//--------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// //
// class for TPC reconstruction //
// //
///////////////////////////////////////////////////////////////////////////////
#include <TObject.h>
#include <TString.h>
#include <TObjString.h>
#include <TObjArray.h>
#include <TFile.h>
#include <AliLog.h>
#include <AliPID.h>
#include <AliESDpid.h>
#include <AliTPCPIDResponse.h>
#include "AliTPCReconstructor.h"
#include "AliRunLoader.h"
#include "AliRun.h"
#include "AliRawReader.h"
#include "AliTPCclusterer.h"
#include "AliTPCtracker.h"
#include "AliTPCParam.h"
#include "AliTPCParamSR.h"
#include "AliTPCcalibDB.h"
#include "AliTracker.h"
#include "AliMagF.h"
#include "TTreeStream.h"
ClassImp(AliTPCReconstructor)
Int_t AliTPCReconstructor::fgStreamLevel = 0; // stream (debug) level
AliTPCAltroEmulator * AliTPCReconstructor::fAltroEmulator=0; // ALTRO emulator
TTreeSRedirector * AliTPCReconstructor::fgDebugStreamer=0; // NOTE - AliTPCReconstructor is not an owner of the streamer
TString AliTPCReconstructor::fgPIDRespnonsePath="$ALICE_PHYSICS/OADB/COMMON/PID/data/TPCPIDResponse.root";
TVectorD * AliTPCReconstructor::fSystematicErrors=0;
TVectorD * AliTPCReconstructor::fSystematicErrorClusters=0;
TVectorD * AliTPCReconstructor::fgExtendedRoads=0;
TVectorD * AliTPCReconstructor::fgPrimaryDCACut=0;
Double_t AliTPCReconstructor::fgPrimaryZ2XCut = 0;
Double_t AliTPCReconstructor::fgZOutSectorCut = 0;
Bool_t AliTPCReconstructor::fgCompactClusters = kFALSE;
Bool_t AliTPCReconstructor::fgCountMCTrackClusters = kFALSE;
AliTPCReconstructor::AliTPCReconstructor():
AliReconstructor(),
fClusterer(NULL),
fArrSplines(NULL)
{
//
// default constructor
//
//
//
AliTPCcalibDB * calib = AliTPCcalibDB::Instance();
const AliMagF * field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
calib->SetExBField(field);
AliTPCParam* param = GetTPCParam();
if (!param) {
AliWarning("Loading default TPC parameters !");
param = new AliTPCParamSR;
}
fClusterer = new AliTPCclusterer(param);
}
AliTPCReconstructor::AliTPCReconstructor(const AliTPCReconstructor& /*rec*/):
AliReconstructor(),
fClusterer(NULL),
fArrSplines(NULL)
{
//
// Dummy copy constructor
//
}
AliTPCReconstructor& AliTPCReconstructor::operator=(const AliTPCReconstructor&){
//
// dummy operator
//
return *this;
}
//_____________________________________________________________________________
AliTPCReconstructor::~AliTPCReconstructor()
{
if (fClusterer) delete fClusterer;
delete fArrSplines;
delete AliTPCcalibDB::Instance();
}
//_____________________________________________________________________________
void AliTPCReconstructor::Reconstruct(TTree* digitsTree, TTree* clustersTree) const {
// single event local reconstruction
// of TPC data
fClusterer->SetTimeStamp(GetTimeStamp());
fClusterer->SetInput(digitsTree);
fClusterer->SetOutput(clustersTree);
fClusterer->Digits2Clusters();
}
//_____________________________________________________________________________
void AliTPCReconstructor::Reconstruct(AliRawReader* rawReader, TTree* clustersTree) const {
// single event local reconstruction
// of TPC data starting from raw data
fClusterer->SetTimeStamp(GetTimeStamp());
fClusterer->SetOutput(clustersTree);
fClusterer->Digits2Clusters(rawReader);
}
//_____________________________________________________________________________
AliTracker* AliTPCReconstructor::CreateTracker() const
{
// create a TPC tracker
AliTPCParam* param = GetTPCParam();
if (!param) {
AliWarning("Loading default TPC parameters !");
param = new AliTPCParamSR;
}
param->ReadGeoMatrices();
AliTPCtracker* tracker = new AliTPCtracker(param);
ParseOptions(tracker);
return tracker;
}
//_____________________________________________________________________________
void AliTPCReconstructor::FillESD(TTree */*digitsTree*/, TTree */*clustersTree*/,
AliESDEvent* /*esd*/) const
{
// make PID
/* Now done in AliESDpid
Double_t parTPC[] = {50., 0.07, 5.}; // MIP nnormalized to channel 50 -MI
AliTPCpidESD tpcPID(parTPC);
tpcPID.MakePID(esd);
*/
}
//_____________________________________________________________________________
AliTPCParam* AliTPCReconstructor::GetTPCParam() const
{
// get the TPC parameters
AliTPCParam* param = AliTPCcalibDB::Instance()->GetParameters();
return param;
}
//_____________________________________________________________________________
void AliTPCReconstructor::SetSplinesFromOADB(const char* tmplt, AliESDpid *esdPID)
{
//
// load splines from the OADB using 'template'
//
// only load splines if not already set
if (!fArrSplines) {
fArrSplines=new TObjArray(Int_t(AliPID::kSPECIES));
fArrSplines->SetOwner();
TString stemplate(tmplt);
TFile f(GetPIDRespnonsePath());
TObjArray *arrPidResponseMaster=0x0;
if (f.IsOpen() && !f.IsZombie()){
arrPidResponseMaster=dynamic_cast<TObjArray*>(f.Get("TPCPIDResponse"));
}
f.Close();
if (!arrPidResponseMaster){
AliError("PID response array not found, cannot assign proper splines");
return;
}
for (Int_t ispec=0; ispec<AliPID::kSPECIES; ++ispec)
{
Int_t ispec2=ispec;
if (ispec==Int_t(AliPID::kMuon)) ispec2=Int_t(AliPID::kPion);
TString particle=AliPID::ParticleName(ispec2);
particle.ToUpper();
TString splineName;
splineName.Form(stemplate.Data(),particle.Data());
TObject *spline=arrPidResponseMaster->FindObject(splineName.Data());
if (!spline) {
AliError(Form("No spline found for '%s'", splineName.Data()));
continue;
};
AliInfo(Form("Adding Response function %d:%s",ispec,splineName.Data()));
fArrSplines->AddAt(spline->Clone(), ispec);
}
arrPidResponseMaster->Delete();
delete arrPidResponseMaster;
if (fArrSplines->GetEntries()!=Int_t(AliPID::kSPECIES)) {
AliError("Splines not found for all species, cannot use proper PID");
delete fArrSplines;
fArrSplines=NULL;
return;
}
}
for (Int_t ispec=0; ispec<AliPID::kSPECIES; ++ispec)
{
esdPID->GetTPCResponse().SetResponseFunction( (AliPID::EParticleType)ispec, fArrSplines->UncheckedAt(ispec) );
}
esdPID->GetTPCResponse().SetUseDatabase(kTRUE);
}
//_____________________________________________________________________________
void AliTPCReconstructor::GetPidSettings(AliESDpid *esdPID)
{
//
// Get TPC pid splines. They should be written to the OCDB during the CPass
// the splines themselves are owned by the OCDB object
//
// parse options
TString allopt(GetOption());
TObjArray *optArray=allopt.Tokenize(";");
// defines whether the pid was set via a specific option in the rec.C
Bool_t pidSetInOptions = kFALSE;
for (Int_t iopt=0; iopt<optArray->GetEntriesFast(); ++iopt){
if (!optArray->At(iopt)) continue;
TString option(static_cast<TObjString*>(optArray->At(iopt))->GetString().Strip(TString::kBoth,' '));
if (!option.BeginsWith("PID.")) continue;
// remove 'PID.' identifyer
option.Remove(0,4);
// parse PID type
if (option.BeginsWith("Static=")){
option.Remove(0,option.First('=')+1);
if (option.Contains("LHC13b2_fix_PID")) {
esdPID->GetTPCResponse().SetBetheBlochParameters(0.0320981, 19.9768, 2.52666e-16, 2.72123, 6.08092);
esdPID->GetTPCResponse().SetMip(53.4968);
pidSetInOptions=kTRUE;
}
} else if (option.BeginsWith("OADB=")) {
option.Remove(0,option.First('=')+1);
AliInfo(Form("Setting splines From OADB using template: '%s'",option.Data()));
SetSplinesFromOADB(option, esdPID);
pidSetInOptions=kTRUE;
} else if (option.BeginsWith("OCDB=")){
option.Remove(0,option.First('=')+1);
// not yet implemented
}
}
delete optArray;
//
// Initialisation of BB parameters from the OCDB.
// They are stored in the AliTPCParam
//
if (!pidSetInOptions) {
AliTPCParam* param = AliTPCcalibDB::Instance()->GetParameters();
if (param) {
TVectorD *paramBB=param->GetBetheBlochParameters();
const Float_t maxnSigmaRange = param->GetSigmaRangePIDinTracking();
if (paramBB){
esdPID->GetTPCResponse().SetBetheBlochParameters((*paramBB)(0),(*paramBB)(1),(*paramBB)(2),(*paramBB)(3),(*paramBB)(4));
AliInfo(Form("Setting BB parameters from OCDB (AliTPCParam): %.2g, %.2g, %.2g, %.2g, %.2g",
(*paramBB)(0),(*paramBB)(1),(*paramBB)(2),(*paramBB)(3),(*paramBB)(4)));
AliInfoF("Setting max sigma PID range to %.2f", maxnSigmaRange);
esdPID->SetProbabilityRangeNsigma(maxnSigmaRange);
} else {
AliError("Couldn't get BB parameters from OCDB, the old default values will be used instead");
}
} else {
AliError("Couldn't get TPC parameters");
}
}
/*
AliTPCcalibDB * calib = AliTPCcalibDB::Instance();
//Get pid splines array
TObjArray *arrSplines=calib->GetPidResponse();
if (!arrSplines) return;
AliTPCPIDResponse &tpcPID=esdPID->GetTPCResponse();
tpcPID.SetUseDatabase(kTRUE);
// check if parametrisations are already set.
// since this is uniq for one run, we don't have to reload them
if (tpcPID.GetResponseFunction(AliPID::kPion)) return;
// get the default object
TObject *defaultPID=arrSplines->At(AliPID::kUnknown);
// loop over all particle species and set the response functions
for (Int_t ispec=0; ispec<AliPID::kUnknown; ++ispec){
TObject *pidSpline=arrSplines->At(ispec);
if (!pidSpline) pidSpline=defaultPID;
tpcPID.SetResponseFunction((AliPID::EParticleType)ispec,pidSpline);
}
*/
}
//_____________________________________________________________________________
void AliTPCReconstructor::ParseOptions( AliTPCtracker* tracker ) const
{
// parse options from rec.C and set in clusterer and tracker
TString option = GetOption();
Int_t useHLTClusters = 3;
if (option.Contains("use")) {
AliInfo(Form("Overide TPC RecoParam with option %s",option.Data()));
if (option.Contains("useRAW")) {
useHLTClusters = 1;
if (option.Contains("useRAWorHLT"))
useHLTClusters = 2;
}
else if (option.Contains("useHLT")) {
useHLTClusters = 3;
if (option.Contains("useHLTorRAW"))
useHLTClusters = 4;
}
}
else {
const AliTPCRecoParam* param = GetRecoParam();
useHLTClusters = param->GetUseHLTClusters();
}
AliInfo(Form("Usage of HLT clusters in TPC reconstruction : %d", useHLTClusters));
fClusterer->SetUseHLTClusters(useHLTClusters);
tracker->SetUseHLTClusters(useHLTClusters);
return;
}
//_____________________________________________________________________________
void AliTPCReconstructor::SetSystematicErrorCluster( TVectorD *vec )
{
// set clusters syst.errors which will override persistent data member from AliTPCRecoParam::fSystematicErrors
fSystematicErrorClusters=vec;
AliTPCRecoParam::SetSystematicErrorClusterCustom(vec);
}
//_____________________________________________________________________________
void AliTPCReconstructor::SetPrimaryDCACut( TVectorD *dcacut )
{
// set clusters syst.errors which will override persistent data member from AliTPCRecoParam::fSystematicErrors
fgPrimaryDCACut=dcacut;
AliTPCRecoParam::SetPrimaryDCACut(dcacut);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <fstream>
#include <ctype.h>
#include <metaObject.h>
#include <metaUtils.h>
int testMetaObject(int , char *[])
{
MetaObject tObj;
tObj.InitializeEssential(3);
tObj.FileName("testObject.txt");
tObj.Comment("TestObject");
tObj.ObjectTypeName("Object");
tObj.ObjectSubTypeName("MinorObject");
tObj.Position(0, 1);
tObj.Position(1, 2);
tObj.Position(2, 3);
float orient[9];
int i;
for(i=0; i<9; i++)
{
orient[i] = 0;
}
orient[0] = 1;
orient[5] = 1;
orient[7] = 1;
tObj.Orientation(orient);
tObj.ElementSpacing(0, 1);
tObj.ElementSpacing(1, 2);
tObj.ElementSpacing(2, 1);
// Add user's defined fields
int myarray[3];
myarray[0]=1;
myarray[1]=2;
myarray[2]=3;
tObj.AddUserField("MyName", MET_STRING, strlen("Julien"), "Julien");
tObj.AddUserField("MyArray", MET_INT_ARRAY,3,myarray);
float myMatrix[4];
for(i=0; i<4; i++)
{
myMatrix[i] = i;
}
tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2,myMatrix);
tObj.PrintInfo();
tObj.Write();
tObj.Clear();
tObj.ClearUserFields();
tObj.AddUserField("MyName", MET_STRING);
tObj.AddUserField("MyArray", MET_INT_ARRAY,3);
tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2);
std::cout << "Test Reading: ";
tObj.Read();
std::cout << "[PASSED]" << std::endl;
tObj.PrintInfo();
char* name = static_cast<char*>(tObj.GetUserField("MyName"));
if(strcmp(name,"Julien"))
{
std::cout << "MyName: FAIL" << std::endl;
return 1;
}
delete [] name;
int* array = static_cast<int*>(tObj.GetUserField("MyArray"));
for(i=0;i<3;i++)
{
if(array[i] != i+1)
{
std::cout << "MyArray: FAIL" << std::endl;
return 1;
}
}
delete [] array;
float* matrix = static_cast<float*>(tObj.GetUserField("MyMatrix"));
for(i=0; i<4; i++)
{
if(matrix[i] != i)
{
std::cout << "MyMatrix: FAIL" << std::endl;
return 1;
}
}
delete [] matrix;
std::cout << "PASSED!" << std::endl;
tObj.Clear();
tObj.ClearUserFields();
tObj.FileName("testObject2.txt");
tObj.InitializeEssential(2);
tObj.Position(0, 4);
tObj.ElementSpacing(0,2);
tObj.PrintInfo();
tObj.Write();
tObj.Clear();
tObj.Read();
tObj.PrintInfo();
if(tObj.NDims() != 2)
{
std::cout << "NDims: FAIL" << std::endl;
return 1;
}
else
{
std::cout << "NDims: PASS" << std::endl;
}
int zero = 0;
if(tObj.Position(zero) != 4)
{
std::cout << "Position: FAIL :" << tObj.Position(zero) << std::endl;
return 1;
}
else
{
std::cout << "Position: PASS" << std::endl;
}
if(tObj.ElementSpacing(zero) != 2)
{
std::cout << "ElementSpacing: FAIL: " << tObj.ElementSpacing(zero) << std::endl;
return 1;
}
else
{
std::cout << "ElementSpacing: PASS" << std::endl;
}
// testing metaUtils
char* inDataChar = new char[1];
inDataChar[0]=1;
char* outDataChar = new char[1];
if(!MET_ValueToValue(MET_CHAR_ARRAY,inDataChar,0,MET_CHAR_ARRAY,outDataChar))
{
std::cout << "MET_ValueToValue: FAIL" << std::endl;
return 1;
}
else
{
std::cout << "outDataChar = " << outDataChar[0] << std::endl;
}
delete [] inDataChar;
delete [] outDataChar;
unsigned char* inDataUChar = new unsigned char[1];
inDataUChar[0]=1;
unsigned char* outDataUChar = new unsigned char[1];
if(!MET_ValueToValue(MET_UCHAR_ARRAY,inDataUChar,0,MET_UCHAR_ARRAY,outDataUChar))
{
std::cout << "MET_ValueToValue: FAIL" << std::endl;
return 1;
}
else
{
std::cout << "outDataUChar = " << outDataUChar[0] << std::endl;
}
delete [] inDataUChar;
delete [] outDataUChar;
std::cout << "[DONE]" << std::endl;
return 0;
}
<commit_msg>ERR: bad char in output.<commit_after>#include <stdio.h>
#include <fstream>
#include <ctype.h>
#include <metaObject.h>
#include <metaUtils.h>
#include "itkNumericTraits.h"
int testMetaObject(int , char *[])
{
MetaObject tObj;
tObj.InitializeEssential(3);
tObj.FileName("testObject.txt");
tObj.Comment("TestObject");
tObj.ObjectTypeName("Object");
tObj.ObjectSubTypeName("MinorObject");
tObj.Position(0, 1);
tObj.Position(1, 2);
tObj.Position(2, 3);
float orient[9];
int i;
for(i=0; i<9; i++)
{
orient[i] = 0;
}
orient[0] = 1;
orient[5] = 1;
orient[7] = 1;
tObj.Orientation(orient);
tObj.ElementSpacing(0, 1);
tObj.ElementSpacing(1, 2);
tObj.ElementSpacing(2, 1);
// Add user's defined fields
int myarray[3];
myarray[0]=1;
myarray[1]=2;
myarray[2]=3;
tObj.AddUserField("MyName", MET_STRING, strlen("Julien"), "Julien");
tObj.AddUserField("MyArray", MET_INT_ARRAY,3,myarray);
float myMatrix[4];
for(i=0; i<4; i++)
{
myMatrix[i] = i;
}
tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2,myMatrix);
tObj.PrintInfo();
tObj.Write();
tObj.Clear();
tObj.ClearUserFields();
tObj.AddUserField("MyName", MET_STRING);
tObj.AddUserField("MyArray", MET_INT_ARRAY,3);
tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2);
std::cout << "Test Reading: ";
tObj.Read();
std::cout << "[PASSED]" << std::endl;
tObj.PrintInfo();
char* name = static_cast<char*>(tObj.GetUserField("MyName"));
if(strcmp(name,"Julien"))
{
std::cout << "MyName: FAIL" << std::endl;
return 1;
}
delete [] name;
int* array = static_cast<int*>(tObj.GetUserField("MyArray"));
for(i=0;i<3;i++)
{
if(array[i] != i+1)
{
std::cout << "MyArray: FAIL" << std::endl;
return 1;
}
}
delete [] array;
float* matrix = static_cast<float*>(tObj.GetUserField("MyMatrix"));
for(i=0; i<4; i++)
{
if(matrix[i] != i)
{
std::cout << "MyMatrix: FAIL" << std::endl;
return 1;
}
}
delete [] matrix;
std::cout << "PASSED!" << std::endl;
tObj.Clear();
tObj.ClearUserFields();
tObj.FileName("testObject2.txt");
tObj.InitializeEssential(2);
tObj.Position(0, 4);
tObj.ElementSpacing(0,2);
tObj.PrintInfo();
tObj.Write();
tObj.Clear();
tObj.Read();
tObj.PrintInfo();
if(tObj.NDims() != 2)
{
std::cout << "NDims: FAIL" << std::endl;
return 1;
}
else
{
std::cout << "NDims: PASS" << std::endl;
}
int zero = 0;
if(tObj.Position(zero) != 4)
{
std::cout << "Position: FAIL :" << tObj.Position(zero) << std::endl;
return 1;
}
else
{
std::cout << "Position: PASS" << std::endl;
}
if(tObj.ElementSpacing(zero) != 2)
{
std::cout << "ElementSpacing: FAIL: " << tObj.ElementSpacing(zero) << std::endl;
return 1;
}
else
{
std::cout << "ElementSpacing: PASS" << std::endl;
}
// testing metaUtils
char* inDataChar = new char[1];
inDataChar[0]=1;
char* outDataChar = new char[1];
if(!MET_ValueToValue(MET_CHAR_ARRAY,inDataChar,0,MET_CHAR_ARRAY,outDataChar))
{
std::cout << "MET_ValueToValue: FAIL" << std::endl;
return 1;
}
else
{
std::cout << "outDataChar = " << static_cast<itk::NumericTraits<char>::PrintType>(outDataChar[0]) << std::endl;
}
delete [] inDataChar;
delete [] outDataChar;
unsigned char* inDataUChar = new unsigned char[1];
inDataUChar[0]=1;
unsigned char* outDataUChar = new unsigned char[1];
if(!MET_ValueToValue(MET_UCHAR_ARRAY,inDataUChar,0,MET_UCHAR_ARRAY,outDataUChar))
{
std::cout << "MET_ValueToValue: FAIL" << std::endl;
return 1;
}
else
{
std::cout << "outDataUChar = " << static_cast<itk::NumericTraits<char>::PrintType>(outDataUChar[0]) << std::endl;
}
delete [] inDataUChar;
delete [] outDataUChar;
std::cout << "[DONE]" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdexcept>
#include <QMutexLocker>
#include <Utils.hpp>
#include "USBRadio.hpp"
#include "Geometry2d/Util.hpp"
// Include this file for base station usb vendor/product ids
#include "firmware-common/base2015/usb-interface.hpp"
// included for kicer status enum
#include "firmware-common/robot2015/cpu/status.h"
using namespace std;
using namespace Packet;
// Timeout for control transfers, in milliseconds
static const int Control_Timeout = 1000;
USBRadio::USBRadio() : _mutex(QMutex::Recursive) {
_printedError = false;
_device = nullptr;
_usb_context = nullptr;
libusb_init(&_usb_context);
for (int i = 0; i < NumRXTransfers; ++i) {
_rxTransfers[i] = libusb_alloc_transfer(0);
}
}
USBRadio::~USBRadio() {
if (_device) {
libusb_close(_device);
}
for (int i = 0; i < NumRXTransfers; ++i) {
libusb_free_transfer(_rxTransfers[i]);
}
libusb_exit(_usb_context);
}
bool USBRadio::open() {
libusb_device** devices = nullptr;
ssize_t numDevices = libusb_get_device_list(_usb_context, &devices);
if (numDevices < 0) {
fprintf(stderr, "libusb_get_device_list failed\n");
return false;
}
int numRadios = 0;
for (int i = 0; i < numDevices; ++i) {
struct libusb_device_descriptor desc;
int err = libusb_get_device_descriptor(devices[i], &desc);
if (err == 0 && desc.idVendor == RJ_BASE2015_VENDOR_ID &&
desc.idProduct == RJ_BASE2015_PRODUCT_ID) {
++numRadios;
int err = libusb_open(devices[i], &_device);
if (err == 0) {
break;
}
}
}
libusb_free_device_list(devices, 1);
if (!numRadios) {
if (!_printedError) {
fprintf(stderr, "USBRadio: No radio is connected\n");
_printedError = true;
}
return false;
}
if (!_device) {
if (!_printedError) {
fprintf(stderr, "USBRadio: All radios are in use\n");
_printedError = true;
}
return false;
}
if (libusb_set_configuration(_device, 1)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't set configuration\n");
_printedError = true;
}
return false;
}
if (libusb_claim_interface(_device, 0)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't claim interface\n");
_printedError = true;
}
return false;
}
channel(_channel);
// Start the receive transfers
for (int i = 0; i < NumRXTransfers; ++i) {
// Populate the required libusb_transfer fields for a bulk transfer.
libusb_fill_bulk_transfer(
_rxTransfers[i], // the transfer to populate
_device, // handle of the device that will handle the transfer
LIBUSB_ENDPOINT_IN |
2, // address of the endpoint where this transfer will be sent
_rxBuffers[i], // data buffer
rtp::ReverseSize, // length of data buffer
rxCompleted, // callback function to be invoked on transfer
// completion
this, // user data to pass to callback function
0); // timeout for the transfer in milliseconds
libusb_submit_transfer(_rxTransfers[i]);
}
_printedError = false;
return true;
}
void USBRadio::rxCompleted(libusb_transfer* transfer) {
USBRadio* radio = (USBRadio*)transfer->user_data;
if (transfer->status == LIBUSB_TRANSFER_COMPLETED &&
transfer->actual_length == rtp::ReverseSize) {
// Parse the packet and add to the list of RadioRx's
radio->handleRxData(transfer->buffer);
}
// Restart the transfer
libusb_submit_transfer(transfer);
}
void USBRadio::command(uint8_t cmd) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioStrobe, 0, cmd,
nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::command control write failed");
}
}
void USBRadio::write(uint8_t reg, uint8_t value) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioWriteRegister,
value, reg, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::write control write failed");
}
}
uint8_t USBRadio::read(uint8_t reg) {
uint8_t value = 0;
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioReadRegister, 0,
reg, &value, 1, Control_Timeout)) {
throw runtime_error("USBRadio::read control write failed");
}
return value;
}
bool USBRadio::isOpen() const { return _device; }
void USBRadio::send(Packet::RadioTx& packet) {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
uint8_t forward_packet[rtp::ForwardSize];
// ensure Forward_Size is correct
static_assert(sizeof(rtp::Header) + 6 * sizeof(rtp::RobotTxMessage) ==
rtp::ForwardSize,
"Forward packet contents exceeds buffer size");
// Unit conversions
static const float Seconds_Per_Cycle = 0.005f;
static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f;
static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f);
rtp::Header* header = (rtp::Header*)forward_packet;
header->port = rtp::PortType::CONTROL;
header->address = rtp::BROADCAST_ADDRESS;
header->type = rtp::MessageType::CONTROL;
// Build a forward packet
for (int slot = 0; slot < 6; ++slot) {
// Calculate the offset into the @forward_packet for this robot's
// control message and cast it to a ControlMessage pointer for easy
// access
size_t offset =
sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
rtp::RobotTxMessage* msg =
(rtp::RobotTxMessage*)(forward_packet + offset);
if (slot < packet.robots_size()) {
const Packet::Control& robot = packet.robots(slot).control();
msg->uid = packet.robots(slot).uid();
msg->messageType = rtp::RobotTxMessage::ControlMessageType;
auto &controlMessage = msg->message.controlMessage;
controlMessage.bodyX = static_cast<int16_t >(robot.xvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyY = static_cast<int16_t >(robot.yvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyW = static_cast<int16_t >(robot.avelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.dribbler = clamp(static_cast<uint16_t>(robot.dvelocity()) * 2, 0, 255);
controlMessage.kickStrength = robot.kcstrength();
controlMessage.shootMode = robot.shootmode();
controlMessage.triggerMode = robot.triggermode();
controlMessage.song = robot.song();
} else {
// empty slot
msg->uid = rtp::INVALID_ROBOT_UID;
}
}
// int numRobotTXMessages = packet.robots_size();
//
// for (int configStartIndex=0; configStartIndex<packet.configs_size(); configStartIndex+=rtp::ConfMessage::length) {
// if (numRobotTXMessages<6) {
// auto slot = numRobotTXMessages;
// size_t offset =
// sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
// rtp::RobotTxMessage* msg =
// (rtp::RobotTxMessage*)(forward_packet + offset);
//
// msg->uid = rtp::ANY_ROBOT_UID;
// msg->messageType = rtp::RobotTxMessage::ConfMessageType;
//
// auto &confMessage = msg->message.confMessage;
//
//
// auto numToCopy = std::min(static_cast<int>(rtp::ConfMessage::length), packet.configs_size()-configStartIndex);
// for (int i=0; i<numToCopy; i++) {
// const auto &config = packet.configs(i+configStartIndex);
// auto key = static_cast<DebugCommunication::ConfigCommunication>(config.key());
// confMessage.keys[i] = key;
// confMessage.values[i] = DebugCommunication::configToValue(key, config.value());
// }
// numRobotTXMessages++;
// }
// }
// {
// std::lock_guard<std::mutex> lock(current_receive_debug_mutex);
// current_receive_debug.clear();
// for (auto debugMessages : packet.debug_communication()) {
// current_receive_debug.push_back(static_cast<DebugCommunication::DebugResponse>(debugMessages.key()));
// }
// }
// if (numRobotTXMessages<6) {
// auto slot = numRobotTXMessages;
// size_t offset =
// sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
// rtp::RobotTxMessage* msg =
// (rtp::RobotTxMessage*)(forward_packet + offset);
//
// msg->uid = rtp::ANY_ROBOT_UID;
// msg->messageType = rtp::RobotTxMessage::DebugMessageType;
//
// auto &debugMessage = msg->message.debugMessage;
// std::copy_n(current_receive_debug.begin(), std::min(current_receive_debug.size(), debugMessage.keys.size()), debugMessage.keys.begin());
//
// numRobotTXMessages++;
// }
// Send the forward packet
int sent = 0;
int transferRetCode =
libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 2, forward_packet,
sizeof(forward_packet), &sent, Control_Timeout);
if (transferRetCode != LIBUSB_SUCCESS || sent != sizeof(forward_packet)) {
fprintf(stderr, "USBRadio: Bulk write failed. sent = %d, size = %lu\n",
sent, (unsigned long int)sizeof(forward_packet));
if (transferRetCode != LIBUSB_SUCCESS)
fprintf(stderr, " Error: '%s'\n",
libusb_error_name(transferRetCode));
int ret = libusb_clear_halt(_device, LIBUSB_ENDPOINT_OUT | 2);
if (ret != 0) {
printf("tried to clear halt, error = %s\n. closing device\n",
libusb_error_name(ret));
libusb_close(_device);
_device = nullptr;
}
}
}
void USBRadio::receive() {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
// Handle USB events. This will call callbacks.
struct timeval tv = {0, 0};
libusb_handle_events_timeout(_usb_context, &tv);
}
// Note: this method assumes that sizeof(buf) == rtp::ReverseSize
void USBRadio::handleRxData(uint8_t* buf) {
RadioRx packet = RadioRx();
rtp::Header* header = (rtp::Header*)buf;
rtp::RobotStatusMessage* msg =
(rtp::RobotStatusMessage*)(buf + sizeof(rtp::Header));
packet.set_timestamp(RJ::timestamp());
packet.set_robot_id(msg->uid);
// Hardware version
packet.set_hardware_version(RJ2015);
// battery voltage
packet.set_battery(msg->battVoltage *
rtp::RobotStatusMessage::BATTERY_SCALE_FACTOR);
// ball sense
if (BallSenseStatus_IsValid(msg->ballSenseStatus)) {
packet.set_ball_sense_status(BallSenseStatus(msg->ballSenseStatus));
}
// Using same flags as 2011 robot. See firmware/robot2011/cpu/status.h.
// Report that everything is good b/c the bot currently has no way of
// detecting kicker issues
packet.set_kicker_status((msg->kickStatus ? Kicker_Charged : 0) |
(msg->kickHealthy ? Kicker_Enabled : 0) | Kicker_I2C_OK);
// motor errors
for (int i = 0; i < 5; i++) {
bool err = msg->motorErrors & (1 << i);
packet.add_motor_status(err ? MotorStatus::Hall_Failure
: MotorStatus::Good);
}
// fpga status
if (FpgaStatus_IsValid(msg->fpgaStatus)) {
packet.set_fpga_status(FpgaStatus(msg->fpgaStatus));
}
{
std::lock_guard<std::mutex> lock(current_receive_debug_mutex);
for (int index = 0; index < current_receive_debug.size(); ++index) {
auto debugResponse = current_receive_debug[index];
const auto &name = DebugCommunication::DEBUGRESPONSE_TO_STRING.at(debugResponse);
// auto value = msg->debug_data[index];
//
// auto packet_debug_response = packet.add_debug_responses();
// packet_debug_response->set_key(name);
// packet_debug_response->set_value(DebugCommunication::debugResponseValueToFloat(debugResponse, value));
}
}
_reversePackets.push_back(packet);
}
void USBRadio::channel(int n) {
QMutexLocker lock(&_mutex);
if (_device) {
if (libusb_control_transfer(
_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioSetChannel, n, 0, nullptr, 0,
Control_Timeout)) {
throw runtime_error("USBRadio::channel control write failed");
}
}
Radio::channel(n);
}
<commit_msg>"Fix" radio issues<commit_after>#include <stdio.h>
#include <stdexcept>
#include <QMutexLocker>
#include <Utils.hpp>
#include "USBRadio.hpp"
#include "Geometry2d/Util.hpp"
// Include this file for base station usb vendor/product ids
#include "firmware-common/base2015/usb-interface.hpp"
// included for kicer status enum
#include "firmware-common/robot2015/cpu/status.h"
using namespace std;
using namespace Packet;
// Timeout for control transfers, in milliseconds
static const int Control_Timeout = 1000;
USBRadio::USBRadio() : _mutex(QMutex::Recursive) {
_printedError = false;
_device = nullptr;
_usb_context = nullptr;
libusb_init(&_usb_context);
for (int i = 0; i < NumRXTransfers; ++i) {
_rxTransfers[i] = libusb_alloc_transfer(0);
}
}
USBRadio::~USBRadio() {
if (_device) {
libusb_close(_device);
}
for (int i = 0; i < NumRXTransfers; ++i) {
libusb_free_transfer(_rxTransfers[i]);
}
libusb_exit(_usb_context);
}
bool USBRadio::open() {
libusb_device** devices = nullptr;
ssize_t numDevices = libusb_get_device_list(_usb_context, &devices);
if (numDevices < 0) {
fprintf(stderr, "libusb_get_device_list failed\n");
return false;
}
int numRadios = 0;
for (int i = 0; i < numDevices; ++i) {
struct libusb_device_descriptor desc;
int err = libusb_get_device_descriptor(devices[i], &desc);
if (err == 0 && desc.idVendor == RJ_BASE2015_VENDOR_ID &&
desc.idProduct == RJ_BASE2015_PRODUCT_ID) {
++numRadios;
int err = libusb_open(devices[i], &_device);
if (err == 0) {
break;
}
}
}
libusb_free_device_list(devices, 1);
if (!numRadios) {
if (!_printedError) {
fprintf(stderr, "USBRadio: No radio is connected\n");
_printedError = true;
}
return false;
}
if (!_device) {
if (!_printedError) {
fprintf(stderr, "USBRadio: All radios are in use\n");
_printedError = true;
}
return false;
}
if (libusb_set_configuration(_device, 1)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't set configuration\n");
_printedError = true;
}
return false;
}
if (libusb_claim_interface(_device, 0)) {
if (!_printedError) {
fprintf(stderr, "USBRadio: Can't claim interface\n");
_printedError = true;
}
return false;
}
channel(_channel);
// Start the receive transfers
for (int i = 0; i < NumRXTransfers; ++i) {
// Populate the required libusb_transfer fields for a bulk transfer.
libusb_fill_bulk_transfer(
_rxTransfers[i], // the transfer to populate
_device, // handle of the device that will handle the transfer
LIBUSB_ENDPOINT_IN |
2, // address of the endpoint where this transfer will be sent
_rxBuffers[i], // data buffer
rtp::ReverseSize, // length of data buffer
rxCompleted, // callback function to be invoked on transfer
// completion
this, // user data to pass to callback function
0); // timeout for the transfer in milliseconds
libusb_submit_transfer(_rxTransfers[i]);
}
_printedError = false;
return true;
}
void USBRadio::rxCompleted(libusb_transfer* transfer) {
USBRadio* radio = (USBRadio*)transfer->user_data;
if (transfer->status == LIBUSB_TRANSFER_COMPLETED &&
transfer->actual_length == rtp::ReverseSize) {
// Parse the packet and add to the list of RadioRx's
radio->handleRxData(transfer->buffer);
}
// Restart the transfer
libusb_submit_transfer(transfer);
}
void USBRadio::command(uint8_t cmd) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioStrobe, 0, cmd,
nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::command control write failed");
}
}
void USBRadio::write(uint8_t reg, uint8_t value) {
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioWriteRegister,
value, reg, nullptr, 0, Control_Timeout)) {
throw runtime_error("USBRadio::write control write failed");
}
}
uint8_t USBRadio::read(uint8_t reg) {
uint8_t value = 0;
if (libusb_control_transfer(_device,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioReadRegister, 0,
reg, &value, 1, Control_Timeout)) {
throw runtime_error("USBRadio::read control write failed");
}
return value;
}
bool USBRadio::isOpen() const { return _device; }
void USBRadio::send(Packet::RadioTx& packet) {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
uint8_t forward_packet[rtp::ForwardSize];
// ensure Forward_Size is correct
static_assert(sizeof(rtp::Header) + 6 * sizeof(rtp::RobotTxMessage) ==
rtp::ForwardSize,
"Forward packet contents exceeds buffer size");
// Unit conversions
static const float Seconds_Per_Cycle = 0.005f;
static const float Meters_Per_Tick = 0.026f * 2 * M_PI / 6480.0f;
static const float Radians_Per_Tick = 0.026f * M_PI / (0.0812f * 3240.0f);
rtp::Header* header = (rtp::Header*)forward_packet;
header->port = rtp::PortType::CONTROL;
header->address = rtp::BROADCAST_ADDRESS;
header->type = rtp::MessageType::CONTROL;
// Build a forward packet
for (int slot = 0; slot < 6; ++slot) {
// Calculate the offset into the @forward_packet for this robot's
// control message and cast it to a ControlMessage pointer for easy
// access
size_t offset =
sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
rtp::RobotTxMessage* msg =
(rtp::RobotTxMessage*)(forward_packet + offset);
if (slot < packet.robots_size()) {
const Packet::Control& robot = packet.robots(slot).control();
msg->uid = packet.robots(slot).uid();
msg->messageType = rtp::RobotTxMessage::ControlMessageType;
auto &controlMessage = msg->message.controlMessage;
controlMessage.bodyX = static_cast<int16_t >(robot.xvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyY = static_cast<int16_t >(robot.yvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.bodyW = static_cast<int16_t >(robot.avelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
controlMessage.dribbler = clamp(static_cast<uint16_t>(robot.dvelocity()) * 2, 0, 255);
controlMessage.kickStrength = robot.kcstrength();
controlMessage.shootMode = robot.shootmode();
controlMessage.triggerMode = robot.triggermode();
controlMessage.song = robot.song();
} else {
// empty slot
msg->uid = rtp::INVALID_ROBOT_UID;
}
}
// int numRobotTXMessages = packet.robots_size();
//
// for (int configStartIndex=0; configStartIndex<packet.configs_size(); configStartIndex+=rtp::ConfMessage::length) {
// if (numRobotTXMessages<6) {
// auto slot = numRobotTXMessages;
// size_t offset =
// sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
// rtp::RobotTxMessage* msg =
// (rtp::RobotTxMessage*)(forward_packet + offset);
//
// msg->uid = rtp::ANY_ROBOT_UID;
// msg->messageType = rtp::RobotTxMessage::ConfMessageType;
//
// auto &confMessage = msg->message.confMessage;
//
//
// auto numToCopy = std::min(static_cast<int>(rtp::ConfMessage::length), packet.configs_size()-configStartIndex);
// for (int i=0; i<numToCopy; i++) {
// const auto &config = packet.configs(i+configStartIndex);
// auto key = static_cast<DebugCommunication::ConfigCommunication>(config.key());
// confMessage.keys[i] = key;
// confMessage.values[i] = DebugCommunication::configToValue(key, config.value());
// }
// numRobotTXMessages++;
// }
// }
// {
// std::lock_guard<std::mutex> lock(current_receive_debug_mutex);
// current_receive_debug.clear();
// for (auto debugMessages : packet.debug_communication()) {
// current_receive_debug.push_back(static_cast<DebugCommunication::DebugResponse>(debugMessages.key()));
// }
// }
// if (numRobotTXMessages<6) {
// auto slot = numRobotTXMessages;
// size_t offset =
// sizeof(rtp::Header) + slot * sizeof(rtp::RobotTxMessage);
// rtp::RobotTxMessage* msg =
// (rtp::RobotTxMessage*)(forward_packet + offset);
//
// msg->uid = rtp::ANY_ROBOT_UID;
// msg->messageType = rtp::RobotTxMessage::DebugMessageType;
//
// auto &debugMessage = msg->message.debugMessage;
// std::copy_n(current_receive_debug.begin(), std::min(current_receive_debug.size(), debugMessage.keys.size()), debugMessage.keys.begin());
//
// numRobotTXMessages++;
// }
// Send the forward packet
int sent = 0;
// TODO FIXME remove this hack, which increases the size of data packets by 2.
// See +2 on sizeof's below.
int transferRetCode =
libusb_bulk_transfer(_device, LIBUSB_ENDPOINT_OUT | 2, forward_packet,
sizeof(forward_packet) + 2, &sent, Control_Timeout);
if (transferRetCode != LIBUSB_SUCCESS || sent != sizeof(forward_packet) + 2) {
fprintf(stderr, "USBRadio: Bulk write failed. sent = %d, size = %lu\n",
sent, (unsigned long int)sizeof(forward_packet));
if (transferRetCode != LIBUSB_SUCCESS)
fprintf(stderr, " Error: '%s'\n",
libusb_error_name(transferRetCode));
int ret = libusb_clear_halt(_device, LIBUSB_ENDPOINT_OUT | 2);
if (ret != 0) {
printf("tried to clear halt, error = %s\n. closing device\n",
libusb_error_name(ret));
libusb_close(_device);
_device = nullptr;
}
}
}
void USBRadio::receive() {
QMutexLocker lock(&_mutex);
if (!_device) {
if (!open()) {
return;
}
}
// Handle USB events. This will call callbacks.
struct timeval tv = {0, 0};
libusb_handle_events_timeout(_usb_context, &tv);
}
// Note: this method assumes that sizeof(buf) == rtp::ReverseSize
void USBRadio::handleRxData(uint8_t* buf) {
RadioRx packet = RadioRx();
rtp::Header* header = (rtp::Header*)buf;
rtp::RobotStatusMessage* msg =
(rtp::RobotStatusMessage*)(buf + sizeof(rtp::Header));
packet.set_timestamp(RJ::timestamp());
packet.set_robot_id(msg->uid);
// Hardware version
packet.set_hardware_version(RJ2015);
// battery voltage
packet.set_battery(msg->battVoltage *
rtp::RobotStatusMessage::BATTERY_SCALE_FACTOR);
// ball sense
if (BallSenseStatus_IsValid(msg->ballSenseStatus)) {
packet.set_ball_sense_status(BallSenseStatus(msg->ballSenseStatus));
}
// Using same flags as 2011 robot. See firmware/robot2011/cpu/status.h.
// Report that everything is good b/c the bot currently has no way of
// detecting kicker issues
packet.set_kicker_status((msg->kickStatus ? Kicker_Charged : 0) |
(msg->kickHealthy ? Kicker_Enabled : 0) | Kicker_I2C_OK);
// motor errors
for (int i = 0; i < 5; i++) {
bool err = msg->motorErrors & (1 << i);
packet.add_motor_status(err ? MotorStatus::Hall_Failure
: MotorStatus::Good);
}
// fpga status
if (FpgaStatus_IsValid(msg->fpgaStatus)) {
packet.set_fpga_status(FpgaStatus(msg->fpgaStatus));
}
{
std::lock_guard<std::mutex> lock(current_receive_debug_mutex);
for (int index = 0; index < current_receive_debug.size(); ++index) {
auto debugResponse = current_receive_debug[index];
const auto &name = DebugCommunication::DEBUGRESPONSE_TO_STRING.at(debugResponse);
// auto value = msg->debug_data[index];
//
// auto packet_debug_response = packet.add_debug_responses();
// packet_debug_response->set_key(name);
// packet_debug_response->set_value(DebugCommunication::debugResponseValueToFloat(debugResponse, value));
}
}
_reversePackets.push_back(packet);
}
void USBRadio::channel(int n) {
QMutexLocker lock(&_mutex);
if (_device) {
if (libusb_control_transfer(
_device, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
Base2015ControlCommand::RadioSetChannel, n, 0, nullptr, 0,
Control_Timeout)) {
throw runtime_error("USBRadio::channel control write failed");
}
}
Radio::channel(n);
}
<|endoftext|>
|
<commit_before>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
#pragma comment( lib, "libglog_static_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libglog_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#pragma comment( lib, "libglog_static.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libglog.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<commit_msg>Modify complile error of NFLogPlugin<commit_after>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
//#pragma comment( lib, "libglog_static_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libglog_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#pragma comment( lib, "libglog_static.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libglog.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<|endoftext|>
|
<commit_before>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
#pragma comment( lib, "libglog_static_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libglog_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#pragma comment( lib, "libglog_static.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libglog.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<commit_msg>Modify complile error of NFLogPlugin<commit_after>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
//#pragma comment( lib, "libglog_static_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libglog_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#pragma comment( lib, "libglog_static.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libglog.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/memory/memory.h"
#include "paddle/memory/detail/buddy_allocator.h"
#include "paddle/memory/detail/system_allocator.h"
#include <cstring> // for memcpy
namespace paddle {
namespace memory {
detail::BuddyAllocator* GetCPUBuddyAllocator() {
static detail::BuddyAllocator* a = nullptr;
if (a == nullptr) {
a = new detail::BuddyAllocator(new detail::CPUAllocator,
platform::CpuMinChunkSize(),
platform::CpuMaxChunkSize());
}
return a;
}
template <>
void* Alloc<platform::CPUPlace>(platform::CPUPlace place, size_t size) {
return GetCPUBuddyAllocator()->Alloc(size);
}
template <>
void Free<platform::CPUPlace>(platform::CPUPlace place, void* p) {
GetCPUBuddyAllocator()->Free(p);
}
template <>
size_t Used<platform::CPUPlace>(platform::CPUPlace place) {
return GetCPUBuddyAllocator()->Used();
}
#ifndef PADDLE_ONLY_CPU
detail::BuddyAllocator* GetGPUBuddyAllocator(int gpu_id) {
static detail::BuddyAllocator** as = NULL;
if (as == NULL) {
int gpu_num = platform::GetDeviceCount();
as = new detail::BuddyAllocator*[gpu_num];
for (int gpu = 0; gpu < gpu_num; gpu++) {
platform::SetDeviceId(gpu);
as[gpu] = new detail::BuddyAllocator(new detail::GPUAllocator,
platform::GpuMinChunkSize(),
platform::GpuMaxChunkSize());
}
}
platform::SetDeviceId(gpu_id);
return as[gpu_id];
}
template <>
void* Alloc<platform::GPUPlace>(platform::GPUPlace place, size_t size) {
return GetGPUBuddyAllocator(place.device)->Alloc(size);
}
template <>
void Free<platform::GPUPlace>(platform::GPUPlace place, void* p) {
GetGPUBuddyAllocator(place.device)->Free(p);
}
template <>
size_t Used<platform::GPUPlace>(platform::GPUPlace place) {
return GetGPUBuddyAllocator(place.device)->Used();
}
#endif // PADDLE_ONLY_CPU
} // namespace memory
} // namespace paddle
<commit_msg>FIX: Release CPU/GPU memory via deleter<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/memory/memory.h"
#include "paddle/memory/detail/buddy_allocator.h"
#include "paddle/memory/detail/system_allocator.h"
#include <algorithm> // for transfrom
#include <cstring> // for memcpy
#include <mutex> // for call_once
#include "glog/logging.h"
namespace paddle {
namespace memory {
using BuddyAllocator = detail::BuddyAllocator;
std::once_flag cpu_alloctor_flag;
std::once_flag gpu_alloctor_flag;
BuddyAllocator* GetCPUBuddyAllocator() {
static std::unique_ptr<BuddyAllocator, void (*)(BuddyAllocator*)> a{
nullptr, [](BuddyAllocator* p) { delete p; }};
std::call_once(cpu_alloctor_flag, [&]() {
a.reset(new BuddyAllocator(new detail::CPUAllocator,
platform::CpuMinChunkSize(),
platform::CpuMaxChunkSize()));
});
return a.get();
}
template <>
void* Alloc<platform::CPUPlace>(platform::CPUPlace place, size_t size) {
return GetCPUBuddyAllocator()->Alloc(size);
}
template <>
void Free<platform::CPUPlace>(platform::CPUPlace place, void* p) {
GetCPUBuddyAllocator()->Free(p);
}
template <>
size_t Used<platform::CPUPlace>(platform::CPUPlace place) {
return GetCPUBuddyAllocator()->Used();
}
#ifndef PADDLE_ONLY_CPU
BuddyAllocator* GetGPUBuddyAllocator(int gpu_id) {
using BuddyAllocVec = std::vector<BuddyAllocator*>;
static std::unique_ptr<BuddyAllocVec, void (*)(BuddyAllocVec * p)> as{
new std::vector<BuddyAllocator*>, [](BuddyAllocVec* p) {
std::for_each(p->begin(), p->end(),
[](BuddyAllocator* p) { delete p; });
}};
// GPU buddy alloctors
auto& alloctors = *as.get();
// GPU buddy allocator initialization
std::call_once(gpu_alloctor_flag, [&]() {
int gpu_num = platform::GetDeviceCount();
alloctors.reserve(gpu_num);
for (int gpu = 0; gpu < gpu_num; gpu++) {
platform::SetDeviceId(gpu);
alloctors.emplace_back(new BuddyAllocator(new detail::GPUAllocator,
platform::GpuMinChunkSize(),
platform::GpuMaxChunkSize()));
}
});
platform::SetDeviceId(gpu_id);
return alloctors[gpu_id];
}
template <>
void* Alloc<platform::GPUPlace>(platform::GPUPlace place, size_t size) {
return GetGPUBuddyAllocator(place.device)->Alloc(size);
}
template <>
void Free<platform::GPUPlace>(platform::GPUPlace place, void* p) {
GetGPUBuddyAllocator(place.device)->Free(p);
}
template <>
size_t Used<platform::GPUPlace>(platform::GPUPlace place) {
return GetGPUBuddyAllocator(place.device)->Used();
}
#endif // PADDLE_ONLY_CPU
} // namespace memory
} // namespace paddle
<|endoftext|>
|
<commit_before><commit_msg>Use better web app icons.<commit_after><|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "AutoFilterTest.h"
#include "AutoPacket.h"
#include "AutoPacketFactory.h"
#include "TestFixtures/Decoration.h"
TEST_F(AutoFilterTest, VerifyDescendentAwareness) {
AutoCurrentContext()->Initiate();
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> parentFactory;
auto packet1 = parentFactory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
std::shared_ptr<AutoPacket> packet2;
std::weak_ptr<AutoPacket> packet3;
std::weak_ptr<FilterA> filterChecker;
// Create a subcontext
{
AutoCreateContext subContext;
{
CurrentContextPusher pusher(subContext);
//add a filter in the subcontext
AutoRequired<FilterA> subFilter;
filterChecker = subFilter;
}
//Create a packet where a subscriber exists only in a subcontext
packet2 = parentFactory->NewPacket();
auto strongPacket3 = parentFactory->NewPacket();
packet3 = strongPacket3;
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
EXPECT_TRUE(packet3.lock()->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
}
EXPECT_TRUE(packet3.expired()) << "Packet was not destroyed when it's subscribers were removed";
EXPECT_FALSE(filterChecker.expired()) << "Packet keeping subcontext member alive";
// Create a packet after the subcontext has been destroyed
auto packet4 = parentFactory->NewPacket();
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
packet2->Decorate(Decoration<0>());
// Verify the second one will no longe have subscriptions -
// normally removing a subscriber would mean the packet still has the subscriber, but
// in this case, the subscriber was actually destroyed so the packet has lost a subscriber.
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
// Verify the third one does not:
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
packet2.reset();
EXPECT_TRUE(filterChecker.expired()) << "Subscriber didn't expire after packet was reset.";
}
TEST_F(AutoFilterTest, VerifySimpleFilter) {
AutoCurrentContext()->Initiate();
AutoRequired<AutoPacketFactory> factory;
AutoRequired<FilterA> filterA;
// Verify that the subscriber has been properly detected:
bool bFound = false;
for(const auto& cur : factory->GetSubscriberVector())
if(cur.GetAutoFilter() == filterA) {
bFound = true;
break;
}
ASSERT_TRUE(bFound) << "Failed to find an added subscriber ";
// Obtain a packet from the factory:
auto packet = factory->NewPacket();
// Decorate with one instance:
packet->Decorate(Decoration<0>());
// Verify that no hit takes place with inadequate decoration:
EXPECT_FALSE(filterA->m_called) << "Filter called prematurely with insufficient decoration";
// Now decorate with the other requirement of the filter:
packet->Decorate(Decoration<1>());
// A hit should have taken place at this point:
EXPECT_TRUE(filterA->m_called) << "Filter was not called even though it was fully satisfied";
}
TEST_F(AutoFilterTest, VerifyNoMultiDecorate) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet and attempt redundant introduction:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Redundant decoration did not throw an exception as expected";
// Verify that a call has not yet been made
EXPECT_FALSE(filterA->m_called) << "A call made on an idempotent packet decoration";
// Now finish saturating the filter and ensure we get a call:
packet->Decorate(Decoration<1>());
EXPECT_TRUE(filterA->m_called) << "Filter was not called after being fully satisfied";
}
TEST_F(AutoFilterTest, VerifyInterThreadDecoration) {
AutoRequired<FilterB> filterB;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext ctxt;
// Kick off all threads:
ctxt->Initiate();
// Obtain a packet for processing and decorate it:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
// Verify that the recipient has NOT yet received the message:
EXPECT_FALSE(filterB->m_called) << "A call was made to a thread which should not have been able to process it";
// Wake up the barrier and post a quit message:
filterB->m_barr.wait();
*filterB += [&filterB] { filterB->Stop(); };
filterB->Wait();
// Verify that the filter method has been called
EXPECT_TRUE(filterB->m_called) << "A deferred filter method was not called as expected";
}
TEST_F(AutoFilterTest, VerifyTeardownArrangement) {
AutoCurrentContext()->Initiate();
AutoRequired<AutoPacketFactory> factory;
std::weak_ptr<FilterA> filterAWeak;
{
std::shared_ptr<AutoPacket> packet;
{
// Create the filter and subscribe it
std::shared_ptr<FilterA> filterA(new FilterA);
filterAWeak = filterA;
factory->AddSubscriber(filterA);
// Create the packet--this should lock in references to all subscribers:
packet = factory->NewPacket();
}
// Verify that the subscription has not expired:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber while it was still registered";
{
std::shared_ptr<FilterA> filterA = filterAWeak.lock();
// Unsubscribe the filter:
factory->RemoveSubscriber(filterA);
}
// Verify that unsubscription STILL does not result in expiration:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber expired before all packets on that subscriber were satisfied";
//Create a new packet after having removed the only filter on it.
auto packet2 = factory->NewPacket();
ASSERT_FALSE(packet2->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
// Satisfy the packet:
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
auto packet3 = factory->NewPacket();
ASSERT_FALSE(packet3->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
}
// Filter should be expired now:
ASSERT_TRUE(filterAWeak.expired()) << "Subscriber was still left outstanding even though all references should be gone";
}
TEST_F(AutoFilterTest, VerifyCheckout) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
{
// Verify that an unsubscribed decoration returns a correct checkout:
auto unused = packet->Checkout<Decoration<4>>();
EXPECT_FALSE(unused) << "Checkout incorrectly generated for unsubscribed decoration";
}
// Satisfy the other decoration:
packet->Decorate(Decoration<1>());
{
AutoCheckout<Decoration<0>> exterior;
{
AutoCheckout<Decoration<0>> checkout = packet->Checkout<Decoration<0>>();
// Verify we can move the original type:
AutoCheckout<Decoration<0>> checkoutMoved(std::move(checkout));
// Verify no hits yet:
EXPECT_FALSE(filterA->m_called) << "Filter called as a consequence of a checkout move operation";
// Move the checkout a second time:
exterior = std::move(checkoutMoved);
}
// Still no hits
EXPECT_FALSE(filterA->m_called) << "Filter called before a decoration checkout expired";
// Mark ready so we get committed:
exterior.Ready();
}
// Verify a hit took place now
EXPECT_TRUE(filterA->m_called) << "Filter was not called after all decorations were installed";
}
TEST_F(AutoFilterTest, RollbackCorrectness) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<1>());
// Request and immediately allow the destruction of a checkout:
packet->Checkout<Decoration<0>>();
// Verify no hit took place--the checkout should have been cancelled:
EXPECT_FALSE(filterA->m_called) << "Filter was called even though one decoration shouldn't have been available";
// We should not be able to obtain another checkout of this decoration on this packet:
EXPECT_ANY_THROW(packet->Checkout<Decoration<0>>()) << "An attempt to check out a decoration a second time should have failed";
// We shouldn't be able to manually decorate, either:
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "An attempt to manually add a previously failed decoration succeeded where it should not have";
}
TEST_F(AutoFilterTest, VerifyAntiDecorate) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
{
// Obtain a new packet and mark an unsatisfiable decoration:
auto packet = factory->NewPacket();
packet->Unsatisfiable<Decoration<0>>();
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Decoration succeeded on a decoration marked unsatisfiable";
}
{
// Obtain a new packet and try to make a satisfied decoration unsatisfiable.
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Unsatisfiable<Decoration<0>>()) << "Succeeded in marking an already-existing decoration as unsatisfiable";
}
}
TEST_F(AutoFilterTest, VerifyReflexiveReciept) {
AutoRequired<FilterA> filterA;
AutoRequired<FilterC> filterC;
AutoRequired<FilterD> filterD;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext()->Initiate();
// Obtain a packet first:
auto packet = factory->NewPacket();
// The mere act of obtaining a packet should have triggered filterD to be fired:
EXPECT_TRUE(filterD->m_called) << "Trivial filter was not called as expected";
// Decorate--should satisfy filterC
packet->Decorate(Decoration<0>());
EXPECT_TRUE(filterC->m_called) << "FilterC should have been satisfied with one decoration";
// FilterC should have also satisfied filterA:
EXPECT_TRUE(filterA->m_called) << "FilterA should have been satisfied by FilterC";
}
TEST_F(AutoFilterTest, VerifyReferenceBasedInput) {
std::shared_ptr<AutoPacket> packet;
{
AutoCreateContext sub;
CurrentContextPusher pshr(sub);
sub->Initiate();
AutoRequired<AutoPacketFactory> factory;
AutoRequired<FilterGen<Decoration<0>, Decoration<1>&>> makesDec1;
// Create a packet and put decoration 0 on it:
packet = factory->NewPacket();
// No early call
ASSERT_FALSE(makesDec1->m_called) << "Single-input autofilter was invoked prematurely";
// Now we decorate, after ensuring an early call did not happen
packet->Decorate(Decoration<0>());
// Verify that our filter got called when its sole input was satisfied
ASSERT_TRUE(makesDec1->m_called) << "Single-input autofilter was not called as expected";
// Now make sure that the packet has the expected decoration:
ASSERT_TRUE(packet->Has<Decoration<1>>());
sub->SignalShutdown(false);
}
}<commit_msg>Adding unit test to guard against leaks caused by deferred AutoFilter recipients in subcontexts<commit_after>#include "stdafx.h"
#include "AutoFilterTest.h"
#include "AutoPacket.h"
#include "AutoPacketFactory.h"
#include "TestFixtures/Decoration.h"
TEST_F(AutoFilterTest, VerifyDescendentAwareness) {
AutoCurrentContext()->Initiate();
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> parentFactory;
auto packet1 = parentFactory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
std::shared_ptr<AutoPacket> packet2;
std::weak_ptr<AutoPacket> packet3;
std::weak_ptr<FilterA> filterChecker;
// Create a subcontext
{
AutoCreateContext subContext;
{
CurrentContextPusher pusher(subContext);
//add a filter in the subcontext
AutoRequired<FilterA> subFilter;
filterChecker = subFilter;
}
//Create a packet where a subscriber exists only in a subcontext
packet2 = parentFactory->NewPacket();
auto strongPacket3 = parentFactory->NewPacket();
packet3 = strongPacket3;
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
EXPECT_TRUE(packet3.lock()->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
}
EXPECT_TRUE(packet3.expired()) << "Packet was not destroyed when it's subscribers were removed";
EXPECT_FALSE(filterChecker.expired()) << "Packet keeping subcontext member alive";
// Create a packet after the subcontext has been destroyed
auto packet4 = parentFactory->NewPacket();
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
packet2->Decorate(Decoration<0>());
// Verify the second one will no longe have subscriptions -
// normally removing a subscriber would mean the packet still has the subscriber, but
// in this case, the subscriber was actually destroyed so the packet has lost a subscriber.
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
// Verify the third one does not:
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
packet2.reset();
EXPECT_TRUE(filterChecker.expired()) << "Subscriber didn't expire after packet was reset.";
}
TEST_F(AutoFilterTest, VerifySimpleFilter) {
AutoCurrentContext()->Initiate();
AutoRequired<AutoPacketFactory> factory;
AutoRequired<FilterA> filterA;
// Verify that the subscriber has been properly detected:
bool bFound = false;
for(const auto& cur : factory->GetSubscriberVector())
if(cur.GetAutoFilter() == filterA) {
bFound = true;
break;
}
ASSERT_TRUE(bFound) << "Failed to find an added subscriber ";
// Obtain a packet from the factory:
auto packet = factory->NewPacket();
// Decorate with one instance:
packet->Decorate(Decoration<0>());
// Verify that no hit takes place with inadequate decoration:
EXPECT_FALSE(filterA->m_called) << "Filter called prematurely with insufficient decoration";
// Now decorate with the other requirement of the filter:
packet->Decorate(Decoration<1>());
// A hit should have taken place at this point:
EXPECT_TRUE(filterA->m_called) << "Filter was not called even though it was fully satisfied";
}
TEST_F(AutoFilterTest, VerifyNoMultiDecorate) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet and attempt redundant introduction:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Redundant decoration did not throw an exception as expected";
// Verify that a call has not yet been made
EXPECT_FALSE(filterA->m_called) << "A call made on an idempotent packet decoration";
// Now finish saturating the filter and ensure we get a call:
packet->Decorate(Decoration<1>());
EXPECT_TRUE(filterA->m_called) << "Filter was not called after being fully satisfied";
}
TEST_F(AutoFilterTest, VerifyInterThreadDecoration) {
AutoRequired<FilterB> filterB;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext ctxt;
// Kick off all threads:
ctxt->Initiate();
// Obtain a packet for processing and decorate it:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
// Verify that the recipient has NOT yet received the message:
EXPECT_FALSE(filterB->m_called) << "A call was made to a thread which should not have been able to process it";
// Wake up the barrier and post a quit message:
filterB->m_barr.wait();
*filterB += [&filterB] { filterB->Stop(); };
filterB->Wait();
// Verify that the filter method has been called
EXPECT_TRUE(filterB->m_called) << "A deferred filter method was not called as expected";
}
TEST_F(AutoFilterTest, VerifyTeardownArrangement) {
AutoCurrentContext()->Initiate();
AutoRequired<AutoPacketFactory> factory;
std::weak_ptr<FilterA> filterAWeak;
{
std::shared_ptr<AutoPacket> packet;
{
// Create the filter and subscribe it
std::shared_ptr<FilterA> filterA(new FilterA);
filterAWeak = filterA;
factory->AddSubscriber(filterA);
// Create the packet--this should lock in references to all subscribers:
packet = factory->NewPacket();
}
// Verify that the subscription has not expired:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber while it was still registered";
{
std::shared_ptr<FilterA> filterA = filterAWeak.lock();
// Unsubscribe the filter:
factory->RemoveSubscriber(filterA);
}
// Verify that unsubscription STILL does not result in expiration:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber expired before all packets on that subscriber were satisfied";
//Create a new packet after having removed the only filter on it.
auto packet2 = factory->NewPacket();
ASSERT_FALSE(packet2->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
// Satisfy the packet:
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
auto packet3 = factory->NewPacket();
ASSERT_FALSE(packet3->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
}
// Filter should be expired now:
ASSERT_TRUE(filterAWeak.expired()) << "Subscriber was still left outstanding even though all references should be gone";
}
TEST_F(AutoFilterTest, VerifyCheckout) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
{
// Verify that an unsubscribed decoration returns a correct checkout:
auto unused = packet->Checkout<Decoration<4>>();
EXPECT_FALSE(unused) << "Checkout incorrectly generated for unsubscribed decoration";
}
// Satisfy the other decoration:
packet->Decorate(Decoration<1>());
{
AutoCheckout<Decoration<0>> exterior;
{
AutoCheckout<Decoration<0>> checkout = packet->Checkout<Decoration<0>>();
// Verify we can move the original type:
AutoCheckout<Decoration<0>> checkoutMoved(std::move(checkout));
// Verify no hits yet:
EXPECT_FALSE(filterA->m_called) << "Filter called as a consequence of a checkout move operation";
// Move the checkout a second time:
exterior = std::move(checkoutMoved);
}
// Still no hits
EXPECT_FALSE(filterA->m_called) << "Filter called before a decoration checkout expired";
// Mark ready so we get committed:
exterior.Ready();
}
// Verify a hit took place now
EXPECT_TRUE(filterA->m_called) << "Filter was not called after all decorations were installed";
}
TEST_F(AutoFilterTest, RollbackCorrectness) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<1>());
// Request and immediately allow the destruction of a checkout:
packet->Checkout<Decoration<0>>();
// Verify no hit took place--the checkout should have been cancelled:
EXPECT_FALSE(filterA->m_called) << "Filter was called even though one decoration shouldn't have been available";
// We should not be able to obtain another checkout of this decoration on this packet:
EXPECT_ANY_THROW(packet->Checkout<Decoration<0>>()) << "An attempt to check out a decoration a second time should have failed";
// We shouldn't be able to manually decorate, either:
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "An attempt to manually add a previously failed decoration succeeded where it should not have";
}
TEST_F(AutoFilterTest, VerifyAntiDecorate) {
AutoCurrentContext()->Initiate();
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
{
// Obtain a new packet and mark an unsatisfiable decoration:
auto packet = factory->NewPacket();
packet->Unsatisfiable<Decoration<0>>();
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Decoration succeeded on a decoration marked unsatisfiable";
}
{
// Obtain a new packet and try to make a satisfied decoration unsatisfiable.
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Unsatisfiable<Decoration<0>>()) << "Succeeded in marking an already-existing decoration as unsatisfiable";
}
}
TEST_F(AutoFilterTest, VerifyReflexiveReciept) {
AutoRequired<FilterA> filterA;
AutoRequired<FilterC> filterC;
AutoRequired<FilterD> filterD;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext()->Initiate();
// Obtain a packet first:
auto packet = factory->NewPacket();
// The mere act of obtaining a packet should have triggered filterD to be fired:
EXPECT_TRUE(filterD->m_called) << "Trivial filter was not called as expected";
// Decorate--should satisfy filterC
packet->Decorate(Decoration<0>());
EXPECT_TRUE(filterC->m_called) << "FilterC should have been satisfied with one decoration";
// FilterC should have also satisfied filterA:
EXPECT_TRUE(filterA->m_called) << "FilterA should have been satisfied by FilterC";
}
TEST_F(AutoFilterTest, VerifyReferenceBasedInput) {
std::shared_ptr<AutoPacket> packet;
{
AutoCreateContext sub;
CurrentContextPusher pshr(sub);
sub->Initiate();
AutoRequired<AutoPacketFactory> factory;
AutoRequired<FilterGen<Decoration<0>, Decoration<1>&>> makesDec1;
// Create a packet and put decoration 0 on it:
packet = factory->NewPacket();
// No early call
ASSERT_FALSE(makesDec1->m_called) << "Single-input autofilter was invoked prematurely";
// Now we decorate, after ensuring an early call did not happen
packet->Decorate(Decoration<0>());
// Verify that our filter got called when its sole input was satisfied
ASSERT_TRUE(makesDec1->m_called) << "Single-input autofilter was not called as expected";
// Now make sure that the packet has the expected decoration:
ASSERT_TRUE(packet->Has<Decoration<1>>());
sub->SignalShutdown(false);
}
}
class DeferredAutoFilter:
public CoreThread
{
public:
DeferredAutoFilter(void) :
nReceived(0)
{}
Deferred AutoFilter(const Decoration<0>& dec) {
nReceived++;
return Deferred(this);
}
size_t nReceived;
};
TEST_F(AutoFilterTest, DeferredRecieptInSubContext) {
AutoCurrentContext()->Initiate();
static const size_t nPackets = 5;
AutoRequired<AutoPacketFactory> factory;
std::vector<std::weak_ptr<AutoPacket>> allPackets;
// Issue a packet before the subcontext is created, hold it for awhile:
auto preissued = factory->NewPacket();
allPackets.push_back(preissued);
{
// Create subcontext
AutoCreateContext ctxt;
ctxt->Initiate();
CurrentContextPusher pshr(ctxt);
AutoRequired<DeferredAutoFilter> daf;
// Issue a few packets, have them get picked up by the subcontext:
for(size_t i = nPackets; i--;)
{
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
allPackets.push_back(packet);
}
// Terminate the subcontext, release references
ctxt->SignalShutdown(true);
ctxt->Wait();
// Verify that the filter got all of the packets that it should have gotten:
ASSERT_EQ(nPackets, daf->nReceived) << "AutoFilter did not get all packets that were pended to it";
}
// Release the preissued packet:
preissued.reset();
// Now verify that all of our packets are expired:
for(auto cur : allPackets)
ASSERT_TRUE(cur.expired()) << "Packet did not expire after all recipients went out of scope";
}<|endoftext|>
|
<commit_before><commit_msg>Implement "indent_size = tab" support.<commit_after><|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "scribblearea.h"
//! [0]
ScribbleArea::ScribbleArea(QWidget *parent)
: QWidget(parent)
{
setAttribute(Qt::WA_StaticContents);
modified = false;
scribbling = false;
myPenWidth = 1;
myPenColor = Qt::blue;
}
//! [0]
//! [1]
bool ScribbleArea::openImage(const QString &fileName)
//! [1] //! [2]
{
QImage loadedImage;
if (!loadedImage.load(fileName))
return false;
QSize newSize = loadedImage.size().expandedTo(size());
resizeImage(&loadedImage, newSize);
image = loadedImage;
modified = false;
update();
return true;
}
//! [2]
//! [3]
bool ScribbleArea::saveImage(const QString &fileName, const char *fileFormat)
//! [3] //! [4]
{
QImage visibleImage = image;
resizeImage(&visibleImage, size());
if (visibleImage.save(fileName, fileFormat)) {
modified = false;
return true;
} else {
return false;
}
}
//! [4]
//! [5]
void ScribbleArea::setPenColor(const QColor &newColor)
//! [5] //! [6]
{
myPenColor = newColor;
}
//! [6]
//! [7]
void ScribbleArea::setPenWidth(int newWidth)
//! [7] //! [8]
{
myPenWidth = newWidth;
}
//! [8]
//! [9]
void ScribbleArea::clearImage()
//! [9] //! [10]
{
image.fill(qRgb(255, 255, 255));
modified = true;
update();
}
//! [10]
//! [11]
void ScribbleArea::mousePressEvent(QMouseEvent *event)
//! [11] //! [12]
{
if (event->button() == Qt::LeftButton) {
lastPoint = event->pos();
scribbling = true;
}
}
void ScribbleArea::mouseMoveEvent(QMouseEvent *event)
{
if ((event->buttons() & Qt::LeftButton) && scribbling)
drawLineTo(event->pos());
}
void ScribbleArea::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && scribbling) {
drawLineTo(event->pos());
scribbling = false;
}
}
//! [12] //! [13]
void ScribbleArea::paintEvent(QPaintEvent * /* event */)
//! [13] //! [14]
{
QPainter painter(this);
painter.drawImage(QPoint(0, 0), image);
}
//! [14]
//! [15]
void ScribbleArea::resizeEvent(QResizeEvent *event)
//! [15] //! [16]
{
if (width() > image.width() || height() > image.height()) {
int newWidth = qMax(width() + 128, image.width());
int newHeight = qMax(height() + 128, image.height());
resizeImage(&image, QSize(newWidth, newHeight));
update();
}
QWidget::resizeEvent(event);
}
//! [16]
//! [17]
void ScribbleArea::drawLineTo(const QPoint &endPoint)
//! [17] //! [18]
{
QPainter painter(&image);
painter.setPen(QPen(myPenColor, myPenWidth, Qt::SolidLine, Qt::RoundCap,
Qt::RoundJoin));
painter.drawLine(lastPoint, endPoint);
modified = true;
int rad = (myPenWidth / 2) + 2;
update(QRect(lastPoint, endPoint).normalized()
.adjusted(-rad, -rad, +rad, +rad));
lastPoint = endPoint;
}
//! [18]
//! [19]
void ScribbleArea::resizeImage(QImage *image, const QSize &newSize)
//! [19] //! [20]
{
if (image->size() == newSize)
return;
QImage newImage(newSize, QImage::Format_RGB32);
newImage.fill(qRgb(255, 255, 255));
QPainter painter(&newImage);
painter.drawImage(QPoint(0, 0), *image);
*image = newImage;
}
//! [20]
//! [21]
void ScribbleArea::print()
{
#ifndef QT_NO_PRINTER
QPrinter printer(QPrinter::HighResolution);
QPrintDialog *printDialog = new QPrintDialog(&printer, this);
//! [21] //! [22]
if (printDialog->exec() == QDialog::Accepted) {
QPainter painter(&printer);
QRect rect = painter.viewport();
QSize size = image.size();
size.scale(rect.size(), Qt::KeepAspectRatio);
painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
painter.setWindow(image.rect());
painter.drawImage(0, 0, image);
}
#endif // QT_NO_PRINTER
}
//! [22]
<commit_msg>Fixes performance problem with scribble avoiding to redraw whole screen on every MotionNotify event.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "scribblearea.h"
//! [0]
ScribbleArea::ScribbleArea(QWidget *parent)
: QWidget(parent)
{
setAttribute(Qt::WA_StaticContents);
modified = false;
scribbling = false;
myPenWidth = 1;
myPenColor = Qt::blue;
}
//! [0]
//! [1]
bool ScribbleArea::openImage(const QString &fileName)
//! [1] //! [2]
{
QImage loadedImage;
if (!loadedImage.load(fileName))
return false;
QSize newSize = loadedImage.size().expandedTo(size());
resizeImage(&loadedImage, newSize);
image = loadedImage;
modified = false;
update();
return true;
}
//! [2]
//! [3]
bool ScribbleArea::saveImage(const QString &fileName, const char *fileFormat)
//! [3] //! [4]
{
QImage visibleImage = image;
resizeImage(&visibleImage, size());
if (visibleImage.save(fileName, fileFormat)) {
modified = false;
return true;
} else {
return false;
}
}
//! [4]
//! [5]
void ScribbleArea::setPenColor(const QColor &newColor)
//! [5] //! [6]
{
myPenColor = newColor;
}
//! [6]
//! [7]
void ScribbleArea::setPenWidth(int newWidth)
//! [7] //! [8]
{
myPenWidth = newWidth;
}
//! [8]
//! [9]
void ScribbleArea::clearImage()
//! [9] //! [10]
{
image.fill(qRgb(255, 255, 255));
modified = true;
update();
}
//! [10]
//! [11]
void ScribbleArea::mousePressEvent(QMouseEvent *event)
//! [11] //! [12]
{
if (event->button() == Qt::LeftButton) {
lastPoint = event->pos();
scribbling = true;
}
}
void ScribbleArea::mouseMoveEvent(QMouseEvent *event)
{
if ((event->buttons() & Qt::LeftButton) && scribbling)
drawLineTo(event->pos());
}
void ScribbleArea::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && scribbling) {
drawLineTo(event->pos());
scribbling = false;
}
}
//! [12] //! [13]
void ScribbleArea::paintEvent(QPaintEvent *event)
//! [13] //! [14]
{
QPainter painter(this);
QRect dirtyRect = event->rect();
painter.drawImage(dirtyRect, image, dirtyRect);
}
//! [14]
//! [15]
void ScribbleArea::resizeEvent(QResizeEvent *event)
//! [15] //! [16]
{
if (width() > image.width() || height() > image.height()) {
int newWidth = qMax(width() + 128, image.width());
int newHeight = qMax(height() + 128, image.height());
resizeImage(&image, QSize(newWidth, newHeight));
update();
}
QWidget::resizeEvent(event);
}
//! [16]
//! [17]
void ScribbleArea::drawLineTo(const QPoint &endPoint)
//! [17] //! [18]
{
QPainter painter(&image);
painter.setPen(QPen(myPenColor, myPenWidth, Qt::SolidLine, Qt::RoundCap,
Qt::RoundJoin));
painter.drawLine(lastPoint, endPoint);
modified = true;
int rad = (myPenWidth / 2) + 2;
update(QRect(lastPoint, endPoint).normalized()
.adjusted(-rad, -rad, +rad, +rad));
lastPoint = endPoint;
}
//! [18]
//! [19]
void ScribbleArea::resizeImage(QImage *image, const QSize &newSize)
//! [19] //! [20]
{
if (image->size() == newSize)
return;
QImage newImage(newSize, QImage::Format_RGB32);
newImage.fill(qRgb(255, 255, 255));
QPainter painter(&newImage);
painter.drawImage(QPoint(0, 0), *image);
*image = newImage;
}
//! [20]
//! [21]
void ScribbleArea::print()
{
#ifndef QT_NO_PRINTER
QPrinter printer(QPrinter::HighResolution);
QPrintDialog *printDialog = new QPrintDialog(&printer, this);
//! [21] //! [22]
if (printDialog->exec() == QDialog::Accepted) {
QPainter painter(&printer);
QRect rect = painter.viewport();
QSize size = image.size();
size.scale(rect.size(), Qt::KeepAspectRatio);
painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
painter.setWindow(image.rect());
painter.drawImage(0, 0, image);
}
#endif // QT_NO_PRINTER
}
//! [22]
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: abpfinalpage.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-10-12 10:37:12 $
*
* 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_extensions.hxx"
#ifndef EXTENSIONS_ABP_ABPFINALPAGE_HXX
#include "abpfinalpage.hxx"
#endif
#ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX
#include "addresssettings.hxx"
#endif
#ifndef EXTENSIONS_ABSPILOT_HXX
#include "abspilot.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UNOTOOLS_UCBHELPER_HXX
#include <unotools/ucbhelper.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef SVTOOLS_FILENOTATION_HXX_
#include <svtools/filenotation.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
//.........................................................................
namespace abp
{
//.........................................................................
using namespace ::svt;
using namespace ::utl;
const SfxFilter* lcl_getBaseFilter()
{
static const String s_sDatabaseType = String::CreateFromAscii("StarOffice XML (Base)");
const SfxFilter* pFilter = SfxFilter::GetFilterByName( s_sDatabaseType);
OSL_ENSURE(pFilter,"Filter: StarOffice XML (Base) could not be found!");
return pFilter;
}
//=====================================================================
//= FinalPage
//=====================================================================
//---------------------------------------------------------------------
FinalPage::FinalPage( OAddessBookSourcePilot* _pParent )
:AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_FINAL))
,m_aExplanation ( this, ResId( FT_FINISH_EXPL ) )
,m_aLocationLabel ( this, ResId( FT_LOCATION ) )
,m_aLocation ( this, ResId( CBB_LOCATION ) )
,m_aBrowse ( this, ResId( PB_BROWSE ) )
,m_aRegisterName ( this, ResId( CB_REGISTER_DS ) )
,m_aNameLabel ( this, ResId( FT_NAME_EXPL ) )
,m_aName ( this, ResId( ET_DATASOURCENAME ) )
,m_aDuplicateNameError ( this, ResId( FT_DUPLICATENAME ) )
,m_bCheckFileName (sal_True)
{
FreeResource();
m_aName.SetModifyHdl( LINK(this, FinalPage, OnNameModified) );
m_aLocation.SetModifyHdl( LINK(this, FinalPage, OnNameModified) );
m_aBrowse.SetClickHdl( LINK( this, FinalPage, OnBrowse ) );
m_aRegisterName.SetClickHdl( LINK( this, FinalPage, OnRegister ) );
m_aRegisterName.Check(TRUE);
const SfxFilter* pFilter = lcl_getBaseFilter();
if ( pFilter )
{
m_aLocation.SetFilter(pFilter->GetDefaultExtension());
}
}
//---------------------------------------------------------------------
sal_Bool FinalPage::isValidName() const
{
::rtl::OUString sCurrentName(m_aName.GetText());
if (0 == sCurrentName.getLength())
// the name must not be empty
return sal_False;
if ( m_aInvalidDataSourceNames.find( sCurrentName ) != m_aInvalidDataSourceNames.end() )
// there already is a data source with this name
return sal_False;
return sal_True;
}
//---------------------------------------------------------------------
void FinalPage::setFields()
{
AddressSettings& rSettings = getSettings();
INetURLObject aURL( rSettings.sDataSourceName );
if( aURL.GetProtocol() == INET_PROT_NOT_VALID )
{
String sPath = SvtPathOptions().GetWorkPath();
sPath += '/';
sPath += String(rSettings.sDataSourceName);
const SfxFilter* pFilter = lcl_getBaseFilter();
if ( pFilter )
{
String sExt = pFilter->GetDefaultExtension();
sPath += sExt.GetToken(1,'*');
}
aURL.SetURL(sPath);
}
OSL_ENSURE( aURL.GetProtocol() != INET_PROT_NOT_VALID ,"No valid file name!");
rSettings.sDataSourceName = aURL.GetMainURL( INetURLObject::NO_DECODE );
OFileNotation aFileNotation( rSettings.sDataSourceName );
m_aLocation.SetText(aFileNotation.get(OFileNotation::N_SYSTEM));
String sName = aURL.getName( );
xub_StrLen nPos = sName.Search(String(aURL.GetExtension()));
if ( nPos != STRING_NOTFOUND )
{
sName.Erase(nPos-1,4);
}
m_aName.SetText(sName);
OnRegister(&m_aRegisterName);
}
//---------------------------------------------------------------------
void FinalPage::initializePage()
{
AddressBookSourcePage::initializePage();
setFields();
}
//---------------------------------------------------------------------
sal_Bool FinalPage::commitPage(COMMIT_REASON _eReason)
{
if (!AddressBookSourcePage::commitPage(_eReason))
return sal_False;
OFileNotation aFileNotation( m_aLocation.GetText() );
::rtl::OUString sURL = aFileNotation.get(OFileNotation::N_URL);
// check if the name exists
if ( m_bCheckFileName )
{
if ( ::utl::UCBContentHelper::Exists( sURL ) )
{
QueryBox aBox( this, WB_YES_NO, ModuleRes( RID_STR_ALREADYEXISTOVERWRITE ) );
if ( aBox.Execute() != RET_YES )
return sal_False;
}
}
AddressSettings& rSettings = getSettings();
rSettings.sDataSourceName = sURL;
rSettings.bRegisterDataSource = m_aRegisterName.IsChecked();
if ( rSettings.bRegisterDataSource )
rSettings.sRegisteredDataSourceName = m_aName.GetText();
return sal_True;
}
//---------------------------------------------------------------------
void FinalPage::ActivatePage()
{
AddressBookSourcePage::ActivatePage();
// get the names of all data sources
ODataSourceContext aContext( getORB() );
aContext.getDataSourceNames( m_aInvalidDataSourceNames );
// in real, the data source which this dialog should create, is already part of the context
// as it's name is - of course - a valid name, we have to remove it from the bag
// DBG_ASSERT( getDialog()->getDataSource().getName() == getSettings().sDataSourceName,
// "FinalPage::ActivatePage: inconsistent names!" );
// give the name edit the focus
m_aLocation.GrabFocus();
// default the finish button
getDialog()->defaultButton( WZB_FINISH );
}
//---------------------------------------------------------------------
void FinalPage::DeactivatePage()
{
AddressBookSourcePage::DeactivatePage();
// default the "next" button, again
getDialog()->defaultButton( WZB_NEXT );
// disable the finish button
getDialog()->enableButtons( WZB_FINISH, sal_False );
}
//---------------------------------------------------------------------
sal_Bool FinalPage::determineNextButtonState()
{
return sal_False;
}
//---------------------------------------------------------------------
void FinalPage::implCheckName()
{
sal_Bool bValidName = isValidName();
sal_Bool bEmptyName = 0 == m_aName.GetText().Len();
sal_Bool bEmptyLocation = 0 == m_aLocation.GetText().Len();
// enable or disable the finish button
getDialog()->enableButtons( WZB_FINISH, !bEmptyLocation && (!m_aRegisterName.IsChecked() || bValidName) );
// show the error message for an invalid name
m_aDuplicateNameError.Show( !bValidName && !bEmptyName );
}
//---------------------------------------------------------------------
IMPL_LINK( FinalPage, OnNameModified, Edit*, _pEdit)
{
if ( _pEdit == &m_aLocation )
m_bCheckFileName = sal_True;
implCheckName();
return 0L;
}
// -----------------------------------------------------------------------------
IMPL_LINK( FinalPage, OnBrowse, PushButton*, EMPTYARG )
{
OFileNotation aOldFile( m_aLocation.GetText() );
WinBits nBits(WB_STDMODAL|WB_SAVEAS);
::sfx2::FileDialogHelper aFileDlg( com::sun::star::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION,static_cast<sal_uInt32>(nBits) ,this);
aFileDlg.SetDisplayDirectory( aOldFile.get(OFileNotation::N_URL) );
static const String s_sDatabaseType = String::CreateFromAscii("StarOffice XML (Base)");
const SfxFilter* pFilter = SfxFilter::GetFilterByName( s_sDatabaseType);
OSL_ENSURE(pFilter,"Filter: StarOffice XML (Base) could not be found!");
if ( pFilter )
{
aFileDlg.AddFilter(pFilter->GetFilterName(),pFilter->GetDefaultExtension());
aFileDlg.SetCurrentFilter(pFilter->GetFilterName());
}
if ( aFileDlg.Execute() == ERRCODE_NONE )
{
INetURLObject aURL( aFileDlg.GetPath() );
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
{
OFileNotation aFileNotation( aURL.GetMainURL( INetURLObject::NO_DECODE ) );
m_aLocation.SetText(aFileNotation.get(OFileNotation::N_SYSTEM));
implCheckName();
m_bCheckFileName = sal_False;
}
}
return 0L;
}
// -----------------------------------------------------------------------------
IMPL_LINK( FinalPage, OnRegister, CheckBox*, EMPTYARG )
{
BOOL bEnable = m_aRegisterName.IsChecked();
m_aNameLabel.Enable(bEnable);
m_aName.Enable(bEnable);
implCheckName();
return 0L;
}
//.........................................................................
} // namespace abp
//.........................................................................
<commit_msg>INTEGRATION: CWS residcleanup (1.8.98); FILE MERGED 2007/02/28 20:46:08 pl 1.8.98.1: #i74635# no more ResMgr fallback<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: abpfinalpage.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2007-04-26 08:04:13 $
*
* 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_extensions.hxx"
#ifndef EXTENSIONS_ABP_ABPFINALPAGE_HXX
#include "abpfinalpage.hxx"
#endif
#ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX
#include "addresssettings.hxx"
#endif
#ifndef EXTENSIONS_ABSPILOT_HXX
#include "abspilot.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UNOTOOLS_UCBHELPER_HXX
#include <unotools/ucbhelper.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef SVTOOLS_FILENOTATION_HXX_
#include <svtools/filenotation.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
//.........................................................................
namespace abp
{
//.........................................................................
using namespace ::svt;
using namespace ::utl;
const SfxFilter* lcl_getBaseFilter()
{
static const String s_sDatabaseType = String::CreateFromAscii("StarOffice XML (Base)");
const SfxFilter* pFilter = SfxFilter::GetFilterByName( s_sDatabaseType);
OSL_ENSURE(pFilter,"Filter: StarOffice XML (Base) could not be found!");
return pFilter;
}
//=====================================================================
//= FinalPage
//=====================================================================
//---------------------------------------------------------------------
FinalPage::FinalPage( OAddessBookSourcePilot* _pParent )
:AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_FINAL))
,m_aExplanation ( this, ModuleRes( FT_FINISH_EXPL ) )
,m_aLocationLabel ( this, ModuleRes( FT_LOCATION ) )
,m_aLocation ( this, ModuleRes( CBB_LOCATION ) )
,m_aBrowse ( this, ModuleRes( PB_BROWSE ) )
,m_aRegisterName ( this, ModuleRes( CB_REGISTER_DS ) )
,m_aNameLabel ( this, ModuleRes( FT_NAME_EXPL ) )
,m_aName ( this, ModuleRes( ET_DATASOURCENAME ) )
,m_aDuplicateNameError ( this, ModuleRes( FT_DUPLICATENAME ) )
,m_bCheckFileName (sal_True)
{
FreeResource();
m_aName.SetModifyHdl( LINK(this, FinalPage, OnNameModified) );
m_aLocation.SetModifyHdl( LINK(this, FinalPage, OnNameModified) );
m_aBrowse.SetClickHdl( LINK( this, FinalPage, OnBrowse ) );
m_aRegisterName.SetClickHdl( LINK( this, FinalPage, OnRegister ) );
m_aRegisterName.Check(TRUE);
const SfxFilter* pFilter = lcl_getBaseFilter();
if ( pFilter )
{
m_aLocation.SetFilter(pFilter->GetDefaultExtension());
}
}
//---------------------------------------------------------------------
sal_Bool FinalPage::isValidName() const
{
::rtl::OUString sCurrentName(m_aName.GetText());
if (0 == sCurrentName.getLength())
// the name must not be empty
return sal_False;
if ( m_aInvalidDataSourceNames.find( sCurrentName ) != m_aInvalidDataSourceNames.end() )
// there already is a data source with this name
return sal_False;
return sal_True;
}
//---------------------------------------------------------------------
void FinalPage::setFields()
{
AddressSettings& rSettings = getSettings();
INetURLObject aURL( rSettings.sDataSourceName );
if( aURL.GetProtocol() == INET_PROT_NOT_VALID )
{
String sPath = SvtPathOptions().GetWorkPath();
sPath += '/';
sPath += String(rSettings.sDataSourceName);
const SfxFilter* pFilter = lcl_getBaseFilter();
if ( pFilter )
{
String sExt = pFilter->GetDefaultExtension();
sPath += sExt.GetToken(1,'*');
}
aURL.SetURL(sPath);
}
OSL_ENSURE( aURL.GetProtocol() != INET_PROT_NOT_VALID ,"No valid file name!");
rSettings.sDataSourceName = aURL.GetMainURL( INetURLObject::NO_DECODE );
OFileNotation aFileNotation( rSettings.sDataSourceName );
m_aLocation.SetText(aFileNotation.get(OFileNotation::N_SYSTEM));
String sName = aURL.getName( );
xub_StrLen nPos = sName.Search(String(aURL.GetExtension()));
if ( nPos != STRING_NOTFOUND )
{
sName.Erase(nPos-1,4);
}
m_aName.SetText(sName);
OnRegister(&m_aRegisterName);
}
//---------------------------------------------------------------------
void FinalPage::initializePage()
{
AddressBookSourcePage::initializePage();
setFields();
}
//---------------------------------------------------------------------
sal_Bool FinalPage::commitPage(COMMIT_REASON _eReason)
{
if (!AddressBookSourcePage::commitPage(_eReason))
return sal_False;
OFileNotation aFileNotation( m_aLocation.GetText() );
::rtl::OUString sURL = aFileNotation.get(OFileNotation::N_URL);
// check if the name exists
if ( m_bCheckFileName )
{
if ( ::utl::UCBContentHelper::Exists( sURL ) )
{
QueryBox aBox( this, WB_YES_NO, ModuleRes( RID_STR_ALREADYEXISTOVERWRITE ) );
if ( aBox.Execute() != RET_YES )
return sal_False;
}
}
AddressSettings& rSettings = getSettings();
rSettings.sDataSourceName = sURL;
rSettings.bRegisterDataSource = m_aRegisterName.IsChecked();
if ( rSettings.bRegisterDataSource )
rSettings.sRegisteredDataSourceName = m_aName.GetText();
return sal_True;
}
//---------------------------------------------------------------------
void FinalPage::ActivatePage()
{
AddressBookSourcePage::ActivatePage();
// get the names of all data sources
ODataSourceContext aContext( getORB() );
aContext.getDataSourceNames( m_aInvalidDataSourceNames );
// in real, the data source which this dialog should create, is already part of the context
// as it's name is - of course - a valid name, we have to remove it from the bag
// DBG_ASSERT( getDialog()->getDataSource().getName() == getSettings().sDataSourceName,
// "FinalPage::ActivatePage: inconsistent names!" );
// give the name edit the focus
m_aLocation.GrabFocus();
// default the finish button
getDialog()->defaultButton( WZB_FINISH );
}
//---------------------------------------------------------------------
void FinalPage::DeactivatePage()
{
AddressBookSourcePage::DeactivatePage();
// default the "next" button, again
getDialog()->defaultButton( WZB_NEXT );
// disable the finish button
getDialog()->enableButtons( WZB_FINISH, sal_False );
}
//---------------------------------------------------------------------
sal_Bool FinalPage::determineNextButtonState()
{
return sal_False;
}
//---------------------------------------------------------------------
void FinalPage::implCheckName()
{
sal_Bool bValidName = isValidName();
sal_Bool bEmptyName = 0 == m_aName.GetText().Len();
sal_Bool bEmptyLocation = 0 == m_aLocation.GetText().Len();
// enable or disable the finish button
getDialog()->enableButtons( WZB_FINISH, !bEmptyLocation && (!m_aRegisterName.IsChecked() || bValidName) );
// show the error message for an invalid name
m_aDuplicateNameError.Show( !bValidName && !bEmptyName );
}
//---------------------------------------------------------------------
IMPL_LINK( FinalPage, OnNameModified, Edit*, _pEdit)
{
if ( _pEdit == &m_aLocation )
m_bCheckFileName = sal_True;
implCheckName();
return 0L;
}
// -----------------------------------------------------------------------------
IMPL_LINK( FinalPage, OnBrowse, PushButton*, EMPTYARG )
{
OFileNotation aOldFile( m_aLocation.GetText() );
WinBits nBits(WB_STDMODAL|WB_SAVEAS);
::sfx2::FileDialogHelper aFileDlg( com::sun::star::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION,static_cast<sal_uInt32>(nBits) ,this);
aFileDlg.SetDisplayDirectory( aOldFile.get(OFileNotation::N_URL) );
static const String s_sDatabaseType = String::CreateFromAscii("StarOffice XML (Base)");
const SfxFilter* pFilter = SfxFilter::GetFilterByName( s_sDatabaseType);
OSL_ENSURE(pFilter,"Filter: StarOffice XML (Base) could not be found!");
if ( pFilter )
{
aFileDlg.AddFilter(pFilter->GetFilterName(),pFilter->GetDefaultExtension());
aFileDlg.SetCurrentFilter(pFilter->GetFilterName());
}
if ( aFileDlg.Execute() == ERRCODE_NONE )
{
INetURLObject aURL( aFileDlg.GetPath() );
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
{
OFileNotation aFileNotation( aURL.GetMainURL( INetURLObject::NO_DECODE ) );
m_aLocation.SetText(aFileNotation.get(OFileNotation::N_SYSTEM));
implCheckName();
m_bCheckFileName = sal_False;
}
}
return 0L;
}
// -----------------------------------------------------------------------------
IMPL_LINK( FinalPage, OnRegister, CheckBox*, EMPTYARG )
{
BOOL bEnable = m_aRegisterName.IsChecked();
m_aNameLabel.Enable(bEnable);
m_aName.Enable(bEnable);
implCheckName();
return 0L;
}
//.........................................................................
} // namespace abp
//.........................................................................
<|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* Licensed under the MIT license (see LICENSE).
*/
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <algorithm>
#include "log.h"
#include "../fnv.h"
namespace fnordmetric {
namespace database {
LogReader::LogReader(
std::shared_ptr<PageManager> page_manager,
const PageManager::Page& first_log_page,
LogSnapshot* destination) :
page_manager_(std::move(page_manager)),
current_page_(first_log_page),
destination_(destination) {}
void LogReader::import() {
bool running = true;
destination_->last_used_byte = current_page_.offset + current_page_.size;
while (running) {
auto mmapped_offset = current_page_.offset;
auto mmapped = page_manager_->getPage(current_page_);
size_t offset = 0;
destination_->current_log_page = current_page_;
destination_->current_log_page_offset = offset;
while (current_page_.offset == mmapped_offset) {
running = importNextEntry(mmapped.get(), current_page_.size, &offset);
if (running) {
destination_->current_log_page_offset = offset;
} else {
break;
}
}
}
for (auto& stream : destination_->streams) {
if (stream.pages_.size() > 0) {
countPageUsedBytes(stream.pages_.back());
}
}
}
bool LogReader::importNextEntry(
const PageManager::PageRef* mmapped,
size_t mmaped_size,
size_t* offset) {
size_t header_size = sizeof(Log::EntryHeader);
if (*offset + header_size >= mmaped_size) {
return false;
}
auto entry_header = mmapped->structAt<Log::EntryHeader>(*offset);
size_t entry_size = header_size + entry_header->size;
if (entry_header->size == 0 || *offset + entry_size >= mmaped_size) {
return false;
}
if (entry_header->checksum != entry_header->computeChecksum()) {
fprintf(stderr, "warning: invalid checksum for log entry 0x%" PRIx64 "\n",
mmapped->page_.offset + *offset);
return false;
}
*offset += entry_size;
importLogEntry(entry_header);
return true;
}
void LogReader::importLogEntry(const Log::EntryHeader* entry) {
switch (entry->type) {
case Log::PAGE_ALLOC_ENTRY: {
auto alloc_entry = (Log::PageAllocEntry *) entry;
auto iter = streams_.find(alloc_entry->stream_id);
LogSnapshot::StreamState* stream_state;
if (iter == streams_.end()) {
destination_->streams.emplace_back(alloc_entry->stream_id);
stream_state = &destination_->streams.back();
streams_[alloc_entry->stream_id] = stream_state;
size_t key_len = alloc_entry->hdr.size -
(sizeof(Log::PageAllocEntry) - sizeof(Log::EntryHeader));
stream_state->stream_key_.insert(0, alloc_entry->stream_key, key_len);
if (alloc_entry->stream_id > destination_->max_stream_id) {
destination_->max_stream_id = alloc_entry->stream_id;
}
} else {
stream_state = iter->second;
}
PageManager::Page page;
page.offset = alloc_entry->page_offset;
page.size = alloc_entry->page_size;
auto alloc = new PageAlloc(page, alloc_entry->page_first_row_time);
stream_state->pages_.push_back(std::shared_ptr<PageAlloc>(alloc));
setLastUsedByte(page.offset + page.size);
break;
}
case Log::PAGE_FINISH_ENTRY: {
auto finish_entry = (Log::PageFinishEntry *) entry;
auto iter = streams_.find(finish_entry->stream_id);
if (iter != streams_.end()) {
auto stream_state = iter->second;
if (stream_state->pages_.back()->page_.offset ==
finish_entry->page_offset) {
stream_state->pages_.back()->used_ = finish_entry->page_used;
break;
}
}
fprintf(stderr, "warning: unexpected PAGE_FINISH log entry\n");
break;
}
case Log::NEXT_PAGE_ENTRY: {
auto next_entry = (Log::NextPageEntry *) entry;
current_page_.offset = next_entry->page_offset;
current_page_.size = next_entry->page_size;
setLastUsedByte(current_page_.offset + current_page_.size);
break;
}
default:
fprintf(stderr, "warning: invalid log entry type %i\n", entry->type);
};
}
void LogReader::countPageUsedBytes(std::shared_ptr<PageAlloc> page) {
size_t offset = 0;
size_t max = page->page_.size - sizeof(Log::EntryHeader) - 1;
auto mmapped = page_manager_->getPage(page->page_);
while (offset < max) {
auto row = mmapped->structAt<RowHeader>(offset);
auto row_size = sizeof(RowHeader) + row->size;
if (row->size == 0 || row->time == 0) {
return;
}
if (offset + row_size >= page->page_.size) {
return;
}
if (row->checksum != row->computeChecksum()) {
return;
}
offset += row_size;
page->used_ = offset;
}
}
void LogReader::setLastUsedByte(uint64_t index) {
if (index > destination_->last_used_byte) {
destination_->last_used_byte = index;
}
}
const uint64_t Log::kMinLogPageSize = 512;
Log::Log(
const LogSnapshot& snapshot,
std::shared_ptr<PageManager> page_manager) :
page_manager_(page_manager),
current_page_(snapshot.current_log_page),
current_page_offset_(snapshot.current_log_page_offset) {}
Log::Log(
const PageManager::Page& first_log_page,
std::shared_ptr<PageManager> page_manager) :
page_manager_(page_manager),
current_page_(first_log_page),
current_page_offset_(0) {}
void Log::appendEntry(Log::PageAllocEntry entry) {
entry.hdr.size = sizeof(PageAllocEntry) - sizeof(EntryHeader);
entry.hdr.type = PAGE_ALLOC_ENTRY;
appendEntry((uint8_t *) &entry, sizeof(PageAllocEntry));
}
void Log::appendEntry(Log::PageAllocEntry entry, const std::string& stream_key) {
assert(stream_key.size() < 0xffff);
entry.hdr.size = sizeof(PageAllocEntry) - sizeof(EntryHeader);
entry.hdr.size += stream_key.size();
entry.hdr.type = PAGE_ALLOC_ENTRY;
size_t tmp_len = sizeof(PageAllocEntry) + stream_key.size();
uint8_t* tmp = (uint8_t *) malloc(tmp_len);
assert(tmp);
memcpy(tmp, &entry, sizeof(PageAllocEntry));
memcpy(tmp + sizeof(PageAllocEntry), stream_key.c_str(), stream_key.size());
appendEntry(tmp, tmp_len);
free(tmp);
}
void Log::appendEntry(Log::PageFinishEntry entry) {
entry.hdr.size = sizeof(PageFinishEntry) - sizeof(EntryHeader);
entry.hdr.type = PAGE_FINISH_ENTRY;
appendEntry((uint8_t *) &entry, sizeof(PageFinishEntry));
}
void Log::appendEntry(Log::PageFreeEntry entry) {
entry.hdr.size = sizeof(PageFreeEntry) - sizeof(EntryHeader);
entry.hdr.type = PAGE_FREE_ENTRY;
appendEntry((uint8_t *) &entry, sizeof(PageFreeEntry));
}
// FIXPAUL lock!
void Log::appendEntry(uint8_t* data, size_t length) {
uint64_t reserved_length = length + sizeof(Log::NextPageEntry);
/* allocate a new page if the current one is full */
if (current_page_offset_ + reserved_length >= current_page_.size) {
assert(current_page_offset_ + sizeof(Log::NextPageEntry) <=
current_page_.size);
auto next_page_size = std::max(kMinLogPageSize, reserved_length);
auto next_page = page_manager_->allocPage(next_page_size);
Log::NextPageEntry log_entry;
log_entry.page_offset = next_page.offset;
log_entry.page_size = next_page.size;
log_entry.hdr.size = sizeof(Log::NextPageEntry) - sizeof(Log::EntryHeader);
log_entry.hdr.type = NEXT_PAGE_ENTRY;
log_entry.hdr.checksum = log_entry.hdr.computeChecksum();
auto mmaped = page_manager_->getPage(current_page_);
auto dst = mmaped->structAt<char>(current_page_offset_);
memcpy(dst, (char *) &log_entry, sizeof(Log::NextPageEntry));
current_page_offset_ += sizeof(Log::NextPageEntry);
current_page_ = next_page;
current_page_offset_ = 0;
}
/* memcpy the entry into the current page */
auto entry = (Log::EntryHeader*) data;
entry->checksum = entry->computeChecksum();
auto mmaped = page_manager_->getPage(current_page_);
auto dst = mmaped->structAt<char>(current_page_offset_);
memcpy(dst, data, length);
current_page_offset_ += length;
// FIXPAUL msync
}
uint32_t Log::EntryHeader::computeChecksum() {
FNV<uint32_t> fnv;
return fnv.hash(
(uint8_t *) (((char* ) this) + sizeof(checksum)),
size + sizeof(EntryHeader) - sizeof(checksum));
}
LogSnapshot::LogSnapshot() : max_stream_id(0) {}
LogSnapshot::StreamState::StreamState(uint32_t stream_id) :
stream_id_(stream_id) {}
}
}
<commit_msg>fix includes...<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* Licensed under the MIT license (see LICENSE).
*/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <inttypes.h>
#include <algorithm>
#include "log.h"
#include "../fnv.h"
namespace fnordmetric {
namespace database {
LogReader::LogReader(
std::shared_ptr<PageManager> page_manager,
const PageManager::Page& first_log_page,
LogSnapshot* destination) :
page_manager_(std::move(page_manager)),
current_page_(first_log_page),
destination_(destination) {}
void LogReader::import() {
bool running = true;
destination_->last_used_byte = current_page_.offset + current_page_.size;
while (running) {
auto mmapped_offset = current_page_.offset;
auto mmapped = page_manager_->getPage(current_page_);
size_t offset = 0;
destination_->current_log_page = current_page_;
destination_->current_log_page_offset = offset;
while (current_page_.offset == mmapped_offset) {
running = importNextEntry(mmapped.get(), current_page_.size, &offset);
if (running) {
destination_->current_log_page_offset = offset;
} else {
break;
}
}
}
for (auto& stream : destination_->streams) {
if (stream.pages_.size() > 0) {
countPageUsedBytes(stream.pages_.back());
}
}
}
bool LogReader::importNextEntry(
const PageManager::PageRef* mmapped,
size_t mmaped_size,
size_t* offset) {
size_t header_size = sizeof(Log::EntryHeader);
if (*offset + header_size >= mmaped_size) {
return false;
}
auto entry_header = mmapped->structAt<Log::EntryHeader>(*offset);
size_t entry_size = header_size + entry_header->size;
if (entry_header->size == 0 || *offset + entry_size >= mmaped_size) {
return false;
}
if (entry_header->checksum != entry_header->computeChecksum()) {
fprintf(stderr, "warning: invalid checksum for log entry 0x%" PRIx64 "\n",
mmapped->page_.offset + *offset);
return false;
}
*offset += entry_size;
importLogEntry(entry_header);
return true;
}
void LogReader::importLogEntry(const Log::EntryHeader* entry) {
switch (entry->type) {
case Log::PAGE_ALLOC_ENTRY: {
auto alloc_entry = (Log::PageAllocEntry *) entry;
auto iter = streams_.find(alloc_entry->stream_id);
LogSnapshot::StreamState* stream_state;
if (iter == streams_.end()) {
destination_->streams.emplace_back(alloc_entry->stream_id);
stream_state = &destination_->streams.back();
streams_[alloc_entry->stream_id] = stream_state;
size_t key_len = alloc_entry->hdr.size -
(sizeof(Log::PageAllocEntry) - sizeof(Log::EntryHeader));
stream_state->stream_key_.insert(0, alloc_entry->stream_key, key_len);
if (alloc_entry->stream_id > destination_->max_stream_id) {
destination_->max_stream_id = alloc_entry->stream_id;
}
} else {
stream_state = iter->second;
}
PageManager::Page page;
page.offset = alloc_entry->page_offset;
page.size = alloc_entry->page_size;
auto alloc = new PageAlloc(page, alloc_entry->page_first_row_time);
stream_state->pages_.push_back(std::shared_ptr<PageAlloc>(alloc));
setLastUsedByte(page.offset + page.size);
break;
}
case Log::PAGE_FINISH_ENTRY: {
auto finish_entry = (Log::PageFinishEntry *) entry;
auto iter = streams_.find(finish_entry->stream_id);
if (iter != streams_.end()) {
auto stream_state = iter->second;
if (stream_state->pages_.back()->page_.offset ==
finish_entry->page_offset) {
stream_state->pages_.back()->used_ = finish_entry->page_used;
break;
}
}
fprintf(stderr, "warning: unexpected PAGE_FINISH log entry\n");
break;
}
case Log::NEXT_PAGE_ENTRY: {
auto next_entry = (Log::NextPageEntry *) entry;
current_page_.offset = next_entry->page_offset;
current_page_.size = next_entry->page_size;
setLastUsedByte(current_page_.offset + current_page_.size);
break;
}
default:
fprintf(stderr, "warning: invalid log entry type %i\n", entry->type);
};
}
void LogReader::countPageUsedBytes(std::shared_ptr<PageAlloc> page) {
size_t offset = 0;
size_t max = page->page_.size - sizeof(Log::EntryHeader) - 1;
auto mmapped = page_manager_->getPage(page->page_);
while (offset < max) {
auto row = mmapped->structAt<RowHeader>(offset);
auto row_size = sizeof(RowHeader) + row->size;
if (row->size == 0 || row->time == 0) {
return;
}
if (offset + row_size >= page->page_.size) {
return;
}
if (row->checksum != row->computeChecksum()) {
return;
}
offset += row_size;
page->used_ = offset;
}
}
void LogReader::setLastUsedByte(uint64_t index) {
if (index > destination_->last_used_byte) {
destination_->last_used_byte = index;
}
}
const uint64_t Log::kMinLogPageSize = 512;
Log::Log(
const LogSnapshot& snapshot,
std::shared_ptr<PageManager> page_manager) :
page_manager_(page_manager),
current_page_(snapshot.current_log_page),
current_page_offset_(snapshot.current_log_page_offset) {}
Log::Log(
const PageManager::Page& first_log_page,
std::shared_ptr<PageManager> page_manager) :
page_manager_(page_manager),
current_page_(first_log_page),
current_page_offset_(0) {}
void Log::appendEntry(Log::PageAllocEntry entry) {
entry.hdr.size = sizeof(PageAllocEntry) - sizeof(EntryHeader);
entry.hdr.type = PAGE_ALLOC_ENTRY;
appendEntry((uint8_t *) &entry, sizeof(PageAllocEntry));
}
void Log::appendEntry(Log::PageAllocEntry entry, const std::string& stream_key) {
assert(stream_key.size() < 0xffff);
entry.hdr.size = sizeof(PageAllocEntry) - sizeof(EntryHeader);
entry.hdr.size += stream_key.size();
entry.hdr.type = PAGE_ALLOC_ENTRY;
size_t tmp_len = sizeof(PageAllocEntry) + stream_key.size();
uint8_t* tmp = (uint8_t *) malloc(tmp_len);
assert(tmp);
memcpy(tmp, &entry, sizeof(PageAllocEntry));
memcpy(tmp + sizeof(PageAllocEntry), stream_key.c_str(), stream_key.size());
appendEntry(tmp, tmp_len);
free(tmp);
}
void Log::appendEntry(Log::PageFinishEntry entry) {
entry.hdr.size = sizeof(PageFinishEntry) - sizeof(EntryHeader);
entry.hdr.type = PAGE_FINISH_ENTRY;
appendEntry((uint8_t *) &entry, sizeof(PageFinishEntry));
}
void Log::appendEntry(Log::PageFreeEntry entry) {
entry.hdr.size = sizeof(PageFreeEntry) - sizeof(EntryHeader);
entry.hdr.type = PAGE_FREE_ENTRY;
appendEntry((uint8_t *) &entry, sizeof(PageFreeEntry));
}
// FIXPAUL lock!
void Log::appendEntry(uint8_t* data, size_t length) {
uint64_t reserved_length = length + sizeof(Log::NextPageEntry);
/* allocate a new page if the current one is full */
if (current_page_offset_ + reserved_length >= current_page_.size) {
assert(current_page_offset_ + sizeof(Log::NextPageEntry) <=
current_page_.size);
auto next_page_size = std::max(kMinLogPageSize, reserved_length);
auto next_page = page_manager_->allocPage(next_page_size);
Log::NextPageEntry log_entry;
log_entry.page_offset = next_page.offset;
log_entry.page_size = next_page.size;
log_entry.hdr.size = sizeof(Log::NextPageEntry) - sizeof(Log::EntryHeader);
log_entry.hdr.type = NEXT_PAGE_ENTRY;
log_entry.hdr.checksum = log_entry.hdr.computeChecksum();
auto mmaped = page_manager_->getPage(current_page_);
auto dst = mmaped->structAt<char>(current_page_offset_);
memcpy(dst, (char *) &log_entry, sizeof(Log::NextPageEntry));
current_page_offset_ += sizeof(Log::NextPageEntry);
current_page_ = next_page;
current_page_offset_ = 0;
}
/* memcpy the entry into the current page */
auto entry = (Log::EntryHeader*) data;
entry->checksum = entry->computeChecksum();
auto mmaped = page_manager_->getPage(current_page_);
auto dst = mmaped->structAt<char>(current_page_offset_);
memcpy(dst, data, length);
current_page_offset_ += length;
// FIXPAUL msync
}
uint32_t Log::EntryHeader::computeChecksum() {
FNV<uint32_t> fnv;
return fnv.hash(
(uint8_t *) (((char* ) this) + sizeof(checksum)),
size + sizeof(EntryHeader) - sizeof(checksum));
}
LogSnapshot::LogSnapshot() : max_stream_id(0) {}
LogSnapshot::StreamState::StreamState(uint32_t stream_id) :
stream_id_(stream_id) {}
}
}
<|endoftext|>
|
<commit_before>//
// main.cpp
// NetworksProject
//
// Created by Patrick Dang-Ho on 2017-03-12.
// Copyright © 2017 Patrick Dang-Ho. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
<commit_msg>delete original main.cpp from task 4 folder<commit_after><|endoftext|>
|
<commit_before>#include "scope.h"
#include <yuni/core/noncopyable.h>
#include "details/utils/check-for-valid-identifier-name.h"
#include "details/grammar/nany.h"
#include "details/ast/ast.h"
using namespace Yuni;
namespace ny {
namespace ir {
namespace Producer {
namespace {
struct AttributeContext final {
AttributeContext(AST::Node& node)
: storage{std::make_unique<Attributes>(node)}
, attributes(*storage)
{}
ShortString32 name;
ShortString32 value;
std::unique_ptr<Attributes> storage;
Attributes& attributes;
};
} // namespace
bool Scope::fetchAttributes(AST::Node& node) {
assert(node.rule == AST::rgAttributes);
AttributeContext ctx{node};
for (auto& child : node.children) {
// checking for node type
if (unlikely(child.rule != AST::rgAttributesParameter))
return unexpectedNode(child, "invalid node, not attribute parameter");
AST::Node* nodevalue;
switch (child.children.size()) {
case 1:
nodevalue = nullptr;
break;
case 2:
nodevalue = &(child.children[1]);
break;
default:
return unexpectedNode(child, "invalid attribute parameter node");
}
AST::Node& nodekey = child.children[0];
if (unlikely(nodekey.rule != AST::rgEntity))
return unexpectedNode(child, "invalid attribute parameter name type");
if (nodevalue) {
if (unlikely(nodevalue->rule != AST::rgEntity))
return (error(child) << "unsupported expression for attribute ctx.value");
}
ctx.name.clear();
ctx.value.clear();
if (not AST::appendEntityAsString(ctx.name, nodekey))
return unexpectedNode(child, "invalid entity");
switch (ctx.name[0]) {
case 'n': {
if (ctx.name == "nodiscard") {
if (unlikely(nodevalue))
return (error(child) << "no ctx.value expected for attribute '" << ctx.name << '\'');
break;
}
}
// [[fallthru]]
case 'p': {
if (ctx.name == "per") {
if (unlikely(!nodevalue))
return (error(child) << "ctx.value expected for attribute '" << ctx.name << '\'');
AST::appendEntityAsString(ctx.value, *nodevalue);
if (ctx.value == "thread")
warning(child) << "ignored attribute 'per: thread'";
else if (ctx.value == "process")
warning(child) << "ignored attribute 'per: process'";
else
return (error(child) << "invalid 'per' ctx.value");
break;
}
}
// [[fallthru]]
case 's': {
if (ctx.name == "nosuggest") {
ctx.attributes.flags += Attributes::Flag::doNotSuggest;
if (unlikely(nodevalue))
return (error(child) << "the attribute '" << ctx.name << "' does not accept ctx.values");
break;
}
}
// [[fallthru]]
case 't': {
if (ctx.name == "threadproc") {
ctx.attributes.flags += Attributes::Flag::threadproc;
if (unlikely(nodevalue))
return (error(child) << "the attribute '" << ctx.name << "' does not accept ctx.values");
break;
}
}
// [[fallthru]]
case '_': {
if (ctx.name == "__nanyc_builtinalias") {
if (unlikely(!nodevalue))
return (error(child) << "ctx.value expected for attribute '" << ctx.name << '\'');
ctx.attributes.builtinAlias = nodevalue;
ctx.attributes.flags += Attributes::Flag::builtinAlias;
break;
}
if (ctx.name == "__nanyc_shortcircuit") {
if (unlikely(!nodevalue))
return (error(child) << "ctx.value expected for attribute '" << ctx.name << '\'');
AST::appendEntityAsString(ctx.value, *nodevalue);
bool isTrue = (ctx.value == "__true");
if (not isTrue and (ctx.value.empty() or ctx.value != "__false")) {
error(child.children[1]) << "invalid shortcircuit ctx.value, expected '__false' or '__true', got '"
<< ctx.value << "'";
return false;
}
if (isTrue)
ctx.attributes.flags += Attributes::Flag::shortcircuit;
break;
}
if (ctx.name == "__nanyc_synthetic") {
ctx.attributes.flags += Attributes::Flag::pushSynthetic;
if (unlikely(nodevalue))
return (error(child) << "the attribute '" << ctx.name << "' does not accept ctx.values");
break;
}
// [FALLBACK]
// ignore vendor specific attributes (starting by '__')
if (ctx.name.size() > 2 and ctx.name[1] == '_') {
// emit a warning for the unsupported specific nany attributes
if (unlikely(ctx.name.startsWith("__nanyc_")))
warning(child) << "unknown nanyc attribute '" << ctx.name << "'";
break;
}
}
// [[fallthru]]
default: {
error(child) << "unknown attribute '" << ctx.name << '\'';
return false;
}
}
}
attributes = std::move(ctx.storage);
return true;
}
} // namespace Producer
} // namespace ir
} // namespace ny
<commit_msg>ast2ir: attributes: use exception for unexpected nodes<commit_after>#include "scope.h"
#include <yuni/core/noncopyable.h>
#include "details/utils/check-for-valid-identifier-name.h"
#include "details/grammar/nany.h"
#include "details/ast/ast.h"
#include "exception.h"
using namespace Yuni;
namespace ny {
namespace ir {
namespace Producer {
namespace {
struct AttributeContext final {
AttributeContext(AST::Node& node)
: storage{std::make_unique<Attributes>(node)}
, attributes(*storage)
{}
ShortString32 name;
ShortString32 value;
std::unique_ptr<Attributes> storage;
Attributes& attributes;
};
} // namespace
bool Scope::fetchAttributes(AST::Node& node) {
assert(node.rule == AST::rgAttributes);
try {
AttributeContext ctx{node};
for (auto& child : node.children) {
// checking for node type
if (unlikely(child.rule != AST::rgAttributesParameter))
throw UnexpectedNode(child, "invalid node, not attribute parameter");
AST::Node* nodevalue;
switch (child.children.size()) {
case 1:
nodevalue = nullptr;
break;
case 2:
nodevalue = &(child.children[1]);
break;
default:
throw UnexpectedNode(child, "invalid attribute parameter node");
}
AST::Node& nodekey = child.children[0];
if (unlikely(nodekey.rule != AST::rgEntity))
throw UnexpectedNode(child, "invalid attribute parameter name type");
if (nodevalue) {
if (unlikely(nodevalue->rule != AST::rgEntity))
return (error(child) << "unsupported expression for attribute ctx.value");
}
ctx.name.clear();
ctx.value.clear();
if (not AST::appendEntityAsString(ctx.name, nodekey))
throw UnexpectedNode(child, "invalid entity");
switch (ctx.name[0]) {
case 'n': {
if (ctx.name == "nodiscard") {
if (unlikely(nodevalue))
return (error(child) << "no ctx.value expected for attribute '" << ctx.name << '\'');
break;
}
}
// [[fallthru]]
case 'p': {
if (ctx.name == "per") {
if (unlikely(!nodevalue))
return (error(child) << "ctx.value expected for attribute '" << ctx.name << '\'');
AST::appendEntityAsString(ctx.value, *nodevalue);
if (ctx.value == "thread")
warning(child) << "ignored attribute 'per: thread'";
else if (ctx.value == "process")
warning(child) << "ignored attribute 'per: process'";
else
return (error(child) << "invalid 'per' ctx.value");
break;
}
}
// [[fallthru]]
case 's': {
if (ctx.name == "nosuggest") {
ctx.attributes.flags += Attributes::Flag::doNotSuggest;
if (unlikely(nodevalue))
return (error(child) << "the attribute '" << ctx.name << "' does not accept ctx.values");
break;
}
}
// [[fallthru]]
case 't': {
if (ctx.name == "threadproc") {
ctx.attributes.flags += Attributes::Flag::threadproc;
if (unlikely(nodevalue))
return (error(child) << "the attribute '" << ctx.name << "' does not accept ctx.values");
break;
}
}
// [[fallthru]]
case '_': {
if (ctx.name == "__nanyc_builtinalias") {
if (unlikely(!nodevalue))
return (error(child) << "ctx.value expected for attribute '" << ctx.name << '\'');
ctx.attributes.builtinAlias = nodevalue;
ctx.attributes.flags += Attributes::Flag::builtinAlias;
break;
}
if (ctx.name == "__nanyc_shortcircuit") {
if (unlikely(!nodevalue))
return (error(child) << "ctx.value expected for attribute '" << ctx.name << '\'');
AST::appendEntityAsString(ctx.value, *nodevalue);
bool isTrue = (ctx.value == "__true");
if (not isTrue and (ctx.value.empty() or ctx.value != "__false")) {
error(child.children[1]) << "invalid shortcircuit ctx.value, expected '__false' or '__true', got '"
<< ctx.value << "'";
return false;
}
if (isTrue)
ctx.attributes.flags += Attributes::Flag::shortcircuit;
break;
}
if (ctx.name == "__nanyc_synthetic") {
ctx.attributes.flags += Attributes::Flag::pushSynthetic;
if (unlikely(nodevalue))
return (error(child) << "the attribute '" << ctx.name << "' does not accept ctx.values");
break;
}
// [FALLBACK]
// ignore vendor specific attributes (starting by '__')
if (ctx.name.size() > 2 and ctx.name[1] == '_') {
// emit a warning for the unsupported specific nany attributes
if (unlikely(ctx.name.startsWith("__nanyc_")))
warning(child) << "unknown nanyc attribute '" << ctx.name << "'";
break;
}
}
// [[fallthru]]
default: {
error(child) << "unknown attribute '" << ctx.name << '\'';
return false;
}
}
}
attributes = std::move(ctx.storage);
return true;
}
catch (const UnexpectedNode& e) {
unexpectedNode(e.node, e.message);
}
return false;
}
} // namespace Producer
} // namespace ir
} // namespace ny
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_FEATURES_IMPL_PPF_H_
#define PCL_FEATURES_IMPL_PPF_H_
#include "pcl/features/ppf.h"
#include <pcl/features/pfh.h>
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PPFEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
/// initialize output container
output.clear ();
output.resize (input_->points.size () * input_->points.size ());
PCL_INFO ("PPFEstimation input size: %u\nOutput PPF size: %u\n",
input_->points.size (), output.size ());
/// compute point pair features for every pair of points in the cloud
for (size_t i = 0; i < input_->points.size (); ++i)
for (size_t j = 0 ; j < input_->points.size (); ++j)
{
PointOutT p;
if (i != j)
{
if (pcl::computePairFeatures (input_->points[i].getVector4fMap (),
normals_->points[i].getNormalVector4fMap (),
input_->points[j].getVector4fMap (),
normals_->points[j].getNormalVector4fMap (),
p.f1, p.f2, p.f3, p.f4))
{
/// calculate alpha_m angle
Eigen::Vector3f model_reference_point = input_->points[i].getVector3fMap (),
model_reference_normal = normals_->points[i].getNormalVector3fMap (),
model_point = input_->points[j].getVector3fMap ();
Eigen::AngleAxisf rotation_mg (acos (model_reference_normal.dot (Eigen::Vector3f::UnitX ())),
model_reference_normal.cross (Eigen::Vector3f::UnitX ()).normalized ());
Eigen::Affine3f transform_mg = Eigen::Translation3f ( rotation_mg * ((-1) * model_reference_point)) * rotation_mg;
p.alpha_m = acos (Eigen::Vector3f::UnitY ().dot ((transform_mg * model_point).normalized ()));
}
else
{
PCL_ERROR ("Computing pair feature vector between points %zu and %zu went wrong.\n", i, j);
p.f1 = p.f2 = p.f3 = p.f4 = p.alpha_m = 0.0;
}
}
/// do not calculate the feature for identity pairs (i, i) as they are not used
/// in the following computations
else
p.f1 = p.f2 = p.f3 = p.f4 = p.alpha_m = 0.0;
output.points[i*input_->points.size () + j] = p;
}
}
#define PCL_INSTANTIATE_PPFEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PPFEstimation<T,NT,OutT>;
#endif // PCL_FEATURES_IMPL_PPF_H_
<commit_msg>removed info message<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_FEATURES_IMPL_PPF_H_
#define PCL_FEATURES_IMPL_PPF_H_
#include "pcl/features/ppf.h"
#include <pcl/features/pfh.h>
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PPFEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
/// initialize output container
output.clear ();
output.resize (input_->points.size () * input_->points.size ());
/// compute point pair features for every pair of points in the cloud
for (size_t i = 0; i < input_->points.size (); ++i)
for (size_t j = 0 ; j < input_->points.size (); ++j)
{
PointOutT p;
if (i != j)
{
if (pcl::computePairFeatures (input_->points[i].getVector4fMap (),
normals_->points[i].getNormalVector4fMap (),
input_->points[j].getVector4fMap (),
normals_->points[j].getNormalVector4fMap (),
p.f1, p.f2, p.f3, p.f4))
{
/// calculate alpha_m angle
Eigen::Vector3f model_reference_point = input_->points[i].getVector3fMap (),
model_reference_normal = normals_->points[i].getNormalVector3fMap (),
model_point = input_->points[j].getVector3fMap ();
Eigen::AngleAxisf rotation_mg (acos (model_reference_normal.dot (Eigen::Vector3f::UnitX ())),
model_reference_normal.cross (Eigen::Vector3f::UnitX ()).normalized ());
Eigen::Affine3f transform_mg = Eigen::Translation3f ( rotation_mg * ((-1) * model_reference_point)) * rotation_mg;
p.alpha_m = acos (Eigen::Vector3f::UnitY ().dot ((transform_mg * model_point).normalized ()));
}
else
{
PCL_ERROR ("Computing pair feature vector between points %zu and %zu went wrong.\n", i, j);
p.f1 = p.f2 = p.f3 = p.f4 = p.alpha_m = 0.0;
}
}
/// do not calculate the feature for identity pairs (i, i) as they are not used
/// in the following computations
else
p.f1 = p.f2 = p.f3 = p.f4 = p.alpha_m = 0.0;
output.points[i*input_->points.size () + j] = p;
}
}
#define PCL_INSTANTIATE_PPFEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PPFEstimation<T,NT,OutT>;
#endif // PCL_FEATURES_IMPL_PPF_H_
<|endoftext|>
|
<commit_before>//
// BackCurl.cpp
// Created by Taymindis Woon on 23/5/17.
// Copyright © 2017 Taymindis Woon. All rights reserved.
//
#include "BackCurl.h"
namespace bcl {
/** If you activate mainLoopCallBack, please make sure bcl::LoopBackFire on the loop thread, for e.g. UI thread **/
void init() {
curl_global_init(CURL_GLOBAL_ALL);
}
void LoopBackFire() {
while (!internal::_mainLoopTasks.empty()) {
auto task(std::move(internal::_mainLoopTasks.front()));
internal::_mainLoopTasks.pop_front();
// lock during the task?
internal::_tasks_mutex.lock();
task();
internal::_tasks_mutex.unlock();
}
}
bool isReady(FutureResponse const& f) {
return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
/*
You should call curl_global_cleanup once for each call you make to curl_global_init, after you are done using libcurl.
This function is not thread safe. You must not call it when any other thread in the program (i.e. a thread sharing the same memory) is running.
This doesn't just mean no other thread that is using libcurl. Because curl_global_cleanup calls functions of other libraries
that are similarly thread unsafe, it could conflict with any other thread that uses these other libraries.
*/
void cleanUp() {
curl_global_cleanup();
}
// For image purpose
size_t
writeByteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
MemoryByte *memBlock = (MemoryByte *)userp;
memBlock->append((unsigned char*)contents, realsize);
return realsize;
}
// For Content
size_t
writeContentCallback(void *contents, size_t size, size_t nmemb, void *contentWrapper) {
size_t realsize = size * nmemb;
std::string *memBlock = (std::string *)contentWrapper;
memBlock->append((char*)contents, realsize);
return realsize;
}
namespace internal {
std::deque<std::function<void()>> _mainLoopTasks;
std::mutex _tasks_mutex;
bool _hasMainLoopCallBack = false;
void BackCurlLoopCallBackChecker(bcl::Response &s) {
_hasMainLoopCallBack = true;
}
void wrapResponse(bcl::Request &r, bcl::Response &resp) {
curl_easy_getinfo(r.curl, CURLINFO_RESPONSE_CODE, &resp.code);
curl_easy_getinfo(r.curl, CURLINFO_TOTAL_TIME, &resp.totalTime);
char *url = NULL;
curl_easy_getinfo(r.curl, CURLINFO_EFFECTIVE_URL, &url);
if (url)
resp.effectiveUrl = std::string(url);
char *ct = NULL;
curl_easy_getinfo(r.curl, CURLINFO_CONTENT_TYPE, &ct);
if (ct)
resp.contentType = std::string(ct);
resp.__body = r.dataPtr;
resp.curl = r.curl;
}
/*** comment this pattern for that you can return bahavior right this **/
// template <typename DataType>
// auto __execute__(std::function<void(bcl::Request &req)> optsFilter, std::function<void(bcl::Response)> respFilter, CALL_TYPE,
// DataType &chunk) -> Response<decltype(chunk)>
void __execute__(std::function<void(bcl::Request &req)> optsFilter, std::function<void(bcl::Response &resp)> responseCallback,
internal::CALL_TYPE callType, Request &request, Response &response) {
CURLcode curlCode;
curl_slist *headersList = NULL;
// curl_global_init(CURL_GLOBAL_ALL);
// Response response;
response.__streamRef = new int;
(*response.__streamRef)++;
/* init the curl session */
request.curl = curl_easy_init();
try {
/***ROOT CAUSE MESSAGE***/
if ((curlCode = curl_easy_setopt(request.curl, CURLOPT_ERRORBUFFER, request.errorBuffer)) != CURLE_OK) {
fprintf(stderr, "Failed to set error buffer [%d]\n", curlCode);
throw request.errorBuffer;
}
optsFilter(request);
bcl::Headers &headers = request.headers;
if (headers.size() > 0) {
for (size_t i = 0; i < headers.size(); ++i)
headersList = curl_slist_append(headersList, (headers.at(i).first + ": " + headers.at(i).second).c_str());
if (curl_easy_setopt(request.curl, CURLOPT_HTTPHEADER, headersList) != CURLE_OK) {
fprintf(stderr, "Failed to set headers params [%s]\n", request.errorBuffer);
throw request.errorBuffer;
}
}
/* get it! and check for errors*/
if (curl_easy_perform(request.curl) != CURLE_OK) {
throw request.errorBuffer;
}
} catch (char const* err) {
response.error = std::string(err);
} catch (std::exception& e) {
}
bcl::internal::wrapResponse(request, response);
if (callType == internal::ASYNC_CALL) {
(*response.__streamRef) += 2; // Expected will destruct 2 more time
responseCallback(response);
// response.close(); temporary close as Response bundle will close smartly
} else if (callType == internal::MAIN_LOOP_CALLBACK) {
(*response.__streamRef) += 2; // Expected will destruct 2 more time
std::function<void()> task(std::bind(responseCallback, response));
{
std::lock_guard<std::mutex> lock(_tasks_mutex);
_mainLoopTasks.push_back(std::move(task));
}
} else {
responseCallback(response);
// response.close(); temporary close
}
if (headersList) {
curl_slist_free_all(headersList);
}
/* cleanup curl stuff */
// curl_easy_cleanup(request.curl); // Resp will clean up
// Not needed, all will be free when out of scope
// SDL_free(chunk.memory);
// chunk.erase(chunk.begin());
/* we're done with libcurl, so clean it up */
// curl_global_cleanup(); // TODO should we free every time??
}
}
// ** Response Bundle ** /
bcl::Response::Response() {
curl = NULL;
__streamRef = NULL;
__body = NULL;
}
void bcl::Response::close() {
// delete static_cast<std::remove_pointer<decltype(body)*>::type>(body); //best solution so far
streamClose(__body);
delete __streamRef;
// printf("address of CURL is %p\n", curl);
curl_easy_cleanup(curl); // TODO please implement clean up curl later by using valgrind got error or not
__streamRef = NULL;
__body = NULL;
}
Response& bcl::Response::operator = (const Response& r)
{
// Assignment operator
if (this != &r) // Avoid self assignment
{
// Decrement the old reference count
// if reference become zero delete the old data¢
if (__streamRef != NULL && --(*__streamRef) == 0)
{
close();
}
// Copy the data and reference pointer
// and increment the reference count
__body = r.__body;
__streamRef = r.__streamRef;
curl = r.curl;
(*__streamRef)++;
}
return *this;
}
std::function<void(void*)>& bcl::Response::attachStreamClose() {
return streamClose;
}
bcl::Response::~Response () {
if (__streamRef != NULL && --(*__streamRef) == 0) {
close();
}
}
}
// Test Scope ------------------------------------------------------------------
// void simpleGetOption(bcl::Request &req) {
// bcl::setOpts(req, CURLOPT_URL , "http://www.google.com",
// CURLOPT_FOLLOWLOCATION, 1L,
// CURLOPT_WRITEFUNCTION, &bcl::writeContentCallback,
// CURLOPT_WRITEDATA, req.dataPtr,
// CURLOPT_USERAGENT, "libcurl-agent/1.0",
// CURLOPT_RANGE, "0-200000"
// );
// }
// void doSync() {
// bcl::execute<std::string>(simpleGetOption, [&](bcl::Response & resp) {
// std::string ret = std::string(resp.getBody<std::string>()->c_str());
// printf("Sync === %s\n", ret.c_str());
// // return ret;
// // std::this_thread::sleep_for(std::chrono::milliseconds(500));
// return resp;
// });
// }
// void doFuture() {
// bcl::FutureResponse frp;
// frp = bcl::execFuture<std::string>(simpleGetOption);
// while(bcl::hasRequestedButNotReady(frp)) {
// printf("Future Sync ==%s\n", "Drawing Graphiccccc");
// }
// bcl::Response r = frp.get();
// printf("The data content is = %s\n", r.getBody<std::string>()->c_str());
// printf("Got Http Status code = %ld\n", r.code);
// printf("Got Error = %s\n", r.error.c_str());
// if(!bcl::isProcessing(frp)) printf("no data process now, no more coming data\n\n" );
// }
// int countUI = 0;
// void doGuiWork() {
// printf("%s", "Drawing thousand Pieces of Color ");
// countUI++;
// }
// void doUpdate() {
// bcl::LoopBackFire();
// }
// void doRunOnUI () {
// bool gui_running = true;
// std::cout << "Game is running thread: ";
// bcl::executeOnUI<std::string>([](bcl::Request & req) -> void {
// bcl::setOpts(req, CURLOPT_URL , "http://www.google.com",
// CURLOPT_FOLLOWLOCATION, 1L,
// CURLOPT_WRITEFUNCTION, &bcl::writeContentCallback,
// CURLOPT_WRITEDATA, req.dataPtr,
// CURLOPT_USERAGENT, "libcurl-agent/1.0",
// CURLOPT_RANGE, "0-200000"
// );
// }, [&](bcl::Response & resp) {
// printf("On UI === %s\n", resp.getBody<std::string>()->c_str());
// printf("Done , stop gui running with count ui %d\n", countUI );
// std::this_thread::sleep_for(std::chrono::milliseconds(500));
// gui_running = false;
// });
// while (gui_running) {
// doGuiWork();
// doUpdate();
// std::this_thread::sleep_for(std::chrono::milliseconds(1000 / 16));
// }
// }
// int main()
// {
// bcl::init();
// doSync();
// // doRunOnUI();
// bcl::cleanUp();
// return 1;
// }
<commit_msg>Fixed the uninitialized value<commit_after>//
// BackCurl.cpp
// Created by Taymindis Woon on 23/5/17.
// Copyright © 2017 Taymindis Woon. All rights reserved.
//
#include "BackCurl.h"
namespace bcl {
/** If you activate mainLoopCallBack, please make sure bcl::LoopBackFire on the loop thread, for e.g. UI thread **/
void init() {
curl_global_init(CURL_GLOBAL_ALL);
}
void LoopBackFire() {
while (!internal::_mainLoopTasks.empty()) {
auto task(std::move(internal::_mainLoopTasks.front()));
internal::_mainLoopTasks.pop_front();
// lock during the task?
internal::_tasks_mutex.lock();
task();
internal::_tasks_mutex.unlock();
}
}
bool isReady(FutureResponse const& f) {
return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
/*
You should call curl_global_cleanup once for each call you make to curl_global_init, after you are done using libcurl.
This function is not thread safe. You must not call it when any other thread in the program (i.e. a thread sharing the same memory) is running.
This doesn't just mean no other thread that is using libcurl. Because curl_global_cleanup calls functions of other libraries
that are similarly thread unsafe, it could conflict with any other thread that uses these other libraries.
*/
void cleanUp() {
curl_global_cleanup();
}
// For image purpose
size_t
writeByteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
MemoryByte *memBlock = (MemoryByte *)userp;
memBlock->append((unsigned char*)contents, realsize);
return realsize;
}
// For Content
size_t
writeContentCallback(void *contents, size_t size, size_t nmemb, void *contentWrapper) {
size_t realsize = size * nmemb;
std::string *memBlock = (std::string *)contentWrapper;
memBlock->append((char*)contents, realsize);
return realsize;
}
namespace internal {
std::deque<std::function<void()>> _mainLoopTasks;
std::mutex _tasks_mutex;
bool _hasMainLoopCallBack = false;
void BackCurlLoopCallBackChecker(bcl::Response &s) {
_hasMainLoopCallBack = true;
}
void wrapResponse(bcl::Request &r, bcl::Response &resp) {
curl_easy_getinfo(r.curl, CURLINFO_RESPONSE_CODE, &resp.code);
curl_easy_getinfo(r.curl, CURLINFO_TOTAL_TIME, &resp.totalTime);
char *url = NULL;
curl_easy_getinfo(r.curl, CURLINFO_EFFECTIVE_URL, &url);
if (url)
resp.effectiveUrl = std::string(url);
char *ct = NULL;
curl_easy_getinfo(r.curl, CURLINFO_CONTENT_TYPE, &ct);
if (ct)
resp.contentType = std::string(ct);
resp.__body = r.dataPtr;
resp.curl = r.curl;
}
/*** comment this pattern for that you can return bahavior right this **/
// template <typename DataType>
// auto __execute__(std::function<void(bcl::Request &req)> optsFilter, std::function<void(bcl::Response)> respFilter, CALL_TYPE,
// DataType &chunk) -> Response<decltype(chunk)>
void __execute__(std::function<void(bcl::Request &req)> optsFilter, std::function<void(bcl::Response &resp)> responseCallback,
internal::CALL_TYPE callType, Request &request, Response &response) {
CURLcode curlCode;
curl_slist *headersList = NULL;
// curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
request.curl = curl_easy_init();
try {
/***ROOT CAUSE MESSAGE***/
if ((curlCode = curl_easy_setopt(request.curl, CURLOPT_ERRORBUFFER, request.errorBuffer)) != CURLE_OK) {
fprintf(stderr, "Failed to set error buffer [%d]\n", curlCode);
throw request.errorBuffer;
}
optsFilter(request);
bcl::Headers &headers = request.headers;
if (headers.size() > 0) {
for (size_t i = 0; i < headers.size(); ++i)
headersList = curl_slist_append(headersList, (headers.at(i).first + ": " + headers.at(i).second).c_str());
if (curl_easy_setopt(request.curl, CURLOPT_HTTPHEADER, headersList) != CURLE_OK) {
fprintf(stderr, "Failed to set headers params [%s]\n", request.errorBuffer);
throw request.errorBuffer;
}
}
/* get it! and check for errors*/
if (curl_easy_perform(request.curl) != CURLE_OK) {
throw request.errorBuffer;
}
} catch (char const* err) {
response.error = std::string(err);
} catch (std::exception& e) {
}
bcl::internal::wrapResponse(request, response);
if (callType == internal::ASYNC_CALL) {
(*response.__streamRef) += 2; // Expected will destruct 2 more time
responseCallback(response);
// response.close(); temporary close as Response bundle will close smartly
} else if (callType == internal::MAIN_LOOP_CALLBACK) {
(*response.__streamRef) += 2; // Expected will destruct 2 more time
std::function<void()> task(std::bind(responseCallback, response));
{
std::lock_guard<std::mutex> lock(_tasks_mutex);
_mainLoopTasks.push_back(std::move(task));
}
} else {
responseCallback(response);
// response.close(); temporary close
}
if (headersList) {
curl_slist_free_all(headersList);
}
/* cleanup curl stuff */
// curl_easy_cleanup(request.curl); // Resp will clean up
// Not needed, all will be free when out of scope
// SDL_free(chunk.memory);
// chunk.erase(chunk.begin());
/* we're done with libcurl, so clean it up */
// curl_global_cleanup(); // TODO should we free every time??
}
}
// ** Response Bundle ** /
bcl::Response::Response() {
curl = NULL;
__streamRef = new int(1);
__body = NULL;
}
void bcl::Response::close() {
// delete static_cast<std::remove_pointer<decltype(body)*>::type>(body); //best solution so far
if (__body)
streamClose(__body);
delete __streamRef;
// printf("address of CURL is %p\n", curl);
if (curl)
curl_easy_cleanup(curl); // TODO please implement clean up curl later by using valgrind got error or not
__streamRef = NULL;
__body = NULL;
}
Response& bcl::Response::operator = (const Response& r)
{
// Assignment operator
if (this != &r) // Avoid self assignment
{
// Decrement the old reference count
// if reference become zero delete the old data¢
if (__streamRef != NULL && --(*__streamRef) == 0)
{
close();
}
// Copy the data and reference pointer
// and increment the reference count
__body = r.__body;
__streamRef = r.__streamRef;
curl = r.curl;
(*__streamRef)++;
}
return *this;
}
std::function<void(void*)>& bcl::Response::attachStreamClose() {
return streamClose;
}
bcl::Response::~Response () {
if (__streamRef != NULL && --(*__streamRef) == 0) {
close();
}
}
}<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_HELPER_KDTREE_INL
#define SOFA_HELPER_KDTREE_INL
#include "kdTree.h"
#include <map>
#include <limits>
#include <set>
#include <iterator>
namespace sofa
{
namespace helper
{
template<class Coord>
void kdTree<Coord>::build(const VecCoord& positions)
{
unsigned int nbp=positions.size();
UIlist list; for(unsigned int i=0; i<nbp; i++) list.push_back(i);
tree.resize(nbp);
firstNode=build(list,(unsigned char)0, positions);
}
template<class Coord>
void kdTree<Coord>::build(const VecCoord& positions, const vector<unsigned int> &ROI)
{
unsigned int nbp=ROI.size();
UIlist list; for(unsigned int i=0; i<nbp; i++) list.push_back(ROI[i]);
tree.resize(nbp);
firstNode=build(list,(unsigned char)0, positions);
}
template<class Coord>
void kdTree<Coord>::print(const unsigned int index)
{
std::cout<<index<<"["<<(int)tree[index].splitdir<<"] "<<tree[index].left<<" "<<tree[index].right<<std::endl;
if(tree[index].left!=index) print(tree[index].left);
if(tree[index].right!=index) print(tree[index].right);
}
template<class Coord>
unsigned int kdTree<Coord>::build(UIlist &list, unsigned char direction, const VecCoord& positions)
{
// detect leaf
if(list.size()==(unsigned int)1)
{
unsigned int index=list.front(); list.pop_front();
tree[index].left=tree[index].right=index;
tree[index].splitdir=direction;
return index;
}
// ordered list of 1D coord
distanceSet q;
UIlist::iterator it;
for(it=list.begin(); it!=list.end(); it++) q.insert( distanceToPoint(positions[*it][direction],*it));
it=list.begin(); for(distanceSetIt sit=q.begin(); sit!=q.end(); sit++) {*it=sit->second; it++;}
// split list in 2
it=list.begin(); advance (it,list.size()/2);
UIlist newlist;
newlist.splice(newlist.begin(),list,list.begin(),it);
// add node
unsigned int index=list.front(); list.pop_front();
tree[index].splitdir=direction;
tree[index].left=tree[index].right=index;
// split children recursively
unsigned char newdirection=direction+1; if(newdirection==dim) newdirection=0;
if(newlist.size()!=0) tree[index].left=build(newlist,newdirection,positions);
if(list.size()!=0) tree[index].right=build(list,newdirection,positions);
// return child index to parent
return index;
}
template<class Coord>
void kdTree<Coord>::closest(distanceSet &cl,const Coord &x, const unsigned int ¤tnode, const VecCoord& positions)
// [zhang94] algorithm
{
Real Dmax;
distanceSetIt it=cl.end();
if(cl.size()==N) { it--; Dmax=it->first; } else Dmax=std::numeric_limits<Real>::max();
unsigned int splitdir=tree[currentnode].splitdir;
Coord pos=positions[currentnode];
Real c1=x[splitdir],c2=pos[splitdir];
if(abs(c1-c2)<=Dmax)
{
Real d=(x-pos).norm();
if(d<Dmax)
{
Dmax=d;
cl.insert(distanceToPoint(d,currentnode));
if(cl.size()>N) {it=cl.end(); it--; cl.erase(it);}
}
}
if(tree[currentnode].left!=currentnode) if(c1-Dmax<c2) closest(cl,x,tree[currentnode].left,positions);
if(tree[currentnode].right!=currentnode) if(c2-Dmax<c1) closest(cl,x,tree[currentnode].right,positions);
}
// slightly improved version of the above, for one point
template<class Coord>
void kdTree<Coord>::closest(distanceToPoint &cl,const Coord &x, const unsigned int ¤tnode, const VecCoord& positions)
{
Real Dmax=cl.first;
unsigned int splitdir=tree[currentnode].splitdir;
Coord pos=positions[currentnode];
Real c1=x[splitdir],c2=pos[splitdir];
if(fabs(c1-c2)<=Dmax)
{
Real d=(x-pos).norm();
if(d<Dmax)
{
Dmax=d;
cl.first=d;
cl.second=currentnode;
}
}
if(tree[currentnode].left!=currentnode) if(c1-Dmax<c2) closest(cl,x,tree[currentnode].left,positions);
if(tree[currentnode].right!=currentnode) if(c2-Dmax<c1) closest(cl,x,tree[currentnode].right,positions);
}
template<class Coord>
void kdTree<Coord>::getNClosest(distanceSet &cl, const Coord &x, const VecCoord& positions, const unsigned int n)
{
N=n;
cl.clear();
closest(cl,x,firstNode,positions);
}
template<class Coord>
unsigned int kdTree<Coord>::getClosest(const Coord &x, const VecCoord& positions)
{
distanceToPoint cl(std::numeric_limits<Real>::max(),firstNode);
closest(cl,x,firstNode,positions);
return cl.second;
}
template<class Coord>
void kdTree<Coord>::getNClosestCached(distanceSet &cl, distanceToPoint &cacheThresh_max, distanceToPoint &cacheThresh_min, Coord &previous_x, const Coord &x, const VecCoord& positions, const unsigned int n)
{
Real dx=(previous_x-x).norm();
if(dx>=cacheThresh_max.first || cl.size()<2)
{
getNClosest(cl,x,positions,n);
distanceSetIt it0=cl.begin(), it1=it0; it1++;
typename distanceSet::reverse_iterator itn=cl.rbegin();
cacheThresh_max.first=((itn->first)-(it0->first))*(Real)0.5; // half distance between first and last closest points
cacheThresh_max.second=itn->second;
cacheThresh_min.first=((it1->first)-(it0->first))*(Real)0.5; // half distance between first and second closest points
cacheThresh_min.second=it0->second;
previous_x=x;
// std::cout<<"not in cache"<<std::endl;
}
else if(dx>=cacheThresh_min.first) // in the cache -> update N-1 distances
{
distanceSet newset;
for(distanceSetIt it=cl.begin(); it!=cl.end(); it++)
if(it->second!=cacheThresh_max.second)
newset.insert(distanceToPoint((positions[it->second]-x).norm(),it->second));
else
newset.insert(distanceToPoint(std::numeric_limits<Real>::max(),it->second));
cl.swap(newset);
// std::cout<<"in cache:"<<std::endl;
}
else // still the same closest point
{
distanceSet newset;
for(distanceSetIt it=cl.begin(); it!=cl.end(); it++)
if(it->second==cacheThresh_min.second)
newset.insert(distanceToPoint((positions[it->second]-x).norm(),it->second));
else
newset.insert(distanceToPoint(std::numeric_limits<Real>::max(),it->second));
cl.swap(newset);
// std::cout<<"same"<<std::endl;
}
}
}
}
#endif
<commit_msg>fix bug in kdtree build using roi<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_HELPER_KDTREE_INL
#define SOFA_HELPER_KDTREE_INL
#include "kdTree.h"
#include <map>
#include <limits>
#include <set>
#include <iterator>
namespace sofa
{
namespace helper
{
template<class Coord>
void kdTree<Coord>::build(const VecCoord& positions)
{
unsigned int nbp=positions.size();
UIlist list; for(unsigned int i=0; i<nbp; i++) list.push_back(i);
tree.resize(nbp);
firstNode=build(list,(unsigned char)0, positions);
}
template<class Coord>
void kdTree<Coord>::build(const VecCoord& positions, const vector<unsigned int> &ROI)
{
unsigned int nbp=ROI.size();
UIlist list; for(unsigned int i=0; i<nbp; i++) list.push_back(ROI[i]);
tree.resize(positions.size());
firstNode=build(list,(unsigned char)0, positions);
}
template<class Coord>
void kdTree<Coord>::print(const unsigned int index)
{
std::cout<<index<<"["<<(int)tree[index].splitdir<<"] "<<tree[index].left<<" "<<tree[index].right<<std::endl;
if(tree[index].left!=index) print(tree[index].left);
if(tree[index].right!=index) print(tree[index].right);
}
template<class Coord>
unsigned int kdTree<Coord>::build(UIlist &list, unsigned char direction, const VecCoord& positions)
{
// detect leaf
if(list.size()==(unsigned int)1)
{
unsigned int index=list.front(); list.pop_front();
tree[index].left=tree[index].right=index;
tree[index].splitdir=direction;
return index;
}
// ordered list of 1D coord
distanceSet q;
UIlist::iterator it;
for(it=list.begin(); it!=list.end(); it++) q.insert( distanceToPoint(positions[*it][direction],*it));
it=list.begin(); for(distanceSetIt sit=q.begin(); sit!=q.end(); sit++) {*it=sit->second; it++;}
// split list in 2
it=list.begin(); advance (it,list.size()/2);
UIlist newlist;
newlist.splice(newlist.begin(),list,list.begin(),it);
// add node
unsigned int index=list.front(); list.pop_front();
tree[index].splitdir=direction;
tree[index].left=tree[index].right=index;
// split children recursively
unsigned char newdirection=direction+1; if(newdirection==dim) newdirection=0;
if(newlist.size()!=0) tree[index].left=build(newlist,newdirection,positions);
if(list.size()!=0) tree[index].right=build(list,newdirection,positions);
// return child index to parent
return index;
}
template<class Coord>
void kdTree<Coord>::closest(distanceSet &cl,const Coord &x, const unsigned int ¤tnode, const VecCoord& positions)
// [zhang94] algorithm
{
Real Dmax;
distanceSetIt it=cl.end();
if(cl.size()==N) { it--; Dmax=it->first; } else Dmax=std::numeric_limits<Real>::max();
unsigned int splitdir=tree[currentnode].splitdir;
Coord pos=positions[currentnode];
Real c1=x[splitdir],c2=pos[splitdir];
if(abs(c1-c2)<=Dmax)
{
Real d=(x-pos).norm();
if(d<Dmax)
{
Dmax=d;
cl.insert(distanceToPoint(d,currentnode));
if(cl.size()>N) {it=cl.end(); it--; cl.erase(it);}
}
}
if(tree[currentnode].left!=currentnode) if(c1-Dmax<c2) closest(cl,x,tree[currentnode].left,positions);
if(tree[currentnode].right!=currentnode) if(c2-Dmax<c1) closest(cl,x,tree[currentnode].right,positions);
}
// slightly improved version of the above, for one point
template<class Coord>
void kdTree<Coord>::closest(distanceToPoint &cl,const Coord &x, const unsigned int ¤tnode, const VecCoord& positions)
{
Real Dmax=cl.first;
unsigned int splitdir=tree[currentnode].splitdir;
Coord pos=positions[currentnode];
Real c1=x[splitdir],c2=pos[splitdir];
if(fabs(c1-c2)<=Dmax)
{
Real d=(x-pos).norm();
if(d<Dmax)
{
Dmax=d;
cl.first=d;
cl.second=currentnode;
}
}
if(tree[currentnode].left!=currentnode) if(c1-Dmax<c2) closest(cl,x,tree[currentnode].left,positions);
if(tree[currentnode].right!=currentnode) if(c2-Dmax<c1) closest(cl,x,tree[currentnode].right,positions);
}
template<class Coord>
void kdTree<Coord>::getNClosest(distanceSet &cl, const Coord &x, const VecCoord& positions, const unsigned int n)
{
N=n;
cl.clear();
closest(cl,x,firstNode,positions);
}
template<class Coord>
unsigned int kdTree<Coord>::getClosest(const Coord &x, const VecCoord& positions)
{
distanceToPoint cl(std::numeric_limits<Real>::max(),firstNode);
closest(cl,x,firstNode,positions);
return cl.second;
}
template<class Coord>
void kdTree<Coord>::getNClosestCached(distanceSet &cl, distanceToPoint &cacheThresh_max, distanceToPoint &cacheThresh_min, Coord &previous_x, const Coord &x, const VecCoord& positions, const unsigned int n)
{
Real dx=(previous_x-x).norm();
if(dx>=cacheThresh_max.first || cl.size()<2)
{
getNClosest(cl,x,positions,n);
distanceSetIt it0=cl.begin(), it1=it0; it1++;
typename distanceSet::reverse_iterator itn=cl.rbegin();
cacheThresh_max.first=((itn->first)-(it0->first))*(Real)0.5; // half distance between first and last closest points
cacheThresh_max.second=itn->second;
cacheThresh_min.first=((it1->first)-(it0->first))*(Real)0.5; // half distance between first and second closest points
cacheThresh_min.second=it0->second;
previous_x=x;
// std::cout<<"not in cache"<<std::endl;
}
else if(dx>=cacheThresh_min.first) // in the cache -> update N-1 distances
{
distanceSet newset;
for(distanceSetIt it=cl.begin(); it!=cl.end(); it++)
if(it->second!=cacheThresh_max.second)
newset.insert(distanceToPoint((positions[it->second]-x).norm(),it->second));
else
newset.insert(distanceToPoint(std::numeric_limits<Real>::max(),it->second));
cl.swap(newset);
// std::cout<<"in cache:"<<std::endl;
}
else // still the same closest point
{
distanceSet newset;
for(distanceSetIt it=cl.begin(); it!=cl.end(); it++)
if(it->second==cacheThresh_min.second)
newset.insert(distanceToPoint((positions[it->second]-x).norm(),it->second));
else
newset.insert(distanceToPoint(std::numeric_limits<Real>::max(),it->second));
cl.swap(newset);
// std::cout<<"same"<<std::endl;
}
}
}
}
#endif
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "errors.hpp"
#include <boost/bind.hpp>
#include "arch/arch.hpp"
#include "serializer/log/log_serializer.hpp"
namespace stress {
#include "../stress-client/utils.hpp"
#include "../stress-client/utils.cc"
#include "../stress-client/random.cc"
}
class timer_token_t;
struct txn_info_t {
ticks_t start, end;
};
typedef std::deque<txn_info_t> log_t;
struct txn_callback_t {
virtual void on_transaction_complete() = 0;
} *cb;
void transact(serializer_t *ser, log_t *log, unsigned inserts, unsigned updates, txn_callback_t *cb) {
/* If there aren't enough blocks to update, then convert the updates into inserts */
std::vector<serializer_write_t> writes;
if (updates > ser->max_block_id()) {
inserts += updates;
updates = 0;
}
/* To save CPU time (from clearing many bufs) we malloc() one buf and clear it and then
write all the blocks from that one. I hope this doesn't bias the test. */
void *dummy_buf = ser->malloc();
memset(dummy_buf, 0xDB, ser->get_block_size().value());
writes.reserve(updates + inserts);
/* As a simple way to avoid updating the same block twice in one transaction, select
a contiguous range of blocks starting at a random offset within range */
block_id_t begin = stress::random(0, ser->max_block_id() - updates);
// We just need some value for this.
repli_timestamp_t tstamp = repli_timestamp_t::distant_past;
for (unsigned i = 0; i < updates; i++) {
writes.push_back(serializer_write_t::make_update(begin + i, tstamp, dummy_buf));
}
/* Generate new IDs to insert by simply taking (highest ID + 1) */
for (unsigned i = 0; i < inserts; i++) {
writes.push_back(serializer_write_t::make_update(ser->max_block_id() + i, tstamp, dummy_buf));
}
do_writes(ser, writes, DEFAULT_DISK_ACCOUNT);
ser->free(dummy_buf);
cb->on_transaction_complete();
}
#define RUN_FOREVER (-1)
struct config_t {
const char *log_file, *tps_log_file;
log_serializer_static_config_t ser_static_config;
log_serializer_dynamic_config_t ser_dynamic_config;
log_serializer_private_dynamic_config_t ser_private_dynamic_config;
int duration; /* Seconds */
unsigned concurrent_txns;
unsigned inserts_per_txn, updates_per_txn;
};
struct tester_t :
public thread_message_t,
public txn_callback_t
{
log_t *log;
FILE *tps_log_fd;
log_serializer_t *ser;
unsigned active_txns, total_txns;
config_t *config;
thread_pool_t *pool;
bool stop, interrupted;
timer_token_t *timer;
ticks_t last_time;
unsigned txns_last_sec;
unsigned secs_so_far;
scoped_ptr_t<io_backender_t> io_backender;
struct interrupt_msg_t :
public thread_message_t
{
tester_t *tester;
interrupt_msg_t(tester_t *tester) : tester(tester) { }
void on_thread_switch() {
fprintf(stderr, "Interrupted.\n");
tester->stop_test();
cancel_timer(tester->timer);
}
} interruptor;
tester_t(config_t *config, thread_pool_t *pool)
: tps_log_fd(NULL), ser(NULL), active_txns(0), total_txns(0), config(config), pool(pool), stop(false), interrupted(false), last_time(0), txns_last_sec(0), secs_so_far(0), interruptor(this)
{
make_io_backender(aio_native, &io_backender);
last_time = get_ticks();
if(config->tps_log_file) {
tps_log_fd = fopen(config->tps_log_file, "a");
}
}
/* When on_thread_switch() is called, it could either be the start message telling us to run the
test or the shutdown message from call_later_on_this_thread(). We differentiate by checking 'ser'. */
void on_thread_switch() {
if (!ser) coro_t::spawn(boost::bind(&tester_t::start, this));
else coro_t::spawn(boost::bind(&tester_t::shutdown, this));
}
void start() {
if (config->log_file) {
log = new log_t();
} else {
log = NULL;
}
fprintf(stderr, "Creating a database...\n");
filepath_file_opener_t file_opener(config->ser_private_dynamic_config.db_filename, io_backender.get());
log_serializer_t::create(&file_opener,
config->ser_static_config);
fprintf(stderr, "Starting serializer...\n");
ser = new log_serializer_t(config->ser_dynamic_config,
&file_opener,
&get_global_perfmon_collection());
on_serializer_ready(ser);
}
void on_serializer_ready(log_serializer_t *ls) {
fprintf(stderr, "Running test...\n");
if(config->duration != RUN_FOREVER) {
timer = fire_timer_once(config->duration * 1000, &tester_t::on_timer, this);
}
linux_thread_message_t *prev_interrupt_message = pool->set_interrupt_message(&interruptor);
guarantee(prev_interrupt_message == NULL);
pump();
}
static void on_timer(void *self) {
tester_t *tester = (tester_t *)self;
fprintf(stderr, "Time's up.\n");
tester->stop_test();
}
void pump() {
while (active_txns < config->concurrent_txns && !stop) {
active_txns++;
total_txns++;
coro_t::spawn_sometime(boost::bind(transact, ser, log, config->inserts_per_txn, config->updates_per_txn, this));
}
// See if we need to report the TPS
ticks_t cur_time = get_ticks();
if(ticks_to_secs(cur_time - last_time) >= 1.0f) {
if(tps_log_fd) {
fprintf(tps_log_fd, "%d\n", txns_last_sec);
}
last_time = cur_time;
txns_last_sec = 0;
secs_so_far++;
// Flush every five seconds in case of a crash
if(secs_so_far % 5 == 0) {
fflush(tps_log_fd);
}
}
if (active_txns == 0 && stop) {
/* Serializer doesn't like shutdown() to be called from within
on_serializer_write_txn() */
call_later_on_this_thread(this);
}
}
void stop_test() {
if (stop) return;
linux_thread_message_t *prev_interrupt_message = pool->set_interrupt_message(NULL);
guarantee(prev_interrupt_message == &interruptor);
fprintf(stderr, "Started %d transactions and completed %d of them\n",
total_txns, total_txns - active_txns);
if (tps_log_fd)
fclose(tps_log_fd);
if (config->log_file) {
FILE *log_file = fopen(config->log_file, "w");
log_t::iterator it;
for (it = log->begin(); it != log->end(); it++) {
fprintf(log_file, "%.6f %.6f\n", ticks_to_secs(it->start), ticks_to_secs(it->end));
}
fclose(log_file);
fprintf(stderr, "Wrote log to '%s'\n", config->log_file);
delete(log);
}
stop = true;
if (active_txns > 0) {
fprintf(stderr, "Waiting for the remaining %d transactions...\n", active_txns);
}
}
void on_transaction_complete() {
active_txns--;
txns_last_sec++;
pump();
}
void shutdown() {
fprintf(stderr, "Waiting for serializer to shut down...\n");
delete ser;
on_serializer_shutdown();
}
void on_serializer_shutdown() {
fprintf(stderr, "Done.\n");
pool->shutdown_thread_pool();
}
};
const char *read_arg(int &argc, char **&argv) {
if (argc == 0) {
fail_due_to_user_error("Expected another argument at the end.");
} else {
argc--;
return (argv++)[0];
}
}
void parse_config(int argc, char *argv[], config_t *config) {
config->ser_private_dynamic_config.db_filename = "rethinkdb_data";
#ifdef SEMANTIC_SERIALIZER_CHECK
config->ser_private_dynamic_config.semantic_filename = "rethinkdb_data.semantic";
#endif
config->log_file = NULL;
config->tps_log_file = NULL;
// config->ser_static_config uses its own defaults from constructor
// config->ser_dynamic_config uses its own defaults from constructor
config->duration = 10; /* Seconds */
config->concurrent_txns = 8;
config->inserts_per_txn = 10;
config->updates_per_txn = 2;
read_arg(argc, argv);
while (argc) {
const char *flag = read_arg(argc, argv);
if (strcmp(flag, "-f") == 0) {
config->ser_private_dynamic_config.db_filename = read_arg(argc, argv);
#ifdef SEMANTIC_SERIALIZER_CHECK
config->ser_private_dynamic_config.semantic_filename = config->ser_private_dynamic_config.db_filename + ".semantic";
#endif
} else if (strcmp(flag, "--log") == 0) {
config->log_file = read_arg(argc, argv);
} else if (strcmp(flag, "--tps-log") == 0) {
config->tps_log_file = read_arg(argc, argv);
} else if (strcmp(flag, "--block-size") == 0) {
config->ser_static_config.block_size_ = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--extent-size") == 0) {
config->ser_static_config.extent_size_ = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--active-data-extents") == 0) {
config->ser_dynamic_config.num_active_data_extents = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--file-zone-size") == 0) {
config->ser_dynamic_config.file_zone_size = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--duration") == 0) {
config->duration = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--forever") == 0) {
config->duration = RUN_FOREVER;
} else if (strcmp(flag, "--concurrent") == 0) {
config->concurrent_txns = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--inserts-per-txn") == 0) {
config->inserts_per_txn = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--updates-per-txn") == 0) {
config->updates_per_txn = atoi(read_arg(argc, argv));
} else {
fail_due_to_user_error("Don't know how to handle \"%s\"", flag);
}
}
rassert(config->ser_static_config.block_size().ser_value() > 0);
rassert(config->ser_static_config.extent_size() > 0);
rassert(config->ser_dynamic_config.num_active_data_extents > 0);
rassert(config->ser_dynamic_config.file_zone_size > 0);
rassert(config->duration > 0 || config->duration == RUN_FOREVER);
rassert(config->concurrent_txns > 0);
}
int main(int argc, char *argv[]) {
config_t config;
parse_config(argc, argv, &config);
thread_pool_t thread_pool(1, true);
tester_t tester(&config, &thread_pool);
thread_pool.run_thread_pool(&tester);
return 0;
}
<commit_msg>Made serializer-bench not use private_dynamic_config_t.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "errors.hpp"
#include <boost/bind.hpp>
#include "arch/arch.hpp"
#include "serializer/log/log_serializer.hpp"
namespace stress {
#include "../stress-client/utils.hpp"
#include "../stress-client/utils.cc"
#include "../stress-client/random.cc"
}
class timer_token_t;
struct txn_info_t {
ticks_t start, end;
};
typedef std::deque<txn_info_t> log_t;
struct txn_callback_t {
virtual void on_transaction_complete() = 0;
} *cb;
void transact(serializer_t *ser, log_t *log, unsigned inserts, unsigned updates, txn_callback_t *cb) {
/* If there aren't enough blocks to update, then convert the updates into inserts */
std::vector<serializer_write_t> writes;
if (updates > ser->max_block_id()) {
inserts += updates;
updates = 0;
}
/* To save CPU time (from clearing many bufs) we malloc() one buf and clear it and then
write all the blocks from that one. I hope this doesn't bias the test. */
void *dummy_buf = ser->malloc();
memset(dummy_buf, 0xDB, ser->get_block_size().value());
writes.reserve(updates + inserts);
/* As a simple way to avoid updating the same block twice in one transaction, select
a contiguous range of blocks starting at a random offset within range */
block_id_t begin = stress::random(0, ser->max_block_id() - updates);
// We just need some value for this.
repli_timestamp_t tstamp = repli_timestamp_t::distant_past;
for (unsigned i = 0; i < updates; i++) {
writes.push_back(serializer_write_t::make_update(begin + i, tstamp, dummy_buf));
}
/* Generate new IDs to insert by simply taking (highest ID + 1) */
for (unsigned i = 0; i < inserts; i++) {
writes.push_back(serializer_write_t::make_update(ser->max_block_id() + i, tstamp, dummy_buf));
}
do_writes(ser, writes, DEFAULT_DISK_ACCOUNT);
ser->free(dummy_buf);
cb->on_transaction_complete();
}
#define RUN_FOREVER (-1)
struct config_t {
const char *log_file, *tps_log_file;
log_serializer_static_config_t ser_static_config;
log_serializer_dynamic_config_t ser_dynamic_config;
std::string db_filename;
int duration; /* Seconds */
unsigned concurrent_txns;
unsigned inserts_per_txn, updates_per_txn;
};
struct tester_t :
public thread_message_t,
public txn_callback_t
{
log_t *log;
FILE *tps_log_fd;
log_serializer_t *ser;
unsigned active_txns, total_txns;
config_t *config;
thread_pool_t *pool;
bool stop, interrupted;
timer_token_t *timer;
ticks_t last_time;
unsigned txns_last_sec;
unsigned secs_so_far;
scoped_ptr_t<io_backender_t> io_backender;
struct interrupt_msg_t :
public thread_message_t
{
tester_t *tester;
interrupt_msg_t(tester_t *tester) : tester(tester) { }
void on_thread_switch() {
fprintf(stderr, "Interrupted.\n");
tester->stop_test();
cancel_timer(tester->timer);
}
} interruptor;
tester_t(config_t *config, thread_pool_t *pool)
: tps_log_fd(NULL), ser(NULL), active_txns(0), total_txns(0), config(config), pool(pool), stop(false), interrupted(false), last_time(0), txns_last_sec(0), secs_so_far(0), interruptor(this)
{
make_io_backender(aio_native, &io_backender);
last_time = get_ticks();
if(config->tps_log_file) {
tps_log_fd = fopen(config->tps_log_file, "a");
}
}
/* When on_thread_switch() is called, it could either be the start message telling us to run the
test or the shutdown message from call_later_on_this_thread(). We differentiate by checking 'ser'. */
void on_thread_switch() {
if (!ser) coro_t::spawn(boost::bind(&tester_t::start, this));
else coro_t::spawn(boost::bind(&tester_t::shutdown, this));
}
void start() {
if (config->log_file) {
log = new log_t();
} else {
log = NULL;
}
fprintf(stderr, "Creating a database...\n");
filepath_file_opener_t file_opener(config->db_filename, io_backender.get());
log_serializer_t::create(&file_opener,
config->ser_static_config);
fprintf(stderr, "Starting serializer...\n");
ser = new log_serializer_t(config->ser_dynamic_config,
&file_opener,
&get_global_perfmon_collection());
on_serializer_ready(ser);
}
void on_serializer_ready(log_serializer_t *ls) {
fprintf(stderr, "Running test...\n");
if(config->duration != RUN_FOREVER) {
timer = fire_timer_once(config->duration * 1000, &tester_t::on_timer, this);
}
linux_thread_message_t *prev_interrupt_message = pool->set_interrupt_message(&interruptor);
guarantee(prev_interrupt_message == NULL);
pump();
}
static void on_timer(void *self) {
tester_t *tester = (tester_t *)self;
fprintf(stderr, "Time's up.\n");
tester->stop_test();
}
void pump() {
while (active_txns < config->concurrent_txns && !stop) {
active_txns++;
total_txns++;
coro_t::spawn_sometime(boost::bind(transact, ser, log, config->inserts_per_txn, config->updates_per_txn, this));
}
// See if we need to report the TPS
ticks_t cur_time = get_ticks();
if(ticks_to_secs(cur_time - last_time) >= 1.0f) {
if(tps_log_fd) {
fprintf(tps_log_fd, "%d\n", txns_last_sec);
}
last_time = cur_time;
txns_last_sec = 0;
secs_so_far++;
// Flush every five seconds in case of a crash
if(secs_so_far % 5 == 0) {
fflush(tps_log_fd);
}
}
if (active_txns == 0 && stop) {
/* Serializer doesn't like shutdown() to be called from within
on_serializer_write_txn() */
call_later_on_this_thread(this);
}
}
void stop_test() {
if (stop) return;
linux_thread_message_t *prev_interrupt_message = pool->set_interrupt_message(NULL);
guarantee(prev_interrupt_message == &interruptor);
fprintf(stderr, "Started %d transactions and completed %d of them\n",
total_txns, total_txns - active_txns);
if (tps_log_fd)
fclose(tps_log_fd);
if (config->log_file) {
FILE *log_file = fopen(config->log_file, "w");
log_t::iterator it;
for (it = log->begin(); it != log->end(); it++) {
fprintf(log_file, "%.6f %.6f\n", ticks_to_secs(it->start), ticks_to_secs(it->end));
}
fclose(log_file);
fprintf(stderr, "Wrote log to '%s'\n", config->log_file);
delete(log);
}
stop = true;
if (active_txns > 0) {
fprintf(stderr, "Waiting for the remaining %d transactions...\n", active_txns);
}
}
void on_transaction_complete() {
active_txns--;
txns_last_sec++;
pump();
}
void shutdown() {
fprintf(stderr, "Waiting for serializer to shut down...\n");
delete ser;
on_serializer_shutdown();
}
void on_serializer_shutdown() {
fprintf(stderr, "Done.\n");
pool->shutdown_thread_pool();
}
};
const char *read_arg(int &argc, char **&argv) {
if (argc == 0) {
fail_due_to_user_error("Expected another argument at the end.");
} else {
argc--;
return (argv++)[0];
}
}
void parse_config(int argc, char *argv[], config_t *config) {
config->db_filename = "rethinkdb_data";
config->log_file = NULL;
config->tps_log_file = NULL;
// config->ser_static_config uses its own defaults from constructor
// config->ser_dynamic_config uses its own defaults from constructor
config->duration = 10; /* Seconds */
config->concurrent_txns = 8;
config->inserts_per_txn = 10;
config->updates_per_txn = 2;
read_arg(argc, argv);
while (argc) {
const char *flag = read_arg(argc, argv);
if (strcmp(flag, "-f") == 0) {
config->db_filename = read_arg(argc, argv);
} else if (strcmp(flag, "--log") == 0) {
config->log_file = read_arg(argc, argv);
} else if (strcmp(flag, "--tps-log") == 0) {
config->tps_log_file = read_arg(argc, argv);
} else if (strcmp(flag, "--block-size") == 0) {
config->ser_static_config.block_size_ = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--extent-size") == 0) {
config->ser_static_config.extent_size_ = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--active-data-extents") == 0) {
config->ser_dynamic_config.num_active_data_extents = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--file-zone-size") == 0) {
config->ser_dynamic_config.file_zone_size = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--duration") == 0) {
config->duration = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--forever") == 0) {
config->duration = RUN_FOREVER;
} else if (strcmp(flag, "--concurrent") == 0) {
config->concurrent_txns = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--inserts-per-txn") == 0) {
config->inserts_per_txn = atoi(read_arg(argc, argv));
} else if (strcmp(flag, "--updates-per-txn") == 0) {
config->updates_per_txn = atoi(read_arg(argc, argv));
} else {
fail_due_to_user_error("Don't know how to handle \"%s\"", flag);
}
}
rassert(config->ser_static_config.block_size().ser_value() > 0);
rassert(config->ser_static_config.extent_size() > 0);
rassert(config->ser_dynamic_config.num_active_data_extents > 0);
rassert(config->ser_dynamic_config.file_zone_size > 0);
rassert(config->duration > 0 || config->duration == RUN_FOREVER);
rassert(config->concurrent_txns > 0);
}
int main(int argc, char *argv[]) {
config_t config;
parse_config(argc, argv, &config);
thread_pool_t thread_pool(1, true);
tester_t tester(&config, &thread_pool);
thread_pool.run_thread_pool(&tester);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Morwenn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <functional>
#include <iterator>
#include <numeric>
#include <random>
#include <type_traits>
#include <utility>
#include <vector>
#include <catch2/catch.hpp>
#include <cpp-sort/sort.h>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/functional.h>
namespace
{
struct tricky_function
{
template<typename T, typename U>
auto operator()(T&& lhs, U&& rhs)
noexcept(noexcept(std::forward<T>(lhs) > std::forward<U>(rhs)))
-> decltype(std::forward<T>(lhs) > std::forward<U>(rhs))
{
// Compare values in reverse order
return std::forward<T>(lhs) > std::forward<U>(rhs);
}
template<typename T>
auto operator()(T&& value) const noexcept
-> decltype(std::forward<T>(value))
{
return std::forward<T>(value);
}
};
enum struct call
{
iterator,
iterable
};
struct comparison_sorter_impl
{
template<
typename Iterator,
typename Compare = std::less<>,
typename = std::enable_if_t<cppsort::is_projection_iterator_v<
cppsort::utility::identity, Iterator, Compare
>>
>
auto operator()(Iterator first, Iterator last, Compare compare={}) const
-> call
{
cppsort::sort(first, last, compare);
return call::iterator;
}
template<
typename Iterable,
typename Compare = std::less<>,
typename = std::enable_if_t<cppsort::is_projection_v<
cppsort::utility::identity, Iterable, Compare
>>
>
auto operator()(Iterable& iterable, Compare compare={}) const
-> call
{
cppsort::sort(iterable, compare);
return call::iterable;
}
};
struct projection_sorter_impl
{
template<
typename Iterator,
typename Projection=cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection_iterator_v<
Projection, Iterator
>>
>
auto operator()(Iterator first, Iterator last, Projection projection={}) const
-> call
{
// Use as_projection to make an actual projection-only sorter
cppsort::sort(first, last, cppsort::utility::as_projection(projection));
return call::iterator;
}
template<
typename Iterable,
typename Projection=cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection_v<
Projection, Iterable
>>
>
auto operator()(Iterable& iterable, Projection projection={}) const
-> call
{
// Use as_projection to make an actual projection-only sorter
cppsort::sort(iterable, cppsort::utility::as_projection(projection));
return call::iterable;
}
};
struct comparison_sorter:
cppsort::sorter_facade<comparison_sorter_impl>
{};
struct projection_sorter:
cppsort::sorter_facade<projection_sorter_impl>
{};
}
TEST_CASE( "sorter_facade with sorters overloaded for iterables and mixed comparison/projection",
"[sorter_facade][compare][projection][as_projection]" )
{
// Test the intersection between mixed comparison/projection functions,
// as_projection, as_comparison and some additional sorter_facade
// overloads
struct wrapper { int value; };
// Collection to sort
std::vector<int> collection(100);
std::iota(std::begin(collection), std::end(collection), 0);
std::mt19937 engine(Catch::rngSeed());
std::shuffle(std::begin(collection), std::end(collection), engine);
auto vec = collection;
tricky_function func;
comparison_sorter comp_sort;
projection_sorter proj_sort;
SECTION( "comparison_sorter" )
{
vec = collection;
auto res1 = cppsort::sort(comp_sort, vec, func);
CHECK( res1 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res2 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec), func);
CHECK( res2 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res3 = cppsort::sort(comp_sort, vec, cppsort::utility::as_comparison(func));
CHECK( res3 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res4 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_comparison(func));
CHECK( res4 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res5 = cppsort::sort(comp_sort, vec, cppsort::utility::as_projection(func));
CHECK( res5 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res6 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_projection(func));
CHECK( res6 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res7 = cppsort::sort(comp_sort, vec, func,
cppsort::utility::as_projection(func));
CHECK( res7 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res8 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec), func,
cppsort::utility::as_projection(func));
CHECK( res8 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res9 = cppsort::sort(comp_sort, vec, cppsort::utility::as_comparison(func),
cppsort::utility::as_projection(func));
CHECK( res9 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res10 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_comparison(func),
cppsort::utility::as_projection(func));
CHECK( res10 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
}
SECTION( "projection_sorter" )
{
vec = collection;
auto res1 = cppsort::sort(proj_sort, vec, cppsort::utility::as_projection(func));
CHECK( res1 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res2 = cppsort::sort(proj_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_projection(func));
CHECK( res2 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res3 = cppsort::sort(proj_sort, vec, func);
CHECK( res3 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res4 = cppsort::sort(proj_sort, std::begin(vec), std::end(vec), func);
CHECK( res4 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
}
}
<commit_msg>Remove redundant lines in test suite<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2020 Morwenn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <functional>
#include <iterator>
#include <numeric>
#include <random>
#include <type_traits>
#include <utility>
#include <vector>
#include <catch2/catch.hpp>
#include <cpp-sort/sort.h>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/functional.h>
namespace
{
struct tricky_function
{
template<typename T, typename U>
auto operator()(T&& lhs, U&& rhs)
noexcept(noexcept(std::forward<T>(lhs) > std::forward<U>(rhs)))
-> decltype(std::forward<T>(lhs) > std::forward<U>(rhs))
{
// Compare values in reverse order
return std::forward<T>(lhs) > std::forward<U>(rhs);
}
template<typename T>
auto operator()(T&& value) const noexcept
-> decltype(std::forward<T>(value))
{
return std::forward<T>(value);
}
};
enum struct call
{
iterator,
iterable
};
struct comparison_sorter_impl
{
template<
typename Iterator,
typename Compare = std::less<>,
typename = std::enable_if_t<cppsort::is_projection_iterator_v<
cppsort::utility::identity, Iterator, Compare
>>
>
auto operator()(Iterator first, Iterator last, Compare compare={}) const
-> call
{
cppsort::sort(first, last, compare);
return call::iterator;
}
template<
typename Iterable,
typename Compare = std::less<>,
typename = std::enable_if_t<cppsort::is_projection_v<
cppsort::utility::identity, Iterable, Compare
>>
>
auto operator()(Iterable& iterable, Compare compare={}) const
-> call
{
cppsort::sort(iterable, compare);
return call::iterable;
}
};
struct projection_sorter_impl
{
template<
typename Iterator,
typename Projection=cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection_iterator_v<
Projection, Iterator
>>
>
auto operator()(Iterator first, Iterator last, Projection projection={}) const
-> call
{
// Use as_projection to make an actual projection-only sorter
cppsort::sort(first, last, cppsort::utility::as_projection(projection));
return call::iterator;
}
template<
typename Iterable,
typename Projection=cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection_v<
Projection, Iterable
>>
>
auto operator()(Iterable& iterable, Projection projection={}) const
-> call
{
// Use as_projection to make an actual projection-only sorter
cppsort::sort(iterable, cppsort::utility::as_projection(projection));
return call::iterable;
}
};
struct comparison_sorter:
cppsort::sorter_facade<comparison_sorter_impl>
{};
struct projection_sorter:
cppsort::sorter_facade<projection_sorter_impl>
{};
}
TEST_CASE( "sorter_facade with sorters overloaded for iterables and mixed comparison/projection",
"[sorter_facade][compare][projection][as_projection]" )
{
// Test the intersection between mixed comparison/projection functions,
// as_projection, as_comparison and some additional sorter_facade
// overloads
// Collection to sort
std::vector<int> collection(100);
std::iota(std::begin(collection), std::end(collection), 0);
std::mt19937 engine(Catch::rngSeed());
std::shuffle(std::begin(collection), std::end(collection), engine);
auto vec = collection;
tricky_function func;
comparison_sorter comp_sort;
projection_sorter proj_sort;
SECTION( "comparison_sorter" )
{
auto res1 = cppsort::sort(comp_sort, vec, func);
CHECK( res1 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res2 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec), func);
CHECK( res2 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res3 = cppsort::sort(comp_sort, vec, cppsort::utility::as_comparison(func));
CHECK( res3 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res4 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_comparison(func));
CHECK( res4 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res5 = cppsort::sort(comp_sort, vec, cppsort::utility::as_projection(func));
CHECK( res5 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res6 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_projection(func));
CHECK( res6 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res7 = cppsort::sort(comp_sort, vec, func,
cppsort::utility::as_projection(func));
CHECK( res7 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res8 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec), func,
cppsort::utility::as_projection(func));
CHECK( res8 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res9 = cppsort::sort(comp_sort, vec, cppsort::utility::as_comparison(func),
cppsort::utility::as_projection(func));
CHECK( res9 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
vec = collection;
auto res10 = cppsort::sort(comp_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_comparison(func),
cppsort::utility::as_projection(func));
CHECK( res10 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) );
}
SECTION( "projection_sorter" )
{
auto res1 = cppsort::sort(proj_sort, vec, cppsort::utility::as_projection(func));
CHECK( res1 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res2 = cppsort::sort(proj_sort, std::begin(vec), std::end(vec),
cppsort::utility::as_projection(func));
CHECK( res2 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res3 = cppsort::sort(proj_sort, vec, func);
CHECK( res3 == call::iterable );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
vec = collection;
auto res4 = cppsort::sort(proj_sort, std::begin(vec), std::end(vec), func);
CHECK( res4 == call::iterator );
CHECK( std::is_sorted(std::begin(vec), std::end(vec)) );
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: framework.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: as $ $Date: 2001-05-21 06:12:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_HELPER_OINSTANCEPROVIDER_HXX_
#include <helper/oinstanceprovider.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_SERVICEMANAGER_HXX_
#include <classes/servicemanager.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_DEFINES_HXX_
#include <defines.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMELOADER_HPP_
#include <com/sun/star/frame/XFrameLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XLOADEVENTLISTENER_HPP_
#include <com/sun/star/frame/XLoadEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_FRAMESEARCHFLAG_HPP_
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMES_HPP_
#include <com/sun/star/frame/XFrames.hpp>
#endif
#ifndef _COM_SUN_STAR_CONNECTION_XConnection_HPP_
#include <com/sun/star/connection/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_BRIDGE_XBridgeFactory_HPP_
#include <com/sun/star/bridge/XBridgeFactory.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _SVT_UNOIFACE_HXX
#include <svtools/unoiface.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
using namespace ::rtl ;
using namespace ::vos ;
using namespace ::comphelper ;
using namespace ::framework ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::frame ;
using namespace ::com::sun::star::awt ;
using namespace ::com::sun::star::beans ;
using namespace ::com::sun::star::util ;
using namespace ::com::sun::star::connection ;
using namespace ::com::sun::star::bridge ;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define APPLICATIONNAME "FrameWork"
#define COMMANDARGUMENT_PLUGIN DECLARE_ASCII("-plugin" )
#define NAME_PLUGINBRIDGE DECLARE_ASCII("mozilla plugin bridge" )
#define PROTOCOL_PLUGINBRIDGE DECLARE_ASCII("urp" )
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short normal application
@descr An instance of these class can be a normal node in frame tree only. The highest level to be allowed is 3!
On 1 stand the desktop himself as the only one, on 2 are all tasks present ... and then comes frames only.
A frame support influencing of his subtree, find of subframes, activate- and deactivate-mechanism as well as
set/get of a frame window, component or controller.
@implements XInterface
XTypeProvider
XServiceInfo
XFramesSupplier
XFrame
XComponent
XStatusIndicatorSupplier
XDispatchProvider
XDispatchProviderInterception
XBrowseHistoryRegistry
XLoadEventListener
XEventListener
XWindowListener
XTopWindowListener
[ XDebugging, if TEST_TREE is defined! ]
@base OMutexMember
OWeakObject
@devstatus deprecated
*//*-*************************************************************************************************************/
class FrameWork : public Application
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
void Main();
private:
void impl_analyzeCommandArguments();
private:
sal_Bool m_bUsePlugIn ;
}; // class FrameWork
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// global variables
//_________________________________________________________________________________________________________________
FrameWork aFrameWork ;
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// private methods
//*****************************************************************************************************************
void FrameWork::impl_analyzeCommandArguments()
{
// First reset all member variables which present states of incoming arguments!
m_bUsePlugIn = sal_False; // depends from "/plugin"
// Then step over all given arguments and search for supported one.
OStartupInfo aInfo ;
OUString sArgument ;
sal_uInt32 nCount = aInfo.getCommandArgCount();
for ( sal_uInt32 nArgument=0; nArgument<nCount; ++nArgument )
{
// If extraction of current argument successfull ...
if ( aInfo.getCommandArg( nArgument, sArgument ) == osl_Process_E_None )
{
// ... search for matching with supported values.
if ( sArgument == COMMANDARGUMENT_PLUGIN )
{
// We found "/plugin" => set internal equivalent.
m_bUsePlugIn = sal_True;
}
}
}
}
//_________________________________________________________________________________________________________________
// main
//_________________________________________________________________________________________________________________
void FrameWork::Main()
{
//-------------------------------------------------------------------------------------------------------------
// a) Initialize ouer application
// Analyze command arguments.
impl_analyzeCommandArguments();
// Create new global servicemanager.
ServiceManager aManager;
Reference< XMultiServiceFactory > xGlobalServiceManager = aManager.getGlobalUNOServiceManager();
if ( xGlobalServiceManager.is() == sal_True )
{
// If it was successful - set in as static value in UNOTOOLS!
setProcessServiceFactory( xGlobalServiceManager );
//---------------------------------------------------------------------------------------------------------
// b) Create root of ouer frame tree
// Create top of frame hierarchy - the desktop.
Reference< XDesktop > xDesktop( xGlobalServiceManager->createInstance( SERVICENAME_DESKTOP ), UNO_QUERY );
// Safe impossible cases
// We need the desktop for working.
LOG_ASSERT( !(xDesktop.is()==sal_False), "FrameWork::Main()\nCan't instanciate desktop!Servicename unknown?\n" )
//---------------------------------------------------------------------------------------------------------
// c) Initialize connection to possible PlugIn dll.
// OPipeConnection removed, connection to plugin now uses acceptor service
#if 0
if ( m_bUsePlugIn == sal_True )
{
Reference< XConnection > xConnection = new OPipeConnection( xGlobalServiceManager );
Reference< XBridgeFactory > xBridgeFactory ( xGlobalServiceManager->createInstance( SERVICENAME_BRIDGEFACTORY ), UNO_QUERY );
if (
( xConnection.is() == sal_True ) &&
( xBridgeFactory.is() == sal_True )
)
{
Reference< XBridge > xBridge = xBridgeFactory->createBridge( NAME_PLUGINBRIDGE ,
PROTOCOL_PLUGINBRIDGE ,
xConnection ,
new OInstanceProvider( xGlobalServiceManager ) );
}
else
{
// Error handling ... !?
LOG_ASSERT( sal_False, "FrameWork::Main()\nNo connection to plugin. Initialization of bridge failed.\n" )
}
}
#endif
//---------------------------------------------------------------------------------------------------------
// d) Initialize new task with a HTML-URL in it.
// Cast desktop to right interface to do this.
Reference< XDispatchProvider > xDispatchProvider( xDesktop, UNO_QUERY );
// Safe impossible cases.
// Desktop MUST support these interface!
LOG_ASSERT( !(xDispatchProvider.is()==sal_False), "FrameWork::Main()\nDesktop don't support XDispatchProvider interface.\n" )
if ( xDispatchProvider.is() == sal_True )
{
// Build URL ...
OUString sURL( RTL_CONSTASCII_USTRINGPARAM( "file://e|/dokumentation/Documentation/projekte/services/inimanager/inimanager/index.html" ));
URL aURL;
aURL.Complete = sURL;
// ... and dispatch it.
Reference< XDispatch > xDispatch = xDispatchProvider->queryDispatch( aURL, FRAMETYPE_BLANK, 0 );
xDispatch->dispatch( aURL, Sequence< PropertyValue >() );
// Use special feature of desktop service and log current tree state in file.
// LOG_TREE( xDesktop )
// Build URL ...
sURL = OUString( RTL_CONSTASCII_USTRINGPARAM( "file://d|/menu.htm" ));
aURL.Complete = sURL;
// ... and dispatch it.
xDispatch = xDispatchProvider->queryDispatch( aURL, FRAMETYPE_BLANK, 0 );
xDispatch->dispatch( aURL, Sequence< PropertyValue >() );
// Use special feature of desktop service and log current tree state in file.
// LOG_TREE( xDesktop )
}
// Set running-mode for application.
Execute();
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.8.584); FILE MERGED 2005/09/05 13:05:58 rt 1.8.584.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: framework.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:05:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_HELPER_OINSTANCEPROVIDER_HXX_
#include <helper/oinstanceprovider.hxx>
#endif
#ifndef __FRAMEWORK_CLASSES_SERVICEMANAGER_HXX_
#include <classes/servicemanager.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_DEFINES_HXX_
#include <defines.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMELOADER_HPP_
#include <com/sun/star/frame/XFrameLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XLOADEVENTLISTENER_HPP_
#include <com/sun/star/frame/XLoadEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_FRAMESEARCHFLAG_HPP_
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMES_HPP_
#include <com/sun/star/frame/XFrames.hpp>
#endif
#ifndef _COM_SUN_STAR_CONNECTION_XConnection_HPP_
#include <com/sun/star/connection/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_BRIDGE_XBridgeFactory_HPP_
#include <com/sun/star/bridge/XBridgeFactory.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _SVT_UNOIFACE_HXX
#include <svtools/unoiface.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
using namespace ::rtl ;
using namespace ::vos ;
using namespace ::comphelper ;
using namespace ::framework ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::frame ;
using namespace ::com::sun::star::awt ;
using namespace ::com::sun::star::beans ;
using namespace ::com::sun::star::util ;
using namespace ::com::sun::star::connection ;
using namespace ::com::sun::star::bridge ;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define APPLICATIONNAME "FrameWork"
#define COMMANDARGUMENT_PLUGIN DECLARE_ASCII("-plugin" )
#define NAME_PLUGINBRIDGE DECLARE_ASCII("mozilla plugin bridge" )
#define PROTOCOL_PLUGINBRIDGE DECLARE_ASCII("urp" )
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short normal application
@descr An instance of these class can be a normal node in frame tree only. The highest level to be allowed is 3!
On 1 stand the desktop himself as the only one, on 2 are all tasks present ... and then comes frames only.
A frame support influencing of his subtree, find of subframes, activate- and deactivate-mechanism as well as
set/get of a frame window, component or controller.
@implements XInterface
XTypeProvider
XServiceInfo
XFramesSupplier
XFrame
XComponent
XStatusIndicatorSupplier
XDispatchProvider
XDispatchProviderInterception
XBrowseHistoryRegistry
XLoadEventListener
XEventListener
XWindowListener
XTopWindowListener
[ XDebugging, if TEST_TREE is defined! ]
@base OMutexMember
OWeakObject
@devstatus deprecated
*//*-*************************************************************************************************************/
class FrameWork : public Application
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
void Main();
private:
void impl_analyzeCommandArguments();
private:
sal_Bool m_bUsePlugIn ;
}; // class FrameWork
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// global variables
//_________________________________________________________________________________________________________________
FrameWork aFrameWork ;
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// private methods
//*****************************************************************************************************************
void FrameWork::impl_analyzeCommandArguments()
{
// First reset all member variables which present states of incoming arguments!
m_bUsePlugIn = sal_False; // depends from "/plugin"
// Then step over all given arguments and search for supported one.
OStartupInfo aInfo ;
OUString sArgument ;
sal_uInt32 nCount = aInfo.getCommandArgCount();
for ( sal_uInt32 nArgument=0; nArgument<nCount; ++nArgument )
{
// If extraction of current argument successfull ...
if ( aInfo.getCommandArg( nArgument, sArgument ) == osl_Process_E_None )
{
// ... search for matching with supported values.
if ( sArgument == COMMANDARGUMENT_PLUGIN )
{
// We found "/plugin" => set internal equivalent.
m_bUsePlugIn = sal_True;
}
}
}
}
//_________________________________________________________________________________________________________________
// main
//_________________________________________________________________________________________________________________
void FrameWork::Main()
{
//-------------------------------------------------------------------------------------------------------------
// a) Initialize ouer application
// Analyze command arguments.
impl_analyzeCommandArguments();
// Create new global servicemanager.
ServiceManager aManager;
Reference< XMultiServiceFactory > xGlobalServiceManager = aManager.getGlobalUNOServiceManager();
if ( xGlobalServiceManager.is() == sal_True )
{
// If it was successful - set in as static value in UNOTOOLS!
setProcessServiceFactory( xGlobalServiceManager );
//---------------------------------------------------------------------------------------------------------
// b) Create root of ouer frame tree
// Create top of frame hierarchy - the desktop.
Reference< XDesktop > xDesktop( xGlobalServiceManager->createInstance( SERVICENAME_DESKTOP ), UNO_QUERY );
// Safe impossible cases
// We need the desktop for working.
LOG_ASSERT( !(xDesktop.is()==sal_False), "FrameWork::Main()\nCan't instanciate desktop!Servicename unknown?\n" )
//---------------------------------------------------------------------------------------------------------
// c) Initialize connection to possible PlugIn dll.
// OPipeConnection removed, connection to plugin now uses acceptor service
#if 0
if ( m_bUsePlugIn == sal_True )
{
Reference< XConnection > xConnection = new OPipeConnection( xGlobalServiceManager );
Reference< XBridgeFactory > xBridgeFactory ( xGlobalServiceManager->createInstance( SERVICENAME_BRIDGEFACTORY ), UNO_QUERY );
if (
( xConnection.is() == sal_True ) &&
( xBridgeFactory.is() == sal_True )
)
{
Reference< XBridge > xBridge = xBridgeFactory->createBridge( NAME_PLUGINBRIDGE ,
PROTOCOL_PLUGINBRIDGE ,
xConnection ,
new OInstanceProvider( xGlobalServiceManager ) );
}
else
{
// Error handling ... !?
LOG_ASSERT( sal_False, "FrameWork::Main()\nNo connection to plugin. Initialization of bridge failed.\n" )
}
}
#endif
//---------------------------------------------------------------------------------------------------------
// d) Initialize new task with a HTML-URL in it.
// Cast desktop to right interface to do this.
Reference< XDispatchProvider > xDispatchProvider( xDesktop, UNO_QUERY );
// Safe impossible cases.
// Desktop MUST support these interface!
LOG_ASSERT( !(xDispatchProvider.is()==sal_False), "FrameWork::Main()\nDesktop don't support XDispatchProvider interface.\n" )
if ( xDispatchProvider.is() == sal_True )
{
// Build URL ...
OUString sURL( RTL_CONSTASCII_USTRINGPARAM( "file://e|/dokumentation/Documentation/projekte/services/inimanager/inimanager/index.html" ));
URL aURL;
aURL.Complete = sURL;
// ... and dispatch it.
Reference< XDispatch > xDispatch = xDispatchProvider->queryDispatch( aURL, FRAMETYPE_BLANK, 0 );
xDispatch->dispatch( aURL, Sequence< PropertyValue >() );
// Use special feature of desktop service and log current tree state in file.
// LOG_TREE( xDesktop )
// Build URL ...
sURL = OUString( RTL_CONSTASCII_USTRINGPARAM( "file://d|/menu.htm" ));
aURL.Complete = sURL;
// ... and dispatch it.
xDispatch = xDispatchProvider->queryDispatch( aURL, FRAMETYPE_BLANK, 0 );
xDispatch->dispatch( aURL, Sequence< PropertyValue >() );
// Use special feature of desktop service and log current tree state in file.
// LOG_TREE( xDesktop )
}
// Set running-mode for application.
Execute();
}
}
<|endoftext|>
|
<commit_before>//===- tools/seec-trace-print/OnlinePythonTutor.cpp -----------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/MappedFunctionState.hpp"
#include "seec/Clang/MappedGlobalVariable.hpp"
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedProcessTrace.hpp"
#include "seec/Clang/MappedStateMovement.hpp"
#include "seec/Clang/MappedThreadState.hpp"
#include "seec/Util/Printing.hpp"
#include "clang/AST/Decl.h"
#include "llvm/Support/raw_ostream.h"
using namespace seec;
using namespace seec::cm;
using namespace seec::util;
llvm::StringRef GetSingularMainFileContents(ProcessTrace const &Trace)
{
auto const &CompileInfoMap = Trace.getMapping().getCompileInfoMap();
if (CompileInfoMap.size() != 1)
return llvm::StringRef();
auto const FI = CompileInfoMap.cbegin()->second->getMainFileInfo();
if (!FI)
return llvm::StringRef();
return FI->getContents().getBuffer();
}
class OPTPrinter {
llvm::raw_ostream &Out;
IndentationGuide Indent;
ProcessTrace const &Trace;
ProcessState Process;
OPTPrinter(llvm::raw_ostream &ToStream, ProcessTrace const &FromTrace)
: Out(ToStream),
Indent(" ", 1),
Trace(FromTrace),
Process(FromTrace)
{}
void printValue(Value const &V);
void printGlobal(GlobalVariable const &GV, std::string &NameOut);
void printGlobals();
void printParameter(ParamState const &Param, std::string &NameOut);
void printLocal(LocalState const &Local, std::string &NameOut);
void printFunction(FunctionState const &Function);
void printThread(ThreadState const &Thread);
void printState();
bool printAllStates();
public:
static bool print(llvm::raw_ostream &Out, ProcessTrace const &Trace)
{
OPTPrinter Printer(Out, Trace);
return Printer.printAllStates();
}
};
void OPTPrinter::printValue(Value const &V)
{
writeJSONStringLiteral(V.getValueAsStringFull(), Out);
}
void OPTPrinter::printGlobal(GlobalVariable const &GV, std::string &NameOut)
{
NameOut = GV.getClangValueDecl()->getNameAsString();
Out << Indent.getString();
writeJSONStringLiteral(NameOut, Out);
Out << ": ";
if (auto const V = GV.getValue())
printValue(*V);
else
Out << "\"<no value>\"";
}
void OPTPrinter::printGlobals()
{
std::vector<std::string> OrderedNames;
// globals: dict
Out << Indent.getString() << "\"globals\": {\n";
Indent.indent();
bool PreviousPrinted = false;
for (auto const &GV : Process.getGlobalVariables()) {
if (!GV || (GV->isInSystemHeader() && !GV->isReferenced()))
continue;
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
OrderedNames.emplace_back();
printGlobal(*GV, OrderedNames.back());
}
Indent.unindent();
Out << "\n" << Indent.getString() << "},\n";
// ordered_globals: [string]
Out << Indent.getString() << "\"ordered_globals\": [";
for (std::size_t i = 0; i < OrderedNames.size(); ++i) {
if (i != 0)
Out << ", ";
writeJSONStringLiteral(OrderedNames[i], Out);
}
Out << "],\n";
}
void OPTPrinter::printParameter(ParamState const &Param, std::string &NameOut)
{
NameOut = Param.getDecl()->getNameAsString();
Out << Indent.getString();
writeJSONStringLiteral(NameOut, Out);
Out << ": ";
if (auto const V = Param.getValue())
printValue(*V);
else
Out << "\"<no value>\"";
}
void OPTPrinter::printLocal(LocalState const &Local, std::string &NameOut)
{
NameOut = Local.getDecl()->getNameAsString();
Out << Indent.getString();
writeJSONStringLiteral(NameOut, Out);
Out << ": ";
if (auto const V = Local.getValue())
printValue(*V);
else
Out << "\"<no value>\"";
}
void OPTPrinter::printFunction(FunctionState const &Function)
{
Out << Indent.getString() << "{\n";
Indent.indent();
// func_name
Out << Indent.getString() << "\"func_name\": ";
writeJSONStringLiteral(Function.getNameAsString(), Out);
Out << ",\n";
// frame_id = ?
// unique_hash = ?
// encoded_locals = dict
std::vector<std::string> OrderedVarnames;
Out << Indent.getString() << "\"encoded_locals\": {\n";
Indent.indent();
{
bool PreviousPrinted = false;
for (auto const &Param : Function.getParameters()) {
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
OrderedVarnames.emplace_back();
printParameter(Param, OrderedVarnames.back());
}
for (auto const &Local : Function.getLocals()) {
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
OrderedVarnames.emplace_back();
printLocal(Local, OrderedVarnames.back());
}
}
Indent.unindent();
Out << "\n" << Indent.getString() << "},\n";
// ordered_varnames = [string]
Out << Indent.getString() << "\"ordered_varnames\": [";
for (std::size_t i = 0; i < OrderedVarnames.size(); ++i) {
if (i != 0)
Out << ", ";
writeJSONStringLiteral(OrderedVarnames[i], Out);
}
Out << "],\n";
// is_highlighted = ?
// These are for Closures and Zombie Frames, so we don't need them.
Out << Indent.getString() << "\"is_parent\" = false,\n";
Out << Indent.getString() << "\"is_zombie\" = false,\n";
Out << Indent.getString() << "\"parent_frame_id_list\": [],\n";
Indent.unindent();
Out << Indent.getString() << "}";
}
void OPTPrinter::printThread(ThreadState const &Thread)
{
auto const &Stack = Thread.getCallStack();
// func_name
// stack_to_render
if (!Stack.empty()) {
// Write the active function's name.
auto const &Active = Stack.back().get();
Out << Indent.getString() << "\"func_name\": ";
writeJSONStringLiteral(Active.getNameAsString(), Out);
Out << ",\n";
// Write the stack.
Out << Indent.getString() << "\"stack_to_render\": [\n";
Indent.indent();
bool PreviousPrinted = false;
for (auto const &Fn : Stack) {
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
printFunction(Fn);
}
Indent.unindent();
Out << "\n" << Indent.getString() << "]\n";
}
else {
Out << Indent.getString() << "\"func_name\": \"<none>\",\n";
Out << Indent.getString() << "\"stack_to_render\": [],\n";
}
// line: int
// event: string
}
void OPTPrinter::printState()
{
Out << Indent.getString() << "{\n";
Indent.indent();
printGlobals();
printThread(Process.getThread(0));
// stdout
if (auto const Stream = Process.getStreamStdout()) {
Out << Indent.getString() << "\"stdout\": ";
writeJSONStringLiteral(Stream->getWritten(), Out);
Out << ",\n";
}
else {
Out << Indent.getString() << "\"stdout\": \"\",\n";
}
// heap
Out << Indent.getString() << "\"heap\": {}\n";
Indent.unindent();
Out << Indent.getString() << "}";
}
bool OPTPrinter::printAllStates()
{
// OnlinePythonTutor output only supports single-threaded programs.
if (Process.getThreadCount() != 1)
return false;
Out << Indent.getString() << "{\n";
Indent.indent();
// Write the source code.
auto const SourceCode = GetSingularMainFileContents(Trace);
if (SourceCode.empty())
return false;
Out << Indent.getString() << "\"code\": ";
writeJSONStringLiteral(SourceCode, Out);
Out << ",\n";
Out << Indent.getString() << "\"trace\": [\n";
Indent.indent();
printState();
while (moveForward(Process.getThread(0))) {
Out << ",\n";
printState();
}
Out << "\n";
Indent.unindent();
Out << Indent.getString() << "]\n";
Indent.unindent();
Out << Indent.getString() << "}\n";
return true;
}
void PrintOnlinePythonTutor(ProcessTrace const &Trace)
{
OPTPrinter::print(llvm::outs(), Trace);
}
<commit_msg>Add support for frame_id, unique_hash, is_highlighted, event, and line. Also correct some bugs with the output. Now successfully renders with OnlinePythonTutor.<commit_after>//===- tools/seec-trace-print/OnlinePythonTutor.cpp -----------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/MappedFunctionState.hpp"
#include "seec/Clang/MappedGlobalVariable.hpp"
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedProcessTrace.hpp"
#include "seec/Clang/MappedStateMovement.hpp"
#include "seec/Clang/MappedThreadState.hpp"
#include "seec/Trace/FunctionState.hpp"
#include "seec/Trace/TraceReader.hpp"
#include "seec/Util/Printing.hpp"
#include "clang/AST/Decl.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/raw_ostream.h"
using namespace seec;
using namespace seec::cm;
using namespace seec::util;
llvm::StringRef GetSingularMainFileContents(ProcessTrace const &Trace)
{
auto const &CompileInfoMap = Trace.getMapping().getCompileInfoMap();
if (CompileInfoMap.size() != 1)
return llvm::StringRef();
auto const FI = CompileInfoMap.cbegin()->second->getMainFileInfo();
if (!FI)
return llvm::StringRef();
return FI->getContents().getBuffer();
}
class OPTPrinter {
llvm::raw_ostream &Out;
IndentationGuide Indent;
ProcessTrace const &Trace;
ProcessState Process;
llvm::DenseMap<seec::trace::offset_uint, uint32_t> FrameIDMap;
unsigned PreviousLine;
OPTPrinter(llvm::raw_ostream &ToStream, ProcessTrace const &FromTrace)
: Out(ToStream),
Indent(" ", 1),
Trace(FromTrace),
Process(FromTrace),
FrameIDMap(),
PreviousLine(1)
{}
uint32_t getFrameID(FunctionState const &Function);
void printValue(Value const &V);
void printGlobal(GlobalVariable const &GV, std::string &NameOut);
void printGlobals();
void printParameter(ParamState const &Param, std::string &NameOut);
void printLocal(LocalState const &Local, std::string &NameOut);
void printFunction(FunctionState const &Function, bool IsActive);
void printThread(ThreadState const &Thread);
bool printAndMoveState();
bool printAllStates();
public:
static bool print(llvm::raw_ostream &Out, ProcessTrace const &Trace)
{
OPTPrinter Printer(Out, Trace);
return Printer.printAllStates();
}
};
uint32_t OPTPrinter::getFrameID(FunctionState const &Function)
{
auto const &Trace = Function.getUnmappedState().getTrace();
auto const Result = FrameIDMap.insert(std::make_pair(Trace.getEventStart(),
FrameIDMap.size() + 1));
return Result.first->second;
}
void OPTPrinter::printValue(Value const &V)
{
writeJSONStringLiteral(V.getValueAsStringFull(), Out);
}
void OPTPrinter::printGlobal(GlobalVariable const &GV, std::string &NameOut)
{
NameOut = GV.getClangValueDecl()->getNameAsString();
Out << Indent.getString();
writeJSONStringLiteral(NameOut, Out);
Out << ": ";
if (auto const V = GV.getValue())
printValue(*V);
else
Out << "\"<no value>\"";
}
void OPTPrinter::printGlobals()
{
std::vector<std::string> OrderedNames;
// globals: dict
Out << Indent.getString() << "\"globals\": {\n";
Indent.indent();
bool PreviousPrinted = false;
for (auto const &GV : Process.getGlobalVariables()) {
if (!GV || (GV->isInSystemHeader() && !GV->isReferenced()))
continue;
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
OrderedNames.emplace_back();
printGlobal(*GV, OrderedNames.back());
}
Indent.unindent();
Out << "\n" << Indent.getString() << "},\n";
// ordered_globals: [string]
Out << Indent.getString() << "\"ordered_globals\": [";
for (std::size_t i = 0; i < OrderedNames.size(); ++i) {
if (i != 0)
Out << ", ";
writeJSONStringLiteral(OrderedNames[i], Out);
}
Out << "],\n";
}
void OPTPrinter::printParameter(ParamState const &Param, std::string &NameOut)
{
NameOut = Param.getDecl()->getNameAsString();
Out << Indent.getString();
writeJSONStringLiteral(NameOut, Out);
Out << ": ";
if (auto const V = Param.getValue())
printValue(*V);
else
Out << "\"<no value>\"";
}
void OPTPrinter::printLocal(LocalState const &Local, std::string &NameOut)
{
NameOut = Local.getDecl()->getNameAsString();
Out << Indent.getString();
writeJSONStringLiteral(NameOut, Out);
Out << ": ";
if (auto const V = Local.getValue())
printValue(*V);
else
Out << "\"<no value>\"";
}
void OPTPrinter::printFunction(FunctionState const &Function, bool IsActive)
{
Out << Indent.getString() << "{\n";
Indent.indent();
// func_name
auto const FnName = Function.getNameAsString();
Out << Indent.getString() << "\"func_name\": ";
writeJSONStringLiteral(FnName, Out);
Out << ",\n";
// frame_id = unique key for this function call
// unique_hash = func_name + frame_id
auto const FrameID = getFrameID(Function);
Out << Indent.getString() << "\"frame_id\": " << FrameID << ",\n";
Out << Indent.getString() << "\"unique_hash\": ";
writeJSONStringLiteral(FnName + std::to_string(FrameID), Out);
Out << ",\n";
// encoded_locals = dict
std::vector<std::string> OrderedVarnames;
Out << Indent.getString() << "\"encoded_locals\": {\n";
Indent.indent();
{
bool PreviousPrinted = false;
for (auto const &Param : Function.getParameters()) {
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
OrderedVarnames.emplace_back();
printParameter(Param, OrderedVarnames.back());
}
for (auto const &Local : Function.getLocals()) {
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
OrderedVarnames.emplace_back();
printLocal(Local, OrderedVarnames.back());
}
}
Indent.unindent();
Out << "\n" << Indent.getString() << "},\n";
// ordered_varnames = [string]
Out << Indent.getString() << "\"ordered_varnames\": [";
for (std::size_t i = 0; i < OrderedVarnames.size(); ++i) {
if (i != 0)
Out << ", ";
writeJSONStringLiteral(OrderedVarnames[i], Out);
}
Out << "],\n";
// is_highlighted = ?
Out << Indent.getString();
if (IsActive)
Out << "\"is_highlighted\": true,\n";
else
Out << "\"is_highlighted\": false,\n";
// These are for Closures and Zombie Frames, so we don't need them.
Out << Indent.getString() << "\"is_parent\": false,\n";
Out << Indent.getString() << "\"is_zombie\": false,\n";
Out << Indent.getString() << "\"parent_frame_id_list\": []\n";
Indent.unindent();
Out << Indent.getString() << "}";
}
void OPTPrinter::printThread(ThreadState const &Thread)
{
auto const &Stack = Thread.getCallStack();
// func_name
// stack_to_render
if (!Stack.empty()) {
// Write the active function's name.
auto const &Active = Stack.back().get();
Out << Indent.getString() << "\"func_name\": ";
writeJSONStringLiteral(Active.getNameAsString(), Out);
Out << ",\n";
// Write the stack.
Out << Indent.getString() << "\"stack_to_render\": [\n";
Indent.indent();
bool PreviousPrinted = false;
for (auto const &Fn : Stack) {
if (PreviousPrinted)
Out << ",\n";
else
PreviousPrinted = true;
printFunction(Fn, &Fn.get() == &Active);
}
Indent.unindent();
Out << "\n" << Indent.getString() << "],\n";
}
else {
Out << Indent.getString() << "\"func_name\": \"<none>\",\n";
Out << Indent.getString() << "\"stack_to_render\": [],\n";
}
// event: string
Out << Indent.getString() << "\"event\": ";
if (!Thread.isAtEnd())
Out << "\"step_line\"";
else
Out << "\"return\"";
Out << ",\n";
}
/// \brief Get the start line in the outermost file.
///
static unsigned getLineOutermost(clang::SourceLocation Start,
clang::ASTContext const &AST)
{
auto const &SourceManager = AST.getSourceManager();
while (Start.isMacroID())
Start = SourceManager.getExpansionLoc(Start);
return SourceManager.getSpellingLineNumber(Start);
}
bool OPTPrinter::printAndMoveState()
{
Out << Indent.getString() << "{\n";
Indent.indent();
printGlobals();
printThread(Process.getThread(0));
// stdout
if (auto const Stream = Process.getStreamStdout()) {
Out << Indent.getString() << "\"stdout\": ";
writeJSONStringLiteral(Stream->getWritten(), Out);
Out << ",\n";
}
else {
Out << Indent.getString() << "\"stdout\": \"\",\n";
}
// TODO: heap
Out << Indent.getString() << "\"heap\": {},\n";
// Move now so that we can get the "next" line number.
auto const Moved = moveForward(Process.getThread(0));
// line: int
auto const &Thread = Process.getThread(0);
auto const &Stack = Thread.getCallStack();
if (!Stack.empty()) {
auto const &ActiveFn = Stack.back().get();
auto const &AST = ActiveFn.getMappedAST()->getASTUnit().getASTContext();
if (auto const ActiveStmt = ActiveFn.getActiveStmt())
PreviousLine = getLineOutermost(ActiveStmt->getLocStart(), AST);
else
PreviousLine = getLineOutermost(ActiveFn.getFunctionDecl()->getLocStart(),
AST);
}
Out << Indent.getString() << "\"line\": " << PreviousLine << "\n";
Indent.unindent();
Out << Indent.getString() << "}";
return Moved;
}
bool OPTPrinter::printAllStates()
{
// OnlinePythonTutor output only supports single-threaded programs.
if (Process.getThreadCount() != 1)
return false;
Out << Indent.getString() << "{\n";
Indent.indent();
// Write the source code.
auto const SourceCode = GetSingularMainFileContents(Trace);
if (SourceCode.empty())
return false;
Out << Indent.getString() << "\"code\": ";
writeJSONStringLiteral(SourceCode, Out);
Out << ",\n";
Out << Indent.getString() << "\"trace\": [\n";
Indent.indent();
while (printAndMoveState()) {
Out << ",\n";
}
Out << "\n";
Indent.unindent();
Out << Indent.getString() << "]\n";
Indent.unindent();
Out << Indent.getString() << "}\n";
return true;
}
void PrintOnlinePythonTutor(ProcessTrace const &Trace)
{
OPTPrinter::print(llvm::outs(), Trace);
}
<|endoftext|>
|
<commit_before>
#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>
#include <sfeMovie/Movie.hpp>
#include <iostream>
#include <algorithm>
/*
* Here is a little use sample for sfeMovie.
* It'll open and display the movie specified by MOVIE_FILE above.
*
* This sample implements basic controls as follow:
* - Escape key to exit
* - Space key to play/pause the movie playback
* - S key to stop and go back to the beginning of the movie
* - R key to restart playing from the beginning of the movie
* - F key to toggle between windowed and fullscreen mode
*/
void my_pause()
{
#ifdef SFML_SYSTEM_WINDOWS
system("PAUSE");
#endif
}
std::string StatusToString(sfe::Status status)
{
switch (status) {
case sfe::Stopped: return "Stopped"; break;
case sfe::Paused: return "Paused"; break;
case sfe::Playing: return "Playing"; break;
default: return "unknown status"; break;
}
}
void drawControls(sf::RenderWindow& window, const sfe::Movie& movie)
{
const int kHorizontalMargin = 10;
const int kVerticalMargin = 10;
const int kTimelineBackgroundHeight = 20;
const int kTimelineInnerMargin = 4;
sf::RectangleShape background(sf::Vector2f(window.getSize().x - 2 * kHorizontalMargin, kTimelineBackgroundHeight));
background.setPosition(kHorizontalMargin, window.getSize().y - kTimelineBackgroundHeight - kVerticalMargin);
background.setFillColor(sf::Color(0, 0, 0, 255/2));
sf::RectangleShape border(sf::Vector2f(background.getSize().x - 2 * kTimelineInnerMargin, background.getSize().y - 2 * kTimelineInnerMargin));
border.setPosition(background.getPosition().x + kTimelineInnerMargin, background.getPosition().y + kTimelineInnerMargin);
border.setFillColor(sf::Color::Transparent);
border.setOutlineColor(sf::Color::White);
border.setOutlineThickness(1.0);
float fprogress = movie.getPlayingOffset().asSeconds() / movie.getDuration().asSeconds();
sf::RectangleShape progress(sf::Vector2f(1, border.getSize().y - 2 * border.getOutlineThickness()));
progress.setPosition(border.getPosition().x + border.getOutlineThickness() + fprogress * (border.getSize().x - 2 * border.getOutlineThickness()), border.getPosition().y + border.getOutlineThickness());
progress.setFillColor(sf::Color::White);
window.draw(background);
window.draw(border);
window.draw(progress);
}
int main(int argc, const char *argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << std::string(argv[0]) << " movie_path" << std::endl;
my_pause();
return 1;
}
std::string mediaFile = std::string(argv[1]);
std::cout << "Going to open movie file \"" << mediaFile << "\"" << std::endl;
sfe::Movie movie;
if (!movie.openFromFile(mediaFile)) {
my_pause();
return 1;
}
bool fullscreen = false;
sf::VideoMode mode = sf::VideoMode::getDesktopMode();
int width = std::min((int)mode.width, movie.getSize().x);
int height = std::min((int)mode.height, movie.getSize().y);
// Create window
sf::RenderWindow window(sf::VideoMode(width, height), "sfeMovie Player", sf::Style::Close);
movie.fit(0, 0, width, height);
// Scale movie to the window drawing area and enable VSync
window.setFramerateLimit(60);
movie.play();
while (window.isOpen())
{
sf::Event ev;
while (window.pollEvent(ev))
{
// Window closure
if (ev.type == sf::Event::Closed ||
(ev.type == sf::Event::KeyPressed &&
ev.key.code == sf::Keyboard::Escape))
{
window.close();
}
if (ev.type == sf::Event::KeyPressed) {
if (ev.key.code == sf::Keyboard::Space) {
if (movie.getStatus() == sfe::Playing) {
movie.pause();
} else {
movie.play();
}
} else if (ev.key.code == sf::Keyboard::F) {
fullscreen = !fullscreen;
window.create(sf::VideoMode(width, height), "sfeMovie Player", fullscreen ? sf::Style::Fullscreen : sf::Style::Close);
movie.fit(0, 0, window.getSize().x, window.getSize().y);
} else if (ev.key.code == sf::Keyboard::P) {
std::cout << "Status: " << StatusToString(movie.getStatus()) << std::endl;
std::cout << "Position: " << movie.getPlayingOffset().asSeconds() << "s" << std::endl;
std::cout << "Duration: " << movie.getDuration().asSeconds() << "s" << std::endl;
std::cout << "Size: " << movie.getSize().x << "x" << movie.getSize().y << std::endl;
std::cout << "Framerate: " << movie.getFramerate() << " FPS (average)" << std::endl;
std::cout << "Volume: " << movie.getVolume() << std::endl;
std::cout << "Sample rate: " << movie.getSampleRate() << std::endl;
std::cout << "Channel count: " << movie.getChannelCount() << std::endl;
}
} else if (ev.type == sf::Event::MouseWheelMoved) {
float volume = movie.getVolume() + 10 * ev.mouseWheel.delta;
volume = std::min(volume, 100.f);
volume = std::max(volume, 0.f);
movie.setVolume(volume);
}
}
movie.update();
// Render movie
window.clear();
window.draw(movie);
drawControls(window, movie);
window.display();
}
return 0;
}
<commit_msg>#49 Display stream info in sfeMovie sample<commit_after>
#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>
#include <sfeMovie/Movie.hpp>
#include <iostream>
#include <algorithm>
/*
* Here is a little use sample for sfeMovie.
* It'll open and display the movie specified by MOVIE_FILE above.
*
* This sample implements basic controls as follow:
* - Escape key to exit
* - Space key to play/pause the movie playback
* - S key to stop and go back to the beginning of the movie
* - R key to restart playing from the beginning of the movie
* - F key to toggle between windowed and fullscreen mode
*/
void my_pause()
{
#ifdef SFML_SYSTEM_WINDOWS
system("PAUSE");
#endif
}
std::string StatusToString(sfe::Status status)
{
switch (status) {
case sfe::Stopped: return "Stopped"; break;
case sfe::Paused: return "Paused"; break;
case sfe::Playing: return "Playing"; break;
default: return "unknown status"; break;
}
}
std::string MediaTypeToString(sfe::MediaType type)
{
switch (type) {
case sfe::MEDIA_TYPE_AUDIO: return "audio";
case sfe::MEDIA_TYPE_SUBTITLE: return "subtitle";
case sfe::MEDIA_TYPE_VIDEO: return "video";
case sfe::MEDIA_TYPE_UNKNOWN: return "unknown";
default: return "(null)";
}
}
void drawControls(sf::RenderWindow& window, const sfe::Movie& movie)
{
const int kHorizontalMargin = 10;
const int kVerticalMargin = 10;
const int kTimelineBackgroundHeight = 20;
const int kTimelineInnerMargin = 4;
sf::RectangleShape background(sf::Vector2f(window.getSize().x - 2 * kHorizontalMargin, kTimelineBackgroundHeight));
background.setPosition(kHorizontalMargin, window.getSize().y - kTimelineBackgroundHeight - kVerticalMargin);
background.setFillColor(sf::Color(0, 0, 0, 255/2));
sf::RectangleShape border(sf::Vector2f(background.getSize().x - 2 * kTimelineInnerMargin, background.getSize().y - 2 * kTimelineInnerMargin));
border.setPosition(background.getPosition().x + kTimelineInnerMargin, background.getPosition().y + kTimelineInnerMargin);
border.setFillColor(sf::Color::Transparent);
border.setOutlineColor(sf::Color::White);
border.setOutlineThickness(1.0);
float fprogress = movie.getPlayingOffset().asSeconds() / movie.getDuration().asSeconds();
sf::RectangleShape progress(sf::Vector2f(1, border.getSize().y - 2 * border.getOutlineThickness()));
progress.setPosition(border.getPosition().x + border.getOutlineThickness() + fprogress * (border.getSize().x - 2 * border.getOutlineThickness()), border.getPosition().y + border.getOutlineThickness());
progress.setFillColor(sf::Color::White);
window.draw(background);
window.draw(border);
window.draw(progress);
}
void printMovieInfo(const sfe::Movie& movie)
{
std::cout << "Status: " << StatusToString(movie.getStatus()) << std::endl;
std::cout << "Position: " << movie.getPlayingOffset().asSeconds() << "s" << std::endl;
std::cout << "Duration: " << movie.getDuration().asSeconds() << "s" << std::endl;
std::cout << "Size: " << movie.getSize().x << "x" << movie.getSize().y << std::endl;
std::cout << "Framerate: " << movie.getFramerate() << " FPS (average)" << std::endl;
std::cout << "Volume: " << movie.getVolume() << std::endl;
std::cout << "Sample rate: " << movie.getSampleRate() << std::endl;
std::cout << "Channel count: " << movie.getChannelCount() << std::endl;
const std::vector<sfe::StreamDescriptor>& streams = movie.getStreams();
std::cout << streams.size() << " streams found in the media" << std::endl;
for (std::vector<sfe::StreamDescriptor>::const_iterator it = streams.begin(); it != streams.end(); ++it) {
std::cout << " #" << it->index << " : " << MediaTypeToString(it->type);
if (!it->language.empty())
std::cout << " (language: " << it->language << ")";
std::cout << std::endl;
}
}
int main(int argc, const char *argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << std::string(argv[0]) << " movie_path" << std::endl;
my_pause();
return 1;
}
std::string mediaFile = std::string(argv[1]);
std::cout << "Going to open movie file \"" << mediaFile << "\"" << std::endl;
sfe::Movie movie;
if (!movie.openFromFile(mediaFile)) {
my_pause();
return 1;
}
bool fullscreen = false;
sf::VideoMode mode = sf::VideoMode::getDesktopMode();
int width = std::min((int)mode.width, movie.getSize().x);
int height = std::min((int)mode.height, movie.getSize().y);
// Create window
sf::RenderWindow window(sf::VideoMode(width, height), "sfeMovie Player", sf::Style::Close);
movie.fit(0, 0, width, height);
// Scale movie to the window drawing area and enable VSync
window.setFramerateLimit(60);
movie.play();
while (window.isOpen())
{
sf::Event ev;
while (window.pollEvent(ev))
{
// Window closure
if (ev.type == sf::Event::Closed ||
(ev.type == sf::Event::KeyPressed &&
ev.key.code == sf::Keyboard::Escape))
{
window.close();
}
if (ev.type == sf::Event::KeyPressed) {
if (ev.key.code == sf::Keyboard::Space) {
if (movie.getStatus() == sfe::Playing) {
movie.pause();
} else {
movie.play();
}
} else if (ev.key.code == sf::Keyboard::F) {
fullscreen = !fullscreen;
window.create(sf::VideoMode(width, height), "sfeMovie Player", fullscreen ? sf::Style::Fullscreen : sf::Style::Close);
movie.fit(0, 0, window.getSize().x, window.getSize().y);
} else if (ev.key.code == sf::Keyboard::P) {
printMovieInfo(movie);
}
} else if (ev.type == sf::Event::MouseWheelMoved) {
float volume = movie.getVolume() + 10 * ev.mouseWheel.delta;
volume = std::min(volume, 100.f);
volume = std::max(volume, 0.f);
movie.setVolume(volume);
}
}
movie.update();
// Render movie
window.clear();
window.draw(movie);
drawControls(window, movie);
window.display();
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "CommandRegistry.h"
void megamol::frontend_resources::CommandRegistry::add_command(const megamol::frontend_resources::Command& c) {
const bool command_is_new = command_index.find(c.name) == command_index.end();
const bool key_code_unused = key_to_command.find(c.key) == key_to_command.end();
if (command_is_new && key_code_unused) {
push_command(c);
} else {
Command c2;
if (!command_is_new) {
c2.name = increment_name(c.name);
}
if (key_code_unused) {
c2.key = c.key;
}
c2.param = c.param;
push_command(c2);
}
}
void megamol::frontend_resources::CommandRegistry::remove_command(const megamol::core::param::AbstractParam* param) {
auto it = std::find_if(commands.begin(), commands.end(), [param] (const Command& c){return c.param == param;});
if (it != commands.end()) {
command_index.erase(it->name);
if (it->key.key != Key::KEY_UNKNOWN) key_to_command.erase(it->key);
commands.erase(it);
}
}
void megamol::frontend_resources::CommandRegistry::update_hotkey(const std::string& command_name, KeyCode key) {
if (!is_new(command_name)) {
auto& c = commands[command_index[command_name]];
const auto old_key = c.key;
c.key = key;
key_to_command.erase(old_key);
}
}
std::string megamol::frontend_resources::CommandRegistry::increment_name(const std::string& oldname) {
std::string new_name;
std::string prefix;
std::regex r("^(.*?)_\\d+$");
std::cmatch m;
if (std::regex_match(oldname.c_str(), m, r)) {
// already have a suffix
prefix = m[0];
} else {
prefix = oldname;
}
int cnt = 0;
bool isnew = false;
do {
cnt++;
new_name = prefix + "_" + std::to_string(cnt);
isnew = is_new(new_name);
} while (!isnew);
return new_name;
}
void megamol::frontend_resources::CommandRegistry::push_command(const Command& c) {
commands.push_back(c);
if (c.key.key != Key::KEY_UNKNOWN) key_to_command[c.key] = static_cast<int>(commands.size() - 1);
command_index[c.name] = static_cast<int>(commands.size() - 1);
}
<commit_msg>small fix to update_hotkey<commit_after>#include "CommandRegistry.h"
void megamol::frontend_resources::CommandRegistry::add_command(const megamol::frontend_resources::Command& c) {
const bool command_is_new = command_index.find(c.name) == command_index.end();
const bool key_code_unused = key_to_command.find(c.key) == key_to_command.end();
if (command_is_new && key_code_unused) {
push_command(c);
} else {
Command c2;
if (!command_is_new) {
c2.name = increment_name(c.name);
}
if (key_code_unused) {
c2.key = c.key;
}
c2.param = c.param;
push_command(c2);
}
}
void megamol::frontend_resources::CommandRegistry::remove_command(const megamol::core::param::AbstractParam* param) {
auto it = std::find_if(commands.begin(), commands.end(), [param] (const Command& c){return c.param == param;});
if (it != commands.end()) {
command_index.erase(it->name);
if (it->key.key != Key::KEY_UNKNOWN) key_to_command.erase(it->key);
commands.erase(it);
}
}
void megamol::frontend_resources::CommandRegistry::update_hotkey(const std::string& command_name, KeyCode key) {
if (!is_new(command_name)) {
auto& c = commands[command_index[command_name]];
const auto old_key = c.key;
c.key = key;
key_to_command.erase(old_key);
key_to_command[key] = command_index[command_name];
}
}
std::string megamol::frontend_resources::CommandRegistry::increment_name(const std::string& oldname) {
std::string new_name;
std::string prefix;
std::regex r("^(.*?)_\\d+$");
std::cmatch m;
if (std::regex_match(oldname.c_str(), m, r)) {
// already have a suffix
prefix = m[0];
} else {
prefix = oldname;
}
int cnt = 0;
bool isnew = false;
do {
cnt++;
new_name = prefix + "_" + std::to_string(cnt);
isnew = is_new(new_name);
} while (!isnew);
return new_name;
}
void megamol::frontend_resources::CommandRegistry::push_command(const Command& c) {
commands.push_back(c);
if (c.key.key != Key::KEY_UNKNOWN) key_to_command[c.key] = static_cast<int>(commands.size() - 1);
command_index[c.name] = static_cast<int>(commands.size() - 1);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/webassembly/wavm.hpp>
#include <eosio/chain/webassembly/wabt.hpp>
#include <eosio/chain/webassembly/eos-vm.hpp>
#include <eosio/chain/webassembly/runtime_interface.hpp>
#include <eosio/chain/wasm_eosio_injection.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/code_object.hpp>
#include <eosio/chain/exceptions.hpp>
#include <fc/scoped_exit.hpp>
#include "IR/Module.h"
#include "Runtime/Intrinsics.h"
#include "Platform/Platform.h"
#include "WAST/WAST.h"
#include "IR/Validate.h"
#include <eosio/vm/allocator.hpp>
using namespace fc;
using namespace eosio::chain::webassembly;
using namespace eosio::vm;
using namespace IR;
using namespace Runtime;
using boost::multi_index_container;
namespace eosio { namespace chain {
struct wasm_interface_impl {
struct wasm_cache_entry {
digest_type code_hash;
uint32_t first_block_num_used;
uint32_t last_block_num_used;
std::unique_ptr<wasm_instantiated_module_interface> module;
uint8_t vm_type = 0;
uint8_t vm_version = 0;
};
struct by_hash;
struct by_first_block_num;
struct by_last_block_num;
wasm_interface_impl(wasm_interface::vm_type vm, const chainbase::database& d) : db(d) {
if(vm == wasm_interface::vm_type::wavm)
runtime_interface = std::make_unique<webassembly::wavm::wavm_runtime>();
else if(vm == wasm_interface::vm_type::wabt)
runtime_interface = std::make_unique<webassembly::wabt_runtime::wabt_runtime>();
else if(vm == wasm_interface::vm_type::eos_vm)
runtime_interface = std::make_unique<webassembly::eos_vm_runtime::eos_vm_runtime>();
else
EOS_THROW(wasm_exception, "wasm_interface_impl fall through");
}
~wasm_interface_impl() {
if(is_shutting_down)
for(wasm_cache_index::iterator it = wasm_instantiation_cache.begin(); it != wasm_instantiation_cache.end(); ++it)
wasm_instantiation_cache.modify(it, [](wasm_cache_entry& e) {
e.module.release();
});
}
static wasm_allocator* get_wasm_allocator() {
static wasm_allocator walloc;
return &walloc;
}
std::vector<uint8_t> parse_initial_memory(const Module& module) {
std::vector<uint8_t> mem_image;
for(const DataSegment& data_segment : module.dataSegments) {
EOS_ASSERT(data_segment.baseOffset.type == InitializerExpression::Type::i32_const, wasm_exception, "");
EOS_ASSERT(module.memories.defs.size(), wasm_exception, "");
const U32 base_offset = data_segment.baseOffset.i32;
const Uptr memory_size = (module.memories.defs[0].type.size.min << IR::numBytesPerPageLog2);
if(base_offset >= memory_size || base_offset + data_segment.data.size() > memory_size)
FC_THROW_EXCEPTION(wasm_execution_error, "WASM data segment outside of valid memory range");
if(base_offset + data_segment.data.size() > mem_image.size())
mem_image.resize(base_offset + data_segment.data.size(), 0x00);
memcpy(mem_image.data() + base_offset, data_segment.data.data(), data_segment.data.size());
}
return mem_image;
}
void code_block_num_last_used(const digest_type& code_hash, const uint8_t& vm_type, const uint8_t& vm_version, const uint32_t& block_num) {
wasm_cache_index::iterator it = wasm_instantiation_cache.find(boost::make_tuple(code_hash, vm_type, vm_version));
if(it != wasm_instantiation_cache.end())
wasm_instantiation_cache.modify(it, [block_num](wasm_cache_entry& e) {
e.last_block_num_used = block_num;
});
}
void current_lib(uint32_t lib) {
//anything last used before or on the LIB can be evicted
wasm_instantiation_cache.get<by_last_block_num>().erase(wasm_instantiation_cache.get<by_last_block_num>().begin(), wasm_instantiation_cache.get<by_last_block_num>().upper_bound(lib));
}
const std::unique_ptr<wasm_instantiated_module_interface>& get_instantiated_module( const digest_type& code_hash, const uint8_t& vm_type,
const uint8_t& vm_version, transaction_context& trx_context, bool inject )
{
wasm_cache_index::iterator it = wasm_instantiation_cache.find(
boost::make_tuple(code_hash, vm_type, vm_version) );
const code_object* codeobject = nullptr;
if(it == wasm_instantiation_cache.end()) {
codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));
it = wasm_instantiation_cache.emplace( wasm_interface_impl::wasm_cache_entry{
.code_hash = code_hash,
.first_block_num_used = codeobject->first_block_used,
.last_block_num_used = UINT32_MAX,
.module = nullptr,
.vm_type = vm_type,
.vm_version = vm_version
} ).first;
}
if(!it->module) {
if(!codeobject)
codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));
auto timer_pause = fc::make_scoped_exit([&](){
trx_context.resume_billing_timer();
});
trx_context.pause_billing_timer();
IR::Module module;
std::vector<U8> bytes = {(const U8*)codeobject->code.data(), (const U8*)codeobject->code.data() + codeobject->code.size()};
try {
Serialization::MemoryInputStream stream((const U8*)bytes.data(), bytes.size());
WASM::serialize(stream, module);
module.userSections.clear();
} catch(const Serialization::FatalSerializationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
} catch(const IR::ValidationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
}
if(inject) {
wasm_injections::wasm_binary_injection injector(module);
injector.inject();
try {
Serialization::ArrayOutputStream outstream;
WASM::serialize(outstream, module);
bytes = outstream.getBytes();
} catch(const Serialization::FatalSerializationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
} catch(const IR::ValidationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
}
}
wasm_instantiation_cache.modify(it, [&](auto& c) {
c.module = runtime_interface->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module));
});
}
return it->module;
}
bool is_shutting_down = false;
std::unique_ptr<wasm_runtime_interface> runtime_interface;
wasm_interface::vm_type runtime;
typedef boost::multi_index_container<
wasm_cache_entry,
indexed_by<
ordered_unique<tag<by_hash>,
composite_key< wasm_cache_entry,
member<wasm_cache_entry, digest_type, &wasm_cache_entry::code_hash>,
member<wasm_cache_entry, uint8_t, &wasm_cache_entry::vm_type>,
member<wasm_cache_entry, uint8_t, &wasm_cache_entry::vm_version>
>
>,
ordered_non_unique<tag<by_first_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::first_block_num_used>>,
ordered_non_unique<tag<by_last_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::last_block_num_used>>
>
> wasm_cache_index;
wasm_cache_index wasm_instantiation_cache;
const chainbase::database& db;
};
#define _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
_REGISTER_WAVM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) \
_REGISTER_WABT_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) \
_REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)
#define _REGISTER_INTRINSIC4(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
_REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG )
#define _REGISTER_INTRINSIC3(CLS, MOD, METHOD, WASM_SIG, NAME)\
_REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, decltype(&CLS::METHOD) )
#define _REGISTER_INTRINSIC2(CLS, MOD, METHOD, WASM_SIG)\
_REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, BOOST_PP_STRINGIZE(METHOD), decltype(&CLS::METHOD) )
#define _REGISTER_INTRINSIC1(CLS, MOD, METHOD)\
static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":" BOOST_PP_STRINGIZE(METHOD) " without a signature");
#define _REGISTER_INTRINSIC0(CLS, MOD, METHOD)\
static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":<unknown> without a method name and signature");
#define _UNWRAP_SEQ(...) __VA_ARGS__
#define _EXPAND_ARGS(CLS, MOD, INFO)\
( CLS, MOD, _UNWRAP_SEQ INFO )
#define _REGISTER_INTRINSIC(R, CLS, INFO)\
BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, "env", INFO), BOOST_PP_EMPTY())
#define REGISTER_INTRINSICS(CLS, MEMBERS)\
BOOST_PP_SEQ_FOR_EACH(_REGISTER_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))
#define _REGISTER_INJECTED_INTRINSIC(R, CLS, INFO)\
BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, EOSIO_INJECTED_MODULE_NAME, INFO), BOOST_PP_EMPTY())
#define REGISTER_INJECTED_INTRINSICS(CLS, MEMBERS)\
BOOST_PP_SEQ_FOR_EACH(_REGISTER_INJECTED_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))
} } // eosio::chain
<commit_msg>just totally disable injection for now<commit_after>#pragma once
#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/webassembly/wavm.hpp>
#include <eosio/chain/webassembly/wabt.hpp>
#include <eosio/chain/webassembly/eos-vm.hpp>
#include <eosio/chain/webassembly/runtime_interface.hpp>
#include <eosio/chain/wasm_eosio_injection.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/code_object.hpp>
#include <eosio/chain/exceptions.hpp>
#include <fc/scoped_exit.hpp>
#include "IR/Module.h"
#include "Runtime/Intrinsics.h"
#include "Platform/Platform.h"
#include "WAST/WAST.h"
#include "IR/Validate.h"
#include <eosio/vm/allocator.hpp>
using namespace fc;
using namespace eosio::chain::webassembly;
using namespace eosio::vm;
using namespace IR;
using namespace Runtime;
using boost::multi_index_container;
namespace eosio { namespace chain {
struct wasm_interface_impl {
struct wasm_cache_entry {
digest_type code_hash;
uint32_t first_block_num_used;
uint32_t last_block_num_used;
std::unique_ptr<wasm_instantiated_module_interface> module;
uint8_t vm_type = 0;
uint8_t vm_version = 0;
};
struct by_hash;
struct by_first_block_num;
struct by_last_block_num;
wasm_interface_impl(wasm_interface::vm_type vm, const chainbase::database& d) : db(d) {
if(vm == wasm_interface::vm_type::wavm)
runtime_interface = std::make_unique<webassembly::wavm::wavm_runtime>();
else if(vm == wasm_interface::vm_type::wabt)
runtime_interface = std::make_unique<webassembly::wabt_runtime::wabt_runtime>();
else if(vm == wasm_interface::vm_type::eos_vm)
runtime_interface = std::make_unique<webassembly::eos_vm_runtime::eos_vm_runtime>();
else
EOS_THROW(wasm_exception, "wasm_interface_impl fall through");
}
~wasm_interface_impl() {
if(is_shutting_down)
for(wasm_cache_index::iterator it = wasm_instantiation_cache.begin(); it != wasm_instantiation_cache.end(); ++it)
wasm_instantiation_cache.modify(it, [](wasm_cache_entry& e) {
e.module.release();
});
}
static wasm_allocator* get_wasm_allocator() {
static wasm_allocator walloc;
return &walloc;
}
std::vector<uint8_t> parse_initial_memory(const Module& module) {
std::vector<uint8_t> mem_image;
for(const DataSegment& data_segment : module.dataSegments) {
EOS_ASSERT(data_segment.baseOffset.type == InitializerExpression::Type::i32_const, wasm_exception, "");
EOS_ASSERT(module.memories.defs.size(), wasm_exception, "");
const U32 base_offset = data_segment.baseOffset.i32;
const Uptr memory_size = (module.memories.defs[0].type.size.min << IR::numBytesPerPageLog2);
if(base_offset >= memory_size || base_offset + data_segment.data.size() > memory_size)
FC_THROW_EXCEPTION(wasm_execution_error, "WASM data segment outside of valid memory range");
if(base_offset + data_segment.data.size() > mem_image.size())
mem_image.resize(base_offset + data_segment.data.size(), 0x00);
memcpy(mem_image.data() + base_offset, data_segment.data.data(), data_segment.data.size());
}
return mem_image;
}
void code_block_num_last_used(const digest_type& code_hash, const uint8_t& vm_type, const uint8_t& vm_version, const uint32_t& block_num) {
wasm_cache_index::iterator it = wasm_instantiation_cache.find(boost::make_tuple(code_hash, vm_type, vm_version));
if(it != wasm_instantiation_cache.end())
wasm_instantiation_cache.modify(it, [block_num](wasm_cache_entry& e) {
e.last_block_num_used = block_num;
});
}
void current_lib(uint32_t lib) {
//anything last used before or on the LIB can be evicted
wasm_instantiation_cache.get<by_last_block_num>().erase(wasm_instantiation_cache.get<by_last_block_num>().begin(), wasm_instantiation_cache.get<by_last_block_num>().upper_bound(lib));
}
const std::unique_ptr<wasm_instantiated_module_interface>& get_instantiated_module( const digest_type& code_hash, const uint8_t& vm_type,
const uint8_t& vm_version, transaction_context& trx_context, bool inject )
{
wasm_cache_index::iterator it = wasm_instantiation_cache.find(
boost::make_tuple(code_hash, vm_type, vm_version) );
const code_object* codeobject = nullptr;
if(it == wasm_instantiation_cache.end()) {
codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));
it = wasm_instantiation_cache.emplace( wasm_interface_impl::wasm_cache_entry{
.code_hash = code_hash,
.first_block_num_used = codeobject->first_block_used,
.last_block_num_used = UINT32_MAX,
.module = nullptr,
.vm_type = vm_type,
.vm_version = vm_version
} ).first;
}
if(!it->module) {
if(!codeobject)
codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));
auto timer_pause = fc::make_scoped_exit([&](){
trx_context.resume_billing_timer();
});
trx_context.pause_billing_timer();
IR::Module module;
std::vector<U8> bytes = {(const U8*)codeobject->code.data(), (const U8*)codeobject->code.data() + codeobject->code.size()};
try {
Serialization::MemoryInputStream stream((const U8*)bytes.data(), bytes.size());
WASM::serialize(stream, module);
module.userSections.clear();
} catch(const Serialization::FatalSerializationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
} catch(const IR::ValidationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
}
if(false && inject) {
wasm_injections::wasm_binary_injection injector(module);
injector.inject();
std::cout << "INJECTING!!!!!!!!!!!!\n";
try {
Serialization::ArrayOutputStream outstream;
WASM::serialize(outstream, module);
bytes = outstream.getBytes();
} catch(const Serialization::FatalSerializationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
} catch(const IR::ValidationException& e) {
EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
}
}
wasm_instantiation_cache.modify(it, [&](auto& c) {
c.module = runtime_interface->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module));
});
}
return it->module;
}
bool is_shutting_down = false;
std::unique_ptr<wasm_runtime_interface> runtime_interface;
wasm_interface::vm_type runtime;
typedef boost::multi_index_container<
wasm_cache_entry,
indexed_by<
ordered_unique<tag<by_hash>,
composite_key< wasm_cache_entry,
member<wasm_cache_entry, digest_type, &wasm_cache_entry::code_hash>,
member<wasm_cache_entry, uint8_t, &wasm_cache_entry::vm_type>,
member<wasm_cache_entry, uint8_t, &wasm_cache_entry::vm_version>
>
>,
ordered_non_unique<tag<by_first_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::first_block_num_used>>,
ordered_non_unique<tag<by_last_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::last_block_num_used>>
>
> wasm_cache_index;
wasm_cache_index wasm_instantiation_cache;
const chainbase::database& db;
};
#define _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
_REGISTER_WAVM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) \
_REGISTER_WABT_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) \
_REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)
#define _REGISTER_INTRINSIC4(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
_REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG )
#define _REGISTER_INTRINSIC3(CLS, MOD, METHOD, WASM_SIG, NAME)\
_REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, decltype(&CLS::METHOD) )
#define _REGISTER_INTRINSIC2(CLS, MOD, METHOD, WASM_SIG)\
_REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, BOOST_PP_STRINGIZE(METHOD), decltype(&CLS::METHOD) )
#define _REGISTER_INTRINSIC1(CLS, MOD, METHOD)\
static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":" BOOST_PP_STRINGIZE(METHOD) " without a signature");
#define _REGISTER_INTRINSIC0(CLS, MOD, METHOD)\
static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":<unknown> without a method name and signature");
#define _UNWRAP_SEQ(...) __VA_ARGS__
#define _EXPAND_ARGS(CLS, MOD, INFO)\
( CLS, MOD, _UNWRAP_SEQ INFO )
#define _REGISTER_INTRINSIC(R, CLS, INFO)\
BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, "env", INFO), BOOST_PP_EMPTY())
#define REGISTER_INTRINSICS(CLS, MEMBERS)\
BOOST_PP_SEQ_FOR_EACH(_REGISTER_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))
#define _REGISTER_INJECTED_INTRINSIC(R, CLS, INFO)\
BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, EOSIO_INJECTED_MODULE_NAME, INFO), BOOST_PP_EMPTY())
#define REGISTER_INJECTED_INTRINSICS(CLS, MEMBERS)\
BOOST_PP_SEQ_FOR_EACH(_REGISTER_INJECTED_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))
} } // eosio::chain
<|endoftext|>
|
<commit_before>#include "bittorrent/ui/platforms/IOS.h"
#if BT_IOS
#import <UIKit/UIAlertView.h>
#import <UIKit/UIApplication.h>
@interface AlertViewHelper : NSObject<UIAlertViewDelegate>
typedef void(^CompletionHandler)(NSInteger buttonIndex);
@property (strong,nonatomic) CompletionHandler completionHandler;
+ (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler;
@end
@implementation AlertViewHelper
+ (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler {
__block AlertViewHelper* delegate = [AlertViewHelper new];
alertView.delegate = delegate;
delegate.completionHandler = ^(NSInteger buttonIndex) {
handler(buttonIndex);
alertView.delegate = nil;
delegate = nil;
};
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
self.completionHandler(buttonIndex);
}
@end
namespace bittorrent {
namespace ui {
namespace platforms {
bool IOS::canOpenURL(const char* url) const {
return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}
bool IOS::openURL(const char* url) {
return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}
void IOS::openDialog(Window* window, const char* title, const char* message, const std::vector<std::string>& buttons, std::function<void(int)> action) {
UIAlertView* alert = [UIAlertView new];
alert.title = [NSString stringWithUTF8String:title];
alert.message = [NSString stringWithUTF8String:message];
for (auto& button : buttons) {
[alert addButtonWithTitle:[NSString stringWithUTF8String:button.c_str()]];
}
[AlertViewHelper showAlertView:alert withCompletionHandler:^(NSInteger buttonIndex) {
action(buttonIndex);
}];
}
}}}
#endif
<commit_msg>suppress warning<commit_after>#include "bittorrent/ui/platforms/IOS.h"
#if BT_IOS
#import <UIKit/UIAlertView.h>
#import <UIKit/UIApplication.h>
@interface AlertViewHelper : NSObject<UIAlertViewDelegate>
typedef void(^CompletionHandler)(NSInteger buttonIndex);
@property (strong,nonatomic) CompletionHandler completionHandler;
+ (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler;
@end
@implementation AlertViewHelper
+ (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
__block AlertViewHelper* delegate = [AlertViewHelper new];
alertView.delegate = delegate;
delegate.completionHandler = ^(NSInteger buttonIndex) {
handler(buttonIndex);
alertView.delegate = nil;
delegate = nil;
};
[alertView show];
#pragma clang diagnostic pop
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
self.completionHandler(buttonIndex);
}
@end
namespace bittorrent {
namespace ui {
namespace platforms {
bool IOS::canOpenURL(const char* url) const {
return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}
bool IOS::openURL(const char* url) {
return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}
void IOS::openDialog(Window* window, const char* title, const char* message, const std::vector<std::string>& buttons, std::function<void(int)> action) {
UIAlertView* alert = [UIAlertView new];
alert.title = [NSString stringWithUTF8String:title];
alert.message = [NSString stringWithUTF8String:message];
for (auto& button : buttons) {
[alert addButtonWithTitle:[NSString stringWithUTF8String:button.c_str()]];
}
[AlertViewHelper showAlertView:alert withCompletionHandler:^(NSInteger buttonIndex) {
action(buttonIndex);
}];
}
}}}
#endif
<|endoftext|>
|
<commit_before>
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Windows4Root.h"
#include "TWin32SplashThread.h"
TWin32SplashThread *gSplash = 0;
extern void CreateSplash(DWORD time, BOOL extended);
extern void DestroySplashScreen();
//______________________________________________________________________________
static DWORD WINAPI HandleSplashThread(LPVOID extended)
{
// thread for handling Splash Screen
CreateSplash(4, (Bool_t)extended);
::ExitThread(0);
if (gSplash) delete gSplash;
gSplash = 0;
return 0;
}
//______________________________________________________________________________
TWin32SplashThread::TWin32SplashThread(Bool_t extended)
{
// ctor.
fHandle = 0;
DWORD splashId = 0;
fHandle = ::CreateThread( NULL, 0,&HandleSplashThread, (LPVOID)extended, 0, &splashId );
gSplash = this;
}
//______________________________________________________________________________
TWin32SplashThread::~TWin32SplashThread()
{
// dtor
DestroySplashScreen();
TerminateThread(fHandle, 0);
if (fHandle) ::CloseHandle(fHandle);
fHandle = 0;
}
<commit_msg>From Axel: in C++ "return" is better than ExitThread. Says MS. And who are we to doubt that!<commit_after>
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Windows4Root.h"
#include "TWin32SplashThread.h"
TWin32SplashThread *gSplash = 0;
extern void CreateSplash(DWORD time, BOOL extended);
extern void DestroySplashScreen();
//______________________________________________________________________________
static DWORD WINAPI HandleSplashThread(LPVOID extended)
{
// thread for handling Splash Screen
CreateSplash(4, (Bool_t)extended);
if (gSplash) delete gSplash;
gSplash = 0;
return 0;
}
//______________________________________________________________________________
TWin32SplashThread::TWin32SplashThread(Bool_t extended)
{
// ctor.
fHandle = 0;
DWORD splashId = 0;
fHandle = ::CreateThread( NULL, 0,&HandleSplashThread, (LPVOID)extended, 0, &splashId );
gSplash = this;
}
//______________________________________________________________________________
TWin32SplashThread::~TWin32SplashThread()
{
// dtor
DestroySplashScreen();
TerminateThread(fHandle, 0);
if (fHandle) ::CloseHandle(fHandle);
fHandle = 0;
}
<|endoftext|>
|
<commit_before>#include "Card.h"
#include "Deck.h"
int main() {
// Instantiate deck of cards
Deck *d = new Deck();
// Pick a card from the deck
string noCards;
// 1 or 2 character number
const regex reg("\\d{1,2}");
while (true) {
cout << "How many cards (1-52): " << flush;
getline(cin, noCards);
// Validate user input
const bool result = regex_match(noCards, reg);
if (result)
{
int iNoCards = atoi(noCards.c_str());
for (unsigned int i = 0; i < iNoCards; ++i) {
d->pickCard();
}
}
else
{
cout << "Number 1-25 please" << endl;
}
cin.clear();
if (noCards == "0") { break; }
}
//cin.get();
delete d;
return 0;
}<commit_msg>Improved support for user input<commit_after>#include "Card.h"
#include "Deck.h"
bool validEntry(string *nC, unsigned int *iC){
// 1 or 2 character number regex pattern
const regex reg("\\d{1,2}");
// Validate user input
bool valid = regex_match(*nC, reg);
const string s = *nC;
*iC = atoi(s.c_str());
if (*iC > 52) { valid = false; }
return valid;
}
int main() {
// Instantiate deck of cards
Deck *d = new Deck();
// Pick a card from the deck
string noCards;
string *nC = &noCards;
// integer for valid result
unsigned int iNoCards;
unsigned int *iN = &iNoCards;
while (true) {
d->getDeck();
cout << "How many cards (1-52): " << flush;
getline(cin, *nC);
if (validEntry(nC, iN))
{
for (unsigned int i = 0; i < *iN; ++i) {
d->pickCard();
}
}
else
{
cout << "Number 1-25 please" << endl;
}
cin.clear();
if (noCards == "0") { break; }
}
delete d;
return 0;
}<|endoftext|>
|
<commit_before>/// \file ROOT/RHistBufferedFill.h
/// \ingroup Hist ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-07-03
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_RHistBufferedFill
#define ROOT7_RHistBufferedFill
#include "ROOT/RSpan.hxx"
namespace ROOT {
namespace Experimental {
namespace Internal {
template <class DERIVED, class HIST, int SIZE>
class RHistBufferedFillBase {
public:
using CoordArray_t = typename HIST::CoordArray_t;
using Weight_t = typename HIST::Weight_t;
private:
size_t fCursor = 0;
std::array<CoordArray_t, SIZE> fXBuf;
std::array<Weight_t, SIZE> fWBuf;
public:
RHistBufferedFillBase() {}
~RHistBufferedFillBase() { toDerived().Flush(); }
DERIVED &toDerived() { return *static_cast<DERIVED *>(this); }
const DERIVED &toDerived() const { return *static_cast<const DERIVED *>(this); }
std::span<const CoordArray_t> GetCoords() const
{
return std::span<const CoordArray_t>(fXBuf.begin(), fXBuf.begin() + fCursor);
}
std::span<const Weight_t> GetWeights() const
{
return std::span<const Weight_t>(fWBuf.begin(), fWBuf.begin() + fCursor);
}
void Fill(const CoordArray_t &x, Weight_t weight = 1.)
{
fXBuf[fCursor] = x;
fWBuf[fCursor++] = weight;
if (fCursor == SIZE) {
Flush();
}
}
void Flush() {
toDerived().FlushImpl();
fCursor = 0;
}
};
} // namespace Internal
/** \class RHistBufferedFill
Buffers calls to Fill().
Once the buffer is full, on destruction of when calling Flush(), it sends the
buffers off as an ideally vectorizable FillN() operation. It also serves as a
multi-threaded way of filling the same histogram, reducing the locking
frequency.
The HIST template can be either a RHist instance, a RHistImpl instance, or
a RHistLockedFill instance.
**/
template <class HIST, int SIZE = 1024>
class RHistBufferedFill: public Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE> {
public:
using Hist_t = HIST;
using CoordArray_t = typename HIST::CoordArray_t;
using Weight_t = typename HIST::Weight_t;
private:
HIST &fHist;
size_t fCursor = 0;
std::array<CoordArray_t, SIZE> fXBuf;
std::array<Weight_t, SIZE> fWBuf;
friend class Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE>;
void FlushImpl() { fHist.FillN(this->GetCoords(), this->GetWeights()); }
public:
RHistBufferedFill(Hist_t &hist): fHist{hist} {}
void FillN(const std::span<const CoordArray_t> xN, const std::span<const Weight_t> weightN)
{
fHist.FillN(xN, weightN);
}
void FillN(const std::span<const CoordArray_t> xN) { fHist.FillN(xN); }
HIST &GetHist()
{
this->Flush(); // synchronize!
return fHist;
}
operator HIST &() { return GetHist(); }
static constexpr int GetNDim() { return HIST::GetNDim(); }
};
} // namespace Experimental
} // namespace ROOT
#endif
<commit_msg>Do not duplicate RHistBufferedFillBase data members in RHistBufferedFill<commit_after>/// \file ROOT/RHistBufferedFill.h
/// \ingroup Hist ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-07-03
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_RHistBufferedFill
#define ROOT7_RHistBufferedFill
#include "ROOT/RSpan.hxx"
namespace ROOT {
namespace Experimental {
namespace Internal {
template <class DERIVED, class HIST, int SIZE>
class RHistBufferedFillBase {
public:
using CoordArray_t = typename HIST::CoordArray_t;
using Weight_t = typename HIST::Weight_t;
private:
size_t fCursor = 0;
std::array<CoordArray_t, SIZE> fXBuf;
std::array<Weight_t, SIZE> fWBuf;
public:
RHistBufferedFillBase() {}
~RHistBufferedFillBase() { toDerived().Flush(); }
DERIVED &toDerived() { return *static_cast<DERIVED *>(this); }
const DERIVED &toDerived() const { return *static_cast<const DERIVED *>(this); }
std::span<const CoordArray_t> GetCoords() const
{
return std::span<const CoordArray_t>(fXBuf.begin(), fXBuf.begin() + fCursor);
}
std::span<const Weight_t> GetWeights() const
{
return std::span<const Weight_t>(fWBuf.begin(), fWBuf.begin() + fCursor);
}
void Fill(const CoordArray_t &x, Weight_t weight = 1.)
{
fXBuf[fCursor] = x;
fWBuf[fCursor++] = weight;
if (fCursor == SIZE) {
Flush();
}
}
void Flush() {
toDerived().FlushImpl();
fCursor = 0;
}
};
} // namespace Internal
/** \class RHistBufferedFill
Buffers calls to Fill().
Once the buffer is full, on destruction of when calling Flush(), it sends the
buffers off as an ideally vectorizable FillN() operation. It also serves as a
multi-threaded way of filling the same histogram, reducing the locking
frequency.
The HIST template can be either a RHist instance, a RHistImpl instance, or
a RHistLockedFill instance.
**/
template <class HIST, int SIZE = 1024>
class RHistBufferedFill: public Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE> {
public:
using Hist_t = HIST;
using CoordArray_t = typename HIST::CoordArray_t;
using Weight_t = typename HIST::Weight_t;
private:
HIST &fHist;
friend class Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE>;
void FlushImpl() { fHist.FillN(this->GetCoords(), this->GetWeights()); }
public:
RHistBufferedFill(Hist_t &hist): fHist{hist} {}
void FillN(const std::span<const CoordArray_t> xN, const std::span<const Weight_t> weightN)
{
fHist.FillN(xN, weightN);
}
void FillN(const std::span<const CoordArray_t> xN) { fHist.FillN(xN); }
HIST &GetHist()
{
this->Flush(); // synchronize!
return fHist;
}
operator HIST &() { return GetHist(); }
static constexpr int GetNDim() { return HIST::GetNDim(); }
};
} // namespace Experimental
} // namespace ROOT
#endif
<|endoftext|>
|
<commit_before>#include <SofaTest/Python_test.h>
#include <sofa/helper/system/FileSystem.h>
namespace sofa {
static bool ends_with(const std::string& suffix, const std::string& full){
const std::size_t lf = full.length();
const std::size_t ls = suffix.length();
if(lf < ls) return false;
return (0 == full.compare(lf - ls, ls, suffix));
}
static bool starts_with(const std::string& prefix, const std::string& full){
const std::size_t lf = full.length();
const std::size_t lp = prefix.length();
if(lf < lp) return false;
return (0 == full.compare(0, lp, prefix));
}
static bool is_scene_file(const std::string& filename) {
return starts_with("scene_", filename) && ends_with(".py", filename);
}
static bool is_test_file(const std::string& filename) {
return starts_with("test_", filename) && ends_with(".py", filename);
}
// these are sofa scenes
static struct Tests : public Python_test_list
{
Tests()
{
static const std::string scenePath = std::string(COMPLIANT_TEST_PYTHON_DIR);
std::vector<std::string> files;
helper::system::FileSystem::listDirectory(scenePath, files);
for(const std::string& file : files) {
if(is_scene_file(file) ) {
addTest(file, scenePath);
}
}
}
} tests;
// run test list
INSTANTIATE_TEST_CASE_P(Batch,
Python_scene_test,
::testing::ValuesIn(tests.list));
TEST_P(Python_scene_test, sofa_python_scene_tests)
{
run(GetParam());
}
////////////////////////
// these are just python files loaded in the sofa python environment (paths...)
static struct Tests2 : public Python_test_list
{
Tests2()
{
static const std::string testPath = std::string(COMPLIANT_TEST_PYTHON_DIR);
std::vector<std::string> files;
helper::system::FileSystem::listDirectory(testPath, files);
for(const std::string& file : files) {
if(is_test_file(file) ) {
addTest(file, testPath);
}
}
}
} tests2;
// run test list
INSTANTIATE_TEST_CASE_P(Batch,
Python_test,
::testing::ValuesIn(tests2.list));
TEST_P(Python_test, sofa_python_tests)
{
run(GetParam());
}
} // namespace sofa
<commit_msg>[Compliant] use SofaTest test list from dir<commit_after>#include <SofaTest/Python_test.h>
#include <sofa/helper/system/FileSystem.h>
namespace sofa {
// these are sofa scenes
static struct Tests : public Python_test_list {
Tests() {
addTestDir(COMPLIANT_TEST_PYTHON_DIR, "scene_");
}
} tests;
// run test list
INSTANTIATE_TEST_CASE_P(Batch,
Python_scene_test,
::testing::ValuesIn(tests.list));
TEST_P(Python_scene_test, sofa_python_scene_tests)
{
run(GetParam());
}
////////////////////////
// these are just python files loaded in the sofa python environment (paths...)
static struct Tests2 : public Python_test_list {
Tests2() {
addTestDir(COMPLIANT_TEST_PYTHON_DIR, "test_");
}
} tests2;
// run test list
INSTANTIATE_TEST_CASE_P(Batch,
Python_test,
::testing::ValuesIn(tests2.list));
TEST_P(Python_test, sofa_python_tests)
{
run(GetParam());
}
} // namespace sofa
<|endoftext|>
|
<commit_before>#ifndef VFRENDERING_ISOSURFACE_RENDERER_H
#define VFRENDERING_ISOSURFACE_RENDERER_H
#include <functional>
#include <VFRendering/RendererBase.hxx>
namespace VFRendering {
class IsosurfaceRenderer : public RendererBase {
public:
enum Option {
ISOVALUE = 700,
VALUEFUNCTION
};
IsosurfaceRenderer(const View& view);
virtual ~IsosurfaceRenderer();
virtual void update(bool keep_geometry) override;
virtual void draw(float aspect_ratio) const override;
virtual void optionsHaveChanged(const std::vector<int>& changed_options) override;
private:
void updateShaderProgram();
void updateIsosurfaceIndices();
unsigned int m_program = 0;
unsigned int m_vao = 0;
unsigned int m_ibo = 0;
unsigned int m_position_vbo = 0;
unsigned int m_direction_vbo = 0;
unsigned int m_num_indices = 0;
};
}
template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::ISOVALUE> {
double default_value = 0;
};
template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::VALUEFUNCTION> {
std::function<float(const glm::vec3&, const glm::vec3&)> default_value = [] (const glm::vec3& position, const glm::vec3& direction) {
(void)direction;
return position.x+position.y;
};
};
#endif
<commit_msg>Set default value function back to direction.z<commit_after>#ifndef VFRENDERING_ISOSURFACE_RENDERER_H
#define VFRENDERING_ISOSURFACE_RENDERER_H
#include <functional>
#include <VFRendering/RendererBase.hxx>
namespace VFRendering {
class IsosurfaceRenderer : public RendererBase {
public:
enum Option {
ISOVALUE = 700,
VALUEFUNCTION
};
IsosurfaceRenderer(const View& view);
virtual ~IsosurfaceRenderer();
virtual void update(bool keep_geometry) override;
virtual void draw(float aspect_ratio) const override;
virtual void optionsHaveChanged(const std::vector<int>& changed_options) override;
private:
void updateShaderProgram();
void updateIsosurfaceIndices();
unsigned int m_program = 0;
unsigned int m_vao = 0;
unsigned int m_ibo = 0;
unsigned int m_position_vbo = 0;
unsigned int m_direction_vbo = 0;
unsigned int m_num_indices = 0;
};
}
template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::ISOVALUE> {
double default_value = 0;
};
template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::VALUEFUNCTION> {
std::function<float(const glm::vec3&, const glm::vec3&)> default_value = [] (const glm::vec3& position, const glm::vec3& direction) {
(void)position;
return direction.z;
};
};
#endif
<|endoftext|>
|
<commit_before>#ifndef CLOTHO_ITERATOR_HELPER_HPP_
#define CLOTHO_ITERATOR_HELPER_HPP_
#include "clotho/utility/element_iterator.hpp"
namespace clotho {
namespace utility {
template < class Container >
struct iterator_helper {
typedef clotho::utility::element_iterator< Container > type;
static type make_first( Container & con ) {
return type( con );
}
static type make_second( Container & con ) {
return type( con );
}
};
template < class Element >
struct iterator_helper< std::pair< Element, Element > > {
typedef element_iterator< std::pair< Element, Element > > type;
static type make_first( std::pair< Element, Element > & ind ) {
return element_iterator< Element >( ind, pair_iterator_state::FIRST);
}
static type make_last( std::pair< Element, Element > & ind ) {
return element_iterator< Element >( ind );
}
};
#include <memory>
template < class Element >
struct iterator_helper< std::shared_ptr< Element > > {
typedef typename iterator_helper< Element >::type type;
static type make_first( std::shared_ptr< Element > s ) {
return iterator_helper< Element >::make_first( *s );
}
static type make_last( std::shared_ptr< Element > s ) {
return iterator_helper< Element >::make_last( *s );
}
};
} // namespace utility {
} // namespace clotho {
#endif // CLOTHO_ITERATOR_HELPER_HPP_
<commit_msg>slight changes to helpers<commit_after>#ifndef CLOTHO_ITERATOR_HELPER_HPP_
#define CLOTHO_ITERATOR_HELPER_HPP_
#include "clotho/utility/element_iterator.hpp"
namespace clotho {
namespace utility {
template < class Container >
struct iterator_helper {
typedef clotho::utility::element_iterator< Container > type;
static type make_first( Container & con ) {
return type( con );
}
static type make_last( Container & con ) {
return type( con );
}
};
template < class Element >
struct iterator_helper< std::pair< Element, Element > > {
typedef clotho::utility::element_iterator< std::pair< Element, Element > > type;
static type make_first( std::pair< Element, Element > & ind ) {
return type( ind, pair_iterator_state::FIRST);
}
static type make_last( std::pair< Element, Element > & ind ) {
return type( ind );
}
};
template < class Element >
struct iterator_helper< std::shared_ptr< Element > > :
public iterator_helper< Element >
{
typedef iterator_helper< Element > base_type;
typedef typename base_type::type type;
static type make_first( std::shared_ptr< Element > s ) {
return base_type::make_first( *s );
}
static type make_last( std::shared_ptr< Element > s ) {
return base_type::make_last( *s );
}
};
} // namespace utility {
} // namespace clotho {
#endif // CLOTHO_ITERATOR_HELPER_HPP_
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GLOBAL_CONFIG_PARSER_HPP
#define RJ_GLOBAL_CONFIG_PARSER_HPP
#include <string>
#include <utility>
#include <vector>
namespace rj
{
using config_entry = std::pair<std::string, std::string>;
using config_entry_vec = std::vector<config_entry>;
class config_parser
{
const std::vector<std::string>& m_content;
config_entry_vec m_entrys;
public:
config_parser(const std::vector<std::string>& content) :
m_content{content}
{this->parse();}
auto get_entrys() const noexcept
-> const decltype(m_entrys)&
{return m_entrys;}
private:
void parse() noexcept
{
for(auto& a : m_content)
{
auto pos_equ(a.find('='));
if(pos_equ != std::string::npos)
{
auto pair(std::make_pair(a.substr(0, pos_equ), a.substr(pos_equ + 1, a.size() - pos_equ - 1)));
if(!pair.first.empty() && !pair.second.empty())
m_entrys.push_back(pair);
}
}
}
};
}
#endif // RJ_GLOBAL_CONFIG_PARSER_HPP
<commit_msg>config_parser: added empty()<commit_after>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GLOBAL_CONFIG_PARSER_HPP
#define RJ_GLOBAL_CONFIG_PARSER_HPP
#include <string>
#include <utility>
#include <vector>
namespace rj
{
using config_entry = std::pair<std::string, std::string>;
using config_entry_vec = std::vector<config_entry>;
class config_parser
{
const std::vector<std::string>& m_content;
config_entry_vec m_entrys;
public:
config_parser(const std::vector<std::string>& content) :
m_content{content}
{this->parse();}
auto get_entrys() const noexcept
-> const decltype(m_entrys)&
{return m_entrys;}
bool empty() const noexcept
{return m_entrys.empty();}
private:
void parse() noexcept
{
for(auto& a : m_content)
{
auto pos_equ(a.find('='));
if(pos_equ != std::string::npos)
{
auto pair(std::make_pair(a.substr(0, pos_equ), a.substr(pos_equ + 1, a.size() - pos_equ - 1)));
if(!pair.first.empty() && !pair.second.empty())
m_entrys.push_back(pair);
}
}
}
};
}
#endif // RJ_GLOBAL_CONFIG_PARSER_HPP
<|endoftext|>
|
<commit_before>/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES 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 qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file interfaces/matlab/qpOASES_matlab_utils.hpp
* \author Hans Joachim Ferreau, Alexander Buchner
* \version 3.2
* \date 2007-2015
*
* Collects utility functions for Interface to Matlab(R) that
* enables to call qpOASES as a MEX function.
*
*/
/* Work-around for settings where mexErrMsgTxt causes unexpected behaviour. */
#ifdef __AVOID_MEXERRMSGTXT__
#define myMexErrMsgTxt( TEXT ) mexPrintf( "%s\n\n",(TEXT) );
#else
#define myMexErrMsgTxt mexErrMsgTxt
#endif
#include "mex.h"
#include "matrix.h"
#include "string.h"
#include <vector>
/*
* QProblem instance class
*/
class QPInstance
{
private:
static int_t s_nexthandle;
public:
QPInstance( uint_t _nV = 0,
uint_t _nC = 0,
HessianType _hessianType = HST_UNKNOWN,
BooleanType _isSimplyBounded = BT_FALSE,
BooleanType _sparseLA = BT_FALSE
);
~QPInstance( );
returnValue deleteQPMatrices();
int_t getNV() const;
int_t getNC() const;
int_t handle;
SQProblem* sqp;
QProblemB* qpb;
BooleanType isSimplyBounded;
BooleanType sparseLA;
SymmetricMatrix* H;
Matrix* A;
sparse_int_t* Hir;
sparse_int_t* Hjc;
sparse_int_t* Air;
sparse_int_t* Ajc;
real_t* Hv;
real_t* Av;
};
/*
* end of file
*/
<commit_msg>added typeinfo header to Matlab interface as suggested in ticket #49<commit_after>/*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES 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 qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file interfaces/matlab/qpOASES_matlab_utils.hpp
* \author Hans Joachim Ferreau, Alexander Buchner
* \version 3.2
* \date 2007-2015
*
* Collects utility functions for Interface to Matlab(R) that
* enables to call qpOASES as a MEX function.
*
*/
/* Work-around for settings where mexErrMsgTxt causes unexpected behaviour. */
#ifdef __AVOID_MEXERRMSGTXT__
#define myMexErrMsgTxt( TEXT ) mexPrintf( "%s\n\n",(TEXT) );
#else
#define myMexErrMsgTxt mexErrMsgTxt
#endif
/* Workaround for problem on Matlab 2012b
* see https://github.com/robotology/codyco-superbuild/issues/84
* see http://stackoverflow.com/questions/22440523/mex-files-using-xcode-5-1-under-os-x-10-9-with-matlab-2012a/22705789#22705789 */
/* #include <typeinfo> */
#include "mex.h"
#include "matrix.h"
#include "string.h"
#include <vector>
/*
* QProblem instance class
*/
class QPInstance
{
private:
static int_t s_nexthandle;
public:
QPInstance( uint_t _nV = 0,
uint_t _nC = 0,
HessianType _hessianType = HST_UNKNOWN,
BooleanType _isSimplyBounded = BT_FALSE,
BooleanType _sparseLA = BT_FALSE
);
~QPInstance( );
returnValue deleteQPMatrices();
int_t getNV() const;
int_t getNC() const;
int_t handle;
SQProblem* sqp;
QProblemB* qpb;
BooleanType isSimplyBounded;
BooleanType sparseLA;
SymmetricMatrix* H;
Matrix* A;
sparse_int_t* Hir;
sparse_int_t* Hjc;
sparse_int_t* Air;
sparse_int_t* Ajc;
real_t* Hv;
real_t* Av;
};
/*
* end of file
*/
<|endoftext|>
|
<commit_before>#include "arduino_serial.hpp"
#include <UartInterface.hpp>
#define ARDUINO_DEFAULT_SERIAL 1
#include <stdio.h>
#include <stdlib.h>
::uart::ConcreteUart UartCommand(ARDUINO_DEFAULT_SERIAL, &::arduino::serial::uart_callback);
namespace arduino
{
namespace serial
{
ArduinoSerial Serial;
void uart_callback (const uint8_t c)
{
Serial.uart_receive_fifo.push_back(c);
return;
}
ArduinoSerial::ArduinoSerial()
{
return;
}
void ArduinoSerial::begin(int Speed)
{
UartCommand.Configure();
this->uart_receive_fifo.clear();
return;
}
void ArduinoSerial::write(const char c)
{
UartCommand.send((const unsigned char*)&c, sizeof(c));
}
void ArduinoSerial::print(const char* pString)
{
while (*pString)
{
UartCommand.send((const unsigned char*)&(pString[0]), sizeof(pString[0]));
pString++;
}
}
void ArduinoSerial::print(const char c)
{
UartCommand.send((const unsigned char*)&c, sizeof(c));
}
void ArduinoSerial::print(const int c, ArduinoFormat_T format)
{
char Buffer[32];
memset(Buffer, 0, sizeof(Buffer));
if (format == DEC)
{
sprintf(Buffer, "%i", c);
}
else if (format == HEX)
{
sprintf(Buffer, "%x", c);
}
else
{
sprintf(Buffer, "%x", c);
}
this->print(Buffer);
}
void ArduinoSerial::print(double d, int size)
{
char Buffer[16];
memset(Buffer, 0, sizeof(Buffer));
sprintf(Buffer, "%05f", d);
this->print(Buffer);
}
void ArduinoSerial::println(const char c, ArduinoFormat_T format)
{
this->print(c, format);
this->println();
}
void ArduinoSerial::println(const char* pString)
{
this->print(pString);
this->println();
}
void ArduinoSerial::println()
{
this->print("\r\n");
}
int ArduinoSerial::available()
{
return this->uart_receive_fifo.size();
}
unsigned char ArduinoSerial::read()
{
uint8_t c;
c = this->uart_receive_fifo.front();
this->uart_receive_fifo.pop_front();
return c;
}
} //namespace serial
} //namespace arduino
<commit_msg>(ARDUINO) Fix string.h include.<commit_after>#include "arduino_serial.hpp"
#include <UartInterface.hpp>
#define ARDUINO_DEFAULT_SERIAL 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
::uart::ConcreteUart UartCommand(ARDUINO_DEFAULT_SERIAL, &::arduino::serial::uart_callback);
namespace arduino
{
namespace serial
{
ArduinoSerial Serial;
void uart_callback (const uint8_t c)
{
Serial.uart_receive_fifo.push_back(c);
return;
}
ArduinoSerial::ArduinoSerial()
{
return;
}
void ArduinoSerial::begin(int Speed)
{
UartCommand.Configure();
this->uart_receive_fifo.clear();
return;
}
void ArduinoSerial::write(const char c)
{
UartCommand.send((const unsigned char*)&c, sizeof(c));
}
void ArduinoSerial::print(const char* pString)
{
while (*pString)
{
UartCommand.send((const unsigned char*)&(pString[0]), sizeof(pString[0]));
pString++;
}
}
void ArduinoSerial::print(const char c)
{
UartCommand.send((const unsigned char*)&c, sizeof(c));
}
void ArduinoSerial::print(const int c, ArduinoFormat_T format)
{
char Buffer[32];
memset(Buffer, 0, sizeof(Buffer));
if (format == DEC)
{
sprintf(Buffer, "%i", c);
}
else if (format == HEX)
{
sprintf(Buffer, "%x", c);
}
else
{
sprintf(Buffer, "%x", c);
}
this->print(Buffer);
}
void ArduinoSerial::print(double d, int size)
{
char Buffer[16];
memset(Buffer, 0, sizeof(Buffer));
sprintf(Buffer, "%05f", d);
this->print(Buffer);
}
void ArduinoSerial::println(const char c, ArduinoFormat_T format)
{
this->print(c, format);
this->println();
}
void ArduinoSerial::println(const char* pString)
{
this->print(pString);
this->println();
}
void ArduinoSerial::println()
{
this->print("\r\n");
}
int ArduinoSerial::available()
{
return this->uart_receive_fifo.size();
}
unsigned char ArduinoSerial::read()
{
uint8_t c;
c = this->uart_receive_fifo.front();
this->uart_receive_fifo.pop_front();
return c;
}
} //namespace serial
} //namespace arduino
<|endoftext|>
|
<commit_before>#ifndef MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH
#define MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH
#include "simplify.hh"
#include "complex.hh"
#include "variables.hh"
#include "zero.hh"
#include "multiplication.hh"
#include "integral_polynomial.hh"
namespace manifolds {
template <class T>
struct Simplification<Composition<Real, ImagN<T> >, /*com_re_i*/ 0> {
static auto Combine(Composition<Real, ImagN<T> >) {
SIMPLIFY_INFO("Simplifying Real part of "
"non-complex function");
return zero;
}
};
template <class T>
struct Simplification<Composition<Imag, ImagN<T> >, /*com_im_i*/ 0> {
static auto Combine(Composition<Imag, ImagN<T> >) {
return GetIPolynomial<1>();
}
};
template <class T>
struct Simplification<Composition<Real, T>, /*com_re_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Real, T> t) {
return get<1>(t.GetFunctions());
}
};
template <class T>
struct Simplification<Composition<Imag, T>, /*com_im_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Imag, T> t) { return zero; }
};
template <class T>
struct Simplification<Composition<Phase, T>, /*com_ph_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Phase, T> t) {
auto t2 = get<1>(t.GetFunctions());
return MultiplyRaw(Sign()(t2), GetPolynomial(M_PI));
}
};
template <class T>
struct Simplification<Composition<Phase, ImagN<T> >, /*com_ph_i*/ 0> {
static auto Combine(Composition<Phase, ImagN<T> >) {
return GetPolynomial(M_PI);
}
};
template <class T>
struct Simplification<Composition<Norm, ImagN<T> >, /*com_nm_i*/ 0> {
static auto Combine(Composition<Norm, ImagN<T> >) {
return GetIPolynomial<1>();
}
};
template <class T>
struct Simplification<Composition<Norm, T>, /*com_nm_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Norm, T> t) {
return GetIPolynomial<0, 0, 1>()(get<1>(t.GetFunctions()));
}
};
template <class T>
struct Simplification<Composition<Conjugate, ImagN<T> >, /*com_con_i*/ 0> {
static auto Combine(Composition<Conjugate, ImagN<T> >) {
return UnaryMinus<ImagN<T> >();
}
};
template <class T>
struct Simplification<Composition<Conjugate, T>, /*com_con_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Conjugate, T> t) {
return get<1>(t.GetFunctions());
}
};
template <class T, class T2, T2... cs>
struct Simplification<
Composition<IntegralPolynomial<std::integer_sequence<T2, cs...> >,
ImagN<T> >,
/**/ 0, typename std::enable_if<(sizeof...(cs) > 2)>::type> {
typedef typename std::conditional<std::is_unsigned<T2>::value,
typename std::make_signed<T2>::type,
T2>::type Tout;
template <Tout c0, Tout c1, Tout... c_outs>
static auto Add(
int_<1>,
IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> > p) {
return AddRaw(
IntegralPolynomial<std::integer_sequence<Tout, c0> >(),
MultiplyRaw(IntegralPolynomial<std::integer_sequence<Tout, c1> >(), I));
}
template <Tout c0, Tout c1, Tout... c_outs, int N>
static auto Add(
int_<N>,
IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> >) {
static const Tout c0_2 =
c0 +
((N % 2 == 0)
? ((N % 4 == 0)
? nth<N - 2,
std::integral_constant<Tout, c_outs>...>::type::value
: -nth<N - 2, std::integral_constant<
Tout, c_outs>...>::type::value)
: 0);
static const Tout c1_2 =
c1 +
((N % 2 == 1)
? ((N % 4 == 1)
? nth<N - 2,
std::integral_constant<Tout, c_outs>...>::type::value
: -nth<N - 2, std::integral_constant<
Tout, c_outs>...>::type::value)
: 0);
return Add(int_<N - 1>(),
IntegralPolynomial<
std::integer_sequence<Tout, c0_2, c1_2, c_outs...> >());
}
static auto Combine(Composition<
IntegralPolynomial<std::integer_sequence<T2, cs...> >, ImagN<T> >) {
return Add(int_<sizeof...(cs) - 1>(),
IntegralPolynomial<std::integer_sequence<Tout, (Tout)cs...> >());
}
};
template <class... C, class Complex>
struct Simplification<Composition<ImagN<Complex>, C...>, /*com_i_cs*/ 0> {
static auto Combine(Composition<ImagN<Complex>, C...>) { return I; }
};
template <class F, class ... Fs>
struct Simplification<
Composition<
F, Addition<Fs...> >, /*re_add_fs*/0,
typename std::enable_if<
std::is_same<F, Real>::value ||
std::is_same<F, Imag>::value
>::type>
{
template <std::size_t ... is>
static auto Combine(Composition<
F, Addition<Fs...> > c,
std::integer_sequence<
std::size_t, is...>)
{
auto t = get<1>(c.GetFunctions()).GetFunctions();
return AddRaw((F()(get<is>(t)))...);
}
static auto Combine(Composition<
F, Addition<Fs...> > c)
{
return Combine(c, std::index_sequence_for<Fs...>());
}
};
template <class F, class ... Fs>
struct Simplification<
Composition<
F, Multiplication<Fs...> >, /*re_add_fs*/0,
typename std::enable_if<
std::is_same<F, Real>::value ||
std::is_same<F, Imag>::value
>::type>
{
template <std::size_t ... is>
static auto Combine(Composition<
F, Multiplication<Fs...> > c,
std::integer_sequence<
std::size_t, is...>)
{
auto t = get<1>(c.GetFunctions()).GetFunctions();
return MultiplyRaw((F()(get<is>(t)))...);
}
static auto Combine(Composition<
F, Multiplication<Fs...> > c)
{
return Combine(c, std::index_sequence_for<Fs...>());
}
};
}
#endif
<commit_msg>Split Real and Imag parts of multiplication into separate simplifications<commit_after>#ifndef MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH
#define MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH
#include "simplify.hh"
#include "complex.hh"
#include "variables.hh"
#include "zero.hh"
#include "multiplication.hh"
#include "integral_polynomial.hh"
namespace manifolds {
template <class T>
struct Simplification<Composition<Real, ImagN<T> >, /*com_re_i*/ 0> {
static auto Combine(Composition<Real, ImagN<T> >) {
SIMPLIFY_INFO("Simplifying Real part of "
"non-complex function");
return zero;
}
};
template <class T>
struct Simplification<Composition<Imag, ImagN<T> >, /*com_im_i*/ 0> {
static auto Combine(Composition<Imag, ImagN<T> >) {
return GetIPolynomial<1>();
}
};
template <class T>
struct Simplification<Composition<Real, T>, /*com_re_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Real, T> t) {
return get<1>(t.GetFunctions());
}
};
template <class T>
struct Simplification<Composition<Imag, T>, /*com_im_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Imag, T> t) { return zero; }
};
template <class T>
struct Simplification<Composition<Phase, T>, /*com_ph_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Phase, T> t) {
auto t2 = get<1>(t.GetFunctions());
return GetPolynomial(-M_PI/2, M_PI/2)(Sign()(t2));
}
};
template <class T>
struct Simplification<Composition<Phase, ImagN<T> >, /*com_ph_i*/ 0> {
static auto Combine(Composition<Phase, ImagN<T> >) {
return GetPolynomial(M_PI);
}
};
template <class T>
struct Simplification<Composition<Norm, ImagN<T> >, /*com_nm_i*/ 0> {
static auto Combine(Composition<Norm, ImagN<T> >) {
return GetIPolynomial<1>();
}
};
template <class T>
struct Simplification<Composition<Norm, T>, /*com_nm_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Norm, T> t) {
return GetIPolynomial<0, 0, 1>()(get<1>(t.GetFunctions()));
}
};
template <class T>
struct Simplification<Composition<Conjugate, ImagN<T> >, /*com_con_i*/ 0> {
static auto Combine(Composition<Conjugate, ImagN<T> >) {
return UnaryMinus<ImagN<T> >();
}
};
template <class T>
struct Simplification<Composition<Conjugate, T>, /*com_con_f*/ 1,
typename std::enable_if<ComplexOutputType<T>::value ==
NeverComplex>::type> {
static auto Combine(Composition<Conjugate, T> t) {
return get<1>(t.GetFunctions());
}
};
template <class T, class T2, T2... cs>
struct Simplification<
Composition<IntegralPolynomial<std::integer_sequence<T2, cs...> >,
ImagN<T> >,
/**/ 0, typename std::enable_if<(sizeof...(cs) > 2)>::type> {
typedef typename std::conditional<std::is_unsigned<T2>::value,
typename std::make_signed<T2>::type,
T2>::type Tout;
template <Tout c0, Tout c1, Tout... c_outs>
static auto Add(
int_<1>,
IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> > p) {
return AddRaw(
IntegralPolynomial<std::integer_sequence<Tout, c0> >(),
MultiplyRaw(IntegralPolynomial<std::integer_sequence<Tout, c1> >(), I));
}
template <Tout c0, Tout c1, Tout... c_outs, int N>
static auto Add(
int_<N>,
IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> >) {
static const Tout c0_2 =
c0 +
((N % 2 == 0)
? ((N % 4 == 0)
? nth<N - 2,
std::integral_constant<Tout, c_outs>...>::type::value
: -nth<N - 2, std::integral_constant<
Tout, c_outs>...>::type::value)
: 0);
static const Tout c1_2 =
c1 +
((N % 2 == 1)
? ((N % 4 == 1)
? nth<N - 2,
std::integral_constant<Tout, c_outs>...>::type::value
: -nth<N - 2, std::integral_constant<
Tout, c_outs>...>::type::value)
: 0);
return Add(int_<N - 1>(),
IntegralPolynomial<
std::integer_sequence<Tout, c0_2, c1_2, c_outs...> >());
}
static auto Combine(Composition<
IntegralPolynomial<std::integer_sequence<T2, cs...> >, ImagN<T> >) {
return Add(int_<sizeof...(cs) - 1>(),
IntegralPolynomial<std::integer_sequence<Tout, (Tout)cs...> >());
}
};
template <class... C, class Complex>
struct Simplification<Composition<ImagN<Complex>, C...>, /*com_i_cs*/ 0> {
static auto Combine(Composition<ImagN<Complex>, C...>) { return I; }
};
template <class F, class ... Fs>
struct Simplification<
Composition<
F, Addition<Fs...> >, /*re_add_fs*/0,
typename std::enable_if<
std::is_same<F, Real>::value ||
std::is_same<F, Imag>::value
>::type>
{
template <std::size_t ... is>
static auto Combine(Composition<
F, Addition<Fs...> > c,
std::integer_sequence<
std::size_t, is...>)
{
auto t = get<1>(c.GetFunctions()).GetFunctions();
return AddRaw((F()(get<is>(t)))...);
}
static auto Combine(Composition<
F, Addition<Fs...> > c)
{
return Combine(c, std::index_sequence_for<Fs...>());
}
};
template <class F1, class F2>
struct Simplification<
Composition<
Real, Multiplication<F1, F2> >, /*re_add_fs*/0>
{
static auto Combine(Composition<
Real, Multiplication<F1,F2> > c)
{
auto t = get<1>(c.GetFunctions()).GetFunctions();
auto left = get<0>(t);
auto right = get<1>(t);
return SubRaw(MultiplyRaw(Real()(left), Real()(right)),
MultiplyRaw(Imag()(left), Imag()(right)));
}
};
template <class F1, class F2>
struct Simplification<
Composition<
Imag, Multiplication<F1, F2> >, /*im_add_fs*/0>
{
static auto Combine(Composition<
Imag, Multiplication<F1, F2> > c)
{
auto t = get<1>(c.GetFunctions()).GetFunctions();
auto left = get<0>(t);
auto right = get<1>(t);
return AddRaw(MultiplyRaw(Real()(left), Imag()(right)),
MultiplyRaw(Imag()(left), Real()(right)));
}
};
}
#endif
<|endoftext|>
|
<commit_before>/*
@ 0xCCCCCCCC
*/
#include "tcp_connection.h"
#include <WS2tcpip.h>
#include "kbase/basic_types.h"
#include "kbase/error_exception_util.h"
#include "kbase/logging.h"
#include "winsock_ctx.h"
TcpConnection::TcpConnection()
: state_(State::WaitConnect)
{
Internal = 0;
InternalHigh = 0;
Offset = 0;
OffsetHigh = 0;
hEvent = nullptr;
}
void TcpConnection::Conncect(ScopedSocketHandle&& conn_socket)
{
ENSURE(CHECK, !conn_socket_).Require("Connection socket must be empty!");
conn_socket_ = std::move(conn_socket);
sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(client_addr));
int len = sizeof(client_addr);
getpeername(conn_socket_.get(), reinterpret_cast<sockaddr*>(&client_addr), &len);
inet_ntop(client_addr.sin_family, &client_addr.sin_addr, client_ip_, kClientIPSize);
printf("Connects to %s on worker %u\n", client_ip_, GetCurrentThreadId());
ReadRequest();
}
void TcpConnection::ReadRequest()
{
state_ = State::WaitRequest;
buf_info_.buf = io_buf_;
buf_info_.len = kIOBufSize;
DWORD flags = 0;
auto rv = WSARecv(conn_socket_.get(), &buf_info_, 1, nullptr, &flags, this, nullptr);
if (rv == SOCKET_ERROR && (WSAGetLastError() != ERROR_IO_PENDING)) {
LOG(WARNING) << "WSARecv() failed: " << WSAGetLastError();
// TODO: reset.
}
}
void TcpConnection::WriteResponse()
{
state_ = State::WaitResponse;
}
void TcpConnection::Disconnect()
{
state_ = State::WaitReset;
//winsock_ctx::DisconnectEx(conn_socket_.get(), this, 0, 0);
conn_socket_.reset();
}
void TcpConnection::OnIOComplete(int64_t bytes_transferred)
{
switch (state_) {
case State::WaitRequest:
OnReadRequestComplete(bytes_transferred);
break;
case State::WaitReset:
OnDisconnectComplete();
default:
ENSURE(CHECK, kbase::NotReached())(kbase::enum_cast(state_)).Require();
break;
}
}
void TcpConnection::OnReadRequestComplete(int64_t bytes_transferred)
{
if (bytes_transferred == 0) {
Disconnect();
return;
}
// TODO: implement request parse.
std::string msg(io_buf_, bytes_transferred);
printf("-> %s\n", msg.c_str());
ReadRequest();
}
void TcpConnection::OnDisconnectComplete()
{
printf("Client %s disconnected! on worker %u\n", client_ip_, GetCurrentThreadId());
conn_socket_.reset();
state_ = State::WaitConnect;
}
<commit_msg>Fix disconnection transition<commit_after>/*
@ 0xCCCCCCCC
*/
#include "tcp_connection.h"
#include <WS2tcpip.h>
#include "kbase/basic_types.h"
#include "kbase/error_exception_util.h"
#include "kbase/logging.h"
#include "winsock_ctx.h"
TcpConnection::TcpConnection()
: state_(State::WaitConnect)
{
Internal = 0;
InternalHigh = 0;
Offset = 0;
OffsetHigh = 0;
hEvent = nullptr;
}
void TcpConnection::Conncect(ScopedSocketHandle&& conn_socket)
{
ENSURE(CHECK, !conn_socket_).Require("Connection socket must be empty!");
conn_socket_ = std::move(conn_socket);
sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(client_addr));
int len = sizeof(client_addr);
getpeername(conn_socket_.get(), reinterpret_cast<sockaddr*>(&client_addr), &len);
inet_ntop(client_addr.sin_family, &client_addr.sin_addr, client_ip_, kClientIPSize);
printf("Connects to %s on worker %u\n", client_ip_, GetCurrentThreadId());
ReadRequest();
}
void TcpConnection::ReadRequest()
{
state_ = State::WaitRequest;
buf_info_.buf = io_buf_;
buf_info_.len = kIOBufSize;
DWORD flags = 0;
auto rv = WSARecv(conn_socket_.get(), &buf_info_, 1, nullptr, &flags, this, nullptr);
if (rv == SOCKET_ERROR && (WSAGetLastError() != ERROR_IO_PENDING)) {
LOG(WARNING) << "WSARecv() failed: " << WSAGetLastError();
// TODO: reset.
}
}
void TcpConnection::WriteResponse()
{
state_ = State::WaitResponse;
}
void TcpConnection::Disconnect()
{
state_ = State::WaitReset;
winsock_ctx::DisconnectEx(conn_socket_.get(), this, 0, 0);
}
void TcpConnection::OnIOComplete(int64_t bytes_transferred)
{
switch (state_) {
case State::WaitRequest:
OnReadRequestComplete(bytes_transferred);
break;
case State::WaitReset:
OnDisconnectComplete();
break;
default:
ENSURE(CHECK, kbase::NotReached())(kbase::enum_cast(state_)).Require();
break;
}
}
void TcpConnection::OnReadRequestComplete(int64_t bytes_transferred)
{
if (bytes_transferred == 0) {
Disconnect();
return;
}
// TODO: implement request parse.
std::string msg(io_buf_, bytes_transferred);
printf("-> %s\n", msg.c_str());
ReadRequest();
}
void TcpConnection::OnDisconnectComplete()
{
printf("Client %s disconnected on worker %u!\n", client_ip_, GetCurrentThreadId());
conn_socket_.reset();
state_ = State::WaitConnect;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.