text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Add bubblesort implementation<commit_after><|endoftext|> |
<commit_before><commit_msg>am 760f0994: am c0f18b9d: am c4c77d63: Merge "Add property for background GC type"<commit_after><|endoftext|> |
<commit_before>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* trans/auto_impls.cpp
* - Automatic trait/method impls
*
* Handles implementing Clone (when in 1.29 mode)
*/
#include "main_bindings.hpp"
#include "trans_list.hpp"
#include <hir/hir.hpp>
#include <mir/mir.hpp>
#include <hir_typeck/common.hpp> // monomorph
#include <hir_typeck/static.hpp> // StaticTraitResolve
#include <deque>
#include <algorithm> // find_if
namespace {
struct State
{
::HIR::Crate& crate;
StaticTraitResolve resolve;
const TransList& trans_list;
::std::deque<::HIR::TypeRef> todo_list;
::std::set<::HIR::TypeRef> done_list;
::HIR::SimplePath lang_Clone;
State(::HIR::Crate& crate, const TransList& trans_list):
crate(crate),
resolve( crate ),
trans_list(trans_list)
{
lang_Clone = crate.get_lang_item_path(Span(), "clone");
}
void enqueue_type(const ::HIR::TypeRef& ty) {
if( this->trans_list.auto_clone_impls.count(ty) == 0 && this->done_list.count(ty) == 0 ) {
this->done_list.insert( ty.clone() );
this->todo_list.push_back( ty.clone() );
}
}
};
}
void Trans_AutoImpl_Clone(State& state, ::HIR::TypeRef ty)
{
Span sp;
TRACE_FUNCTION_F(ty);
// Create MIR
::MIR::Function mir_fcn;
if( state.resolve.type_is_copy(sp, ty) )
{
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
::MIR::LValue::make_Return({}),
::MIR::RValue::make_Use( ::MIR::LValue::make_Deref({ box$(::MIR::LValue::make_Argument({ 0 })) }) )
}));
bb.terminator = ::MIR::Terminator::make_Return({});
mir_fcn.blocks.push_back(::std::move( bb ));
}
else
{
const auto& lang_Clone = state.resolve.m_crate.get_lang_item_path(sp, "clone");
TU_MATCH_HDRA( (ty.m_data), {)
default:
TODO(sp, "auto Clone for " << ty << " - Not Copy");
TU_ARMA(Tuple, te) {
assert(te.size() > 0);
::std::vector< ::MIR::Param> values;
// For each field of the tuple, create a clone (either using Copy if posible, or calling Clone::clone)
for(const auto& subty : te)
{
auto fld_lvalue = ::MIR::LValue::make_Field({ box$(::MIR::LValue::make_Deref({ box$(::MIR::LValue::make_Argument({ 0 })) })), static_cast<unsigned>(values.size()) });
if( state.resolve.type_is_copy(sp, subty) )
{
values.push_back( ::std::move(fld_lvalue) );
}
else
{
// Allocate to locals (one for the `&T`, the other for the cloned `T`)
auto borrow_lv = ::MIR::LValue::make_Local( mir_fcn.locals.size() );
mir_fcn.locals.push_back(::HIR::TypeRef::new_borrow(::HIR::BorrowType::Shared, subty.clone()));
auto res_lv = ::MIR::LValue::make_Local( mir_fcn.locals.size() );
mir_fcn.locals.push_back(subty.clone());
// Call `<T as Clone>::clone`, passing a borrow of the field
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
borrow_lv.clone(),
::MIR::RValue::make_Borrow({ 0, ::HIR::BorrowType::Shared, mv$(fld_lvalue) })
}));
bb.terminator = ::MIR::Terminator::make_Call({
static_cast<unsigned>(mir_fcn.blocks.size() + 2), // return block (after the panic block below)
static_cast<unsigned>(mir_fcn.blocks.size() + 1), // panic block (next block)
res_lv.clone(),
::MIR::CallTarget( ::HIR::Path(subty.clone(), lang_Clone, "clone") ),
::make_vec1<::MIR::Param>( ::std::move(borrow_lv) )
});
mir_fcn.blocks.push_back(::std::move( bb ));
// Stub panic handling (TODO: Make this iterate `values` and drop all of them)
::MIR::BasicBlock panic_bb;
bb.terminator = ::MIR::Terminator::make_Diverge({});
mir_fcn.blocks.push_back(::std::move( panic_bb ));
// Save the output of the `clone` call
values.push_back( ::std::move(res_lv) );
}
}
// Construct the result tuple
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
::MIR::LValue::make_Return({}),
::MIR::RValue::make_Tuple({ mv$(values) })
}));
bb.terminator = ::MIR::Terminator::make_Return({});
mir_fcn.blocks.push_back(::std::move( bb ));
}
}
}
// Function
::HIR::Function fcn {
/*m_save_code=*/false,
::HIR::Linkage {},
::HIR::Function::Receiver::BorrowShared,
/*m_abi=*/ABI_RUST,
/*m_unsafe =*/false,
/*m_const=*/false,
::HIR::GenericParams {},
/*m_args=*/::make_vec1(::std::make_pair(
::HIR::Pattern( ::HIR::PatternBinding(false, ::HIR::PatternBinding::Type::Move, "self", 0), ::HIR::Pattern::Data::make_Any({}) ),
::HIR::TypeRef::new_borrow(::HIR::BorrowType::Shared, ty.clone())
)),
/*m_variadic=*/false,
/*m_return=*/ty.clone(),
::HIR::ExprPtr {}
};
fcn.m_code.m_mir = ::MIR::FunctionPointer( new ::MIR::Function(mv$(mir_fcn)) );
// Impl
::HIR::TraitImpl impl;
impl.m_type = mv$(ty);
impl.m_methods.insert(::std::make_pair( ::std::string("clone"), ::HIR::TraitImpl::ImplEnt< ::HIR::Function> { false, ::std::move(fcn) } ));
// Add impl to the crate
state.crate.m_trait_impls.insert(::std::make_pair( state.lang_Clone, ::std::move(impl) ));
}
void Trans_AutoImpls(::HIR::Crate& crate, TransList& trans_list)
{
if( TARGETVER_1_19 )
return ;
State state { crate, trans_list };
// Generate for all
for(const auto& ty : trans_list.auto_clone_impls)
{
state.done_list.insert( ty.clone() );
Trans_AutoImpl_Clone(state, ty.clone());
}
while( !state.todo_list.empty() )
{
auto ty = ::std::move(state.todo_list.front());
state.todo_list.pop_back();
Trans_AutoImpl_Clone(state, mv$(ty));
}
const auto impl_range = crate.m_trait_impls.equal_range( state.lang_Clone );
for(const auto& ty : state.done_list)
{
// TODO: Find a way of turning a set into a vector so items can be erased.
auto p = ::HIR::Path(ty.clone(), ::HIR::GenericPath(state.lang_Clone), "clone");
//DEBUG("add_function(" << p << ")");
auto e = trans_list.add_function(::std::move(p));
auto it = ::std::find_if( impl_range.first, impl_range.second, [&](const auto& i){ return i.second.m_type == ty; });
assert( it->second.m_methods.size() == 1 );
e->ptr = &it->second.m_methods.begin()->second.data;
}
}
<commit_msg>Trans Auto Impls - Clone for closures<commit_after>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* trans/auto_impls.cpp
* - Automatic trait/method impls
*
* Handles implementing Clone (when in 1.29 mode)
*/
#include "main_bindings.hpp"
#include "trans_list.hpp"
#include <hir/hir.hpp>
#include <mir/mir.hpp>
#include <hir_typeck/common.hpp> // monomorph
#include <hir_typeck/static.hpp> // StaticTraitResolve
#include <deque>
#include <algorithm> // find_if
namespace {
struct State
{
::HIR::Crate& crate;
StaticTraitResolve resolve;
const TransList& trans_list;
::std::deque<::HIR::TypeRef> todo_list;
::std::set<::HIR::TypeRef> done_list;
::HIR::SimplePath lang_Clone;
State(::HIR::Crate& crate, const TransList& trans_list):
crate(crate),
resolve( crate ),
trans_list(trans_list)
{
lang_Clone = crate.get_lang_item_path(Span(), "clone");
}
void enqueue_type(const ::HIR::TypeRef& ty) {
if( this->trans_list.auto_clone_impls.count(ty) == 0 && this->done_list.count(ty) == 0 ) {
this->done_list.insert( ty.clone() );
this->todo_list.push_back( ty.clone() );
}
}
};
}
namespace {
::MIR::Param clone_field(const State& state, const Span& sp, ::MIR::Function& mir_fcn, const ::HIR::TypeRef& subty, ::MIR::LValue fld_lvalue)
{
if( state.resolve.type_is_copy(sp, subty) )
{
return ::std::move(fld_lvalue);
}
else
{
const auto& lang_Clone = state.resolve.m_crate.get_lang_item_path(sp, "clone");
// Allocate to locals (one for the `&T`, the other for the cloned `T`)
auto borrow_lv = ::MIR::LValue::make_Local( mir_fcn.locals.size() );
mir_fcn.locals.push_back(::HIR::TypeRef::new_borrow(::HIR::BorrowType::Shared, subty.clone()));
auto res_lv = ::MIR::LValue::make_Local( mir_fcn.locals.size() );
mir_fcn.locals.push_back(subty.clone());
// Call `<T as Clone>::clone`, passing a borrow of the field
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
borrow_lv.clone(),
::MIR::RValue::make_Borrow({ 0, ::HIR::BorrowType::Shared, mv$(fld_lvalue) })
}));
bb.terminator = ::MIR::Terminator::make_Call({
static_cast<unsigned>(mir_fcn.blocks.size() + 2), // return block (after the panic block below)
static_cast<unsigned>(mir_fcn.blocks.size() + 1), // panic block (next block)
res_lv.clone(),
::MIR::CallTarget( ::HIR::Path(subty.clone(), lang_Clone, "clone") ),
::make_vec1<::MIR::Param>( ::std::move(borrow_lv) )
});
mir_fcn.blocks.push_back(::std::move( bb ));
// Stub panic handling (TODO: Make this iterate `values` and drop all of them)
::MIR::BasicBlock panic_bb;
bb.terminator = ::MIR::Terminator::make_Diverge({});
mir_fcn.blocks.push_back(::std::move( panic_bb ));
// Save the output of the `clone` call
return ::std::move(res_lv);
}
}
}
void Trans_AutoImpl_Clone(State& state, ::HIR::TypeRef ty)
{
Span sp;
TRACE_FUNCTION_F(ty);
// Create MIR
::MIR::Function mir_fcn;
if( state.resolve.type_is_copy(sp, ty) )
{
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
::MIR::LValue::make_Return({}),
::MIR::RValue::make_Use( ::MIR::LValue::make_Deref({ box$(::MIR::LValue::make_Argument({ 0 })) }) )
}));
bb.terminator = ::MIR::Terminator::make_Return({});
mir_fcn.blocks.push_back(::std::move( bb ));
}
else
{
TU_MATCH_HDRA( (ty.m_data), {)
default:
TODO(sp, "auto Clone for " << ty << " - Unknown and not Copy");
TU_ARMA(Path, te) {
// closures are identified by the name starting with 'closure#'
if( TU_TEST1(te.path.m_data, Generic, .m_path.m_components.back().compare(0, 8, "closure#") == 0) ) {
const auto& gp = te.path.m_data.as_Generic();
const auto& str = state.resolve.m_crate.get_struct_by_path(sp, gp.m_path);
Trans_Params p;
p.sp = sp;
p.pp_impl = gp.m_params.clone();
::std::vector< ::MIR::Param> values; values.reserve( str.m_data.as_Tuple().size() );
for(const auto& fld : str.m_data.as_Tuple())
{
::HIR::TypeRef tmp;
const auto& ty_m = monomorphise_type_needed(fld.ent) ? (tmp = p.monomorph(state.resolve, fld.ent)) : fld.ent;
auto fld_lvalue = ::MIR::LValue::make_Field({ box$(::MIR::LValue::make_Deref({ box$(::MIR::LValue::make_Argument({ 0 })) })), static_cast<unsigned>(values.size()) });
values.push_back( clone_field(state, sp, mir_fcn, ty_m, mv$(fld_lvalue)) );
}
// Construct the result value
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
::MIR::LValue::make_Return({}),
::MIR::RValue::make_Struct({ gp.clone(), mv$(values) })
}));
bb.terminator = ::MIR::Terminator::make_Return({});
mir_fcn.blocks.push_back(::std::move( bb ));
}
else {
TODO(sp, "auto Clone for " << ty << " - Unknown and not Copy");
}
}
TU_ARMA(Array, te) {
ASSERT_BUG(sp, te.size_val < 256, "TODO: Is more than 256 elements sane for auto-generated non-Copy Clone impl? " << ty);
::std::vector< ::MIR::Param> values; values.reserve(te.size_val);
for(size_t i = 0; i < te.size_val; i ++)
{
auto fld_lvalue = ::MIR::LValue::make_Field({ box$(::MIR::LValue::make_Deref({ box$(::MIR::LValue::make_Argument({ 0 })) })), static_cast<unsigned>(i) });
values.push_back( clone_field(state, sp, mir_fcn, *te.inner, mv$(fld_lvalue)) );
}
// Construct the result
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
::MIR::LValue::make_Return({}),
::MIR::RValue::make_Array({ mv$(values) })
}));
bb.terminator = ::MIR::Terminator::make_Return({});
mir_fcn.blocks.push_back(::std::move( bb ));
}
TU_ARMA(Tuple, te) {
assert(te.size() > 0);
::std::vector< ::MIR::Param> values; values.reserve(te.size());
// For each field of the tuple, create a clone (either using Copy if posible, or calling Clone::clone)
for(const auto& subty : te)
{
auto fld_lvalue = ::MIR::LValue::make_Field({ box$(::MIR::LValue::make_Deref({ box$(::MIR::LValue::make_Argument({ 0 })) })), static_cast<unsigned>(values.size()) });
values.push_back( clone_field(state, sp, mir_fcn, subty, mv$(fld_lvalue)) );
}
// Construct the result tuple
::MIR::BasicBlock bb;
bb.statements.push_back(::MIR::Statement::make_Assign({
::MIR::LValue::make_Return({}),
::MIR::RValue::make_Tuple({ mv$(values) })
}));
bb.terminator = ::MIR::Terminator::make_Return({});
mir_fcn.blocks.push_back(::std::move( bb ));
}
}
}
// Function
::HIR::Function fcn {
/*m_save_code=*/false,
::HIR::Linkage {},
::HIR::Function::Receiver::BorrowShared,
/*m_abi=*/ABI_RUST,
/*m_unsafe =*/false,
/*m_const=*/false,
::HIR::GenericParams {},
/*m_args=*/::make_vec1(::std::make_pair(
::HIR::Pattern( ::HIR::PatternBinding(false, ::HIR::PatternBinding::Type::Move, "self", 0), ::HIR::Pattern::Data::make_Any({}) ),
::HIR::TypeRef::new_borrow(::HIR::BorrowType::Shared, ty.clone())
)),
/*m_variadic=*/false,
/*m_return=*/ty.clone(),
::HIR::ExprPtr {}
};
fcn.m_code.m_mir = ::MIR::FunctionPointer( new ::MIR::Function(mv$(mir_fcn)) );
// Impl
::HIR::TraitImpl impl;
impl.m_type = mv$(ty);
impl.m_methods.insert(::std::make_pair( ::std::string("clone"), ::HIR::TraitImpl::ImplEnt< ::HIR::Function> { false, ::std::move(fcn) } ));
// Add impl to the crate
state.crate.m_trait_impls.insert(::std::make_pair( state.lang_Clone, ::std::move(impl) ));
}
void Trans_AutoImpls(::HIR::Crate& crate, TransList& trans_list)
{
if( TARGETVER_1_19 )
return ;
State state { crate, trans_list };
// Generate for all
for(const auto& ty : trans_list.auto_clone_impls)
{
state.done_list.insert( ty.clone() );
Trans_AutoImpl_Clone(state, ty.clone());
}
while( !state.todo_list.empty() )
{
auto ty = ::std::move(state.todo_list.front());
state.todo_list.pop_back();
Trans_AutoImpl_Clone(state, mv$(ty));
}
const auto impl_range = crate.m_trait_impls.equal_range( state.lang_Clone );
for(const auto& ty : state.done_list)
{
// TODO: Find a way of turning a set into a vector so items can be erased.
auto p = ::HIR::Path(ty.clone(), ::HIR::GenericPath(state.lang_Clone), "clone");
//DEBUG("add_function(" << p << ")");
auto e = trans_list.add_function(::std::move(p));
auto it = ::std::find_if( impl_range.first, impl_range.second, [&](const auto& i){ return i.second.m_type == ty; });
assert( it->second.m_methods.size() == 1 );
e->ptr = &it->second.m_methods.begin()->second.data;
}
}
<|endoftext|> |
<commit_before><commit_msg>[SQUASH] Make windows happy?<commit_after><|endoftext|> |
<commit_before>#ifndef HMLIB_MEMORY_INC
#define HMLIB_MEMORY_INC 100
#
namespace hmLib{
template<typename T,typename D = default_deleter<const T>>
class clone_ptr{
private:
typedef T* pointer;
typedef D deleter;
typedef clone_ptr<T, D> my_type;
typedef rvalue_reference<my_type> rvalue_reference;
private:
pointer ptr;
deleter dlt;
public:
clone_ptr()
:ptr(0)
,dlt(){
}
explicit clone_ptr(pointer ptr_)
:ptr(ptr_)
,dlt(){
}
clone_ptr(pointer ptr_,deleter dlt_)
:ptr(ptr_)
,dlt(dlt_){
}
explicit clone_ptr(rvalue_reference mptr_)
:ptr(mptr_.ref.get())
,dlt(mptr_.ref.get_deleter()) {
mptr_.ref.release();
}
const my_type& operator=(rvalue_reference mptr_) {
if(this!=&(mptr_.ref)) {
if(ptr)dlt(ptr);
ptr=mptr_.ref.get();
dlt=mptr_.ref.get_deleter();
mptr_.ref.release();
}
return *this;
}
template<typename U>
explicit clone_ptr(hmLib::rvalue_reference<clone_ptr<U, D> > mptr_)
: ptr(mptr_.ref.get())
, dlt(mptr_.ref.get_deleter()) {
mptr_.ref.release();
}
template<typename U>
const my_type& operator=(hmLib::rvalue_reference<clone_ptr<U, D> > mptr_) {
if(ptr!=mptr_.ref.get()) {
if(ptr)dlt(ptr);
ptr=mptr_.ref.get();
dlt=mptr_.ref.get_deleter();
mptr_.ref.release();
}
return *this;
}
~clone_ptr() {
if(ptr)dlt(ptr);
}
void swap(my_type& My_) {
if(this==&My_)return;
pointer tmp_ptr=ptr;
deleter tmp_dlt=dlt;
ptr=My_.ptr;
dlt=My_.dlt;
My_.ptr=tmp_ptr;
My_.dlt=tmp_dlt;
}
private:
//copy disable
clone_ptr(const my_type&);
const my_type& operator=(const my_type& My_);
public:
pointer get()const { return ptr; }
deleter get_deleter()const { return dlt; }
pointer release() {
pointer ans=ptr;
ptr=0;
return ptr;
}
void reset(pointer ptr_=0) {
if(ptr)dlt(ptr);
ptr=ptr_;
dlt=deleter();
}
void reset(pointer ptr_, deleter dlt_) {
if(ptr)dlt(ptr);
ptr=ptr_;
dlt=dlt_;
}
operator bool() { return ptr!=0; }
T& operator*() { return *ptr; }
T* operator->() { return ptr; }
const T& operator*() const { return *ptr; }
const T* operator->() const { return ptr; }
};
template<typename T, typename D>
class clone_ptr<T[],D>{
public:
typedef clone_ptr<_Ty[], _Dx> _Myt;
typedef _clone_ptr_base<_Ty, _Dx> _Mybase;
typedef typename _Mybase::pointer pointer;
typedef _Ty element_type;
typedef _Dx deleter_type;
using _Mybase::get_deleter;
_CONST_FUN clone_ptr() _NOEXCEPT
: _Mybase(pointer())
{ // default construct
static_assert(!is_pointer<_Dx>::value,
"clone_ptr constructed with null deleter pointer");
}
template<class _Uty>
using _Enable_ctor_reset = enable_if_t<
is_same<_Uty, pointer>::value
|| (is_same<pointer, element_type *>::value
&& is_pointer<_Uty>::value
&& is_convertible<
remove_pointer_t<_Uty>(*)[],
element_type(*)[]
>::value)>;
template<class _Uty,
class = _Enable_ctor_reset<_Uty> >
explicit clone_ptr(_Uty _Ptr) _NOEXCEPT
: _Mybase(_Ptr)
{ // construct with pointer
static_assert(!is_pointer<_Dx>::value,
"clone_ptr constructed with null deleter pointer");
}
template<class _Uty,
class = _Enable_ctor_reset<_Uty> >
clone_ptr(_Uty _Ptr,
typename _If<is_reference<_Dx>::value, _Dx,
const typename remove_reference<_Dx>::type&>::type _Dt) _NOEXCEPT
: _Mybase(_Ptr, _Dt)
{ // construct with pointer and (maybe const) deleter&
}
template<class _Uty,
class = _Enable_ctor_reset<_Uty> >
clone_ptr(_Uty _Ptr,
typename remove_reference<_Dx>::type&& _Dt) _NOEXCEPT
: _Mybase(_Ptr, _STD move(_Dt))
{ // construct by moving deleter
static_assert(!is_reference<_Dx>::value,
"clone_ptr constructed with reference to rvalue deleter");
}
clone_ptr(clone_ptr&& _Right) _NOEXCEPT
: _Mybase(_Right.release(),
_STD forward<_Dx>(_Right.get_deleter()))
{ // construct by moving _Right
}
_Myt& operator=(_Myt&& _Right) _NOEXCEPT
{ // assign by moving _Right
if (this != &_Right)
{ // different, do the swap
reset(_Right.release());
this->get_deleter() = _STD move(_Right.get_deleter());
}
return (*this);
}
template<class _Uty,
class _Ex,
bool _More,
class _UP_pointer = typename clone_ptr<_Uty, _Ex>::pointer,
class _UP_element_type = typename clone_ptr<_Uty, _Ex>::element_type>
using _Enable_conversion = enable_if_t<
is_array<_Uty>::value
&& is_same<pointer, element_type *>::value
&& is_same<_UP_pointer, _UP_element_type *>::value
&& is_convertible<_UP_element_type(*)[], element_type(*)[]>::value
&& _More>;
template<class _Uty,
class _Ex,
class = _Enable_conversion<_Uty, _Ex,
is_reference<_Dx>::value
? is_same<_Ex, _Dx>::value
: is_convertible<_Ex, _Dx>::value> >
clone_ptr(clone_ptr<_Uty, _Ex>&& _Right) _NOEXCEPT
: _Mybase(_Right.release(),
_STD forward<_Ex>(_Right.get_deleter()))
{ // construct by moving _Right
}
template<class _Uty,
class _Ex,
class = _Enable_conversion<_Uty, _Ex,
is_assignable<_Dx&, _Ex&&>::value> >
_Myt& operator=(clone_ptr<_Uty, _Ex>&& _Right) _NOEXCEPT
{ // assign by moving _Right
reset(_Right.release());
this->get_deleter() = _STD forward<_Ex>(_Right.get_deleter());
return (*this);
}
_CONST_FUN clone_ptr(nullptr_t) _NOEXCEPT
: _Mybase(pointer())
{ // null pointer construct
static_assert(!is_pointer<_Dx>::value,
"clone_ptr constructed with null deleter pointer");
}
_Myt& operator=(nullptr_t) _NOEXCEPT
{ // assign a null pointer
reset();
return (*this);
}
void reset(nullptr_t = nullptr_t()) _NOEXCEPT
{ // establish new null pointer
reset(pointer());
}
void swap(_Myt& _Right) _NOEXCEPT
{ // swap elements
_Swap_adl(this->_Myptr(), _Right._Myptr());
_Swap_adl(this->get_deleter(), _Right.get_deleter());
}
~clone_ptr() _NOEXCEPT
{ // destroy the object
_Delete();
}
_Ty& operator[](size_t _Idx) const
{ // return reference to object
return (get()[_Idx]);
}
pointer get() const _NOEXCEPT
{ // return pointer to object
return (this->_Myptr());
}
explicit operator bool() const _NOEXCEPT
{ // test for non-null pointer
return (get() != pointer());
}
pointer release() _NOEXCEPT
{ // yield ownership of pointer
pointer _Ans = get();
this->_Myptr() = pointer();
return (_Ans);
}
template<class _Uty,
class = _Enable_ctor_reset<_Uty> >
void reset(_Uty _Ptr) _NOEXCEPT
{ // establish new pointer
pointer _Old = get();
this->_Myptr() = _Ptr;
if (_Old != pointer())
this->get_deleter()(_Old);
}
clone_ptr(const _Myt&) = delete;
_Myt& operator=(const _Myt&) = delete;
private:
void _Delete(){ // delete the pointer
if (get() != pointer())
this->get_deleter()(get());
}
};
}
#ifdef HMLIB_MEMORY_STD
namespace std{
}
#endif
#
#endif
<commit_msg>Remove memory.hpp<commit_after><|endoftext|> |
<commit_before><commit_msg>important fix in conversion function<commit_after><|endoftext|> |
<commit_before>#include <iostream>
int main() {
int sum, n1, n2;
std::cout << "Enter n1: ";
std::cin >> n1;
std::cout << "Enter n2: ";
std::cin >> n2;
sum = n1+n2;
std::cout << std::endl;
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
<commit_msg>redundant<commit_after><|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "MockupNetworkManager.hpp"
#include "MockupNetworkEventListener.hpp"
using namespace rd;
//-- Class for the setup of each test
//--------------------------------------------------------------------------------------
class MockupNetworkManagerTest : public testing::Test
{
public:
virtual void SetUp()
{
MockupNetworkManager::RegisterManager();
networkManager = (MockupNetworkManager *) RdNetworkManager::getNetworkManager(MockupNetworkManager::id);
me = RdPlayer(0, "me", 100, 100, 0, 0);
other_player = RdPlayer(1, "dummy", 100, 100, 1, 0);
}
virtual void TearDown()
{
RdNetworkManager::destroyNetworkManager();
}
protected:
MockupNetworkManager * networkManager;
RdPlayer me, other_player;
};
//-- Things that are being tested
//-----------------------------------------------------------------------------------------------------
TEST_F(MockupNetworkManagerTest, PlayerCreatedWhenLogin)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, ErrorLoginTwice)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_FALSE(networkManager->login(other_player));
ASSERT_TRUE(networkManager->isLoggedIn());
players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, PlayerRemovedOnLogout)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->logout(me));
EXPECT_FALSE(networkManager->isLoggedIn());
players = networkManager->getPlayerData();
ASSERT_EQ(0, players.size());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, ErrorLogoutTwice)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->logout(me));
EXPECT_FALSE(networkManager->isLoggedIn());
players = networkManager->getPlayerData();
ASSERT_EQ(0, players.size());
EXPECT_FALSE(networkManager->logout(me));
EXPECT_FALSE(networkManager->isLoggedIn());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, SetPlayerAddsPlayer)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
std::vector<RdPlayer> players;
players.push_back(me);
players.push_back(other_player);
EXPECT_TRUE(networkManager->setPlayerData(players));
players = networkManager->getPlayerData();
ASSERT_EQ(2, players.size());
EXPECT_EQ(0, players[0].getId());
EXPECT_EQ(1, players[1].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, PlayerDamagedWhenShot)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
std::vector<RdPlayer> players;
players.push_back(me);
players.push_back(other_player);
EXPECT_TRUE(networkManager->setPlayerData(players));
ASSERT_TRUE(networkManager->setLoggedIn(true));
players = networkManager->getPlayerData();
ASSERT_EQ(2, players.size());
ASSERT_TRUE(networkManager->sendPlayerHit(other_player, 100));
players = networkManager->getPlayerData();
ASSERT_EQ(2, players.size());
EXPECT_EQ(0, players[1].getHealth());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, ListenersNotifiedOnEvent)
{
MockupNetworkEventListener listener;
RdNetworkEventListener * plistener = (RdNetworkEventListener *) &listener;
ASSERT_TRUE(((RdNetworkManager*)networkManager)->addNetworkEventListener(plistener));
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
/* Check that data > 0 and check contents */
std::vector<RdPlayer> players = listener.getStoredPlayers();
EXPECT_EQ(1, listener.getDataArrived());
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
<commit_msg>Add new test case for MockupNetworkManager (integration with mentalMap)<commit_after>#include "gtest/gtest.h"
#include "MockupNetworkManager.hpp"
#include "MockupNetworkEventListener.hpp"
using namespace rd;
//-- Class for the setup of each test
//--------------------------------------------------------------------------------------
class MockupNetworkManagerTest : public testing::Test
{
public:
virtual void SetUp()
{
MockupNetworkManager::RegisterManager();
networkManager = (MockupNetworkManager *) RdNetworkManager::getNetworkManager(MockupNetworkManager::id);
me = RdPlayer(0, "me", 100, 100, 0, 0);
other_player = RdPlayer(1, "dummy", 100, 100, 1, 0);
}
virtual void TearDown()
{
RdNetworkManager::destroyNetworkManager();
}
protected:
MockupNetworkManager * networkManager;
RdPlayer me, other_player;
};
//-- Things that are being tested
//-----------------------------------------------------------------------------------------------------
TEST_F(MockupNetworkManagerTest, PlayerCreatedWhenLogin)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, ErrorLoginTwice)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_FALSE(networkManager->login(other_player));
ASSERT_TRUE(networkManager->isLoggedIn());
players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, PlayerRemovedOnLogout)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->logout(me));
EXPECT_FALSE(networkManager->isLoggedIn());
players = networkManager->getPlayerData();
ASSERT_EQ(0, players.size());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, ErrorLogoutTwice)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
std::vector<RdPlayer> players = networkManager->getPlayerData();
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->logout(me));
EXPECT_FALSE(networkManager->isLoggedIn());
players = networkManager->getPlayerData();
ASSERT_EQ(0, players.size());
EXPECT_FALSE(networkManager->logout(me));
EXPECT_FALSE(networkManager->isLoggedIn());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, SetPlayerAddsPlayer)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
std::vector<RdPlayer> players;
players.push_back(me);
players.push_back(other_player);
EXPECT_TRUE(networkManager->setPlayerData(players));
players = networkManager->getPlayerData();
ASSERT_EQ(2, players.size());
EXPECT_EQ(0, players[0].getId());
EXPECT_EQ(1, players[1].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, PlayerDamagedWhenShot)
{
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
std::vector<RdPlayer> players;
players.push_back(me);
players.push_back(other_player);
EXPECT_TRUE(networkManager->setPlayerData(players));
ASSERT_TRUE(networkManager->setLoggedIn(true));
players = networkManager->getPlayerData();
ASSERT_EQ(2, players.size());
ASSERT_TRUE(networkManager->sendPlayerHit(other_player, 100));
players = networkManager->getPlayerData();
ASSERT_EQ(2, players.size());
EXPECT_EQ(0, players[1].getHealth());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, ListenersNotifiedOnEvent)
{
MockupNetworkEventListener listener;
RdNetworkEventListener * plistener = (RdNetworkEventListener *) &listener;
ASSERT_TRUE(((RdNetworkManager*)networkManager)->addNetworkEventListener(plistener));
ASSERT_TRUE(networkManager->start());
ASSERT_FALSE(networkManager->isStopped());
ASSERT_TRUE(networkManager->login(me));
ASSERT_TRUE(networkManager->isLoggedIn());
/* Check that data > 0 and check contents */
std::vector<RdPlayer> players = listener.getStoredPlayers();
EXPECT_EQ(1, listener.getDataArrived());
ASSERT_EQ(1, players.size());
EXPECT_EQ(0, players[0].getId());
ASSERT_TRUE(networkManager->stop());
ASSERT_TRUE(networkManager->isStopped());
}
TEST_F(MockupNetworkManagerTest, ManagerIsIntegratedWithMentalMap)
{
ASSERT_FALSE(true);
}
<|endoftext|> |
<commit_before>// RUN: %clangxx_tsan -O1 %s -o %t && %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int Global;
void *Thread1(void *x) {
sleep(1);
Global++;
return NULL;
}
void *Thread2(void *x) {
pthread_mutex_t mtx;
pthread_mutex_init(&mtx, 0);
pthread_mutex_lock(&mtx);
Global--;
pthread_mutex_unlock(&mtx);
pthread_mutex_destroy(&mtx);
return NULL;
}
int main() {
pthread_t t[2];
pthread_create(&t[0], NULL, Thread1, NULL);
pthread_create(&t[1], NULL, Thread2, NULL);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
}
// CHECK: WARNING: ThreadSanitizer: data race
// CHECK: Write of size 4 at {{.*}} by thread T1:
// CHECK: Previous write of size 4 at {{.*}} by thread T2
// CHECK: (mutexes: write [[M1:M[0-9]+]]):
// CHECK: Mutex [[M1]] is already destroyed
// CHECK-NOT: Mutex {{.*}} created at
<commit_msg>tsan: fix flaky test<commit_after>// RUN: %clangxx_tsan -O1 %s -o %t && %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int Global;
__thread int huge[1024*1024];
void *Thread1(void *x) {
sleep(1);
Global++;
return NULL;
}
void *Thread2(void *x) {
pthread_mutex_t mtx;
pthread_mutex_init(&mtx, 0);
pthread_mutex_lock(&mtx);
Global--;
pthread_mutex_unlock(&mtx);
pthread_mutex_destroy(&mtx);
return NULL;
}
int main() {
pthread_t t[2];
pthread_create(&t[0], NULL, Thread1, NULL);
pthread_create(&t[1], NULL, Thread2, NULL);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
}
// CHECK: WARNING: ThreadSanitizer: data race
// CHECK: Write of size 4 at {{.*}} by thread T1:
// CHECK: Previous write of size 4 at {{.*}} by thread T2
// CHECK: (mutexes: write [[M1:M[0-9]+]]):
// CHECK: Mutex [[M1]] is already destroyed
// CHECK-NOT: Mutex {{.*}} created at
<|endoftext|> |
<commit_before>/*************************************************
* Library Internal/Global State Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/libstate.h>
#include <botan/config.h>
#include <botan/modules.h>
#include <botan/engine.h>
#include <botan/stl_util.h>
#include <botan/mutex.h>
#include <botan/charset.h>
#include <botan/x931_rng.h>
#include <botan/randpool.h>
#include <botan/selftest.h>
#include <algorithm>
namespace Botan {
/*************************************************
* Botan's global state *
*************************************************/
namespace {
Library_State* global_lib_state = 0;
}
/*************************************************
* Access the global state object *
*************************************************/
Library_State& global_state()
{
if(!global_lib_state)
LibraryInitializer::initialize();
return (*global_lib_state);
}
/*************************************************
* Set a new global state object *
*************************************************/
void set_global_state(Library_State* new_state)
{
delete swap_global_state(new_state);
}
/*************************************************
* Swap two global state objects *
*************************************************/
Library_State* swap_global_state(Library_State* new_state)
{
Library_State* old_state = global_lib_state;
global_lib_state = new_state;
return old_state;
}
/*************************************************
* Increment the Engine iterator *
*************************************************/
Engine* Library_State::Engine_Iterator::next()
{
return lib.get_engine_n(n++);
}
/*************************************************
* Get a new mutex object *
*************************************************/
Mutex* Library_State::get_mutex() const
{
return mutex_factory->make();
}
/*************************************************
* Get an allocator by its name *
*************************************************/
Allocator* Library_State::get_allocator(const std::string& type) const
{
Mutex_Holder lock(allocator_lock);
if(type != "")
return search_map<std::string, Allocator*>(alloc_factory, type, 0);
if(!cached_default_allocator)
{
std::string chosen = config().option("base/default_allocator");
if(chosen == "")
chosen = "malloc";
cached_default_allocator =
search_map<std::string, Allocator*>(alloc_factory, chosen, 0);
}
return cached_default_allocator;
}
/*************************************************
* Create a new name to object mapping *
*************************************************/
void Library_State::add_allocator(Allocator* allocator)
{
Mutex_Holder lock(allocator_lock);
allocator->init();
allocators.push_back(allocator);
alloc_factory[allocator->type()] = allocator;
}
/*************************************************
* Set the default allocator type *
*************************************************/
void Library_State::set_default_allocator(const std::string& type) const
{
Mutex_Holder lock(allocator_lock);
if(type == "")
return;
config().set("conf", "base/default_allocator", type);
cached_default_allocator = 0;
}
/*************************************************
* Get an engine out of the list *
*************************************************/
Engine* Library_State::get_engine_n(u32bit n) const
{
Mutex_Holder lock(engine_lock);
if(n >= engines.size())
return 0;
return engines[n];
}
/*************************************************
* Add a new engine to the list *
*************************************************/
void Library_State::add_engine(Engine* engine)
{
Mutex_Holder lock(engine_lock);
engines.insert(engines.begin(), engine);
}
/*************************************************
* Set the configuration object *
*************************************************/
Config& Library_State::config() const
{
if(!config_obj)
{
config_obj = new Config();
config_obj->load_defaults();
}
return (*config_obj);
}
/*************************************************
* Load a set of modules *
*************************************************/
void Library_State::initialize(const InitializerOptions& args,
Modules& modules)
{
if(mutex_factory)
throw Invalid_State("Library_State has already been initialized");
if(args.thread_safe())
mutex_factory = modules.mutex_factory();
else
mutex_factory = new Default_Mutex_Factory;
allocator_lock = get_mutex();
engine_lock = get_mutex();
cached_default_allocator = 0;
std::vector<Allocator*> mod_allocs = modules.allocators();
for(u32bit j = 0; j != mod_allocs.size(); ++j)
add_allocator(mod_allocs[j]);
set_default_allocator(modules.default_allocator());
std::vector<Engine*> mod_engines = modules.engines();
for(u32bit j = 0; j != mod_engines.size(); ++j)
engines.push_back(mod_engines[j]);
if(args.fips_mode() || args.self_test())
{
if(!passes_self_tests())
throw Self_Test_Failure("Initialization self-tests");
}
}
/*************************************************
* Library_State Constructor *
*************************************************/
Library_State::Library_State()
{
mutex_factory = 0;
allocator_lock = engine_lock = 0;
config_obj = 0;
cached_default_allocator = 0;
}
/*************************************************
* Library_State Destructor *
*************************************************/
Library_State::~Library_State()
{
delete config_obj;
std::for_each(engines.begin(), engines.end(), del_fun<Engine>());
cached_default_allocator = 0;
for(u32bit j = 0; j != allocators.size(); ++j)
{
allocators[j]->destroy();
delete allocators[j];
}
delete mutex_factory;
}
}
<commit_msg>The two remaining locks were not being deleted, leaking memory<commit_after>/*************************************************
* Library Internal/Global State Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/libstate.h>
#include <botan/config.h>
#include <botan/modules.h>
#include <botan/engine.h>
#include <botan/stl_util.h>
#include <botan/mutex.h>
#include <botan/charset.h>
#include <botan/x931_rng.h>
#include <botan/randpool.h>
#include <botan/selftest.h>
#include <algorithm>
namespace Botan {
/*************************************************
* Botan's global state *
*************************************************/
namespace {
Library_State* global_lib_state = 0;
}
/*************************************************
* Access the global state object *
*************************************************/
Library_State& global_state()
{
if(!global_lib_state)
LibraryInitializer::initialize();
return (*global_lib_state);
}
/*************************************************
* Set a new global state object *
*************************************************/
void set_global_state(Library_State* new_state)
{
delete swap_global_state(new_state);
}
/*************************************************
* Swap two global state objects *
*************************************************/
Library_State* swap_global_state(Library_State* new_state)
{
Library_State* old_state = global_lib_state;
global_lib_state = new_state;
return old_state;
}
/*************************************************
* Increment the Engine iterator *
*************************************************/
Engine* Library_State::Engine_Iterator::next()
{
return lib.get_engine_n(n++);
}
/*************************************************
* Get a new mutex object *
*************************************************/
Mutex* Library_State::get_mutex() const
{
return mutex_factory->make();
}
/*************************************************
* Get an allocator by its name *
*************************************************/
Allocator* Library_State::get_allocator(const std::string& type) const
{
Mutex_Holder lock(allocator_lock);
if(type != "")
return search_map<std::string, Allocator*>(alloc_factory, type, 0);
if(!cached_default_allocator)
{
std::string chosen = config().option("base/default_allocator");
if(chosen == "")
chosen = "malloc";
cached_default_allocator =
search_map<std::string, Allocator*>(alloc_factory, chosen, 0);
}
return cached_default_allocator;
}
/*************************************************
* Create a new name to object mapping *
*************************************************/
void Library_State::add_allocator(Allocator* allocator)
{
Mutex_Holder lock(allocator_lock);
allocator->init();
allocators.push_back(allocator);
alloc_factory[allocator->type()] = allocator;
}
/*************************************************
* Set the default allocator type *
*************************************************/
void Library_State::set_default_allocator(const std::string& type) const
{
Mutex_Holder lock(allocator_lock);
if(type == "")
return;
config().set("conf", "base/default_allocator", type);
cached_default_allocator = 0;
}
/*************************************************
* Get an engine out of the list *
*************************************************/
Engine* Library_State::get_engine_n(u32bit n) const
{
Mutex_Holder lock(engine_lock);
if(n >= engines.size())
return 0;
return engines[n];
}
/*************************************************
* Add a new engine to the list *
*************************************************/
void Library_State::add_engine(Engine* engine)
{
Mutex_Holder lock(engine_lock);
engines.insert(engines.begin(), engine);
}
/*************************************************
* Set the configuration object *
*************************************************/
Config& Library_State::config() const
{
if(!config_obj)
{
config_obj = new Config();
config_obj->load_defaults();
}
return (*config_obj);
}
/*************************************************
* Load a set of modules *
*************************************************/
void Library_State::initialize(const InitializerOptions& args,
Modules& modules)
{
if(mutex_factory)
throw Invalid_State("Library_State has already been initialized");
if(args.thread_safe())
mutex_factory = modules.mutex_factory();
else
mutex_factory = new Default_Mutex_Factory;
allocator_lock = get_mutex();
engine_lock = get_mutex();
cached_default_allocator = 0;
std::vector<Allocator*> mod_allocs = modules.allocators();
for(u32bit j = 0; j != mod_allocs.size(); ++j)
add_allocator(mod_allocs[j]);
set_default_allocator(modules.default_allocator());
std::vector<Engine*> mod_engines = modules.engines();
for(u32bit j = 0; j != mod_engines.size(); ++j)
engines.push_back(mod_engines[j]);
if(args.fips_mode() || args.self_test())
{
if(!passes_self_tests())
throw Self_Test_Failure("Initialization self-tests");
}
}
/*************************************************
* Library_State Constructor *
*************************************************/
Library_State::Library_State()
{
mutex_factory = 0;
allocator_lock = engine_lock = 0;
config_obj = 0;
cached_default_allocator = 0;
}
/*************************************************
* Library_State Destructor *
*************************************************/
Library_State::~Library_State()
{
delete config_obj;
std::for_each(engines.begin(), engines.end(), del_fun<Engine>());
cached_default_allocator = 0;
for(u32bit j = 0; j != allocators.size(); ++j)
{
allocators[j]->destroy();
delete allocators[j];
}
delete allocator_lock;
delete engine_lock;
delete mutex_factory;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil -*- */
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
#include <schwa/macros.h>
#include <schwa/config.h>
#include <schwa/pool.h>
#include <schwa/port.h>
#include <schwa/dr.h>
#include <schwa/io/array_reader.h>
#include <schwa/msgpack.h>
namespace cf = schwa::config;
namespace dr = schwa::dr;
namespace io = schwa::io;
namespace mp = schwa::msgpack;
namespace port = schwa::port;
namespace {
class Config : public cf::OpMain {
public:
cf::IStreamOp input;
cf::Op<int> limit;
Config(void) :
cf::OpMain("drui", "Schwa-Lab Docrep UI"),
input(*this, "input", "input filename"),
limit(*this, "limit", "upper bound on the number of documents to process from the input stream", -1)
{ }
virtual ~Config(void) { }
};
class FauxDoc : public dr::Doc {
public:
class Schema;
};
class FauxDoc::Schema : public dr::Doc::Schema<FauxDoc> {
public:
Schema(void) : dr::Doc::Schema<FauxDoc>("FauxDoc", "The document class.") { }
};
class DocProcessor {
private:
static const char *SEP;
static const char *REPR_NIL;
static const char *REPR_UNKNOWN;
const FauxDoc &_doc;
std::ostream &_out;
const unsigned int _doc_num;
unsigned int _indent;
void process_fields(const std::vector<dr::RTFieldDef *> &fields);
void process_store(const dr::RTStoreDef &store);
std::ostream &write_indent(void);
std::ostream &write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_primitive(const mp::Value &value);
void write_slice(const dr::RTFieldDef &field, const mp::Value &value);
public:
DocProcessor(const FauxDoc &doc, std::ostream &out, unsigned int doc_num) :
_doc(doc),
_out(out),
_doc_num(doc_num),
_indent(0)
{ }
void process_doc(void);
inline void operator ()(void) { process_doc(); }
private:
DISALLOW_COPY_AND_ASSIGN(DocProcessor);
friend class DocProcessorTest;
};
const char *DocProcessor::SEP = "\t\033[1;30m # ";
const char *DocProcessor::REPR_NIL = "<nil>";
const char *DocProcessor::REPR_UNKNOWN = "<UNKNOWN VALUE>";
void
DocProcessor::process_doc(void) {
const dr::RTManager &rt = *_doc.rt();
write_indent() << port::BOLD << _doc_num << ":" << port::OFF << " {" << SEP << "Document" << port::OFF << "\n";
++_indent;
const dr::RTSchema *schema = rt.doc;
assert(schema != nullptr);
// TODO document fields? where are they?
//process_fields(schema->fields);
for (const auto *store : schema->stores)
process_store(*store);
--_indent;
write_indent() << "},\n";
}
void
DocProcessor::process_fields(const std::vector<dr::RTFieldDef *> &fields) {
for (const dr::RTFieldDef *field : fields) {
(void)field;
}
}
void
DocProcessor::process_store(const dr::RTStoreDef &store) {
assert(store.is_lazy());
const dr::RTSchema &klass = *store.klass;
// iterate through each field name to find the largest name so we can align
// all of the values when printing out.
unsigned int max_length = 0;
for (const auto& field : klass.fields)
if (field->serial.size() > max_length)
max_length = field->serial.size();
// decode the lazy store values into dynamic msgpack objects
schwa::Pool pool(4096);
io::ArrayReader reader(store.lazy_data, store.lazy_nbytes);
mp::Value *value = mp::read_dynamic(reader, pool);
// <instances> ::= [ <instance> ]
assert(is_array(value->type));
const mp::Array &array = *value->via._array;
// write header
write_indent() << port::BOLD << store.serial << ":" << port::OFF << " {";
_out << SEP << klass.serial;
_out << " (" << array.size() << ")"<< port::OFF << "\n";
++_indent;
for (uint32_t i = 0; i != array.size(); ++i) {
assert(is_map(array[i].type));
const mp::Map &map = *array[i].via._map;
write_indent() << port::BOLD << "0x" << std::hex << i << std::dec << ":" << port::OFF << " {\n";
++_indent;
// <instance> ::= { <field_id> : <obj_val> }
for (uint32_t j = 0; j != map.size(); ++j) {
assert(is_uint(map.get(j).key.type));
const mp::Map::Pair &pair = map.get(j);
const dr::RTFieldDef &field = *klass.fields[pair.key.via._uint64];
write_indent() << port::BOLD << std::setw(max_length) << std::left << field.serial << ": " << port::OFF;
write_field(store, field, pair.value) << "\n";
}
--_indent;
write_indent() << "},\n";
}
--_indent;
write_indent() << "},\n";
}
std::ostream &
DocProcessor::write_indent(void) {
for (unsigned int i = 0; i != _indent; ++i)
_out << " ";
return _out;
}
std::ostream &
DocProcessor::write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
const auto flags = _out.flags();
if (field.is_slice)
write_slice(field, value);
else if (field.points_into != nullptr || field.is_self_pointer)
write_pointer(store, field, value);
else
write_primitive(value);
_out.flags(flags);
return _out;
}
void
DocProcessor::write_slice(const dr::RTFieldDef &field, const mp::Value &value) {
assert(is_array(value.type));
const auto &array = *value.via._array;
assert(array.size() == 2);
assert(is_uint(array[0].type));
assert(is_uint(array[1].type));
const uint64_t a = array[0].via._uint64;
const uint64_t b = array[1].via._uint64;
_out << "[0x" << std::hex << a << ", 0x" << std::hex << (a + b) << "],";
_out << SEP;
if (field.points_into == nullptr)
_out << "byte slice";
else
_out << "slice into " << field.points_into->serial;
_out << " (" << std::dec << a << ", " << std::dec << (a + b) << ")" << port::OFF;
}
void
DocProcessor::write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
if (field.is_collection) {
assert(is_array(value.type));
const mp::Array &array = *value.via._array;
_out << "[";
for (uint32_t i = 0; i != array.size(); ++i) {
const mp::Value &v = array[i];
if (i != 0)
_out << ", ";
if (is_nil(v.type) || is_uint(v.type)) {
if (is_nil(v.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << v.via._uint64;
}
else
_out << port::RED << v.type << port::OFF;
}
_out << "]";
}
else {
if (is_nil(value.type) || is_uint(value.type)) {
if (is_nil(value.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << value.via._uint64;
}
else
_out << port::RED << value.type << port::OFF;
}
_out << SEP;
if (field.is_self_pointer)
_out << "self-pointer" << (field.is_collection ? "s" : "") << " into " << store.serial;
else
_out << "pointer" << (field.is_collection ? "s" : "") << " into " << field.points_into->serial;
_out << port::OFF;
}
void
DocProcessor::write_primitive(const mp::Value &value) {
if (is_bool(value.type)) {
_out << std::boolalpha << value.via._bool << ",";
}
else if (is_double(value.type)) {
_out << value.via._double << ",";
_out << SEP << "double" << port::OFF;
}
else if (is_float(value.type)) {
_out << value.via._float << ",";
_out << SEP << "float" << port::OFF;
}
else if (is_nil(value.type)) {
_out << REPR_NIL;
}
else if (is_sint(value.type)) {
_out << "0x" << std::hex << value.via._int64 << std::dec << ",";
_out << SEP << "int (" << value.via._int64 << ")" << port::OFF;
}
else if (is_uint(value.type)) {
_out << "0x" << std::hex << value.via._uint64 << std::dec << ",";
_out << SEP << "uint (" << value.via._uint64 << ")" << port::OFF;
}
else if (is_array(value.type)) {
_out << port::RED << "TODO array" << port::OFF;
}
else if (is_map(value.type)) {
_out << port::RED << "TODO map" << port::OFF;
}
else if (is_raw(value.type)) {
const mp::Raw &raw = *value.via._raw;
(_out << "\"").write(raw.value(), raw.size()) << "\",";
_out << SEP << "raw (" << std::dec << raw.size() << "B)" << port::OFF;
}
else
_out << port::RED << REPR_UNKNOWN << port::OFF;
}
} // namespace
int
main(int argc, char *argv[]) {
// process args
Config c;
c.main(argc, argv);
// construct a docrep reader over the provided input stream
std::istream &in = c.input.file();
FauxDoc::Schema schema;
dr::Reader reader(in, schema);
// read the documents off the input stream
FauxDoc doc;
for (unsigned int i = 0; reader >> doc; ++i)
DocProcessor(doc, std::cout, i)();
return 0;
}
<commit_msg>Relocated some constexpr locations.<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil -*- */
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
#include <schwa/macros.h>
#include <schwa/config.h>
#include <schwa/pool.h>
#include <schwa/port.h>
#include <schwa/dr.h>
#include <schwa/io/array_reader.h>
#include <schwa/msgpack.h>
namespace cf = schwa::config;
namespace dr = schwa::dr;
namespace io = schwa::io;
namespace mp = schwa::msgpack;
namespace port = schwa::port;
namespace {
class Config : public cf::OpMain {
public:
cf::IStreamOp input;
cf::Op<int> limit;
Config(void) :
cf::OpMain("drui", "Schwa-Lab Docrep UI"),
input(*this, "input", "input filename"),
limit(*this, "limit", "upper bound on the number of documents to process from the input stream", -1)
{ }
virtual ~Config(void) { }
};
class FauxDoc : public dr::Doc {
public:
class Schema;
};
class FauxDoc::Schema : public dr::Doc::Schema<FauxDoc> {
public:
Schema(void) : dr::Doc::Schema<FauxDoc>("FauxDoc", "The document class.") { }
};
class DocProcessor {
private:
static constexpr const char *const SEP = "\t\033[1;30m # ";
static constexpr const char *const REPR_NIL = "<nil>";
static constexpr const char *const REPR_UNKNOWN = "<UNKNOWN VALUE>";
const FauxDoc &_doc;
std::ostream &_out;
const unsigned int _doc_num;
unsigned int _indent;
void process_fields(const std::vector<dr::RTFieldDef *> &fields);
void process_store(const dr::RTStoreDef &store);
std::ostream &write_indent(void);
std::ostream &write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_primitive(const mp::Value &value);
void write_slice(const dr::RTFieldDef &field, const mp::Value &value);
public:
DocProcessor(const FauxDoc &doc, std::ostream &out, unsigned int doc_num) :
_doc(doc),
_out(out),
_doc_num(doc_num),
_indent(0)
{ }
void process_doc(void);
inline void operator ()(void) { process_doc(); }
private:
DISALLOW_COPY_AND_ASSIGN(DocProcessor);
friend class DocProcessorTest;
};
void
DocProcessor::process_doc(void) {
const dr::RTManager &rt = *_doc.rt();
write_indent() << port::BOLD << _doc_num << ":" << port::OFF << " {" << SEP << "Document" << port::OFF << "\n";
++_indent;
const dr::RTSchema *schema = rt.doc;
assert(schema != nullptr);
// TODO document fields? where are they?
//process_fields(schema->fields);
for (const auto *store : schema->stores)
process_store(*store);
--_indent;
write_indent() << "},\n";
}
void
DocProcessor::process_fields(const std::vector<dr::RTFieldDef *> &fields) {
for (const dr::RTFieldDef *field : fields) {
(void)field;
}
}
void
DocProcessor::process_store(const dr::RTStoreDef &store) {
assert(store.is_lazy());
const dr::RTSchema &klass = *store.klass;
// iterate through each field name to find the largest name so we can align
// all of the values when printing out.
unsigned int max_length = 0;
for (const auto& field : klass.fields)
if (field->serial.size() > max_length)
max_length = field->serial.size();
// decode the lazy store values into dynamic msgpack objects
schwa::Pool pool(4096);
io::ArrayReader reader(store.lazy_data, store.lazy_nbytes);
mp::Value *value = mp::read_dynamic(reader, pool);
// <instances> ::= [ <instance> ]
assert(is_array(value->type));
const mp::Array &array = *value->via._array;
// write header
write_indent() << port::BOLD << store.serial << ":" << port::OFF << " {";
_out << SEP << klass.serial;
_out << " (" << array.size() << ")"<< port::OFF << "\n";
++_indent;
for (uint32_t i = 0; i != array.size(); ++i) {
assert(is_map(array[i].type));
const mp::Map &map = *array[i].via._map;
write_indent() << port::BOLD << "0x" << std::hex << i << std::dec << ":" << port::OFF << " {\n";
++_indent;
// <instance> ::= { <field_id> : <obj_val> }
for (uint32_t j = 0; j != map.size(); ++j) {
assert(is_uint(map.get(j).key.type));
const mp::Map::Pair &pair = map.get(j);
const dr::RTFieldDef &field = *klass.fields[pair.key.via._uint64];
write_indent() << port::BOLD << std::setw(max_length) << std::left << field.serial << ": " << port::OFF;
write_field(store, field, pair.value) << "\n";
}
--_indent;
write_indent() << "},\n";
}
--_indent;
write_indent() << "},\n";
}
std::ostream &
DocProcessor::write_indent(void) {
for (unsigned int i = 0; i != _indent; ++i)
_out << " ";
return _out;
}
std::ostream &
DocProcessor::write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
const auto flags = _out.flags();
if (field.is_slice)
write_slice(field, value);
else if (field.points_into != nullptr || field.is_self_pointer)
write_pointer(store, field, value);
else
write_primitive(value);
_out.flags(flags);
return _out;
}
void
DocProcessor::write_slice(const dr::RTFieldDef &field, const mp::Value &value) {
assert(is_array(value.type));
const auto &array = *value.via._array;
assert(array.size() == 2);
assert(is_uint(array[0].type));
assert(is_uint(array[1].type));
const uint64_t a = array[0].via._uint64;
const uint64_t b = array[1].via._uint64;
_out << "[0x" << std::hex << a << ", 0x" << std::hex << (a + b) << "],";
_out << SEP;
if (field.points_into == nullptr)
_out << "byte slice";
else
_out << "slice into " << field.points_into->serial;
_out << " (" << std::dec << a << ", " << std::dec << (a + b) << ")" << port::OFF;
}
void
DocProcessor::write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
if (field.is_collection) {
assert(is_array(value.type));
const mp::Array &array = *value.via._array;
_out << "[";
for (uint32_t i = 0; i != array.size(); ++i) {
const mp::Value &v = array[i];
if (i != 0)
_out << ", ";
if (is_nil(v.type) || is_uint(v.type)) {
if (is_nil(v.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << v.via._uint64;
}
else
_out << port::RED << v.type << port::OFF;
}
_out << "]";
}
else {
if (is_nil(value.type) || is_uint(value.type)) {
if (is_nil(value.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << value.via._uint64;
}
else
_out << port::RED << value.type << port::OFF;
}
_out << SEP;
if (field.is_self_pointer)
_out << "self-pointer" << (field.is_collection ? "s" : "") << " into " << store.serial;
else
_out << "pointer" << (field.is_collection ? "s" : "") << " into " << field.points_into->serial;
_out << port::OFF;
}
void
DocProcessor::write_primitive(const mp::Value &value) {
if (is_bool(value.type)) {
_out << std::boolalpha << value.via._bool << ",";
}
else if (is_double(value.type)) {
_out << value.via._double << ",";
_out << SEP << "double" << port::OFF;
}
else if (is_float(value.type)) {
_out << value.via._float << ",";
_out << SEP << "float" << port::OFF;
}
else if (is_nil(value.type)) {
_out << REPR_NIL;
}
else if (is_sint(value.type)) {
_out << "0x" << std::hex << value.via._int64 << std::dec << ",";
_out << SEP << "int (" << value.via._int64 << ")" << port::OFF;
}
else if (is_uint(value.type)) {
_out << "0x" << std::hex << value.via._uint64 << std::dec << ",";
_out << SEP << "uint (" << value.via._uint64 << ")" << port::OFF;
}
else if (is_array(value.type)) {
_out << port::RED << "TODO array" << port::OFF;
}
else if (is_map(value.type)) {
_out << port::RED << "TODO map" << port::OFF;
}
else if (is_raw(value.type)) {
const mp::Raw &raw = *value.via._raw;
(_out << "\"").write(raw.value(), raw.size()) << "\",";
_out << SEP << "raw (" << std::dec << raw.size() << "B)" << port::OFF;
}
else
_out << port::RED << REPR_UNKNOWN << port::OFF;
}
} // namespace
int
main(int argc, char *argv[]) {
// process args
Config c;
c.main(argc, argv);
// construct a docrep reader over the provided input stream
std::istream &in = c.input.file();
FauxDoc::Schema schema;
dr::Reader reader(in, schema);
// read the documents off the input stream
FauxDoc doc;
for (unsigned int i = 0; reader >> doc; ++i)
DocProcessor(doc, std::cout, i)();
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "TestLib.h"
#include "AffineGapVectorized.h"
#include "LandauVishkin.h"
// Test fixture for all the affine gap tests
struct AffineGapVectorizedTest {
AffineGapVectorized<> ag;
AffineGapVectorizedTest() : ag(1, 4, 6, 1) {
initializeLVProbabilitiesToPhredPlus33();
}
int editDist;
int computeScore(
const char* text,
int textLen,
const char* pattern,
const char* qualityString,
int patternLen,
int w,
int scoreInit)
{
char* quality = new char[strlen(text) + 1];
for (int i = 0; i < strlen(text); i++) {
quality[i] = '2';
}
quality[strlen(text)] = '\0';
int retVal = ag.computeScore(text, textLen, pattern, quality, patternLen, w, scoreInit);
delete[] quality;
return retVal;
}
};
TEST_F(AffineGapVectorizedTest, "equal strings") {
ASSERT_EQ(25, computeScore("ACGTA", 5, "ACGTA", NULL, 5, 16, 20));
}
TEST_F(AffineGapVectorizedTest, "one deletion") {
ASSERT_EQ(21, computeScore("AACGTACGT", 9, "ACGTACGT", NULL, 8, 16, 20));
}
TEST_F(AffineGapVectorizedTest, "long deletion") {
// ASSERT_EQ(21, ag.computeScore("ACGTAAAAACGTACGTACGT", 20, "ACGTACGTACGTACGT", NULL, 16, 3, 20)); // edit distance = 3
ASSERT_EQ(26, computeScore("ACGTAAAAACGTACGTACGT", 20, "ACGTACGTACGTACGT", NULL, 16, 16, 20)); // edit distance = 4
}
TEST_F(AffineGapVectorizedTest, "long insertion") {
ASSERT_EQ(104, computeScore("CCGTCTCAACAATAACAACAACAACAACAAAAACCAGTCACTGTGTTAGGGACAGTCAGAACATGGGGGGATGGGAAAGAGGAGTTACAGGGAGACTT", 98, "CCGTCTCAACAATAACAACAACAACAACAACAAAAGCCAGTCACTGTGTTAGGGACAGTCAGAACATGGGGGGATGGGAAAGAGGAGTTACAGGGAGACTT", "22222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222", 101, 16, 20));
ASSERT_EQ(103, computeScore("ACAATTAGGCAAAAAATCAATGGGATTCAGACAAATATGGGACAATTTTCTCTCTCTGTCTCTCTCTCTGTCTCTCTCTCTGACACACACACACA", 95, "ACAATTAGGCAAAAAATCAATGGGATTCAGACAAATATGGGACAATTTTCTCTCTCTGTCTCTCTCTCTGTCTCTGTCTCTCTCTCTGACACACACACACA", "22222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222", 101, 16, 20)); // 64M6I31M
}
TEST_F(AffineGapVectorizedTest, "synthetic") {
ASSERT_EQ(72, computeScore("CATTGGCCAGGCTGGTCTCGAACTCCTGACCTCATGATCCACACGCCTCGA", 51, "TGTTGGTCAGGCTGGTCTCGAACTCCT", NULL, 27, 16, 60))
ASSERT_EQ(80, computeScore("CAAAAATTAGCTGGGCACGGTGGCAGGCGCCTGTAATCCCAGCTACTCAGGAGACTGAGGCAGGAGAA", 68, "GAAAAATTAGCTGTGCACGGTGGCAGGCGCCTGTA", NULL, 35, 16, 55));
ASSERT_EQ(-1, computeScore("CAAAAAATTAGCCACGCATGGTGGCATATCCCTGTAGTCCCAGCTACTCGGGGCTGAGGCAGGAG", 65, "GAAAAATTAGCTGTGCACGGTGGCAGGCGCCTGTA", NULL, 35, 16, 40));
ASSERT_EQ(95, computeScore("TAACCAATTAGACAGCTTCTTCCCACCCCAGACCCCAGAGACCTGGCCCAAGCCTGGAGAAGACATCCTGTTTCCCCTGAGGAAGTGGCCCAGATTG", 97, "AAACCAATTAGACAGCTTCTTC", NULL, 22, 16, 78));
ASSERT_EQ(83, computeScore("CTCTGTCTCTCTCTCTGTCTCTCTCTTTTAACAGGGTATAAACAGACTTAGGGTAACTAAAAAACGGATTAACAATAAGTGATACGA", 87, "CTCTGTCTCTGTCTCTCTCTCTGTCTCTCTCTTTTAACAGGGTATAAACAGACTTAGGGTAACTAAAAAACGGATTAACA", NULL, 80, 8, 21));
}
/* Edit distance tests */
/*
TEST_F(AffineGapTest, "edit distance-equal length strings") {
ag.computeScore("GAGTCCCCTTTTTTTTTTTTTCCTTTATAAAAGGCTTTCGATCAGACTCGGTCCGTCATACTTTCTGTGACTTCTATTTTCTCGTCAGAACTTGAGATGT", 100, "GAGTCCCCTTTTTTTTTTTTTCCTTTATAAAAGGCTTTCGATCAGACTCGGTCCGTCATACTTTCTGTGACTTCAATTAACTCGTCAGAACTTGAGATGT", NULL, 100, 16, 20, NULL, &editDist);
ASSERT_EQ(editDist, 3);
}
TEST_F(AffineGapTest, "edit distance-ref longer") {
ASSERT_EQ(8, ag.computeScore("TGAGAGGGACGGACATGAGGGGACAAAGTCAAGTCTTTTGTTCAAACTTTATGTCTTGTATCTTATGGAGGTCAAATCTTTCAGACTACATACGGAGAATCAAGG", 105, "TGAGCGGGACGGACATGACAAAGTCAAGTCTTTTGTACAAACTTTATGTCTTGTATCTTATGGAGGTCAAATCTTTCAGACTACATACGGAGAATCCAGG", NULL, 100, 16, 20))
}
TEST_F(AffineGapTest, "edit distance-ref shorter") {
ASSERT_EQ(5, ag.computeScore("ATACTGAACGACTTCCAAGTCTACTAGTAATCGTCAAAAATCGTTATTTCGTAAAAAAAAAGAAAAAACTCTGTCCCAGAGTATAACAACGGG", 93, "ATACTGAACGACTTCCAAGTCTACTAGAAATCGTCAAAAATCGTTATTTCGTACAAAAAAAAATAAAAAACTCTGTCCCATAGTATAACAACGGG", NULL, 95, 16, 20))
}
*/
<commit_msg>Fix failing affine gap test<commit_after>#include "stdafx.h"
#include "TestLib.h"
#include "AffineGapVectorized.h"
#include "LandauVishkin.h"
// Test fixture for all the affine gap tests
struct AffineGapVectorizedTest {
AffineGapVectorized<> ag;
AffineGapVectorizedTest() : ag(1, 4, 6, 1) {
initializeLVProbabilitiesToPhredPlus33();
}
int editDist;
int computeScore(
const char* text,
int textLen,
const char* pattern,
const char* qualityString,
int patternLen,
int w,
int scoreInit)
{
char* quality = new char[strlen(text) + 1];
for (int i = 0; i < strlen(text); i++) {
quality[i] = '2';
}
quality[strlen(text)] = '\0';
int retVal = ag.computeScore(text, textLen, pattern, quality, patternLen, w, scoreInit);
delete[] quality;
return retVal;
}
};
TEST_F(AffineGapVectorizedTest, "equal strings") {
ASSERT_EQ(25, computeScore("ACGTA", 5, "ACGTA", NULL, 5, 16, 20));
}
TEST_F(AffineGapVectorizedTest, "one deletion") {
ASSERT_EQ(21, computeScore("AACGTACGT", 9, "ACGTACGT", NULL, 8, 16, 20));
}
TEST_F(AffineGapVectorizedTest, "long deletion") {
// ASSERT_EQ(21, ag.computeScore("ACGTAAAAACGTACGTACGT", 20, "ACGTACGTACGTACGT", NULL, 16, 3, 20)); // edit distance = 3
ASSERT_EQ(26, computeScore("ACGTAAAAACGTACGTACGT", 20, "ACGTACGTACGTACGT", NULL, 16, 16, 20)); // edit distance = 4
}
TEST_F(AffineGapVectorizedTest, "long insertion") {
ASSERT_EQ(104, computeScore("CCGTCTCAACAATAACAACAACAACAACAAAAACCAGTCACTGTGTTAGGGACAGTCAGAACATGGGGGGATGGGAAAGAGGAGTTACAGGGAGACTT", 98, "CCGTCTCAACAATAACAACAACAACAACAACAAAAGCCAGTCACTGTGTTAGGGACAGTCAGAACATGGGGGGATGGGAAAGAGGAGTTACAGGGAGACTT", "22222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222", 101, 16, 20));
ASSERT_EQ(103, computeScore("ACAATTAGGCAAAAAATCAATGGGATTCAGACAAATATGGGACAATTTTCTCTCTCTGTCTCTCTCTCTGTCTCTCTCTCTGACACACACACACA", 95, "ACAATTAGGCAAAAAATCAATGGGATTCAGACAAATATGGGACAATTTTCTCTCTCTGTCTCTCTCTCTGTCTCTGTCTCTCTCTCTGACACACACACACA", "22222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222", 101, 16, 20)); // 64M6I31M
}
TEST_F(AffineGapVectorizedTest, "synthetic") {
ASSERT_EQ(72, computeScore("CATTGGCCAGGCTGGTCTCGAACTCCTGACCTCATGATCCACACGCCTCGA", 51, "TGTTGGTCAGGCTGGTCTCGAACTCCT", NULL, 27, 16, 60))
ASSERT_EQ(80, computeScore("CAAAAATTAGCTGGGCACGGTGGCAGGCGCCTGTAATCCCAGCTACTCAGGAGACTGAGGCAGGAGAA", 68, "GAAAAATTAGCTGTGCACGGTGGCAGGCGCCTGTA", NULL, 35, 16, 55));
ASSERT_EQ(41, computeScore("CAAAAAATTAGCCACGCATGGTGGCATATCCCTGTAGTCCCAGCTACTCGGGGCTGAGGCAGGAG", 65, "GAAAAATTAGCTGTGCACGGTGGCAGGCGCCTGTA", NULL, 35, 16, 40));
ASSERT_EQ(95, computeScore("TAACCAATTAGACAGCTTCTTCCCACCCCAGACCCCAGAGACCTGGCCCAAGCCTGGAGAAGACATCCTGTTTCCCCTGAGGAAGTGGCCCAGATTG", 97, "AAACCAATTAGACAGCTTCTTC", NULL, 22, 16, 78));
ASSERT_EQ(83, computeScore("CTCTGTCTCTCTCTCTGTCTCTCTCTTTTAACAGGGTATAAACAGACTTAGGGTAACTAAAAAACGGATTAACAATAAGTGATACGA", 87, "CTCTGTCTCTGTCTCTCTCTCTGTCTCTCTCTTTTAACAGGGTATAAACAGACTTAGGGTAACTAAAAAACGGATTAACA", NULL, 80, 8, 21));
}
/* Edit distance tests */
/*
TEST_F(AffineGapTest, "edit distance-equal length strings") {
ag.computeScore("GAGTCCCCTTTTTTTTTTTTTCCTTTATAAAAGGCTTTCGATCAGACTCGGTCCGTCATACTTTCTGTGACTTCTATTTTCTCGTCAGAACTTGAGATGT", 100, "GAGTCCCCTTTTTTTTTTTTTCCTTTATAAAAGGCTTTCGATCAGACTCGGTCCGTCATACTTTCTGTGACTTCAATTAACTCGTCAGAACTTGAGATGT", NULL, 100, 16, 20, NULL, &editDist);
ASSERT_EQ(editDist, 3);
}
TEST_F(AffineGapTest, "edit distance-ref longer") {
ASSERT_EQ(8, ag.computeScore("TGAGAGGGACGGACATGAGGGGACAAAGTCAAGTCTTTTGTTCAAACTTTATGTCTTGTATCTTATGGAGGTCAAATCTTTCAGACTACATACGGAGAATCAAGG", 105, "TGAGCGGGACGGACATGACAAAGTCAAGTCTTTTGTACAAACTTTATGTCTTGTATCTTATGGAGGTCAAATCTTTCAGACTACATACGGAGAATCCAGG", NULL, 100, 16, 20))
}
TEST_F(AffineGapTest, "edit distance-ref shorter") {
ASSERT_EQ(5, ag.computeScore("ATACTGAACGACTTCCAAGTCTACTAGTAATCGTCAAAAATCGTTATTTCGTAAAAAAAAAGAAAAAACTCTGTCCCAGAGTATAACAACGGG", 93, "ATACTGAACGACTTCCAAGTCTACTAGAAATCGTCAAAAATCGTTATTTCGTACAAAAAAAAATAAAAAACTCTGTCCCATAGTATAACAACGGG", NULL, 95, 16, 20))
}
*/
<|endoftext|> |
<commit_before>#include <Nazara/Math/EulerAngles.hpp>
#include <Catch/catch.hpp>
SCENARIO("EulerAngles", "[MATH][EULERANGLES]")
{
GIVEN("Two zero euler angles")
{
Nz::EulerAnglesf firstZero(0.f, 0.f, 0.f);
Nz::EulerAnglesf secondZero(Nz::EulerAngles<int>::Zero());
THEN("They should be equal")
{
REQUIRE(firstZero == secondZero);
}
WHEN("We do some operations")
{
Nz::EulerAnglesf euler90(Nz::FromDegrees(90.f), Nz::FromDegrees(90.f), Nz::FromDegrees(90.f));
Nz::EulerAnglesf euler270(Nz::FromDegrees(270.f), Nz::FromDegrees(270.f), Nz::FromDegrees(270.f));
Nz::EulerAnglesf euler360 = euler90 + euler270;
euler360.Normalize();
Nz::EulerAnglesf euler0 = euler270 - euler90;
euler0 -= euler90;
euler0 -= euler90;
THEN("They should still be equal")
{
REQUIRE(euler360 == firstZero);
REQUIRE(euler0 == secondZero);
}
}
WHEN("We ask for conversion to quaternion")
{
THEN("They are the same")
{
REQUIRE(firstZero.ToQuaternion() == secondZero.ToQuaternion());
REQUIRE(firstZero.ToQuaternion() == Nz::EulerAnglesf(Nz::Quaternionf(1.f, 0.f, 0.f, 0.f)));
REQUIRE(secondZero.ToQuaternion() == Nz::EulerAnglesf(Nz::Quaternionf(1.f, 0.f, 0.f, 0.f)));
}
}
}
GIVEN("Three rotation of 90 on each axis")
{
Nz::EulerAnglesf euler90P(Nz::FromDegrees(90.f), 0.f, 0.f);
Nz::EulerAnglesf euler90Y(0.f, Nz::FromDegrees(90.f), 0.f);
Nz::EulerAnglesf euler90R(0.f, 0.f, Nz::FromDegrees(90.f));
WHEN("We transform the axis")
{
THEN("This is supposed to be left-handed")
{
Nz::Vector3f rotation90P = euler90P.ToQuaternion() * Nz::Vector3f::UnitY();
Nz::Vector3f rotation90Y = euler90Y.ToQuaternion() * Nz::Vector3f::UnitZ();
Nz::Vector3f rotation90R = euler90R.ToQuaternion() * Nz::Vector3f::UnitX();
REQUIRE(rotation90P == Nz::Vector3f::UnitZ());
REQUIRE(rotation90Y == Nz::Vector3f::UnitX());
REQUIRE(rotation90R == Nz::Vector3f::UnitY());
}
}
}
GIVEN("Euler angles with rotation 45 on each axis")
{
WHEN("We convert to quaternion")
{
THEN("These results are expected")
{
REQUIRE(Nz::EulerAngles<int>(Nz::FromDegrees(45.f), 0.f, 0.f) == Nz::EulerAngles<int>(Nz::Quaternionf(0.923879504204f, 0.382683455944f, 0.f, 0.f).ToEulerAngles()));
REQUIRE(Nz::EulerAngles<int>(0.f, Nz::FromDegrees(45.f), 0.f) == Nz::EulerAngles<int>(Nz::Quaternionf(0.923879504204f, 0.f, 0.382683455944f, 0.f).ToEulerAngles()));
REQUIRE(Nz::EulerAngles<int>(0.f, 0.f, Nz::FromDegrees(45.f)) == Nz::EulerAngles<int>(Nz::Quaternionf(0.923879504204f, 0.f, 0.f, 0.382683455944f).ToEulerAngles()));
}
}
}
GIVEN("Three euler angles: (0, 22.5, 22.5), (90, 90, 0) and (30, 0, 30)")
{
Nz::EulerAnglesf euler45(Nz::FromDegrees(0.f), Nz::FromDegrees(22.5f), Nz::FromDegrees(22.5f));
Nz::EulerAnglesf euler90(Nz::FromDegrees(90.f), Nz::FromDegrees(90.f), Nz::FromDegrees(0.f));
Nz::EulerAnglesf euler30(Nz::FromDegrees(30.f), Nz::FromDegrees(0.f), Nz::FromDegrees(30.f));
WHEN("We convert them to quaternion")
{
THEN("And then convert to euler angles, we have identity")
{
Nz::EulerAnglesf tmp = Nz::Quaternionf(euler45.ToQuaternion()).ToEulerAngles();
REQUIRE(tmp.pitch == Approx(0.f));
REQUIRE(tmp.yaw == Approx(22.5f));
REQUIRE(tmp.roll == Approx(22.5f));
tmp = Nz::Quaternionf(euler90.ToQuaternion()).ToEulerAngles();
REQUIRE(tmp.pitch == Approx(90.f));
REQUIRE(tmp.yaw == Approx(90.f));
REQUIRE(tmp.roll == Approx(0.f));
tmp = Nz::Quaternionf(euler30.ToQuaternion()).ToEulerAngles();
REQUIRE(tmp.pitch == Approx(30.f));
REQUIRE(tmp.yaw == Approx(0.f).margin(0.0001f));
REQUIRE(tmp.roll == Approx(30.f));
}
}
}
}
<commit_msg>Fix some units test<commit_after>#include <Nazara/Math/Angle.hpp>
#include <Nazara/Math/EulerAngles.hpp>
#include <Catch/catch.hpp>
SCENARIO("EulerAngles", "[MATH][EULERANGLES]")
{
GIVEN("Two zero euler angles")
{
Nz::EulerAnglesf firstZero(0.f, 0.f, 0.f);
Nz::EulerAnglesf secondZero(Nz::EulerAngles<int>::Zero());
THEN("They should be equal")
{
REQUIRE(firstZero == secondZero);
}
WHEN("We do some operations")
{
Nz::EulerAnglesf euler90(Nz::FromDegrees(90.f), Nz::FromDegrees(90.f), Nz::FromDegrees(90.f));
Nz::EulerAnglesf euler270(Nz::FromDegrees(270.f), Nz::FromDegrees(270.f), Nz::FromDegrees(270.f));
Nz::EulerAnglesf euler360 = euler90 + euler270;
euler360.Normalize();
Nz::EulerAnglesf euler0 = euler270 - euler90;
euler0 -= euler90;
euler0 -= euler90;
THEN("They should still be equal")
{
CHECK(euler360 == firstZero);
CHECK(euler0 == secondZero);
}
}
WHEN("We ask for conversion to quaternion")
{
THEN("They are the same")
{
CHECK(firstZero.ToQuaternion() == secondZero.ToQuaternion());
CHECK(firstZero.ToQuaternion() == Nz::EulerAnglesf(Nz::Quaternionf(1.f, 0.f, 0.f, 0.f)));
CHECK(secondZero.ToQuaternion() == Nz::EulerAnglesf(Nz::Quaternionf(1.f, 0.f, 0.f, 0.f)));
}
}
}
GIVEN("Three rotation of 90 on each axis")
{
Nz::EulerAnglesf euler90P(Nz::FromDegrees(90.f), 0.f, 0.f);
Nz::EulerAnglesf euler90Y(0.f, Nz::FromDegrees(90.f), 0.f);
Nz::EulerAnglesf euler90R(0.f, 0.f, Nz::FromDegrees(90.f));
WHEN("We transform the axis")
{
THEN("This is supposed to be left-handed")
{
Nz::Vector3f rotation90P = euler90P.ToQuaternion() * Nz::Vector3f::UnitY();
Nz::Vector3f rotation90Y = euler90Y.ToQuaternion() * Nz::Vector3f::UnitZ();
Nz::Vector3f rotation90R = euler90R.ToQuaternion() * Nz::Vector3f::UnitX();
CHECK(rotation90P == Nz::Vector3f::UnitZ());
CHECK(rotation90Y == Nz::Vector3f::UnitX());
CHECK(rotation90R == Nz::Vector3f::UnitY());
}
}
}
GIVEN("Euler angles with rotation 45 on each axis")
{
WHEN("We convert to quaternion")
{
THEN("These results are expected")
{
CHECK(Nz::EulerAngles<int>(Nz::FromDegrees(45.f), 0.f, 0.f) == Nz::EulerAngles<int>(Nz::Quaternionf(0.923879504204f, 0.382683455944f, 0.f, 0.f).ToEulerAngles()));
CHECK(Nz::EulerAngles<int>(0.f, Nz::FromDegrees(45.f), 0.f) == Nz::EulerAngles<int>(Nz::Quaternionf(0.923879504204f, 0.f, 0.382683455944f, 0.f).ToEulerAngles()));
CHECK(Nz::EulerAngles<int>(0.f, 0.f, Nz::FromDegrees(45.f)) == Nz::EulerAngles<int>(Nz::Quaternionf(0.923879504204f, 0.f, 0.f, 0.382683455944f).ToEulerAngles()));
}
}
}
GIVEN("Three euler angles: (0, 22.5, 22.5), (90, 90, 0) and (30, 0, 30)")
{
Nz::EulerAnglesf euler45(Nz::FromDegrees(0.f), Nz::FromDegrees(22.5f), Nz::FromDegrees(22.5f));
Nz::EulerAnglesf euler90(Nz::FromDegrees(90.f), Nz::FromDegrees(90.f), Nz::FromDegrees(0.f));
Nz::EulerAnglesf euler30(Nz::FromDegrees(30.f), Nz::FromDegrees(0.f), Nz::FromDegrees(30.f));
WHEN("We convert them to quaternion")
{
THEN("And then convert to euler angles, we have identity")
{
Nz::EulerAnglesf tmp = Nz::Quaternionf(euler45.ToQuaternion()).ToEulerAngles();
CHECK(tmp.pitch == Approx(0.f));
CHECK(tmp.yaw == Approx(22.5f));
CHECK(tmp.roll == Approx(22.5f));
tmp = Nz::Quaternionf(euler90.ToQuaternion()).ToEulerAngles();
CHECK(tmp.pitch == Approx(90.f));
CHECK(tmp.yaw == Approx(90.f));
CHECK(tmp.roll == Approx(0.f));
tmp = Nz::Quaternionf(euler30.ToQuaternion()).ToEulerAngles();
CHECK(tmp.pitch == Approx(30.f));
CHECK(tmp.yaw == Approx(0.f).margin(0.0001f));
CHECK(tmp.roll == Approx(30.f));
}
}
}
GIVEN("An angle of 45 degrees")
{
Nz::DegreeAnglef angle(45.f);
WHEN("We convert it to Euler angles")
{
Nz::EulerAnglesf eulerAngles(angle);
THEN("It should be equal to a 2D rotation of 45 degrees")
{
CHECK(eulerAngles == Nz::EulerAnglesf(0.f, 0.f, 45.f));
}
}
}
}
<|endoftext|> |
<commit_before>/* Sirikata
* Context.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* 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 Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sirikata/core/util/Standard.hh>
#include <sirikata/core/service/Context.hpp>
#include <sirikata/core/network/IOServiceFactory.hpp>
#include <sirikata/core/network/IOStrandImpl.hpp>
#include <boost/asio.hpp>
#include <sirikata/core/service/Breakpad.hpp>
namespace Sirikata {
Context* Context::mainContextPtr = NULL;
Context::Context(const String& name, Network::IOService* ios, Network::IOStrand* strand, Trace::Trace* _trace, const Time& epoch, const Duration& simlen)
: ioService(ios),
mainStrand(strand),
profiler( new TimeProfiler(name) ),
timeSeries(NULL),
mFinishedTimer( Network::IOTimer::create(ios) ),
mTrace(_trace),
mEpoch(epoch),
mLastSimTime(Time::null()),
mSimDuration(simlen),
mKillThread(),
mKillService(NULL),
mKillTimer(),
mStopRequested(false)
{
Breakpad::init();
}
Context::~Context() {
delete profiler;
}
void Context::start() {
mSignalHandler = Signal::registerHandler(
std::tr1::bind(&Context::handleSignal, this, std::tr1::placeholders::_1)
);
if (mSimDuration == Duration::zero())
return;
Time t_now = simTime();
Time t_end = simTime(mSimDuration);
Duration wait_dur = t_end - t_now;
mFinishedTimer->wait(
wait_dur,
mainStrand->wrap(
std::tr1::bind(&Context::shutdown, this)
)
);
}
void Context::run(uint32 nthreads, ExecutionThreads exthreads) {
mExecutionThreadsType = exthreads;
uint32 nworkers = (exthreads == IncludeOriginal ? nthreads-1 : nthreads);
// Start workers
for(uint32 i = 1; i < nworkers; i++) {
mWorkerThreads.push_back(
new Thread( std::tr1::bind(&Context::workerThread, this) )
);
}
// Run
if (exthreads == IncludeOriginal) {
ioService->run();
cleanupWorkerThreads();
}
}
void Context::workerThread() {
ioService->run();
}
void Context::cleanupWorkerThreads() {
// Wait for workers to finish
for(uint32 i = 0; i < mWorkerThreads.size(); i++) {
mWorkerThreads[i]->join();
delete mWorkerThreads[i];
}
mWorkerThreads.clear();
}
void Context::shutdown() {
// If the original thread wasn't running this context as well, then it won't
// be able to wait for the worker threads it created.
if (mExecutionThreadsType != IncludeOriginal)
cleanupWorkerThreads();
Signal::unregisterHandler(mSignalHandler);
this->stop();
for(std::vector<Service*>::iterator it = mServices.begin(); it != mServices.end(); it++)
(*it)->stop();
}
void Context::stop() {
if (!mStopRequested.read()) {
mStopRequested = true;
mFinishedTimer.reset();
startForceQuitTimer();
}
}
void Context::handleSignal(Signal::Type stype) {
// Try to keep this minimal. Post the shutdown process rather than
// actually running it here. This makes the extent of the signal
// handling known completely in this method, whereas calling
// shutdown can cause a cascade of cleanup.
ioService->post( std::tr1::bind(&Context::shutdown, this) );
}
void Context::cleanup() {
Network::IOTimerPtr timer = mKillTimer;
if (timer) {
timer->cancel();
mKillTimer.reset();
timer.reset();
mKillService->stop();
mKillThread->join();
Network::IOServiceFactory::destroyIOService(mKillService);
mKillService = NULL;
mKillThread.reset();
}
}
void Context::startForceQuitTimer() {
// Note that we need to do this on another thread, with another IOService.
// This is necessary to ensure that *this* doesn't keep things from
// exiting.
mKillService = Network::IOServiceFactory::makeIOService();
mKillTimer = Network::IOTimer::create(mKillService);
mKillTimer->wait(
Duration::seconds(5),
std::tr1::bind(&Context::forceQuit, this)
);
mKillThread = std::tr1::shared_ptr<Thread>(
new Thread(
std::tr1::bind(&Network::IOService::runNoReturn, mKillService)
)
);
}
} // namespace Sirikata
<commit_msg>If context ran out of work, make sure it runs shutdown process. Fixes #324.<commit_after>/* Sirikata
* Context.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* 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 Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sirikata/core/util/Standard.hh>
#include <sirikata/core/service/Context.hpp>
#include <sirikata/core/network/IOServiceFactory.hpp>
#include <sirikata/core/network/IOStrandImpl.hpp>
#include <boost/asio.hpp>
#include <sirikata/core/service/Breakpad.hpp>
namespace Sirikata {
Context* Context::mainContextPtr = NULL;
Context::Context(const String& name, Network::IOService* ios, Network::IOStrand* strand, Trace::Trace* _trace, const Time& epoch, const Duration& simlen)
: ioService(ios),
mainStrand(strand),
profiler( new TimeProfiler(name) ),
timeSeries(NULL),
mFinishedTimer( Network::IOTimer::create(ios) ),
mTrace(_trace),
mEpoch(epoch),
mLastSimTime(Time::null()),
mSimDuration(simlen),
mKillThread(),
mKillService(NULL),
mKillTimer(),
mStopRequested(false)
{
Breakpad::init();
}
Context::~Context() {
delete profiler;
}
void Context::start() {
mSignalHandler = Signal::registerHandler(
std::tr1::bind(&Context::handleSignal, this, std::tr1::placeholders::_1)
);
if (mSimDuration == Duration::zero())
return;
Time t_now = simTime();
Time t_end = simTime(mSimDuration);
Duration wait_dur = t_end - t_now;
mFinishedTimer->wait(
wait_dur,
mainStrand->wrap(
std::tr1::bind(&Context::shutdown, this)
)
);
}
void Context::run(uint32 nthreads, ExecutionThreads exthreads) {
mExecutionThreadsType = exthreads;
uint32 nworkers = (exthreads == IncludeOriginal ? nthreads-1 : nthreads);
// Start workers
for(uint32 i = 1; i < nworkers; i++) {
mWorkerThreads.push_back(
new Thread( std::tr1::bind(&Context::workerThread, this) )
);
}
// Run
if (exthreads == IncludeOriginal) {
ioService->run();
cleanupWorkerThreads();
}
// If we exited gracefully, call shutdown automatically to clean everything
// up, make sure stop() methods get called, etc.
if (!mStopRequested.read())
this->shutdown();
}
void Context::workerThread() {
ioService->run();
}
void Context::cleanupWorkerThreads() {
// Wait for workers to finish
for(uint32 i = 0; i < mWorkerThreads.size(); i++) {
mWorkerThreads[i]->join();
delete mWorkerThreads[i];
}
mWorkerThreads.clear();
}
void Context::shutdown() {
// If the original thread wasn't running this context as well, then it won't
// be able to wait for the worker threads it created.
if (mExecutionThreadsType != IncludeOriginal)
cleanupWorkerThreads();
Signal::unregisterHandler(mSignalHandler);
this->stop();
for(std::vector<Service*>::iterator it = mServices.begin(); it != mServices.end(); it++)
(*it)->stop();
}
void Context::stop() {
if (!mStopRequested.read()) {
mStopRequested = true;
mFinishedTimer.reset();
startForceQuitTimer();
}
}
void Context::handleSignal(Signal::Type stype) {
// Try to keep this minimal. Post the shutdown process rather than
// actually running it here. This makes the extent of the signal
// handling known completely in this method, whereas calling
// shutdown can cause a cascade of cleanup.
ioService->post( std::tr1::bind(&Context::shutdown, this) );
}
void Context::cleanup() {
Network::IOTimerPtr timer = mKillTimer;
if (timer) {
timer->cancel();
mKillTimer.reset();
timer.reset();
mKillService->stop();
mKillThread->join();
Network::IOServiceFactory::destroyIOService(mKillService);
mKillService = NULL;
mKillThread.reset();
}
}
void Context::startForceQuitTimer() {
// Note that we need to do this on another thread, with another IOService.
// This is necessary to ensure that *this* doesn't keep things from
// exiting.
mKillService = Network::IOServiceFactory::makeIOService();
mKillTimer = Network::IOTimer::create(mKillService);
mKillTimer->wait(
Duration::seconds(5),
std::tr1::bind(&Context::forceQuit, this)
);
mKillThread = std::tr1::shared_ptr<Thread>(
new Thread(
std::tr1::bind(&Network::IOService::runNoReturn, mKillService)
)
);
}
} // namespace Sirikata
<|endoftext|> |
<commit_before>#include <iostream>
#include "format.hpp"
int main(int argc, char* argv[]);
int main(int argc, char* argv[])
{
using namespace utils;
{
int a = 1000;
format("%d\n") % a;
}
{
static const char* t = { "Asdfg" };
format("'%s'\n") % t;
}
{
char tmp[100];
strcpy(tmp, "Qwert");
format("'%s'\n") % tmp;
}
{
char str[] = { "Asdfg" };
int i = 123;
float a = 1000.105f;
float b = 0.0f;
format("%d, '%s', %7.3f, %6.2f\n") % i % str % a % b;
}
{
float x = 1.0f;
float y = 2.0f;
float z = 3.0f;
char tmp[512];
sformat("Value: %f, %f, %f\n", tmp, sizeof(tmp)) % x % y % z;
sformat("Value: %f, %f, %f\n", tmp, sizeof(tmp), true) % y % z % x;
sformat("Value: %f, %f, %f\n", tmp, sizeof(tmp), true) % z % x % y;
int size = sformat::chaout().size();
format("(%d)\n%s") % size % tmp;
}
{ // 10進、16進、8進、2進
int16_t n = -1;
format("%d, 0x%04x, 0o%03o, 0b%04b\n") % n % n % n % n;
n = 1;
format("%d, 0x%04x, 0o%03o, 0b%04b\n") % n % n % n % n;
}
{ // 異なったプロトタイプ
static const char* str = { "Poiuytrewq" };
int val = 1921;
format("%s, %d\n") % val % str;
}
}
<commit_msg>update: cleanup<commit_after>#include <iostream>
#include <boost/format.hpp>
#include "format.hpp"
int main(int argc, char* argv[]);
int main(int argc, char* argv[])
{
using namespace utils;
{
int a = 1000;
format("%d\n") % a;
}
{
static const char* t = { "Asdfg" };
format("'%s'\n") % t;
}
{
char tmp[100];
strcpy(tmp, "Qwert");
format("'%s'\n") % tmp;
}
{
char str[] = { "Asdfg" };
int i = 123;
float a = 1000.105f;
float b = 0.0f;
format("%d, '%s', %7.3f, %6.2f\n") % i % str % a % b;
}
{
float x = 1.0f;
float y = 2.0f;
float z = 3.0f;
char tmp[512];
sformat("Value: %f, %f, %f\n", tmp, sizeof(tmp)) % x % y % z;
sformat("Value: %f, %f, %f\n", tmp, sizeof(tmp), true) % y % z % x;
sformat("Value: %f, %f, %f\n", tmp, sizeof(tmp), true) % z % x % y;
int size = sformat::chaout().size();
format("(%d)\n%s") % size % tmp;
}
{ // 10進、16進、8進、2進
int16_t n = -1;
format("%d, 0x%04x, 0o%03o, 0b%04b\n") % n % n % n % n;
n = 1;
format("%d, 0x%04x, 0o%03o, 0b%04b\n") % n % n % n % n;
}
{ // 異なったプロトタイプ
static const char* str = { "Poiuytrewq" };
int val = 1921;
format("%s, %d\n") % val % str;
}
format("\n");
{ // 0.01 * 10000
float a = 0.0f;
for(int i = 0; i < 10000; ++i) {
a += 0.01f;
}
format("0.01 * 10000 (float): %6.3f\n") % a;
}
{ // 0.01 * 10000
double a = 0.0f;
for(int i = 0; i < 10000; ++i) {
a += 0.01;
}
std::cout << boost::format("0.01 * 10000 (double): %6.3f\n") % a;
}
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#ifndef HTTP_MESSAGE_HPP
#define HTTP_MESSAGE_HPP
#include "header.hpp"
namespace http {
class Message {
private:
//----------------------------------------
// Internal class type aliases
using Limit = std::size_t;
using HSize = std::size_t;
using HValue = const std::string&;
using Message_Body = std::string;
//----------------------------------------
public:
//----------------------------------------
// Default constructor
//----------------------------------------
explicit Message() = default;
//----------------------------------------
// Constructor to specify the limit of how many
// fields that can be added to the message
//
// @param limit - Capacity of how many fields can
// be added to the message
//----------------------------------------
explicit Message(const Limit limit) noexcept;
//----------------------------------------
// Default destructor
//----------------------------------------
virtual ~Message() noexcept = default;
//----------------------------------------
// Set a field limit for this message
//
// @param limit - The limit to set
//
// @return - The object that invoked this
// method
//----------------------------------------
Message& set_header_limit(const Limit limit) noexcept;
//----------------------------------------
// Get the current field limit for this
// message
//
// @return - The current field limit
//----------------------------------------
Limit get_header_limit() const noexcept;
//----------------------------------------
// Add a new field to the current set of
// headers
//
// @tparam (std::string) field - The field name
// @tparam (std::string) value - The field value
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Field, typename Value>
Message& add_header(Field&& field, Value&& value);
//----------------------------------------
// Add a set of fields to the message from
// a <std::string> object in the following
// format:
//
// "name: value\r\n"
//
// @tparam (std::string) data - The set of fields
// to add to this
// message
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Data>
Message& add_headers(Data&& data);
//----------------------------------------
// Change the value of the specified field
//
// If the field is absent from the message it
// will be added with the associated value
//
// @tparam (std::string) field - The field name
// @tparam (std::string) value - The field value
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Field, typename Value>
Message& set_header(Field&& field, Value&& value);
//----------------------------------------
// Get the value associated with the
// specified field name
//
// Should call <has_header> before
// calling this
//
// @tparam (std::string) field - The field name to
// get associated value
//
// @return - The value associated with the
// specified field name
//----------------------------------------
template <typename Field>
HValue get_header_value(Field&& field) const noexcept;
//----------------------------------------
// Check if the specified field is within
// this message
//
// @tparam (std::string) field - The field name to
// search for
//
// @return - true is present, false otherwise
//----------------------------------------
template <typename Field>
bool has_header(Field&& field) const noexcept;
//----------------------------------------
// Remove the specified field from this
// message
//
// @tparam (std::string) field - The header field to
// remove from this message
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Field>
Message& erase_header(Field&& field) noexcept;
//----------------------------------------
// Remove all header fields from this
// message
//
// @return - The object that invoked this method
//----------------------------------------
Message& clear_headers() noexcept;
//----------------------------------------
// Check if there are no fields in this
// message
//
// @return - true if the message has no
// fields, false otherwise
//----------------------------------------
bool is_header_empty() const noexcept;
//----------------------------------------
// Get the number of fields in this
// message
//
// @return - The number of fields in this
// message
//----------------------------------------
HSize header_size() const noexcept;
//----------------------------------------
// Add an entity to the message
//
// @tparam (std::string) message_body - The entity to be
// sent with the
// message
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Entity>
Message& add_body(Entity&& message_body);
//----------------------------------------
// Get the entity in this the message
//
// @return - The entity in this message
//----------------------------------------
const Message_Body& get_body() const noexcept;
//----------------------------------------
// Remove the entity from the message
//
// @return - The object that invoked this method
//----------------------------------------
Message& clear_body() noexcept;
//----------------------------------------
// Reset the message as if it was now
// default constructed
//
// @return - The object that invoked this method
//----------------------------------------
Message& reset() noexcept;
//-----------------------------------
// Get a string representation of this
// class
//
// @return - A string representation
//-----------------------------------
std::string to_string() const;
//-----------------------------------
// Operator to transform this class
// into string form
//-----------------------------------
operator std::string () const;
//-----------------------------------
private:
//------------------------------
// Class data members
//------------------------------
Header header_fields_;
Message_Body message_body_;
//-----------------------------------
// Deleted move and copy operations
//-----------------------------------
Message(const Message&) = delete;
Message(Message&&) = delete;
//-----------------------------------
// Deleted move and copy assignment operations
//-----------------------------------
Message& operator = (const Message&) = delete;
Message& operator = (Message&&) = delete;
}; //< class Message
inline Message::Message(const Limit limit) noexcept:
header_fields_{limit},
message_body_{}
{}
inline Message& Message::set_header_limit(const Limit limit) noexcept {
header_fields_.set_limit(limit);
return *this;
}
inline Message::Limit Message::get_header_limit() const noexcept {
return header_fields_.get_limit();
}
template <typename Field, typename Value>
inline Message& Message::add_header(Field&& field, Value&& value) {
header_fields_.add_field(std::forward<Field>(field), std::forward<Value>(value));
return *this;
}
template <typename Data>
inline Message& Message::add_headers(Data&& data) {
header_fields_.add_fields(std::forward<Data>(data));
return *this;
}
template <typename Field, typename Value>
inline Message& Message::set_header(Field&& field, Value&& value) {
header_fields_.set_field(std::forward<Field>(field), std::forward<Value>(value));
return *this;
}
template <typename Field>
inline Message::HValue Message::get_header_value(Field&& field) const noexcept {
return header_fields_.get_value(std::forward<Field>(field));
}
template <typename Field>
inline bool Message::has_header(Field&& field) const noexcept {
return header_fields_.has_field(std::forward<Field>(field));
}
template <typename Field>
inline Message& Message::erase_header(Field&& field) noexcept {
header_fields_.erase(std::forward<Field>(field));
return *this;
}
inline Message& Message::clear_headers() noexcept {
header_fields_.clear();
return *this;
}
inline bool Message::is_header_empty() const noexcept {
return header_fields_.is_empty();
}
inline Message::HSize Message::header_size() const noexcept {
return header_fields_.size();
}
template<typename Entity>
inline Message& Message::add_body(Entity&& message_body) {
if (message_body.empty()) return *this;
//-----------------------------------
message_body_ = std::forward<Entity>(message_body);
//-----------------------------------
return add_header(header_fields::Entity::Content_Length,
std::to_string(message_body_.size()));
}
const Message::Message_Body& Message::get_body() const noexcept {
return message_body_;
}
inline Message& Message::clear_body() noexcept {
message_body_.clear();
return erase_header(header_fields::Entity::Content_Length);
}
inline Message& Message::reset() noexcept {
return clear_headers().clear_body();
}
inline std::string Message::to_string() const {
return *this;
}
inline Message::operator std::string () const {
std::ostringstream message;
//-----------------------------------
message << header_fields_
<< message_body_;
//-----------------------------------
return message.str();
}
std::ostream& operator << (std::ostream& output_device, const Message& message) {
return output_device << message.to_string();
}
} //< namespace http
#endif //< HTTP_MESSAGE_HPP<commit_msg>Added missing include<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#ifndef HTTP_MESSAGE_HPP
#define HTTP_MESSAGE_HPP
#include <sstream>
#include "header.hpp"
namespace http {
class Message {
private:
//----------------------------------------
// Internal class type aliases
using Limit = std::size_t;
using HSize = std::size_t;
using HValue = const std::string&;
using Message_Body = std::string;
//----------------------------------------
public:
//----------------------------------------
// Default constructor
//----------------------------------------
explicit Message() = default;
//----------------------------------------
// Constructor to specify the limit of how many
// fields that can be added to the message
//
// @param limit - Capacity of how many fields can
// be added to the message
//----------------------------------------
explicit Message(const Limit limit) noexcept;
//----------------------------------------
// Default destructor
//----------------------------------------
virtual ~Message() noexcept = default;
//----------------------------------------
// Set a field limit for this message
//
// @param limit - The limit to set
//
// @return - The object that invoked this
// method
//----------------------------------------
Message& set_header_limit(const Limit limit) noexcept;
//----------------------------------------
// Get the current field limit for this
// message
//
// @return - The current field limit
//----------------------------------------
Limit get_header_limit() const noexcept;
//----------------------------------------
// Add a new field to the current set of
// headers
//
// @tparam (std::string) field - The field name
// @tparam (std::string) value - The field value
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Field, typename Value>
Message& add_header(Field&& field, Value&& value);
//----------------------------------------
// Add a set of fields to the message from
// a <std::string> object in the following
// format:
//
// "name: value\r\n"
//
// @tparam (std::string) data - The set of fields
// to add to this
// message
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Data>
Message& add_headers(Data&& data);
//----------------------------------------
// Change the value of the specified field
//
// If the field is absent from the message it
// will be added with the associated value
//
// @tparam (std::string) field - The field name
// @tparam (std::string) value - The field value
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Field, typename Value>
Message& set_header(Field&& field, Value&& value);
//----------------------------------------
// Get the value associated with the
// specified field name
//
// Should call <has_header> before
// calling this
//
// @tparam (std::string) field - The field name to
// get associated value
//
// @return - The value associated with the
// specified field name
//----------------------------------------
template <typename Field>
HValue get_header_value(Field&& field) const noexcept;
//----------------------------------------
// Check if the specified field is within
// this message
//
// @tparam (std::string) field - The field name to
// search for
//
// @return - true is present, false otherwise
//----------------------------------------
template <typename Field>
bool has_header(Field&& field) const noexcept;
//----------------------------------------
// Remove the specified field from this
// message
//
// @tparam (std::string) field - The header field to
// remove from this message
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Field>
Message& erase_header(Field&& field) noexcept;
//----------------------------------------
// Remove all header fields from this
// message
//
// @return - The object that invoked this method
//----------------------------------------
Message& clear_headers() noexcept;
//----------------------------------------
// Check if there are no fields in this
// message
//
// @return - true if the message has no
// fields, false otherwise
//----------------------------------------
bool is_header_empty() const noexcept;
//----------------------------------------
// Get the number of fields in this
// message
//
// @return - The number of fields in this
// message
//----------------------------------------
HSize header_size() const noexcept;
//----------------------------------------
// Add an entity to the message
//
// @tparam (std::string) message_body - The entity to be
// sent with the
// message
//
// @return - The object that invoked this method
//----------------------------------------
template <typename Entity>
Message& add_body(Entity&& message_body);
//----------------------------------------
// Get the entity in this the message
//
// @return - The entity in this message
//----------------------------------------
const Message_Body& get_body() const noexcept;
//----------------------------------------
// Remove the entity from the message
//
// @return - The object that invoked this method
//----------------------------------------
Message& clear_body() noexcept;
//----------------------------------------
// Reset the message as if it was now
// default constructed
//
// @return - The object that invoked this method
//----------------------------------------
Message& reset() noexcept;
//-----------------------------------
// Get a string representation of this
// class
//
// @return - A string representation
//-----------------------------------
std::string to_string() const;
//-----------------------------------
// Operator to transform this class
// into string form
//-----------------------------------
operator std::string () const;
//-----------------------------------
private:
//------------------------------
// Class data members
//------------------------------
Header header_fields_;
Message_Body message_body_;
//-----------------------------------
// Deleted move and copy operations
//-----------------------------------
Message(const Message&) = delete;
Message(Message&&) = delete;
//-----------------------------------
// Deleted move and copy assignment operations
//-----------------------------------
Message& operator = (const Message&) = delete;
Message& operator = (Message&&) = delete;
}; //< class Message
inline Message::Message(const Limit limit) noexcept:
header_fields_{limit},
message_body_{}
{}
inline Message& Message::set_header_limit(const Limit limit) noexcept {
header_fields_.set_limit(limit);
return *this;
}
inline Message::Limit Message::get_header_limit() const noexcept {
return header_fields_.get_limit();
}
template <typename Field, typename Value>
inline Message& Message::add_header(Field&& field, Value&& value) {
header_fields_.add_field(std::forward<Field>(field), std::forward<Value>(value));
return *this;
}
template <typename Data>
inline Message& Message::add_headers(Data&& data) {
header_fields_.add_fields(std::forward<Data>(data));
return *this;
}
template <typename Field, typename Value>
inline Message& Message::set_header(Field&& field, Value&& value) {
header_fields_.set_field(std::forward<Field>(field), std::forward<Value>(value));
return *this;
}
template <typename Field>
inline Message::HValue Message::get_header_value(Field&& field) const noexcept {
return header_fields_.get_value(std::forward<Field>(field));
}
template <typename Field>
inline bool Message::has_header(Field&& field) const noexcept {
return header_fields_.has_field(std::forward<Field>(field));
}
template <typename Field>
inline Message& Message::erase_header(Field&& field) noexcept {
header_fields_.erase(std::forward<Field>(field));
return *this;
}
inline Message& Message::clear_headers() noexcept {
header_fields_.clear();
return *this;
}
inline bool Message::is_header_empty() const noexcept {
return header_fields_.is_empty();
}
inline Message::HSize Message::header_size() const noexcept {
return header_fields_.size();
}
template<typename Entity>
inline Message& Message::add_body(Entity&& message_body) {
if (message_body.empty()) return *this;
//-----------------------------------
message_body_ = std::forward<Entity>(message_body);
//-----------------------------------
return add_header(header_fields::Entity::Content_Length,
std::to_string(message_body_.size()));
}
const Message::Message_Body& Message::get_body() const noexcept {
return message_body_;
}
inline Message& Message::clear_body() noexcept {
message_body_.clear();
return erase_header(header_fields::Entity::Content_Length);
}
inline Message& Message::reset() noexcept {
return clear_headers().clear_body();
}
inline std::string Message::to_string() const {
return *this;
}
inline Message::operator std::string () const {
std::ostringstream message;
//-----------------------------------
message << header_fields_
<< message_body_;
//-----------------------------------
return message.str();
}
std::ostream& operator << (std::ostream& output_device, const Message& message) {
return output_device << message.to_string();
}
} //< namespace http
#endif //< HTTP_MESSAGE_HPP<|endoftext|> |
<commit_before>// Copyright (c) 2018 Michael C. Heiber
// This source file is part of the Excimontec project, which is subject to the MIT License.
// For more information, see the LICENSE file that accompanies this software.
// The Excimontec project can be found on Github at https://github.com/MikeHeiber/Excimontec
#include "gtest/gtest.h"
#include "KMC_Lattice/Utils.h"
#include <mpi.h>
using namespace std;
using namespace Utils;
namespace MPI_Tests {
class MPI_Test : public ::testing::Test {
protected:
int procid;
int nproc;
void SetUp() {
MPI_Comm_size(MPI_COMM_WORLD, &nproc);
MPI_Comm_rank(MPI_COMM_WORLD, &procid);
}
};
TEST_F(MPI_Test, CalculateVectorAvgTests) {
// Seteup unique data vectors on each proc
vector<double> data(3);
for (int i = 0; i < (int)data.size(); i++) {
data[i] = 3 * procid + i;
}
vector<double> data_avg = MPI_calculateVectorAvg(data);
if (procid == 0) {
EXPECT_EQ(3, (int)data_avg.size());
EXPECT_EQ(4.5, data_avg[0]);
EXPECT_EQ(5.5, data_avg[1]);
EXPECT_EQ(6.5, data_avg[2]);
}
}
}
int main(int argc, char **argv) {
int result = 0;
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
<commit_msg>Testing Update<commit_after>// Copyright (c) 2018 Michael C. Heiber
// This source file is part of the Excimontec project, which is subject to the MIT License.
// For more information, see the LICENSE file that accompanies this software.
// The Excimontec project can be found on Github at https://github.com/MikeHeiber/Excimontec
#include "gtest/gtest.h"
#include "KMC_Lattice/Utils.h"
#include <mpi.h>
using namespace std;
using namespace Utils;
namespace MPI_Tests {
class MPI_Test : public ::testing::Test {
protected:
int procid;
int nproc;
void SetUp() {
MPI_Comm_size(MPI_COMM_WORLD, &nproc);
MPI_Comm_rank(MPI_COMM_WORLD, &procid);
}
};
TEST_F(MPI_Test, CalculateVectorAvgTests) {
// Seteup unique data vectors on each proc
vector<double> data(3);
for (int i = 0; i < (int)data.size(); i++) {
data[i] = 3 * procid + i;
}
vector<double> data_avg = MPI_calculateVectorAvg(data);
if (procid == 0) {
EXPECT_EQ(3, (int)data_avg.size());
EXPECT_DOUBLE_EQ(4.5, data_avg[0]);
EXPECT_DOUBLE_EQ(5.5, data_avg[1]);
EXPECT_DOUBLE_EQ(6.5, data_avg[2]);
}
}
TEST_F(MPI_Test, CalculateVectorSumTests) {
// Seteup unique data vectors on each proc
vector<double> data(3);
for (int i = 0; i < (int)data.size(); i++) {
data[i] = 3 * procid + i;
}
vector<double> data_sum = MPI_calculateVectorSum(data);
if (procid == 0) {
EXPECT_EQ(3, (int)data_sum.size());
EXPECT_DOUBLE_EQ(18.0, data_sum[0]);
EXPECT_DOUBLE_EQ(22.0, data_sum[1]);
EXPECT_DOUBLE_EQ(26.0, data_sum[2]);
}
vector<int> data2(3);
for (int i = 0; i < (int)data2.size(); i++) {
data2[i] = 3 * procid + i;
}
vector<int> data_sum2 = MPI_calculateVectorSum(data2);
if (procid == 0) {
EXPECT_EQ(3, (int)data_sum2.size());
EXPECT_EQ(18, data_sum2[0]);
EXPECT_EQ(22, data_sum2[1]);
EXPECT_EQ(26, data_sum2[2]);
}
}
TEST_F(MPI_Test, GatherVectorsTests) {
// Seteup unique data vectors on each proc
vector<double> data(3);
for (int i = 0; i < (int)data.size(); i++) {
data[i] = 3 * procid + i;
}
vector<double> data_all = MPI_gatherVectors(data);
if (procid == 0) {
EXPECT_EQ(12, (int)data_all.size());
for (int i = 0; i < 3 * nproc; i++) {
EXPECT_DOUBLE_EQ((double)i, data_all[i]);
}
}
vector<int> data2(3);
for (int i = 0; i < (int)data2.size(); i++) {
data2[i] = 3 * procid + i;
}
vector<int> data_all2 = MPI_gatherVectors(data2);
if (procid == 0) {
EXPECT_EQ(12, (int)data_all2.size());
for (int i = 0; i < 3 * nproc; i++) {
EXPECT_EQ(i, data_all2[i]);
}
}
}
}
int main(int argc, char **argv) {
int result = 0;
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
<|endoftext|> |
<commit_before>/*
kopetexsl.cpp - Kopete XSL Routines
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxml/parser.h>
#include <kdebug.h>
#include <kopetexsl.h>
#include <qregexp.h>
#include <qsignal.h>
//#define XSL_DEBUG 1
extern int xmlLoadExtDtdDefaultValue;
const QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString )
{
KopeteXSLThread mThread( xmlString, xslString );
mThread.start();
mThread.wait();
return mThread.result();
}
void KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString,
QObject *target, const char* slotCompleted )
{
KopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString, target, slotCompleted );
mThread->start();
}
bool KopeteXSL::isValid( const QString &xslString )
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xslDoc = NULL;
bool retVal = false;
// Convert QString into a C string
QCString xslCString = xslString.utf8();
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
retVal = true;
xsltFreeStylesheet(style_sheet);
}
else
{
xmlFreeDoc(xslDoc);
}
}
return retVal;
}
KopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted )
{
m_xml = xmlString;
m_xsl = xslString;
m_target = target;
m_slotCompleted = slotCompleted;
}
void KopeteXSLThread::run()
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xmlDoc, xslDoc, resultDoc;
//Init Stuff
xmlLoadExtDtdDefaultValue = 0;
xmlSubstituteEntitiesDefault(1);
// Convert QString into a C string
QCString xmlCString = m_xml.utf8();
QCString xslCString = m_xsl.utf8();
// Read XML docs in from memory
xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xmlDoc != NULL )
{
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
resultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL);
if( resultDoc != NULL )
{
//Save the result into the QString
xmlChar *mem;
int size;
xmlDocDumpMemory( resultDoc, &mem, &size );
m_resultString = QString::fromUtf8( QCString( (char*)mem, size + 1 ) );
delete mem;
xmlFreeDoc(resultDoc);
}
else
{
kdDebug() << "Transformed document is null!!!" << endl;
}
xsltFreeStylesheet(style_sheet);
}
else
{
kdDebug() << "Document is not valid XSL!!!" << endl;
xmlFreeDoc(xslDoc);
}
}
else
{
kdDebug() << "XSL Document could not be parsed!!!" << endl;
}
xmlFreeDoc(xmlDoc);
}
else
{
kdDebug() << "XML Document could not be parsed!!!" << endl;
}
//Signal completion
if( m_target && m_slotCompleted )
{
QSignal completeSignal( m_target );
completeSignal.connect( m_target, m_slotCompleted );
completeSignal.setValue( m_resultString );
completeSignal.activate();
delete this;
}
}
QString KopeteXSL::unescape( const QString &xml )
{
QString data = xml;
data.replace( QRegExp( QString::fromLatin1( "\"\"" ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( ">" ) ), QString::fromLatin1( ">" ) );
data.replace( QRegExp( QString::fromLatin1( "<" ) ), QString::fromLatin1( "<" ) );
data.replace( QRegExp( QString::fromLatin1( """ ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( "&" ) ), QString::fromLatin1( "&" ) );
return data;
}
<commit_msg>compile<commit_after>/*
kopetexsl.cpp - Kopete XSL Routines
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include <libxslt/xsltconfig.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxml/parser.h>
#include <kdebug.h>
#include <kopetexsl.h>
#include <qregexp.h>
#include <qsignal.h>
//#define XSL_DEBUG 1
extern int xmlLoadExtDtdDefaultValue;
const QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString )
{
KopeteXSLThread mThread( xmlString, xslString );
mThread.start();
mThread.wait();
return mThread.result();
}
void KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString,
QObject *target, const char* slotCompleted )
{
KopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString, target, slotCompleted );
mThread->start();
}
bool KopeteXSL::isValid( const QString &xslString )
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xslDoc = NULL;
bool retVal = false;
// Convert QString into a C string
QCString xslCString = xslString.utf8();
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
retVal = true;
xsltFreeStylesheet(style_sheet);
}
else
{
xmlFreeDoc(xslDoc);
}
}
return retVal;
}
KopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted )
{
m_xml = xmlString;
m_xsl = xslString;
m_target = target;
m_slotCompleted = slotCompleted;
}
void KopeteXSLThread::run()
{
xsltStylesheetPtr style_sheet = NULL;
xmlDocPtr xmlDoc, xslDoc, resultDoc;
//Init Stuff
xmlLoadExtDtdDefaultValue = 0;
xmlSubstituteEntitiesDefault(1);
// Convert QString into a C string
QCString xmlCString = m_xml.utf8();
QCString xslCString = m_xsl.utf8();
// Read XML docs in from memory
xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );
xslDoc = xmlParseMemory( xslCString, xslCString.length() );
if( xmlDoc != NULL )
{
if( xslDoc != NULL )
{
style_sheet = xsltParseStylesheetDoc( xslDoc );
if( style_sheet != NULL )
{
resultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL);
if( resultDoc != NULL )
{
//Save the result into the QString
xmlChar *mem;
int size;
xmlDocDumpMemory( resultDoc, &mem, &size );
m_resultString = QString::fromUtf8( QCString( (char*)mem, size + 1 ) );
delete mem;
xmlFreeDoc(resultDoc);
}
else
{
kdDebug() << "Transformed document is null!!!" << endl;
}
xsltFreeStylesheet(style_sheet);
}
else
{
kdDebug() << "Document is not valid XSL!!!" << endl;
xmlFreeDoc(xslDoc);
}
}
else
{
kdDebug() << "XSL Document could not be parsed!!!" << endl;
}
xmlFreeDoc(xmlDoc);
}
else
{
kdDebug() << "XML Document could not be parsed!!!" << endl;
}
//Signal completion
if( m_target && m_slotCompleted )
{
QSignal completeSignal( m_target );
completeSignal.connect( m_target, m_slotCompleted );
completeSignal.setValue( m_resultString );
completeSignal.activate();
delete this;
}
}
QString KopeteXSL::unescape( const QString &xml )
{
QString data = xml;
data.replace( QRegExp( QString::fromLatin1( "\"\"" ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( ">" ) ), QString::fromLatin1( ">" ) );
data.replace( QRegExp( QString::fromLatin1( "<" ) ), QString::fromLatin1( "<" ) );
data.replace( QRegExp( QString::fromLatin1( """ ) ), QString::fromLatin1( "\"" ) );
data.replace( QRegExp( QString::fromLatin1( "&" ) ), QString::fromLatin1( "&" ) );
return data;
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "base/rect.h"
TEST_CASE("rect-test", "[rect]")
{
// rect at x,y w,h
/*
(1,6) (4,6)
-----------
| |
| | h=4
| w=3 |
-----------
(1,2) (4, 2)
*/
auto r = recti{1, 2, 3, 4};
CHECK(r.x == 1);
CHECK(r.y == 2);
CHECK(r.width == 3);
CHECK(r.height == 4);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
///////////////////////////////////////////////////////////////////////////
// set_foobar(...)
SECTION("set top")
{
r.set_top(42);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 42);
}
SECTION("set left")
{
r.set_left(-42);
CHECK(r.get_left() == -42);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("set right")
{
r.set_right(42);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 42);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("set bottom")
{
r.set_bottom(-42);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == -42);
CHECK(r.get_top() == 6);
}
///////////////////////////////////////////////////////////////////////////
// cut
SECTION("cut left")
{
const auto cut = r.cut_left(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 2);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 2);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("cut right")
{
const auto cut = r.cut_right(1);
CHECK(cut.get_left() == 3);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 3);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("cut top")
{
const auto cut = r.cut_top(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 5);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 5);
}
SECTION("cut bottom")
{
const auto cut = r.cut_bottom(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 3);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 3);
CHECK(r.get_top() == 6);
}
///////////////////////////////////////////////////////////////////////////
// get_cut
SECTION("get cut left")
{
const auto cut = r.get_cut_left(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 2);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("get cut right")
{
const auto cut = r.get_cut_right(1);
CHECK(cut.get_left() == 3);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("get cut top")
{
const auto cut = r.get_cut_top(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 5);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("get cut bottom")
{
const auto cut = r.get_cut_bottom(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 3);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
///////////////////////////////////////////////////////////////////////////
// get_offset
///////////////////////////////////////////////////////////////////////////
// get_inset
SECTION("inset 1")
{
const auto rr = r.get_inset(1);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
CHECK(rr.get_left() == 2);
CHECK(rr.get_right() == 3);
CHECK(rr.get_bottom() == 3);
CHECK(rr.get_top() == 5);
}
SECTION("inset -1")
{
const auto rr = r.get_inset(-1);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
CHECK(rr.get_left() == 0);
CHECK(rr.get_right() == 5);
CHECK(rr.get_bottom() == 1);
CHECK(rr.get_top() == 7);
}
}
<commit_msg>test: rect test completed<commit_after>#include "catch.hpp"
#include "base/rect.h"
TEST_CASE("rect-test", "[rect]")
{
// rect at x,y w,h
/*
(1,6) (4,6)
-----------
| |
| | h=4
| w=3 |
-----------
(1,2) (4, 2)
*/
auto r = recti{1, 2, 3, 4};
CHECK(r.x == 1);
CHECK(r.y == 2);
CHECK(r.width == 3);
CHECK(r.height == 4);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
///////////////////////////////////////////////////////////////////////////
// set_foobar(...)
SECTION("set top")
{
r.set_top(42);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 42);
}
SECTION("set left")
{
r.set_left(-42);
CHECK(r.get_left() == -42);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("set right")
{
r.set_right(42);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 42);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("set bottom")
{
r.set_bottom(-42);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == -42);
CHECK(r.get_top() == 6);
}
///////////////////////////////////////////////////////////////////////////
// cut
SECTION("cut left")
{
const auto cut = r.cut_left(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 2);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 2);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("cut right")
{
const auto cut = r.cut_right(1);
CHECK(cut.get_left() == 3);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 3);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("cut top")
{
const auto cut = r.cut_top(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 5);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 5);
}
SECTION("cut bottom")
{
const auto cut = r.cut_bottom(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 3);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 3);
CHECK(r.get_top() == 6);
}
///////////////////////////////////////////////////////////////////////////
// get_cut
SECTION("get cut left")
{
const auto cut = r.get_cut_left(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 2);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("get cut right")
{
const auto cut = r.get_cut_right(1);
CHECK(cut.get_left() == 3);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("get cut top")
{
const auto cut = r.get_cut_top(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 5);
CHECK(cut.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("get cut bottom")
{
const auto cut = r.get_cut_bottom(1);
CHECK(cut.get_left() == 1);
CHECK(cut.get_right() == 4);
CHECK(cut.get_bottom() == 2);
CHECK(cut.get_top() == 3);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
///////////////////////////////////////////////////////////////////////////
// get_offset
SECTION("get offset (0,0)")
{
const auto off = r.get_offset({0, 0});
CHECK(off.get_left() == 1);
CHECK(off.get_right() == 4);
CHECK(off.get_bottom() == 2);
CHECK(off.get_top() == 6);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
SECTION("get offset (...)")
{
const auto off = r.get_offset({1, 2});
CHECK(off.get_left() == 2);
CHECK(off.get_right() == 5);
CHECK(off.get_bottom() == 4);
CHECK(off.get_top() == 8);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
}
///////////////////////////////////////////////////////////////////////////
// get_inset
SECTION("inset 1")
{
const auto rr = r.get_inset(1);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
CHECK(rr.get_left() == 2);
CHECK(rr.get_right() == 3);
CHECK(rr.get_bottom() == 3);
CHECK(rr.get_top() == 5);
}
SECTION("inset -1")
{
const auto rr = r.get_inset(-1);
CHECK(r.get_left() == 1);
CHECK(r.get_right() == 4);
CHECK(r.get_bottom() == 2);
CHECK(r.get_top() == 6);
CHECK(rr.get_left() == 0);
CHECK(rr.get_right() == 5);
CHECK(rr.get_bottom() == 1);
CHECK(rr.get_top() == 7);
}
}
<|endoftext|> |
<commit_before>//
// Created by Rui Wang on 16-4-30.
//
#include "gtest/gtest.h"
#include "harness.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <iostream>
#include <ctime>
#include <cassert>
#include <backend/planner/hybrid_scan_plan.h>
#include <backend/executor/hybrid_scan_executor.h>
#include "backend/catalog/manager.h"
#include "backend/catalog/schema.h"
#include "backend/concurrency/transaction.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "backend/common/timer.h"
#include "backend/executor/abstract_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/index/index_factory.h"
#include "backend/planner/insert_plan.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/data_table.h"
#include "backend/storage/table_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/constant_value_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/conjunction_expression.h"
#include "backend/index/index_factory.h"
namespace peloton {
namespace test {
class HybridIndexTests : public PelotonTest {};
static double projectivity = 1.0;
static int columncount = 4;
static size_t tuples_per_tile_group = 10;
static size_t tile_group = 10;
void CreateTable(std::unique_ptr<storage::DataTable>& hyadapt_table, bool indexes) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const bool is_inlined = true;
// Create schema first
std::vector<catalog::Column> columns;
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto column =
catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"" + std::to_string(col_itr), is_inlined);
columns.push_back(column);
}
catalog::Schema *table_schema = new catalog::Schema(columns);
std::string table_name("HYADAPTTABLE");
/////////////////////////////////////////////////////////
// Create table.
/////////////////////////////////////////////////////////
bool own_schema = true;
bool adapt_table = true;
hyadapt_table.reset(storage::TableFactory::GetDataTable(
INVALID_OID, INVALID_OID, table_schema, table_name,
tuples_per_tile_group, own_schema, adapt_table));
// PRIMARY INDEX
if (indexes == true) {
std::vector<oid_t> key_attrs;
auto tuple_schema = hyadapt_table->GetSchema();
catalog::Schema *key_schema;
index::IndexMetadata *index_metadata;
bool unique;
key_attrs = {0};
key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs);
key_schema->SetIndexedColumns(key_attrs);
unique = true;
index_metadata = new index::IndexMetadata(
"primary_index", 123, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique);
index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata);
hyadapt_table->AddIndex(pkey_index);
}
}
void LoadTable(std::unique_ptr<storage::DataTable>& hyadapt_table) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const int tuple_count = tile_group * tuples_per_tile_group;
auto table_schema = hyadapt_table->GetSchema();
/////////////////////////////////////////////////////////
// Load in the data
/////////////////////////////////////////////////////////
// Insert tuples into tile_group.
//auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
const bool allocate = true;
//auto txn = txn_manager.BeginTransaction();
std::unique_ptr<VarlenPool> pool(new VarlenPool(BACKEND_TYPE_MM));
int rowid;
for (rowid = 0; rowid < tuple_count; rowid++) {
int populate_value = rowid;
storage::Tuple tuple(table_schema, allocate);
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto value = ValueFactory::GetIntegerValue(populate_value);
tuple.SetValue(col_itr, value, pool.get());
}
ItemPointer tuple_slot_id = hyadapt_table->InsertTuple(&tuple);
assert(tuple_slot_id.block != INVALID_OID);
assert(tuple_slot_id.offset != INVALID_OID);
//txn->RecordInsert(tuple_slot_id);
}
//txn_manager.CommitTransaction();
}
expression::AbstractExpression *CreatePredicate(const int lower_bound) {
// ATTR0 >= LOWER_BOUND
// First, create tuple value expression.
expression::AbstractExpression *tuple_value_expr =
expression::ExpressionUtil::TupleValueFactory(0, 0);
// Second, create constant value expression.
Value constant_value = ValueFactory::GetIntegerValue(lower_bound);
expression::AbstractExpression *constant_value_expr =
expression::ExpressionUtil::ConstantValueFactory(constant_value);
// Finally, link them together using an greater than expression.
expression::AbstractExpression *predicate =
expression::ExpressionUtil::ComparisonFactory(
EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, tuple_value_expr,
constant_value_expr);
return predicate;
}
void GenerateSequence(std::vector<oid_t>& hyadapt_column_ids, oid_t column_count) {
// Reset sequence
hyadapt_column_ids.clear();
// Generate sequence
for (oid_t column_id = 1; column_id <= column_count; column_id++)
hyadapt_column_ids.push_back(column_id);
std::random_shuffle(hyadapt_column_ids.begin(), hyadapt_column_ids.end());
}
void ExecuteTest(executor::AbstractExecutor *executor, size_t tiple_group_counts) {
Timer<> timer;
size_t tuple_counts = 0;
timer.Start();
bool status = false;
status = executor->Init();
if (status == false) throw Exception("Init failed");
std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;
while (executor->Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_tile(
executor->GetOutput());
tuple_counts += result_tile->GetTupleCount();
result_tiles.emplace_back(result_tile.release());
tiple_group_counts--;
}
// Execute stuff
executor->Execute();
timer.Stop();
double time_per_transaction = timer.GetDuration();
LOG_INFO("%f", time_per_transaction);
EXPECT_EQ(tiple_group_counts, 0);
EXPECT_EQ(tuple_counts, tile_group * tuples_per_tile_group);
}
TEST_F(HybridIndexTests, SeqScanTest) {
std::unique_ptr<storage::DataTable> hyadapt_table;
CreateTable(hyadapt_table, false);
//LoadTable(hyadapt_table);
LOG_INFO("%s", hyadapt_table->GetInfo().c_str());
const int lower_bound = 30;
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
/////////////////////////////////////////////////////////
// SEQ SCAN + PREDICATE
/////////////////////////////////////////////////////////
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Column ids to be added to logical tile after scan.
std::vector<oid_t> column_ids;
// oid_t column_count = state.projectivity * state.column_count;
oid_t column_count = projectivity * columncount;
std::vector<oid_t> hyadapt_column_ids;
GenerateSequence(hyadapt_column_ids, column_count);
for (oid_t col_itr = 0; col_itr < column_count; col_itr++) {
column_ids.push_back(hyadapt_column_ids[col_itr]);
}
// Create and set up seq scan executor
auto predicate = nullptr; // CreatePredicate(lower_bound);
planner::HybridScanPlan hybrid_scan_node(hyadapt_table.get(), predicate, column_ids);
executor::HybridScanExecutor Hybrid_scan_executor(&hybrid_scan_node, context.get());
ExecuteTest(&Hybrid_scan_executor, hyadapt_table->hyGetTileGroupCount());
txn_manager.CommitTransaction();
}
} // namespace tet
} // namespace peloton
<commit_msg>update<commit_after>//
// Created by Rui Wang on 16-4-30.
//
#include "gtest/gtest.h"
#include "harness.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <iostream>
#include <ctime>
#include <cassert>
#include <backend/planner/hybrid_scan_plan.h>
#include <backend/executor/hybrid_scan_executor.h>
#include "backend/catalog/manager.h"
#include "backend/catalog/schema.h"
#include "backend/concurrency/transaction.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "backend/common/timer.h"
#include "backend/executor/abstract_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/index/index_factory.h"
#include "backend/planner/insert_plan.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/data_table.h"
#include "backend/storage/table_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/constant_value_expression.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/conjunction_expression.h"
#include "backend/index/index_factory.h"
namespace peloton {
namespace test {
class HybridIndexTests : public PelotonTest {};
static double projectivity = 1.0;
static int columncount = 4;
static size_t tuples_per_tile_group = 10;
static size_t tile_group = 10;
void CreateTable(std::unique_ptr<storage::DataTable>& hyadapt_table, bool indexes) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const bool is_inlined = true;
// Create schema first
std::vector<catalog::Column> columns;
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto column =
catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
"" + std::to_string(col_itr), is_inlined);
columns.push_back(column);
}
catalog::Schema *table_schema = new catalog::Schema(columns);
std::string table_name("HYADAPTTABLE");
/////////////////////////////////////////////////////////
// Create table.
/////////////////////////////////////////////////////////
bool own_schema = true;
bool adapt_table = true;
hyadapt_table.reset(storage::TableFactory::GetDataTable(
INVALID_OID, INVALID_OID, table_schema, table_name,
tuples_per_tile_group, own_schema, adapt_table));
// PRIMARY INDEX
if (indexes == true) {
std::vector<oid_t> key_attrs;
auto tuple_schema = hyadapt_table->GetSchema();
catalog::Schema *key_schema;
index::IndexMetadata *index_metadata;
bool unique;
key_attrs = {0};
key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs);
key_schema->SetIndexedColumns(key_attrs);
unique = true;
index_metadata = new index::IndexMetadata(
"primary_index", 123, INDEX_TYPE_BTREE,
INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique);
index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata);
hyadapt_table->AddIndex(pkey_index);
}
}
void LoadTable(std::unique_ptr<storage::DataTable>& hyadapt_table) {
oid_t column_count = projectivity * columncount;
const oid_t col_count = column_count + 1;
const int tuple_count = tile_group * tuples_per_tile_group;
auto table_schema = hyadapt_table->GetSchema();
/////////////////////////////////////////////////////////
// Load in the data
/////////////////////////////////////////////////////////
// Insert tuples into tile_group.
//auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
const bool allocate = true;
//auto txn = txn_manager.BeginTransaction();
std::unique_ptr<VarlenPool> pool(new VarlenPool(BACKEND_TYPE_MM));
int rowid;
for (rowid = 0; rowid < tuple_count; rowid++) {
int populate_value = rowid;
storage::Tuple tuple(table_schema, allocate);
for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
auto value = ValueFactory::GetIntegerValue(populate_value);
tuple.SetValue(col_itr, value, pool.get());
}
ItemPointer tuple_slot_id = hyadapt_table->InsertTuple(&tuple);
assert(tuple_slot_id.block != INVALID_OID);
assert(tuple_slot_id.offset != INVALID_OID);
//txn->RecordInsert(tuple_slot_id);
}
//txn_manager.CommitTransaction();
}
expression::AbstractExpression *CreatePredicate(const int lower_bound) {
// ATTR0 >= LOWER_BOUND
// First, create tuple value expression.
expression::AbstractExpression *tuple_value_expr =
expression::ExpressionUtil::TupleValueFactory(0, 0);
// Second, create constant value expression.
Value constant_value = ValueFactory::GetIntegerValue(lower_bound);
expression::AbstractExpression *constant_value_expr =
expression::ExpressionUtil::ConstantValueFactory(constant_value);
// Finally, link them together using an greater than expression.
expression::AbstractExpression *predicate =
expression::ExpressionUtil::ComparisonFactory(
EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, tuple_value_expr,
constant_value_expr);
return predicate;
}
void GenerateSequence(std::vector<oid_t>& hyadapt_column_ids, oid_t column_count) {
// Reset sequence
hyadapt_column_ids.clear();
// Generate sequence
for (oid_t column_id = 0; column_id < column_count; column_id++)
hyadapt_column_ids.push_back(column_id);
// std::random_shuffle(hyadapt_column_ids.begin(), hyadapt_column_ids.end());
}
void ExecuteTest(executor::AbstractExecutor *executor, size_t tiple_group_counts) {
Timer<> timer;
size_t tuple_counts = 0;
timer.Start();
bool status = false;
status = executor->Init();
if (status == false) throw Exception("Init failed");
std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;
while (executor->Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_tile(
executor->GetOutput());
tuple_counts += result_tile->GetTupleCount();
result_tiles.emplace_back(result_tile.release());
tiple_group_counts--;
}
// Execute stuff
executor->Execute();
timer.Stop();
double time_per_transaction = timer.GetDuration();
LOG_INFO("%f", time_per_transaction);
EXPECT_EQ(tiple_group_counts, 0);
EXPECT_EQ(tuple_counts, tile_group * tuples_per_tile_group);
}
TEST_F(HybridIndexTests, SeqScanTest) {
std::unique_ptr<storage::DataTable> hyadapt_table;
CreateTable(hyadapt_table, false);
//LoadTable(hyadapt_table);
LOG_INFO("%s", hyadapt_table->GetInfo().c_str());
const int lower_bound = 30;
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
/////////////////////////////////////////////////////////
// SEQ SCAN + PREDICATE
/////////////////////////////////////////////////////////
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Column ids to be added to logical tile after scan.
std::vector<oid_t> column_ids;
// oid_t column_count = state.projectivity * state.column_count;
oid_t column_count = projectivity * columncount;
std::vector<oid_t> hyadapt_column_ids;
GenerateSequence(hyadapt_column_ids, column_count);
for (oid_t col_itr = 0; col_itr < column_count; col_itr++) {
column_ids.push_back(hyadapt_column_ids[col_itr]);
}
// Create and set up seq scan executor
auto predicate = nullptr; // CreatePredicate(lower_bound);
planner::HybridScanPlan hybrid_scan_node(hyadapt_table.get(), predicate, column_ids);
executor::HybridScanExecutor Hybrid_scan_executor(&hybrid_scan_node, context.get());
ExecuteTest(&Hybrid_scan_executor, hyadapt_table->hyGetTileGroupCount());
txn_manager.CommitTransaction();
}
} // namespace tet
} // namespace peloton
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 midnightBITS
*
* 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.
*/
#pragma once
#include <string>
#include <gui/types.hpp>
namespace gui {
struct image_ref;
struct node;
struct style_save { int __unused; };
using style_handle = style_save*;
struct point {
pixels x;
pixels y;
point() : x(0), y(0) {}
point(const pixels& x, const pixels& y) : x(x), y(y) {}
point(const point&) = default;
point& operator=(const point&) = default;
point(point&&) = default;
point& operator=(point&&) = default;
};
struct size {
pixels width;
pixels height;
size() : width(0), height(0) {}
size(const pixels& width, const pixels& height) : width(width), height(height) {}
size(const size&) = default;
size& operator=(const size&) = default;
size(size&&) = default;
size& operator=(size&&) = default;
bool empty() const
{
return !width.value() || !height.value();
}
};
inline point operator + (const point& lhs, const point& rhs) {
return{ lhs.x + rhs.x, lhs.y + rhs.y };
}
inline point operator + (const point& lhs, const size& rhs) {
return{ lhs.x + rhs.width, lhs.y + rhs.height };
}
inline size operator - (const point& lhs, const point& rhs) {
return{ std::abs((lhs.x - rhs.x).value()), std::abs((lhs.y - rhs.y).value()) };
}
struct rect {
gui::point origin;
gui::size size;
rect() = default;
rect(const gui::point& topleft, const gui::point& bottomright) : origin(topleft), size(bottomright - topleft) {}
rect(const gui::point& origin, const gui::size& size) : origin(origin), size(size) {}
rect(const rect&) = default;
rect& operator=(const rect&) = default;
rect(rect&&) = default;
rect& operator=(rect&&) = default;
};
struct ratio {
int num;
int denom;
long double scaleD(const pixels& px) const
{
return num * px.value() / denom;
}
float scaleF(const pixels& px) const
{
return (float)(num * px.value() / denom);
}
long scaleL(const pixels& px) const
{
return (long)(0.5 + num * px.value() / denom);
}
int scaleI(const pixels& px) const
{
return (int)(0.5 + num * px.value() / denom);
}
pixels invert(int value) const {
return (long double)value * denom / num;
}
pixels invert(double value) const {
return (long double)value * denom / num;
}
pixels invert(long double value) const {
return value * denom / num;
}
static int GCD(int a, int b) {
if (!b)
return a;
return GCD(b, a % b);
}
ratio gcd() const {
auto factor = GCD(num, denom);
return{ num / factor, denom / factor };
}
};
inline ratio operator * (const ratio& lhs, const ratio& rhs)
{
auto out = lhs.gcd();
auto right = rhs.gcd();
auto gcd = ratio::GCD(out.num, right.denom);
out.num /= gcd;
right.denom /= gcd;
gcd = ratio::GCD(right.num, out.denom);
right.num /= gcd;
out.denom /= gcd;
out.num *= right.num;
out.denom *= right.denom;
return out;
}
struct painter {
virtual ~painter() {}
virtual void moveOrigin(const pixels& x, const pixels& y) = 0;
void moveOrigin(const point& pt) { moveOrigin(pt.x, pt.y); }
virtual point getOrigin() const = 0;
virtual void setOrigin(const point& orig) = 0;
virtual void paintImage(const image_ref* img, const pixels& width, const pixels& height) = 0;
virtual void paintString(const std::string& text) = 0;
virtual void paintBackground(colorref, const pixels& width, const pixels& height) = 0;
virtual void paintBorder(node*) = 0;
virtual size measureString(const std::string& text) = 0;
virtual pixels fontBaseline() = 0;
virtual bool visible(node*) const = 0;
virtual style_handle applyStyle(node*) = 0;
virtual void restoreStyle(style_handle) = 0;
virtual ratio trueZoom() const = 0;
};
class push_origin {
painter* m_painter;
point orig;
public:
explicit push_origin(painter* paint) : m_painter(paint), orig(paint->getOrigin())
{
}
~push_origin()
{
m_painter->setOrigin(orig);
}
};
};<commit_msg>[JIRDESK-79] Adding box layers<commit_after>/*
* Copyright (C) 2015 midnightBITS
*
* 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.
*/
#pragma once
#include <string>
#include <gui/types.hpp>
namespace gui {
struct image_ref;
struct node;
struct style_save { int __unused; };
using style_handle = style_save*;
struct point {
pixels x;
pixels y;
point() : x(0), y(0) {}
point(const pixels& x, const pixels& y) : x(x), y(y) {}
point(const point&) = default;
point& operator=(const point&) = default;
point(point&&) = default;
point& operator=(point&&) = default;
};
struct size {
pixels width;
pixels height;
size() : width(0), height(0) {}
size(const pixels& width, const pixels& height) : width(width), height(height) {}
size(const size&) = default;
size& operator=(const size&) = default;
size(size&&) = default;
size& operator=(size&&) = default;
bool empty() const
{
return !width.value() || !height.value();
}
};
inline point operator + (const point& lhs, const point& rhs) {
return{ lhs.x + rhs.x, lhs.y + rhs.y };
}
inline point operator + (const point& lhs, const size& rhs) {
return{ lhs.x + rhs.width, lhs.y + rhs.height };
}
inline size operator - (const point& lhs, const point& rhs) {
return{ std::abs((lhs.x - rhs.x).value()), std::abs((lhs.y - rhs.y).value()) };
}
struct box {
pixels top;
pixels right;
pixels left;
pixels bottom;
box() = default;
box(const box&) = default;
box& operator=(const box&) = default;
box(box&&) = default;
box& operator=(box&&) = default;
// this constructors takes top, right, bottom and left,
// with values filled like in CSS
box(const pixels& top, const pixels& right, const pixels& bottom, const pixels& left)
: top(top)
, right(right)
, bottom(bottom)
, left(left)
{
}
// this constructors takes top, right and bottom,
// with missing value filled like in CSS
box(const pixels& top, const pixels& right, const pixels& bottom)
: top(top)
, right(right)
, bottom(bottom)
, left(right)
{
}
// this constructors takes top and right,
// with missing values filled like in CSS
box(const pixels& top, const pixels& right)
: top(top)
, right(right)
, bottom(top)
, left(right)
{
}
// this constructors takes only top,
// with missing values filled like in CSS
box(const pixels& top)
: top(top)
, right(top)
, bottom(top)
, left(top)
{
}
};
struct rect {
gui::point origin;
gui::size size;
rect() = default;
rect(const gui::point& topleft, const gui::point& bottomright) : origin(topleft), size(bottomright - topleft) {}
rect(const gui::point& origin, const gui::size& size) : origin(origin), size(size) {}
rect(const rect&) = default;
rect& operator=(const rect&) = default;
rect(rect&&) = default;
rect& operator=(rect&&) = default;
};
struct reach {
rect position;
box values;
reach() = default;
reach(const rect& position, const box& values) : position(position), values(values) {}
reach(const reach&) = default;
reach& operator=(const reach&) = default;
reach(reach&&) = default;
reach& operator=(reach&&) = default;
};
struct css_box {
box margin;
box border;
box padding;
css_box() = default;
css_box(const box& margin, const box& border, const box& padding) : margin(margin), border(border), padding(padding) {}
css_box(const css_box&) = default;
css_box& operator=(const css_box&) = default;
css_box(css_box&&) = default;
css_box& operator=(css_box&&) = default;
};
struct ratio {
int num;
int denom;
long double scaleD(const pixels& px) const
{
return num * px.value() / denom;
}
float scaleF(const pixels& px) const
{
return (float)(num * px.value() / denom);
}
long scaleL(const pixels& px) const
{
return (long)(0.5 + num * px.value() / denom);
}
int scaleI(const pixels& px) const
{
return (int)(0.5 + num * px.value() / denom);
}
pixels invert(int value) const {
return (long double)value * denom / num;
}
pixels invert(double value) const {
return (long double)value * denom / num;
}
pixels invert(long double value) const {
return value * denom / num;
}
static int GCD(int a, int b) {
if (!b)
return a;
return GCD(b, a % b);
}
ratio gcd() const {
auto factor = GCD(num, denom);
return{ num / factor, denom / factor };
}
};
inline ratio operator * (const ratio& lhs, const ratio& rhs)
{
auto out = lhs.gcd();
auto right = rhs.gcd();
auto gcd = ratio::GCD(out.num, right.denom);
out.num /= gcd;
right.denom /= gcd;
gcd = ratio::GCD(right.num, out.denom);
right.num /= gcd;
out.denom /= gcd;
out.num *= right.num;
out.denom *= right.denom;
return out;
}
struct painter {
virtual ~painter() {}
virtual void moveOrigin(const pixels& x, const pixels& y) = 0;
void moveOrigin(const point& pt) { moveOrigin(pt.x, pt.y); }
virtual point getOrigin() const = 0;
virtual void setOrigin(const point& orig) = 0;
virtual void paintImage(const image_ref* img, const pixels& width, const pixels& height) = 0;
virtual void paintString(const std::string& text) = 0;
virtual void paintBackground(colorref, const pixels& width, const pixels& height) = 0;
virtual void paintBorder(node*) = 0;
virtual size measureString(const std::string& text) = 0;
virtual pixels fontBaseline() = 0;
virtual bool visible(node*) const = 0;
virtual style_handle applyStyle(node*) = 0;
virtual void restoreStyle(style_handle) = 0;
virtual ratio trueZoom() const = 0;
};
class push_origin {
painter* m_painter;
point orig;
public:
explicit push_origin(painter* paint) : m_painter(paint), orig(paint->getOrigin())
{
}
~push_origin()
{
m_painter->setOrigin(orig);
}
};
};<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 Max Kellermann <max@duempel.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 CONST_BUFFER_HPP
#define CONST_BUFFER_HPP
#include <inline/compiler.h>
#include <cstddef>
#ifndef NDEBUG
#include <assert.h>
#endif
/**
* A reference to a memory area that is read-only.
*/
template<typename T>
struct ConstBuffer {
typedef size_t size_type;
typedef const T *pointer_type;
typedef pointer_type const_pointer_type;
typedef pointer_type iterator;
typedef pointer_type const_iterator;
pointer_type data;
size_type size;
ConstBuffer() = default;
constexpr ConstBuffer(std::nullptr_t):data(nullptr), size(0) {}
constexpr ConstBuffer(pointer_type _data, size_type _size)
:data(_data), size(_size) {}
constexpr static ConstBuffer Null() {
return ConstBuffer(nullptr, 0);
}
/**
* Cast a ConstBuffer<void> to a ConstBuffer<T>. A "void"
* buffer records its size in bytes, and when casting to "T",
* the assertion below ensures that the size is a multiple of
* sizeof(T).
*/
#ifdef NDEBUG
constexpr
#endif
static ConstBuffer<T> FromVoid(ConstBuffer<void> other) {
static_assert(sizeof(T) > 0, "Empty base type");
#ifndef NDEBUG
assert(other.size % sizeof(T) == 0);
#endif
return ConstBuffer<T>(pointer_type(other.data),
other.size / sizeof(T));
}
constexpr ConstBuffer<void> ToVoid() const {
static_assert(sizeof(T) > 0, "Empty base type");
return ConstBuffer<void>(data, size * sizeof(T));
}
constexpr bool IsNull() const {
return data == nullptr;
}
constexpr bool IsEmpty() const {
return size == 0;
}
constexpr iterator begin() const {
return data;
}
constexpr iterator end() const {
return data + size;
}
constexpr const_iterator cbegin() const {
return data;
}
constexpr const_iterator cend() const {
return data + size;
}
constexpr operator ConstBuffer<void>() const {
return { data, size };
}
};
#endif
<commit_msg>util/ConstBuffer: copy latest version from upstream<commit_after>/*
* Copyright (C) 2013 Max Kellermann <max@duempel.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 CONST_BUFFER_HPP
#define CONST_BUFFER_HPP
#include <inline/compiler.h>
#include <cstddef>
#ifndef NDEBUG
#include <assert.h>
#endif
template<typename T>
struct ConstBuffer;
template<>
struct ConstBuffer<void> {
typedef size_t size_type;
typedef const void *pointer_type;
typedef pointer_type const_pointer_type;
typedef pointer_type iterator;
typedef pointer_type const_iterator;
pointer_type data;
size_type size;
ConstBuffer() = default;
constexpr ConstBuffer(std::nullptr_t):data(nullptr), size(0) {}
constexpr ConstBuffer(pointer_type _data, size_type _size)
:data(_data), size(_size) {}
constexpr static ConstBuffer Null() {
return ConstBuffer(nullptr, 0);
}
constexpr static ConstBuffer<void> FromVoid(ConstBuffer<void> other) {
return other;
}
constexpr ConstBuffer<void> ToVoid() const {
return *this;
}
constexpr bool IsNull() const {
return data == nullptr;
}
constexpr bool IsEmpty() const {
return size == 0;
}
};
/**
* A reference to a memory area that is read-only.
*/
template<typename T>
struct ConstBuffer {
typedef size_t size_type;
typedef const T *pointer_type;
typedef pointer_type const_pointer_type;
typedef pointer_type iterator;
typedef pointer_type const_iterator;
pointer_type data;
size_type size;
ConstBuffer() = default;
constexpr ConstBuffer(std::nullptr_t):data(nullptr), size(0) {}
constexpr ConstBuffer(pointer_type _data, size_type _size)
:data(_data), size(_size) {}
constexpr static ConstBuffer Null() {
return ConstBuffer(nullptr, 0);
}
/**
* Cast a ConstBuffer<void> to a ConstBuffer<T>. A "void"
* buffer records its size in bytes, and when casting to "T",
* the assertion below ensures that the size is a multiple of
* sizeof(T).
*/
#ifdef NDEBUG
constexpr
#endif
static ConstBuffer<T> FromVoid(ConstBuffer<void> other) {
static_assert(sizeof(T) > 0, "Empty base type");
#ifndef NDEBUG
assert(other.size % sizeof(T) == 0);
#endif
return ConstBuffer<T>(pointer_type(other.data),
other.size / sizeof(T));
}
constexpr ConstBuffer<void> ToVoid() const {
static_assert(sizeof(T) > 0, "Empty base type");
return ConstBuffer<void>(data, size * sizeof(T));
}
constexpr bool IsNull() const {
return data == nullptr;
}
constexpr bool IsEmpty() const {
return size == 0;
}
constexpr iterator begin() const {
return data;
}
constexpr iterator end() const {
return data + size;
}
constexpr const_iterator cbegin() const {
return data;
}
constexpr const_iterator cend() const {
return data + size;
}
#ifdef NDEBUG
constexpr
#endif
const T &operator[](size_type i) const {
#ifndef NDEBUG
assert(i < size);
#endif
return data[i];
}
};
#endif
<|endoftext|> |
<commit_before>#include "GLMaterial.h"
#include "GLTexture.h"
#include "GLShaderManager.h"
#include "Package.h"
namespace {
static const std::string constantVsh = R"GLSL(
attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;
uniform mat4 uProjMatrix;
uniform mat4 uMVMatrix;
varying vec2 vUV;
void main(void) {
vUV = aVertexUV;
gl_Position = uProjMatrix * (uMVMatrix * vec4(aVertexPosition, 1.0));
}
)GLSL";
static const std::string constantFsh = R"GLSL(
precision mediump float;
varying vec2 vUV;
#ifdef EMISSION_TEXTURE
uniform sampler2D uEmissionTex;
#else
uniform vec4 uEmissionColor;
#endif
void main(void) {
#ifdef EMISSION_TEXTURE
vec4 emission = texture2D(uEmissionTex, vUV);
#else
vec4 emission = uEmissionColor;
#endif
vec4 color = emission;
if (color.a == 0.0) {
discard;
}
gl_FragColor = color;
}
)GLSL";
static const std::string prebakedVsh = R"GLSL(
attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;
attribute vec4 aVertexColor;
uniform mat4 uProjMatrix;
uniform mat4 uMVMatrix;
varying vec2 vUV;
varying lowp vec4 vColor;
void main(void) {
vUV = aVertexUV;
vColor = aVertexColor;
gl_Position = uProjMatrix * (uMVMatrix * vec4(aVertexPosition, 1.0));
}
)GLSL";
static const std::string prebakedFsh = R"GLSL(
precision mediump float;
varying vec2 vUV;
varying lowp vec4 vColor;
#ifdef DIFFUSE_TEXTURE
uniform sampler2D uDiffuseTex;
#else
uniform vec4 uDiffuseColor;
#endif
void main(void) {
#ifdef DIFFUSE_TEXTURE
vec4 diffuse = texture2D(uDiffuseTex, vUV);
#else
vec4 diffuse = uDiffuseColor;
#endif
vec4 color = diffuse * vColor;
if (color.a == 0.0) {
discard;
}
gl_FragColor = color;
}
)GLSL";
static const std::string lambertPhongBlinnVsh = R"GLSL(
attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;
attribute vec3 aVertexNormal;
uniform mat4 uProjMatrix;
uniform mat4 uMVMatrix;
uniform mat4 uInvTransMVMatrix;
varying vec2 vUV;
varying vec3 vNormal;
varying vec3 vPos;
void main(void) {
vec4 pos = uMVMatrix * vec4(aVertexPosition, 1.0);
vUV = aVertexUV;
vNormal = vec3(uInvTransMVMatrix * vec4(aVertexNormal, 0.0));
vPos = vec3(pos) / pos.w;
gl_Position = uProjMatrix * pos;
}
)GLSL";
static const std::string lambertPhongBlinnFsh = R"GLSL(
precision mediump float;
varying vec2 vUV;
varying vec3 vNormal;
varying vec3 vPos;
uniform vec4 uAmbientLightColor;
uniform vec3 uMainLightDir;
uniform vec4 uMainLightColor;
#ifdef EMISSION_TEXTURE
uniform sampler2D uEmissionTex;
#else
uniform vec4 uEmissionColor;
#endif
#ifdef AMBIENT_TEXTURE
uniform sampler2D uAmbientTex;
#else
uniform vec4 uAmbientColor;
#endif
#ifdef DIFFUSE_TEXTURE
uniform sampler2D uDiffuseTex;
#else
uniform vec4 uDiffuseColor;
#endif
#ifdef TRANSPARENT_TEXTURE
uniform sampler2D uTransparentTex;
#else
uniform vec4 uTransparentColor;
#endif
uniform float uTransparency;
#if defined(BLINN) || defined(PHONG)
#ifdef SPECULAR_TEXTURE
uniform sampler2D uSpecularTex;
#else
uniform vec4 uSpecularColor;
#endif
uniform float uShininess;
#endif
void main(void) {
#ifdef EMISSION_TEXTURE
vec4 emission = texture2D(uEmissionTex, vUV);
#else
vec4 emission = uEmissionColor;
#endif
#ifdef AMBIENT_TEXTURE
vec4 ambient = texture2D(uAmbientTex, vUV);
#else
vec4 ambient = uAmbientColor;
#endif
#ifdef DIFFUSE_TEXTURE
vec4 diffuse = texture2D(uDiffuseTex, vUV);
#else
vec4 diffuse = uDiffuseColor;
#endif
vec3 n = normalize(vNormal);
float n_dot_l = max(dot(n, uMainLightDir), 0.0);
vec4 color = emission + (ambient + diffuse) * uAmbientLightColor + n_dot_l * diffuse * uMainLightColor;
#if defined(BLINN) || defined(PHONG)
if (n_dot_l > 0.0) {
#ifdef SPECULAR_TEXTURE
vec4 specular = texture2D(uSpecularTex, vUV);
#else
vec4 specular = uSpecularColor;
#endif
#ifdef BLINN
vec3 v = normalize(-vPos);
vec3 h = normalize(v + uMainLightDir);
float refl = pow(max(dot(h, n), 0.0), uShininess);
#else
vec3 v = normalize(-vPos);
vec3 r = reflect(uMainLightDir, n);
float refl = pow(max(dot(r, v), 0.0), uShininess);
#endif
color = color + refl * specular * uMainLightColor;
}
#endif
#ifdef TRANSPARENT_TEXTURE
vec4 transparent = texture2D(uTransparentTex, vUV);
#else
vec4 transparent = uTransparentColor;
#endif
vec4 opacity = vec4(1.0, 1.0, 1.0, 1.0) - transparent;
float alpha = max(opacity.r, max(opacity.g, opacity.b));
if (alpha == 0.0) {
discard;
}
gl_FragColor = vec4((color * opacity).rgb * alpha, alpha);
}
)GLSL";
}
namespace carto { namespace nml {
GLMaterial::GLColorOrTexture::GLColorOrTexture() :
textureId(),
texture(),
color(cglib::vec4<float>::zero())
{
}
GLMaterial::GLColorOrTexture::GLColorOrTexture(const ColorOrTexture& colorOrTexture, const std::map<std::string, std::shared_ptr<GLTexture>>& textureMap) :
textureId(),
texture(),
color(cglib::vec4<float>::zero())
{
if (colorOrTexture.has_texture_id()) {
textureId = colorOrTexture.texture_id();
auto it = textureMap.find(colorOrTexture.texture_id());
if (it != textureMap.end()) {
texture = it->second;
}
}
if (colorOrTexture.has_color()) {
ColorRGBA c = colorOrTexture.color();
color = cglib::vec4<float>(c.r(), c.g(),c.b(), c.a());
}
}
GLMaterial::GLMaterial(const Material& material, const std::map<std::string, std::shared_ptr<GLTexture>>& textureMap) :
_type(Material::CONSTANT),
_culling(Material::NONE),
_opaqueMode(Material::OPAQUE),
_emission(),
_ambient(),
_diffuse(),
_transparent(),
_transparency(),
_specular(),
_shininess(),
_glProgramId()
{
_type = material.type();
_culling = material.culling();
_opaqueMode = material.has_opaque_mode() ? material.opaque_mode() : Material::OPAQUE;
_emission = material.has_emission() ? GLColorOrTexture(material.emission(), textureMap) : GLColorOrTexture();
_ambient = material.has_ambient() ? GLColorOrTexture(material.ambient(), textureMap) : GLColorOrTexture();
_diffuse = material.has_diffuse() ? GLColorOrTexture(material.diffuse(), textureMap) : GLColorOrTexture();
_transparent = material.has_transparent() ? GLColorOrTexture(material.transparent(), textureMap) : GLColorOrTexture();
_transparency = material.has_transparency() ? material.transparency() : 0.0f;
_specular = material.has_specular() ? GLColorOrTexture(material.specular(), textureMap) : GLColorOrTexture();
_shininess = material.has_shininess() ? material.shininess() : 0.0f;
}
void GLMaterial::create(GLShaderManager& shaderManager) {
std::set<std::string> defs;
if (!_emission.textureId.empty()) {
defs.insert("EMISSION_TEXTURE");
}
if (!_ambient.textureId.empty()) {
defs.insert("AMBIENT_TEXTURE");
}
if (!_diffuse.textureId.empty()) {
defs.insert("DIFFUSE_TEXTURE");
}
if (!_transparent.textureId.empty()) {
defs.insert("TRANSPARENT_TEXTURE");
}
if (!_specular.textureId.empty()) {
defs.insert("SPECULAR_TEXTURE");
}
switch (_type) {
case Material::CONSTANT:
_glProgramId = shaderManager.createProgram(constantVsh, constantFsh, defs);
break;
case Material::PREBAKED:
_glProgramId = shaderManager.createProgram(prebakedVsh, prebakedFsh, defs);
break;
case Material::LAMBERT:
_glProgramId = shaderManager.createProgram(lambertPhongBlinnVsh, lambertPhongBlinnFsh, defs);
break;
case Material::PHONG:
defs.insert("PHONG");
_glProgramId = shaderManager.createProgram(lambertPhongBlinnVsh, lambertPhongBlinnFsh, defs);
break;
case Material::BLINN:
defs.insert("BLINN");
_glProgramId = shaderManager.createProgram(lambertPhongBlinnVsh, lambertPhongBlinnFsh, defs);
break;
default:
assert(false);
}
}
void GLMaterial::dispose() {
}
int GLMaterial::getCulling() const {
return _culling;
}
void GLMaterial::replaceTexture(const std::string &textureId, const std::shared_ptr<GLTexture>& texture) {
GLColorOrTexture* channels[] = {
&_emission,
&_ambient,
&_diffuse,
&_specular,
nullptr
};
for (int i = 0; channels[i]; i++) {
if (channels[i]->textureId == textureId) {
channels[i]->texture = texture;
}
}
}
void GLMaterial::bind(const RenderState& renderState, const cglib::mat4x4<float>& mvMatrix, const cglib::mat4x4<float>& invTransMVMatrix) {
glDepthMask(_opaqueMode == Material::OPAQUE ? GL_TRUE : GL_FALSE);
glUseProgram(_glProgramId);
glUniformMatrix4fv(glGetUniformLocation(_glProgramId, "uProjMatrix"), 1, GL_FALSE, renderState.projMatrix.data());
glUniformMatrix4fv(glGetUniformLocation(_glProgramId, "uMVMatrix"), 1, GL_FALSE, mvMatrix.data());
if (_culling == Material::NONE) {
glDisable(GL_CULL_FACE);
} else {
glEnable(GL_CULL_FACE);
glCullFace(_culling == Material::FRONT ? GL_FRONT : GL_BACK);
}
if (_type != Material::PREBAKED) {
if (_emission.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uEmissionTex"), 0);
_emission.texture->bind(0);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uEmissionColor"), 1, _emission.color.data());
}
}
if (_type != Material::CONSTANT) {
if (_diffuse.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uDiffuseTex"), 1);
_diffuse.texture->bind(1);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uDiffuseColor"), 1, _diffuse.color.data());
}
if (_transparent.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uTransparentTex"), 2);
_transparent.texture->bind(2);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uTransparentColor"), 1, _transparent.color.data());
}
glUniform1f(glGetUniformLocation(_glProgramId, "uTransparency"), 1.0f);
if (_type != Material::PREBAKED) {
if (_ambient.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uAmbientTex"), 3);
_ambient.texture->bind(3);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uAmbientColor"), 1, _ambient.color.data());
}
if (_type != Material::LAMBERT) {
if (_specular.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uSpecularTex"), 4);
_specular.texture->bind(4);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uSpecularColor"), 1, _specular.color.data());
}
glUniform1f(glGetUniformLocation(_glProgramId, "uShininess"), _shininess);
}
glUniformMatrix4fv(glGetUniformLocation(_glProgramId, "uInvTransMVMatrix"), 1, GL_FALSE, invTransMVMatrix.data());
glUniform4fv(glGetUniformLocation(_glProgramId, "uAmbientLightColor"), 1, renderState.ambientLightColor.data());
glUniform4fv(glGetUniformLocation(_glProgramId, "uMainLightColor"), 1, renderState.mainLightColor.data());
glUniform3fv(glGetUniformLocation(_glProgramId, "uMainLightDir"), 1, renderState.mainLightDir.data());
}
}
}
} }
<commit_msg>Increase fragment shader precision when rendering NML models<commit_after>#include "GLMaterial.h"
#include "GLTexture.h"
#include "GLShaderManager.h"
#include "Package.h"
namespace {
static const std::string constantVsh = R"GLSL(
attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;
uniform mat4 uProjMatrix;
uniform mat4 uMVMatrix;
varying vec2 vUV;
void main(void) {
vUV = aVertexUV;
gl_Position = uProjMatrix * (uMVMatrix * vec4(aVertexPosition, 1.0));
}
)GLSL";
static const std::string constantFsh = R"GLSL(
precision mediump float;
varying vec2 vUV;
#ifdef EMISSION_TEXTURE
uniform sampler2D uEmissionTex;
#else
uniform vec4 uEmissionColor;
#endif
void main(void) {
#ifdef EMISSION_TEXTURE
vec4 emission = texture2D(uEmissionTex, vUV);
#else
vec4 emission = uEmissionColor;
#endif
vec4 color = emission;
if (color.a == 0.0) {
discard;
}
gl_FragColor = color;
}
)GLSL";
static const std::string prebakedVsh = R"GLSL(
attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;
attribute vec4 aVertexColor;
uniform mat4 uProjMatrix;
uniform mat4 uMVMatrix;
varying vec2 vUV;
varying lowp vec4 vColor;
void main(void) {
vUV = aVertexUV;
vColor = aVertexColor;
gl_Position = uProjMatrix * (uMVMatrix * vec4(aVertexPosition, 1.0));
}
)GLSL";
static const std::string prebakedFsh = R"GLSL(
precision mediump float;
varying vec2 vUV;
varying lowp vec4 vColor;
#ifdef DIFFUSE_TEXTURE
uniform sampler2D uDiffuseTex;
#else
uniform vec4 uDiffuseColor;
#endif
void main(void) {
#ifdef DIFFUSE_TEXTURE
vec4 diffuse = texture2D(uDiffuseTex, vUV);
#else
vec4 diffuse = uDiffuseColor;
#endif
vec4 color = diffuse * vColor;
if (color.a == 0.0) {
discard;
}
gl_FragColor = color;
}
)GLSL";
static const std::string lambertPhongBlinnVsh = R"GLSL(
attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;
attribute vec3 aVertexNormal;
uniform mat4 uProjMatrix;
uniform mat4 uMVMatrix;
uniform mat4 uInvTransMVMatrix;
varying vec2 vUV;
varying vec3 vNormal;
varying vec3 vPos;
void main(void) {
vec4 pos = uMVMatrix * vec4(aVertexPosition, 1.0);
vUV = aVertexUV;
vNormal = vec3(uInvTransMVMatrix * vec4(aVertexNormal, 0.0));
vPos = vec3(pos) / pos.w;
gl_Position = uProjMatrix * pos;
}
)GLSL";
static const std::string lambertPhongBlinnFsh = R"GLSL(
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
varying vec2 vUV;
varying vec3 vNormal;
varying vec3 vPos;
uniform vec4 uAmbientLightColor;
uniform vec3 uMainLightDir;
uniform vec4 uMainLightColor;
#ifdef EMISSION_TEXTURE
uniform sampler2D uEmissionTex;
#else
uniform vec4 uEmissionColor;
#endif
#ifdef AMBIENT_TEXTURE
uniform sampler2D uAmbientTex;
#else
uniform vec4 uAmbientColor;
#endif
#ifdef DIFFUSE_TEXTURE
uniform sampler2D uDiffuseTex;
#else
uniform vec4 uDiffuseColor;
#endif
#ifdef TRANSPARENT_TEXTURE
uniform sampler2D uTransparentTex;
#else
uniform vec4 uTransparentColor;
#endif
uniform float uTransparency;
#if defined(BLINN) || defined(PHONG)
#ifdef SPECULAR_TEXTURE
uniform sampler2D uSpecularTex;
#else
uniform vec4 uSpecularColor;
#endif
uniform float uShininess;
#endif
void main(void) {
#ifdef EMISSION_TEXTURE
vec4 emission = texture2D(uEmissionTex, vUV);
#else
vec4 emission = uEmissionColor;
#endif
#ifdef AMBIENT_TEXTURE
vec4 ambient = texture2D(uAmbientTex, vUV);
#else
vec4 ambient = uAmbientColor;
#endif
#ifdef DIFFUSE_TEXTURE
vec4 diffuse = texture2D(uDiffuseTex, vUV);
#else
vec4 diffuse = uDiffuseColor;
#endif
vec3 n = normalize(vNormal);
float n_dot_l = max(dot(n, uMainLightDir), 0.0);
vec4 color = emission + (ambient + diffuse) * uAmbientLightColor + n_dot_l * diffuse * uMainLightColor;
#if defined(BLINN) || defined(PHONG)
if (n_dot_l > 0.0) {
#ifdef SPECULAR_TEXTURE
vec4 specular = texture2D(uSpecularTex, vUV);
#else
vec4 specular = uSpecularColor;
#endif
#ifdef BLINN
vec3 v = normalize(-vPos);
vec3 h = normalize(v + uMainLightDir);
float refl = pow(max(dot(h, n), 0.0), uShininess);
#else
vec3 v = normalize(-vPos);
vec3 r = reflect(uMainLightDir, n);
float refl = pow(max(dot(r, v), 0.0), uShininess);
#endif
color = color + refl * specular * uMainLightColor;
}
#endif
#ifdef TRANSPARENT_TEXTURE
vec4 transparent = texture2D(uTransparentTex, vUV);
#else
vec4 transparent = uTransparentColor;
#endif
vec4 opacity = vec4(1.0, 1.0, 1.0, 1.0) - transparent;
float alpha = max(opacity.r, max(opacity.g, opacity.b));
if (alpha == 0.0) {
discard;
}
gl_FragColor = vec4((color * opacity).rgb * alpha, alpha);
}
)GLSL";
}
namespace carto { namespace nml {
GLMaterial::GLColorOrTexture::GLColorOrTexture() :
textureId(),
texture(),
color(cglib::vec4<float>::zero())
{
}
GLMaterial::GLColorOrTexture::GLColorOrTexture(const ColorOrTexture& colorOrTexture, const std::map<std::string, std::shared_ptr<GLTexture>>& textureMap) :
textureId(),
texture(),
color(cglib::vec4<float>::zero())
{
if (colorOrTexture.has_texture_id()) {
textureId = colorOrTexture.texture_id();
auto it = textureMap.find(colorOrTexture.texture_id());
if (it != textureMap.end()) {
texture = it->second;
}
}
if (colorOrTexture.has_color()) {
ColorRGBA c = colorOrTexture.color();
color = cglib::vec4<float>(c.r(), c.g(),c.b(), c.a());
}
}
GLMaterial::GLMaterial(const Material& material, const std::map<std::string, std::shared_ptr<GLTexture>>& textureMap) :
_type(Material::CONSTANT),
_culling(Material::NONE),
_opaqueMode(Material::OPAQUE),
_emission(),
_ambient(),
_diffuse(),
_transparent(),
_transparency(),
_specular(),
_shininess(),
_glProgramId()
{
_type = material.type();
_culling = material.culling();
_opaqueMode = material.has_opaque_mode() ? material.opaque_mode() : Material::OPAQUE;
_emission = material.has_emission() ? GLColorOrTexture(material.emission(), textureMap) : GLColorOrTexture();
_ambient = material.has_ambient() ? GLColorOrTexture(material.ambient(), textureMap) : GLColorOrTexture();
_diffuse = material.has_diffuse() ? GLColorOrTexture(material.diffuse(), textureMap) : GLColorOrTexture();
_transparent = material.has_transparent() ? GLColorOrTexture(material.transparent(), textureMap) : GLColorOrTexture();
_transparency = material.has_transparency() ? material.transparency() : 0.0f;
_specular = material.has_specular() ? GLColorOrTexture(material.specular(), textureMap) : GLColorOrTexture();
_shininess = material.has_shininess() ? material.shininess() : 0.0f;
}
void GLMaterial::create(GLShaderManager& shaderManager) {
std::set<std::string> defs;
if (!_emission.textureId.empty()) {
defs.insert("EMISSION_TEXTURE");
}
if (!_ambient.textureId.empty()) {
defs.insert("AMBIENT_TEXTURE");
}
if (!_diffuse.textureId.empty()) {
defs.insert("DIFFUSE_TEXTURE");
}
if (!_transparent.textureId.empty()) {
defs.insert("TRANSPARENT_TEXTURE");
}
if (!_specular.textureId.empty()) {
defs.insert("SPECULAR_TEXTURE");
}
switch (_type) {
case Material::CONSTANT:
_glProgramId = shaderManager.createProgram(constantVsh, constantFsh, defs);
break;
case Material::PREBAKED:
_glProgramId = shaderManager.createProgram(prebakedVsh, prebakedFsh, defs);
break;
case Material::LAMBERT:
_glProgramId = shaderManager.createProgram(lambertPhongBlinnVsh, lambertPhongBlinnFsh, defs);
break;
case Material::PHONG:
defs.insert("PHONG");
_glProgramId = shaderManager.createProgram(lambertPhongBlinnVsh, lambertPhongBlinnFsh, defs);
break;
case Material::BLINN:
defs.insert("BLINN");
_glProgramId = shaderManager.createProgram(lambertPhongBlinnVsh, lambertPhongBlinnFsh, defs);
break;
default:
assert(false);
}
}
void GLMaterial::dispose() {
}
int GLMaterial::getCulling() const {
return _culling;
}
void GLMaterial::replaceTexture(const std::string &textureId, const std::shared_ptr<GLTexture>& texture) {
GLColorOrTexture* channels[] = {
&_emission,
&_ambient,
&_diffuse,
&_specular,
nullptr
};
for (int i = 0; channels[i]; i++) {
if (channels[i]->textureId == textureId) {
channels[i]->texture = texture;
}
}
}
void GLMaterial::bind(const RenderState& renderState, const cglib::mat4x4<float>& mvMatrix, const cglib::mat4x4<float>& invTransMVMatrix) {
glDepthMask(_opaqueMode == Material::OPAQUE ? GL_TRUE : GL_FALSE);
glUseProgram(_glProgramId);
glUniformMatrix4fv(glGetUniformLocation(_glProgramId, "uProjMatrix"), 1, GL_FALSE, renderState.projMatrix.data());
glUniformMatrix4fv(glGetUniformLocation(_glProgramId, "uMVMatrix"), 1, GL_FALSE, mvMatrix.data());
if (_culling == Material::NONE) {
glDisable(GL_CULL_FACE);
} else {
glEnable(GL_CULL_FACE);
glCullFace(_culling == Material::FRONT ? GL_FRONT : GL_BACK);
}
if (_type != Material::PREBAKED) {
if (_emission.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uEmissionTex"), 0);
_emission.texture->bind(0);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uEmissionColor"), 1, _emission.color.data());
}
}
if (_type != Material::CONSTANT) {
if (_diffuse.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uDiffuseTex"), 1);
_diffuse.texture->bind(1);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uDiffuseColor"), 1, _diffuse.color.data());
}
if (_transparent.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uTransparentTex"), 2);
_transparent.texture->bind(2);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uTransparentColor"), 1, _transparent.color.data());
}
glUniform1f(glGetUniformLocation(_glProgramId, "uTransparency"), 1.0f);
if (_type != Material::PREBAKED) {
if (_ambient.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uAmbientTex"), 3);
_ambient.texture->bind(3);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uAmbientColor"), 1, _ambient.color.data());
}
if (_type != Material::LAMBERT) {
if (_specular.texture) {
glUniform1i(glGetUniformLocation(_glProgramId, "uSpecularTex"), 4);
_specular.texture->bind(4);
} else {
glUniform4fv(glGetUniformLocation(_glProgramId, "uSpecularColor"), 1, _specular.color.data());
}
glUniform1f(glGetUniformLocation(_glProgramId, "uShininess"), _shininess);
}
glUniformMatrix4fv(glGetUniformLocation(_glProgramId, "uInvTransMVMatrix"), 1, GL_FALSE, invTransMVMatrix.data());
glUniform4fv(glGetUniformLocation(_glProgramId, "uAmbientLightColor"), 1, renderState.ambientLightColor.data());
glUniform4fv(glGetUniformLocation(_glProgramId, "uMainLightColor"), 1, renderState.mainLightColor.data());
glUniform3fv(glGetUniformLocation(_glProgramId, "uMainLightDir"), 1, renderState.mainLightDir.data());
}
}
}
} }
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "crown.h"
#include "memory.h"
#include "input.h"
#include "console_server.h"
#include "bundle_compiler.h"
#include "device.h"
#include "command_line.h"
#include "json_parser.h"
#include "keyboard.h"
#include "mouse.h"
#include "touch.h"
#include "main.h"
#include "audio.h"
#include "physics.h"
#include "disk_filesystem.h"
#include "config.h"
#include "math_utils.h"
#include <bgfx.h>
namespace crown
{
static void help(const char* msg = NULL)
{
if (msg)
{
printf("Error: %s\n", msg);
}
printf(
"Usage: crown [options]\n"
"Options:\n\n"
" -h --help Show this help.\n"
" --bundle-dir <path> Use <path> as the source directory for compiled resources.\n"
" --parent-window <handle> Set the parent window <handle> of the main window.\n"
" Used only by tools.\n"
"\nAvailable only in debug and development builds:\n\n"
" --source-dir <path> Use <path> as the source directory for resource compilation.\n"
" --compile Do a full compile of the resources.\n"
" --platform <platform> Compile resources for the given <platform>.\n"
" Possible values for <platform> are:\n"
" linux\n"
" android\n"
" windows\n"
" --continue Continue the execution after the resource compilation step.\n"
" --host Read resources from a remote engine instance.\n"
" --wait-console Wait for a console connection before starting up.\n"
);
}
CommandLineSettings parse_command_line(int argc, char** argv)
{
CommandLineSettings cls;
cls.source_dir = NULL;
cls.bundle_dir = NULL;
cls.platform = NULL;
cls.wait_console = false;
cls.do_compile = false;
cls.do_continue = false;
cls.parent_window = 0;
CommandLine cmd(argc, argv);
if (cmd.has_argument("help", 'h'))
{
help();
exit(EXIT_FAILURE);
}
cls.source_dir = cmd.get_parameter("source-dir");
if (!cls.source_dir)
{
help("Source directory must be specified.");
exit(EXIT_FAILURE);
}
cls.bundle_dir = cmd.get_parameter("bundle-dir");
if (!cls.bundle_dir)
{
help("Bundle directory must be specified.");
exit(EXIT_FAILURE);
}
cls.platform = cmd.get_parameter("platform");
if (!cls.platform)
{
help("Platform must be specified.");
exit(EXIT_FAILURE);
}
cls.platform = cmd.get_parameter("platform");
cls.wait_console = cmd.has_argument("wait-console");
cls.do_compile = cmd.has_argument("compile");
cls.do_continue = cmd.has_argument("continue");
const char* parent = cmd.get_parameter("parent-window");
if (parent)
{
cls.parent_window = string::parse_uint(parent);
}
return cls;
}
ConfigSettings parse_config_file(Filesystem& fs)
{
ConfigSettings cs;
cs.console_port = 10001;
cs.boot_package = 0;
cs.boot_script = 0;
cs.window_width = CROWN_DEFAULT_WINDOW_WIDTH;
cs.window_height = CROWN_DEFAULT_WINDOW_HEIGHT;
File* tmpfile = fs.open("crown.config", FOM_READ);
JSONParser config(*tmpfile);
fs.close(tmpfile);
JSONElement root = config.root();
JSONElement cport = root.key_or_nil("console_port");
if (!cport.is_nil())
{
cs.console_port = (int16_t) cport.to_int();
}
JSONElement window_width = root.key_or_nil("window_width");
if (!window_width.is_nil())
{
cs.window_width = math::max((uint16_t)1, (uint16_t)window_width.to_int());
}
JSONElement window_height = root.key_or_nil("window_height");
if (!window_height.is_nil())
{
cs.window_height = math::max((uint16_t)1, (uint16_t)window_height.to_int());
}
cs.boot_script = root.key("boot_script").to_resource_id("lua").name;
cs.boot_package = root.key("boot_package").to_resource_id("package").name;
return cs;
}
bool init(Filesystem& fs, const ConfigSettings& cs)
{
input_globals::init();
audio_globals::init();
physics_globals::init();
bgfx::init();
device_globals::init(fs, cs.boot_package, cs.boot_script);
device()->init();
return true;
}
void update()
{
while (!process_events() && device()->is_running())
{
#if defined(CROWN_DEBUG)
console_server_globals::console().update();
#endif
device()->update();
input_globals::keyboard().update();
input_globals::mouse().update();
input_globals::touch().update();
}
}
void shutdown()
{
device()->shutdown();
device_globals::shutdown();
bgfx::shutdown();
physics_globals::shutdown();
audio_globals::shutdown();
input_globals::shutdown();
}
} // namespace crown
<commit_msg>Require --platform only when compiling<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "crown.h"
#include "memory.h"
#include "input.h"
#include "console_server.h"
#include "bundle_compiler.h"
#include "device.h"
#include "command_line.h"
#include "json_parser.h"
#include "keyboard.h"
#include "mouse.h"
#include "touch.h"
#include "main.h"
#include "audio.h"
#include "physics.h"
#include "disk_filesystem.h"
#include "config.h"
#include "math_utils.h"
#include <bgfx.h>
namespace crown
{
static void help(const char* msg = NULL)
{
if (msg)
{
printf("Error: %s\n", msg);
}
printf(
"Usage: crown [options]\n"
"Options:\n\n"
" -h --help Show this help.\n"
" --bundle-dir <path> Use <path> as the source directory for compiled resources.\n"
" --parent-window <handle> Set the parent window <handle> of the main window.\n"
" Used only by tools.\n"
"\nAvailable only in debug and development builds:\n\n"
" --source-dir <path> Use <path> as the source directory for resource compilation.\n"
" --compile Do a full compile of the resources.\n"
" --platform <platform> Compile resources for the given <platform>.\n"
" Possible values for <platform> are:\n"
" linux\n"
" android\n"
" windows\n"
" --continue Continue the execution after the resource compilation step.\n"
" --host Read resources from a remote engine instance.\n"
" --wait-console Wait for a console connection before starting up.\n"
);
}
CommandLineSettings parse_command_line(int argc, char** argv)
{
CommandLineSettings cls;
cls.source_dir = NULL;
cls.bundle_dir = NULL;
cls.platform = NULL;
cls.wait_console = false;
cls.do_compile = false;
cls.do_continue = false;
cls.parent_window = 0;
CommandLine cmd(argc, argv);
if (cmd.has_argument("help", 'h'))
{
help();
exit(EXIT_FAILURE);
}
cls.source_dir = cmd.get_parameter("source-dir");
if (!cls.source_dir)
{
help("Source directory must be specified.");
exit(EXIT_FAILURE);
}
cls.bundle_dir = cmd.get_parameter("bundle-dir");
if (!cls.bundle_dir)
{
help("Bundle directory must be specified.");
exit(EXIT_FAILURE);
}
cls.platform = cmd.get_parameter("platform");
cls.wait_console = cmd.has_argument("wait-console");
cls.do_compile = cmd.has_argument("compile");
cls.do_continue = cmd.has_argument("continue");
cls.platform = cmd.get_parameter("platform");
if (cls.do_compile && !cls.platform)
{
help("Platform must be specified.");
exit(EXIT_FAILURE);
}
const char* parent = cmd.get_parameter("parent-window");
if (parent)
{
cls.parent_window = string::parse_uint(parent);
}
return cls;
}
ConfigSettings parse_config_file(Filesystem& fs)
{
ConfigSettings cs;
cs.console_port = 10001;
cs.boot_package = 0;
cs.boot_script = 0;
cs.window_width = CROWN_DEFAULT_WINDOW_WIDTH;
cs.window_height = CROWN_DEFAULT_WINDOW_HEIGHT;
File* tmpfile = fs.open("crown.config", FOM_READ);
JSONParser config(*tmpfile);
fs.close(tmpfile);
JSONElement root = config.root();
JSONElement cport = root.key_or_nil("console_port");
if (!cport.is_nil())
{
cs.console_port = (int16_t) cport.to_int();
}
JSONElement window_width = root.key_or_nil("window_width");
if (!window_width.is_nil())
{
cs.window_width = math::max((uint16_t)1, (uint16_t)window_width.to_int());
}
JSONElement window_height = root.key_or_nil("window_height");
if (!window_height.is_nil())
{
cs.window_height = math::max((uint16_t)1, (uint16_t)window_height.to_int());
}
cs.boot_script = root.key("boot_script").to_resource_id("lua").name;
cs.boot_package = root.key("boot_package").to_resource_id("package").name;
return cs;
}
bool init(Filesystem& fs, const ConfigSettings& cs)
{
input_globals::init();
audio_globals::init();
physics_globals::init();
bgfx::init();
device_globals::init(fs, cs.boot_package, cs.boot_script);
device()->init();
return true;
}
void update()
{
while (!process_events() && device()->is_running())
{
#if defined(CROWN_DEBUG)
console_server_globals::console().update();
#endif
device()->update();
input_globals::keyboard().update();
input_globals::mouse().update();
input_globals::touch().update();
}
}
void shutdown()
{
device()->shutdown();
device_globals::shutdown();
bgfx::shutdown();
physics_globals::shutdown();
audio_globals::shutdown();
input_globals::shutdown();
}
} // namespace crown
<|endoftext|> |
<commit_before>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
// Serial includes
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif
#include "serialwifly.h" // this is from Louis' wifly code, which will be a library
#include "common.h"
#include "wifly_thread.h"
#include "test.h" // for bearing calculation
#include "commander.h"
using std::string;
using std::vector;
using namespace std;
/* this is to help with some of the rotation logic */
bool in_rotation = false;
/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates */
uint8_t prev_hunt_state = 10;
/* whether or not we are currently rotating */
bool rotating = false;
/* whether or not we are currently moving */
bool moving = false;
int wifly_connect(char *port) {
/* Start the connection to the WiFly */
/* If the connection does not exist, quit */
/* This is assuming we want to connect to /dev/ttyUSB0 */
/* TODO: Don't make that assumption */
int fd = start_connection(port);
if (fd < 0)
{
// TODO: figure out what we do want to return when there is an error
printf("Error connecting to wifly. Exiting...\n");
return 0;
}
return fd;
}
void update_state(uint8_t &new_state) {
switch (new_state) {
case TRACKING_HUNT_STATE_ROTATE:
rotating = true;
break;
case TRACKING_HUNT_STATE_MOVE:
moving = true;
break;
case TRACKING_HUNT_STATE_OFF:
// finished = true;
break;
case TRACKING_HUNT_STATE_START:
// starting = true;
break;
}
}
void *wifly_thread(void *param) {
// retrieve the MAVInfo struct that is sent to this function as a parameter
struct MAVInfo *uavData = (struct MAVInfo *)param;
// some constants that all need to become parameters
int num_samples = 1;
char *ssid = (char *) "JAMMER01";
char *file_name = (char *) "wifly.csv";
char *bearing_file_name = (char *) "bearing_calc.csv";
char *port = (char *) "/dev/ttyUSB0";
// connect to the wifly
int wifly_fd = wifly_connect(port);
if (wifly_fd < 0) {
printf("Error opening wifly connection\n");
return NULL;
}
/* Go into command mode */
commandmode(wifly_fd);
/* Open a file to write values to */
/* Appending values */
FILE *wifly_file = fopen(file_name, "a");
if (wifly_file == NULL)
{
// TODO: figure out what we do want to return when there is an error
printf("Error opening wifly output file\n");
return NULL;
}
/* Open a file to write bearing calcs to */
FILE *bearing_file = fopen(bearing_file_name, "a");
if (bearing_file == NULL)
{
// TODO: figure out what we do want to return when there is an error
printf("Error opening bearing output file\n");
return NULL;
}
if (get_commands) {
load_move_commands();
}
vector<double> angles;
vector<double> gains;
// main loop that should be constantly taking measurements
// until the main program is stopped
while (RUNNING_FLAG) {
// handle hunt state changes required (sending of commands)
if (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {
printf("State changed from %u to %u\n", prev_hunt_state, uavData->tracking_status.hunt_mode_state);
if (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {
send_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state);
// TODO: maybe want to update the state immediately here...
} else {
update_state(uavData->tracking_status.hunt_mode_state);
}
// update the prev hunt state to be this new state
prev_hunt_state = uavData->tracking_status.hunt_mode_state;
printf("Prev State changed to: %u\n", prev_hunt_state);
}
// make measurements (depending on the current state)
/* check if we are in an official rotation */
if (rotating) {
if (!in_rotation) {
// set our logic to mark we are now running the rotation logic
in_rotation = true;
// clear the vectors
angles.clear();
gains.clear();
}
angles.push_back((double) uavData->vfr_hud.heading);
gains.push_back(scanrssi(wifly_fd, ssid));
}
if (!rotating && in_rotation) {
in_rotation = false;
// do bearing calculation at this point
double bearing = get_bearing(angles, gains);
// write the lat, lon, alt and bearing to file
fprintf(bearing_file, "%llu, %i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing);
// send a mavlink message of the calculated bearing
send_bearing_message(bearing, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);
// tell pixhawk we are finished with the rotation
// send_finish_command();
}
/* Scan values to this file */
/* Add degree at which you measure first */
// cout << uavData->vfr_hud.heading << " ";
fprintf(wifly_file, "%llu,%u,%i,%i,%i,%f,", uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);
int rssi = scanrssi_f(wifly_fd, ssid, wifly_file, num_samples);
cout << uavData->vfr_hud.heading << " " << rssi << "\n";
// send a mavlink message with the current rssi
send_rssi_message(rssi, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);
// TODO: send mavlink message of calculated rssi...
// send a message with a rotate command for testing purposes at the moment
// sendRotateCommand(-1.0);
/* sleep for some time before making another measurement (30 ms for now) */
usleep(30000);
}
/* Be sure to close the output file and connection */
fclose(wifly_file);
close(wifly_fd);
return NULL;
}
<commit_msg>make the loop time pause dynamic, to ensure measurements happen every 30ms regardless of runtime of the rest of the stuff<commit_after>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <time.h>
// Serial includes
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif
#include "serialwifly.h" // this is from Louis' wifly code, which will be a library
#include "common.h"
#include "wifly_thread.h"
#include "test.h" // for bearing calculation
#include "commander.h"
using std::string;
using std::vector;
using namespace std;
/* this is to help with some of the rotation logic */
bool in_rotation = false;
/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates */
uint8_t prev_hunt_state = 10;
/* whether or not we are currently rotating */
bool rotating = false;
/* whether or not we are currently moving */
bool moving = false;
/* microsecond timestamp of the previous loop iteration */
unsigned long prev_loop_timestamp = 0;
int wifly_connect(char *port) {
/* Start the connection to the WiFly */
/* If the connection does not exist, quit */
/* This is assuming we want to connect to /dev/ttyUSB0 */
/* TODO: Don't make that assumption */
int fd = start_connection(port);
if (fd < 0)
{
// TODO: figure out what we do want to return when there is an error
printf("Error connecting to wifly. Exiting...\n");
return 0;
}
return fd;
}
void update_state(uint8_t &new_state) {
switch (new_state) {
case TRACKING_HUNT_STATE_ROTATE:
rotating = true;
break;
case TRACKING_HUNT_STATE_MOVE:
moving = true;
break;
case TRACKING_HUNT_STATE_OFF:
// finished = true;
break;
case TRACKING_HUNT_STATE_START:
// starting = true;
break;
}
}
void *wifly_thread(void *param) {
// retrieve the MAVInfo struct that is sent to this function as a parameter
struct MAVInfo *uavData = (struct MAVInfo *)param;
// some constants that all need to become parameters
int num_samples = 1;
char *ssid = (char *) "JAMMER01";
char *file_name = (char *) "wifly.csv";
char *bearing_file_name = (char *) "bearing_calc.csv";
char *port = (char *) "/dev/ttyUSB0";
// connect to the wifly
int wifly_fd = wifly_connect(port);
if (wifly_fd < 0) {
printf("Error opening wifly connection\n");
return NULL;
}
/* Go into command mode */
commandmode(wifly_fd);
/* Open a file to write values to */
/* Appending values */
FILE *wifly_file = fopen(file_name, "a");
if (wifly_file == NULL)
{
// TODO: figure out what we do want to return when there is an error
printf("Error opening wifly output file\n");
return NULL;
}
/* Open a file to write bearing calcs to */
FILE *bearing_file = fopen(bearing_file_name, "a");
if (bearing_file == NULL)
{
// TODO: figure out what we do want to return when there is an error
printf("Error opening bearing output file\n");
return NULL;
}
if (get_commands) {
load_move_commands();
}
vector<double> angles;
vector<double> gains;
struct timeval tv;
// main loop that should be constantly taking measurements
// until the main program is stopped
while (RUNNING_FLAG) {
// only want to execute this at most ever 30 ms
// basically does a dynamic sleep in the sense that if there is a lot of processing time for doing the bearing
// calculation, we will only pause as long as required so measurements are really made every 30 ms
// (unless of course bearing calculations take too long)
gettimeofday(&tv, NULL);
unsigned long current_loop_time = 1000000 * tv_sec + tv_usec;
if (prev_loop_timestamp != 0 && (current_loop_time - prev_loop_timestamp) < 30000) {
continue;
}
prev_loop_timestamp = current_loop_time;
// handle hunt state changes required (sending of commands)
if (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {
printf("State changed from %u to %u\n", prev_hunt_state, uavData->tracking_status.hunt_mode_state);
if (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {
send_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state);
// TODO: maybe want to update the state immediately here...
} else {
update_state(uavData->tracking_status.hunt_mode_state);
}
// update the prev hunt state to be this new state
prev_hunt_state = uavData->tracking_status.hunt_mode_state;
printf("Prev State changed to: %u\n", prev_hunt_state);
}
// make measurements (depending on the current state)
/* check if we are in an official rotation */
if (rotating) {
if (!in_rotation) {
// set our logic to mark we are now running the rotation logic
in_rotation = true;
// clear the vectors
angles.clear();
gains.clear();
}
angles.push_back((double) uavData->vfr_hud.heading);
gains.push_back(scanrssi(wifly_fd, ssid));
}
if (!rotating && in_rotation) {
in_rotation = false;
// do bearing calculation at this point
double bearing = get_bearing(angles, gains);
// write the lat, lon, alt and bearing to file
fprintf(bearing_file, "%llu, %i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing);
// send a mavlink message of the calculated bearing
send_bearing_message(bearing, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);
// tell pixhawk we are finished with the rotation
// send_finish_command();
}
/* Scan values to this file */
/* Add degree at which you measure first */
// cout << uavData->vfr_hud.heading << " ";
fprintf(wifly_file, "%llu,%u,%i,%i,%i,%f,", uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);
int rssi = scanrssi_f(wifly_fd, ssid, wifly_file, num_samples);
cout << uavData->vfr_hud.heading << " " << rssi << "\n";
// send a mavlink message with the current rssi
send_rssi_message(rssi, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);
// TODO: send mavlink message of calculated rssi...
// send a message with a rotate command for testing purposes at the moment
// sendRotateCommand(-1.0);
/* sleep for some time before making another measurement (30 ms for now) */
// usleep(30000);
}
/* Be sure to close the output file and connection */
fclose(wifly_file);
close(wifly_fd);
return NULL;
}
<|endoftext|> |
<commit_before>/***********************************************************************
* This Source Code Form is subject to the terms of the Mozilla Public *
* License, v. 2.0. If a copy of the MPL was not distributed with this *
* file, You can obtain one at http://mozilla.org/MPL/2.0/. *
***********************************************************************/
#ifndef DUCK_HPP_INCLUDED
#define DUCK_HPP_INCLUDED
/**
* @file Duck.hpp
* @author Maxime PINARD
* @version 0.0
* @license Mozilla Public License, v. .2.0
* @brief Defines the Duck Class
*/
#include <Ducky>
/**
* @class Duck Duck.hpp
* @brief Defines the Duck Class
*/
class Duck : public Duck{
public:
/**
* @brief Duck constructor with path to sprites and starting_coordinates
* @param game_window Window of the game
* @param duck_textures Textures of the duck. Order : Up, Down, Left, Right
* @param duckies_textures Textures of the duckies. Order : Up, Down, Left, Right
* @param starting_coordinates Coordinates of the ducky spawn
*/
void Duck(sf::Window& game_window, sf::Texture duck_textures[4], sf::Texture duckies_textures[4], Coord starting_coordinates);
/**
* @brief Default constructor
*/
Duck();
/**
* @brief Default destructor
*/
~Duck();
/**
* @brief Apply damages to the duck and respawn it
*/
void damaged();
/**
* @brief Add a ducky to the duck familly
* @return [description]
*/
bool power_up();
/**
* @brief Return the number of duckies
* @return The number of duckies
*/
unsigned char size();
private:
std::vector<Ducky> Duckies;
char invulnerability;
};
#endif /*DUCK_HPP_INCLUDED*/<commit_msg>Duck.hpp correction<commit_after>/***********************************************************************
* This Source Code Form is subject to the terms of the Mozilla Public *
* License, v. 2.0. If a copy of the MPL was not distributed with this *
* file, You can obtain one at http://mozilla.org/MPL/2.0/. *
***********************************************************************/
#ifndef DUCK_HPP_INCLUDED
#define DUCK_HPP_INCLUDED
/**
* @file Duck.hpp
* @author Maxime PINARD
* @version 0.0
* @license Mozilla Public License, v. .2.0
* @brief Defines the Duck Class
*/
#include <Ducky>
/**
* @class Duck Duck.hpp
* @brief Defines the Duck Class
*/
class Duck : public Duck{
public:
/**
* @brief Duck constructor with path to sprites and starting_coordinates
* @param game_window Window of the game
* @param duck_textures Textures of the duck. Order : Up, Down, Left, Right
* @param duckies_textures Textures of the duckies. Order : Up, Down, Left, Right
* @param starting_coordinates Coordinates of the ducky spawn
*/
Duck(sf::Window& game_window, sf::Texture duck_textures[4], sf::Texture duckies_textures[4], Coord starting_coordinates);
/**
* @brief Default constructor
*/
Duck();
/**
* @brief Default destructor
*/
~Duck();
/**
* @brief Apply damages to the duck and respawn it
*/
void damaged();
/**
* @brief Add a ducky to the duck familly
* @return [description]
*/
bool power_up();
/**
* @brief Return the number of duckies
* @return The number of duckies
*/
unsigned char size();
private:
std::vector<Ducky> Duckies;
char invulnerability;
};
#endif /*DUCK_HPP_INCLUDED*/<|endoftext|> |
<commit_before>/*
* Harp, an efficient IO library for chemistry file formats
* Copyright (C) 2014 Guillaume Fraux
*
* 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/
*/
/*! @file Harp.hpp
* Harp main C++ API header.
*
* This file contains all the function definitions for the C++ API of Harp, and
* should be self-documented enough.
*/
#ifndef HARP_H
#define HARP_H
#include "Logger.hpp"
#include "HarpFile.hpp"
#include "Error.hpp"
#endif
<commit_msg>Update the main header doc<commit_after>/*
* Harp, an efficient IO library for chemistry file formats
* Copyright (C) 2014 Guillaume Fraux
*
* 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/
*/
/*! @file Harp.hpp
* Harp main C++ API header.
*
* This file includes the public API headers for Harp, and should be the only one
* included by client applications.
*/
#ifndef HARP_HPP
#define HARP_HPP
#include "Logger.hpp"
#include "HarpFile.hpp"
#include "Error.hpp"
#endif
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <cstdlib>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <vw/Core/Functors.h>
#include <vw/Image/Algorithms.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/ImageViewRef.h>
#include <vw/Image/PerPixelViews.h>
#include <vw/Image/PixelMask.h>
#include <vw/Image/MaskViews.h>
#include <vw/Image/PixelTypes.h>
#include <vw/Image/Statistics.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/Cartography/FileIO.h>
#include <vw/Cartography/GeoReference.h>
using namespace vw;
// Global variables
std::string input_file_name, output_file_name = "", shaded_relief_file_name;
float nodata_value;
float min_val = 0, max_val = 0;
// Useful functions
/// Erases a file suffix if one exists and returns the base string
static std::string prefix_from_filename(std::string const& filename) {
std::string result = filename;
int index = result.rfind(".");
if (index != -1)
result.erase(index, result.size());
return result;
}
// Colormap function
class ColormapFunc : public ReturnFixedType<PixelMask<PixelRGB<float> > > {
public:
ColormapFunc() {}
template <class PixelT>
PixelMask<PixelRGB<float> > operator() (PixelT const& pix) const {
if (is_transparent(pix))
return PixelMask<PixelRGB<float> >();
float val = compound_select_channel<const float&>(pix,0);
if (val > 1.0) val = 1.0;
if (val < 0.0) val = 0.0;
Vector2 red_range(3/8.0, 1.0);
Vector2 green_range(2/8.0, 6/8.0);
Vector2 blue_range(0.0, 5/8.0);
float red_span = red_range[1] - red_range[0];
float blue_span = blue_range[1] - blue_range[0];
float green_span = green_range[1] - green_range[0];
float red = 0;
float green = 0;
float blue = 0;
// Red
if (val >= red_range[0] && val <= red_range[0]+red_span/3)
red = (val-red_range[0])/(red_span/3);
if (val >= red_range[0]+red_span/3 && val <= red_range[0]+2*red_span/3)
red = 1.0;
if (val >= red_range[0]+2*red_span/3 && val <= red_range[1])
red = 1-((val-(red_range[0]+2*red_span/3))/(red_span/3));
// Blue
if (val >= blue_range[0] && val <= blue_range[0]+blue_span/3)
blue = (val-blue_range[0])/(blue_span/3);
if (val >= blue_range[0]+blue_span/3 && val <= blue_range[0]+2*blue_span/3)
blue = 1.0;
if (val >= blue_range[0]+2*blue_span/3 && val <= blue_range[1])
blue = 1-((val-(blue_range[0]+2*blue_span/3))/(blue_span/3));
// Green
if (val >= green_range[0] && val <= green_range[0]+green_span/3)
green = (val-green_range[0])/(green_span/3);
if (val >= green_range[0]+green_span/3 && val <= green_range[0]+2*green_span/3)
green = 1.0;
if (val >= green_range[0]+2*green_span/3 && val <= green_range[1])
green = 1-((val-(green_range[0]+2*green_span/3))/(green_span/3));
return PixelRGB<float> ( red, green, blue );
}
};
template <class ViewT>
UnaryPerPixelView<ViewT, ColormapFunc> colormap(ImageViewBase<ViewT> const& view) {
return UnaryPerPixelView<ViewT, ColormapFunc>(view.impl(), ColormapFunc());
}
// ---------------------------------------------------------------------------------------------------
template <class PixelT>
void do_colorized_dem(po::variables_map const& vm) {
cartography::GeoReference georef;
cartography::read_georeference(georef, input_file_name);
DiskImageView<PixelT> disk_dem_file(input_file_name);
ImageViewRef<PixelGray<float> > input_image = channel_cast<float>(disk_dem_file);
vw_out() << "Creating colorized DEM.\n";
if (min_val == 0 && max_val == 0) {
min_max_channel_values( create_mask( input_image, nodata_value), min_val, max_val);
vw_out() << "\t--> DEM color map range: [" << min_val << " " << max_val << "]\n";
} else {
vw_out() << "\t--> Using user-specified color map range: [" << min_val << " " << max_val << "]\n";
}
ImageViewRef<PixelMask<PixelGray<float> > > dem;
DiskImageResource *disk_dem_rsrc = DiskImageResource::open(input_file_name);
if (vm.count("nodata-value")) {
vw_out() << "\t--> Masking nodata value: " << nodata_value << ".\n";
dem = channel_cast<float>(create_mask(input_image, nodata_value));
} else if ( disk_dem_rsrc->has_nodata_value() ) {
nodata_value = disk_dem_rsrc->nodata_value();
vw_out() << "\t--> Extracted nodata value from file: " << nodata_value << ".\n";
dem = create_mask(input_image, nodata_value);
} else {
dem = pixel_cast<PixelMask<PixelGray<float> > >(input_image);
}
delete disk_dem_rsrc;
ImageViewRef<PixelMask<PixelRGB<float> > > colorized_image = colormap(normalize(dem,min_val,max_val,0,1.0));
if (shaded_relief_file_name != "") {
vw_out() << "\t--> Incorporating hillshading from: " << shaded_relief_file_name << ".\n";
DiskImageView<PixelMask<float> > shaded_relief_image(shaded_relief_file_name);
ImageViewRef<PixelMask<PixelRGB<float> > > shaded_image = copy_mask(colorized_image*apply_mask(shaded_relief_image), shaded_relief_image);
vw_out() << "Writing image color-mapped image: " << output_file_name << "\n";
write_georeferenced_image(output_file_name, channel_cast_rescale<uint8>(shaded_image), georef,
TerminalProgressCallback( "tools.colormap", "Writing:"));
} else {
vw_out() << "Writing image color-mapped image: " << output_file_name << "\n";
write_georeferenced_image(output_file_name, channel_cast_rescale<uint8>(colorized_image), georef,
TerminalProgressCallback( "tools.colormap", "Writing:"));
}
}
void save_legend() {
min_val = 0.0;
max_val = 1.0;
ImageView<PixelGray<float> > img(200, 500);
for (int j = 0; j < img.rows(); ++j) {
float val = float(j) / img.rows();
for (int i = 0; i < img.cols(); ++i) {
img(i,j) = val;
}
}
ImageViewRef<PixelMask<PixelRGB<float> > > colorized_image = colormap(img);
write_image("legend.png", channel_cast_rescale<uint8>(apply_mask(colorized_image)));
}
int main( int argc, char *argv[] ) {
set_debug_level(VerboseDebugMessage-1);
po::options_description desc("Description: Produces a colorized image of a DEM \n\nUsage: colormap [options] <input file> \n\nOptions");
desc.add_options()
("help,h", "Display this help message")
("input-file", po::value<std::string>(&input_file_name), "Explicitly specify the input file")
("shaded-relief-file,s", po::value<std::string>(&shaded_relief_file_name)->default_value(""), "Specify a shaded relief image (grayscale) to apply to the colorized image.")
("output-file,o", po::value<std::string>(&output_file_name), "Specify the output file")
("nodata-value", po::value<float>(&nodata_value), "Remap the DEM default value to the min altitude value.")
("min", po::value<float>(&min_val), "Minimum height of the color map.")
("max", po::value<float>(&max_val), "Maximum height of the color map.")
("moon", "Set the min and max values to [-8499 10208] meters, which is suitable for covering elevations on the Moon.")
("mars", "Set the min and max values to [-8208 21249] meters, which is suitable for covering elevations on Mars.")
("legend", "Generate the colormap legend. This image is saved (without labels) as \'legend.png\'")
("verbose", "Verbose output");
po::positional_options_description p;
p.add("input-file", 1);
po::variables_map vm;
po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );
po::notify( vm );
if( vm.count("help") ) {
std::cout << desc << std::endl;
return 1;
}
if( vm.count("legend") ) {
std::cout << "\t--> Saving legend file to disk as \'legend.png\'\n";
save_legend();
exit(0);
}
// This is a reasonable range of elevation values to cover global
// lunar topography.
if( vm.count("moon") ) {
min_val = -8499;
max_val = 10208;
}
// This is a reasonable range of elevation values to cover global
// mars topography.
if( vm.count("mars") ) {
min_val = -8208;
max_val = 21249;
}
if( vm.count("input-file") != 1 ) {
std::cout << "Error: Must specify exactly one input file!\n" << std::endl;
std::cout << desc << std::endl;
return 1;
}
if( output_file_name == "" ) {
output_file_name = prefix_from_filename(input_file_name) + "_CMAP.tif";
}
if( vm.count("verbose") ) {
set_debug_level(VerboseDebugMessage);
}
try {
// Get the right pixel/channel type.
DiskImageResource *rsrc = DiskImageResource::open(input_file_name);
ChannelTypeEnum channel_type = rsrc->channel_type();
PixelFormatEnum pixel_format = rsrc->pixel_format();
delete rsrc;
switch(pixel_format) {
case VW_PIXEL_GRAY:
switch(channel_type) {
case VW_CHANNEL_UINT8: do_colorized_dem<PixelGray<uint8> >(vm); break;
case VW_CHANNEL_INT16: do_colorized_dem<PixelGray<int16> >(vm); break;
case VW_CHANNEL_UINT16: do_colorized_dem<PixelGray<uint16> >(vm); break;
default: do_colorized_dem<PixelGray<float32> >(vm); break;
}
break;
default:
std::cout << "Error: Unsupported pixel format. The DEM image must have only one channel.";
exit(0);
}
}
catch( Exception& e ) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
<commit_msg>Nodata values were not detected prior to autoscaling in colormap. Fixed this by shuffling things around.<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <cstdlib>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <vw/Core/Functors.h>
#include <vw/Image/Algorithms.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/ImageViewRef.h>
#include <vw/Image/PerPixelViews.h>
#include <vw/Image/PixelMask.h>
#include <vw/Image/MaskViews.h>
#include <vw/Image/PixelTypes.h>
#include <vw/Image/Statistics.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/Cartography/FileIO.h>
#include <vw/Cartography/GeoReference.h>
using namespace vw;
// Global variables
std::string input_file_name, output_file_name = "", shaded_relief_file_name;
float nodata_value;
float min_val = 0, max_val = 0;
// Useful functions
/// Erases a file suffix if one exists and returns the base string
static std::string prefix_from_filename(std::string const& filename) {
std::string result = filename;
int index = result.rfind(".");
if (index != -1)
result.erase(index, result.size());
return result;
}
// Colormap function
class ColormapFunc : public ReturnFixedType<PixelMask<PixelRGB<float> > > {
public:
ColormapFunc() {}
template <class PixelT>
PixelMask<PixelRGB<float> > operator() (PixelT const& pix) const {
if (is_transparent(pix))
return PixelMask<PixelRGB<float> >();
float val = compound_select_channel<const float&>(pix,0);
if (val > 1.0) val = 1.0;
if (val < 0.0) val = 0.0;
Vector2 red_range(3/8.0, 1.0);
Vector2 green_range(2/8.0, 6/8.0);
Vector2 blue_range(0.0, 5/8.0);
float red_span = red_range[1] - red_range[0];
float blue_span = blue_range[1] - blue_range[0];
float green_span = green_range[1] - green_range[0];
float red = 0;
float green = 0;
float blue = 0;
// Red
if (val >= red_range[0] && val <= red_range[0]+red_span/3)
red = (val-red_range[0])/(red_span/3);
if (val >= red_range[0]+red_span/3 && val <= red_range[0]+2*red_span/3)
red = 1.0;
if (val >= red_range[0]+2*red_span/3 && val <= red_range[1])
red = 1-((val-(red_range[0]+2*red_span/3))/(red_span/3));
// Blue
if (val >= blue_range[0] && val <= blue_range[0]+blue_span/3)
blue = (val-blue_range[0])/(blue_span/3);
if (val >= blue_range[0]+blue_span/3 && val <= blue_range[0]+2*blue_span/3)
blue = 1.0;
if (val >= blue_range[0]+2*blue_span/3 && val <= blue_range[1])
blue = 1-((val-(blue_range[0]+2*blue_span/3))/(blue_span/3));
// Green
if (val >= green_range[0] && val <= green_range[0]+green_span/3)
green = (val-green_range[0])/(green_span/3);
if (val >= green_range[0]+green_span/3 && val <= green_range[0]+2*green_span/3)
green = 1.0;
if (val >= green_range[0]+2*green_span/3 && val <= green_range[1])
green = 1-((val-(green_range[0]+2*green_span/3))/(green_span/3));
return PixelRGB<float> ( red, green, blue );
}
};
template <class ViewT>
UnaryPerPixelView<ViewT, ColormapFunc> colormap(ImageViewBase<ViewT> const& view) {
return UnaryPerPixelView<ViewT, ColormapFunc>(view.impl(), ColormapFunc());
}
// ---------------------------------------------------------------------------------------------------
template <class PixelT>
void do_colorized_dem(po::variables_map const& vm) {
vw_out() << "Creating colorized DEM.\n";
cartography::GeoReference georef;
cartography::read_georeference(georef, input_file_name);
// Attempt to extract nodata value
DiskImageResource *disk_dem_rsrc = DiskImageResource::open(input_file_name);
if (vm.count("nodata-value")) {
vw_out() << "\t--> Using user-supplied nodata value: " << nodata_value << ".\n";
} else if ( disk_dem_rsrc->has_nodata_value() ) {
nodata_value = disk_dem_rsrc->nodata_value();
vw_out() << "\t--> Extracted nodata value from file: " << nodata_value << ".\n";
}
// Compute min/max
DiskImageView<PixelT> disk_dem_file(input_file_name);
ImageViewRef<PixelGray<float> > input_image = channel_cast<float>(disk_dem_file);
if (min_val == 0 && max_val == 0) {
min_max_channel_values( create_mask( input_image, nodata_value), min_val, max_val);
vw_out() << "\t--> DEM color map range: [" << min_val << " " << max_val << "]\n";
} else {
vw_out() << "\t--> Using user-specified color map range: [" << min_val << " " << max_val << "]\n";
}
ImageViewRef<PixelMask<PixelGray<float> > > dem;
if (vm.count("nodata-value")) {
dem = channel_cast<float>(create_mask(input_image, nodata_value));
} else if ( disk_dem_rsrc->has_nodata_value() ) {
dem = create_mask(input_image, nodata_value);
} else {
dem = pixel_cast<PixelMask<PixelGray<float> > >(input_image);
}
delete disk_dem_rsrc;
ImageViewRef<PixelMask<PixelRGB<float> > > colorized_image = colormap(normalize(dem,min_val,max_val,0,1.0));
if (shaded_relief_file_name != "") {
vw_out() << "\t--> Incorporating hillshading from: " << shaded_relief_file_name << ".\n";
DiskImageView<PixelMask<float> > shaded_relief_image(shaded_relief_file_name);
ImageViewRef<PixelMask<PixelRGB<float> > > shaded_image = copy_mask(colorized_image*apply_mask(shaded_relief_image), shaded_relief_image);
vw_out() << "Writing image color-mapped image: " << output_file_name << "\n";
write_georeferenced_image(output_file_name, channel_cast_rescale<uint8>(shaded_image), georef,
TerminalProgressCallback( "tools.colormap", "Writing:"));
} else {
vw_out() << "Writing image color-mapped image: " << output_file_name << "\n";
write_georeferenced_image(output_file_name, channel_cast_rescale<uint8>(colorized_image), georef,
TerminalProgressCallback( "tools.colormap", "Writing:"));
}
}
void save_legend() {
min_val = 0.0;
max_val = 1.0;
ImageView<PixelGray<float> > img(200, 500);
for (int j = 0; j < img.rows(); ++j) {
float val = float(j) / img.rows();
for (int i = 0; i < img.cols(); ++i) {
img(i,j) = val;
}
}
ImageViewRef<PixelMask<PixelRGB<float> > > colorized_image = colormap(img);
write_image("legend.png", channel_cast_rescale<uint8>(apply_mask(colorized_image)));
}
int main( int argc, char *argv[] ) {
set_debug_level(VerboseDebugMessage-1);
po::options_description desc("Description: Produces a colorized image of a DEM \n\nUsage: colormap [options] <input file> \n\nOptions");
desc.add_options()
("help,h", "Display this help message")
("input-file", po::value<std::string>(&input_file_name), "Explicitly specify the input file")
("shaded-relief-file,s", po::value<std::string>(&shaded_relief_file_name)->default_value(""), "Specify a shaded relief image (grayscale) to apply to the colorized image.")
("output-file,o", po::value<std::string>(&output_file_name), "Specify the output file")
("nodata-value", po::value<float>(&nodata_value), "Remap the DEM default value to the min altitude value.")
("min", po::value<float>(&min_val), "Minimum height of the color map.")
("max", po::value<float>(&max_val), "Maximum height of the color map.")
("moon", "Set the min and max values to [-8499 10208] meters, which is suitable for covering elevations on the Moon.")
("mars", "Set the min and max values to [-8208 21249] meters, which is suitable for covering elevations on Mars.")
("legend", "Generate the colormap legend. This image is saved (without labels) as \'legend.png\'")
("verbose", "Verbose output");
po::positional_options_description p;
p.add("input-file", 1);
po::variables_map vm;
po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );
po::notify( vm );
if( vm.count("help") ) {
std::cout << desc << std::endl;
return 1;
}
if( vm.count("legend") ) {
std::cout << "\t--> Saving legend file to disk as \'legend.png\'\n";
save_legend();
exit(0);
}
// This is a reasonable range of elevation values to cover global
// lunar topography.
if( vm.count("moon") ) {
min_val = -8499;
max_val = 10208;
}
// This is a reasonable range of elevation values to cover global
// mars topography.
if( vm.count("mars") ) {
min_val = -8208;
max_val = 21249;
}
if( vm.count("input-file") != 1 ) {
std::cout << "Error: Must specify exactly one input file!\n" << std::endl;
std::cout << desc << std::endl;
return 1;
}
if( output_file_name == "" ) {
output_file_name = prefix_from_filename(input_file_name) + "_CMAP.tif";
}
if( vm.count("verbose") ) {
set_debug_level(VerboseDebugMessage);
}
try {
// Get the right pixel/channel type.
DiskImageResource *rsrc = DiskImageResource::open(input_file_name);
ChannelTypeEnum channel_type = rsrc->channel_type();
PixelFormatEnum pixel_format = rsrc->pixel_format();
delete rsrc;
switch(pixel_format) {
case VW_PIXEL_GRAY:
switch(channel_type) {
case VW_CHANNEL_UINT8: do_colorized_dem<PixelGray<uint8> >(vm); break;
case VW_CHANNEL_INT16: do_colorized_dem<PixelGray<int16> >(vm); break;
case VW_CHANNEL_UINT16: do_colorized_dem<PixelGray<uint16> >(vm); break;
default: do_colorized_dem<PixelGray<float32> >(vm); break;
}
break;
default:
std::cout << "Error: Unsupported pixel format. The DEM image must have only one channel.";
exit(0);
}
}
catch( Exception& e ) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <node_version.h>
#if NODE_VERSION_AT_LEAST(0, 11, 1) && !defined(_MSC_VER)
#include <sys/types.h>
#endif
#include <v8.h>
#include <node.h>
#include <errno.h>
#include "nan.h"
#if defined(_MSC_VER)
#include <time.h>
#include <windows.h>
// The closest thing to gettimeofday in Windows is GetSystemTimeAsFileTime
// so stub out a gettimeofday() method that uses this
// NOTE: When I tested on Windows XP, it only gave me about 10ms accuracy
// (but at least it compiles)
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz) {
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
unsigned long long t = ft.dwHighDateTime;
t <<= 32;
t |= ft.dwLowDateTime;
t /= 10;
t -= 11644473600000000ULL;
tv->tv_sec = (long) (t / 1000000UL);
tv->tv_usec = (long) (t % 1000000UL);
return 0;
}
#else
#include <sys/time.h>
#endif
static NAN_METHOD(Now) {
NanScope();
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
NanThrowError(node::ErrnoException(errno, "gettimeofday"));
NanReturnUndefined();
}
NanReturnValue(NanNew<v8::Number>((t.tv_sec * 1000000.0) + t.tv_usec));
}
static NAN_METHOD(NowDouble) {
NanScope();
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
NanThrowError(node::ErrnoException(errno, "gettimeofday"));
NanReturnUndefined();
}
NanReturnValue(NanNew<v8::Number>(t.tv_sec + (t.tv_usec * 0.000001)));
}
static NAN_METHOD(NowStruct) {
NanScope();
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
NanThrowError(node::ErrnoException(errno, "gettimeofday"));
NanReturnUndefined();
}
v8::Local<v8::Array> array = NanNew<v8::Array>(2);
array->Set(NanNew<v8::Integer>(0), NanNew<v8::Number>((double)t.tv_sec));
array->Set(NanNew<v8::Integer>(1), NanNew<v8::Number>((double)t.tv_usec));
NanReturnValue(array);
}
extern "C"
void init( v8::Handle<v8::Object> target ) {
NanScope();
NODE_SET_METHOD(target, "now", Now);
NODE_SET_METHOD(target, "nowDouble", NowDouble);
NODE_SET_METHOD(target, "nowStruct", NowStruct);
}
NODE_MODULE(microtime,init)
<commit_msg>cleanup<commit_after>#include <node_version.h>
#if NODE_VERSION_AT_LEAST(0, 11, 1) && !defined(_MSC_VER)
#include <sys/types.h>
#endif
#include <v8.h>
#include <node.h>
#include <errno.h>
#include "nan.h"
#if defined(_MSC_VER)
#include <time.h>
#include <windows.h>
// The closest thing to gettimeofday in Windows is GetSystemTimeAsFileTime
// so stub out a gettimeofday() method that uses this
// NOTE: When I tested on Windows XP, it only gave me about 10ms accuracy
// (but at least it compiles)
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz) {
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
unsigned long long t = ft.dwHighDateTime;
t <<= 32;
t |= ft.dwLowDateTime;
t /= 10;
t -= 11644473600000000ULL;
tv->tv_sec = (long) (t / 1000000UL);
tv->tv_usec = (long) (t % 1000000UL);
return 0;
}
#else
#include <sys/time.h>
#endif
static NAN_METHOD(Now) {
NanScope();
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
NanThrowError(node::ErrnoException(errno, "gettimeofday"));
NanReturnUndefined();
}
NanReturnValue(NanNew<v8::Number>((t.tv_sec * 1000000.0) + t.tv_usec));
}
static NAN_METHOD(NowDouble) {
NanScope();
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
NanThrowError(node::ErrnoException(errno, "gettimeofday"));
NanReturnUndefined();
}
NanReturnValue(NanNew<v8::Number>(t.tv_sec + (t.tv_usec * 0.000001)));
}
static NAN_METHOD(NowStruct) {
NanScope();
timeval t;
int r = gettimeofday(&t, NULL);
if (r < 0) {
NanThrowError(node::ErrnoException(errno, "gettimeofday"));
NanReturnUndefined();
}
v8::Local<v8::Array> array = NanNew<v8::Array>(2);
array->Set(NanNew<v8::Integer>(0), NanNew<v8::Number>((double)t.tv_sec));
array->Set(NanNew<v8::Integer>(1), NanNew<v8::Number>((double)t.tv_usec));
NanReturnValue(array);
}
void init(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "now", Now);
NODE_SET_METHOD(target, "nowDouble", NowDouble);
NODE_SET_METHOD(target, "nowStruct", NowStruct);
}
NODE_MODULE(microtime,init)
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DATA_H
#define DATA_H
#include "cpp_utils/assert.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "server.hpp"
#include "api.hpp"
namespace budget {
template<typename T>
struct data_handler {
size_t next_id;
std::vector<T> data;
data_handler(const char* module, const char* path) : module(module), path(path) {
// Nothing else to init
};
//data_handler should never be copied
data_handler(const data_handler& rhs) = delete;
data_handler& operator=(const data_handler& rhs) = delete;
bool is_changed() const {
return changed;
}
void set_changed() {
if (is_server_running()) {
force_save();
} else {
changed = true;
}
}
template<typename Functor>
void parse_stream(std::istream& file, Functor f){
next_id = 1;
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
T entry;
f(parts, entry);
if (entry.id >= next_id) {
next_id = entry.id + 1;
}
data.push_back(std::move(entry));
}
}
template<typename Functor>
void load(Functor f){
//Make sure to clear the data first, as load_data can be called
//several times
data.clear();
if(is_server_mode()){
auto res = budget::api_get(std::string("/") + module + "/list/");
if(res.success){
std::stringstream ss(res.result);
parse_stream(ss, f);
}
} else {
auto file_path = path_to_budget_file(path);
if (!file_exists(file_path)) {
next_id = 1;
} else {
std::ifstream file(file_path);
if (file.is_open()) {
if (file.good()) {
// We do not use the next_id saved anymore
// Simply consume it
size_t fake;
file >> fake;
file.get();
parse_stream(file, f);
}
}
}
}
}
void load(){
load([](std::vector<std::string>& parts, T& entry){ parts >> entry; });
}
void force_save() {
if (budget::config_contains("random")) {
std::cerr << "budget: error: Saving is disabled in random mode" << std::endl;
return;
}
auto file_path = path_to_budget_file(path);
std::ofstream file(file_path);
// We still save the file ID so that it's still compatible with older versions for now
file << next_id << std::endl;
for (auto& entry : data) {
file << entry << std::endl;
}
changed = false;
}
void save() {
if (is_changed()) {
force_save();
}
}
size_t size() const {
return data.size();
}
decltype(auto) begin() {
return data.begin();
}
decltype(auto) begin() const {
return data.begin();
}
decltype(auto) end() {
return data.end();
}
decltype(auto) end() const {
return data.end();
}
const char* get_module() const {
return module;
}
private:
const char* module;
const char* path;
bool changed = false;
};
template<typename T>
bool exists(const data_handler<T>& data, size_t id){
for(auto& entry : data.data){
if(entry.id == id){
return true;
}
}
return false;
}
template<typename T>
void remove(data_handler<T>& data, size_t id){
data.data.erase(std::remove_if(data.data.begin(), data.data.end(),
[id](const T& entry){ return entry.id == id; }), data.data.end());
data.set_changed();
}
template<typename T>
T& get(data_handler<T>& data, size_t id){
for(auto& value : data.data){
if(value.id == id){
return value;
}
}
cpp_unreachable("The data must exists");
}
template<typename T>
size_t add_data(data_handler<T>& data, T&& entry){
if (is_server_mode()) {
auto params = entry.get_params();
auto res = budget::api_post(std::string("/") + data.get_module() + "/add/", params);
if (!res.success) {
std::cerr << "error: Failed to add expense" << std::endl;
entry.id = 0;
} else {
entry.id = budget::to_number<size_t>(res.result);
data.data.push_back(std::forward<T>(entry));
}
} else {
entry.id = data.next_id++;
data.data.push_back(std::forward<T>(entry));
data.set_changed();
}
return entry.id;
}
} //end of namespace budget
#endif
<commit_msg>Cleanup mode handling in data<commit_after>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DATA_H
#define DATA_H
#include "cpp_utils/assert.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "server.hpp"
#include "api.hpp"
namespace budget {
template<typename T>
struct data_handler {
size_t next_id;
std::vector<T> data;
data_handler(const char* module, const char* path) : module(module), path(path) {
// Nothing else to init
};
//data_handler should never be copied
data_handler(const data_handler& rhs) = delete;
data_handler& operator=(const data_handler& rhs) = delete;
bool is_changed() const {
return changed;
}
void set_changed() {
if (is_server_running()) {
force_save();
} else {
changed = true;
}
}
template<typename Functor>
void parse_stream(std::istream& file, Functor f){
next_id = 1;
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
T entry;
f(parts, entry);
if (entry.id >= next_id) {
next_id = entry.id + 1;
}
data.push_back(std::move(entry));
}
}
template<typename Functor>
void load(Functor f){
//Make sure to clear the data first, as load_data can be called
//several times
data.clear();
if(is_server_mode()){
auto res = budget::api_get(std::string("/") + module + "/list/");
if(res.success){
std::stringstream ss(res.result);
parse_stream(ss, f);
}
} else {
auto file_path = path_to_budget_file(path);
if (!file_exists(file_path)) {
next_id = 1;
} else {
std::ifstream file(file_path);
if (file.is_open()) {
if (file.good()) {
// We do not use the next_id saved anymore
// Simply consume it
size_t fake;
file >> fake;
file.get();
parse_stream(file, f);
}
}
}
}
}
void load(){
load([](std::vector<std::string>& parts, T& entry){ parts >> entry; });
}
void force_save() {
cpp_assert(!is_server_mode(), "force_save() should never be called in server mode");
if (budget::config_contains("random")) {
std::cerr << "budget: error: Saving is disabled in random mode" << std::endl;
return;
}
auto file_path = path_to_budget_file(path);
std::ofstream file(file_path);
// We still save the file ID so that it's still compatible with older versions for now
file << next_id << std::endl;
for (auto& entry : data) {
file << entry << std::endl;
}
changed = false;
}
void save() {
// In server mode, there is nothing to do
if (is_server_mode()) {
// It shoud not be changed
cpp_assert(!is_changed(), "in server mode, is_changed() should never be true");
return;
}
// In other modes, save if it's changed
if (is_changed()) {
force_save();
}
}
size_t size() const {
return data.size();
}
decltype(auto) begin() {
return data.begin();
}
decltype(auto) begin() const {
return data.begin();
}
decltype(auto) end() {
return data.end();
}
decltype(auto) end() const {
return data.end();
}
const char* get_module() const {
return module;
}
private:
const char* module;
const char* path;
bool changed = false;
};
template<typename T>
bool exists(const data_handler<T>& data, size_t id){
for(auto& entry : data.data){
if(entry.id == id){
return true;
}
}
return false;
}
template<typename T>
void remove(data_handler<T>& data, size_t id){
data.data.erase(std::remove_if(data.data.begin(), data.data.end(),
[id](const T& entry){ return entry.id == id; }), data.data.end());
data.set_changed();
}
template<typename T>
T& get(data_handler<T>& data, size_t id){
for(auto& value : data.data){
if(value.id == id){
return value;
}
}
cpp_unreachable("The data must exists");
}
template<typename T>
size_t add_data(data_handler<T>& data, T&& entry){
if (is_server_mode()) {
auto params = entry.get_params();
auto res = budget::api_post(std::string("/") + data.get_module() + "/add/", params);
if (!res.success) {
std::cerr << "error: Failed to add expense" << std::endl;
entry.id = 0;
} else {
entry.id = budget::to_number<size_t>(res.result);
data.data.push_back(std::forward<T>(entry));
}
} else {
entry.id = data.next_id++;
data.data.push_back(std::forward<T>(entry));
data.set_changed();
}
return entry.id;
}
} //end of namespace budget
#endif
<|endoftext|> |
<commit_before>/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "pageview.h"
#include <QAction>
#include <QHeaderView>
#include <QLineEdit>
#include <QTreeView>
#include <QVBoxLayout>
#include <QMessageBox>
#include "filterwidget.h"
#include "itemdelegate.h"
#include "presentation/artifactfilterproxymodel.h"
#include "presentation/metatypes.h"
#include "presentation/querytreemodelbase.h"
using namespace Widgets;
PageView::PageView(QWidget *parent)
: QWidget(parent),
m_filterWidget(new FilterWidget(this)),
m_centralView(new QTreeView(this)),
m_quickAddEdit(new QLineEdit(this))
{
m_filterWidget->setObjectName("filterWidget");
m_centralView->setObjectName("centralView");
m_centralView->header()->hide();
m_centralView->setAlternatingRowColors(true);
m_centralView->setItemDelegate(new ItemDelegate(this));
m_centralView->setDragDropMode(QTreeView::DragDrop);
m_centralView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_centralView->setModel(m_filterWidget->proxyModel());
m_quickAddEdit->setObjectName("quickAddEdit");
m_quickAddEdit->setPlaceholderText(tr("Type and press enter to add an action"));
connect(m_quickAddEdit, SIGNAL(editingFinished()), this, SLOT(onEditingFinished()));
auto layout = new QVBoxLayout;
layout->addWidget(m_filterWidget);
layout->addWidget(m_centralView);
layout->addWidget(m_quickAddEdit);
setLayout(layout);
QAction *removeItemAction = new QAction(this);
removeItemAction->setShortcut(Qt::Key_Delete);
connect(removeItemAction, SIGNAL(triggered()), this, SLOT(onRemoveItemRequested()));
addAction(removeItemAction);
m_askConfirmationFunction = [] (const QString &text, QWidget *parent) -> int {
QString title = tr("Delete Tasks");
return QMessageBox::question(parent, title, text, QMessageBox::Yes | QMessageBox::No);
};
}
QObject *PageView::model() const
{
return m_model;
}
void PageView::setModel(QObject *model)
{
if (model == m_model)
return;
if (m_centralView->selectionModel()) {
disconnect(m_centralView->selectionModel(), 0, this, 0);
}
m_filterWidget->proxyModel()->setSourceModel(0);
m_model = model;
if (!m_model)
return;
QVariant modelProperty = m_model->property("centralListModel");
if (modelProperty.canConvert<QAbstractItemModel*>())
m_filterWidget->proxyModel()->setSourceModel(modelProperty.value<QAbstractItemModel*>());
connect(m_centralView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(onCurrentChanged(QModelIndex)));
}
PageView::AskConfirmationFunction PageView::askConfirmationFunction() const
{
return m_askConfirmationFunction;
}
void PageView::setAskConfirmationFunction(const PageView::AskConfirmationFunction &askConfirmationFunction)
{
m_askConfirmationFunction = askConfirmationFunction;
}
void PageView::onEditingFinished()
{
if (m_quickAddEdit->text().isEmpty())
return;
QMetaObject::invokeMethod(m_model, "addTask", Q_ARG(QString, m_quickAddEdit->text()));
m_quickAddEdit->clear();
}
void PageView::onRemoveItemRequested()
{
const QModelIndexList ¤tIndexes = m_centralView->selectionModel()->selectedIndexes();
if (currentIndexes.isEmpty())
return;
QString text;
if (currentIndexes.size() > 1) {
bool hasDescendants = false;
foreach (const QModelIndex ¤tIndex, currentIndexes) {
if (!currentIndex.isValid())
continue;
if (currentIndex.model()->rowCount(currentIndex) > 0) {
hasDescendants = true;
break;
}
}
if (hasDescendants)
text = tr("Do you really want to delete the selected items and their children?");
else
text = tr("Do you really want to delete the selected items?");
} else {
const QModelIndex ¤tIndex = currentIndexes.first();
if (!currentIndex.isValid())
return;
if (currentIndex.model()->rowCount(currentIndex) > 0)
text = tr("Do you really want to delete the selected task and all its children?");
}
if (!text.isEmpty()) {
int button = m_askConfirmationFunction(text, this);
bool canRemove = (button == QMessageBox::Yes);
if (!canRemove)
return;
}
foreach (const QModelIndex ¤tIndex, currentIndexes) {
if (!currentIndex.isValid())
continue;
QMetaObject::invokeMethod(m_model, "removeItem", Q_ARG(QModelIndex, currentIndex));
}
}
void PageView::onCurrentChanged(const QModelIndex ¤t)
{
auto data = current.data(Presentation::QueryTreeModelBase::ObjectRole);
if (!data.isValid())
return;
auto artifact = data.value<Domain::Artifact::Ptr>();
if (!artifact)
return;
emit currentArtifactChanged(artifact);
}
<commit_msg>Fix uninitialized variable<commit_after>/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <ervin@kde.org>
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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "pageview.h"
#include <QAction>
#include <QHeaderView>
#include <QLineEdit>
#include <QTreeView>
#include <QVBoxLayout>
#include <QMessageBox>
#include "filterwidget.h"
#include "itemdelegate.h"
#include "presentation/artifactfilterproxymodel.h"
#include "presentation/metatypes.h"
#include "presentation/querytreemodelbase.h"
using namespace Widgets;
PageView::PageView(QWidget *parent)
: QWidget(parent),
m_model(0),
m_filterWidget(new FilterWidget(this)),
m_centralView(new QTreeView(this)),
m_quickAddEdit(new QLineEdit(this))
{
m_filterWidget->setObjectName("filterWidget");
m_centralView->setObjectName("centralView");
m_centralView->header()->hide();
m_centralView->setAlternatingRowColors(true);
m_centralView->setItemDelegate(new ItemDelegate(this));
m_centralView->setDragDropMode(QTreeView::DragDrop);
m_centralView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_centralView->setModel(m_filterWidget->proxyModel());
m_quickAddEdit->setObjectName("quickAddEdit");
m_quickAddEdit->setPlaceholderText(tr("Type and press enter to add an action"));
connect(m_quickAddEdit, SIGNAL(editingFinished()), this, SLOT(onEditingFinished()));
auto layout = new QVBoxLayout;
layout->addWidget(m_filterWidget);
layout->addWidget(m_centralView);
layout->addWidget(m_quickAddEdit);
setLayout(layout);
QAction *removeItemAction = new QAction(this);
removeItemAction->setShortcut(Qt::Key_Delete);
connect(removeItemAction, SIGNAL(triggered()), this, SLOT(onRemoveItemRequested()));
addAction(removeItemAction);
m_askConfirmationFunction = [] (const QString &text, QWidget *parent) -> int {
QString title = tr("Delete Tasks");
return QMessageBox::question(parent, title, text, QMessageBox::Yes | QMessageBox::No);
};
}
QObject *PageView::model() const
{
return m_model;
}
void PageView::setModel(QObject *model)
{
if (model == m_model)
return;
if (m_centralView->selectionModel()) {
disconnect(m_centralView->selectionModel(), 0, this, 0);
}
m_filterWidget->proxyModel()->setSourceModel(0);
m_model = model;
if (!m_model)
return;
QVariant modelProperty = m_model->property("centralListModel");
if (modelProperty.canConvert<QAbstractItemModel*>())
m_filterWidget->proxyModel()->setSourceModel(modelProperty.value<QAbstractItemModel*>());
connect(m_centralView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(onCurrentChanged(QModelIndex)));
}
PageView::AskConfirmationFunction PageView::askConfirmationFunction() const
{
return m_askConfirmationFunction;
}
void PageView::setAskConfirmationFunction(const PageView::AskConfirmationFunction &askConfirmationFunction)
{
m_askConfirmationFunction = askConfirmationFunction;
}
void PageView::onEditingFinished()
{
if (m_quickAddEdit->text().isEmpty())
return;
QMetaObject::invokeMethod(m_model, "addTask", Q_ARG(QString, m_quickAddEdit->text()));
m_quickAddEdit->clear();
}
void PageView::onRemoveItemRequested()
{
const QModelIndexList ¤tIndexes = m_centralView->selectionModel()->selectedIndexes();
if (currentIndexes.isEmpty())
return;
QString text;
if (currentIndexes.size() > 1) {
bool hasDescendants = false;
foreach (const QModelIndex ¤tIndex, currentIndexes) {
if (!currentIndex.isValid())
continue;
if (currentIndex.model()->rowCount(currentIndex) > 0) {
hasDescendants = true;
break;
}
}
if (hasDescendants)
text = tr("Do you really want to delete the selected items and their children?");
else
text = tr("Do you really want to delete the selected items?");
} else {
const QModelIndex ¤tIndex = currentIndexes.first();
if (!currentIndex.isValid())
return;
if (currentIndex.model()->rowCount(currentIndex) > 0)
text = tr("Do you really want to delete the selected task and all its children?");
}
if (!text.isEmpty()) {
int button = m_askConfirmationFunction(text, this);
bool canRemove = (button == QMessageBox::Yes);
if (!canRemove)
return;
}
foreach (const QModelIndex ¤tIndex, currentIndexes) {
if (!currentIndex.isValid())
continue;
QMetaObject::invokeMethod(m_model, "removeItem", Q_ARG(QModelIndex, currentIndex));
}
}
void PageView::onCurrentChanged(const QModelIndex ¤t)
{
auto data = current.data(Presentation::QueryTreeModelBase::ObjectRole);
if (!data.isValid())
return;
auto artifact = data.value<Domain::Artifact::Ptr>();
if (!artifact)
return;
emit currentArtifactChanged(artifact);
}
<|endoftext|> |
<commit_before>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>
namespace bts
{
#define MAX_MOMENTUM_NONCE (1<<26)
#define SEARCH_SPACE_BITS 50
#define BIRTHDAYS_PER_HASH 8
// I'm a terrible person.
#define UPDATE_HASH(varname) \
if (varname##_offset >= BIRTHDAYS_PER_HASH) { \
varname##_offset = varname##_offset % BIRTHDAYS_PER_HASH; \
varname##_nonce = (varname##_minhash >> (64 - SEARCH_SPACE_BITS)); \
\
*index = varname##_nonce; \
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash); \
\
varname##_minhash = result_hash[0]; \
for (unsigned int sz = 0; sz < BIRTHDAYS_PER_HASH; ++sz) { \
if (result_hash[sz] < varname##_minhash) { \
varname##_minhash = result_hash[sz]; \
} \
varname##_hash[sz] = result_hash[sz]; \
} \
}
std::vector< std::pair<uint32_t, uint32_t> > momentum_search(uint256 midHash)
{
std::vector< std::pair<uint32_t, uint32_t> > results;
char hash_tmp[sizeof(midHash) + 4];
memcpy((char *)&hash_tmp[4], (char *)&midHash, sizeof(midHash));
uint32_t *index = (uint32_t *)hash_tmp;
bool found_hit = false;
uint32_t i = 0;
while (true) { // Stops after i = MAX_MOMENTUM_NONCE
// X
uint32_t turtle_nonce = i - (i % BIRTHDAYS_PER_HASH);
uint32_t turtle_offset = (i % BIRTHDAYS_PER_HASH);
uint64_t turtle_minhash = 0;
uint64_t turtle_hash[8];
// X'
uint32_t hare_nonce = i - (i % BIRTHDAYS_PER_HASH);
uint32_t hare_offset = (i % BIRTHDAYS_PER_HASH);
uint64_t hare_minhash = 0;
uint64_t hare_hash[8];
// Defining X_0
*index = i;
uint64_t result_hash[8];
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)result_hash);
turtle_minhash = result_hash[0];
hare_minhash = result_hash[0];
for (unsigned int sz = 0; sz < BIRTHDAYS_PER_HASH; ++sz) {
turtle_hash[sz] = result_hash[sz];
hare_hash[sz] = result_hash[sz];
if (result_hash[sz] < turtle_minhash) {
turtle_minhash = result_hash[sz];
hare_minhash = result_hash[sz];
}
}
// Step 1: dig for a hit
// Not using 2^(SEARCH_SPACE_BITS/2)
for(; i < MAX_MOMENTUM_NONCE; ++i) {
// TURTLE
// X = H(X)
++turtle_offset;
UPDATE_HASH(turtle);
// HARE
// X' = H( H(X) )
hare_offset += 2;
UPDATE_HASH(hare);
// Found a collision!
if ((turtle_hash[turtle_offset] >> (64 - SEARCH_SPACE_BITS)) == (hare_hash[hare_offset] >> (64 - SEARCH_SPACE_BITS))) {
// Are we stuck in a loop or find an actual collision?
if (turtle_nonce != hare_nonce && turtle_offset != hare_offset) {
std::cerr << "Collision found!\n";
std::cerr << " Iteration: " << i << "\n";
std::cerr << " Turtle Nonce: " << turtle_nonce << "\n";
std::cerr << " Turtle Offset: " << turtle_offset << "\n";
std::cerr << " Turtle Hash: " << (turtle_hash[turtle_offset] >> (64 - SEARCH_SPACE_BITS)) << "\n";
std::cerr << " Turtle Nonce Valid: " << (turtle_nonce < MAX_MOMENTUM_NONCE ? "YES" : "NO") << "\n";
std::cerr << " Hare Nonce: " << hare_nonce << "\n";
std::cerr << " Hare Offset: " << hare_offset << "\n";
std::cerr << " Hare Hash: " << (hare_hash[hare_offset] >> (64 - SEARCH_SPACE_BITS)) << "\n";
std::cerr << " Hare Nonce Valid: " << (hare_nonce < MAX_MOMENTUM_NONCE ? "YES" : "NO") << "\n";
found_hit = true;
results.push_back( std::make_pair(turtle_nonce + turtle_offset, hare_nonce + hare_offset) );
}
// Either way, go get a new nonce
break;
}
}
// Keep scanning until we do MAX_MOMENTUM_NONCE checks
if (i >= MAX_MOMENTUM_NONCE) {
std::cerr << "Search complete. Collisions found: " << results.size() << "\n";
return results;
}
}
return results;
}
uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a)
{
uint32_t index = a - (a % 8);
char hash_tmp[sizeof(midHash) + 4];
memcpy(&hash_tmp[4], (char *)&midHash, sizeof(midHash));
memcpy(&hash_tmp[0], (char *)&index, sizeof(index));
uint64_t result_hash[8];
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)&result_hash);
uint64_t r = result_hash[a % BIRTHDAYS_PER_HASH] >> (64 - SEARCH_SPACE_BITS);
return r;
}
bool momentum_verify(uint256 head, uint32_t a, uint32_t b)
{
if(a == b) {
return false;
}
if(a > MAX_MOMENTUM_NONCE) {
return false;
}
if(b > MAX_MOMENTUM_NONCE) {
return false;
}
bool r = (getBirthdayHash(head, a) == getBirthdayHash(head, b));
return r;
}
}
<commit_msg>Complete rewrite using Floyd's Algorithm<commit_after>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>
namespace bts
{
uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a);
#define MAX_MOMENTUM_NONCE ( 1<<26 )
#define SEARCH_SPACE_BITS ( 50 )
#define BIRTHDAYS_PER_HASH ( 8 )
#define DEBUG_MODE ( 0 )
///// UTILITY FUNCTIONS /////
// Compresses "hash" to within MAX_MOMENTUM_NONCE space
#define COMPRESS_CHUNK(chunk) ( chunk % MAX_MOMENTUM_NONCE )
#define COMPRESS_HASH(hash) ( COMPRESS_CHUNK(hash[0]) )
// HASH is a wrapper for SHA512
// It creates BIRTHDAYS_PER_HASH elements, each one
// right shifted by (64 - SEARCH_SPACE_BITS)
#define HASH(input, temp, output) \
{ \
*hash_input = input; \
SHA512((unsigned char *)temp, sizeof(temp), (unsigned char *)output); \
output[0] >>= (64 - SEARCH_SPACE_BITS); \
output[1] >>= (64 - SEARCH_SPACE_BITS); \
output[2] >>= (64 - SEARCH_SPACE_BITS); \
output[3] >>= (64 - SEARCH_SPACE_BITS); \
output[4] >>= (64 - SEARCH_SPACE_BITS); \
output[5] >>= (64 - SEARCH_SPACE_BITS); \
output[6] >>= (64 - SEARCH_SPACE_BITS); \
output[7] >>= (64 - SEARCH_SPACE_BITS); \
}
// Given a hash chunk "cur_hash", if it exists in
// "hash_list", return the index, else -1.
#define CONTAINS_HASH(cur_chunk, hash_list) \
(cur_chunk == hash_list[0] ? 0 : \
cur_chunk == hash_list[1] ? 1 : \
cur_chunk == hash_list[2] ? 2 : \
cur_chunk == hash_list[3] ? 3 : \
cur_chunk == hash_list[4] ? 4 : \
cur_chunk == hash_list[5] ? 5 : \
cur_chunk == hash_list[6] ? 6 : \
cur_chunk == hash_list[7] ? 7 : \
0xFF)
#define PRINT_HASH(hash) \
{ \
std::cerr << " 0: " << hash[0] << "\n" \
<< " 1: " << hash[1] << "\n" \
<< " 2: " << hash[2] << "\n" \
<< " 3: " << hash[3] << "\n" \
<< " 4: " << hash[4] << "\n" \
<< " 5: " << hash[5] << "\n" \
<< " 6: " << hash[6] << "\n" \
<< " 7: " << hash[7] << "\n"; \
}
#define COPY_HASH(src, dst) \
{ \
dst[0] = src[0]; \
dst[1] = src[1]; \
dst[2] = src[2]; \
dst[3] = src[3]; \
dst[4] = src[4]; \
dst[5] = src[5]; \
dst[6] = src[6]; \
dst[7] = src[7]; \
}
///// MAIN HASH /////
std::vector< std::pair<uint32_t, uint32_t> > momentum_search(uint256 midHash)
{
std::vector< std::pair<uint32_t, uint32_t> > results;
boost::unordered_map< uint64_t, uint32_t > rainbow( RAINBOW_ENTRIES );
rainbow.rehash( RAINBOW_ENTRIES );
char hash_temp[sizeof(uint256) + 4];
memcpy((char *)&hash_temp[4], (char *)&midHash, sizeof(midHash));
uint32_t *hash_input = (uint32_t *)hash_temp;
uint64_t result_hash[8];
// Floyd's cycle-finding algorithm
uint32_t power = 1;
uint32_t lam = 1;
uint64_t turtle_hash[8];
uint32_t turtle_nonce = 0;
uint64_t hare_hash[8];
uint32_t hare_nonce = 0;
// Turtle = X_0
HASH(0, hash_temp, turtle_hash);
// Hare = F(X_0)
hare_nonce = COMPRESS(result_hash);
HASH(hare_nonce, hash_temp, hare_hash);
while (power <= MAX_MOMENTUM_NONCE) {
for (uint32_t chunk = 0; chunk < BIRTHDAYS_PER_HASH; ++chunk) {
uint32_t offset = CONTAINS_HASH(hare[chunk], turtle_hash);
if (offset != 0xFF) {
if (DEBUG) {
std::cerr << "Found hit PART 1\n";
std::cerr << "Hare Nonce: " << hare_nonce << " + " << chunk << "\n";
PRINT_HASH(hare_hash);
std::cerr << "Trtl Nonce: " << turtle_nonce << " + " << offset << "\n";
PRITN_HASH(turtle_hash);
}
break;
}
}
if (power == lam) {
COPY_HASH(hare_hash, turtle_hash);
turtle_nonce = hare_nonce;
power <<= 1;
lam = 0;
}
hare_nonce = COMPRESS(hare_hash);
HASH(hare_nonce, hash_temp, hare_hash);
++lam;
}
// Nothing found, give up.
if (power >= MAX_MOMENTUM_NONCE) { return results; }
// Rewind to find first repetition of nonces
turtle_nonce = 0;
HASH(turtle_nonce, hash_temp, turtle_hash);
hare_nonce = 0;
HASH_COPY(turtle_hash, hare_hash);
for (uint32_t fastforward = 0; fastforward < lam; ++fastforward) {
hare_nonce = COMPRESS(hare_hash);
HASH(hare_nonce, hash_temp, hare_hash);
}
while (true) {
for (uint32_t chunk = 0; chunk < BIRTHDAYS_PER_HASH; ++chunk) {
uint32_t offset = CONTAINS_HASH(hare[chunk], turtle_hash);
if (offset != 0xFF) {
if (DEBUG) {
std::cerr << "Found hit PART 2\n";
std::cerr << "Hare Nonce: " << hare_nonce << " + " << chunk << "\n";
PRINT_HASH(hare_hash);
std::cerr << "Trtl Nonce: " << turtle_nonce << " + " << offset << "\n";
PRITN_HASH(turtle_hash);
}
results.push_back( std::make_pair( hare_nonce + chunk, turtle_nonce + offset ) );
return results;
}
}
turtle_nonce = COMPRESS(turtle_hash);
HASH(turtle_nonce, hash_temp, turtle_hash);
hare_nonce = COMPRESS(hare_hash);
HASH(hare_nonce, hash_temp, hare_hash);
}
std::cerr << "You should never be here!\n";
return results;
}
uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a)
{
uint32_t index = a - (a % 8);
char hash_tmp[sizeof(midHash) + 4];
memcpy(&hash_tmp[4], (char *)&midHash, sizeof(midHash));
memcpy(&hash_tmp[0], (char *)&index, sizeof(index));
uint64_t result_hash[8];
SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)&result_hash);
uint64_t r = result_hash[a % BIRTHDAYS_PER_HASH] >> (64 - SEARCH_SPACE_BITS);
return r;
}
bool momentum_verify(uint256 head, uint32_t a, uint32_t b)
{
if(a == b) {
return false;
}
if(a > MAX_MOMENTUM_NONCE) {
return false;
}
if(b > MAX_MOMENTUM_NONCE) {
return false;
}
bool r = (getBirthdayHash(head, a) == getBirthdayHash(head, b));
return r;
}
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// Log.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include <cstdio>
#include "Core/Log.h"
#include "Core/Assert.h"
#include "Core/Logger.h"
#include "Core/Threading/RWLock.h"
#include "Core/Containers/Array.h"
#if ORYOL_WINDOWS
#include "Windows.h"
const Oryol::int32 LogBufSize = 2048;
#endif
#if ORYOL_ANDROID
#include <android/log.h>
#endif
namespace Oryol {
namespace Core {
using namespace std;
Log::Level curLogLevel = Log::Level::Dbg;
RWLock lock;
Array<Ptr<Logger>> loggers;
//------------------------------------------------------------------------------
void
Log::AddLogger(const Ptr<Logger>& l) {
if (l) {
lock.LockWrite();
loggers.AddBack(l);
lock.UnlockWrite();
}
}
//------------------------------------------------------------------------------
int32
Log::GetNumLoggers() {
return loggers.Size();
}
//------------------------------------------------------------------------------
Ptr<Logger>
Log::GetLogger(int32 index) {
return loggers[index];
}
//------------------------------------------------------------------------------
void
Log::SetLogLevel(Level l) {
curLogLevel = l;
}
//------------------------------------------------------------------------------
Log::Level
Log::GetLogLevel() {
return curLogLevel;
}
//------------------------------------------------------------------------------
void
Log::Dbg(const char* msg, ...) {
if (curLogLevel >= Level::Dbg) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Dbg, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::Info(const char* msg, ...) {
if (curLogLevel >= Level::Info) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Info, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::Warn(const char* msg, ...) {
if (curLogLevel >= Level::Warn) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Warn, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::Error(const char* msg, ...) {
if (curLogLevel >= Level::Error) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Error, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::vprint(Level lvl, const char* msg, va_list args) {
lock.LockRead();
if (loggers.Empty()) {
#if ORYOL_ANDROID
android_LogPriority pri = ANDROID_LOG_DEFAULT;
switch (lvl) {
case Level::Error: pri = ANDROID_LOG_ERROR; break;
case Level::Warn: pri = ANDROID_LOG_WARN; break;
case Level::Info: pri = ANDROID_LOG_INFO; break;
case Level::Dbg: pri = ANDROID_LOG_DEBUG; break;
default: pri = ANDROID_LOG_DEFAULT; break;
}
__android_log_vprint(pri, "oryol", msg, args);
#else
std::vprintf(msg, args);
#if ORYOL_WINDOWS
char buf[LogBufSize];
std::vsnprintf(buf, sizeof(buf), msg, args);
buf[LogBufSize - 1] = 0;
OutputDebugString(buf);
#endif
#endif
}
else {
for (auto l : loggers) {
l->VPrint(lvl, msg, args);
}
}
lock.UnlockRead();
}
//------------------------------------------------------------------------------
void
Log::AssertMsg(const char* cond, const char* msg, const char* file, int32 line, const char* func) {
lock.LockRead();
if (loggers.Empty()) {
#if ORYOL_ANDROID
__android_log_print(ANDROID_LOG_FATAL, "oryol", "oryol assert: cond='%s'\nmsg='%s'\nfile='%s'\nline='%d'\nfunc='%s'\n",
cond, msg ? msg : "none", file, line, func);
#else
std::printf("oryol assert: cond='%s'\nmsg='%s'\nfile='%s'\nline='%d'\nfunc='%s'\n",
cond, msg ? msg : "none", file, line, func);
#if ORYOL_WINDOWS
char buf[LogBufSize];
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "oryol assert: cond='%s'\nmsg='%s'\nfile='%s'\nline='%d'\nfunc='%s'\n",
cond, msg ? msg : "none", file, line, func);
buf[LogBufSize - 1] = 0;
OutputDebugString(buf);
#endif
#endif
}
else
{
for (const auto& l : loggers) {
l->AssertMsg(cond, msg, file, line, func);
}
}
lock.UnlockRead();
}
} // namespace Core
} // namespace Oryol
<commit_msg>Added logging support for pnacl, and fixed bug when reusing va_list<commit_after>//------------------------------------------------------------------------------
// Log.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include <cstdio>
#include "Core/Log.h"
#include "Core/Assert.h"
#include "Core/Logger.h"
#include "Core/Threading/RWLock.h"
#include "Core/Containers/Array.h"
#if ORYOL_WINDOWS
#include "Windows.h"
#endif
#if ORYOL_ANDROID
#include <android/log.h>
#endif
#if ORYOL_PNACL
#include "Core/pnacl/pnaclInstance.h"
#endif
#if ORYOL_WINDOWS || ORYOL_PNACL
const Oryol::int32 LogBufSize = 2048;
#endif
namespace Oryol {
namespace Core {
using namespace std;
Log::Level curLogLevel = Log::Level::Dbg;
RWLock lock;
Array<Ptr<Logger>> loggers;
//------------------------------------------------------------------------------
void
Log::AddLogger(const Ptr<Logger>& l) {
if (l) {
lock.LockWrite();
loggers.AddBack(l);
lock.UnlockWrite();
}
}
//------------------------------------------------------------------------------
int32
Log::GetNumLoggers() {
return loggers.Size();
}
//------------------------------------------------------------------------------
Ptr<Logger>
Log::GetLogger(int32 index) {
return loggers[index];
}
//------------------------------------------------------------------------------
void
Log::SetLogLevel(Level l) {
curLogLevel = l;
}
//------------------------------------------------------------------------------
Log::Level
Log::GetLogLevel() {
return curLogLevel;
}
//------------------------------------------------------------------------------
void
Log::Dbg(const char* msg, ...) {
if (curLogLevel >= Level::Dbg) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Dbg, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::Info(const char* msg, ...) {
if (curLogLevel >= Level::Info) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Info, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::Warn(const char* msg, ...) {
if (curLogLevel >= Level::Warn) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Warn, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::Error(const char* msg, ...) {
if (curLogLevel >= Level::Error) {
va_list args;
va_start(args, msg);
Log::vprint(Level::Error, msg, args);
va_end(args);
}
}
//------------------------------------------------------------------------------
void
Log::vprint(Level lvl, const char* msg, va_list args) {
lock.LockRead();
if (loggers.Empty()) {
#if ORYOL_ANDROID
android_LogPriority pri = ANDROID_LOG_DEFAULT;
switch (lvl) {
case Level::Error: pri = ANDROID_LOG_ERROR; break;
case Level::Warn: pri = ANDROID_LOG_WARN; break;
case Level::Info: pri = ANDROID_LOG_INFO; break;
case Level::Dbg: pri = ANDROID_LOG_DEBUG; break;
default: pri = ANDROID_LOG_DEFAULT; break;
}
__android_log_vprint(pri, "oryol", msg, args);
#else
#if ORYOL_WINDOWS || ORYOL_PNACL
va_list argsCopy;
va_copy(argsCopy, args);
#endif
// do the vprintf, this will destroy the original
// va_list, so we made a copy before if necessary
std::vprintf(msg, args);
#if ORYOL_WINDOWS || ORYOL_PNACL
char buf[LogBufSize];
std::vsnprintf(buf, sizeof(buf), msg, argsCopy);
buf[LogBufSize - 1] = 0;
#if ORYOL_WINDOWS
OutputDebugString(buf);
#elif ORYOL_PNACL
if (pnaclInstance::HasInstance()) {
pnaclInstance::Instance()->putMsg(buf);
}
#endif
#endif
#endif
}
else {
for (auto l : loggers) {
l->VPrint(lvl, msg, args);
}
}
lock.UnlockRead();
}
//------------------------------------------------------------------------------
void
Log::AssertMsg(const char* cond, const char* msg, const char* file, int32 line, const char* func) {
lock.LockRead();
if (loggers.Empty()) {
#if ORYOL_ANDROID
__android_log_print(ANDROID_LOG_FATAL, "oryol", "oryol assert: cond='%s'\nmsg='%s'\nfile='%s'\nline='%d'\nfunc='%s'\n",
cond, msg ? msg : "none", file, line, func);
#else
std::printf("oryol assert: cond='%s'\nmsg='%s'\nfile='%s'\nline='%d'\nfunc='%s'\n",
cond, msg ? msg : "none", file, line, func);
#if ORYOL_WINDOWS
char buf[LogBufSize];
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "oryol assert: cond='%s'\nmsg='%s'\nfile='%s'\nline='%d'\nfunc='%s'\n",
cond, msg ? msg : "none", file, line, func);
buf[LogBufSize - 1] = 0;
OutputDebugString(buf);
#elif ORYOL_PNACL
if (pnaclInstance::HasInstance()) {
char buf[LogBufSize];
std::snprintf(buf, sizeof(buf), "oryol assert: cond='%s'\nmsg='%s'\nfile='%s'\nline='%d'\nfunc='%s'\n",
cond, msg ? msg : "none", file, line, func);
buf[LogBufSize - 1] = 0;
pnaclInstance::Instance()->putMsg(buf);
}
#endif
#endif
}
else
{
for (const auto& l : loggers) {
l->AssertMsg(cond, msg, file, line, func);
}
}
lock.UnlockRead();
}
} // namespace Core
} // namespace Oryol
<|endoftext|> |
<commit_before>/*
Copyright (C) 2003-2013 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <sstream>
#include "asserts.hpp"
#include "css_parser.hpp"
#include "xhtml_text_node.hpp"
namespace xhtml
{
namespace {
struct DocumentImpl : public Document
{
DocumentImpl(css::StyleSheetPtr ss) : Document(ss) {}
};
struct DocumentFragmentImpl : public DocumentFragment
{
DocumentFragmentImpl(WeakDocumentPtr owner) : DocumentFragment(owner) {}
};
struct AttributeImpl : public Attribute
{
AttributeImpl(const std::string& name, const std::string& value, WeakDocumentPtr owner) : Attribute(name, value, owner) {}
};
}
Node::Node(NodeId id, WeakDocumentPtr owner)
: id_(id),
children_(),
attributes_(),
left_(),
right_(),
parent_(),
owner_document_(owner),
properties_()
{
}
Node::~Node()
{
}
void Node::addChild(NodePtr child)
{
if(child->id() == NodeId::DOCUMENT_FRAGMENT) {
// we add the children of a document fragment rather than the node itself.
if(children_.empty()) {
children_ = child->children_;
for(auto& c : children_) {
c->setParent(shared_from_this());
}
} else {
if(!child->children_.empty()) {
children_.back()->right_ = child->children_.front();
child->children_.front()->left_ = children_.back();
for(auto& c : child->children_) {
c->setParent(shared_from_this());
}
children_.insert(children_.end(), child->children_.begin(), child->children_.end());
}
}
} else {
child->left_ = child->right_ = std::weak_ptr<Node>();
if(!children_.empty()) {
children_.back()->right_ = child;
child->left_ = children_.back();
}
children_.emplace_back(child);
child->setParent(shared_from_this());
}
}
void Node::addAttribute(AttributePtr a)
{
a->setParent(shared_from_this());
attributes_[a->getName()] = a;
}
void Node::preOrderTraversal(std::function<bool(NodePtr)> fn)
{
// Visit node, visit children.
if(!fn(shared_from_this())) {
return;
}
for(auto& c : children_) {
c->preOrderTraversal(fn);
}
}
void Node::postOrderTraversal(std::function<bool(NodePtr)> fn)
{
// Visit children, then this process node.
for(auto& c : children_) {
c->preOrderTraversal(fn);
}
if(!fn(shared_from_this())) {
return;
}
}
AttributePtr Node::getAttribute(const std::string& name)
{
auto it = attributes_.find(name);
return it != attributes_.end() ? it->second : nullptr;
}
std::string Node::nodeToString() const
{
std::ostringstream ss;
for(auto& a : getAttributes()) {
ss << "{" << a.second->toString() << "}";
}
return ss.str();
}
const std::string& Node::getValue() const
{
static std::string null_str;
return null_str;
}
void Node::normalize()
{
std::vector<NodePtr> new_child_list;
TextPtr new_text_node;
for(auto& c : children_) {
if(c->id() == NodeId::TEXT) {
if(!c->getValue().empty()) {
if(new_text_node) {
new_text_node->addText(c->getValue());
} else {
new_text_node = Text::create(c->getValue(), owner_document_);
}
}
} else {
if(new_text_node) {
new_child_list.emplace_back(new_text_node);
new_text_node.reset();
}
new_child_list.emplace_back(c);
}
}
if(new_text_node != nullptr) {
new_child_list.emplace_back(new_text_node);
}
children_ = new_child_list;
for(auto& c : children_) {
c->normalize();
}
}
void Node::processWhitespace()
{
css::CssWhitespace ws = getStyle("whitespace").getValue<css::CssWhitespace>();
// XXX
}
// Documents do not have an owner document.
Document::Document(css::StyleSheetPtr ss)
: Node(NodeId::DOCUMENT, WeakDocumentPtr()),
style_sheet_(ss == nullptr ? std::make_shared<css::StyleSheet>() : ss)
{
}
void Document::processStyles()
{
// parse all the style nodes into the style sheet.
auto ss = style_sheet_;
preOrderTraversal([&ss](NodePtr n) {
if(n->hasTag(ElementId::STYLE)) {
for(auto& child : n->getChildren()) {
if(child->id() == NodeId::TEXT) {
css::Parser::parse(ss, child->getValue());
}
}
}
return true;
});
preOrderTraversal([&ss](NodePtr n) {
ss->applyRulesToElement(n);
return true;
});
// XXX Parse and apply specific element style rules from attributes here.
preOrderTraversal([](NodePtr n) {
if(n->id() == NodeId::ELEMENT) {
auto attr = n->getAttribute("style");
if(attr) {
auto plist = css::Parser::parseDeclarationList(attr->getValue());
n->mergeProperties(plist);
}
}
return true;
});
LOG_DEBUG("STYLESHEET: " << ss->toString());
}
Object Node::getStyle(const std::string& name) const
{
auto o = properties_.getProperty(name);
if(o.shouldInherit()) {
auto p = getParent();
ASSERT_LOG(p != nullptr, "css property(" << name << ") is set to inherit but the node has no parent.");
return p->getStyle(name);
}
if(o.empty()) {
ASSERT_LOG(false, "Unimplemented style was asked for '" << name <<"'");
}
return o;
}
void Node::mergeProperties(const css::PropertyList& plist)
{
properties_.merge(plist);
}
std::string Document::toString() const
{
std::ostringstream ss;
ss << "Document(" << nodeToString() << ")";
return ss.str();
}
DocumentPtr Document::create(css::StyleSheetPtr ss)
{
return std::make_shared<DocumentImpl>(ss);
}
DocumentFragment::DocumentFragment(WeakDocumentPtr owner)
: Node(NodeId::DOCUMENT_FRAGMENT, owner)
{
}
DocumentFragmentPtr DocumentFragment::create(WeakDocumentPtr owner)
{
return std::make_shared<DocumentFragmentImpl>(owner);
}
std::string DocumentFragment::toString() const
{
std::ostringstream ss;
ss << "DocumentFragment(" << nodeToString() << ")";
return ss.str();
}
Attribute::Attribute(const std::string& name, const std::string& value, WeakDocumentPtr owner)
: Node(NodeId::ATTRIBUTE, owner),
name_(name),
value_(value)
{
}
AttributePtr Attribute::create(const std::string& name, const std::string& value, WeakDocumentPtr owner)
{
return std::make_shared<AttributeImpl>(name, value, owner);
}
std::string Attribute::toString() const
{
std::ostringstream ss;
ss << "Attribute('" << name_ << ":" << value_ << "'" << nodeToString() << ")";
return ss.str();
}
}
<commit_msg>Added handling for css from link elements.<commit_after>/*
Copyright (C) 2003-2013 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <sstream>
#include "asserts.hpp"
#include "css_parser.hpp"
#include "xhtml_text_node.hpp"
#include "filesystem.hpp"
namespace xhtml
{
namespace {
struct DocumentImpl : public Document
{
DocumentImpl(css::StyleSheetPtr ss) : Document(ss) {}
};
struct DocumentFragmentImpl : public DocumentFragment
{
DocumentFragmentImpl(WeakDocumentPtr owner) : DocumentFragment(owner) {}
};
struct AttributeImpl : public Attribute
{
AttributeImpl(const std::string& name, const std::string& value, WeakDocumentPtr owner) : Attribute(name, value, owner) {}
};
}
Node::Node(NodeId id, WeakDocumentPtr owner)
: id_(id),
children_(),
attributes_(),
left_(),
right_(),
parent_(),
owner_document_(owner),
properties_()
{
}
Node::~Node()
{
}
void Node::addChild(NodePtr child)
{
if(child->id() == NodeId::DOCUMENT_FRAGMENT) {
// we add the children of a document fragment rather than the node itself.
if(children_.empty()) {
children_ = child->children_;
for(auto& c : children_) {
c->setParent(shared_from_this());
}
} else {
if(!child->children_.empty()) {
children_.back()->right_ = child->children_.front();
child->children_.front()->left_ = children_.back();
for(auto& c : child->children_) {
c->setParent(shared_from_this());
}
children_.insert(children_.end(), child->children_.begin(), child->children_.end());
}
}
} else {
child->left_ = child->right_ = std::weak_ptr<Node>();
if(!children_.empty()) {
children_.back()->right_ = child;
child->left_ = children_.back();
}
children_.emplace_back(child);
child->setParent(shared_from_this());
}
}
void Node::addAttribute(AttributePtr a)
{
a->setParent(shared_from_this());
attributes_[a->getName()] = a;
}
void Node::preOrderTraversal(std::function<bool(NodePtr)> fn)
{
// Visit node, visit children.
if(!fn(shared_from_this())) {
return;
}
for(auto& c : children_) {
c->preOrderTraversal(fn);
}
}
void Node::postOrderTraversal(std::function<bool(NodePtr)> fn)
{
// Visit children, then this process node.
for(auto& c : children_) {
c->preOrderTraversal(fn);
}
if(!fn(shared_from_this())) {
return;
}
}
AttributePtr Node::getAttribute(const std::string& name)
{
auto it = attributes_.find(name);
return it != attributes_.end() ? it->second : nullptr;
}
std::string Node::nodeToString() const
{
std::ostringstream ss;
for(auto& a : getAttributes()) {
ss << "{" << a.second->toString() << "}";
}
return ss.str();
}
const std::string& Node::getValue() const
{
static std::string null_str;
return null_str;
}
void Node::normalize()
{
std::vector<NodePtr> new_child_list;
TextPtr new_text_node;
for(auto& c : children_) {
if(c->id() == NodeId::TEXT) {
if(!c->getValue().empty()) {
if(new_text_node) {
new_text_node->addText(c->getValue());
} else {
new_text_node = Text::create(c->getValue(), owner_document_);
}
}
} else {
if(new_text_node) {
new_child_list.emplace_back(new_text_node);
new_text_node.reset();
}
new_child_list.emplace_back(c);
}
}
if(new_text_node != nullptr) {
new_child_list.emplace_back(new_text_node);
}
children_ = new_child_list;
for(auto& c : children_) {
c->normalize();
}
}
void Node::processWhitespace()
{
css::CssWhitespace ws = getStyle("whitespace").getValue<css::CssWhitespace>();
// XXX
}
// Documents do not have an owner document.
Document::Document(css::StyleSheetPtr ss)
: Node(NodeId::DOCUMENT, WeakDocumentPtr()),
style_sheet_(ss == nullptr ? std::make_shared<css::StyleSheet>() : ss)
{
}
void Document::processStyles()
{
// parse all the style nodes into the style sheet.
auto ss = style_sheet_;
preOrderTraversal([&ss](NodePtr n) {
if(n->hasTag(ElementId::STYLE)) {
for(auto& child : n->getChildren()) {
if(child->id() == NodeId::TEXT) {
css::Parser::parse(ss, child->getValue());
}
}
}
if(n->hasTag(ElementId::LINK)) {
auto rel = n->getAttribute("rel");
auto href = n->getAttribute("href");
auto type = n->getAttribute("type"); // expect "type/css"
//auto media = n->getAttribute("media"); // expect "display" or nullptr
if(rel && rel->getValue() == "stylesheet") {
if(href == nullptr) {
LOG_ERROR("There was no 'href' in the LINK element.");
} else {
//auto css_file = get_uri(href->getValue);
auto css_file = sys::read_file("../data/" + href->getValue());
css::Parser::parse(ss, css_file);
}
}
}
return true;
});
preOrderTraversal([&ss](NodePtr n) {
ss->applyRulesToElement(n);
return true;
});
// XXX Parse and apply specific element style rules from attributes here.
preOrderTraversal([](NodePtr n) {
if(n->id() == NodeId::ELEMENT) {
auto attr = n->getAttribute("style");
if(attr) {
auto plist = css::Parser::parseDeclarationList(attr->getValue());
n->mergeProperties(plist);
}
}
return true;
});
LOG_DEBUG("STYLESHEET: " << ss->toString());
}
Object Node::getStyle(const std::string& name) const
{
auto o = properties_.getProperty(name);
if(o.shouldInherit()) {
auto p = getParent();
ASSERT_LOG(p != nullptr, "css property(" << name << ") is set to inherit but the node has no parent.");
return p->getStyle(name);
}
if(o.empty()) {
ASSERT_LOG(false, "Unimplemented style was asked for '" << name <<"'");
}
return o;
}
void Node::mergeProperties(const css::PropertyList& plist)
{
properties_.merge(plist);
}
std::string Document::toString() const
{
std::ostringstream ss;
ss << "Document(" << nodeToString() << ")";
return ss.str();
}
DocumentPtr Document::create(css::StyleSheetPtr ss)
{
return std::make_shared<DocumentImpl>(ss);
}
DocumentFragment::DocumentFragment(WeakDocumentPtr owner)
: Node(NodeId::DOCUMENT_FRAGMENT, owner)
{
}
DocumentFragmentPtr DocumentFragment::create(WeakDocumentPtr owner)
{
return std::make_shared<DocumentFragmentImpl>(owner);
}
std::string DocumentFragment::toString() const
{
std::ostringstream ss;
ss << "DocumentFragment(" << nodeToString() << ")";
return ss.str();
}
Attribute::Attribute(const std::string& name, const std::string& value, WeakDocumentPtr owner)
: Node(NodeId::ATTRIBUTE, owner),
name_(name),
value_(value)
{
}
AttributePtr Attribute::create(const std::string& name, const std::string& value, WeakDocumentPtr owner)
{
return std::make_shared<AttributeImpl>(name, value, owner);
}
std::string Attribute::toString() const
{
std::ostringstream ss;
ss << "Attribute('" << name_ << ":" << value_ << "'" << nodeToString() << ")";
return ss.str();
}
}
<|endoftext|> |
<commit_before>#include "optimize.hpp"
#include <vector>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <stdexcept>
#include <limits>
#include <algorithm>
#include "pll_util.hpp"
#include "constants.hpp"
#include "Log.hpp"
using namespace std;
static void traverse_update_partials(pll_utree_t * tree, pll_partition_t * partition,
pll_utree_t ** travbuffer, double * branch_lengths, unsigned int * matrix_indices,
pll_operation_t * operations)
{
unsigned int num_matrices, num_ops;
vector<unsigned int> param_indices(partition->rate_cats, 0);
/* perform a full traversal*/
assert(tree->next != nullptr);
unsigned int traversal_size;
// TODO this only needs to be done once, outside of this func. pass traversal size also
// however this is practically nonexistent impact compared to clv comp
pll_utree_traverse(tree, cb_full_traversal, travbuffer, &traversal_size);
/* given the computed traversal descriptor, generate the operations
structure, and the corresponding probability matrix indices that
may need recomputing */
pll_utree_create_operations(travbuffer,
traversal_size,
branch_lengths,
matrix_indices,
operations,
&num_matrices,
&num_ops);
pll_update_prob_matrices(partition,
¶m_indices[0],
matrix_indices,// matrices to update
branch_lengths,
num_matrices); // how many should be updated
/* use the operations array to compute all num_ops inner CLVs. Operations
will be carried out sequentially starting from operation 0 towrds num_ops-1 */
pll_update_partials(partition, operations, num_ops);
}
double optimize_branch_triplet(pll_partition_t * partition, pll_utree_t * tree)
{
if (!tree->next)
tree = tree->back;
vector<pll_utree_t*> travbuffer(4);
vector<double> branch_lengths(3);
vector<unsigned int> matrix_indices(3);
vector<pll_operation_t> operations(4);
traverse_update_partials(tree, partition, &travbuffer[0], &branch_lengths[0],
&matrix_indices[0], &operations[0]);
vector<unsigned int> param_indices(partition->rate_cats, 0);
auto cur_logl = -numeric_limits<double>::infinity();
int smoothings = 32;
cur_logl = -pllmod_opt_optimize_branch_lengths_local (
partition,
tree,
¶m_indices[0],
PLLMOD_OPT_MIN_BRANCH_LEN,
PLLMOD_OPT_MAX_BRANCH_LEN,
OPT_BRANCH_EPSILON,
smoothings,
1, // radius
1); // keep update
return cur_logl;
}
static double optimize_branch_lengths(pll_utree_t * tree, pll_partition_t * partition, pll_optimize_options_t& params,
pll_utree_t ** travbuffer, double cur_logl, double lnl_monitor, int* smoothings)
{
if (!tree->next)
tree = tree->back;
traverse_update_partials(tree, partition, travbuffer, params.lk_params.branch_lengths,
params.lk_params.matrix_indices, params.lk_params.operations);
pll_errno = 0; // hotfix
vector<unsigned int> param_indices(partition->rate_cats, 0);
cur_logl = -1 * pllmod_opt_optimize_branch_lengths_iterative(
partition,
tree,
¶m_indices[0],
PLLMOD_OPT_MIN_BRANCH_LEN,
PLLMOD_OPT_MAX_BRANCH_LEN,
OPT_BRANCH_EPSILON,
*smoothings,
1); // keep updating BLs during call
if (cur_logl+1e-6 < lnl_monitor)
throw runtime_error{string("cur_logl < lnl_monitor: ") + to_string(cur_logl) + string(" : ")
+ to_string(lnl_monitor)};
// reupdate the indices as they may have changed
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index = tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index = tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index = tree->pmatrix_index;
traverse_update_partials(tree, partition, travbuffer, params.lk_params.branch_lengths,
params.lk_params.matrix_indices, params.lk_params.operations);
cur_logl = pll_compute_edge_loglikelihood (partition, tree->clv_index,
tree->scaler_index,
tree->back->clv_index,
tree->back->scaler_index,
tree->pmatrix_index, ¶m_indices[0], nullptr);
return cur_logl;
}
void optimize(Model& model, pll_utree_t * tree, pll_partition_t * partition,
const Tree_Numbers& nums, const bool opt_branches, const bool opt_model)
{
if (!opt_branches && !opt_model)
return;
if (opt_branches)
set_branch_lengths(tree, DEFAULT_BRANCH_LENGTH);
compute_and_set_empirical_frequencies(partition, model);
auto symmetries = (&(model.symmetries())[0]);
vector<unsigned int> param_indices(model.rate_cats(), 0);
// sadly we explicitly need these buffers here and in the params structure
vector<pll_utree_t*> travbuffer(nums.nodes);
vector<double> branch_lengths(nums.branches);
vector<unsigned int> matrix_indices(nums.branches);
vector<pll_operation_t> operations(nums.nodes);
traverse_update_partials(tree, partition, &travbuffer[0], &branch_lengths[0],
&matrix_indices[0], &operations[0]);
// compute logl once to give us a logl starting point
auto cur_logl = pll_compute_edge_loglikelihood (partition, tree->clv_index,
tree->scaler_index,
tree->back->clv_index,
tree->back->scaler_index,
tree->pmatrix_index, ¶m_indices[0], nullptr);
// double cur_logl = -numeric_limits<double>::infinity();
int smoothings;
double lnl_monitor = cur_logl;
// set up high level options structure
pll_optimize_options_t params;
params.lk_params.partition = partition;
params.lk_params.operations = &operations[0];
params.lk_params.branch_lengths = &branch_lengths[0];
params.lk_params.matrix_indices = &matrix_indices[0];
params.lk_params.params_indices = ¶m_indices[0];
params.lk_params.alpha_value = model.alpha();
params.lk_params.rooted = 0;
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index = tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index =
tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index = tree->pmatrix_index;
/* optimization parameters */
params.params_index = 0;
params.subst_params_symmetries = symmetries;
params.factr = OPT_FACTR;
params.pgtol = OPT_PARAM_EPSILON;
vector<pll_utree_t*> branches(nums.branches);
auto num_traversed = utree_query_branches(tree, &branches[0]);
assert (num_traversed == nums.branches);
unsigned int branch_index = 0;
double logl = cur_logl;
if (opt_branches)
{
smoothings = 8;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after hidden blo crouching tiger: " << to_string(cur_logl) << "\n";
}
#define RATE_MIN 1e-4
#define RATE_MAX 1000000.
double min_rates[6] = {RATE_MIN,RATE_MIN,RATE_MIN,RATE_MIN,RATE_MIN,RATE_MIN};
double max_rates[6] = {RATE_MAX,RATE_MAX,RATE_MAX,RATE_MAX,RATE_MAX,RATE_MAX};
do
{
branch_index = rand () % num_traversed;
// lgr << "Start: " << to_string(cur_logl) << "\n";
logl = cur_logl;
if (opt_model)
{
params.which_parameters = PLLMOD_OPT_PARAM_SUBST_RATES;
cur_logl = -pllmod_opt_optimize_multidim(¶ms, min_rates, max_rates);
// lgr << "after rates: " << to_string(cur_logl) << "\n";
if (opt_branches)
{
smoothings = 2;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after blo 1: " << to_string(cur_logl) << "\n";
}
// params.which_parameters = PLL_PARAMETER_FREQUENCIES;
// pll_optimize_parameters_multidim(¶ms, nullptr, nullptr);
if (opt_branches)
{
smoothings = 2;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after blo 2: " << to_string(cur_logl) << "\n";
}
// params.which_parameters = PLL_PARAMETER_PINV;
// cur_logl = -1 * pll_optimize_parameters_brent(¶ms);
params.which_parameters = PLLMOD_OPT_PARAM_ALPHA;
cur_logl = -pllmod_opt_optimize_onedim(¶ms, 0.02, 10000.);
// lgr << "after alpha: " << to_string(cur_logl) << "\n";
}
if (opt_branches)
{
smoothings = 3;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after blo 3: " << to_string(cur_logl) << "\n";
}
} while (fabs (cur_logl - logl) > OPT_EPSILON);
if (opt_model)
{
// update epa model object as well
model.alpha(params.lk_params.alpha_value);
model.substitution_rates(partition->subst_params[0], 6);
model.base_frequencies(partition->frequencies[params.params_index], partition->states);
}
}
void compute_and_set_empirical_frequencies(pll_partition_t * partition, Model& model)
{
double * empirical_freqs = pllmod_msa_empirical_frequencies (partition);
pll_set_frequencies (partition, 0, empirical_freqs);
model.base_frequencies(partition->frequencies[0], partition->states);
free (empirical_freqs);
}
<commit_msg>fixed bug during model update of optimization<commit_after>#include "optimize.hpp"
#include <vector>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <stdexcept>
#include <limits>
#include <algorithm>
#include "pll_util.hpp"
#include "constants.hpp"
#include "Log.hpp"
using namespace std;
static void traverse_update_partials(pll_utree_t * tree, pll_partition_t * partition,
pll_utree_t ** travbuffer, double * branch_lengths, unsigned int * matrix_indices,
pll_operation_t * operations)
{
unsigned int num_matrices, num_ops;
vector<unsigned int> param_indices(partition->rate_cats, 0);
/* perform a full traversal*/
assert(tree->next != nullptr);
unsigned int traversal_size;
// TODO this only needs to be done once, outside of this func. pass traversal size also
// however this is practically nonexistent impact compared to clv comp
pll_utree_traverse(tree, cb_full_traversal, travbuffer, &traversal_size);
/* given the computed traversal descriptor, generate the operations
structure, and the corresponding probability matrix indices that
may need recomputing */
pll_utree_create_operations(travbuffer,
traversal_size,
branch_lengths,
matrix_indices,
operations,
&num_matrices,
&num_ops);
pll_update_prob_matrices(partition,
¶m_indices[0],
matrix_indices,// matrices to update
branch_lengths,
num_matrices); // how many should be updated
/* use the operations array to compute all num_ops inner CLVs. Operations
will be carried out sequentially starting from operation 0 towrds num_ops-1 */
pll_update_partials(partition, operations, num_ops);
}
double optimize_branch_triplet(pll_partition_t * partition, pll_utree_t * tree)
{
if (!tree->next)
tree = tree->back;
vector<pll_utree_t*> travbuffer(4);
vector<double> branch_lengths(3);
vector<unsigned int> matrix_indices(3);
vector<pll_operation_t> operations(4);
traverse_update_partials(tree, partition, &travbuffer[0], &branch_lengths[0],
&matrix_indices[0], &operations[0]);
vector<unsigned int> param_indices(partition->rate_cats, 0);
auto cur_logl = -numeric_limits<double>::infinity();
int smoothings = 32;
cur_logl = -pllmod_opt_optimize_branch_lengths_local (
partition,
tree,
¶m_indices[0],
PLLMOD_OPT_MIN_BRANCH_LEN,
PLLMOD_OPT_MAX_BRANCH_LEN,
OPT_BRANCH_EPSILON,
smoothings,
1, // radius
1); // keep update
return cur_logl;
}
static double optimize_branch_lengths(pll_utree_t * tree, pll_partition_t * partition, pll_optimize_options_t& params,
pll_utree_t ** travbuffer, double cur_logl, double lnl_monitor, int* smoothings)
{
if (!tree->next)
tree = tree->back;
traverse_update_partials(tree, partition, travbuffer, params.lk_params.branch_lengths,
params.lk_params.matrix_indices, params.lk_params.operations);
pll_errno = 0; // hotfix
vector<unsigned int> param_indices(partition->rate_cats, 0);
cur_logl = -1 * pllmod_opt_optimize_branch_lengths_iterative(
partition,
tree,
¶m_indices[0],
PLLMOD_OPT_MIN_BRANCH_LEN,
PLLMOD_OPT_MAX_BRANCH_LEN,
OPT_BRANCH_EPSILON,
*smoothings,
1); // keep updating BLs during call
if (cur_logl+1e-6 < lnl_monitor)
throw runtime_error{string("cur_logl < lnl_monitor: ") + to_string(cur_logl) + string(" : ")
+ to_string(lnl_monitor)};
// reupdate the indices as they may have changed
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index = tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index = tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index = tree->pmatrix_index;
traverse_update_partials(tree, partition, travbuffer, params.lk_params.branch_lengths,
params.lk_params.matrix_indices, params.lk_params.operations);
cur_logl = pll_compute_edge_loglikelihood (partition, tree->clv_index,
tree->scaler_index,
tree->back->clv_index,
tree->back->scaler_index,
tree->pmatrix_index, ¶m_indices[0], nullptr);
return cur_logl;
}
void optimize(Model& model, pll_utree_t * tree, pll_partition_t * partition,
const Tree_Numbers& nums, const bool opt_branches, const bool opt_model)
{
if (!opt_branches && !opt_model)
return;
if (opt_branches)
set_branch_lengths(tree, DEFAULT_BRANCH_LENGTH);
compute_and_set_empirical_frequencies(partition, model);
auto symmetries = (&(model.symmetries())[0]);
vector<unsigned int> param_indices(model.rate_cats(), 0);
// sadly we explicitly need these buffers here and in the params structure
vector<pll_utree_t*> travbuffer(nums.nodes);
vector<double> branch_lengths(nums.branches);
vector<unsigned int> matrix_indices(nums.branches);
vector<pll_operation_t> operations(nums.nodes);
traverse_update_partials(tree, partition, &travbuffer[0], &branch_lengths[0],
&matrix_indices[0], &operations[0]);
// compute logl once to give us a logl starting point
auto cur_logl = pll_compute_edge_loglikelihood (partition, tree->clv_index,
tree->scaler_index,
tree->back->clv_index,
tree->back->scaler_index,
tree->pmatrix_index, ¶m_indices[0], nullptr);
// double cur_logl = -numeric_limits<double>::infinity();
int smoothings;
double lnl_monitor = cur_logl;
// set up high level options structure
pll_optimize_options_t params;
params.lk_params.partition = partition;
params.lk_params.operations = &operations[0];
params.lk_params.branch_lengths = &branch_lengths[0];
params.lk_params.matrix_indices = &matrix_indices[0];
params.lk_params.params_indices = ¶m_indices[0];
params.lk_params.alpha_value = model.alpha();
params.lk_params.rooted = 0;
params.lk_params.where.unrooted_t.parent_clv_index = tree->clv_index;
params.lk_params.where.unrooted_t.parent_scaler_index = tree->scaler_index;
params.lk_params.where.unrooted_t.child_clv_index = tree->back->clv_index;
params.lk_params.where.unrooted_t.child_scaler_index =
tree->back->scaler_index;
params.lk_params.where.unrooted_t.edge_pmatrix_index = tree->pmatrix_index;
/* optimization parameters */
params.params_index = 0;
params.subst_params_symmetries = symmetries;
params.factr = OPT_FACTR;
params.pgtol = OPT_PARAM_EPSILON;
vector<pll_utree_t*> branches(nums.branches);
auto num_traversed = utree_query_branches(tree, &branches[0]);
assert (num_traversed == nums.branches);
unsigned int branch_index = 0;
double logl = cur_logl;
if (opt_branches)
{
smoothings = 8;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after hidden blo crouching tiger: " << to_string(cur_logl) << "\n";
}
#define RATE_MIN 1e-4
#define RATE_MAX 1000000.
double min_rates[6] = {RATE_MIN,RATE_MIN,RATE_MIN,RATE_MIN,RATE_MIN,RATE_MIN};
double max_rates[6] = {RATE_MAX,RATE_MAX,RATE_MAX,RATE_MAX,RATE_MAX,RATE_MAX};
do
{
branch_index = rand () % num_traversed;
// lgr << "Start: " << to_string(cur_logl) << "\n";
logl = cur_logl;
if (opt_model)
{
params.which_parameters = PLLMOD_OPT_PARAM_SUBST_RATES;
cur_logl = -pllmod_opt_optimize_multidim(¶ms, min_rates, max_rates);
// lgr << "after rates: " << to_string(cur_logl) << "\n";
if (opt_branches)
{
smoothings = 2;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after blo 1: " << to_string(cur_logl) << "\n";
}
// params.which_parameters = PLL_PARAMETER_FREQUENCIES;
// pll_optimize_parameters_multidim(¶ms, nullptr, nullptr);
if (opt_branches)
{
smoothings = 2;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after blo 2: " << to_string(cur_logl) << "\n";
}
// params.which_parameters = PLL_PARAMETER_PINV;
// cur_logl = -1 * pll_optimize_parameters_brent(¶ms);
params.which_parameters = PLLMOD_OPT_PARAM_ALPHA;
cur_logl = -pllmod_opt_optimize_onedim(¶ms, 0.02, 10000.);
// lgr << "after alpha: " << to_string(cur_logl) << "\n";
}
if (opt_branches)
{
smoothings = 3;
cur_logl = optimize_branch_lengths(branches[branch_index],
partition, params, &travbuffer[0], cur_logl, lnl_monitor, &smoothings);
// lgr << "after blo 3: " << to_string(cur_logl) << "\n";
}
} while (fabs (cur_logl - logl) > OPT_EPSILON);
if (opt_model)
{
// update epa model object as well
model.alpha(params.lk_params.alpha_value);
model.substitution_rates(partition->subst_params[0], model.substitution_rates().size());
model.base_frequencies(partition->frequencies[params.params_index], partition->states);
}
}
void compute_and_set_empirical_frequencies(pll_partition_t * partition, Model& model)
{
double * empirical_freqs = pllmod_msa_empirical_frequencies (partition);
pll_set_frequencies (partition, 0, empirical_freqs);
model.base_frequencies(partition->frequencies[0], partition->states);
free (empirical_freqs);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCollection.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkCollection.h"
// Description:
// Construct with empty list.
vtkCollection::vtkCollection()
{
this->NumberOfItems = 0;
this->Top = NULL;
this->Bottom = NULL;
this->Current = NULL;
}
vtkCollection::~vtkCollection()
{
this->RemoveAllItems();
}
// Description:
// protected function to delete an element. Internal use only.
void vtkCollection::DeleteElement(vtkCollectionElement *e)
{
delete e;
}
// Description:
// Add an object to the list. Does not prevent duplicate entries.
void vtkCollection::AddItem(vtkObject *a)
{
vtkCollectionElement *elem;
elem = new vtkCollectionElement;
if (!this->Top)
{
this->Top = elem;
}
else
{
this->Bottom->Next = elem;
}
this->Bottom = elem;
elem->Item = a;
elem->Next = NULL;
this->NumberOfItems++;
}
// Description:
// Remove an object from the list. Removes the first object found, not
// all occurrences. If no object found, list is unaffected. See warning
// in description of RemoveItem(int).
void vtkCollection::RemoveItem(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return;
}
elem = this->Top;
prev = NULL;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
this->RemoveItem(i);
return;
}
else
{
prev = elem;
elem = elem->Next;
}
}
}
// Description:
// Remove all objects from the list.
void vtkCollection::RemoveAllItems()
{
int i;
for (i = this->NumberOfItems - 1; i >= 0; i--)
{
this->RemoveItem(i);
}
}
// Description:
// Search for an object and return location in list. If location == 0,
// object was not found.
int vtkCollection::IsItemPresent(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return 0;
}
elem = this->Top;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
return i + 1;
}
else
{
elem = elem->Next;
}
}
return 0;
}
// Description:
// Return the number of objects in the list.
int vtkCollection::GetNumberOfItems()
{
return this->NumberOfItems;
}
void vtkCollection::PrintSelf(ostream& os, vtkIndent indent)
{
vtkObject::PrintSelf(os,indent);
os << indent << "Number Of Items: " << this->NumberOfItems << "\n";
}
// Description:
// Get the i'th item in the collection. NULL is returned if i is out
// of range
vtkObject *vtkCollection::GetItemAsObject(int i)
{
vtkCollectionElement *elem=this->Top;
if (i < 0)
{
return NULL;
}
while (elem != NULL && i > 0)
{
elem = elem->Next;
i--;
}
if ( elem != NULL )
{
return elem->Item;
}
else
{
return NULL;
}
}
// Description:
// Replace the i'th item in the collection with a
void vtkCollection::ReplaceItem(int i, vtkObject *a)
{
vtkCollectionElement *elem;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
elem = this->Top;
for (int j = 0; j < i; j++, elem = elem->Next )
{}
// j == i
elem->Item = a;
}
// Description:
// Remove the i'th item in the list.
// Be careful if using this function during traversal of the list using
// GetNextItemAsObject (or GetNextItem in derived class). The list WILL
// be shortened if a valid index is given! If this->Current is equal to the
// element being removed, have it point to then next element in the list.
void vtkCollection::RemoveItem(int i)
{
vtkCollectionElement *elem,*prev;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
elem = this->Top;
prev = NULL;
for (int j = 0; j < i; j++)
{
prev = elem;
elem = elem->Next;
}
// j == i
if (prev)
{
prev->Next = elem->Next;
}
else
{
this->Top = elem->Next;
}
if (!elem->Next)
{
this->Bottom = prev;
}
if ( this->Current == elem )
{
this->Current = elem->Next;
}
this->DeleteElement(elem);
this->NumberOfItems--;
}
<commit_msg>fixed compile errors<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCollection.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkCollection.h"
// Description:
// Construct with empty list.
vtkCollection::vtkCollection()
{
this->NumberOfItems = 0;
this->Top = NULL;
this->Bottom = NULL;
this->Current = NULL;
}
vtkCollection::~vtkCollection()
{
this->RemoveAllItems();
}
// Description:
// protected function to delete an element. Internal use only.
void vtkCollection::DeleteElement(vtkCollectionElement *e)
{
delete e;
}
// Description:
// Add an object to the list. Does not prevent duplicate entries.
void vtkCollection::AddItem(vtkObject *a)
{
vtkCollectionElement *elem;
elem = new vtkCollectionElement;
if (!this->Top)
{
this->Top = elem;
}
else
{
this->Bottom->Next = elem;
}
this->Bottom = elem;
elem->Item = a;
elem->Next = NULL;
this->NumberOfItems++;
}
// Description:
// Remove an object from the list. Removes the first object found, not
// all occurrences. If no object found, list is unaffected. See warning
// in description of RemoveItem(int).
void vtkCollection::RemoveItem(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return;
}
elem = this->Top;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
this->RemoveItem(i);
return;
}
else
{
elem = elem->Next;
}
}
}
// Description:
// Remove all objects from the list.
void vtkCollection::RemoveAllItems()
{
int i;
for (i = this->NumberOfItems - 1; i >= 0; i--)
{
this->RemoveItem(i);
}
}
// Description:
// Search for an object and return location in list. If location == 0,
// object was not found.
int vtkCollection::IsItemPresent(vtkObject *a)
{
int i;
vtkCollectionElement *elem;
if (!this->Top)
{
return 0;
}
elem = this->Top;
for (i = 0; i < this->NumberOfItems; i++)
{
if (elem->Item == a)
{
return i + 1;
}
else
{
elem = elem->Next;
}
}
return 0;
}
// Description:
// Return the number of objects in the list.
int vtkCollection::GetNumberOfItems()
{
return this->NumberOfItems;
}
void vtkCollection::PrintSelf(ostream& os, vtkIndent indent)
{
vtkObject::PrintSelf(os,indent);
os << indent << "Number Of Items: " << this->NumberOfItems << "\n";
}
// Description:
// Get the i'th item in the collection. NULL is returned if i is out
// of range
vtkObject *vtkCollection::GetItemAsObject(int i)
{
vtkCollectionElement *elem=this->Top;
if (i < 0)
{
return NULL;
}
while (elem != NULL && i > 0)
{
elem = elem->Next;
i--;
}
if ( elem != NULL )
{
return elem->Item;
}
else
{
return NULL;
}
}
// Description:
// Replace the i'th item in the collection with a
void vtkCollection::ReplaceItem(int i, vtkObject *a)
{
vtkCollectionElement *elem;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
elem = this->Top;
for (int j = 0; j < i; j++, elem = elem->Next )
{}
// j == i
elem->Item = a;
}
// Description:
// Remove the i'th item in the list.
// Be careful if using this function during traversal of the list using
// GetNextItemAsObject (or GetNextItem in derived class). The list WILL
// be shortened if a valid index is given! If this->Current is equal to the
// element being removed, have it point to then next element in the list.
void vtkCollection::RemoveItem(int i)
{
vtkCollectionElement *elem,*prev;
if( i < 0 || i >= this->NumberOfItems )
{
return;
}
elem = this->Top;
prev = NULL;
for (int j = 0; j < i; j++)
{
prev = elem;
elem = elem->Next;
}
// j == i
if (prev)
{
prev->Next = elem->Next;
}
else
{
this->Top = elem->Next;
}
if (!elem->Next)
{
this->Bottom = prev;
}
if ( this->Current == elem )
{
this->Current = elem->Next;
}
this->DeleteElement(elem);
this->NumberOfItems--;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "exception.hpp"
#include "array_utilities.hpp"
#include "assert.hpp"
#include "log.hpp"
#include <boost/static_assert.hpp>
#include <cstring>
#include <iostream>
#include <string>
using jewel::num_elements;
using std::endl;
using std::strlen;
using std::strncat;
using std::strncpy;
using std::string;
namespace jewel
{
Exception::Exception() throw()
{
}
Exception::Exception(char const* p_message) throw():
m_message(p_message)
{
if (m_message.size() > max_message_size()) truncate_message();
}
Exception::Exception(Exception const& rhs) throw():
m_message(rhs.m_message)
{
if (m_message.size() > max_message_size()) truncate_message();
}
Exception::~Exception() throw()
{
}
CappedString<Exception::truncation_flag_capacity>
Exception::truncation_flag()
{
CappedString<truncation_flag_capacity> const ret("[TRUNCATED]");
JEWEL_ASSERT (!ret.is_truncated());
JEWEL_ASSERT (ret.size() == truncation_flag_capacity);
return ret;
}
char const* Exception::what() const throw()
{
return m_message.c_str();
}
void
Exception::truncate_message()
{
// TODO This concatenation would be better handled within
// CappedString.
char buf[message_capacity + 1];
size_t const truncation_flag_size = truncation_flag().size();
size_t const truncated_message_size =
message_capacity - truncation_flag_size;
strncpy(buf, m_message.c_str(), truncated_message_size);
buf[truncated_message_size] = '\0';
JEWEL_ASSERT
( truncation_flag_size <=
(message_capacity - truncated_message_size)
);
strcat(buf, truncation_flag().c_str());
buf[message_capacity] = 1; // Doesn't matter as long as it's not '\0';
// We still want m_message to be marked as truncated!
m_message = CappedString<message_capacity>(buf);
return;
}
size_t Exception::max_message_size() throw()
{
return message_capacity - truncation_flag_capacity;
}
} // namespace jewel
<commit_msg>Used CappedString iterators and std::copy algorithm to simplify implementation of jewel::Exception.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "exception.hpp"
#include "array_utilities.hpp"
#include "assert.hpp"
#include "log.hpp"
#include <boost/static_assert.hpp>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using jewel::num_elements;
using std::copy;
using std::endl;
namespace jewel
{
Exception::Exception() throw()
{
}
Exception::Exception(char const* p_message) throw():
m_message(p_message)
{
if (m_message.size() > max_message_size()) truncate_message();
}
Exception::Exception(Exception const& rhs) throw():
m_message(rhs.m_message)
{
if (m_message.size() > max_message_size()) truncate_message();
}
Exception::~Exception() throw()
{
}
CappedString<Exception::truncation_flag_capacity>
Exception::truncation_flag()
{
CappedString<truncation_flag_capacity> const ret("[TRUNCATED]");
JEWEL_ASSERT (!ret.is_truncated());
JEWEL_ASSERT (ret.size() == truncation_flag_capacity);
return ret;
}
char const* Exception::what() const throw()
{
return m_message.c_str();
}
void
Exception::truncate_message()
{
CappedString<truncation_flag_capacity> const trunc_flag =
truncation_flag();
CappedString<message_capacity>::iterator out_it = copy
( trunc_flag.begin(),
trunc_flag.end(),
m_message.begin() + (message_capacity - trunc_flag.size())
);
*out_it = '\0';
return;
}
size_t Exception::max_message_size() throw()
{
return message_capacity - truncation_flag_capacity;
}
} // namespace jewel
<|endoftext|> |
<commit_before>#include "XmlHelper.h"
#include "Exceptions.h"
#include "Helper.h"
#include <QXmlSchemaValidator>
#include <QXmlSchema>
#include <QUrl>
#include <QTemporaryFile>
#include <QXmlSimpleReader>
#include <QXmlInputSource>
QString XmlHelper::isValidXml(QString xml_file)
{
QXmlSimpleReader xmlReader;
XmlValidationMessageHandler2 handler;
xmlReader.setContentHandler(&handler);
xmlReader.setErrorHandler(&handler);
QFile file(xml_file);
QXmlInputSource source(&file);
if (!xmlReader.parse(&source))
{
return handler.errorString();
}
return "";
}
QString XmlHelper::isValidXml(QString xml_name, QString schema_name)
{
//create schema url (both for native files and files from resources)
QUrl schema_url;
QScopedPointer<QTemporaryFile> tmp_file(QTemporaryFile::createNativeFile(schema_name));
if (tmp_file!=0)
{
schema_url = QUrl::fromLocalFile(tmp_file->fileName());
}
else
{
schema_url = QUrl::fromLocalFile(schema_name);
}
//load schema
QXmlSchema schema;
if (!schema.load(schema_url))
{
THROW(FileParseException, "XML schema '" + schema_url.toString() + "' is not valid/present.");
}
//validate file
QXmlSchemaValidator validator(schema);
XmlValidationMessageHandler handler;
validator.setMessageHandler(&handler);
QScopedPointer<QFile> xml_file(Helper::openFileForReading(xml_name));
if (validator.validate(xml_file.data(), schema_url))
{
return "";
}
return handler.messages();
}
QString XmlHelper::XmlValidationMessageHandler::messages()
{
return messages_;
}
void XmlHelper::XmlValidationMessageHandler::handleMessage(QtMsgType /*type*/, const QString& description, const QUrl& /*identifier*/, const QSourceLocation& /*sourceLocation*/)
{
messages_ = messages_ + description + " ";
}
<commit_msg>Refactoring of text file helper functions.<commit_after>#include "XmlHelper.h"
#include "Exceptions.h"
#include "Helper.h"
#include <QXmlSchemaValidator>
#include <QXmlSchema>
#include <QUrl>
#include <QTemporaryFile>
#include <QXmlSimpleReader>
#include <QXmlInputSource>
QString XmlHelper::isValidXml(QString xml_file)
{
QXmlSimpleReader xmlReader;
XmlValidationMessageHandler2 handler;
xmlReader.setContentHandler(&handler);
xmlReader.setErrorHandler(&handler);
QFile file(xml_file);
QXmlInputSource source(&file);
if (!xmlReader.parse(&source))
{
return handler.errorString();
}
return "";
}
QString XmlHelper::isValidXml(QString xml_name, QString schema_name)
{
//create schema url (both for native files and files from resources)
QUrl schema_url;
QScopedPointer<QTemporaryFile> tmp_file(QTemporaryFile::createNativeFile(schema_name));
if (tmp_file!=0)
{
schema_url = QUrl::fromLocalFile(tmp_file->fileName());
}
else
{
schema_url = QUrl::fromLocalFile(schema_name);
}
//load schema
QXmlSchema schema;
if (!schema.load(schema_url))
{
THROW(FileParseException, "XML schema '" + schema_url.toString() + "' is not valid/present.");
}
//validate file
QXmlSchemaValidator validator(schema);
XmlValidationMessageHandler handler;
validator.setMessageHandler(&handler);
QSharedPointer<QFile> xml_file = Helper::openFileForReading(xml_name);
if (validator.validate(xml_file.data(), schema_url))
{
return "";
}
return handler.messages();
}
QString XmlHelper::XmlValidationMessageHandler::messages()
{
return messages_;
}
void XmlHelper::XmlValidationMessageHandler::handleMessage(QtMsgType /*type*/, const QString& description, const QUrl& /*identifier*/, const QSourceLocation& /*sourceLocation*/)
{
messages_ = messages_ + description + " ";
}
<|endoftext|> |
<commit_before>//
// HTTPServer.cpp
// Development
//
// Created by Dmitry Soldatenkov on 12.08.14.
//
//
#include "HTTPServer.h"
#include "net/HttpServer.h"
#include "common/RhodesApp.h"
#include "common/RhoFilePath.h"
#include "common/RhoConf.h"
#include "net/URI.h"
#include "ruby/ext/rho/rhoruby.h"
#include "common/Tokenizer.h"
#include "sync/RhoconnectClientManager.h"
#include "statistic/RhoProfiler.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#if !defined(OS_WINCE)
#ifdef OS_ANDROID
#include "../../platform/android/jni/ifaddrs.h"
#else
#include <ifaddrs.h>
#endif
#include <netinet/in.h>
#else
//#include <ws2tcpip.h>
#include "net/CompatWince.h"
#endif
#include <string.h>
#if !defined(WINDOWS_PLATFORM)
#include <arpa/inet.h>
#endif
#include "logging/RhoLog.h"
#define DEFAULT_LOGCATEGORY "Development_HTTPServer"
static DevHTTPServer* ourDevHTTPServer = NULL;
//ULONG GetSinIP(struct sockaddr_in *_psin, LPSTR pIPStr, UINT IPMaxLen)
//{
// unsigned long ipaddr;
//
// ipaddr = INADDR_NONE;
//
// if (pIPStr && IPMaxLen)
// *pIPStr = '\0';
//
// if ( _psin )
// {
//#if defined(_WIN32)
// ipaddr = _psin->sin_addr.S_un.S_addr;
//#else
// ipaddr = _psin->sin_addr.s_addr;
//#endif
//
// if (pIPStr && IPMaxLen)
// {
// char *pIP;
// struct in_addr in;
//
//#if defined(_WIN32)
// in.S_un.S_addr = ipaddr;
//#else
// in.s_addr = ipaddr;
//#endif
//
// pIP = inet_ntoa(in);
//
// if (pIP)
// adjust_str(pIP, pIPStr, IPMaxLen);
// }
// }
//
// return ipaddr;
//}
extern "C" rho::String get_local_ip_adress();
void DevHTTPServer::init() {
m_local_IP_adress = "";
rho::String szRootPath = rho_native_rhopath();
rho::String szUserPath = rho_native_rhouserpath();
m_httpServer = new rho::net::CHttpServer(RHO_DEVELOPMENT_SERVER_PORT, szRootPath, szUserPath, szRootPath, true, true);
m_httpServer->disableAllLogging();
#ifdef OS_ANDROID
m_local_IP_adress = get_local_ip_adress();
#elif defined(OS_WINCE)
char host[22];
hostent* host_info = 0 ;
if(gethostname(host, sizeof(host)) == SOCKET_ERROR) {
return;
}
host_info = gethostbyname(host);
if(host_info)
{
for( int i=0 ; host_info->h_addr_list[i] ; ++i )
{
const in_addr* address = (in_addr*)host_info->h_addr_list[i] ;
rho::String addrIP = inet_ntoa( *address );
//if (addrIP.find("192.168.") != rho::String::npos) //HOTFIX!!!!
{
m_local_IP_adress = addrIP;
break;
}
}
}
else
{
//error
}
#else
//Obtain the computer's IP
{
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa ->ifa_addr->sa_family == AF_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
unsigned char *n = (unsigned char*)(tmpAddrPtr);
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
if ((ifa->ifa_name[0] == 'e') && (ifa->ifa_name[1] == 'n')) {
// printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
m_local_IP_adress = addressBuffer;
}
}
// else if (ifa->ifa_addr->sa_family==AF_INET6) { // check it is IP6
// // is a valid IP6 Address
// tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
// char addressBuffer[INET6_ADDRSTRLEN];
// inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
// printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
// }
}
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
}
#endif
RAWTRACE("$$$ Our IP adress is : $$$");
RAWTRACE(m_local_IP_adress.c_str());
RAWTRACE("$$$$$$$$$$$$$$$$$$$$$$$$$$");
}
rho::net::CHttpServer* DevHTTPServer::getHTTPServer() {
return m_httpServer;
}
DevHTTPServer* DevHTTPServer::getInstance() {
if (ourDevHTTPServer == NULL) {
ourDevHTTPServer = new DevHTTPServer();
}
return ourDevHTTPServer;
}
rho::String DevHTTPServer::getLocalIPAdress() {
return m_local_IP_adress;
}
rho::String DevHTTPServer::getPort() {
rho::String res = "";
char ttt[16];
int port = m_httpServer->getPort();
sprintf(ttt, "%d", port);
res = ttt;
return res;
}
void DevHTTPServer::run() {
for (;;) {
m_httpServer->run();
}
}
void init_Development_HTTP_Server() {
DevHTTPServer * ds = DevHTTPServer::getInstance();
ds->init();
ds->start(rho::common::IRhoRunnable::epNormal);
}<commit_msg>[WM] live update: detect local ip<commit_after>//
// HTTPServer.cpp
// Development
//
// Created by Dmitry Soldatenkov on 12.08.14.
//
//
#include "HTTPServer.h"
#include "net/HttpServer.h"
#include "common/RhodesApp.h"
#include "common/RhoFilePath.h"
#include "common/RhoConf.h"
#include "net/URI.h"
#include "ruby/ext/rho/rhoruby.h"
#include "common/Tokenizer.h"
#include "sync/RhoconnectClientManager.h"
#include "statistic/RhoProfiler.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#if !defined(OS_WINCE)
#ifdef OS_ANDROID
#include "../../platform/android/jni/ifaddrs.h"
#else
#include <ifaddrs.h>
#endif
#include <netinet/in.h>
#else
//#include <ws2tcpip.h>
#include "net/CompatWince.h"
#endif
#include <string.h>
#if !defined(WINDOWS_PLATFORM)
#include <arpa/inet.h>
#endif
#include "logging/RhoLog.h"
#define DEFAULT_LOGCATEGORY "Development_HTTPServer"
static DevHTTPServer* ourDevHTTPServer = NULL;
//ULONG GetSinIP(struct sockaddr_in *_psin, LPSTR pIPStr, UINT IPMaxLen)
//{
// unsigned long ipaddr;
//
// ipaddr = INADDR_NONE;
//
// if (pIPStr && IPMaxLen)
// *pIPStr = '\0';
//
// if ( _psin )
// {
//#if defined(_WIN32)
// ipaddr = _psin->sin_addr.S_un.S_addr;
//#else
// ipaddr = _psin->sin_addr.s_addr;
//#endif
//
// if (pIPStr && IPMaxLen)
// {
// char *pIP;
// struct in_addr in;
//
//#if defined(_WIN32)
// in.S_un.S_addr = ipaddr;
//#else
// in.s_addr = ipaddr;
//#endif
//
// pIP = inet_ntoa(in);
//
// if (pIP)
// adjust_str(pIP, pIPStr, IPMaxLen);
// }
// }
//
// return ipaddr;
//}
extern "C" rho::String get_local_ip_adress();
void DevHTTPServer::init() {
m_local_IP_adress = "";
rho::String szRootPath = rho_native_rhopath();
rho::String szUserPath = rho_native_rhouserpath();
m_httpServer = new rho::net::CHttpServer(RHO_DEVELOPMENT_SERVER_PORT, szRootPath, szUserPath, szRootPath, true, true);
m_httpServer->disableAllLogging();
#ifdef OS_ANDROID
m_local_IP_adress = get_local_ip_adress();
#elif defined(OS_WINCE)
char host[22];
hostent* host_info = 0 ;
if(gethostname(host, sizeof(host)) == SOCKET_ERROR) {
return;
}
host_info = gethostbyname(host);
if(host_info)
{
const in_addr* address = (in_addr*)host_info->h_addr_list[0];
rho::String addrIP = inet_ntoa( *address );
m_local_IP_adress = addrIP;
}
else
{
//error
}
#else
//Obtain the computer's IP
{
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa ->ifa_addr->sa_family == AF_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
unsigned char *n = (unsigned char*)(tmpAddrPtr);
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
if ((ifa->ifa_name[0] == 'e') && (ifa->ifa_name[1] == 'n')) {
// printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
m_local_IP_adress = addressBuffer;
}
}
// else if (ifa->ifa_addr->sa_family==AF_INET6) { // check it is IP6
// // is a valid IP6 Address
// tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
// char addressBuffer[INET6_ADDRSTRLEN];
// inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
// printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
// }
}
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
}
#endif
RAWTRACE("$$$ Our IP adress is : $$$");
RAWTRACE(m_local_IP_adress.c_str());
RAWTRACE("$$$$$$$$$$$$$$$$$$$$$$$$$$");
}
rho::net::CHttpServer* DevHTTPServer::getHTTPServer() {
return m_httpServer;
}
DevHTTPServer* DevHTTPServer::getInstance() {
if (ourDevHTTPServer == NULL) {
ourDevHTTPServer = new DevHTTPServer();
}
return ourDevHTTPServer;
}
rho::String DevHTTPServer::getLocalIPAdress() {
return m_local_IP_adress;
}
rho::String DevHTTPServer::getPort() {
rho::String res = "";
char ttt[16];
int port = m_httpServer->getPort();
sprintf(ttt, "%d", port);
res = ttt;
return res;
}
void DevHTTPServer::run() {
for (;;) {
m_httpServer->run();
}
}
void init_Development_HTTP_Server() {
DevHTTPServer * ds = DevHTTPServer::getInstance();
ds->init();
ds->start(rho::common::IRhoRunnable::epNormal);
}<|endoftext|> |
<commit_before>#include <iostream>
#include <cstring>
#include <csignal>
#include <list>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include "service.h"
#include "ev++.h"
#include "control.h"
/* TODO: prevent services from respawning too quickly */
/* TODO: detect/guard against dependency cycles */
/* TODO: optional automatic restart of services */
/*
* "simpleinit" from util-linux package handles signals as follows:
* SIGTSTP - spawn no more gettys (in preparation for shutdown etc).
* In dinit terms this should probably mean "no more auto restarts"
* (for any service). (Actually the signal acts as a toggle, if
* respawn is disabled it will be re-enabled and init will
* act as if SIGHUP had also been sent)
* SIGTERM - kill spawned gettys (which are still alive)
* Interestingly, simpleinit just sends a SIGTERM to the gettys.
* "shutdown" however has already sent SIGTERM to every process...
* "/sbin/initctl -r" - rollback services (ran by "shutdown"/halt etc)
* shouldn't return until all services have been stopped.
* shutdown calls this *after* sending SIGTERM to all processes.
* I guess this allows user processes, if any are still around,
* to die before (or just as) the services fall out from underneath
* them. On the other hand it largely subverts the ordered service
* shutdown that init provides.
* SIGQUIT - init will exec() shutdown. shutdown will detect that it is
* running as pid 1 and will just loop and reap child processes.
* This is used by shutdown so that init will not hang on to its
* inode, allowing clean filesystem unmounting.
*
* Not sent by shutdown:
* SIGHUP - re-read inittab and spawn any new getty entries
* SIGINT - (ctrl+alt+del handler) - fork & exec "reboot"
*
* On the contrary dinit currently uses:
* SIGTERM - roll back services and then exec /sbin/halt
* SIGINT - roll back services and then exec /sbin/reboot
*
* It's an open question about whether dinit should roll back services *before*
* running halt/reboot, since those commands should prompt rollback of services
* anyway. But it seems safe to do so.
*/
static bool got_sigterm = false;
static ServiceSet *service_set;
static bool am_system_init = false; // true if we are the system init process
static bool reboot = false; // whether to reboot (instead of halting)
static void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents);
static void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents);
static void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents);
static void open_control_socket(struct ev_loop *loop);
struct ev_io control_socket_io;
int main(int argc, char **argv)
{
using namespace std;
am_system_init = (getpid() == 1);
if (am_system_init) {
// setup STDIN, STDOUT, STDERR so that we can use them
int onefd = open("/dev/console", O_RDONLY, 0);
dup2(onefd, 0);
int twofd = open("/dev/console", O_RDWR, 0);
dup2(twofd, 1);
dup2(twofd, 2);
}
/* Set up signal handlers etc */
/* SIG_CHILD is ignored by default: good */
/* sigemptyset(&sigwait_set); */
/* sigaddset(&sigwait_set, SIGCHLD); */
/* sigaddset(&sigwait_set, SIGINT); */
/* sigaddset(&sigwait_set, SIGTERM); */
/* sigprocmask(SIG_BLOCK, &sigwait_set, NULL); */
/* list of services to start */
list<const char *> services_to_start;
/* service directory name */
const char * service_dir = "/etc/dinit.d";
/* arguments, if given, specify a list of services to start. */
/* if none are given the "boot" service is started. */
if (argc > 1) {
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
// An option...
if (strcmp(argv[i], "--services-dir") == 0 ||
strcmp(argv[i], "-d") == 0) {
++i;
if (i < argc) {
service_dir = argv[i];
}
else {
// error TODO
}
}
else if (strcmp(argv[i], "--help") == 0) {
cout << "dinit, an init with dependency management" << endl;
cout << " --help : display help" << endl;
cout << " --services-dir <dir>, -d <dir> : set base directory for service description files (-d <dir>)" << endl;
cout << " <service-name> : start service with name <service-name>" << endl;
return 0;
}
else {
// unrecognized
if (! am_system_init) {
cerr << "Unrecognized option: " << argv[i] << endl;
return 1;
}
}
}
else {
// LILO puts "auto" on the kernel command line for unattended boots; we'll filter it.
if (! am_system_init || strcmp(argv[i], "auto") != 0) {
services_to_start.push_back(argv[i]);
}
}
}
}
if (services_to_start.empty()) {
services_to_start.push_back("boot");
}
// Set up signal handlers
ev_signal sigint_ev_signal;
if (am_system_init) {
ev_signal_init(&sigint_ev_signal, sigint_reboot_cb, SIGINT);
}
else {
ev_signal_init(&sigint_ev_signal, sigterm_cb, SIGINT);
}
ev_signal sigquit_ev_signal;
if (am_system_init) {
// PID 1: SIGQUIT exec's shutdown
ev_signal_init(&sigquit_ev_signal, sigquit_cb, SIGQUIT);
}
else {
// Otherwise: SIGQUIT terminates dinit
ev_signal_init(&sigquit_ev_signal, sigterm_cb, SIGQUIT);
}
ev_signal sigterm_ev_signal;
ev_signal_init(&sigterm_ev_signal, sigterm_cb, SIGTERM);
/* Set up libev */
struct ev_loop *loop = ev_default_loop(EVFLAG_AUTO /* | EVFLAG_SIGNALFD */);
ev_signal_start(loop, &sigint_ev_signal);
ev_signal_start(loop, &sigquit_ev_signal);
ev_signal_start(loop, &sigterm_ev_signal);
// Try to open control socket (may fail due to readonly filesystem)
open_control_socket(loop);
/* start requested services */
service_set = new ServiceSet(service_dir);
for (list<const char *>::iterator i = services_to_start.begin();
i != services_to_start.end();
++i) {
try {
service_set->startService(*i);
}
catch (ServiceNotFound &snf) {
// TODO log this better
cerr << "Could not find service description: " << snf.serviceName << endl;
}
catch (ServiceLoadExc &sle) {
// TODO log this better
cerr << "Problem loading service description: " << sle.serviceName << endl;
}
}
event_loop:
// Process events until all services have terminated.
while (! service_set->count_active_services() == 0) {
ev_loop(loop, EVLOOP_ONESHOT);
}
if (am_system_init) {
// TODO log this output properly
cout << "dinit: No more active services.";
if (reboot) {
cout << " Will reboot.";
}
else if (got_sigterm) {
cout << " Will halt.";
}
else {
cout << " Re-initiating boot sequence.";
}
cout << endl;
}
if (am_system_init) {
if (reboot) {
// TODO log error from fork
if (fork() == 0) {
execl("/sbin/reboot", "/sbin/reboot", (char *) 0);
}
}
else if (got_sigterm) {
// TODO log error from fork
if (fork() == 0) {
execl("/sbin/halt", "/sbin/halt", (char *) 0);
}
}
else {
// Hmmmmmm.
// It could be that we started in single user mode, and the
// user has now exited the shell. We'll try and re-start the
// boot process...
try {
service_set->startService("boot");
goto event_loop; // yes, the "evil" goto
}
catch (...) {
// TODO catch exceptions and log message as appropriate
// Now WTF do we do? try and reboot
if (fork() == 0) {
execl("/sbin/reboot", "/sbin/reboot", (char *) 0);
}
}
}
// PID 1 should never exit:
while (true) {
pause();
}
}
return 0;
}
// Callback for control socket
static void control_socket_cb(struct ev_loop *loop, ev_io *w, int revents)
{
// Accept a connection
int sockfd = w->fd;
int newfd = accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (newfd != -1) {
new ControlConn(loop, service_set, newfd); // will delete itself when it's finished
// TODO keep a set of control connections so that we can close them when
// terminating?
}
}
static void open_control_socket(struct ev_loop *loop)
{
// TODO make this use a per-user address if PID != 1, and make the address
// overridable from the command line
const char * saddrname = "/dev/dinitctl";
struct sockaddr_un name;
unlink(saddrname);
name.sun_family = AF_UNIX;
strcpy(name.sun_path, saddrname); // TODO make this safe for long names
int namelen = 2 + strlen(saddrname);
//int namelen = sizeof(name);
int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (sockfd == -1) {
// TODO log error
perror("socket");
return;
}
if (bind(sockfd, (struct sockaddr *) &name, namelen) == -1) {
// TODO log error
perror("bind");
close(sockfd);
return;
}
if (listen(sockfd, 10) == -1) {
// TODO log error
perror("listen");
close(sockfd);
return;
}
ev_io_init(&control_socket_io, control_socket_cb, sockfd, EV_READ);
ev_io_start(loop, &control_socket_io);
}
/* handle SIGINT signal (generated by kernel when ctrl+alt+del pressed) */
static void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents)
{
reboot = true;
service_set->stop_all_services();
}
/* handle SIGQUIT (if we are system init) */
static void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents)
{
// This allows remounting the filesystem read-only if the dinit binary has been
// unlinked. In that case the kernel holds the binary open, so that it can't be
// properly removed.
execl("/sbin/shutdown", "/sbin/shutdown", (char *) 0);
}
/* handle SIGTERM - stop all services */
static void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents)
{
got_sigterm = true;
service_set->stop_all_services();
}
<commit_msg>Just adding some comments.<commit_after>#include <iostream>
#include <cstring>
#include <csignal>
#include <list>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include "service.h"
#include "ev++.h"
#include "control.h"
/* TODO: prevent services from respawning too quickly */
/* TODO: detect/guard against dependency cycles */
/* TODO: optional automatic restart of services */
/*
* "simpleinit" from util-linux package handles signals as follows:
* SIGTSTP - spawn no more gettys (in preparation for shutdown etc).
* In dinit terms this should probably mean "no more auto restarts"
* (for any service). (Actually the signal acts as a toggle, if
* respawn is disabled it will be re-enabled and init will
* act as if SIGHUP had also been sent)
* SIGTERM - kill spawned gettys (which are still alive)
* Interestingly, simpleinit just sends a SIGTERM to the gettys.
* "shutdown" however has already sent SIGTERM to every process...
* "/sbin/initctl -r" - rollback services (ran by "shutdown"/halt etc)
* shouldn't return until all services have been stopped.
* shutdown calls this *after* sending SIGTERM to all processes.
* I guess this allows user processes, if any are still around,
* to die before (or just as) the services fall out from underneath
* them. On the other hand it largely subverts the ordered service
* shutdown that init provides.
* SIGQUIT - init will exec() shutdown. shutdown will detect that it is
* running as pid 1 and will just loop and reap child processes.
* This is used by shutdown so that init will not hang on to its
* inode, allowing clean filesystem unmounting.
*
* Not sent by shutdown:
* SIGHUP - re-read inittab and spawn any new getty entries
* SIGINT - (ctrl+alt+del handler) - fork & exec "reboot"
*
* On the contrary dinit currently uses:
* SIGTERM - roll back services and then exec /sbin/halt
* SIGINT - roll back services and then exec /sbin/reboot
*
* It's an open question about whether dinit should roll back services *before*
* running halt/reboot, since those commands should prompt rollback of services
* anyway. But it seems safe to do so.
*/
static bool got_sigterm = false;
static ServiceSet *service_set;
static bool am_system_init = false; // true if we are the system init process
static bool reboot = false; // whether to reboot (instead of halting)
static void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents);
static void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents);
static void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents);
static void open_control_socket(struct ev_loop *loop);
struct ev_io control_socket_io;
int main(int argc, char **argv)
{
using namespace std;
am_system_init = (getpid() == 1);
if (am_system_init) {
// setup STDIN, STDOUT, STDERR so that we can use them
int onefd = open("/dev/console", O_RDONLY, 0);
dup2(onefd, 0);
int twofd = open("/dev/console", O_RDWR, 0);
dup2(twofd, 1);
dup2(twofd, 2);
}
/* Set up signal handlers etc */
/* SIG_CHILD is ignored by default: good */
/* sigemptyset(&sigwait_set); */
/* sigaddset(&sigwait_set, SIGCHLD); */
/* sigaddset(&sigwait_set, SIGINT); */
/* sigaddset(&sigwait_set, SIGTERM); */
/* sigprocmask(SIG_BLOCK, &sigwait_set, NULL); */
/* list of services to start */
list<const char *> services_to_start;
/* service directory name */
const char * service_dir = "/etc/dinit.d";
// Arguments, if given, specify a list of services to start.
// If we are running as init (PID=1), the kernel gives us any command line
// arguments it was given but didn't recognize, including "single" (usual
// for "boot to single user mode" aka just start the shell). We can treat
// them as services. In the worst case we can't find any of the named
// services, and so we'll start the "boot" service by default.
if (argc > 1) {
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
// An option...
if (strcmp(argv[i], "--services-dir") == 0 ||
strcmp(argv[i], "-d") == 0) {
++i;
if (i < argc) {
service_dir = argv[i];
}
else {
// error TODO
}
}
else if (strcmp(argv[i], "--help") == 0) {
cout << "dinit, an init with dependency management" << endl;
cout << " --help : display help" << endl;
cout << " --services-dir <dir>, -d <dir> : set base directory for service description files (-d <dir>)" << endl;
cout << " <service-name> : start service with name <service-name>" << endl;
return 0;
}
else {
// unrecognized
if (! am_system_init) {
cerr << "Unrecognized option: " << argv[i] << endl;
return 1;
}
}
}
else {
// LILO puts "auto" on the kernel command line for unattended boots; we'll filter it.
if (! am_system_init || strcmp(argv[i], "auto") != 0) {
services_to_start.push_back(argv[i]);
}
}
}
}
if (services_to_start.empty()) {
services_to_start.push_back("boot");
}
// Set up signal handlers
ev_signal sigint_ev_signal;
if (am_system_init) {
ev_signal_init(&sigint_ev_signal, sigint_reboot_cb, SIGINT);
}
else {
ev_signal_init(&sigint_ev_signal, sigterm_cb, SIGINT);
}
ev_signal sigquit_ev_signal;
if (am_system_init) {
// PID 1: SIGQUIT exec's shutdown
ev_signal_init(&sigquit_ev_signal, sigquit_cb, SIGQUIT);
}
else {
// Otherwise: SIGQUIT terminates dinit
ev_signal_init(&sigquit_ev_signal, sigterm_cb, SIGQUIT);
}
ev_signal sigterm_ev_signal;
ev_signal_init(&sigterm_ev_signal, sigterm_cb, SIGTERM);
/* Set up libev */
struct ev_loop *loop = ev_default_loop(EVFLAG_AUTO /* | EVFLAG_SIGNALFD */);
ev_signal_start(loop, &sigint_ev_signal);
ev_signal_start(loop, &sigquit_ev_signal);
ev_signal_start(loop, &sigterm_ev_signal);
// Try to open control socket (may fail due to readonly filesystem)
open_control_socket(loop);
/* start requested services */
service_set = new ServiceSet(service_dir);
for (list<const char *>::iterator i = services_to_start.begin();
i != services_to_start.end();
++i) {
try {
service_set->startService(*i);
}
catch (ServiceNotFound &snf) {
// TODO log this better
cerr << "Could not find service description: " << snf.serviceName << endl;
}
catch (ServiceLoadExc &sle) {
// TODO log this better
cerr << "Problem loading service description: " << sle.serviceName << endl;
}
}
event_loop:
// Process events until all services have terminated.
while (! service_set->count_active_services() == 0) {
ev_loop(loop, EVLOOP_ONESHOT);
}
if (am_system_init) {
// TODO log this output properly
cout << "dinit: No more active services.";
if (reboot) {
cout << " Will reboot.";
}
else if (got_sigterm) {
cout << " Will halt.";
}
else {
cout << " Re-initiating boot sequence.";
}
cout << endl;
}
if (am_system_init) {
if (reboot) {
// TODO log error from fork
if (fork() == 0) {
execl("/sbin/reboot", "/sbin/reboot", (char *) 0);
}
}
else if (got_sigterm) {
// TODO log error from fork
if (fork() == 0) {
execl("/sbin/halt", "/sbin/halt", (char *) 0);
}
}
else {
// Hmmmmmm.
// It could be that we started in single user mode, and the
// user has now exited the shell. We'll try and re-start the
// boot process...
try {
service_set->startService("boot");
goto event_loop; // yes, the "evil" goto
}
catch (...) {
// TODO catch exceptions and log message as appropriate
// Now WTF do we do? try and reboot
if (fork() == 0) {
execl("/sbin/reboot", "/sbin/reboot", (char *) 0);
}
}
}
// PID 1 should never exit:
while (true) {
pause();
}
}
return 0;
}
// Callback for control socket
static void control_socket_cb(struct ev_loop *loop, ev_io *w, int revents)
{
// TODO limit the number of active connections. Keep a tally, and disable the
// control connection listening socket watcher if it gets high, and re-enable
// it once it falls below the maximum.
// Accept a connection
int sockfd = w->fd;
int newfd = accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (newfd != -1) {
new ControlConn(loop, service_set, newfd); // will delete itself when it's finished
// TODO keep a set of control connections so that we can close them when
// terminating?
}
}
static void open_control_socket(struct ev_loop *loop)
{
// TODO make this use a per-user address if PID != 1, and make the address
// overridable from the command line
const char * saddrname = "/dev/dinitctl";
struct sockaddr_un name;
unlink(saddrname);
name.sun_family = AF_UNIX;
strcpy(name.sun_path, saddrname); // TODO make this safe for long names
int namelen = 2 + strlen(saddrname);
//int namelen = sizeof(name);
int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (sockfd == -1) {
// TODO log error
perror("socket");
return;
}
if (bind(sockfd, (struct sockaddr *) &name, namelen) == -1) {
// TODO log error
perror("bind");
close(sockfd);
return;
}
if (listen(sockfd, 10) == -1) {
// TODO log error
perror("listen");
close(sockfd);
return;
}
ev_io_init(&control_socket_io, control_socket_cb, sockfd, EV_READ);
ev_io_start(loop, &control_socket_io);
}
/* handle SIGINT signal (generated by kernel when ctrl+alt+del pressed) */
static void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents)
{
reboot = true;
service_set->stop_all_services();
}
/* handle SIGQUIT (if we are system init) */
static void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents)
{
// This allows remounting the filesystem read-only if the dinit binary has been
// unlinked. In that case the kernel holds the binary open, so that it can't be
// properly removed.
execl("/sbin/shutdown", "/sbin/shutdown", (char *) 0);
}
/* handle SIGTERM - stop all services */
static void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents)
{
got_sigterm = true;
service_set->stop_all_services();
}
<|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
}<|endoftext|> |
<commit_before>/*
* AdjMatrix.cpp
*
* Created on: 17/apr/2010
* Author: ciccio
*/
#include "AdjMatrix.h"
#include <stdio.h>
#include <vector>
#include "globals.h"
using namespace std;
AdjMatrix::AdjMatrix() {
// TODO Auto-generated constructor stub
}
AdjMatrix::~AdjMatrix() {
for(int i=0;i<_n;i++)
delete (*_mat)[i];
delete *_mat;
delete _mat;
}
AdjMatrix::AdjMatrix(int n, int m) {
_n=n;
_m=m;
_mat= new int **;
(*_mat)= new int *[n];
for(int i=0;i<n;i++) {
(*_mat)[i]=new int [m];
for(int j=0;j<m;j++)
(*_mat)[i][j]=0;
}
}
void AdjMatrix::toDot(Nodeset &Ns) {
FILE *fid;
Nodeset::iterator i;
Nodeset::iterator j;
int ii=0, ij=0;
fid=fopen((string(protname) + ".dot").c_str(), "w");
string attr_string="";
std::map<std::string, std::string>::iterator mapit;
std::map<std::string, std::string> attribs;
fprintf(fid, "digraph G {\n");
fprintf(fid, "node [shape=box, style=rounded];\n");
fprintf(fid, "rankdir=LR;\n");
for(i=Ns.begin(); i!=Ns.end(); ++i){
attr_string = "[ label = ";
attr_string += i->getName();
attribs = i->GetAttributes();
for(mapit = attribs.begin(); mapit!=attribs.end(); mapit++){
attr_string += ", ";
attr_string += (mapit -> first).c_str();
attr_string += " = ";
attr_string += (mapit -> second).c_str();
}
attr_string += "] ";
fprintf(fid, "%d %s;\n", i->getId(), attr_string.c_str());
//fprintf(fid, "%d [ label = \"%s\", color = \"%s\" ];\n", i->getId(), i->getName().c_str(), i->GetAttribute("color").c_str());
}
for (ii=0;ii<_n;++ii){ // process ARCs
for (ij=0; ij<_m; ++ij) {
if((*_mat)[ii][ij])
fprintf(fid, "%d->%d;\n", ii, ij);
}
}
fprintf(fid, "}");
fclose(fid);
}
void AdjMatrix::Set(unsigned i, unsigned j)
{
(*_mat)[i][j]=1;
}
ostream& AdjMatrix::operator>>(std::ostream &){
int j,i;
for(i=0; i<_n; i++){
for(j=0; j<_m-1; j++)
cout << (*_mat)[i][j] << ",";
cout <<(*_mat)[i][j] << endl;
}
}
<commit_msg>Added empty arrows for F flag.<commit_after>/*
* AdjMatrix.cpp
*
* Created on: 17/apr/2010
* Author: ciccio
*/
#include "AdjMatrix.h"
#include <stdio.h>
#include <vector>
#include "globals.h"
using namespace std;
AdjMatrix::AdjMatrix() {
// TODO Auto-generated constructor stub
}
AdjMatrix::~AdjMatrix() {
for(int i=0;i<_n;i++)
delete (*_mat)[i];
delete *_mat;
delete _mat;
}
AdjMatrix::AdjMatrix(int n, int m) {
_n=n;
_m=m;
_mat= new int **;
(*_mat)= new int *[n];
for(int i=0;i<n;i++) {
(*_mat)[i]=new int [m];
for(int j=0;j<m;j++)
(*_mat)[i][j]=0;
}
}
void AdjMatrix::toDot(Nodeset &Ns) {
FILE *fid;
Nodeset::iterator i;
Nodeset::iterator j;
int ii=0, ij=0;
fid=fopen((string(protname) + ".dot").c_str(), "w");
string attr_string="";
std::map<std::string, std::string>::iterator mapit;
std::map<std::string, std::string> attribs;
fprintf(fid, "digraph G {\n");
fprintf(fid, "node [shape=box, style=rounded];\n");
fprintf(fid, "rankdir=LR;\n");
for(i=Ns.begin(); i!=Ns.end(); ++i){
attr_string = "[ label = ";
attr_string += i->getName();
attribs = i->GetAttributes();
for(mapit = attribs.begin(); mapit!=attribs.end(); mapit++){
attr_string += ", ";
attr_string += (mapit -> first).c_str();
attr_string += " = ";
attr_string += (mapit -> second).c_str();
}
attr_string += "] ";
fprintf(fid, "%d %s;\n", i->getId(), attr_string.c_str());
//fprintf(fid, "%d [ label = \"%s\", color = \"%s\" ];\n", i->getId(), i->getName().c_str(), i->GetAttribute("color").c_str());
}
for (ii=0, i=Ns.begin(); ii<_n; ++ii, ++i){ // process ARCs
for (ij=0; ij<_m; ++ij) {
if((*_mat)[ii][ij]) {
bool found = false;
attribs = i->GetAttributes();
for(mapit = attribs.begin(); mapit!=attribs.end(); mapit++){
if(mapit->first == "LEAF_FLAGS" && mapit->second == "F") {
fprintf(fid, "%d->%d [arrowhead = \"empty\"];\n", ii, ij);
found = true;
}
}
if (!found)
fprintf(fid, "%d->%d;\n", ii, ij);
}
}
}
fprintf(fid, "}");
fclose(fid);
}
void AdjMatrix::Set(unsigned i, unsigned j)
{
(*_mat)[i][j]=1;
}
ostream& AdjMatrix::operator>>(std::ostream &){
int j,i;
for(i=0; i<_n; i++){
for(j=0; j<_m-1; j++)
cout << (*_mat)[i][j] << ",";
cout <<(*_mat)[i][j] << endl;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 CEA LIST
*
* This file is part of LIMA.
*
* LIMA 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.
*
* LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/>
*/
#include "LimaFileSystemWatcherTest.h"
#include "common/misc/LimaFileSystemWatcher.h"
#include "common/QsLog/QsLogCategories.h"
#include "common/AbstractFactoryPattern/AmosePluginsManager.h"
#include <QtCore/QTemporaryFile>
#include <QtTest/QtTest>
using namespace Lima;
QTEST_MAIN ( LimaFileSystemWatcherTest );
void LimaFileSystemWatcherTest::initTestCase()
{
// Called before the first testfunction is executed
QsLogging::initQsLog();
// Necessary to initialize factories under Windows
Lima::AmosePluginsManager::single();
}
void LimaFileSystemWatcherTest::cleanupTestCase()
{
// Called after the last testfunction was executed
}
void LimaFileSystemWatcherTest::init()
{
// Called before each testfunction is executed
}
void LimaFileSystemWatcherTest::cleanup()
{
// Called after every testfunction
}
void LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0()
{
LimaFileSystemWatcher watcher;
QSignalSpy stateSpy( &watcher, SIGNAL( fileChanged ( QString) ) );
QVERIFY( stateSpy.isValid() );
QCOMPARE( stateSpy.count(), 0 );
QTemporaryFile tmpFile;
tmpFile.setAutoRemove(false);
QVERIFY2(tmpFile.open(),"Was not able to open the temporary file");
QString tmpFileName = tmpFile.fileName();
watcher.addPath(tmpFileName);
QTextStream out(&tmpFile);
out << "yo";
tmpFile.close();
QVERIFY2( QFile(tmpFileName).exists(), "The tmpFile does not exist while it should");
QTest::qWait(500);
// we changed the file. The fileChanged signal should have been triggered
QCOMPARE( stateSpy.count(), 1 );
// remove the tmp file. This should trigger the signal
QFile::remove(tmpFileName);
QVERIFY2( !QFile(tmpFileName).exists(), "The tmpFile still exists while it has been removed");
QTest::qWait(500);
// we removed the file. The fileChanged signal should have been triggered
QCOMPARE( stateSpy.count(), 2 );
// recreate the file. This should also trigger the signal
QFile recreatedFile(tmpFileName);
QVERIFY2( recreatedFile.open(QIODevice::ReadWrite), "Was not able to recreate the file");
recreatedFile.close();
QTest::qWait(500);
// we recreated the file. The fileChanged signal should have been triggered
QCOMPARE( stateSpy.count(), 3 );
}
<commit_msg>Debug messages<commit_after>/*
* Copyright 2015 CEA LIST
*
* This file is part of LIMA.
*
* LIMA 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.
*
* LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/>
*/
#include "LimaFileSystemWatcherTest.h"
#include "common/misc/LimaFileSystemWatcher.h"
#include "common/QsLog/QsLogCategories.h"
#include "common/AbstractFactoryPattern/AmosePluginsManager.h"
#include <QtCore/QTemporaryFile>
#include <QtTest/QtTest>
using namespace Lima;
QTEST_MAIN ( LimaFileSystemWatcherTest );
void LimaFileSystemWatcherTest::initTestCase()
{
// Called before the first testfunction is executed
QsLogging::initQsLog();
// Necessary to initialize factories under Windows
Lima::AmosePluginsManager::single();
}
void LimaFileSystemWatcherTest::cleanupTestCase()
{
// Called after the last testfunction was executed
std::cerr << "LimaFileSystemWatcherTest::cleanupTestCase" << std::endl;
}
void LimaFileSystemWatcherTest::init()
{
// Called before each testfunction is executed
}
void LimaFileSystemWatcherTest::cleanup()
{
// Called after every testfunction
}
void LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0()
{
LimaFileSystemWatcher watcher;
QSignalSpy stateSpy( &watcher, SIGNAL( fileChanged ( QString) ) );
QVERIFY( stateSpy.isValid() );
QCOMPARE( stateSpy.count(), 0 );
QTemporaryFile tmpFile;
QVERIFY2(tmpFile.open(),"Was not able to open the temporary file");
QString tmpFileName = tmpFile.fileName();
watcher.addPath(tmpFileName);
QTextStream out(&tmpFile);
out << "yo";
tmpFile.close();
QVERIFY2( QFile(tmpFileName).exists(), "The tmpFile does not exist while it should");
QTest::qWait(500);
// we changed the file. The fileChanged signal should have been triggered
QCOMPARE( stateSpy.count(), 1 );
std::cerr << "LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0 1" << std::endl;
// remove the tmp file. This should trigger the signal
QFile::remove(tmpFileName);
QVERIFY2( !QFile(tmpFileName).exists(), "The tmpFile still exists while it has been removed");
QTest::qWait(500);
// we removed the file. The fileChanged signal should have been triggered
QCOMPARE( stateSpy.count(), 2 );
std::cerr << "LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0 2" << std::endl;
// recreate the file. This should also trigger the signal
QFile recreatedFile(tmpFileName);
QVERIFY2( recreatedFile.open(QIODevice::ReadWrite), "Was not able to recreate the file");
recreatedFile.close();
QTest::qWait(500);
// we recreated the file. The fileChanged signal should have been triggered
QCOMPARE( stateSpy.count(), 3 );
std::cerr << "LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0 3" << std::endl;
}
<|endoftext|> |
<commit_before>#pragma once
#include "dllist.cpp"
template <typename T>
class DoubleLinkedChain : public DoubleLinkedList<T>
{
protected:
void copy(const DoubleLinkedChain<T>& other)
{
if (!other.front || !other.back)
return;
DoubleListElement<T> *pFront = other.front, *pn = pFront->prev;
DoubleLinkedList<T> lFront;
while (pFront && pFront->prev == pn)
{
lFront.insertEnd(pFront->data);
pn = pFront;
pFront = pFront->next;
}
if (pFront)
{
DoubleListElement<T> *pBack = other.back;
pn = pBack->next;
DoubleLinkedList<T> lBack;
while (pBack && pBack->next == pn)
{
lBack.insertBegin(pBack->data);
pn = pBack;
pBack = pBack->prev;
}
lFront.back->next = pFront;
lBack.front->prev = pBack;
this->front = lFront.front;
this->back = lBack.back;
lBack.back = lBack.front = NULL;
}
else
{
this->front = lFront.front;
this->back = lFront.back;
}
lFront.back = lFront.front = NULL;
}
public:
void clear()
{
if (!this->front || !this->back)
return;
DoubleListElement<T> *pFront = this->front, *prev = pFront->prev;
while (pFront && pFront->prev == prev)
{
prev = pFront;
pFront = pFront->next;
}
prev->next = NULL;
DoubleListElement<T> *pBack = this->back, *next = pBack->next;
while (pBack && pBack->next == next)
{
next = pBack;
pBack = pBack->prev;
}
next->prev = NULL;
DoubleLinkedList<T> lFront, lBack;
lFront.front = this->front;
lFront.back = prev;
if (this->front != next && prev != this->back)
{
lBack.front = next;
lBack.back = this->back;
}
this->back = this->front = NULL;
}
DoubleLinkedChain()
{
this->front = NULL;
this->back = NULL;
}
DoubleLinkedChain(const DoubleLinkedChain& other)
{
copy(other);
}
DoubleLinkedChain& operator=(const DoubleLinkedChain& other)
{
if (&other != this)
{
clear();
copy(other);
}
return *this;
}
~DoubleLinkedChain()
{
clear();
}
DoubleListElement<T>* getFrontPtr() { return this->front; }
const DoubleListElement<T>* getFrontPtr() const { return this->front; }
DoubleListElement<T>* getBackPtr() { return this->back; }
const DoubleListElement<T>* getBackPtr() const { return this->back; }
bool adoptList(DoubleLinkedList<T>& l)
{
if (!l.front || !l.back)
return false;
clear();
this->front = l.front;
this->back = l.back;
l.front = NULL;
l.back = NULL;
return true;
}
bool attachAtBegin(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
{
if (it)
{
if (this->front)
{
this->front->prev = it.ptr;
if (it.ptr == l.back)
it.ptr->next = this->front;
while (this->front && this->front->prev)
this->front = this->front->prev;
}
else
{
this->front = l.front;
this->back = l.back;
}
l.front = NULL;
l.back = NULL;
return true;
}
else
return false;
}
bool attachAtEnd(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
{
if (it)
{
if (this->back)
{
this->back->next = it.ptr;
if (it.ptr == l.front)
it.ptr->prev = this->back;
while (this->back && this->back->next)
this->back = this->back->next;
}
else
{
this->front = l.front;
this->back = l.back;
}
l.front = NULL;
l.back = NULL;
return true;
}
else
return false;
}
bool attachListAtFront(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
{
if (it && l.front && !l.front->prev)
{
l.front->prev = it.ptr;
if (it.ptr == this->back)
{
this->back->next = l.front;
while (this->back && this->back->next)
this->back = this->back->next;
}
return true;
}
else
return false;
}
bool attachListAtBack(DoubleLinkedList<T>& l,
DoubleLinkedListIterator<T>& it)
{
if (it && l.back && !l.back->next)
{
l.back->next = it.ptr;
if (it.ptr == this->front)
{
this->front->back = l.back;
while (this->front && this->front->prev)
this->front = this->front->prev;
}
return true;
}
else
return false;
}
bool join_at(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2,
DoubleLinkedListIterator<T>& M1, DoubleLinkedListIterator<T>& M2)
{
return adoptList(L1) && attachListAtFront(L2, M1) &&
attachAtEnd(L2, M2);
}
bool join(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2)
{
DoubleLinkedListIterator<T> itL1 = L1.begin(), itL2 = L2.end(), M1, M2;
while (itL1 && itL2)
{
if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
{
M1 = itL1;
M2 = itL2;
}
itL1++;
itL2--;
}
itL1 = L1.end();
itL2 = L2.begin();
while (itL1 && itL2)
{
if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
{
M1 = itL1;
M2 = itL2;
}
itL1--;
itL2++;
}
return join_at(L1, L2, M1, M2);
}
bool isJoined() const
{
if (!this->front || !this->back)
return false;
DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;
while (pFront && pFront->prev == pn)
{
pn = pFront;
pFront = pFront->next;
}
DoubleListElement<T> *pBack = this->back;
pn = pBack->next;
while (pBack && pBack->next == pn)
{
pn = pBack;
pBack = pBack->prev;
}
return pFront && pBack;
}
T sum() const
{
T S = T();
if (!this->front || !this->back)
return S;
DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;
while (pFront && pFront->prev == pn)
{
S += pFront->data;
pn = pFront;
pFront = pFront->next;
}
if (pFront)
{
DoubleListElement<T> *pBack = this->back;
pn = pBack->next;
while (pBack && pBack->next == pn)
{
S += pBack->data;
pn = pBack;
pBack = pBack->prev;
}
}
return S;
}
};
<commit_msg>fixed formatting issue<commit_after>#pragma once
#include "dllist.cpp"
template <typename T>
class DoubleLinkedChain : public DoubleLinkedList<T>
{
protected:
void copy(const DoubleLinkedChain<T>& other)
{
if (!other.front || !other.back)
return;
DoubleListElement<T> *pFront = other.front, *pn = pFront->prev;
DoubleLinkedList<T> lFront;
while (pFront && pFront->prev == pn)
{
lFront.insertEnd(pFront->data);
pn = pFront;
pFront = pFront->next;
}
if (pFront)
{
DoubleListElement<T> *pBack = other.back;
pn = pBack->next;
DoubleLinkedList<T> lBack;
while (pBack && pBack->next == pn)
{
lBack.insertBegin(pBack->data);
pn = pBack;
pBack = pBack->prev;
}
lFront.back->next = pFront;
lBack.front->prev = pBack;
this->front = lFront.front;
this->back = lBack.back;
lBack.back = lBack.front = NULL;
}
else
{
this->front = lFront.front;
this->back = lFront.back;
}
lFront.back = lFront.front = NULL;
}
public:
void clear()
{
if (!this->front || !this->back)
return;
DoubleListElement<T> *pFront = this->front, *prev = pFront->prev;
while (pFront && pFront->prev == prev)
{
prev = pFront;
pFront = pFront->next;
}
prev->next = NULL;
DoubleListElement<T> *pBack = this->back, *next = pBack->next;
while (pBack && pBack->next == next)
{
next = pBack;
pBack = pBack->prev;
}
next->prev = NULL;
DoubleLinkedList<T> lFront, lBack;
lFront.front = this->front;
lFront.back = prev;
if (this->front != next && prev != this->back)
{
lBack.front = next;
lBack.back = this->back;
}
this->back = this->front = NULL;
}
DoubleLinkedChain()
{
this->front = NULL;
this->back = NULL;
}
DoubleLinkedChain(const DoubleLinkedChain& other)
{
copy(other);
}
DoubleLinkedChain& operator=(const DoubleLinkedChain& other)
{
if (&other != this)
{
clear();
copy(other);
}
return *this;
}
~DoubleLinkedChain()
{
clear();
}
DoubleListElement<T>* getFrontPtr() { return this->front; }
const DoubleListElement<T>* getFrontPtr() const { return this->front; }
DoubleListElement<T>* getBackPtr() { return this->back; }
const DoubleListElement<T>* getBackPtr() const { return this->back; }
bool adoptList(DoubleLinkedList<T>& l)
{
if (!l.front || !l.back)
return false;
clear();
this->front = l.front;
this->back = l.back;
l.front = NULL;
l.back = NULL;
return true;
}
bool attachAtBegin(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
{
if (it)
{
if (this->front)
{
this->front->prev = it.ptr;
if (it.ptr == l.back)
it.ptr->next = this->front;
while (this->front && this->front->prev)
this->front = this->front->prev;
}
else
{
this->front = l.front;
this->back = l.back;
}
l.front = NULL;
l.back = NULL;
return true;
}
else
return false;
}
bool attachAtEnd(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
{
if (it)
{
if (this->back)
{
this->back->next = it.ptr;
if (it.ptr == l.front)
it.ptr->prev = this->back;
while (this->back && this->back->next)
this->back = this->back->next;
}
else
{
this->front = l.front;
this->back = l.back;
}
l.front = NULL;
l.back = NULL;
return true;
}
else
return false;
}
bool attachListAtFront(DoubleLinkedList<T>& l,
DoubleLinkedListIterator<T>& it)
{
if (it && l.front && !l.front->prev)
{
l.front->prev = it.ptr;
if (it.ptr == this->back)
{
this->back->next = l.front;
while (this->back && this->back->next)
this->back = this->back->next;
}
return true;
}
else
return false;
}
bool attachListAtBack(DoubleLinkedList<T>& l,
DoubleLinkedListIterator<T>& it)
{
if (it && l.back && !l.back->next)
{
l.back->next = it.ptr;
if (it.ptr == this->front)
{
this->front->back = l.back;
while (this->front && this->front->prev)
this->front = this->front->prev;
}
return true;
}
else
return false;
}
bool join_at(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2,
DoubleLinkedListIterator<T>& M1, DoubleLinkedListIterator<T>& M2)
{
return adoptList(L1) && attachListAtFront(L2, M1) &&
attachAtEnd(L2, M2);
}
bool join(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2)
{
DoubleLinkedListIterator<T> itL1 = L1.begin(), itL2 = L2.end(), M1, M2;
while (itL1 && itL2)
{
if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
{
M1 = itL1;
M2 = itL2;
}
itL1++;
itL2--;
}
itL1 = L1.end();
itL2 = L2.begin();
while (itL1 && itL2)
{
if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
{
M1 = itL1;
M2 = itL2;
}
itL1--;
itL2++;
}
return join_at(L1, L2, M1, M2);
}
bool isJoined() const
{
if (!this->front || !this->back)
return false;
DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;
while (pFront && pFront->prev == pn)
{
pn = pFront;
pFront = pFront->next;
}
DoubleListElement<T> *pBack = this->back;
pn = pBack->next;
while (pBack && pBack->next == pn)
{
pn = pBack;
pBack = pBack->prev;
}
return pFront && pBack;
}
T sum() const
{
T S = T();
if (!this->front || !this->back)
return S;
DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;
while (pFront && pFront->prev == pn)
{
S += pFront->data;
pn = pFront;
pFront = pFront->next;
}
if (pFront)
{
DoubleListElement<T> *pBack = this->back;
pn = pBack->next;
while (pBack && pBack->next == pn)
{
S += pBack->data;
pn = pBack;
pBack = pBack->prev;
}
}
return S;
}
};
<|endoftext|> |
<commit_before>/**
* \file
*/
#pragma once
#include "future.hpp"
#include <boost/asio.hpp>
#include <curl/curl.h>
#include <cstddef>
#include <exception>
#include <memory>
#include <mutex>
#include <unordered_map>
namespace asiocurl {
/**
* Services curl easy handles using Boost.ASIO.
*/
class io_service {
private:
class control {
private:
using mutex_type=std::recursive_mutex;
mutable mutex_type m_;
bool stop_;
public:
control (const control &) = delete;
control (control &&) = delete;
control & operator = (const control &) = delete;
control & operator = (control &&) = delete;
control ();
using guard_type=std::unique_lock<mutex_type>;
guard_type lock () const noexcept;
explicit operator bool () const noexcept;
void stop () noexcept;
};
class easy_state {
public:
CURL * easy;
std::exception_ptr ex;
promise<CURLMsg> promise;
easy_state () = delete;
easy_state (const easy_state &) = delete;
easy_state (easy_state &&) = default;
easy_state & operator = (const easy_state &) = delete;
easy_state & operator = (easy_state &&) = delete;
explicit easy_state (CURL *);
void set_exception () noexcept;
void set_exception (std::exception_ptr) noexcept;
};
class socket_state {
public:
int what;
bool read;
bool write;
bool closed;
boost::asio::ip::tcp::socket socket;
socket_state () = delete;
socket_state (const socket_state &) = delete;
socket_state (socket_state &&) = default;
socket_state & operator = (const socket_state &) = delete;
socket_state & operator = (socket_state &&) = delete;
socket_state (const boost::asio::ip::tcp::socket::protocol_type &, boost::asio::io_service &);
};
boost::asio::io_service & ios_;
CURLM * handle_;
using handles_type=std::unordered_map<CURL *,easy_state>;
handles_type handles_;
using sockets_type=std::unordered_map<curl_socket_t,socket_state>;
sockets_type sockets_;
std::shared_ptr<control> control_;
boost::asio::deadline_timer timer_;
static curl_socket_t open (void *, curlsocktype, struct curl_sockaddr *) noexcept;
static int close (void *, curl_socket_t) noexcept;
static int socket (CURL *, curl_socket_t, int, void *, void *) noexcept;
static int timer (CURLM *, long, void *) noexcept;
void do_action (curl_socket_t, int) noexcept;
void remove_socket (sockets_type::iterator) noexcept;
void abort (easy_state &) noexcept;
void abort (handles_type::iterator) noexcept;
void complete (CURLMsg) noexcept;
void read (socket_state &);
void write (socket_state &);
public:
io_service () = delete;
io_service (const io_service &) = delete;
io_service (io_service &&) = delete;
io_service & operator = (const io_service &) = delete;
io_service & operator = (io_service &&) = delete;
explicit io_service (boost::asio::io_service & ios);
~io_service () noexcept;
/**
* Adds a curl easy handle to be managed by this io_service.
*
* The io_service does not assume ownership of the easy handle
* and the easy handle must remain valid until the io_service
* is done with it.
*
* \param [in] easy
* The easy handle to add to the io_service.
*
* \return
* A handle to the future value of the completed transfer
* represented by the easy handle.
*/
future<CURLMsg> add (CURL * easy);
/**
* Removes a curl easy handle from the io_service.
*
* Once this call completes the io_service will no longer
* use the easy handle.
*
* Note that the io_service does not reset any options it has
* set on the easy handle. Accordingly reusing the easy handle
* without calling curl_easy_reset on it leads to undefined behaviour
* unless the new transfer is handled through the same io_service.
*
* If \em easy was never added to this io_service, or if the
* transfer has completed, nothing happens.
*
* Note that it is not necessary to call this function after
* a transfer completes: In this instance the easy handle is
* automatically disassociated from the io_service.
*
* \param [in] easy
* The easy handle to disassociate from the io_service.
*
* \return
* \em true if \em easy was disassociated from the
* io_service, \em false if \em easy was not associated
* with the io_service.
*/
bool remove (CURL * easy) noexcept;
};
}
<commit_msg>asiocurl::io_service - Constructor & Destructor Documentation<commit_after>/**
* \file
*/
#pragma once
#include "future.hpp"
#include <boost/asio.hpp>
#include <curl/curl.h>
#include <cstddef>
#include <exception>
#include <memory>
#include <mutex>
#include <unordered_map>
namespace asiocurl {
/**
* Services curl easy handles using Boost.ASIO.
*/
class io_service {
private:
class control {
private:
using mutex_type=std::recursive_mutex;
mutable mutex_type m_;
bool stop_;
public:
control (const control &) = delete;
control (control &&) = delete;
control & operator = (const control &) = delete;
control & operator = (control &&) = delete;
control ();
using guard_type=std::unique_lock<mutex_type>;
guard_type lock () const noexcept;
explicit operator bool () const noexcept;
void stop () noexcept;
};
class easy_state {
public:
CURL * easy;
std::exception_ptr ex;
promise<CURLMsg> promise;
easy_state () = delete;
easy_state (const easy_state &) = delete;
easy_state (easy_state &&) = default;
easy_state & operator = (const easy_state &) = delete;
easy_state & operator = (easy_state &&) = delete;
explicit easy_state (CURL *);
void set_exception () noexcept;
void set_exception (std::exception_ptr) noexcept;
};
class socket_state {
public:
int what;
bool read;
bool write;
bool closed;
boost::asio::ip::tcp::socket socket;
socket_state () = delete;
socket_state (const socket_state &) = delete;
socket_state (socket_state &&) = default;
socket_state & operator = (const socket_state &) = delete;
socket_state & operator = (socket_state &&) = delete;
socket_state (const boost::asio::ip::tcp::socket::protocol_type &, boost::asio::io_service &);
};
boost::asio::io_service & ios_;
CURLM * handle_;
using handles_type=std::unordered_map<CURL *,easy_state>;
handles_type handles_;
using sockets_type=std::unordered_map<curl_socket_t,socket_state>;
sockets_type sockets_;
std::shared_ptr<control> control_;
boost::asio::deadline_timer timer_;
static curl_socket_t open (void *, curlsocktype, struct curl_sockaddr *) noexcept;
static int close (void *, curl_socket_t) noexcept;
static int socket (CURL *, curl_socket_t, int, void *, void *) noexcept;
static int timer (CURLM *, long, void *) noexcept;
void do_action (curl_socket_t, int) noexcept;
void remove_socket (sockets_type::iterator) noexcept;
void abort (easy_state &) noexcept;
void abort (handles_type::iterator) noexcept;
void complete (CURLMsg) noexcept;
void read (socket_state &);
void write (socket_state &);
public:
io_service () = delete;
io_service (const io_service &) = delete;
io_service (io_service &&) = delete;
io_service & operator = (const io_service &) = delete;
io_service & operator = (io_service &&) = delete;
/**
* Creates a new io_service which uses a certain
* boost::asio::io_service for socket I/O and timeouts.
*
* \param [in] ios
* The boost::asio::io_service with which this io_service
* shall be associated. This reference must remain valid
* for the lifetime of the io_service or the behaviour is
* undefined.
*/
explicit io_service (boost::asio::io_service & ios);
/**
* Shuts the io_service down.
*
* Any pending transfers will be immediately aborted.
*
* Any pending asynchronous operations will be cancelled. When
* those pending operations complete they will be no ops (i.e.
* it is not necessary to drain the boost::asio::io_service before
* calling this destructor).
*/
~io_service () noexcept;
/**
* Adds a curl easy handle to be managed by this io_service.
*
* The io_service does not assume ownership of the easy handle
* and the easy handle must remain valid until the io_service
* is done with it.
*
* \param [in] easy
* The easy handle to add to the io_service.
*
* \return
* A handle to the future value of the completed transfer
* represented by the easy handle.
*/
future<CURLMsg> add (CURL * easy);
/**
* Removes a curl easy handle from the io_service.
*
* Once this call completes the io_service will no longer
* use the easy handle.
*
* Note that the io_service does not reset any options it has
* set on the easy handle. Accordingly reusing the easy handle
* without calling curl_easy_reset on it leads to undefined behaviour
* unless the new transfer is handled through the same io_service.
*
* If \em easy was never added to this io_service, or if the
* transfer has completed, nothing happens.
*
* Note that it is not necessary to call this function after
* a transfer completes: In this instance the easy handle is
* automatically disassociated from the io_service.
*
* \param [in] easy
* The easy handle to disassociate from the io_service.
*
* \return
* \em true if \em easy was disassociated from the
* io_service, \em false if \em easy was not associated
* with the io_service.
*/
bool remove (CURL * easy) noexcept;
};
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <map>
#include <string>
#include <functional>
#include "function_traits.hpp"
#include "string_utils.hpp"
//#include "tuple_utils.hpp"
#include "token_parser.hpp"
#include "request.hpp"
#include "response.hpp"
namespace cinatra
{
class HTTPRouter
{
typedef std::function<bool(Request&, Response&, token_parser &)> invoker_function;
public:
HTTPRouter()
{}
template<typename Function>
typename std::enable_if<!std::is_member_function_pointer<Function>::value>::type route(const std::string& name, const Function& f)
{
std::string funcName = getFuncName(name);
register_nonmenber_impl<Function>(funcName, f); //对函数指针有效.
}
std::string getFuncName(std::string name)
{
size_t pos = name.find_first_of(':');
if (pos == std::string::npos)
return name;
std::string funcName = name.substr(0, pos - 1);
std::vector<string> v;
while (pos != string::npos)
{
//获取参数key,/hello/:name/:age
size_t nextpos = name.find_first_of('/', pos);
string paramKey = name.substr(pos + 1, nextpos - pos - 1);
v.push_back(std::move(paramKey));
pos = name.find_first_of(':', nextpos);
}
parser_.add(name, v);
return funcName;
}
template<typename Function, typename Self>
typename std::enable_if<std::is_member_function_pointer<Function>::value>::type route(const std::string& name, const Function& f, Self* self)
{
std::string funcName = getFuncName(name);
register_member_impl<Function, Function, Self>(funcName, f, self);
}
void remove_function(const std::string& name) {
this->map_invokers.erase(name);
}
bool dispatch(Request& req, Response& resp)
{
token_parser parser;
parser.parse(req, parser_.get_map());
if (parser.empty())
return false;
std::string func_name = parser.get_function_name();
if (func_name.empty())
{
return nullptr;
}
bool r = false;
auto it = map_invokers.equal_range(func_name);
for (auto itr = it.first; itr != it.second; ++itr)
{
try
{
auto it = resp.context().find(PARAM_ERROR);
if (it != resp.context().end())
{
resp.context().erase(it);
}
r = itr->second(req, resp, parser);
}
catch (const std::exception& e)
{
LOG_INFO << e.what();
r = false;
}
if (resp.context().find(PARAM_ERROR) == resp.context().end())
return r;
}
if (it.first==it.second)
{
//处理非标准的情况.
size_t pos = func_name.rfind('/');
while (pos != string::npos&&pos!=0)
{
string name = func_name;
if (pos != 0)
name = func_name.substr(0, pos);
string params = func_name.substr(pos);
parser.parse(params);
auto it = map_invokers.equal_range(name);
for (auto itr = it.first; itr != it.second; ++itr)
{
try
{
auto it = resp.context().find(PARAM_ERROR);
if (it != resp.context().end())
{
resp.context().erase(it);
}
r = itr->second(req, resp, parser);
}
catch (const std::exception& e)
{
LOG_INFO << e.what();
r = false;
}
if (resp.context().find(PARAM_ERROR) == resp.context().end())
return r;
}
pos = func_name.rfind('/', pos - 1);
}
}
return r;
}
//如果有参数key就按照key从query里取出相应的参数值.
//如果没有则直接查找,需要逐步匹配,先匹配最长的,接着匹配次长的,直到查找完所有可能的path.
invoker_function getFunction(token_parser& parser)
{
std::string func_name = parser.get_function_name();
if (func_name.empty())
{
return nullptr;
}
auto it = map_invokers.find(func_name);
if (it != map_invokers.end())
return it->second;
//处理非标准的情况.
size_t pos = func_name.rfind('/');
while (pos != string::npos)
{
string& name = func_name;
if (pos!=0)
name = func_name.substr(0, pos);
auto it = map_invokers.find(name);
if (it == map_invokers.end())
{
pos = func_name.rfind('/', pos - 1);
if (pos == 0)
return nullptr;
}
else
{
string params = func_name.substr(pos);
parser.parse(params);
return it->second;
}
}
return nullptr;
}
public:
template<class Signature, typename Function>
void register_nonmenber_impl(const std::string& name, const Function& f)
{
// instantiate and store the invoker by name
this->map_invokers.emplace(name, std::bind(&invoker<Function, Signature>::template call<std::tuple<>>, f, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3,
std::tuple<>()));
}
template<class Signature, typename Function, typename Self>
void register_member_impl(const std::string& name, const Function& f, Self* self)
{
// instantiate and store the invoker by name
this->map_invokers.emplace(name, std::bind(&invoker<Function, Signature>::template call_member<std::tuple<>, Self>, f, self, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3,
std::tuple<>()));
}
private:
template<typename Function, class Signature = Function, size_t N = function_traits<Signature>::arity>
struct invoker;
template<typename Function, class Signature, size_t N>
struct invoker
{
// add an argument to a Fusion cons-list for each parameter type
template<typename Args>
static inline bool call(const Function& func, Request& req, Response& res, token_parser & parser, const Args& args)
{
if (N != parser.size() + 2)
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
typedef typename function_traits<Signature>::template args<N-1>::type arg_type;
typename std::decay<arg_type>::type param;
if (!parser.get<arg_type>(param))
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
return HTTPRouter::invoker<Function, Signature, N - 1>::call(func, req, res, parser, std::tuple_cat(std::make_tuple(param), args));
}
template<typename Args, typename Self>
static inline bool call_member(Function func, Self* self, Request& req, Response& res, token_parser & parser, const Args& args)
{
if (N != parser.size() + 2)
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
typedef typename function_traits<Signature>::template args<N-1>::type arg_type;
typename std::decay<arg_type>::type param;
if (!parser.get<arg_type>(param))
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
return HTTPRouter::invoker<Function, Signature, N - 1>::call_member(func, self, req, res, parser, std::tuple_cat(std::make_tuple(param), args));
}
};
template<typename Function, class Signature>
struct invoker<Function, Signature, 2>
{
// the argument list is complete, now call the function
template<typename Args>
static inline bool call(const Function& func, Request& req, Response& res, token_parser &parser, const Args& args)
{
if (function_traits<Signature>::arity == 2 && !parser.empty())
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
apply(func, req, res, args);
return true;
}
template<typename Args, typename Self>
static inline bool call_member(const Function& func, Self* self, Request& req, Response& res, token_parser &parser, const Args& args)
{
if (function_traits<Signature>::arity == 2 && !parser.empty())
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
apply_member(func, self, req, res, args);
return true;
}
};
template<int...>
struct IndexTuple{};
template<int N, int... Indexes>
struct MakeIndexes : MakeIndexes<N - 1, N - 1, Indexes...>{};
template<int... indexes>
struct MakeIndexes<0, indexes...>
{
typedef IndexTuple<indexes...> type;
};
template<typename F, int ... Indexes, typename ... Args>
static void apply_helper(const F& f, Request& req, Response& res, IndexTuple<Indexes...>, const std::tuple<Args...>& tup)
{
f(req, res, std::get<Indexes>(tup)...);
}
template<typename F, typename ... Args>
static void apply(const F& f, Request& req, Response& res, const std::tuple<Args...>& tp)
{
apply_helper(f, req, res, typename MakeIndexes<sizeof... (Args)>::type(), tp);
}
template<typename F, typename Self, int ... Indexes, typename ... Args>
static void apply_helper_member(const F& f, Self* self, Request& req, Response& res, IndexTuple<Indexes...>, const std::tuple<Args...>& tup)
{
(*self.*f)(req, res, std::get<Indexes>(tup)...);
}
template<typename F, typename Self, typename ... Args>
static void apply_member(const F& f, Self* self, Request& req, Response& res, const std::tuple<Args...>& tp)
{
apply_helper_member(f, self, req, res, typename MakeIndexes<sizeof... (Args)>::type(), tp);
}
private:
std::multimap<std::string, invoker_function> map_invokers;
token_parser parser_;
const static int PARAM_ERROR = -9999;
};
}
<commit_msg>去掉一些重复代码。<commit_after>#pragma once
#include <vector>
#include <map>
#include <string>
#include <functional>
#include "function_traits.hpp"
#include "string_utils.hpp"
//#include "tuple_utils.hpp"
#include "token_parser.hpp"
#include "request.hpp"
#include "response.hpp"
namespace cinatra
{
class HTTPRouter
{
typedef std::function<bool(Request&, Response&, token_parser &)> invoker_function;
public:
HTTPRouter()
{}
template<typename Function>
typename std::enable_if<!std::is_member_function_pointer<Function>::value>::type route(const std::string& name, const Function& f)
{
std::string funcName = getFuncName(name);
register_nonmenber_impl<Function>(funcName, f); //对函数指针有效.
}
std::string getFuncName(std::string name)
{
size_t pos = name.find_first_of(':');
if (pos == std::string::npos)
return name;
std::string funcName = name.substr(0, pos - 1);
std::vector<string> v;
while (pos != string::npos)
{
//获取参数key,/hello/:name/:age
size_t nextpos = name.find_first_of('/', pos);
string paramKey = name.substr(pos + 1, nextpos - pos - 1);
v.push_back(std::move(paramKey));
pos = name.find_first_of(':', nextpos);
}
parser_.add(name, v);
return funcName;
}
template<typename Function, typename Self>
typename std::enable_if<std::is_member_function_pointer<Function>::value>::type route(const std::string& name, const Function& f, Self* self)
{
std::string funcName = getFuncName(name);
register_member_impl<Function, Function, Self>(funcName, f, self);
}
void remove_function(const std::string& name) {
this->map_invokers.erase(name);
}
bool dispatch(Request& req, Response& resp)
{
token_parser parser;
parser.parse(req, parser_.get_map());
if (parser.empty())
return false;
std::string func_name = parser.get_function_name();
if (func_name.empty())
{
return nullptr;
}
bool finish = false;
bool r = handle(req, resp, func_name, parser, finish);
if (finish)
return r;
auto it = map_invokers.equal_range(func_name);
if (it.first==it.second)
{
//处理非标准的情况.
size_t pos = func_name.rfind('/');
while (pos != string::npos&&pos!=0)
{
string name = func_name;
if (pos != 0)
name = func_name.substr(0, pos);
string params = func_name.substr(pos);
parser.parse(params);
bool r = handle(req, resp, name, parser, finish);
if (finish)
return r;
pos = func_name.rfind('/', pos - 1);
}
}
return r;
}
bool handle(Request& req, Response& resp, string& name, token_parser& parser, bool& finish)
{
bool r = false;
auto it = map_invokers.equal_range(name);
for (auto itr = it.first; itr != it.second; ++itr)
{
try
{
auto it = resp.context().find(PARAM_ERROR);
if (it != resp.context().end())
{
resp.context().erase(it);
}
r = itr->second(req, resp, parser);
}
catch (const std::exception& e)
{
LOG_INFO << e.what();
r = false;
}
if (resp.context().find(PARAM_ERROR) == resp.context().end())
{
finish = true;
break;
}
}
return r;
}
//如果有参数key就按照key从query里取出相应的参数值.
//如果没有则直接查找,需要逐步匹配,先匹配最长的,接着匹配次长的,直到查找完所有可能的path.
invoker_function getFunction(token_parser& parser)
{
std::string func_name = parser.get_function_name();
if (func_name.empty())
{
return nullptr;
}
auto it = map_invokers.find(func_name);
if (it != map_invokers.end())
return it->second;
//处理非标准的情况.
size_t pos = func_name.rfind('/');
while (pos != string::npos)
{
string& name = func_name;
if (pos!=0)
name = func_name.substr(0, pos);
auto it = map_invokers.find(name);
if (it == map_invokers.end())
{
pos = func_name.rfind('/', pos - 1);
if (pos == 0)
return nullptr;
}
else
{
string params = func_name.substr(pos);
parser.parse(params);
return it->second;
}
}
return nullptr;
}
public:
template<class Signature, typename Function>
void register_nonmenber_impl(const std::string& name, const Function& f)
{
// instantiate and store the invoker by name
this->map_invokers.emplace(name, std::bind(&invoker<Function, Signature>::template call<std::tuple<>>, f, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3,
std::tuple<>()));
}
template<class Signature, typename Function, typename Self>
void register_member_impl(const std::string& name, const Function& f, Self* self)
{
// instantiate and store the invoker by name
this->map_invokers.emplace(name, std::bind(&invoker<Function, Signature>::template call_member<std::tuple<>, Self>, f, self, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3,
std::tuple<>()));
}
private:
template<typename Function, class Signature = Function, size_t N = function_traits<Signature>::arity>
struct invoker;
template<typename Function, class Signature, size_t N>
struct invoker
{
// add an argument to a Fusion cons-list for each parameter type
template<typename Args>
static inline bool call(const Function& func, Request& req, Response& res, token_parser & parser, const Args& args)
{
if (N != parser.size() + 2)
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
typedef typename function_traits<Signature>::template args<N-1>::type arg_type;
typename std::decay<arg_type>::type param;
if (!parser.get<arg_type>(param))
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
return HTTPRouter::invoker<Function, Signature, N - 1>::call(func, req, res, parser, std::tuple_cat(std::make_tuple(param), args));
}
template<typename Args, typename Self>
static inline bool call_member(Function func, Self* self, Request& req, Response& res, token_parser & parser, const Args& args)
{
if (N != parser.size() + 2)
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
typedef typename function_traits<Signature>::template args<N-1>::type arg_type;
typename std::decay<arg_type>::type param;
if (!parser.get<arg_type>(param))
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
return HTTPRouter::invoker<Function, Signature, N - 1>::call_member(func, self, req, res, parser, std::tuple_cat(std::make_tuple(param), args));
}
};
template<typename Function, class Signature>
struct invoker<Function, Signature, 2>
{
// the argument list is complete, now call the function
template<typename Args>
static inline bool call(const Function& func, Request& req, Response& res, token_parser &parser, const Args& args)
{
if (function_traits<Signature>::arity == 2 && !parser.empty())
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
apply(func, req, res, args);
return true;
}
template<typename Args, typename Self>
static inline bool call_member(const Function& func, Self* self, Request& req, Response& res, token_parser &parser, const Args& args)
{
if (function_traits<Signature>::arity == 2 && !parser.empty())
{
res.context().emplace(PARAM_ERROR, 0);
return false;
}
apply_member(func, self, req, res, args);
return true;
}
};
template<int...>
struct IndexTuple{};
template<int N, int... Indexes>
struct MakeIndexes : MakeIndexes<N - 1, N - 1, Indexes...>{};
template<int... indexes>
struct MakeIndexes<0, indexes...>
{
typedef IndexTuple<indexes...> type;
};
template<typename F, int ... Indexes, typename ... Args>
static void apply_helper(const F& f, Request& req, Response& res, IndexTuple<Indexes...>, const std::tuple<Args...>& tup)
{
f(req, res, std::get<Indexes>(tup)...);
}
template<typename F, typename ... Args>
static void apply(const F& f, Request& req, Response& res, const std::tuple<Args...>& tp)
{
apply_helper(f, req, res, typename MakeIndexes<sizeof... (Args)>::type(), tp);
}
template<typename F, typename Self, int ... Indexes, typename ... Args>
static void apply_helper_member(const F& f, Self* self, Request& req, Response& res, IndexTuple<Indexes...>, const std::tuple<Args...>& tup)
{
(*self.*f)(req, res, std::get<Indexes>(tup)...);
}
template<typename F, typename Self, typename ... Args>
static void apply_member(const F& f, Self* self, Request& req, Response& res, const std::tuple<Args...>& tp)
{
apply_helper_member(f, self, req, res, typename MakeIndexes<sizeof... (Args)>::type(), tp);
}
private:
std::multimap<std::string, invoker_function> map_invokers;
token_parser parser_;
const static int PARAM_ERROR = -9999;
};
}
<|endoftext|> |
<commit_before><commit_msg>For iOS we already hardocde the inifile as rc in the .app directory<commit_after><|endoftext|> |
<commit_before><commit_msg>LOK: Corner case with working dir as '/'.<commit_after><|endoftext|> |
<commit_before>#include "bloomierFilter.h"
BloomierFilter::BloomierFilter(size_t pM, size_t pK, size_t pQ){
mM = pM;;
mK = pK;
mQ = pQ;
mBitVectorSize = ceil(pQ / static_cast<float>(CHAR_BIT));
mBloomierHash = new BloomierHash(pM, pK, mBitVectorSize);
mOrderAndMatchFinder = new OrderAndMatchFinder(pM, pK, mBloomierHash);
mTable = new bloomierTable(pM);
mValueTable = new vvsize_t_p(pM);
for (size_t i = 0; i < pM; ++i) {
(*mTable)[i] = new bitVector(mBitVectorSize, 0);
(*mValueTable)[i] = new vsize_t();
}
mEncoder = new Encoder(mBitVectorSize);
mPiIndex = 0;
}
BloomierFilter::~BloomierFilter(){
}
void BloomierFilter::check() {
std::cout << __LINE__ << std::endl;
size_t sumTable = 0;
for(size_t i = 0; i < mTable->size(); ++i) {
try {
sumTable += (*mTable)[i]->size();
} catch(int e) {
std::cout << "i: " << i << std::endl;
}
}
std::cout << __LINE__ << std::endl;
size_t sumValueTable = 0;
for(size_t i = 0; i < mValueTable->size(); ++i) {
sumValueTable += (*mValueTable)[i]->size();
}
std::cout << "sumTable: " << sumTable << std::endl;
std::cout << "sumValueTable: " << sumValueTable << std::endl;
std::cout << __LINE__ << std::endl;
}
bloomierTable* BloomierFilter::getTable() {
return mTable;
}
void BloomierFilter::setTable(bloomierTable* pTable) {
if (mTable != NULL) {
for (size_t i = 0; i < mTable->size(); ++i) {
delete (*mTable)[i];
}
delete mTable;
}
mTable = pTable;
}
vvsize_t_p* BloomierFilter::getValueTable() {
return mValueTable;
}
void BloomierFilter::setValueTable(vvsize_t_p* pTable) {
mValueTable = pTable;
}
void BloomierFilter::xorOperation(bitVector* pValue, bitVector* pMask, vsize_t* pNeighbors) {
this->xorBitVector(pValue, pMask);
for (auto it = pNeighbors->begin(); it != pNeighbors->end(); ++it) {
if (*it < mTable->size()) {
this->xorBitVector(pValue, (*mTable)[(*it)]);
}
}
}
vsize_t* BloomierFilter::get(size_t pKey) {
// std::cout << __LINE__ << std::endl;
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey);
bitVector* mask = mBloomierHash->getMask(pKey);
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
this->xorOperation(valueToGet, mask, neighbors);
size_t h = mEncoder->decode(valueToGet);
if (h < neighbors->size()) {
size_t L = (*neighbors)[h];
if (L < mValueTable->size()) {
delete neighbors;
delete mask;
delete valueToGet;
return (*mValueTable)[L];
}
}
delete neighbors;
delete mask;
delete valueToGet;
return new vsize_t();
}
bool BloomierFilter::set(size_t pKey, size_t pValue) {
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey);
bitVector* mask = mBloomierHash->getMask(pKey);
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
this->xorOperation(valueToGet, mask, neighbors);
size_t h = mEncoder->decode(valueToGet);
delete mask;
delete valueToGet;
if (h < neighbors->size()) {
size_t L = (*neighbors)[h];
delete neighbors;
if (L < mValueTable->size()) {
vsize_t* v = ((*mValueTable)[L]);
v->push_back(pValue);
return true;
}
} else {
delete neighbors;
vsize_t* keys = new vsize_t (1, pKey);
vvsize_t_p* values = new vvsize_t_p (1);
(*values)[0] = new vsize_t(1, pValue);
this->create(keys, values, mPiIndex);
return true;
}
return false;
}
void BloomierFilter::create(vsize_t* pKeys, vvsize_t_p* pValues, size_t piIndex) {
mOrderAndMatchFinder->find(pKeys);
vsize_t* piVector = mOrderAndMatchFinder->getPiVector();
vsize_t* tauVector = mOrderAndMatchFinder->getTauVector();
for (size_t i = piIndex; i < piVector->size(); ++i) {
vsize_t* neighbors = mBloomierHash->getKNeighbors((*pKeys)[i]);
bitVector* mask = mBloomierHash->getMask((*pKeys)[i]);
size_t l = (*tauVector)[i];
size_t L = (*neighbors)[l];
bitVector* encodeValue = mEncoder->encode(l);
this->xorBitVector((*mTable)[L], encodeValue);
this->xorBitVector((*mTable)[L], mask);
for (size_t j = 0; j < neighbors->size(); ++j) {
if (j != l) {
this->xorBitVector((*mTable)[L], (*mTable)[(*neighbors)[j]]);
}
}
for (size_t j = 0; j < (*pValues)[i-piIndex]->size(); ++j) {
(*mValueTable)[L]->push_back((*pValues)[i-piIndex]->operator[](j));
}
delete neighbors;
delete mask;
delete encodeValue;
}
mPiIndex += pKeys->size();
delete pKeys;
for (size_t i = 0; i < pValues->size(); ++i) {
delete (*pValues)[i];
}
delete pValues;
// delete piVector;
// delete tauVector;
}
void BloomierFilter::xorBitVector(bitVector* pResult, bitVector* pInput) {
size_t length = std::min(pResult->size(), pInput->size());
for (size_t i = 0; i < length; ++i) {
(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];
}
}<commit_msg>Added a hashSeed<commit_after>#include "bloomierFilter.h"
BloomierFilter::BloomierFilter(size_t pM, size_t pK, size_t pQ, size_t pHashSeed){
mM = pM;;
mK = pK;
mQ = pQ;
mBitVectorSize = ceil(pQ / static_cast<float>(CHAR_BIT));
mBloomierHash = new BloomierHash(pM, pK, mBitVectorSize, pHashSeed);
mOrderAndMatchFinder = new OrderAndMatchFinder(pM, pK, mBloomierHash);
mTable = new bloomierTable(pM);
mValueTable = new vvsize_t_p(pM);
for (size_t i = 0; i < pM; ++i) {
(*mTable)[i] = new bitVector(mBitVectorSize, 0);
(*mValueTable)[i] = new vsize_t();
}
mEncoder = new Encoder(mBitVectorSize);
mPiIndex = 0;
}
BloomierFilter::~BloomierFilter(){
}
void BloomierFilter::check() {
std::cout << __LINE__ << std::endl;
size_t sumTable = 0;
for(size_t i = 0; i < mTable->size(); ++i) {
try {
sumTable += (*mTable)[i]->size();
} catch(int e) {
std::cout << "i: " << i << std::endl;
}
}
std::cout << __LINE__ << std::endl;
size_t sumValueTable = 0;
for(size_t i = 0; i < mValueTable->size(); ++i) {
sumValueTable += (*mValueTable)[i]->size();
}
std::cout << "sumTable: " << sumTable << std::endl;
std::cout << "sumValueTable: " << sumValueTable << std::endl;
std::cout << __LINE__ << std::endl;
}
bloomierTable* BloomierFilter::getTable() {
return mTable;
}
void BloomierFilter::setTable(bloomierTable* pTable) {
if (mTable != NULL) {
for (size_t i = 0; i < mTable->size(); ++i) {
delete (*mTable)[i];
}
delete mTable;
}
mTable = pTable;
}
vvsize_t_p* BloomierFilter::getValueTable() {
return mValueTable;
}
void BloomierFilter::setValueTable(vvsize_t_p* pTable) {
mValueTable = pTable;
}
void BloomierFilter::xorOperation(bitVector* pValue, bitVector* pMask, vsize_t* pNeighbors) {
this->xorBitVector(pValue, pMask);
for (auto it = pNeighbors->begin(); it != pNeighbors->end(); ++it) {
if (*it < mTable->size()) {
this->xorBitVector(pValue, (*mTable)[(*it)]);
}
}
}
vsize_t* BloomierFilter::get(size_t pKey) {
// std::cout << __LINE__ << std::endl;
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey);
bitVector* mask = mBloomierHash->getMask(pKey);
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
this->xorOperation(valueToGet, mask, neighbors);
size_t h = mEncoder->decode(valueToGet);
if (h < neighbors->size()) {
size_t L = (*neighbors)[h];
if (L < mValueTable->size()) {
delete neighbors;
delete mask;
delete valueToGet;
return (*mValueTable)[L];
}
}
delete neighbors;
delete mask;
delete valueToGet;
return new vsize_t();
}
bool BloomierFilter::set(size_t pKey, size_t pValue) {
vsize_t* neighbors = mBloomierHash->getKNeighbors(pKey);
bitVector* mask = mBloomierHash->getMask(pKey);
bitVector* valueToGet = new bitVector(mBitVectorSize, 0);
this->xorOperation(valueToGet, mask, neighbors);
size_t h = mEncoder->decode(valueToGet);
delete mask;
delete valueToGet;
if (h < neighbors->size()) {
size_t L = (*neighbors)[h];
delete neighbors;
if (L < mValueTable->size()) {
vsize_t* v = ((*mValueTable)[L]);
v->push_back(pValue);
return true;
}
} else {
delete neighbors;
vsize_t* keys = new vsize_t (1, pKey);
vvsize_t_p* values = new vvsize_t_p (1);
(*values)[0] = new vsize_t(1, pValue);
this->create(keys, values, mPiIndex);
return true;
}
return false;
}
void BloomierFilter::create(vsize_t* pKeys, vvsize_t_p* pValues, size_t piIndex) {
mOrderAndMatchFinder->find(pKeys);
vsize_t* piVector = mOrderAndMatchFinder->getPiVector();
vsize_t* tauVector = mOrderAndMatchFinder->getTauVector();
for (size_t i = piIndex; i < piVector->size(); ++i) {
vsize_t* neighbors = mBloomierHash->getKNeighbors((*pKeys)[i]);
bitVector* mask = mBloomierHash->getMask((*pKeys)[i]);
size_t l = (*tauVector)[i];
size_t L = (*neighbors)[l];
bitVector* encodeValue = mEncoder->encode(l);
this->xorBitVector((*mTable)[L], encodeValue);
this->xorBitVector((*mTable)[L], mask);
for (size_t j = 0; j < neighbors->size(); ++j) {
if (j != l) {
this->xorBitVector((*mTable)[L], (*mTable)[(*neighbors)[j]]);
}
}
for (size_t j = 0; j < (*pValues)[i-piIndex]->size(); ++j) {
(*mValueTable)[L]->push_back((*pValues)[i-piIndex]->operator[](j));
}
delete neighbors;
delete mask;
delete encodeValue;
}
mPiIndex += pKeys->size();
delete pKeys;
for (size_t i = 0; i < pValues->size(); ++i) {
delete (*pValues)[i];
}
delete pValues;
// delete piVector;
// delete tauVector;
}
void BloomierFilter::xorBitVector(bitVector* pResult, bitVector* pInput) {
size_t length = std::min(pResult->size(), pInput->size());
for (size_t i = 0; i < length; ++i) {
(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];
}
}<|endoftext|> |
<commit_before>/**
* thrift - a lightweight cross-language rpc/serialization tool
*
* This file contains the main compiler engine for Thrift, which invokes the
* scanner/parser to build the thrift object tree. The interface generation
* code for each language lives in a file by the language name.
*
* @author Mark Slee <mcslee@facebook.com>
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string>
// Careful: must include globals first
#include "globals.h"
#include "main.h"
#include "parse/t_program.h"
#include "generate/t_cpp_generator.h"
#include "generate/t_java_generator.h"
#include "generate/t_php_generator.h"
#include "generate/t_py_generator.h"
using namespace std;
/** Global program tree */
t_program* g_program;
/** Global debug state */
int g_debug = 0;
/** Global time string */
char* g_time_str;
/**
* Report an error to the user. This is called yyerror for historical
* reasons (lex and yacc expect the error reporting routine to be called
* this). Call this function to report any errors to the user.
* yyerror takes printf style arguments.
*
* @param fmt C format string followed by additional arguments
*/
void yyerror(char* fmt, ...) {
va_list args;
fprintf(stderr,
"\n!!! Error: line %d (last token was '%s')",
yylineno,
yytext);
fprintf(stderr, "\n!!! ");
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
}
/**
* Prints a debug message from the parser.
*
* @param fmt C format string followed by additional arguments
*/
void pdebug(char* fmt, ...) {
if (g_debug == 0) {
return;
}
va_list args;
printf("[Parse] ");
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
/**
* Prints a failure message and exits
*
* @param fmt C format string followed by additional arguments
*/
void failure(char* fmt, ...) {
va_list args;
fprintf(stderr, "\n!!! Failure: ");
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
printf("\n");
exit(1);
}
/**
* Diplays the usage message and then exits with an error code.
*/
void usage() {
fprintf(stderr, "Usage: thrift [options] file\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, " --cpp Generate C++ output files\n");
fprintf(stderr, " --java Generate Java output files\n");
fprintf(stderr, " --php Generate PHP output files\n");
fprintf(stderr, " --phpi Generate PHP inlined files\n");
fprintf(stderr, " --py Generate Python output files\n");
fprintf(stderr, " --debug Print parse debugging to standard output\n");
exit(1);
}
/**
* Parse it up.. then spit it back out, in pretty much every language
*/
int main(int argc, char** argv) {
int i;
bool gen_cpp = false;
bool gen_java = false;
bool gen_py = false;
bool gen_php = false;
bool php_inline = false;
// Setup time string
time_t now = time(NULL);
g_time_str = ctime(&now);
// Check for necessary arguments
if (argc < 2) {
usage();
}
for (i = 1; i < argc-1; i++) {
if (strcmp(argv[i], "--debug") == 0) {
g_debug = 1;
} else if (strcmp(argv[i], "--cpp") == 0) {
gen_cpp = true;
} else if (strcmp(argv[i], "--java") == 0) {
gen_java = true;
} else if (strcmp(argv[i], "--php") == 0) {
gen_php = true;
php_inline = false;
} else if (strcmp(argv[i], "--phpi") == 0) {
gen_php = true;
php_inline = true;
} else if (strcmp(argv[i], "--py") == 0) {
gen_py = true;
} else {
fprintf(stderr, "!!! Unrecognized option: %s\n", argv[i]);
usage();
}
}
if (!gen_cpp && !gen_java && !gen_php && !gen_py) {
fprintf(stderr, "!!! No output language(s) specified\n\n");
usage();
}
// Open input file
char* input_file = argv[i];
yyin = fopen(input_file, "r");
if (yyin == 0) {
failure("Could not open input file: \"%s\"", input_file);
}
// Extract program name by dropping directory and .thrift from filename
string name = input_file;
string::size_type slash = name.rfind("/");
if (slash != string::npos) {
name = name.substr(slash+1);
}
string::size_type dot = name.find(".");
if (dot != string::npos) {
name = name.substr(0, dot);
}
// Parse it
g_program = new t_program(name);
if (yyparse() != 0) {
failure("Parser error.");
}
// Generate code
try {
if (gen_cpp) {
t_cpp_generator* cpp = new t_cpp_generator();
cpp->generate_program(g_program);
delete cpp;
}
if (gen_java) {
t_java_generator* java = new t_java_generator();
java->generate_program(g_program);
delete java;
}
if (gen_php) {
t_php_generator* php = new t_php_generator(php_inline);
php->generate_program(g_program);
delete php;
}
if (gen_py) {
t_py_generator* py = new t_py_generator();
py->generate_program(g_program);
delete py;
}
} catch (string s) {
printf("Error: %s\n", s.c_str());
} catch (const char* exc) {
printf("Error: %s\n", exc);
}
// Clean up
delete g_program;
// Finished
return 0;
}
<commit_msg>Thrift compiler to tokenize args by " " so you can use script files<commit_after>/**
* thrift - a lightweight cross-language rpc/serialization tool
*
* This file contains the main compiler engine for Thrift, which invokes the
* scanner/parser to build the thrift object tree. The interface generation
* code for each language lives in a file by the language name.
*
* @author Mark Slee <mcslee@facebook.com>
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string>
// Careful: must include globals first
#include "globals.h"
#include "main.h"
#include "parse/t_program.h"
#include "generate/t_cpp_generator.h"
#include "generate/t_java_generator.h"
#include "generate/t_php_generator.h"
#include "generate/t_py_generator.h"
using namespace std;
/** Global program tree */
t_program* g_program;
/** Global debug state */
int g_debug = 0;
/** Global time string */
char* g_time_str;
/**
* Report an error to the user. This is called yyerror for historical
* reasons (lex and yacc expect the error reporting routine to be called
* this). Call this function to report any errors to the user.
* yyerror takes printf style arguments.
*
* @param fmt C format string followed by additional arguments
*/
void yyerror(char* fmt, ...) {
va_list args;
fprintf(stderr,
"\n!!! Error: line %d (last token was '%s')",
yylineno,
yytext);
fprintf(stderr, "\n!!! ");
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
}
/**
* Prints a debug message from the parser.
*
* @param fmt C format string followed by additional arguments
*/
void pdebug(char* fmt, ...) {
if (g_debug == 0) {
return;
}
va_list args;
printf("[Parse] ");
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
/**
* Prints a failure message and exits
*
* @param fmt C format string followed by additional arguments
*/
void failure(char* fmt, ...) {
va_list args;
fprintf(stderr, "\n!!! Failure: ");
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
printf("\n");
exit(1);
}
/**
* Diplays the usage message and then exits with an error code.
*/
void usage() {
fprintf(stderr, "Usage: thrift [options] file\n");
fprintf(stderr, "Options:\n");
fprintf(stderr, " --cpp Generate C++ output files\n");
fprintf(stderr, " --java Generate Java output files\n");
fprintf(stderr, " --php Generate PHP output files\n");
fprintf(stderr, " --phpi Generate PHP inlined files\n");
fprintf(stderr, " --py Generate Python output files\n");
fprintf(stderr, " --debug Print parse debugging to standard output\n");
exit(1);
}
/**
* Parse it up.. then spit it back out, in pretty much every language
*/
int main(int argc, char** argv) {
int i;
bool gen_cpp = false;
bool gen_java = false;
bool gen_py = false;
bool gen_php = false;
bool php_inline = false;
// Setup time string
time_t now = time(NULL);
g_time_str = ctime(&now);
// Check for necessary arguments
if (argc < 2) {
usage();
}
for (i = 1; i < argc-1; i++) {
char* arg;
arg = strtok(argv[i], " ");
while (arg != NULL) {
if (strcmp(arg, "--debug") == 0) {
g_debug = 1;
} else if (strcmp(arg, "--cpp") == 0) {
gen_cpp = true;
} else if (strcmp(arg, "--java") == 0) {
gen_java = true;
} else if (strcmp(arg, "--php") == 0) {
gen_php = true;
php_inline = false;
} else if (strcmp(arg, "--phpi") == 0) {
gen_php = true;
php_inline = true;
} else if (strcmp(arg, "--py") == 0) {
gen_py = true;
} else {
fprintf(stderr, "!!! Unrecognized option: %s\n", arg);
usage();
}
// Tokenize more
arg = strtok(NULL, " ");
}
}
if (!gen_cpp && !gen_java && !gen_php && !gen_py) {
fprintf(stderr, "!!! No output language(s) specified\n\n");
usage();
}
// Open input file
char* input_file = argv[i];
yyin = fopen(input_file, "r");
if (yyin == 0) {
failure("Could not open input file: \"%s\"", input_file);
}
// Extract program name by dropping directory and .thrift from filename
string name = input_file;
string::size_type slash = name.rfind("/");
if (slash != string::npos) {
name = name.substr(slash+1);
}
string::size_type dot = name.find(".");
if (dot != string::npos) {
name = name.substr(0, dot);
}
// Parse it
g_program = new t_program(name);
if (yyparse() != 0) {
failure("Parser error.");
}
// Generate code
try {
if (gen_cpp) {
t_cpp_generator* cpp = new t_cpp_generator();
cpp->generate_program(g_program);
delete cpp;
}
if (gen_java) {
t_java_generator* java = new t_java_generator();
java->generate_program(g_program);
delete java;
}
if (gen_php) {
t_php_generator* php = new t_php_generator(php_inline);
php->generate_program(g_program);
delete php;
}
if (gen_py) {
t_py_generator* py = new t_py_generator();
py->generate_program(g_program);
delete py;
}
} catch (string s) {
printf("Error: %s\n", s.c_str());
} catch (const char* exc) {
printf("Error: %s\n", exc);
}
// Clean up
delete g_program;
// Finished
return 0;
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief FifoQueue class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-12-10
*/
#ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
#include "distortos/scheduler/FifoQueueBase.hpp"
namespace distortos
{
/**
* \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt
* communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for
* scheduler::FifoQueueBase.
*
* \param T is the type of data in queue
*/
template<typename T>
class FifoQueue : private scheduler::FifoQueueBase
{
public:
/// type of uninitialized storage for data
using Storage = Storage<T>;
/**
* \brief FifoQueue's constructor
*
* \param [in] storage is an array of Storage elements
* \param [in] maxElements is the number of elements in storage array
*/
FifoQueue(Storage* const storage, const size_t maxElements) :
FifoQueueBase{storage, maxElements, TypeTag<T>{}}
{
}
/**
* \brief Pops the oldest (first) element from the queue.
*
* Wrapper for scheduler::FifoQueueBase::pop(T&)
*
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int pop(T& value)
{
return FifoQueueBase::pop(value);
}
/**
* \brief Pushes the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::push(const T&)
*
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const T& value)
{
return FifoQueueBase::push(value);
}
/**
* \brief Pushes the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::push(T&&)
*
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(T&& value)
{
return FifoQueueBase::push(std::move(value));
}
/**
* \brief Tries to pop the oldest (first) element from the queue.
*
* Wrapper for scheduler::FifoQueueBase::tryPop(T&)
*
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPop(T& value)
{
return FifoQueueBase::tryPop(value);
}
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* Wrapper for scheduler::FifoQueueBase::tryPopFor(TickClock::duration, T&)
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPopFor(const TickClock::duration duration, T& value)
{
return FifoQueueBase::tryPopFor(duration, value);
}
/**
* \brief Tries to push the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::tryPush(const T&)
*
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPush(const T& value)
{
return FifoQueueBase::tryPush(value);
}
/**
* \brief Tries to push the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::tryPush(T&&)
*
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPush(T&& value)
{
return FifoQueueBase::tryPush(std::move(value));
}
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, const T&)
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPushFor(const TickClock::duration duration, const T& value)
{
return FifoQueueBase::tryPushFor(duration, value);
}
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
<commit_msg>FifoQueue: add FifoQueue::tryPushFor(TickClock::duration, T&&)<commit_after>/**
* \file
* \brief FifoQueue class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-12-10
*/
#ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
#include "distortos/scheduler/FifoQueueBase.hpp"
namespace distortos
{
/**
* \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt
* communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for
* scheduler::FifoQueueBase.
*
* \param T is the type of data in queue
*/
template<typename T>
class FifoQueue : private scheduler::FifoQueueBase
{
public:
/// type of uninitialized storage for data
using Storage = Storage<T>;
/**
* \brief FifoQueue's constructor
*
* \param [in] storage is an array of Storage elements
* \param [in] maxElements is the number of elements in storage array
*/
FifoQueue(Storage* const storage, const size_t maxElements) :
FifoQueueBase{storage, maxElements, TypeTag<T>{}}
{
}
/**
* \brief Pops the oldest (first) element from the queue.
*
* Wrapper for scheduler::FifoQueueBase::pop(T&)
*
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int pop(T& value)
{
return FifoQueueBase::pop(value);
}
/**
* \brief Pushes the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::push(const T&)
*
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(const T& value)
{
return FifoQueueBase::push(value);
}
/**
* \brief Pushes the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::push(T&&)
*
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::wait();
* - error codes returned by Semaphore::post();
*/
int push(T&& value)
{
return FifoQueueBase::push(std::move(value));
}
/**
* \brief Tries to pop the oldest (first) element from the queue.
*
* Wrapper for scheduler::FifoQueueBase::tryPop(T&)
*
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPop(T& value)
{
return FifoQueueBase::tryPop(value);
}
/**
* \brief Tries to pop the oldest (first) element from the queue for a given duration of time.
*
* Wrapper for scheduler::FifoQueueBase::tryPopFor(TickClock::duration, T&)
*
* \param [in] duration is the duration after which the call will be terminated without popping the element
* \param [out] value is a reference to object that will be used to return popped value, its contents are swapped
* with the value in the queue's storage and destructed when no longer needed
*
* \return zero if element was popped successfully, error code otherwise:
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPopFor(const TickClock::duration duration, T& value)
{
return FifoQueueBase::tryPopFor(duration, value);
}
/**
* \brief Tries to push the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::tryPush(const T&)
*
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPush(const T& value)
{
return FifoQueueBase::tryPush(value);
}
/**
* \brief Tries to push the element to the queue.
*
* Wrapper for scheduler::FifoQueueBase::tryPush(T&&)
*
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWait();
* - error codes returned by Semaphore::post();
*/
int tryPush(T&& value)
{
return FifoQueueBase::tryPush(std::move(value));
}
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, const T&)
*
* \param [in] duration is the duration after which the wait will be terminated without pushing the element
* \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPushFor(const TickClock::duration duration, const T& value)
{
return FifoQueueBase::tryPushFor(duration, value);
}
/**
* \brief Tries to push the element to the queue for a given duration of time.
*
* Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, T&&)
*
* \param [in] duration is the duration after which the call will be terminated without pushing the element
* \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is
* move-constructed
*
* \return zero if element was pushed successfully, error code otherwise:
* - error codes returned by Semaphore::tryWaitFor();
* - error codes returned by Semaphore::post();
*/
int tryPushFor(const TickClock::duration duration, T&& value)
{
return FifoQueueBase::tryPushFor(duration, std::move(value));
}
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <map>
#include <iostream>
#include <fstream>
#include <iterator>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include "driver.h"
#include "passes.h"
#include "symbol.h"
#include "expr.h"
#include "stmt.h"
#include "docs.h"
#include "mysystem.h"
#include "stringutil.h"
#include "scopeResolve.h"
#include "AstToText.h"
#include "AstPrintDocs.h"
static int compareNames(const void* v1, const void* v2) {
Symbol* s1 = *(Symbol* const *)v1;
Symbol* s2 = *(Symbol* const *)v2;
return strcmp(s1->name, s2->name);
}
static int compareClasses(const void *v1, const void* v2) {
Type *t1 = *(Type* const *)v1;
Type *t2 = *(Type* const *)v2;
return strcmp(t1->symbol->name, t2->symbol->name);
}
void docs(void) {
if (fDocs) {
// To handle inheritance, we need to look up parent classes and records.
// In order to be successful when looking up these parents, the import
// expressions should be accurately accounted for.
addToSymbolTable(gDefExprs);
processImportExprs();
// Open the directory to store the docs
std::string docsDir = (strlen(fDocsFolder) != 0) ? fDocsFolder : "docs";
std::string docsFolderName = docsDir;
if (!fDocsTextOnly) {
docsFolderName = generateSphinxProject(docsDir);
}
mkdir(docsFolderName.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!mod->hasFlag(FLAG_NO_DOC) && !devOnlyModule(mod)) {
if (isNotSubmodule(mod)) {
std::ofstream *file = openFileFromMod(mod, docsFolderName);
AstPrintDocs *docsVisitor = new AstPrintDocs(file);
mod->accept(docsVisitor);
delete docsVisitor;
// Comment the above three lines and uncomment the following line to
// get the old category based output (or alphabetical). Note that
// this will be restored (hopefully soon)... (thomasvandoren, 2015-02-22)
//
// printModule(file, mod, 0);
file->close();
}
}
}
if (!fDocsTextOnly) {
generateSphinxOutput(docsDir);
}
}
}
bool isNotSubmodule(ModuleSymbol *mod) {
return (mod->defPoint == NULL ||
mod->defPoint->parentSymbol == NULL ||
mod->defPoint->parentSymbol->name == NULL ||
strcmp("chpl__Program", mod->defPoint->parentSymbol->name) == 0 ||
strcmp("_root", mod->defPoint->parentSymbol->name) == 0);
}
void printFields(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
for (int i = 1; i <= cl->fields.length; i++) {
if (VarSymbol *var = toVarSymbol(((DefExpr *)cl->fields.get(i))->sym)) {
var->printDocs(file, tabs);
}
}
}
void inheritance(Vec<AggregateType*> *list, AggregateType *cl) {
for_alist(expr, cl->inherits) {
AggregateType* pt = discoverParentAndCheck(expr, cl);
list->add_exclusive(pt);
inheritance(list, pt);
}
}
void printClass(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
if (!cl->symbol->hasFlag(FLAG_NO_DOC) && ! cl->isUnion()) {
cl->printDocs(file, tabs);
printFields(file, cl, tabs + 1);
// In rst mode, add an additional line break after the attributes and
// before the next directive.
if (!fDocsTextOnly) {
*file << std::endl;
}
// If alphabetical option passed, alphabetizes the output
if (fDocsAlphabetize)
qsort(cl->methods.v, cl->methods.n, sizeof(cl->methods.v[0]),
compareNames);
forv_Vec(FnSymbol, fn, cl->methods){
// We only want to print methods defined within the class under the
// class header
if (fn->isPrimaryMethod())
fn->printDocs(file, tabs + 1);
}
Vec<AggregateType*> superClasses;
inheritance(&superClasses, cl);
if (fDocsAlphabetize)
qsort(superClasses.v, superClasses.n, sizeof(superClasses.v[0]), compareClasses);
forv_Vec(AggregateType, superClass, superClasses) {
superClass->printInheritanceDocs(file, tabs + 1);
printFields(file, superClass, tabs + 2);
forv_Vec(FnSymbol, fn, superClass->methods) {
fn->printDocs(file, tabs + 2);
}
*file << std::endl;
}
}
}
// Returns true if the provided fn is a module initializer, class constructor,
// type constructor, or module copy of a class method. These functions are
// only printed in developer mode. Is not applicable to printing class
// functions.
bool devOnlyFunction(FnSymbol *fn) {
return (fn->hasFlag(FLAG_MODULE_INIT) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)
|| fn->hasFlag(FLAG_CONSTRUCTOR) || fn->isPrimaryMethod());
}
// Returns true if the provide module is one of the internal or standard
// modules. It is our opinion that these should only automatically be printed
// out if the user is in developer mode.
bool devOnlyModule(ModuleSymbol *mod) {
return mod->modTag == MOD_INTERNAL || mod->modTag == MOD_STANDARD;
}
void printModule(std::ofstream *file, ModuleSymbol *mod, unsigned int tabs) {
if (!mod->hasFlag(FLAG_NO_DOC)) {
mod->printDocs(file, tabs);
Vec<VarSymbol*> configs = mod->getTopLevelConfigVars();
if (fDocsAlphabetize)
qsort(configs.v, configs.n, sizeof(configs.v[0]), compareNames);
forv_Vec(VarSymbol, var, configs) {
var->printDocs(file, tabs + 1);
}
Vec<VarSymbol*> variables = mod->getTopLevelVariables();
if (fDocsAlphabetize)
qsort(variables.v, variables.n, sizeof(variables.v[0]), compareNames);
forv_Vec(VarSymbol, var, variables) {
var->printDocs(file, tabs + 1);
}
Vec<FnSymbol*> fns = mod->getTopLevelFunctions(fDocsIncludeExterns);
// If alphabetical option passed, fDocsAlphabetizes the output
if (fDocsAlphabetize)
qsort(fns.v, fns.n, sizeof(fns.v[0]), compareNames);
forv_Vec(FnSymbol, fn, fns) {
// TODO: Add flag to compiler to turn on doc dev only output
// We want methods on classes that are defined at the module level to be
// printed at the module level
if (!devOnlyFunction(fn) || fn->isSecondaryMethod()) {
fn->printDocs(file, tabs + 1);
}
}
Vec<AggregateType*> classes = mod->getTopLevelClasses();
if (fDocsAlphabetize)
qsort(classes.v, classes.n, sizeof(classes.v[0]), compareClasses);
forv_Vec(AggregateType, cl, classes) {
printClass(file, cl, tabs + 1);
}
Vec<ModuleSymbol*> mods = mod->getTopLevelModules();
if (fDocsAlphabetize)
qsort(mods.v, mods.n, sizeof(mods.v[0]), compareNames);
forv_Vec(ModuleSymbol, subMod, mods) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!devOnlyModule(subMod)) {
subMod->addPrefixToName(mod->docsName() + ".");
printModule(file, subMod, tabs + 1);
}
}
}
}
void createDocsFileFolders(std::string filename) {
size_t dirCutoff = filename.find("/");
size_t total = 0;
while (dirCutoff != std::string::npos) {
// Creates each subdirectory within the new documentation directory
dirCutoff += total;
std::string shorter = filename.substr(dirCutoff+1);
std::string otherHalf = filename.substr(0, dirCutoff);
mkdir(otherHalf.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
total = dirCutoff + 1;
dirCutoff = shorter.find("/");
}
}
/*
* Create new sphinx project at given location and return path where .rst files
* should be placed.
*/
std::string generateSphinxProject(std::string dirpath) {
// FIXME: This ought to be done in a TMPDIR, unless --save-rst is
// provided... (thomasvandoren, 2015-01-29)
// Create the output dir under the docs output dir.
const char * htmldir = astr(dirpath.c_str(), "/html");
// Ensure output directory exists.
const char * mkdirCmd = astr("mkdir -p ", htmldir);
mysystem(mkdirCmd, "creating docs output dir");
// Copy the sphinx template into the output dir.
const char * sphinxTemplate = astr(CHPL_HOME, "/third-party/chpldoc-venv/chpldoc-sphinx-project/*");
const char * cmd = astr("cp -r ", sphinxTemplate, " ", htmldir, "/");
mysystem(cmd, "copying chpldoc sphinx template");
const char * moddir = astr(htmldir, "/source/modules");
return std::string(moddir);
}
/* Call `make html` from inside sphinx project. */
void generateSphinxOutput(std::string dirpath) {
const char * htmldir = astr(dirpath.c_str(), "/html");
// The virtualenv activate script is at:
// $CHPL_HOME/third-party/chpldoc-venv/install/$CHPL_TARGET_PLATFORM/chpldoc-virtualenv/bin/activate
const char * activate = astr(
CHPL_HOME, "/third-party/chpldoc-venv/install/",
CHPL_TARGET_PLATFORM, "/chpdoc-virtualenv/bin/activate");
// Run: `. $activate && cd $htmldir && $CHPL_MAKE html`
const char * cmd = astr(
". ", activate,
" && cd ", htmldir, " && ",
CHPL_MAKE, " html");
mysystem(cmd, "building html output from chpldoc sphinx project");
}
std::string filenameFromMod(ModuleSymbol *mod, std::string docsFolderName) {
std::string filename = mod->filename;
if (mod->modTag == MOD_INTERNAL) {
filename = "internal-modules/";
} else if (mod ->modTag == MOD_STANDARD) {
filename = "standard-modules/";
} else {
size_t location = filename.rfind("/");
if (location != std::string::npos) {
filename = filename.substr(0, location + 1);
} else {
filename = "";
}
}
filename = docsFolderName + "/" + filename;
createDocsFileFolders(filename);
// Creates files for each top level module.
if (fDocsTextOnly) {
filename = filename + mod->name + ".txt";
} else {
filename = filename + mod->name + ".rst";
}
return filename;
}
std::ofstream* openFileFromMod(ModuleSymbol *mod, std::string docsFolderName) {
std::string filename = filenameFromMod(mod, docsFolderName);
return new std::ofstream(filename.c_str(), std::ios::out);
}
<commit_msg>Comment out inheritance lines in docs.cpp.<commit_after>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <map>
#include <iostream>
#include <fstream>
#include <iterator>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include "driver.h"
#include "passes.h"
#include "symbol.h"
#include "expr.h"
#include "stmt.h"
#include "docs.h"
#include "mysystem.h"
#include "stringutil.h"
#include "scopeResolve.h"
#include "AstToText.h"
#include "AstPrintDocs.h"
static int compareNames(const void* v1, const void* v2) {
Symbol* s1 = *(Symbol* const *)v1;
Symbol* s2 = *(Symbol* const *)v2;
return strcmp(s1->name, s2->name);
}
static int compareClasses(const void *v1, const void* v2) {
Type *t1 = *(Type* const *)v1;
Type *t2 = *(Type* const *)v2;
return strcmp(t1->symbol->name, t2->symbol->name);
}
void docs(void) {
if (fDocs) {
// To handle inheritance, we need to look up parent classes and records.
// In order to be successful when looking up these parents, the import
// expressions should be accurately accounted for.
addToSymbolTable(gDefExprs);
processImportExprs();
// Open the directory to store the docs
std::string docsDir = (strlen(fDocsFolder) != 0) ? fDocsFolder : "docs";
std::string docsFolderName = docsDir;
if (!fDocsTextOnly) {
docsFolderName = generateSphinxProject(docsDir);
}
mkdir(docsFolderName.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!mod->hasFlag(FLAG_NO_DOC) && !devOnlyModule(mod)) {
if (isNotSubmodule(mod)) {
std::ofstream *file = openFileFromMod(mod, docsFolderName);
AstPrintDocs *docsVisitor = new AstPrintDocs(file);
mod->accept(docsVisitor);
delete docsVisitor;
// Comment the above three lines and uncomment the following line to
// get the old category based output (or alphabetical). Note that
// this will be restored (hopefully soon)... (thomasvandoren, 2015-02-22)
//
// printModule(file, mod, 0);
file->close();
}
}
}
if (!fDocsTextOnly) {
generateSphinxOutput(docsDir);
}
}
}
bool isNotSubmodule(ModuleSymbol *mod) {
return (mod->defPoint == NULL ||
mod->defPoint->parentSymbol == NULL ||
mod->defPoint->parentSymbol->name == NULL ||
strcmp("chpl__Program", mod->defPoint->parentSymbol->name) == 0 ||
strcmp("_root", mod->defPoint->parentSymbol->name) == 0);
}
void printFields(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
for (int i = 1; i <= cl->fields.length; i++) {
if (VarSymbol *var = toVarSymbol(((DefExpr *)cl->fields.get(i))->sym)) {
var->printDocs(file, tabs);
}
}
}
void inheritance(Vec<AggregateType*> *list, AggregateType *cl) {
for_alist(expr, cl->inherits) {
AggregateType* pt = discoverParentAndCheck(expr, cl);
list->add_exclusive(pt);
inheritance(list, pt);
}
}
void printClass(std::ofstream *file, AggregateType *cl, unsigned int tabs) {
if (!cl->symbol->hasFlag(FLAG_NO_DOC) && ! cl->isUnion()) {
cl->printDocs(file, tabs);
printFields(file, cl, tabs + 1);
// In rst mode, add an additional line break after the attributes and
// before the next directive.
if (!fDocsTextOnly) {
*file << std::endl;
}
// If alphabetical option passed, alphabetizes the output
if (fDocsAlphabetize)
qsort(cl->methods.v, cl->methods.n, sizeof(cl->methods.v[0]),
compareNames);
forv_Vec(FnSymbol, fn, cl->methods){
// We only want to print methods defined within the class under the
// class header
if (fn->isPrimaryMethod())
fn->printDocs(file, tabs + 1);
}
// TODO: Restore the following lines as opt-in feature. They print the the
// "inherited from <blah>" line and all the inherited members and
// methods. (thomasvandoren, 2015-02-23)
//
// Vec<AggregateType*> superClasses;
// inheritance(&superClasses, cl);
// if (fDocsAlphabetize)
// qsort(superClasses.v, superClasses.n, sizeof(superClasses.v[0]), compareClasses);
// forv_Vec(AggregateType, superClass, superClasses) {
// superClass->printInheritanceDocs(file, tabs + 1);
// printFields(file, superClass, tabs + 2);
// forv_Vec(FnSymbol, fn, superClass->methods) {
// fn->printDocs(file, tabs + 2);
// }
// *file << std::endl;
// }
}
}
// Returns true if the provided fn is a module initializer, class constructor,
// type constructor, or module copy of a class method. These functions are
// only printed in developer mode. Is not applicable to printing class
// functions.
bool devOnlyFunction(FnSymbol *fn) {
return (fn->hasFlag(FLAG_MODULE_INIT) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)
|| fn->hasFlag(FLAG_CONSTRUCTOR) || fn->isPrimaryMethod());
}
// Returns true if the provide module is one of the internal or standard
// modules. It is our opinion that these should only automatically be printed
// out if the user is in developer mode.
bool devOnlyModule(ModuleSymbol *mod) {
return mod->modTag == MOD_INTERNAL || mod->modTag == MOD_STANDARD;
}
void printModule(std::ofstream *file, ModuleSymbol *mod, unsigned int tabs) {
if (!mod->hasFlag(FLAG_NO_DOC)) {
mod->printDocs(file, tabs);
Vec<VarSymbol*> configs = mod->getTopLevelConfigVars();
if (fDocsAlphabetize)
qsort(configs.v, configs.n, sizeof(configs.v[0]), compareNames);
forv_Vec(VarSymbol, var, configs) {
var->printDocs(file, tabs + 1);
}
Vec<VarSymbol*> variables = mod->getTopLevelVariables();
if (fDocsAlphabetize)
qsort(variables.v, variables.n, sizeof(variables.v[0]), compareNames);
forv_Vec(VarSymbol, var, variables) {
var->printDocs(file, tabs + 1);
}
Vec<FnSymbol*> fns = mod->getTopLevelFunctions(fDocsIncludeExterns);
// If alphabetical option passed, fDocsAlphabetizes the output
if (fDocsAlphabetize)
qsort(fns.v, fns.n, sizeof(fns.v[0]), compareNames);
forv_Vec(FnSymbol, fn, fns) {
// TODO: Add flag to compiler to turn on doc dev only output
// We want methods on classes that are defined at the module level to be
// printed at the module level
if (!devOnlyFunction(fn) || fn->isSecondaryMethod()) {
fn->printDocs(file, tabs + 1);
}
}
Vec<AggregateType*> classes = mod->getTopLevelClasses();
if (fDocsAlphabetize)
qsort(classes.v, classes.n, sizeof(classes.v[0]), compareClasses);
forv_Vec(AggregateType, cl, classes) {
printClass(file, cl, tabs + 1);
}
Vec<ModuleSymbol*> mods = mod->getTopLevelModules();
if (fDocsAlphabetize)
qsort(mods.v, mods.n, sizeof(mods.v[0]), compareNames);
forv_Vec(ModuleSymbol, subMod, mods) {
// TODO: Add flag to compiler to turn on doc dev only output
if (!devOnlyModule(subMod)) {
subMod->addPrefixToName(mod->docsName() + ".");
printModule(file, subMod, tabs + 1);
}
}
}
}
void createDocsFileFolders(std::string filename) {
size_t dirCutoff = filename.find("/");
size_t total = 0;
while (dirCutoff != std::string::npos) {
// Creates each subdirectory within the new documentation directory
dirCutoff += total;
std::string shorter = filename.substr(dirCutoff+1);
std::string otherHalf = filename.substr(0, dirCutoff);
mkdir(otherHalf.c_str(), S_IWUSR|S_IRUSR|S_IXUSR);
total = dirCutoff + 1;
dirCutoff = shorter.find("/");
}
}
/*
* Create new sphinx project at given location and return path where .rst files
* should be placed.
*/
std::string generateSphinxProject(std::string dirpath) {
// FIXME: This ought to be done in a TMPDIR, unless --save-rst is
// provided... (thomasvandoren, 2015-01-29)
// Create the output dir under the docs output dir.
const char * htmldir = astr(dirpath.c_str(), "/html");
// Ensure output directory exists.
const char * mkdirCmd = astr("mkdir -p ", htmldir);
mysystem(mkdirCmd, "creating docs output dir");
// Copy the sphinx template into the output dir.
const char * sphinxTemplate = astr(CHPL_HOME, "/third-party/chpldoc-venv/chpldoc-sphinx-project/*");
const char * cmd = astr("cp -r ", sphinxTemplate, " ", htmldir, "/");
mysystem(cmd, "copying chpldoc sphinx template");
const char * moddir = astr(htmldir, "/source/modules");
return std::string(moddir);
}
/* Call `make html` from inside sphinx project. */
void generateSphinxOutput(std::string dirpath) {
const char * htmldir = astr(dirpath.c_str(), "/html");
// The virtualenv activate script is at:
// $CHPL_HOME/third-party/chpldoc-venv/install/$CHPL_TARGET_PLATFORM/chpldoc-virtualenv/bin/activate
const char * activate = astr(
CHPL_HOME, "/third-party/chpldoc-venv/install/",
CHPL_TARGET_PLATFORM, "/chpdoc-virtualenv/bin/activate");
// Run: `. $activate && cd $htmldir && $CHPL_MAKE html`
const char * cmd = astr(
". ", activate,
" && cd ", htmldir, " && ",
CHPL_MAKE, " html");
mysystem(cmd, "building html output from chpldoc sphinx project");
}
std::string filenameFromMod(ModuleSymbol *mod, std::string docsFolderName) {
std::string filename = mod->filename;
if (mod->modTag == MOD_INTERNAL) {
filename = "internal-modules/";
} else if (mod ->modTag == MOD_STANDARD) {
filename = "standard-modules/";
} else {
size_t location = filename.rfind("/");
if (location != std::string::npos) {
filename = filename.substr(0, location + 1);
} else {
filename = "";
}
}
filename = docsFolderName + "/" + filename;
createDocsFileFolders(filename);
// Creates files for each top level module.
if (fDocsTextOnly) {
filename = filename + mod->name + ".txt";
} else {
filename = filename + mod->name + ".rst";
}
return filename;
}
std::ofstream* openFileFromMod(ModuleSymbol *mod, std::string docsFolderName) {
std::string filename = filenameFromMod(mod, docsFolderName);
return new std::ofstream(filename.c_str(), std::ios::out);
}
<|endoftext|> |
<commit_before>/** \file json-voorhees/value.hpp
*
* Copyright (c) 2012 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#ifndef __JSON_VOORHEES_VALUE_HPP_INCLUDED__
#define __JSON_VOORHEES_VALUE_HPP_INCLUDED__
#include "standard.hpp"
#include <cstdint>
#include <iterator>
#include <ostream>
#include <stdexcept>
#include <string>
#include <utility>
namespace jsonv
{
namespace detail
{
class object_impl;
class array_impl;
class string_impl;
union value_storage
{
object_impl* object;
array_impl* array;
string_impl* string;
int64_t integer;
double decimal;
bool boolean;
};
}
enum class value_type
{
null,
object,
array,
string,
integer,
decimal,
boolean
};
class value_type_error :
public std::logic_error
{
public:
explicit value_type_error(const std::string& description);
virtual ~value_type_error() throw();
};
class object_view;
class array_view;
/** \see http://json.org/
**/
class value
{
public:
/// Default-construct this to null.
value();
value(const value& source);
value(const string_type& val);
value(const char_type* val);
value(int64_t val);
value(double val);
value(bool val);
value(const object_view& obj_view);
value(const array_view& array_view);
#define JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR(type_) \
value(type_ val);
JSON_VOORHEES_INTEGER_ALTERNATES_LIST(JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR)
// Don't allow any implicit conversions that we have not specified.
template <typename T>
value(T) = delete;
~value();
/** Copy-assigns \c source to this.
*
* If an exception is thrown during the copy, it is propagated out. This instance will be set to a null value - any
* value will be disposed.
**/
value& operator=(const value& source);
value(value&& source);
/** Move-assigns \c source to this.
*
* Unlike a copy, this will never throw.
**/
value& operator=(value&& source);
static value make_object();
static value make_array();
/// Resets this value to null.
void clear();
inline value_type type() const
{
return _type;
}
object_view as_object();
const object_view as_object() const;
array_view as_array();
const array_view as_array() const;
string_type& as_string();
const string_type& as_string() const;
int64_t& as_integer();
int64_t as_integer() const;
double& as_decimal();
double as_decimal() const;
bool& as_boolean();
bool as_boolean() const;
/** Compares two JSON values for equality. Two JSON values are equal if and only if all of the following conditions
* apply:
*
* 1. They have the same valid value for \c type.
* - If \c type is invalid (memory corruption), then two JSON values are \e not equal, even if they have been
* corrupted in the same way and even if they share \c this (a corrupt object is not equal to itself).
* 2. The type comparison is also equal:
* a. Two null values are always equivalent.
* b. string, integer, decimal and boolean follow the classic rules for their type.
* c. objects are equal if they have the same keys and values corresponding with the same key are also equal.
* d. arrays are equal if they have the same length and the values at each index are also equal.
*
* \note
* The rules for equality are based on Python \c dict.
**/
bool operator ==(const value& other) const;
/** Compares two JSON values for inequality. The rules for inequality are the exact opposite of equality.
**/
bool operator !=(const value& other) const;
// FUTURE: I guess do it just like Python?
// bool operator <(const value& other) const;
friend ostream_type& operator <<(ostream_type& stream, const value& val);
private:
detail::value_storage _data;
value_type _type;
};
/** A "view" of a JSON \c value as a JSON object (obtain with \c value::as_object). This does not ensure the object you
* are viewing stays alive, so you must do that yourself -- an \c object_view just has a pointer, so if that pointer
* goes bad, the behavior is undefined. After the awkward lifetime management, this is pretty much an associative
* container for mapping a string to a JSON \c value.
*
* @example
* @code
* jsonv::value val = something();
* jsonv::object_view obj = val.as_object();
* foo(obj["bar"]);
* @endcode
*
* This is a pretty awkward way to do things, actually. The alternative is to roll indexing operator and iterators into
* \c value, which leads to having a bunch of operators inside the class. I figured this is the lesser of two evils.
**/
class object_view
{
public:
typedef size_t size_type;
typedef string_type key_type;
typedef value mapped_type;
typedef std::pair<const string_type, value> value_type;
typedef std::equal_to<string_type> key_compare;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
template <typename T>
struct basic_iterator :
public std::iterator<std::bidirectional_iterator_tag, T>
{
public:
basic_iterator();
basic_iterator(const basic_iterator& source)
{
copy_from(source._storage);
}
basic_iterator& operator++()
{
increment();
return *this;
}
basic_iterator operator++(int) const
{
basic_iterator clone(*this);
clone.increment();
return clone;
}
basic_iterator& operator--()
{
decrement();
return *this;
}
basic_iterator operator--(int) const
{
basic_iterator clone(*this);
clone.decrement();
return clone;
}
template <typename U>
bool operator ==(const basic_iterator<U>& other) const
{
return equals(other._storage);
}
template <typename U>
bool operator !=(const basic_iterator<U>& other) const
{
return !equals(other._storage);
}
T& operator *() const
{
return current();
}
T* operator ->() const
{
return ¤t();
}
private:
friend class object_view;
template <typename U>
explicit basic_iterator(const U&);
void increment();
void decrement();
T& current() const;
bool equals(const char* other_storage) const;
void copy_from(const char* other_storage);
private:
char _storage[sizeof(void*)];
};
typedef basic_iterator<value_type> iterator;
typedef basic_iterator<const value_type> const_iterator;
public:
size_type size() const;
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
value& operator[](const string_type& key);
const value& operator[](const string_type& key) const;
iterator find(const string_type& key);
const_iterator find(const string_type& key) const;
void insert(const value_type& pair);
void insert_many()
{ }
template <typename T, typename... TRest>
void insert_many(T&& pair, TRest&&... rest)
{
insert(std::forward<T>(pair));
insert_many(std::forward<TRest>(rest)...);
}
/// \see value::operator==
bool operator==(const object_view& other) const;
/// \see value::operator!=
bool operator!=(const object_view& other) const;
friend ostream_type& operator <<(ostream_type& stream, const object_view& view);
private:
friend class value;
explicit object_view(detail::object_impl* source);
private:
detail::object_impl* _source;
};
/** This is a view of a \c value as a JSON array (with the same lack of lifetime management as \c object_view). It is a
* sequence container which behaves a lot like an \c std::deque (probably because that is the type that backs it).
**/
class array_view
{
public:
typedef size_t size_type;
typedef value value_type;
typedef value& reference;
typedef const value& const_reference;
typedef value* pointer;
typedef const value* const_pointer;
template <typename T, typename TArrayView>
struct basic_iterator :
public std::iterator<std::random_access_iterator_tag, T>
{
public:
basic_iterator() :
_owner(0),
_index(0)
{ }
basic_iterator(TArrayView* owner, size_type index) :
_owner(owner),
_index(index)
{ }
basic_iterator& operator ++()
{
++_index;
return *this;
}
basic_iterator operator ++(int) const
{
basic_iterator clone = *this;
++clone;
return clone;
}
basic_iterator& operator --()
{
--_index;
return *this;
}
basic_iterator operator --(int) const
{
basic_iterator clone = *this;
--clone;
return clone;
}
template <typename U, typename UArrayView>
bool operator ==(const basic_iterator<U, UArrayView>& other) const
{
return _owner == other._owner && _index == other._index;
}
template <typename U, typename UArrayView>
bool operator !=(const basic_iterator<U, UArrayView>& other) const
{
return !operator==(other);
}
T& operator *() const
{
return _owner->operator[](_index);
}
T* operator ->() const
{
return &_owner->operator[](_index);
}
basic_iterator& operator +=(size_type n)
{
_index += n;
return *this;
}
basic_iterator operator +(size_type n) const
{
basic_iterator clone = *this;
clone += n;
return clone;
}
basic_iterator& operator -=(size_type n)
{
_index -= n;
return *this;
}
basic_iterator operator -(size_type n) const
{
basic_iterator clone = *this;
clone -= n;
return clone;
}
bool operator <(const basic_iterator& rhs) const
{
return _index < rhs._index;
}
bool operator <=(const basic_iterator& rhs) const
{
return _index <= rhs._index;
}
bool operator >(const basic_iterator& rhs) const
{
return _index > rhs._index;
}
bool operator >=(const basic_iterator& rhs) const
{
return _index >= rhs._index;
}
T& operator[](size_type n) const
{
return _owner->operator[](_index + n);
}
private:
TArrayView* _owner;
size_type _index;
};
typedef basic_iterator<value, array_view> iterator;
typedef basic_iterator<const value, const array_view> const_iterator;
public:
size_type size() const;
bool empty() const;
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
value& operator[](size_type idx);
const value& operator[](size_type idx) const;
void push_back(const value& value);
void pop_back();
void push_front(const value& value);
void pop_front();
void clear();
void resize(size_type count, const value& val = value());
/// \see value::operator==
bool operator==(const array_view& other) const;
/// \see value::operator!=
bool operator!=(const array_view& other) const;
void push_back_many()
{ }
template <typename T, typename... TRest>
void push_back_many(T&& val, TRest&&... rest)
{
push_back(std::forward<T>(val));
push_back_many(std::forward<TRest>(rest)...);
}
friend ostream_type& operator <<(ostream_type& stream, const array_view& view);
private:
friend class value;
explicit array_view(detail::array_impl* source);
private:
detail::array_impl* _source;
};
/** Creates an array with the given \a values.
*
* \example
* \code
* jsonv::value val = jsonv::make_array(1, 2, 3, "foo");
* // Creates: [1, 2, 3, "foo"]
* \endcode
**/
template <typename... T>
value make_array(T&&... values)
{
value val = value::make_array();
val.as_array().push_back_many(std::forward<T>(values)...);
return val;
}
/** Creates an object with the given \a pairs.
*
* \example
* \code
* jsonv::value val = jsonv::make_object({"foo", 8}, {"bar", "wat"});
* // Creates: { "bar": "wat", "foo": 8 }
* \endcode
**/
template <typename... T>
value make_object(T&&... pairs)
{
value val = value::make_object();
val.as_object().insert_many(std::forward<T>(pairs)...);
return val;
}
}
#endif/*__JSON_VOORHEES_VALUE_HPP_INCLUDED__*/
<commit_msg>Changes the way make_object works to something more convenient.<commit_after>/** \file json-voorhees/value.hpp
*
* Copyright (c) 2012 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#ifndef __JSON_VOORHEES_VALUE_HPP_INCLUDED__
#define __JSON_VOORHEES_VALUE_HPP_INCLUDED__
#include "standard.hpp"
#include <cstdint>
#include <iterator>
#include <ostream>
#include <stdexcept>
#include <string>
#include <utility>
namespace jsonv
{
namespace detail
{
class object_impl;
class array_impl;
class string_impl;
union value_storage
{
object_impl* object;
array_impl* array;
string_impl* string;
int64_t integer;
double decimal;
bool boolean;
};
}
enum class value_type
{
null,
object,
array,
string,
integer,
decimal,
boolean
};
class value_type_error :
public std::logic_error
{
public:
explicit value_type_error(const std::string& description);
virtual ~value_type_error() throw();
};
class object_view;
class array_view;
/** \see http://json.org/
**/
class value
{
public:
/// Default-construct this to null.
value();
value(const value& source);
value(const string_type& val);
value(const char_type* val);
value(int64_t val);
value(double val);
value(bool val);
value(const object_view& obj_view);
value(const array_view& array_view);
#define JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR(type_) \
value(type_ val);
JSON_VOORHEES_INTEGER_ALTERNATES_LIST(JSONV_VALUE_INTEGER_ALTERNATIVE_CTOR_PROTO_GENERATOR)
// Don't allow any implicit conversions that we have not specified.
template <typename T>
value(T) = delete;
~value();
/** Copy-assigns \c source to this.
*
* If an exception is thrown during the copy, it is propagated out. This instance will be set to a null value - any
* value will be disposed.
**/
value& operator=(const value& source);
value(value&& source);
/** Move-assigns \c source to this.
*
* Unlike a copy, this will never throw.
**/
value& operator=(value&& source);
static value make_object();
static value make_array();
/// Resets this value to null.
void clear();
inline value_type type() const
{
return _type;
}
object_view as_object();
const object_view as_object() const;
array_view as_array();
const array_view as_array() const;
string_type& as_string();
const string_type& as_string() const;
int64_t& as_integer();
int64_t as_integer() const;
double& as_decimal();
double as_decimal() const;
bool& as_boolean();
bool as_boolean() const;
/** Compares two JSON values for equality. Two JSON values are equal if and only if all of the following conditions
* apply:
*
* 1. They have the same valid value for \c type.
* - If \c type is invalid (memory corruption), then two JSON values are \e not equal, even if they have been
* corrupted in the same way and even if they share \c this (a corrupt object is not equal to itself).
* 2. The type comparison is also equal:
* a. Two null values are always equivalent.
* b. string, integer, decimal and boolean follow the classic rules for their type.
* c. objects are equal if they have the same keys and values corresponding with the same key are also equal.
* d. arrays are equal if they have the same length and the values at each index are also equal.
*
* \note
* The rules for equality are based on Python \c dict.
**/
bool operator ==(const value& other) const;
/** Compares two JSON values for inequality. The rules for inequality are the exact opposite of equality.
**/
bool operator !=(const value& other) const;
// FUTURE: I guess do it just like Python?
// bool operator <(const value& other) const;
friend ostream_type& operator <<(ostream_type& stream, const value& val);
private:
detail::value_storage _data;
value_type _type;
};
/** A "view" of a JSON \c value as a JSON object (obtain with \c value::as_object). This does not ensure the object you
* are viewing stays alive, so you must do that yourself -- an \c object_view just has a pointer, so if that pointer
* goes bad, the behavior is undefined. After the awkward lifetime management, this is pretty much an associative
* container for mapping a string to a JSON \c value.
*
* @example
* @code
* jsonv::value val = something();
* jsonv::object_view obj = val.as_object();
* foo(obj["bar"]);
* @endcode
*
* This is a pretty awkward way to do things, actually. The alternative is to roll indexing operator and iterators into
* \c value, which leads to having a bunch of operators inside the class. I figured this is the lesser of two evils.
**/
class object_view
{
public:
typedef size_t size_type;
typedef string_type key_type;
typedef value mapped_type;
typedef std::pair<const string_type, value> value_type;
typedef std::equal_to<string_type> key_compare;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
template <typename T>
struct basic_iterator :
public std::iterator<std::bidirectional_iterator_tag, T>
{
public:
basic_iterator();
basic_iterator(const basic_iterator& source)
{
copy_from(source._storage);
}
basic_iterator& operator++()
{
increment();
return *this;
}
basic_iterator operator++(int) const
{
basic_iterator clone(*this);
clone.increment();
return clone;
}
basic_iterator& operator--()
{
decrement();
return *this;
}
basic_iterator operator--(int) const
{
basic_iterator clone(*this);
clone.decrement();
return clone;
}
template <typename U>
bool operator ==(const basic_iterator<U>& other) const
{
return equals(other._storage);
}
template <typename U>
bool operator !=(const basic_iterator<U>& other) const
{
return !equals(other._storage);
}
T& operator *() const
{
return current();
}
T* operator ->() const
{
return ¤t();
}
private:
friend class object_view;
template <typename U>
explicit basic_iterator(const U&);
void increment();
void decrement();
T& current() const;
bool equals(const char* other_storage) const;
void copy_from(const char* other_storage);
private:
char _storage[sizeof(void*)];
};
typedef basic_iterator<value_type> iterator;
typedef basic_iterator<const value_type> const_iterator;
public:
size_type size() const;
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
value& operator[](const string_type& key);
const value& operator[](const string_type& key) const;
iterator find(const string_type& key);
const_iterator find(const string_type& key) const;
void insert(const value_type& pair);
void insert_many()
{ }
template <typename T, typename... TRest>
void insert_many(T&& pair, TRest&&... rest)
{
insert(std::forward<T>(pair));
insert_many(std::forward<TRest>(rest)...);
}
/// \see value::operator==
bool operator==(const object_view& other) const;
/// \see value::operator!=
bool operator!=(const object_view& other) const;
friend ostream_type& operator <<(ostream_type& stream, const object_view& view);
private:
friend class value;
explicit object_view(detail::object_impl* source);
private:
detail::object_impl* _source;
};
/** This is a view of a \c value as a JSON array (with the same lack of lifetime management as \c object_view). It is a
* sequence container which behaves a lot like an \c std::deque (probably because that is the type that backs it).
**/
class array_view
{
public:
typedef size_t size_type;
typedef value value_type;
typedef value& reference;
typedef const value& const_reference;
typedef value* pointer;
typedef const value* const_pointer;
template <typename T, typename TArrayView>
struct basic_iterator :
public std::iterator<std::random_access_iterator_tag, T>
{
public:
basic_iterator() :
_owner(0),
_index(0)
{ }
basic_iterator(TArrayView* owner, size_type index) :
_owner(owner),
_index(index)
{ }
basic_iterator& operator ++()
{
++_index;
return *this;
}
basic_iterator operator ++(int) const
{
basic_iterator clone = *this;
++clone;
return clone;
}
basic_iterator& operator --()
{
--_index;
return *this;
}
basic_iterator operator --(int) const
{
basic_iterator clone = *this;
--clone;
return clone;
}
template <typename U, typename UArrayView>
bool operator ==(const basic_iterator<U, UArrayView>& other) const
{
return _owner == other._owner && _index == other._index;
}
template <typename U, typename UArrayView>
bool operator !=(const basic_iterator<U, UArrayView>& other) const
{
return !operator==(other);
}
T& operator *() const
{
return _owner->operator[](_index);
}
T* operator ->() const
{
return &_owner->operator[](_index);
}
basic_iterator& operator +=(size_type n)
{
_index += n;
return *this;
}
basic_iterator operator +(size_type n) const
{
basic_iterator clone = *this;
clone += n;
return clone;
}
basic_iterator& operator -=(size_type n)
{
_index -= n;
return *this;
}
basic_iterator operator -(size_type n) const
{
basic_iterator clone = *this;
clone -= n;
return clone;
}
bool operator <(const basic_iterator& rhs) const
{
return _index < rhs._index;
}
bool operator <=(const basic_iterator& rhs) const
{
return _index <= rhs._index;
}
bool operator >(const basic_iterator& rhs) const
{
return _index > rhs._index;
}
bool operator >=(const basic_iterator& rhs) const
{
return _index >= rhs._index;
}
T& operator[](size_type n) const
{
return _owner->operator[](_index + n);
}
private:
TArrayView* _owner;
size_type _index;
};
typedef basic_iterator<value, array_view> iterator;
typedef basic_iterator<const value, const array_view> const_iterator;
public:
size_type size() const;
bool empty() const;
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
value& operator[](size_type idx);
const value& operator[](size_type idx) const;
void push_back(const value& value);
void pop_back();
void push_front(const value& value);
void pop_front();
void clear();
void resize(size_type count, const value& val = value());
/// \see value::operator==
bool operator==(const array_view& other) const;
/// \see value::operator!=
bool operator!=(const array_view& other) const;
void push_back_many()
{ }
template <typename T, typename... TRest>
void push_back_many(T&& val, TRest&&... rest)
{
push_back(std::forward<T>(val));
push_back_many(std::forward<TRest>(rest)...);
}
friend ostream_type& operator <<(ostream_type& stream, const array_view& view);
private:
friend class value;
explicit array_view(detail::array_impl* source);
private:
detail::array_impl* _source;
};
/** Creates an array with the given \a values.
*
* \example
* \code
* jsonv::value val = jsonv::make_array(1, 2, 3, "foo");
* // Creates: [1, 2, 3, "foo"]
* \endcode
**/
template <typename... T>
value make_array(T&&... values)
{
value val = value::make_array();
val.as_array().push_back_many(std::forward<T>(values)...);
return val;
}
namespace detail
{
inline void make_object_impl(jsonv::object_view&)
{ }
template <typename TKey, typename TValue, typename... TRest>
void make_object_impl(jsonv::object_view& obj, TKey&& key, TValue&& value, TRest&&... rest)
{
obj.insert(object_view::value_type(std::forward<TKey>(key), std::forward<TValue>(value)));
make_object_impl(obj, std::forward<TRest>(rest)...);
}
}
/** Creates an object with the given \a entries.
*
* \example
* \code
* jsonv::value val = jsonv::make_object("foo", 8, "bar", "wat");
* // Creates: { "bar": "wat", "foo": 8 }
* \endcode
**/
template <typename... T>
value make_object(T&&... entries)
{
static_assert(sizeof...(T) % 2 == 0, "Must have even number of entries: (key0, value0, key1, value1, ...)");
value val = value::make_object();
object_view obj = val.as_object();
detail::make_object_impl(obj, std::forward<T>(entries)...);
return val;
}
}
#endif/*__JSON_VOORHEES_VALUE_HPP_INCLUDED__*/
<|endoftext|> |
<commit_before>/**
* \file TestIssues.cpp
* \brief Issues submitted
* \author Frank Bergmann
*
* <!--------------------------------------------------------------------------
*
* This file is part of libSEDML. Please visit http://sed-ml.org for more
* information about SED-ML. The latest version of libSEDML can be found on
* github: https://github.com/fbergmann/libSEDML/
*
*
* Copyright (c) 2013-2014, Frank T. Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ---------------------------------------------------------------------- -->
*
*/
#include <limits>
#include <iostream>
#include <check.h>
#include <string>
#include <sstream>
#include <sbml/common/libsbml-version.h>
#include <sedml/common/libsedml-version.h>
#include <sedml/SedDocument.h>
#include <sedml/SedDataGenerator.h>
#include <sedml/SedWriter.h>
#include <sbml/math/L3FormulaFormatter.h>
#include <sbml/math/L3Parser.h>
/** @cond doxygenIgnored */
using namespace std;
LIBSBML_CPP_NAMESPACE_USE
LIBSEDML_CPP_NAMESPACE_USE
/** @endcond */
CK_CPPSTART
START_TEST (test_mathml_issue1)
{
SedDocument doc;
SedDataGenerator* sdg = doc.createDataGenerator();
ASTNode* astn = SBML_parseL3Formula("S1/S2");
sdg->setMath(astn);
ostringstream stream;
SedWriter sw;
sw.writeSedML(&doc, stream);
string v1 = stream.str();
stream.str("");
astn = SBML_parseL3Formula("log(S1/S2)");
sdg->setMath(astn->getChild(1));
sw.writeSedML(&doc, stream);
string v2 = stream.str();
//cout << v1 << endl << endl << v2 << endl << endl;
fail_unless( v1 == v2 );
}
END_TEST
Suite *
create_suite_SedMLIssues (void)
{
Suite *suite = suite_create("SedMLIssues");
TCase *tcase = tcase_create("SedMLIssues");
cout << "Testing issues reported using: " << endl;
cout << " libSBML : " << getLibSBMLDottedVersion() << endl;
cout << " libSEDML : " << getLibSEDMLDottedVersion() << endl << endl;
tcase_add_test( tcase, test_mathml_issue1 );
suite_add_tcase(suite, tcase);
return suite;
}
CK_CPPEND
<commit_msg>- print information about legacy math<commit_after>/**
* \file TestIssues.cpp
* \brief Issues submitted
* \author Frank Bergmann
*
* <!--------------------------------------------------------------------------
*
* This file is part of libSEDML. Please visit http://sed-ml.org for more
* information about SED-ML. The latest version of libSEDML can be found on
* github: https://github.com/fbergmann/libSEDML/
*
*
* Copyright (c) 2013-2014, Frank T. Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ---------------------------------------------------------------------- -->
*
*/
#include <limits>
#include <iostream>
#include <check.h>
#include <string>
#include <sstream>
#include <sbml/common/libsbml-version.h>
#include <sedml/common/libsedml-version.h>
#include <sedml/SedDocument.h>
#include <sedml/SedDataGenerator.h>
#include <sedml/SedWriter.h>
#include <sbml/math/L3FormulaFormatter.h>
#include <sbml/math/L3Parser.h>
/** @cond doxygenIgnored */
using namespace std;
LIBSBML_CPP_NAMESPACE_USE
LIBSEDML_CPP_NAMESPACE_USE
/** @endcond */
CK_CPPSTART
START_TEST (test_mathml_issue1)
{
SedDocument doc;
SedDataGenerator* sdg = doc.createDataGenerator();
ASTNode* astn = SBML_parseL3Formula("S1/S2");
sdg->setMath(astn);
ostringstream stream;
SedWriter sw;
sw.writeSedML(&doc, stream);
string v1 = stream.str();
stream.str("");
astn = SBML_parseL3Formula("log(S1/S2)");
sdg->setMath(astn->getChild(1));
sw.writeSedML(&doc, stream);
string v2 = stream.str();
//cout << v1 << endl << endl << v2 << endl << endl;
fail_unless( v1 == v2 );
}
END_TEST
Suite *
create_suite_SedMLIssues (void)
{
Suite *suite = suite_create("SedMLIssues");
TCase *tcase = tcase_create("SedMLIssues");
cout << "Testing issues reported using: " << endl;
cout << " libSBML : " << getLibSBMLDottedVersion()
#if LIBSBML_USE_LEGACY_MATH
<< " (using legacy math) "
#else
<< " (using new ASTnode implementation) "
#endif
<< endl;
cout << " libSEDML : " << getLibSEDMLDottedVersion() << endl << endl;
tcase_add_test( tcase, test_mathml_issue1 );
suite_add_tcase(suite, tcase);
return suite;
}
CK_CPPEND
<|endoftext|> |
<commit_before>/**
* @file
* TestRunner.cpp
*
* @brief The main method in this file runs all CppUnit tests.
*
* @date: Oct 16, 2009
* @author: sblume
*/
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
int main(int argc, char* argv[]) {
/*see also: http://cppunit.sourceforge.net/doc/lastest/money_example.html#sec_running_test */
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest(suite);
// Change the default outputter to a compiler error format outputter
runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), std::cerr));
// Run the tests.
bool wasSucessful = runner.run();
// Return error code 1 if the one of test failed.
return wasSucessful ? 0 : 1;
}
/* EOF */
<commit_msg>Optional XML output for unittests added. <commit_after>/**
* @file
* TestRunner.cpp
*
* @brief The main method in this file runs all CppUnit tests.
*
* @date: Oct 16, 2009
* @author: sblume
*/
#include <fstream>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/XmlOutputter.h>
int main(int argc, char* argv[]) {
/*see also: http://cppunit.sourceforge.net/doc/lastest/money_example.html#sec_running_test */
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest(suite);
// Check the set parameters.
bool useXmlOutput = false;
if (argc == 2) {
std::string parameter = argv[1];
if (parameter.compare("--report-xml") == 0) {
useXmlOutput = true;
}
}
// Decide which output format to take.
std::ofstream outputStream;
if (useXmlOutput) {
// Change the default outputter to a XML outputter
outputStream.open("unit_test_results.xml");
runner.setOutputter(new CppUnit::XmlOutputter(&runner.result(), outputStream, std::string("ISO-8859-1")));
} else {
// Change the default outputter to a compiler error format outputter
runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), std::cerr));
}
// Run the tests.
bool wasSucessful = runner.run();
// Return error code 1 if the one of test failed.
return wasSucessful ? 0 : 1;
}
/* EOF */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED
#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
namespace libtorrent
{
struct TORRENT_EXPORT bitfield
{
bitfield(): m_bytes(0), m_size(0), m_own(false) {}
bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
{ resize(bits); }
bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
{ resize(bits, val); }
bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
{ assign(b, bits); }
bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
{ assign(rhs.bytes(), rhs.size()); }
void borrow_bytes(char* b, int bits)
{
dealloc();
m_bytes = (unsigned char*)b;
m_size = bits;
m_own = false;
}
~bitfield() { dealloc(); }
void assign(char const* b, int bits)
{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }
bool operator[](int index) const
{ return get_bit(index); }
bool get_bit(int index) const
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
}
void clear_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] &= ~(0x80 >> (index & 7));
}
void set_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] |= (0x80 >> (index & 7));
}
std::size_t size() const { return m_size; }
bool empty() const { return m_size == 0; }
char const* bytes() const { return (char*)m_bytes; }
bitfield& operator=(bitfield const& rhs)
{
assign(rhs.bytes(), rhs.size());
return *this;
}
int count() const
{
// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
const static char num_bits[] =
{
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
};
int ret = 0;
const int num_bytes = m_size / 8;
for (int i = 0; i < num_bytes; ++i)
{
ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
}
int rest = m_size - num_bytes * 8;
for (int i = 0; i < rest; ++i)
{
ret += (m_bytes[num_bytes] >> (7-i)) & 1;
}
TORRENT_ASSERT(ret <= m_size);
TORRENT_ASSERT(ret >= 0);
return ret;
}
struct const_iterator
{
friend struct bitfield;
typedef bool value_type;
typedef ptrdiff_t difference_type;
typedef bool const* pointer;
typedef bool& reference;
typedef std::forward_iterator_tag iterator_category;
bool operator*() { return (*byte & bit) != 0; }
const_iterator& operator++() { inc(); return *this; }
const_iterator operator++(int)
{ const_iterator ret(*this); inc(); return ret; }
const_iterator& operator--() { dec(); return *this; }
const_iterator operator--(int)
{ const_iterator ret(*this); dec(); return ret; }
const_iterator(): byte(0), bit(0x80) {}
bool operator==(const_iterator const& rhs) const
{ return byte == rhs.byte && bit == rhs.bit; }
bool operator!=(const_iterator const& rhs) const
{ return byte != rhs.byte || bit != rhs.bit; }
private:
void inc()
{
TORRENT_ASSERT(byte);
if (bit == 0x01)
{
bit = 0x80;
++byte;
}
else
{
bit >>= 1;
}
}
void dec()
{
TORRENT_ASSERT(byte);
if (bit == 0x80)
{
bit = 0x01;
--byte;
}
else
{
bit <<= 1;
}
}
const_iterator(unsigned char const* ptr, int offset)
: byte(ptr), bit(0x80 >> offset) {}
unsigned char const* byte;
int bit;
};
const_iterator begin() const { return const_iterator(m_bytes, 0); }
const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }
void resize(int bits, bool val)
{
int s = m_size;
int b = m_size & 7;
resize(bits);
if (s >= m_size) return;
int old_size_bytes = (s + 7) / 8;
int new_size_bytes = (m_size + 7) / 8;
if (val)
{
if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
clear_trailing_bits();
}
else
{
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
}
}
void set_all()
{
std::memset(m_bytes, 0xff, (m_size + 7) / 8);
clear_trailing_bits();
}
void clear_all()
{
std::memset(m_bytes, 0x00, (m_size + 7) / 8);
}
void resize(int bits)
{
const int b = (bits + 7) / 8;
if (m_bytes)
{
if (m_own)
{
m_bytes = (unsigned char*)std::realloc(m_bytes, b);
m_own = true;
}
else if (bits > m_size)
{
unsigned char* tmp = (unsigned char*)std::malloc(b);
std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
m_bytes = tmp;
m_own = true;
}
}
else
{
m_bytes = (unsigned char*)std::malloc(b);
m_own = true;
}
m_size = bits;
clear_trailing_bits();
}
void free() { dealloc(); m_size = 0; }
private:
void clear_trailing_bits()
{
// clear the tail bits in the last byte
if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
}
void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
unsigned char* m_bytes;
int m_size:31; // in bits
bool m_own:1;
};
}
#endif // TORRENT_BITFIELD_HPP_INCLUDED
<commit_msg>make electric fence happy by not allocating 0 bytes<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED
#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
namespace libtorrent
{
struct TORRENT_EXPORT bitfield
{
bitfield(): m_bytes(0), m_size(0), m_own(false) {}
bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
{ resize(bits); }
bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
{ resize(bits, val); }
bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
{ assign(b, bits); }
bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
{ assign(rhs.bytes(), rhs.size()); }
void borrow_bytes(char* b, int bits)
{
dealloc();
m_bytes = (unsigned char*)b;
m_size = bits;
m_own = false;
}
~bitfield() { dealloc(); }
void assign(char const* b, int bits)
{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }
bool operator[](int index) const
{ return get_bit(index); }
bool get_bit(int index) const
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
}
void clear_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] &= ~(0x80 >> (index & 7));
}
void set_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] |= (0x80 >> (index & 7));
}
std::size_t size() const { return m_size; }
bool empty() const { return m_size == 0; }
char const* bytes() const { return (char*)m_bytes; }
bitfield& operator=(bitfield const& rhs)
{
assign(rhs.bytes(), rhs.size());
return *this;
}
int count() const
{
// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
const static char num_bits[] =
{
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
};
int ret = 0;
const int num_bytes = m_size / 8;
for (int i = 0; i < num_bytes; ++i)
{
ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
}
int rest = m_size - num_bytes * 8;
for (int i = 0; i < rest; ++i)
{
ret += (m_bytes[num_bytes] >> (7-i)) & 1;
}
TORRENT_ASSERT(ret <= m_size);
TORRENT_ASSERT(ret >= 0);
return ret;
}
struct const_iterator
{
friend struct bitfield;
typedef bool value_type;
typedef ptrdiff_t difference_type;
typedef bool const* pointer;
typedef bool& reference;
typedef std::forward_iterator_tag iterator_category;
bool operator*() { return (*byte & bit) != 0; }
const_iterator& operator++() { inc(); return *this; }
const_iterator operator++(int)
{ const_iterator ret(*this); inc(); return ret; }
const_iterator& operator--() { dec(); return *this; }
const_iterator operator--(int)
{ const_iterator ret(*this); dec(); return ret; }
const_iterator(): byte(0), bit(0x80) {}
bool operator==(const_iterator const& rhs) const
{ return byte == rhs.byte && bit == rhs.bit; }
bool operator!=(const_iterator const& rhs) const
{ return byte != rhs.byte || bit != rhs.bit; }
private:
void inc()
{
TORRENT_ASSERT(byte);
if (bit == 0x01)
{
bit = 0x80;
++byte;
}
else
{
bit >>= 1;
}
}
void dec()
{
TORRENT_ASSERT(byte);
if (bit == 0x80)
{
bit = 0x01;
--byte;
}
else
{
bit <<= 1;
}
}
const_iterator(unsigned char const* ptr, int offset)
: byte(ptr), bit(0x80 >> offset) {}
unsigned char const* byte;
int bit;
};
const_iterator begin() const { return const_iterator(m_bytes, 0); }
const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }
void resize(int bits, bool val)
{
int s = m_size;
int b = m_size & 7;
resize(bits);
if (s >= m_size) return;
int old_size_bytes = (s + 7) / 8;
int new_size_bytes = (m_size + 7) / 8;
if (val)
{
if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
clear_trailing_bits();
}
else
{
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
}
}
void set_all()
{
std::memset(m_bytes, 0xff, (m_size + 7) / 8);
clear_trailing_bits();
}
void clear_all()
{
std::memset(m_bytes, 0x00, (m_size + 7) / 8);
}
void resize(int bits)
{
TORRENT_ASSERT(bits >= 0);
const int b = (bits + 7) / 8;
if (m_bytes)
{
if (m_own)
{
m_bytes = (unsigned char*)std::realloc(m_bytes, b);
m_own = true;
}
else if (bits > m_size)
{
unsigned char* tmp = (unsigned char*)std::malloc(b);
std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
m_bytes = tmp;
m_own = true;
}
}
else if (bits > 0)
{
m_bytes = (unsigned char*)std::malloc(b);
m_own = true;
}
m_size = bits;
clear_trailing_bits();
}
void free() { dealloc(); m_size = 0; }
private:
void clear_trailing_bits()
{
// clear the tail bits in the last byte
if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
}
void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
unsigned char* m_bytes;
int m_size:31; // in bits
bool m_own:1;
};
}
#endif // TORRENT_BITFIELD_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Automaton.cpp - Library for creating and running Finite State Machines.
Published under the MIT License (MIT), Copyright (c) 2015, J.P. van der Landen
*/
#include "Automaton.h"
void atm_timer_millis::set( uint32_t v ) {
value = v;
}
void atm_timer_micros::set( uint32_t v ) {
value = v;
}
int atm_timer_millis::expired( BaseMachine * machine ) {
return value == ATM_TIMER_OFF ? 0 : millis() - machine->state_millis >= value;
}
int atm_timer_micros::expired( Machine * machine ) {
return value == ATM_TIMER_OFF ? 0 : micros() - machine->state_micros >= value;
}
void atm_counter::set( uint16_t v )
{
value = v;
}
uint16_t atm_counter::decrement( void )
{
return value > 0 && value != ATM_COUNTER_OFF ? --value : 0;
}
uint8_t atm_counter::expired()
{
return value == ATM_COUNTER_OFF ? 0 : ( value > 0 ? 0 : 1 );
}
Machine & Machine::state(state_t state)
{
next = state;
last_trigger = -1;
flags &= ~ATM_SLEEP_FLAG;
if ( ( flags & ATM_MSGAC_FLAG ) > 0 ) msgClear();
return *this;
}
state_t Machine::state()
{
return current;
}
int Machine::trigger( int evt )
{
if ( current == -1 ) cycle();
if ( current > -1 ) {
int new_state = read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 );
if ( new_state > -1 ) {
state( new_state );
last_trigger = evt;
return 1;
}
}
return 0;
}
Machine & Machine::onSwitch( swcb_sym_t callback, const char sym_s[], const char sym_e[] )
{
callback_sym = callback;
sym_states = sym_s;
sym_events = sym_e;
return *this;
}
Machine & Machine::label( const char label[] )
{
inst_label = label;
return *this;
}
int8_t Machine::priority()
{
return prio;
}
Machine & Machine::priority( int8_t priority )
{
prio = priority;
return *this;
}
// .asleep() Returns true if the machine is in a sleeping state
uint8_t BaseMachine::asleep()
{
return ( flags & ATM_SLEEP_FLAG ) > 0;
}
BaseMachine & BaseMachine::sleep( uint8_t v )
{
flags |= ATM_SLEEP_FLAG;
flags = v ? flags | ATM_SLEEP_FLAG : flags & ~ATM_SLEEP_FLAG;
return *this;
}
Machine & Machine::begin( const state_t* tbl, int width )
{
state_table = tbl;
state_width = ATM_ON_EXIT + width + 2;
prio = ATM_DEFAULT_PRIO;
if ( !inst_label ) inst_label = class_label;
return *this;
}
Machine & Machine::msgQueue( atm_msg_t msg[], int width, uint8_t autoclear /* = 0 */ )
{
msg_table = msg;
msg_width = width;
flags = autoclear ? flags | ATM_MSGAC_FLAG : flags & ~ATM_MSGAC_FLAG;
return *this;
}
unsigned char Machine::pinChange( uint8_t pin ) {
unsigned char v = digitalRead( pin ) ? 1 : 0;
if ( (( pinstate >> pin ) & 1 ) != ( v == 1 ) ) {
pinstate ^= ( (uint32_t)1 << pin );
return 1;
}
return 0;
}
int Machine::msgRead( uint8_t id_msg, int cnt /* = 1 */, int clear /* = 0 */ )
{
if ( msg_table[id_msg] > 0 ) {
if ( cnt >= msg_table[id_msg] ) {
msg_table[id_msg] = 0;
} else {
msg_table[id_msg] -= cnt;
}
if ( clear ) {
for ( int i = 0; i < msg_width; i++ ) {
msg_table[i] = 0;
}
}
return 1;
}
return 0;
}
int Machine::msgPeek( uint8_t id_msg )
{
return msg_table[id_msg];
}
int Machine::msgClear( uint8_t id_msg ) // Destructive read (clears queue for this type)
{
flags &= ~ATM_SLEEP_FLAG;
if ( msg_table[id_msg] > 0 ) {
msg_table[id_msg] = 0;
return 1;
}
return 0;
}
Machine & Machine::msgClear()
{
flags &= ~ATM_SLEEP_FLAG;
for ( int i = 0; i < msg_width; i++ ) {
msg_table[i] = 0;
}
return *this;
}
Machine & Machine::msgWrite( uint8_t id_msg, int cnt /* = 1 */ )
{
flags &= ~ATM_SLEEP_FLAG;
msg_table[id_msg] += cnt;
return *this;
}
const char * Machine::map_symbol( int id, const char map[] )
{
int cnt = 0;
int i = 0;
if ( id == -1 ) return "*NONE*";
if ( id == 0 ) return map;
while ( 1 ) {
if ( map[i] == '\0' && ++cnt == id ) {
i++;
break;
}
i++;
}
return &map[i];
}
// .cycle() Executes one cycle of a state machine
Machine & Machine::cycle()
{
if ( ( flags & ATM_SLEEP_FLAG ) == 0 ) {
cycles++;
if ( next != -1 ) {
action( ATM_ON_SWITCH );
if ( callback_sym ) {
callback_sym( inst_label,
map_symbol( current, sym_states ),
map_symbol( next, sym_states ),
map_symbol( last_trigger, sym_events ), millis() - state_millis, cycles );
}
if ( current > -1 )
action( read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) );
previous = current;
current = next;
next = -1;
state_millis = millis();
state_micros = micros();
action( read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) );
if ( read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP ) {
flags |= ATM_SLEEP_FLAG;
} else {
flags &= ~ATM_SLEEP_FLAG;
}
cycles = 0;
}
state_t i = read_state( state_table + ( current * state_width ) + ATM_ON_LOOP );
if ( i != -1 ) { action( i ); }
for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) {
if ( ( read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) {
state( read_state( state_table + ( current * state_width ) + i ) );
last_trigger = i - ATM_ON_EXIT - 1;
return *this;
}
}
}
return *this;
}
// TINY MACHINE
TinyMachine & TinyMachine::state( tiny_state_t state )
{
next = state;
flags &= ~ATM_SLEEP_FLAG;
return *this;
}
tiny_state_t TinyMachine::state()
{
return current;
}
int TinyMachine::trigger( int evt )
{
if ( current == -1 ) cycle();
if ( current > -1 ) {
int new_state = tiny_read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 );
if ( new_state > -1 ) {
state( new_state );
return 1;
}
}
return 0;
}
TinyMachine & TinyMachine::begin( const tiny_state_t* tbl, int width )
{
state_table = tbl;
state_width = ATM_ON_EXIT + width + 2;
return *this;
}
// .cycle() Executes one cycle of a state machine
TinyMachine & TinyMachine::cycle()
{
if ( ( flags & ATM_SLEEP_FLAG ) == 0 ) {
if ( next != -1 ) {
action( ATM_ON_SWITCH );
if ( current > -1 )
action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) );
current = next;
next = -1;
state_millis = millis();
action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) );
if ( read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP ) {
flags |= ATM_SLEEP_FLAG;
} else {
flags &= ~ATM_SLEEP_FLAG;
}
}
tiny_state_t i = tiny_read_state( state_table + ( current * state_width ) + ATM_ON_LOOP );
if ( i != -1 ) { action( i ); }
for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) {
if ( ( tiny_read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) {
state( tiny_read_state( state_table + ( current * state_width ) + i ) );
return *this;
}
}
}
return *this;
}
// FACTORY
// .calibrate() Distributes the machines in the inventory to the appropriate priority queues
void Factory::calibrate( void )
{
// Reset all priority queues to empty lists
for ( int8_t i = 0; i < ATM_NO_OF_QUEUES; i++ )
priority_root[i] = 0;
// Walk the inventory list that contains all state machines in this factory
Machine * m = inventory_root;
while ( m ) {
// Prepend every machine to the appropriate priority queue
if ( m->prio < ATM_NO_OF_QUEUES ) {
m->priority_next = priority_root[m->prio];
priority_root[m->prio] = m;
}
m = m->inventory_next;
}
recalibrate = 0;
}
// .run( q ) Traverses an individual priority queue and cycles the machines in it once (except for queue 0)
void Factory::run( int q )
{
Machine * m = priority_root[ q ];
while ( m ) {
if ( q > 0 && ( m->flags & ATM_SLEEP_FLAG ) == 0 ) m->cycle();
// Request a recalibrate if the prio field doesn't match the current queue
if ( m->prio != q ) recalibrate = 1;
// Move to the next machine
m = m->priority_next;
}
}
// .add( machine ) Adds a state machine to the factory by prepending it to the inventory list
Factory & Factory::add( Machine & machine )
{
machine.inventory_next = inventory_root;
inventory_root = &machine;
machine.factory = this;
recalibrate = 1;
return *this;
}
// .find() Search the factory inventory for a machine by instance label
Machine * Factory::find( const char label[] )
{
Machine * m = inventory_root;
while ( m ) {
if ( strcmp( label, m->inst_label ) == 0 ) {
return m;
}
m = m->inventory_next;
}
return 0;
}
int Factory::msgSend( const char label[], int msg, int cnt /* = 1 */ )
{
int r = 0;
Machine * m = inventory_root;
while ( m ) {
if ( strcmp( label, m->inst_label ) == 0 ) {
m->msgWrite( msg, cnt );
r++;
}
m = m->inventory_next;
}
return r;
}
int Factory::msgSendClass( const char label[], int msg, int cnt /* = 1 */ )
{
int r = 0;
Machine * m = inventory_root;
while ( m ) {
if ( strcmp( label, m->class_label ) == 0 ) {
m->msgWrite( msg, cnt );
r++;
}
m = m->inventory_next;
}
return r;
}
// .cycle() executes one factory cycle (runs all priority queues a certain number of times)
Factory & Factory::cycle( void )
{
if ( recalibrate ) calibrate();
run( 1 ); run( 2 ); run( 1 ); run( 2 );
run( 1 ); run( 3 ); run( 1 ); run( 4 );
run( 1 ); run( 2 ); run( 1 ); run( 3 );
run( 1 ); run( 2 ); run( 1 ); run( 0 );
return *this;
}
<commit_msg>Removed redundant code in sleep()<commit_after>/*
Automaton.cpp - Library for creating and running Finite State Machines.
Published under the MIT License (MIT), Copyright (c) 2015, J.P. van der Landen
*/
#include "Automaton.h"
void atm_timer_millis::set( uint32_t v ) {
value = v;
}
void atm_timer_micros::set( uint32_t v ) {
value = v;
}
int atm_timer_millis::expired( BaseMachine * machine ) {
return value == ATM_TIMER_OFF ? 0 : millis() - machine->state_millis >= value;
}
int atm_timer_micros::expired( Machine * machine ) {
return value == ATM_TIMER_OFF ? 0 : micros() - machine->state_micros >= value;
}
void atm_counter::set( uint16_t v )
{
value = v;
}
uint16_t atm_counter::decrement( void )
{
return value > 0 && value != ATM_COUNTER_OFF ? --value : 0;
}
uint8_t atm_counter::expired()
{
return value == ATM_COUNTER_OFF ? 0 : ( value > 0 ? 0 : 1 );
}
Machine & Machine::state(state_t state)
{
next = state;
last_trigger = -1;
flags &= ~ATM_SLEEP_FLAG;
if ( ( flags & ATM_MSGAC_FLAG ) > 0 ) msgClear();
return *this;
}
state_t Machine::state()
{
return current;
}
int Machine::trigger( int evt )
{
if ( current == -1 ) cycle();
if ( current > -1 ) {
int new_state = read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 );
if ( new_state > -1 ) {
state( new_state );
last_trigger = evt;
return 1;
}
}
return 0;
}
Machine & Machine::onSwitch( swcb_sym_t callback, const char sym_s[], const char sym_e[] )
{
callback_sym = callback;
sym_states = sym_s;
sym_events = sym_e;
return *this;
}
Machine & Machine::label( const char label[] )
{
inst_label = label;
return *this;
}
int8_t Machine::priority()
{
return prio;
}
Machine & Machine::priority( int8_t priority )
{
prio = priority;
return *this;
}
// .asleep() Returns true if the machine is in a sleeping state
uint8_t BaseMachine::asleep()
{
return ( flags & ATM_SLEEP_FLAG ) > 0;
}
BaseMachine & BaseMachine::sleep( uint8_t v /* = 1 */ )
{
flags = v ? flags | ATM_SLEEP_FLAG : flags & ~ATM_SLEEP_FLAG;
return *this;
}
Machine & Machine::begin( const state_t* tbl, int width )
{
state_table = tbl;
state_width = ATM_ON_EXIT + width + 2;
prio = ATM_DEFAULT_PRIO;
if ( !inst_label ) inst_label = class_label;
return *this;
}
Machine & Machine::msgQueue( atm_msg_t msg[], int width, uint8_t autoclear /* = 0 */ )
{
msg_table = msg;
msg_width = width;
flags = autoclear ? flags | ATM_MSGAC_FLAG : flags & ~ATM_MSGAC_FLAG;
return *this;
}
unsigned char Machine::pinChange( uint8_t pin ) {
unsigned char v = digitalRead( pin ) ? 1 : 0;
if ( (( pinstate >> pin ) & 1 ) != ( v == 1 ) ) {
pinstate ^= ( (uint32_t)1 << pin );
return 1;
}
return 0;
}
int Machine::msgRead( uint8_t id_msg, int cnt /* = 1 */, int clear /* = 0 */ )
{
if ( msg_table[id_msg] > 0 ) {
if ( cnt >= msg_table[id_msg] ) {
msg_table[id_msg] = 0;
} else {
msg_table[id_msg] -= cnt;
}
if ( clear ) {
for ( int i = 0; i < msg_width; i++ ) {
msg_table[i] = 0;
}
}
return 1;
}
return 0;
}
int Machine::msgPeek( uint8_t id_msg )
{
return msg_table[id_msg];
}
int Machine::msgClear( uint8_t id_msg ) // Destructive read (clears queue for this type)
{
flags &= ~ATM_SLEEP_FLAG;
if ( msg_table[id_msg] > 0 ) {
msg_table[id_msg] = 0;
return 1;
}
return 0;
}
Machine & Machine::msgClear()
{
flags &= ~ATM_SLEEP_FLAG;
for ( int i = 0; i < msg_width; i++ ) {
msg_table[i] = 0;
}
return *this;
}
Machine & Machine::msgWrite( uint8_t id_msg, int cnt /* = 1 */ )
{
flags &= ~ATM_SLEEP_FLAG;
msg_table[id_msg] += cnt;
return *this;
}
const char * Machine::map_symbol( int id, const char map[] )
{
int cnt = 0;
int i = 0;
if ( id == -1 ) return "*NONE*";
if ( id == 0 ) return map;
while ( 1 ) {
if ( map[i] == '\0' && ++cnt == id ) {
i++;
break;
}
i++;
}
return &map[i];
}
// .cycle() Executes one cycle of a state machine
Machine & Machine::cycle()
{
if ( ( flags & ATM_SLEEP_FLAG ) == 0 ) {
cycles++;
if ( next != -1 ) {
action( ATM_ON_SWITCH );
if ( callback_sym ) {
callback_sym( inst_label,
map_symbol( current, sym_states ),
map_symbol( next, sym_states ),
map_symbol( last_trigger, sym_events ), millis() - state_millis, cycles );
}
if ( current > -1 )
action( read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) );
previous = current;
current = next;
next = -1;
state_millis = millis();
state_micros = micros();
action( read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) );
if ( read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP ) {
flags |= ATM_SLEEP_FLAG;
} else {
flags &= ~ATM_SLEEP_FLAG;
}
cycles = 0;
}
state_t i = read_state( state_table + ( current * state_width ) + ATM_ON_LOOP );
if ( i != -1 ) { action( i ); }
for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) {
if ( ( read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) {
state( read_state( state_table + ( current * state_width ) + i ) );
last_trigger = i - ATM_ON_EXIT - 1;
return *this;
}
}
}
return *this;
}
// TINY MACHINE
TinyMachine & TinyMachine::state( tiny_state_t state )
{
next = state;
flags &= ~ATM_SLEEP_FLAG;
return *this;
}
tiny_state_t TinyMachine::state()
{
return current;
}
int TinyMachine::trigger( int evt )
{
if ( current == -1 ) cycle();
if ( current > -1 ) {
int new_state = tiny_read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 );
if ( new_state > -1 ) {
state( new_state );
return 1;
}
}
return 0;
}
TinyMachine & TinyMachine::begin( const tiny_state_t* tbl, int width )
{
state_table = tbl;
state_width = ATM_ON_EXIT + width + 2;
return *this;
}
// .cycle() Executes one cycle of a state machine
TinyMachine & TinyMachine::cycle()
{
if ( ( flags & ATM_SLEEP_FLAG ) == 0 ) {
if ( next != -1 ) {
action( ATM_ON_SWITCH );
if ( current > -1 )
action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) );
current = next;
next = -1;
state_millis = millis();
action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) );
if ( read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP ) {
flags |= ATM_SLEEP_FLAG;
} else {
flags &= ~ATM_SLEEP_FLAG;
}
}
tiny_state_t i = tiny_read_state( state_table + ( current * state_width ) + ATM_ON_LOOP );
if ( i != -1 ) { action( i ); }
for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) {
if ( ( tiny_read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) {
state( tiny_read_state( state_table + ( current * state_width ) + i ) );
return *this;
}
}
}
return *this;
}
// FACTORY
// .calibrate() Distributes the machines in the inventory to the appropriate priority queues
void Factory::calibrate( void )
{
// Reset all priority queues to empty lists
for ( int8_t i = 0; i < ATM_NO_OF_QUEUES; i++ )
priority_root[i] = 0;
// Walk the inventory list that contains all state machines in this factory
Machine * m = inventory_root;
while ( m ) {
// Prepend every machine to the appropriate priority queue
if ( m->prio < ATM_NO_OF_QUEUES ) {
m->priority_next = priority_root[m->prio];
priority_root[m->prio] = m;
}
m = m->inventory_next;
}
recalibrate = 0;
}
// .run( q ) Traverses an individual priority queue and cycles the machines in it once (except for queue 0)
void Factory::run( int q )
{
Machine * m = priority_root[ q ];
while ( m ) {
if ( q > 0 && ( m->flags & ATM_SLEEP_FLAG ) == 0 ) m->cycle();
// Request a recalibrate if the prio field doesn't match the current queue
if ( m->prio != q ) recalibrate = 1;
// Move to the next machine
m = m->priority_next;
}
}
// .add( machine ) Adds a state machine to the factory by prepending it to the inventory list
Factory & Factory::add( Machine & machine )
{
machine.inventory_next = inventory_root;
inventory_root = &machine;
machine.factory = this;
recalibrate = 1;
return *this;
}
// .find() Search the factory inventory for a machine by instance label
Machine * Factory::find( const char label[] )
{
Machine * m = inventory_root;
while ( m ) {
if ( strcmp( label, m->inst_label ) == 0 ) {
return m;
}
m = m->inventory_next;
}
return 0;
}
int Factory::msgSend( const char label[], int msg, int cnt /* = 1 */ )
{
int r = 0;
Machine * m = inventory_root;
while ( m ) {
if ( strcmp( label, m->inst_label ) == 0 ) {
m->msgWrite( msg, cnt );
r++;
}
m = m->inventory_next;
}
return r;
}
int Factory::msgSendClass( const char label[], int msg, int cnt /* = 1 */ )
{
int r = 0;
Machine * m = inventory_root;
while ( m ) {
if ( strcmp( label, m->class_label ) == 0 ) {
m->msgWrite( msg, cnt );
r++;
}
m = m->inventory_next;
}
return r;
}
// .cycle() executes one factory cycle (runs all priority queues a certain number of times)
Factory & Factory::cycle( void )
{
if ( recalibrate ) calibrate();
run( 1 ); run( 2 ); run( 1 ); run( 2 );
run( 1 ); run( 3 ); run( 1 ); run( 4 );
run( 1 ); run( 2 ); run( 1 ); run( 3 );
run( 1 ); run( 2 ); run( 1 ); run( 0 );
return *this;
}
<|endoftext|> |
<commit_before>///
/// @file iterator.hpp
/// @brief The iterator class allows to easily iterate (forward and
/// backward) over prime numbers.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMESIEVE_ITERATOR_HPP
#define PRIMESIEVE_ITERATOR_HPP
#include <vector>
#include <cstddef>
namespace primesieve {
uint64_t get_max_stop();
/// Iterate over prime numbers.
/// primesieve::iterator allows to easily iterate over primes both
/// forwards and backwards. Note that generating the first prime uses
/// O(n^0.5 log log n^0.5) operations, after that any additional
/// prime is generated in amortized O(log n) operations. The memory
/// usage is about pi(sqrt(n)) * 16 bytes. primesieve::iterator
/// objects are very convenient to use at the cost of being slightly
/// slower than the callback_primes() functions.
///
class iterator
{
public:
/// Create a new iterator object.
/// @param start Start iterating at this number. If start is a
/// prime then first calling either next_prime()
/// or previous_prime() will return start.
/// @param stop_hint Stop number optimization hint, gives significant
/// speed up if few primes are generated. E.g. if
/// you want to generate the primes below 1000 use
/// stop_hint = 1000.
/// @pre start <= 2^64 - 2^32 * 10
///
iterator(uint64_t start = 0, uint64_t stop_hint = get_max_stop());
/// Reinitialize this iterator object to start.
/// @param start Start iterating at this number. If start is a
/// prime then first calling either next_prime()
/// or previous_prime() will return start.
/// @param stop_hint Stop number optimization hint, gives significant
/// speed up if few primes are generated. E.g. if
/// you want to generate the primes below 1000 use
/// stop_hint = 1000.
/// @pre start <= 2^64 - 2^32 * 10
///
void skipto(uint64_t start, uint64_t stop_hint = get_max_stop());
/// Free all memory, same as skipto(0).
void clear();
/// Advance the iterator by one position.
/// @return The next prime.
///
uint64_t next_prime()
{
if (i_++ == last_idx_)
generate_next_primes();
return primes_[i_];
}
/// Decrease the iterator by one position.
/// @return The previous prime.
///
uint64_t previous_prime()
{
if (i_-- == 0)
generate_previous_primes();
return primes_[i_];
}
private:
std::size_t i_;
std::size_t last_idx_;
std::vector<uint64_t> primes_;
uint64_t start_;
uint64_t stop_;
uint64_t stop_hint_;
uint64_t count_;
uint64_t get_interval_size(uint64_t);
void generate_primes(uint64_t, uint64_t);
void generate_next_primes();
void generate_previous_primes();
};
} // end namespace
#endif
<commit_msg>Update documentation<commit_after>///
/// @file iterator.hpp
/// @brief The iterator class allows to easily iterate (forward and
/// backward) over prime numbers.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMESIEVE_ITERATOR_HPP
#define PRIMESIEVE_ITERATOR_HPP
#include <vector>
#include <cstddef>
namespace primesieve {
uint64_t get_max_stop();
/// Iterate over prime numbers.
/// primesieve::iterator allows to easily iterate over primes both
/// forwards and backwards. Generating the first prime uses
/// O(n^0.5 log n^0.5) operations, after that any additional prime is
/// generated in amortized O(log n) operations. The memory usage is
/// about pi(n^0.5) * 16 bytes. primesieve::iterator objects are very
/// convenient to use at the cost of being slightly slower than the
/// callback_primes() functions.
///
class iterator
{
public:
/// Create a new iterator object.
/// @param start Start iterating at this number. If start is a
/// prime then first calling either next_prime()
/// or previous_prime() will return start.
/// @param stop_hint Stop number optimization hint, gives significant
/// speed up if few primes are generated. E.g. if
/// you want to generate the primes below 1000 use
/// stop_hint = 1000.
/// @pre start <= 2^64 - 2^32 * 10
///
iterator(uint64_t start = 0, uint64_t stop_hint = get_max_stop());
/// Reinitialize this iterator object to start.
/// @param start Start iterating at this number. If start is a
/// prime then first calling either next_prime()
/// or previous_prime() will return start.
/// @param stop_hint Stop number optimization hint, gives significant
/// speed up if few primes are generated. E.g. if
/// you want to generate the primes below 1000 use
/// stop_hint = 1000.
/// @pre start <= 2^64 - 2^32 * 10
///
void skipto(uint64_t start, uint64_t stop_hint = get_max_stop());
/// Free all memory, same as skipto(0).
void clear();
/// Advance the iterator by one position.
/// @return The next prime.
///
uint64_t next_prime()
{
if (i_++ == last_idx_)
generate_next_primes();
return primes_[i_];
}
/// Decrease the iterator by one position.
/// @return The previous prime.
///
uint64_t previous_prime()
{
if (i_-- == 0)
generate_previous_primes();
return primes_[i_];
}
private:
std::size_t i_;
std::size_t last_idx_;
std::vector<uint64_t> primes_;
uint64_t start_;
uint64_t stop_;
uint64_t stop_hint_;
uint64_t count_;
uint64_t get_interval_size(uint64_t);
void generate_primes(uint64_t, uint64_t);
void generate_next_primes();
void generate_previous_primes();
};
} // end namespace
#endif
<|endoftext|> |
<commit_before>//
// Copyright (C) 2013-2017 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "ribbonanalysis.h"
#include "ui_ribbonanalysis.h"
#include <QMenu>
#include <QDebug>
RibbonAnalysis::RibbonAnalysis(QWidget *parent) :
RibbonWidget(parent),
ui(new Ui::RibbonAnalysis)
{
ui->setupUi(this);
addRibbonButton(ui->Descriptives);
addRibbonButton(ui->ttestButton);
addRibbonButton(ui->anovaButton);
addRibbonButton(ui->frequenciesButton);
addRibbonButton(ui->regressionButton);
addRibbonButton(ui->BFFromT);
addRibbonButton(ui->factoranalysisButton);
ui->BFFromT->setDataSetNotNeeded();
// connect(ui->Descriptives, SIGNAL(clicked()), this, SLOT(itemSelected()));
QMenu *menu;
menu = new QMenu(this);
menu->addAction(QString("Descriptive Statistics"), this, SLOT(itemSelected()))->setObjectName("Descriptives");
menu->addAction(QString("Reliability Analysis"), this, SLOT(itemSelected()))->setObjectName("ReliabilityAnalysis");
ui->Descriptives->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestIndependentSamples");
menu->addAction(QString("Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestPairedSamples");
menu->addAction(QString("One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestOneSample");
menu->addSeparator();
menu->addAction(QString("Bayesian Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianIndependentSamples");
menu->addAction(QString("Bayesian Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianPairedSamples");
menu->addAction(QString("Bayesian One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianOneSample");
ui->ttestButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("ANOVA"), this, SLOT(itemSelected()))->setObjectName("Anova");
menu->addAction(QString("Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasures");
menu->addAction(QString("ANCOVA"), this, SLOT(itemSelected()))->setObjectName("Ancova");
menu->addSeparator();
menu->addAction(QString("Bayesian ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaBayesian");
menu->addAction(QString("Bayesian Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresBayesian");
menu->addAction(QString("Bayesian ANCOVA"), this, SLOT(itemSelected()))->setObjectName("AncovaBayesian");
ui->anovaButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("Correlation");
menu->addAction(QString("Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinear");
menu->addAction(QString("Logistic Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLogistic");
menu->addSeparator();
menu->addAction(QString("Bayesian Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesian");
menu->addAction(QString("Bayesian Correlation Pairs"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesianPairs");
menu->addAction(QString("Bayesian Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinearBayesian");
#ifdef QT_DEBUG
menu->addSeparator();
menu->addAction(QString("BAS Regression Linear link"), this, SLOT(itemSelected()))->setObjectName("BASRegressionLinearLink");
#endif
ui->regressionButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Binomial Test"), this, SLOT(itemSelected()))->setObjectName("BinomialTest");
menu->addAction(QString("Multinomial Test"), this, SLOT(itemSelected()))->setObjectName("MultinomialTest");
menu->addAction(QString("Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("ContingencyTables");
menu->addAction(QString("Log-Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLogLinear");
menu->addSeparator();
menu->addAction(QString("Bayesian Binomial Test"), this, SLOT(itemSelected()))->setObjectName("BinomialTestBayesian");
menu->addAction(QString("Bayesian Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("ContingencyTablesBayesian");
menu->addAction(QString("Bayesian Log-Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLogLinearBayesian");
ui->frequenciesButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Principal Component Analysis"), this, SLOT(itemSelected()))->setObjectName("PrincipalComponentAnalysis");
menu->addAction(QString("Exploratory Factor Analysis"), this, SLOT(itemSelected()))->setObjectName("ExploratoryFactorAnalysis");
ui->factoranalysisButton->setMenu(menu);
#ifndef QT_DEBUG
ui->BFFromT->hide();
#else
menu = new QMenu(this);
menu->addAction(QString("BF From t"), this, SLOT(itemSelected()))->setObjectName("BFFromT");
ui->BFFromT->setMenu(menu);
#endif
}
RibbonAnalysis::~RibbonAnalysis()
{
delete ui;
}
<commit_msg>Hide unfinished multinomial analysis from ribbon<commit_after>//
// Copyright (C) 2013-2017 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "ribbonanalysis.h"
#include "ui_ribbonanalysis.h"
#include <QMenu>
#include <QDebug>
RibbonAnalysis::RibbonAnalysis(QWidget *parent) :
RibbonWidget(parent),
ui(new Ui::RibbonAnalysis)
{
ui->setupUi(this);
addRibbonButton(ui->Descriptives);
addRibbonButton(ui->ttestButton);
addRibbonButton(ui->anovaButton);
addRibbonButton(ui->frequenciesButton);
addRibbonButton(ui->regressionButton);
addRibbonButton(ui->BFFromT);
addRibbonButton(ui->factoranalysisButton);
ui->BFFromT->setDataSetNotNeeded();
// connect(ui->Descriptives, SIGNAL(clicked()), this, SLOT(itemSelected()));
QMenu *menu;
menu = new QMenu(this);
menu->addAction(QString("Descriptive Statistics"), this, SLOT(itemSelected()))->setObjectName("Descriptives");
menu->addAction(QString("Reliability Analysis"), this, SLOT(itemSelected()))->setObjectName("ReliabilityAnalysis");
ui->Descriptives->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestIndependentSamples");
menu->addAction(QString("Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestPairedSamples");
menu->addAction(QString("One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestOneSample");
menu->addSeparator();
menu->addAction(QString("Bayesian Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianIndependentSamples");
menu->addAction(QString("Bayesian Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianPairedSamples");
menu->addAction(QString("Bayesian One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianOneSample");
ui->ttestButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("ANOVA"), this, SLOT(itemSelected()))->setObjectName("Anova");
menu->addAction(QString("Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasures");
menu->addAction(QString("ANCOVA"), this, SLOT(itemSelected()))->setObjectName("Ancova");
menu->addSeparator();
menu->addAction(QString("Bayesian ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaBayesian");
menu->addAction(QString("Bayesian Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresBayesian");
menu->addAction(QString("Bayesian ANCOVA"), this, SLOT(itemSelected()))->setObjectName("AncovaBayesian");
ui->anovaButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("Correlation");
menu->addAction(QString("Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinear");
menu->addAction(QString("Logistic Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLogistic");
menu->addSeparator();
menu->addAction(QString("Bayesian Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesian");
menu->addAction(QString("Bayesian Correlation Pairs"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesianPairs");
menu->addAction(QString("Bayesian Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinearBayesian");
#ifdef QT_DEBUG
menu->addSeparator();
menu->addAction(QString("BAS Regression Linear link"), this, SLOT(itemSelected()))->setObjectName("BASRegressionLinearLink");
#endif
ui->regressionButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Binomial Test"), this, SLOT(itemSelected()))->setObjectName("BinomialTest");
#ifdef QT_DEBUG
menu->addAction(QString("Multinomial Test"), this, SLOT(itemSelected()))->setObjectName("MultinomialTest");
#endif
menu->addAction(QString("Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("ContingencyTables");
menu->addAction(QString("Log-Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLogLinear");
menu->addSeparator();
menu->addAction(QString("Bayesian Binomial Test"), this, SLOT(itemSelected()))->setObjectName("BinomialTestBayesian");
menu->addAction(QString("Bayesian Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("ContingencyTablesBayesian");
menu->addAction(QString("Bayesian Log-Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLogLinearBayesian");
ui->frequenciesButton->setMenu(menu);
menu = new QMenu(this);
menu->addAction(QString("Principal Component Analysis"), this, SLOT(itemSelected()))->setObjectName("PrincipalComponentAnalysis");
menu->addAction(QString("Exploratory Factor Analysis"), this, SLOT(itemSelected()))->setObjectName("ExploratoryFactorAnalysis");
ui->factoranalysisButton->setMenu(menu);
#ifndef QT_DEBUG
ui->BFFromT->hide();
#else
menu = new QMenu(this);
menu->addAction(QString("BF From t"), this, SLOT(itemSelected()))->setObjectName("BFFromT");
ui->BFFromT->setMenu(menu);
#endif
}
RibbonAnalysis::~RibbonAnalysis()
{
delete ui;
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE ScopeReader
#define BOOST_TEST_LOG_LEVEL message
#include <cstddef>
#include <functional>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "../JPetManager/JPetManager.h"
#include "JPetScopeReaderFixtures.h"
#include "../JPetScopeReader/JPetScopeReader.h"
char* convertStringToCharP(const std::string& s)
{
char* pc = new char[s.size() + 1];
std::strcpy(pc, s.c_str());
return pc;
}
std::vector<char*> createArgs(const std::string& commandLine)
{
std::istringstream iss(commandLine);
std::vector<std::string> args {std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>{}
};
std::vector<char*> args_char;
std::transform(args.begin(), args.end(), std::back_inserter(args_char), convertStringToCharP);
return args_char;
}
BOOST_AUTO_TEST_SUITE (JPetScopeReaderTestSuite)
BOOST_AUTO_TEST_CASE (generate_root_file) {
auto commandLine = "main.exe -t scope -f unitTestData/JPetScopeReaderTest/test_file.json";
auto args_char = createArgs(commandLine);
auto argc = args_char.size();
auto argv = args_char.data();
JPetManager& manager = JPetManager::getManager();
manager.parseCmdLine(argc, argv);
manager.run();
BOOST_REQUIRE_MESSAGE(boost::filesystem::exists(gTest_root_filename), "File " << gTest_root_filename << " does not exist.");
}
BOOST_FIXTURE_TEST_CASE (signal_generation_test, signal_generation_fixture) {
check_header(
[] (int osc_file_size, int reco_signal_size) -> void {
BOOST_REQUIRE_EQUAL(osc_file_size, reco_signal_size);
}
);
check_data(
[] (float osc_file_time, float reco_signal_time, float osc_file_ampl, float reco_signal_ampl) -> void {
BOOST_CHECK_CLOSE_FRACTION(osc_file_time, reco_signal_time, 1.f / 131072.f);
BOOST_CHECK_CLOSE_FRACTION(osc_file_ampl, reco_signal_ampl, 1.f / 131072.f);
}
);
}
BOOST_FIXTURE_TEST_CASE (tref_correctness_test, tref_correctness_fixture) {
check_tref_simple(
[] (const void* tref_pointer) -> void {
BOOST_CHECK_PREDICATE(std::not_equal_to <size_t> (), ((size_t) tref_pointer)((size_t) nullptr));
}
);
//check_tref_simple(nullptr);
}
BOOST_AUTO_TEST_CASE (getFilePrefix)
{
JPetScopeReader reader(0);
BOOST_REQUIRE(reader.getFilePrefix("").empty());
BOOST_REQUIRE(reader.getFilePrefix("abkabd").empty());
BOOST_REQUIRE(reader.getFilePrefix("jfsd808").empty());
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c1_0554.txt"), "c1");
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c098_0554.txt"), "c098");
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("cq_"), "cq");
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("a_ss_q"), "a");
}
BOOST_AUTO_TEST_CASE (createInputScopeFileNames)
{
JPetScopeReader reader(0);
BOOST_REQUIRE(reader.createInputScopeFileNames("", {}).empty());
BOOST_REQUIRE(reader.createInputScopeFileNames("non_existing", {}).empty());
BOOST_REQUIRE(!reader.createInputScopeFileNames("unitTestData/JPetScopeReaderTest/scope_files/0", {{"c1",0}, {"c2",1}, {"c3", 2}, {"c4",3}}).empty());
std::map<int, std::vector<string>> expectedRes {
{0, {"C1_00003.txt","C1_00004.txt"}}, {1, {"C2_00003.txt","C2_00004.txt"}},
{2, {"C3_00003.txt","C3_00004.txt"}}, {3, {"C4_00003.txt","C4_00004.txt"}}
};
std::string pathToFiles = "unitTestData/JPetScopeReaderTest/scope_files/0";
std::for_each(expectedRes.begin(), expectedRes.end(),
[&](std::pair<const int, std::vector<std::string> >& el) {
for_each(el.second.begin(), el.second.end(),
[&](std::string& name) {
name = pathToFiles + "/" + name;
});
std::sort(el.second.begin(), el.second.end());
});
std::map<int, std::vector<std::string> > obtainedRes = reader.createInputScopeFileNames(pathToFiles, {{"C1",0}, {"C2",1}, {"C3", 2}, {"C4",3}});
/// to assure the same order of elements for comparison
std::for_each(obtainedRes.begin(), obtainedRes.end(),
[&](std::pair<const int, std::vector<std::string> >& el) {
std::sort(el.second.begin(), el.second.end());
});
BOOST_REQUIRE(!obtainedRes.empty());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[0].begin(), obtainedRes[0].end(), expectedRes[0].begin(), expectedRes[0].end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[1].begin(), obtainedRes[1].end(), expectedRes[1].begin(), expectedRes[1].end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[2].begin(), obtainedRes[2].end(), expectedRes[2].begin(), expectedRes[2].end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[3].begin(), obtainedRes[3].end(), expectedRes[3].begin(), expectedRes[3].end());
}
BOOST_AUTO_TEST_CASE (isCorrectScopeFileName)
{
JPetScopeReader reader(0);
BOOST_REQUIRE(!reader.isCorrectScopeFileName(""));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1_004.gif"));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1004.txt"));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("004.txt"));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("C5_abc.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("C1_023.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("C5_000.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
}
BOOST_AUTO_TEST_CASE (FullTest)
{
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove empty test and change the order of JPetScopeReaderTests<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE ScopeReader
#define BOOST_TEST_LOG_LEVEL message
#include <cstddef>
#include <functional>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "../JPetManager/JPetManager.h"
#include "JPetScopeReaderFixtures.h"
#include "../JPetScopeReader/JPetScopeReader.h"
char* convertStringToCharP(const std::string& s)
{
char* pc = new char[s.size() + 1];
std::strcpy(pc, s.c_str());
return pc;
}
std::vector<char*> createArgs(const std::string& commandLine)
{
std::istringstream iss(commandLine);
std::vector<std::string> args {std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>{}
};
std::vector<char*> args_char;
std::transform(args.begin(), args.end(), std::back_inserter(args_char), convertStringToCharP);
return args_char;
}
BOOST_AUTO_TEST_SUITE (JPetScopeReaderTestSuite)
BOOST_AUTO_TEST_CASE (getFilePrefix)
{
JPetScopeReader reader(0);
BOOST_REQUIRE(reader.getFilePrefix("").empty());
BOOST_REQUIRE(reader.getFilePrefix("abkabd").empty());
BOOST_REQUIRE(reader.getFilePrefix("jfsd808").empty());
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c1_0554.txt"), "c1");
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c098_0554.txt"), "c098");
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("cq_"), "cq");
BOOST_REQUIRE_EQUAL(reader.getFilePrefix("a_ss_q"), "a");
}
BOOST_AUTO_TEST_CASE (createInputScopeFileNames)
{
JPetScopeReader reader(0);
BOOST_REQUIRE(reader.createInputScopeFileNames("", {}).empty());
BOOST_REQUIRE(reader.createInputScopeFileNames("non_existing", {}).empty());
BOOST_REQUIRE(!reader.createInputScopeFileNames("unitTestData/JPetScopeReaderTest/scope_files/0", {{"c1",0}, {"c2",1}, {"c3", 2}, {"c4",3}}).empty());
std::map<int, std::vector<string>> expectedRes {
{0, {"C1_00003.txt","C1_00004.txt"}}, {1, {"C2_00003.txt","C2_00004.txt"}},
{2, {"C3_00003.txt","C3_00004.txt"}}, {3, {"C4_00003.txt","C4_00004.txt"}}
};
std::string pathToFiles = "unitTestData/JPetScopeReaderTest/scope_files/0";
std::for_each(expectedRes.begin(), expectedRes.end(),
[&](std::pair<const int, std::vector<std::string> >& el) {
for_each(el.second.begin(), el.second.end(),
[&](std::string& name) {
name = pathToFiles + "/" + name;
});
std::sort(el.second.begin(), el.second.end());
});
std::map<int, std::vector<std::string> > obtainedRes = reader.createInputScopeFileNames(pathToFiles, {{"C1",0}, {"C2",1}, {"C3", 2}, {"C4",3}});
/// to assure the same order of elements for comparison
std::for_each(obtainedRes.begin(), obtainedRes.end(),
[&](std::pair<const int, std::vector<std::string> >& el) {
std::sort(el.second.begin(), el.second.end());
});
BOOST_REQUIRE(!obtainedRes.empty());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[0].begin(), obtainedRes[0].end(), expectedRes[0].begin(), expectedRes[0].end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[1].begin(), obtainedRes[1].end(), expectedRes[1].begin(), expectedRes[1].end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[2].begin(), obtainedRes[2].end(), expectedRes[2].begin(), expectedRes[2].end());
BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[3].begin(), obtainedRes[3].end(), expectedRes[3].begin(), expectedRes[3].end());
}
BOOST_AUTO_TEST_CASE (isCorrectScopeFileName)
{
JPetScopeReader reader(0);
BOOST_REQUIRE(!reader.isCorrectScopeFileName(""));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1_004.gif"));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1004.txt"));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("004.txt"));
BOOST_REQUIRE(!reader.isCorrectScopeFileName("C5_abc.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("C1_023.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("C5_000.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
}
BOOST_AUTO_TEST_CASE (generate_root_file) {
auto commandLine = "main.exe -t scope -f unitTestData/JPetScopeReaderTest/test_file.json";
auto args_char = createArgs(commandLine);
auto argc = args_char.size();
auto argv = args_char.data();
JPetManager& manager = JPetManager::getManager();
manager.parseCmdLine(argc, argv);
manager.run();
BOOST_REQUIRE_MESSAGE(boost::filesystem::exists(gTest_root_filename), "File " << gTest_root_filename << " does not exist.");
}
BOOST_FIXTURE_TEST_CASE (signal_generation_test, signal_generation_fixture) {
check_header(
[] (int osc_file_size, int reco_signal_size) -> void {
BOOST_REQUIRE_EQUAL(osc_file_size, reco_signal_size);
}
);
check_data(
[] (float osc_file_time, float reco_signal_time, float osc_file_ampl, float reco_signal_ampl) -> void {
BOOST_CHECK_CLOSE_FRACTION(osc_file_time, reco_signal_time, 1.f / 131072.f);
BOOST_CHECK_CLOSE_FRACTION(osc_file_ampl, reco_signal_ampl, 1.f / 131072.f);
}
);
}
BOOST_FIXTURE_TEST_CASE (tref_correctness_test, tref_correctness_fixture) {
check_tref_simple(
[] (const void* tref_pointer) -> void {
BOOST_CHECK_PREDICATE(std::not_equal_to <size_t> (), ((size_t) tref_pointer)((size_t) nullptr));
}
);
//check_tref_simple(nullptr);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>//===- ReadConst.cpp - Code to constants and constant pools ---------------===//
//
// This file implements functionality to deserialize constants and entire
// constant pools.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//
#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include <algorithm>
#include <iostream>
using std::make_pair;
const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
const uchar *EndBuf) {
unsigned PrimType;
if (read_vbr(Buf, EndBuf, PrimType)) return failure<const Type*>(0);
const Type *Val = 0;
if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
return Val;
switch (PrimType) {
case Type::FunctionTyID: {
unsigned Typ;
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
const Type *RetType = getType(Typ);
if (RetType == 0) return failure(Val);
unsigned NumParams;
if (read_vbr(Buf, EndBuf, NumParams)) return failure(Val);
std::vector<const Type*> Params;
while (NumParams--) {
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
const Type *Ty = getType(Typ);
if (Ty == 0) return failure(Val);
Params.push_back(Ty);
}
bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
if (isVarArg) Params.pop_back();
return FunctionType::get(RetType, Params, isVarArg);
}
case Type::ArrayTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return failure(Val);
unsigned NumElements;
if (read_vbr(Buf, EndBuf, NumElements)) return failure(Val);
BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
<< NumElements << "\n");
return ArrayType::get(ElementType, NumElements);
}
case Type::StructTyID: {
unsigned Typ;
std::vector<const Type*> Elements;
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
while (Typ) { // List is terminated by void/0 typeid
const Type *Ty = getType(Typ);
if (Ty == 0) return failure(Val);
Elements.push_back(Ty);
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
}
return StructType::get(Elements);
}
case Type::PointerTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return failure(Val);
return PointerType::get(ElementType);
}
case Type::OpaqueTyID: {
return OpaqueType::get();
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize"
<< " primitive Type " << PrimType << "\n";
return failure(Val);
}
}
// refineAbstractType - The callback method is invoked when one of the
// elements of TypeValues becomes more concrete...
//
void BytecodeParser::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
if (OldType == NewType &&
OldType->isAbstract()) return; // Type is modified, but same
TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
MethodTypeValues.end(), OldType);
if (I == MethodTypeValues.end()) {
I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
assert(I != ModuleTypeValues.end() &&
"Can't refine a type I don't know about!");
}
if (OldType == NewType) {
assert(!OldType->isAbstract());
I->removeUserFromConcrete();
} else {
*I = NewType; // Update to point to new, more refined type.
}
}
// parseTypeConstants - We have to use this wierd code to handle recursive
// types. We know that recursive types will only reference the current slab of
// values in the type plane, but they can forward reference types before they
// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
// this ugly problem, we pesimistically insert an opaque type for each type we
// are about to read. This means that forward references will resolve to
// something and when we reread the type later, we can replace the opaque type
// with a new resolved concrete type.
//
void debug_type_tables();
bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
TypeValuesListTy &Tab,
unsigned NumEntries) {
assert(Tab.size() == 0 && "should not have read type constants in before!");
// Insert a bunch of opaque types to be resolved later...
for (unsigned i = 0; i < NumEntries; ++i)
Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));
// Loop through reading all of the types. Forward types will make use of the
// opaque types just inserted.
//
for (unsigned i = 0; i < NumEntries; ++i) {
const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
if (NewTy == 0) return failure(true);
BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
"' Replacing: " << OldTy << "\n");
// Don't insertValue the new type... instead we want to replace the opaque
// type with the new concrete value...
//
// Refine the abstract type to the new type. This causes all uses of the
// abstract type to use the newty. This also will cause the opaque type
// to be deleted...
//
((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
// This should have replace the old opaque type with the new type in the
// value table... or with a preexisting type that was already in the system
assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
}
BCR_TRACE(5, "Resulting types:\n");
for (unsigned i = 0; i < NumEntries; ++i) {
BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
}
debug_type_tables();
return false;
}
bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
const Type *Ty, Constant *&V) {
// We must check for a ConstantExpr before switching by type because
// a ConstantExpr can be of any type, and has no explicit value.
//
unsigned isExprNumArgs; // 0 if not expr; numArgs if is expr
if (read_vbr(Buf, EndBuf, isExprNumArgs)) return failure(true);
if (isExprNumArgs) {
unsigned opCode;
std::vector<Constant*> argVec;
argVec.reserve(isExprNumArgs);
if (read_vbr(Buf, EndBuf, opCode)) return failure(true);
// Read the slot number and types of each of the arguments
for (unsigned i=0; i < isExprNumArgs; ++i) {
unsigned argValSlot, argTypeSlot;
if (read_vbr(Buf, EndBuf, argValSlot)) return failure(true);
if (read_vbr(Buf, EndBuf, argTypeSlot)) return failure(true);
const Type *argTy = getType(argTypeSlot);
if (argTy == 0) return failure(true);
BCR_TRACE(4, "CE Arg " << i << ": Type: '" << argTy << "' slot: " << argValSlot << "\n");
// Get the arg value from its slot if it exists, otherwise a placeholder
Value *Val = getValue(argTy, argValSlot, false);
Constant *C;
if (Val) {
if (!(C = dyn_cast<Constant>(Val))) return failure(true);
BCR_TRACE(5, "Constant Found in ValueTable!\n");
} else { // Nope... find or create a forward ref. for it
C = fwdRefs.GetFwdRefToConstant(argTy, argValSlot);
}
argVec.push_back(C);
}
// Construct a ConstantExpr of the appropriate kind
if (isExprNumArgs == 1) { // All one-operand expressions
V = ConstantExpr::get(opCode, argVec[0], Ty);
} else if (opCode == Instruction::GetElementPtr) { // GetElementPtr
std::vector<Constant*> IdxList(argVec.begin()+1, argVec.end());
V = ConstantExpr::get(opCode, argVec[0], IdxList, Ty);
} else { // All other 2-operand expressions
V = ConstantExpr::get(opCode, argVec[0], argVec[1], Ty);
}
return false;
}
// Ok, not an ConstantExpr. We now know how to read the given type...
switch (Ty->getPrimitiveID()) {
case Type::BoolTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
if (Val != 0 && Val != 1) return failure(true);
V = ConstantBool::get(Val == 1);
break;
}
case Type::UByteTyID: // Unsigned integer types...
case Type::UShortTyID:
case Type::UIntTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
if (!ConstantUInt::isValueValidForType(Ty, Val)) return failure(true);
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::ULongTyID: {
uint64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::SByteTyID: // Unsigned integer types...
case Type::ShortTyID:
case Type::IntTyID: {
int Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
if (!ConstantSInt::isValueValidForType(Ty, Val)) return failure(true);
V = ConstantSInt::get(Ty, Val);
break;
}
case Type::LongTyID: {
int64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
V = ConstantSInt::get(Ty, Val);
break;
}
case Type::FloatTyID: {
float F;
if (input_data(Buf, EndBuf, &F, &F+1)) return failure(true);
V = ConstantFP::get(Ty, F);
break;
}
case Type::DoubleTyID: {
double Val;
if (input_data(Buf, EndBuf, &Val, &Val+1)) return failure(true);
V = ConstantFP::get(Ty, Val);
break;
}
case Type::TypeTyID:
assert(0 && "Type constants should be handled seperately!!!");
abort();
case Type::ArrayTyID: {
const ArrayType *AT = cast<const ArrayType>(Ty);
unsigned NumElements = AT->getNumElements();
std::vector<Constant*> Elements;
while (NumElements--) { // Read all of the elements of the constant.
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
Value *V = getValue(AT->getElementType(), Slot, false);
if (!V || !isa<Constant>(V)) return failure(true);
Elements.push_back(cast<Constant>(V));
}
V = ConstantArray::get(AT, Elements);
break;
}
case Type::StructTyID: {
const StructType *ST = cast<StructType>(Ty);
const StructType::ElementTypes &ET = ST->getElementTypes();
std::vector<Constant *> Elements;
for (unsigned i = 0; i < ET.size(); ++i) {
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
Value *V = getValue(ET[i], Slot, false);
if (!V || !isa<Constant>(V))
return failure(true);
Elements.push_back(cast<Constant>(V));
}
V = ConstantStruct::get(ST, Elements);
break;
}
case Type::PointerTyID: {
const PointerType *PT = cast<const PointerType>(Ty);
unsigned SubClass;
if (read_vbr(Buf, EndBuf, SubClass)) return failure(true);
switch (SubClass) {
case 0: // ConstantPointerNull value...
V = ConstantPointerNull::get(PT);
break;
case 1: { // ConstantPointerRef value...
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
// Check to see if we have already read this global variable yet...
Value *Val = getValue(PT, Slot, false);
GlobalValue* GV;
if (Val) {
if (!(GV = dyn_cast<GlobalValue>(Val))) return failure(true);
BCR_TRACE(5, "Value Found in ValueTable!\n");
} else { // Nope... find or create a forward ref. for it
GV = fwdRefs.GetFwdRefToGlobal(PT, Slot);
}
V = ConstantPointerRef::get(GV);
break;
}
default:
BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
return failure(true);
}
break;
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize constant value of type '"
<< Ty->getName() << "'\n";
return failure(true);
}
return false;
}
bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
ValueTable &Tab,
TypeValuesListTy &TypeTab) {
while (Buf < EndBuf) {
unsigned NumEntries, Typ;
if (read_vbr(Buf, EndBuf, NumEntries) ||
read_vbr(Buf, EndBuf, Typ)) return failure(true);
const Type *Ty = getType(Typ);
if (Ty == 0) return failure(true);
BCR_TRACE(3, "Type: '" << Ty << "' NumEntries: " << NumEntries << "\n");
if (Typ == Type::TypeTyID) {
if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
} else {
for (unsigned i = 0; i < NumEntries; ++i) {
Constant *I;
int Slot;
if (parseConstantValue(Buf, EndBuf, Ty, I)) return failure(true);
assert(I && "parseConstantValue returned `!failure' and NULL result");
BCR_TRACE(4, "Read Constant: '" << I << "'\n");
if ((Slot = insertValue(I, Tab)) < 0) return failure(true);
resolveRefsToConstant(I, (unsigned) Slot);
}
}
}
if (Buf > EndBuf) return failure(true);
return false;
}
<commit_msg>Break line to fit 80 columns<commit_after>//===- ReadConst.cpp - Code to constants and constant pools ---------------===//
//
// This file implements functionality to deserialize constants and entire
// constant pools.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//
#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include <algorithm>
#include <iostream>
using std::make_pair;
const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
const uchar *EndBuf) {
unsigned PrimType;
if (read_vbr(Buf, EndBuf, PrimType)) return failure<const Type*>(0);
const Type *Val = 0;
if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
return Val;
switch (PrimType) {
case Type::FunctionTyID: {
unsigned Typ;
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
const Type *RetType = getType(Typ);
if (RetType == 0) return failure(Val);
unsigned NumParams;
if (read_vbr(Buf, EndBuf, NumParams)) return failure(Val);
std::vector<const Type*> Params;
while (NumParams--) {
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
const Type *Ty = getType(Typ);
if (Ty == 0) return failure(Val);
Params.push_back(Ty);
}
bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
if (isVarArg) Params.pop_back();
return FunctionType::get(RetType, Params, isVarArg);
}
case Type::ArrayTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return failure(Val);
unsigned NumElements;
if (read_vbr(Buf, EndBuf, NumElements)) return failure(Val);
BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
<< NumElements << "\n");
return ArrayType::get(ElementType, NumElements);
}
case Type::StructTyID: {
unsigned Typ;
std::vector<const Type*> Elements;
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
while (Typ) { // List is terminated by void/0 typeid
const Type *Ty = getType(Typ);
if (Ty == 0) return failure(Val);
Elements.push_back(Ty);
if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
}
return StructType::get(Elements);
}
case Type::PointerTyID: {
unsigned ElTyp;
if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
const Type *ElementType = getType(ElTyp);
if (ElementType == 0) return failure(Val);
return PointerType::get(ElementType);
}
case Type::OpaqueTyID: {
return OpaqueType::get();
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize"
<< " primitive Type " << PrimType << "\n";
return failure(Val);
}
}
// refineAbstractType - The callback method is invoked when one of the
// elements of TypeValues becomes more concrete...
//
void BytecodeParser::refineAbstractType(const DerivedType *OldType,
const Type *NewType) {
if (OldType == NewType &&
OldType->isAbstract()) return; // Type is modified, but same
TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
MethodTypeValues.end(), OldType);
if (I == MethodTypeValues.end()) {
I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
assert(I != ModuleTypeValues.end() &&
"Can't refine a type I don't know about!");
}
if (OldType == NewType) {
assert(!OldType->isAbstract());
I->removeUserFromConcrete();
} else {
*I = NewType; // Update to point to new, more refined type.
}
}
// parseTypeConstants - We have to use this wierd code to handle recursive
// types. We know that recursive types will only reference the current slab of
// values in the type plane, but they can forward reference types before they
// have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
// be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
// this ugly problem, we pesimistically insert an opaque type for each type we
// are about to read. This means that forward references will resolve to
// something and when we reread the type later, we can replace the opaque type
// with a new resolved concrete type.
//
void debug_type_tables();
bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
TypeValuesListTy &Tab,
unsigned NumEntries) {
assert(Tab.size() == 0 && "should not have read type constants in before!");
// Insert a bunch of opaque types to be resolved later...
for (unsigned i = 0; i < NumEntries; ++i)
Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));
// Loop through reading all of the types. Forward types will make use of the
// opaque types just inserted.
//
for (unsigned i = 0; i < NumEntries; ++i) {
const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
if (NewTy == 0) return failure(true);
BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
"' Replacing: " << OldTy << "\n");
// Don't insertValue the new type... instead we want to replace the opaque
// type with the new concrete value...
//
// Refine the abstract type to the new type. This causes all uses of the
// abstract type to use the newty. This also will cause the opaque type
// to be deleted...
//
((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
// This should have replace the old opaque type with the new type in the
// value table... or with a preexisting type that was already in the system
assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
}
BCR_TRACE(5, "Resulting types:\n");
for (unsigned i = 0; i < NumEntries; ++i) {
BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
}
debug_type_tables();
return false;
}
bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
const Type *Ty, Constant *&V) {
// We must check for a ConstantExpr before switching by type because
// a ConstantExpr can be of any type, and has no explicit value.
//
unsigned isExprNumArgs; // 0 if not expr; numArgs if is expr
if (read_vbr(Buf, EndBuf, isExprNumArgs)) return failure(true);
if (isExprNumArgs) {
unsigned opCode;
std::vector<Constant*> argVec;
argVec.reserve(isExprNumArgs);
if (read_vbr(Buf, EndBuf, opCode)) return failure(true);
// Read the slot number and types of each of the arguments
for (unsigned i=0; i < isExprNumArgs; ++i) {
unsigned argValSlot, argTypeSlot;
if (read_vbr(Buf, EndBuf, argValSlot)) return failure(true);
if (read_vbr(Buf, EndBuf, argTypeSlot)) return failure(true);
const Type *argTy = getType(argTypeSlot);
if (argTy == 0) return failure(true);
BCR_TRACE(4, "CE Arg " << i << ": Type: '" << argTy << "' slot: "
<< argValSlot << "\n");
// Get the arg value from its slot if it exists, otherwise a placeholder
Value *Val = getValue(argTy, argValSlot, false);
Constant *C;
if (Val) {
if (!(C = dyn_cast<Constant>(Val))) return failure(true);
BCR_TRACE(5, "Constant Found in ValueTable!\n");
} else { // Nope... find or create a forward ref. for it
C = fwdRefs.GetFwdRefToConstant(argTy, argValSlot);
}
argVec.push_back(C);
}
// Construct a ConstantExpr of the appropriate kind
if (isExprNumArgs == 1) { // All one-operand expressions
V = ConstantExpr::get(opCode, argVec[0], Ty);
} else if (opCode == Instruction::GetElementPtr) { // GetElementPtr
std::vector<Constant*> IdxList(argVec.begin()+1, argVec.end());
V = ConstantExpr::get(opCode, argVec[0], IdxList, Ty);
} else { // All other 2-operand expressions
V = ConstantExpr::get(opCode, argVec[0], argVec[1], Ty);
}
return false;
}
// Ok, not an ConstantExpr. We now know how to read the given type...
switch (Ty->getPrimitiveID()) {
case Type::BoolTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
if (Val != 0 && Val != 1) return failure(true);
V = ConstantBool::get(Val == 1);
break;
}
case Type::UByteTyID: // Unsigned integer types...
case Type::UShortTyID:
case Type::UIntTyID: {
unsigned Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
if (!ConstantUInt::isValueValidForType(Ty, Val)) return failure(true);
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::ULongTyID: {
uint64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
V = ConstantUInt::get(Ty, Val);
break;
}
case Type::SByteTyID: // Unsigned integer types...
case Type::ShortTyID:
case Type::IntTyID: {
int Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
if (!ConstantSInt::isValueValidForType(Ty, Val)) return failure(true);
V = ConstantSInt::get(Ty, Val);
break;
}
case Type::LongTyID: {
int64_t Val;
if (read_vbr(Buf, EndBuf, Val)) return failure(true);
V = ConstantSInt::get(Ty, Val);
break;
}
case Type::FloatTyID: {
float F;
if (input_data(Buf, EndBuf, &F, &F+1)) return failure(true);
V = ConstantFP::get(Ty, F);
break;
}
case Type::DoubleTyID: {
double Val;
if (input_data(Buf, EndBuf, &Val, &Val+1)) return failure(true);
V = ConstantFP::get(Ty, Val);
break;
}
case Type::TypeTyID:
assert(0 && "Type constants should be handled seperately!!!");
abort();
case Type::ArrayTyID: {
const ArrayType *AT = cast<const ArrayType>(Ty);
unsigned NumElements = AT->getNumElements();
std::vector<Constant*> Elements;
while (NumElements--) { // Read all of the elements of the constant.
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
Value *V = getValue(AT->getElementType(), Slot, false);
if (!V || !isa<Constant>(V)) return failure(true);
Elements.push_back(cast<Constant>(V));
}
V = ConstantArray::get(AT, Elements);
break;
}
case Type::StructTyID: {
const StructType *ST = cast<StructType>(Ty);
const StructType::ElementTypes &ET = ST->getElementTypes();
std::vector<Constant *> Elements;
for (unsigned i = 0; i < ET.size(); ++i) {
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
Value *V = getValue(ET[i], Slot, false);
if (!V || !isa<Constant>(V))
return failure(true);
Elements.push_back(cast<Constant>(V));
}
V = ConstantStruct::get(ST, Elements);
break;
}
case Type::PointerTyID: {
const PointerType *PT = cast<const PointerType>(Ty);
unsigned SubClass;
if (read_vbr(Buf, EndBuf, SubClass)) return failure(true);
switch (SubClass) {
case 0: // ConstantPointerNull value...
V = ConstantPointerNull::get(PT);
break;
case 1: { // ConstantPointerRef value...
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
// Check to see if we have already read this global variable yet...
Value *Val = getValue(PT, Slot, false);
GlobalValue* GV;
if (Val) {
if (!(GV = dyn_cast<GlobalValue>(Val))) return failure(true);
BCR_TRACE(5, "Value Found in ValueTable!\n");
} else { // Nope... find or create a forward ref. for it
GV = fwdRefs.GetFwdRefToGlobal(PT, Slot);
}
V = ConstantPointerRef::get(GV);
break;
}
default:
BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
return failure(true);
}
break;
}
default:
std::cerr << __FILE__ << ":" << __LINE__
<< ": Don't know how to deserialize constant value of type '"
<< Ty->getName() << "'\n";
return failure(true);
}
return false;
}
bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
ValueTable &Tab,
TypeValuesListTy &TypeTab) {
while (Buf < EndBuf) {
unsigned NumEntries, Typ;
if (read_vbr(Buf, EndBuf, NumEntries) ||
read_vbr(Buf, EndBuf, Typ)) return failure(true);
const Type *Ty = getType(Typ);
if (Ty == 0) return failure(true);
BCR_TRACE(3, "Type: '" << Ty << "' NumEntries: " << NumEntries << "\n");
if (Typ == Type::TypeTyID) {
if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
} else {
for (unsigned i = 0; i < NumEntries; ++i) {
Constant *I;
int Slot;
if (parseConstantValue(Buf, EndBuf, Ty, I)) return failure(true);
assert(I && "parseConstantValue returned `!failure' and NULL result");
BCR_TRACE(4, "Read Constant: '" << I << "'\n");
if ((Slot = insertValue(I, Tab)) < 0) return failure(true);
resolveRefsToConstant(I, (unsigned) Slot);
}
}
}
if (Buf > EndBuf) return failure(true);
return false;
}
<|endoftext|> |
<commit_before>#include "jakmuse_common.h"
#include <cstdint>
#include <vector>
#include <cstdio>
static void wav_write_header(FILE* f, unsigned samplPerSec, unsigned numSamples)
{
struct wav_header_s {
uint32_t ckId;
uint32_t cksize;
uint32_t WAVEID;
uint32_t fmt_ckId;
uint32_t fmt_cksize;
uint16_t wFormatTag;
uint16_t nChannels;
uint32_t nSamplesPerSec;
uint32_t nAvgBytesPerSec;
uint16_t nBlockAlign;
uint16_t wBitsPerSample;
uint32_t data_ckId;
uint32_t data_cksize;
} header = {
'RIFF',
4 + 24 + (8 + 2 /*B per sample*/ * 1 /*N channels*/ * numSamples + 0),
'WAVE',
'fmt ',
16,
0x0001,
2,
samplPerSec,
samplPerSec * 2 * 1,
2 * 1,
16,
'data',
2 * 1 * numSamples,
};
fwrite(&header, sizeof(wav_header_s), 1, f);
}
static void wav_write_samples(FILE* f, std::vector<short> const& samples)
{
fwrite(samples.data(), sizeof(short), samples.size(), f);
}
bool wav_write_file(std::string const& filename, std::vector<short> const& samples, unsigned samples_per_second)
{
FILE* f = fopen(filename.c_str(), "wb");
if(!f) {
fprintf(stderr, "failed to open %s for writing\n", filename.c_str());
return false;
}
wav_write_header(f, samples_per_second, samples.size());
wav_write_samples(f, samples);
fclose(f);
return true;
}
<commit_msg>...only one channel<commit_after>#include "jakmuse_common.h"
#include <cstdint>
#include <vector>
#include <cstdio>
static void wav_write_header(FILE* f, unsigned samplPerSec, unsigned numSamples)
{
struct wav_header_s {
uint32_t ckId;
uint32_t cksize;
uint32_t WAVEID;
uint32_t fmt_ckId;
uint32_t fmt_cksize;
uint16_t wFormatTag;
uint16_t nChannels;
uint32_t nSamplesPerSec;
uint32_t nAvgBytesPerSec;
uint16_t nBlockAlign;
uint16_t wBitsPerSample;
uint32_t data_ckId;
uint32_t data_cksize;
} header = {
'RIFF',
4 + 24 + (8 + 2 /*B per sample*/ * 1 /*N channels*/ * numSamples + 0),
'WAVE',
'fmt ',
16,
0x0001,
1,
samplPerSec,
samplPerSec * 2 * 1,
2 * 1,
16,
'data',
2 * 1 * numSamples,
};
fwrite(&header, sizeof(wav_header_s), 1, f);
}
static void wav_write_samples(FILE* f, std::vector<short> const& samples)
{
fwrite(samples.data(), sizeof(short), samples.size(), f);
}
bool wav_write_file(std::string const& filename, std::vector<short> const& samples, unsigned samples_per_second)
{
FILE* f = fopen(filename.c_str(), "wb");
if(!f) {
fprintf(stderr, "failed to open %s for writing\n", filename.c_str());
return false;
}
wav_write_header(f, samples_per_second, samples.size());
wav_write_samples(f, samples);
fclose(f);
return true;
}
<|endoftext|> |
<commit_before>/** @file
*
* @ingroup modularLibrary
*
* @brief A Preset Object
*
* @details
*
* @authors Théo de la Hogue
*
* @copyright © 2010, Théo de la Hogue @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTPreset.h"
#define thisTTClass TTPreset
#define thisTTClassName "Preset"
#define thisTTClassTags "preset"
TT_MODULAR_CONSTRUCTOR,
mName(kTTSymEmpty),
mDescription("something about this preset"),
mAddress(kTTAdrsEmpty),
mDirectory(NULL),
mScript(NULL)
{
TT_ASSERT("Correct number of args to create TTPreset", arguments.size() == 0 || arguments.size() == 1);
addAttribute(Name, kTypeSymbol);
addAttribute(Description, kTypeSymbol);
addAttributeWithSetter(Address, kTypeSymbol);
addMessage(Clear);
addMessage(Store);
addMessage(Update);
addMessageWithArguments(Recall);
addMessageWithArguments(Output);
// needed to be handled by a TTXmlHandler
addMessageWithArguments(WriteAsXml);
addMessageProperty(WriteAsXml, hidden, YES);
addMessageWithArguments(ReadFromXml);
addMessageProperty(ReadFromXml, hidden, YES);
// needed to be handled by a TTTextHandler
addMessageWithArguments(WriteAsText);
addMessageProperty(WriteAsText, hidden, YES);
addMessageWithArguments(ReadFromText);
addMessageProperty(ReadFromText, hidden, YES);
TTObjectBaseInstantiate(kTTSym_Script, TTObjectBaseHandle(&mScript), arguments);
}
TTPreset::~TTPreset()
{
if (mScript) {
TTObjectBaseRelease(TTObjectBaseHandle(&mScript));
mScript = NULL;
}
}
TTErr TTPreset::setAddress(const TTValue& value)
{
Clear();
mAddress = value[0];
mDirectory = getDirectoryFrom(mAddress);
if (mDirectory) {
mScript->setAttributeValue(kTTSym_address, mAddress);
return kTTErrNone;
}
else
return kTTErrGeneric; // else wait for directory or not ?
}
TTErr TTPreset::Store()
{
TTNodePtr aNode;
TTObjectBasePtr anObject;
TTList aNodeList, allObjectNodes;
TTAddress aRelativeAddress;
TTValue v, parsedLine;
Clear();
if (mDirectory) {
// 1. Append a preset flag with the name
v = TTValue(TTSymbol("preset"));
v.append(mName);
mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);
// 2. Append a description flag with the description
v = TTValue(TTSymbol("description"));
v.append(mDescription);
mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);
// 3. Append a comment line at the beginning
v = TTValue(TTSymbol("###########################################"));
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
// 4. Append an empty comment line
v.clear();
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
// 5. Look for all Objects under the address into the directory
mDirectory->Lookup(mAddress, aNodeList, &aNode);
mDirectory->LookFor(&aNodeList, &TTPresetTestObject, NULL, allObjectNodes, &aNode);
// 6. Sort the NodeList using object priority order
allObjectNodes.sort(&compareNodePriorityThenNameThenInstance);
// 7. Append a script line for each object found
for (allObjectNodes.begin(); allObjectNodes.end(); allObjectNodes.next()) {
aNode = TTNodePtr((TTPtr)allObjectNodes.current()[0]);
// get relative address
aNode->getAddress(aRelativeAddress, mAddress);
// get object
anObject = aNode->getObject();
// append command line
if (anObject) {
// DATA case
if (anObject->getName() == kTTSym_Data) {
v.clear();
anObject->getAttributeValue(kTTSym_value, v);
if (v.empty())
continue;
v.prepend(aRelativeAddress);
mScript->sendMessage(TTSymbol("AppendCommand"), v, parsedLine);
}
}
}
// 8. Append an empty comment line
v.clear();
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
// 9. Append a comment line at the end
v = TTValue(TTSymbol("###########################################"));
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
return kTTErrNone;
}
else
return kTTErrGeneric;
}
TTErr TTPreset::Update()
{
TTValue v, none;
TTBoolean flattened;
// is the preset already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
mScript->sendMessage(kTTSym_Flatten, mAddress, none);
return processUpdate(mScript);
}
TTErr TTPreset::processUpdate(TTObjectBasePtr aScript)
{
TTListPtr lines;
TTDictionaryBasePtr aLine;
TTAddress anAddress;
TTNodePtr aNode;
TTObjectBasePtr anObject;
TTSymbol service;
TTValue v;
TTErr err;
aScript->getAttributeValue(TTSymbol("flattenedLines"), v);
lines = TTListPtr((TTPtr)v[0]);
// lookat each line of the script
for (lines->begin(); lines->end(); lines->next()) {
aLine = TTDictionaryBasePtr((TTPtr)lines->current()[0]);
// if it is a Data object
if (!aLine->lookup(kTTSym_target, v)) {
anAddress = v[0];
err = getDirectoryFrom(anAddress)->getTTNode(anAddress, &aNode);
if (!err) {
anObject = aNode->getObject();
if (anObject) {
if (anObject->getName() == kTTSym_Data) {
// get his service attribute value
anObject->getAttributeValue(kTTSym_service, v);
service = v[0];
// update only parameters
if (service == kTTSym_parameter) {
// get his current value
err = anObject->getAttributeValue(kTTSym_value, v);
if (!err) {
// replace the former value
aLine->remove(kTTSym_value);
aLine->append(kTTSym_value, v);
}
}
}
}
}
}
}
return kTTErrNone;
}
TTErr TTPreset::Clear()
{
return mScript->sendMessage(TTSymbol("Clear"));
}
TTErr TTPreset::Recall(const TTValue& inputValue, TTValue& outputValue)
{
TTAddress anAddress = kTTAdrsRoot;
TTBoolean flattened;
TTValue v, none;
if (inputValue.size() == 1)
if (inputValue[0].type() == kTypeSymbol)
anAddress = inputValue[0];
// is the cue already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
mScript->sendMessage(kTTSym_Flatten, mAddress, none);
// if an address is passed, run the line at address
if (anAddress != kTTAdrsRoot)
return mScript->sendMessage(TTSymbol("RunCommand"), inputValue, none);
// else run all the script
else
return mScript->sendMessage(kTTSym_Run, mAddress, none);
}
TTErr TTPreset::Output(const TTValue& inputValue, TTValue& outputValue)
{
TTAddress anAddress = kTTAdrsRoot;
TTBoolean flattened;
TTValue v, none;
if (inputValue.size() == 1)
if (inputValue[0].type() == kTypeSymbol)
anAddress = inputValue[0];
// is the preset already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
mScript->sendMessage(kTTSym_Flatten, kTTAdrsRoot, none);
// if an address is passed, dump the line at address
if (anAddress != kTTAdrsRoot)
return mScript->sendMessage(TTSymbol("DumpLine"), inputValue, none);
// else dump all the script
else
return mScript->sendMessage(kTTSym_Dump, inputValue, none);
}
TTErr TTPreset::WriteAsXml(const TTValue& inputValue, TTValue& outputValue)
{
TTXmlHandlerPtr aXmlHandler = NULL;
TTValue v;
aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);
// use WriteAsXml of the script
v = TTValue(mScript);
aXmlHandler->setAttributeValue(kTTSym_object, v);
aXmlHandler->sendMessage(TTSymbol("Write"));
return kTTErrNone;
}
TTErr TTPreset::ReadFromXml(const TTValue& inputValue, TTValue& outputValue)
{
TTXmlHandlerPtr aXmlHandler = NULL;
TTValue v, parsedLine;
aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);
// Preset node : append a preset flag with the name
if (aXmlHandler->mXmlNodeName == TTSymbol("preset")) {
if (!aXmlHandler->mXmlNodeStart)
return kTTErrNone;
v = TTValue(TTSymbol("preset"));
v.append(mName);
mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);
return kTTErrNone;
}
// use ReadFromXml of the script
v = TTValue(mScript);
aXmlHandler->setAttributeValue(kTTSym_object, v);
aXmlHandler->sendMessage(TTSymbol("Read"));
return kTTErrNone;
}
TTErr TTPreset::WriteAsText(const TTValue& inputValue, TTValue& outputValue)
{
TTTextHandlerPtr aTextHandler;
TTBoolean flattened;
TTValue v;
aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);
// théo - since the workshop in june 2014 in Albi we decide to force the script to be flattened
// but we should review all the #TTCue and #TTScript architecture to improve this
// so here we need to unflatten the script before to write it ...
// is the preset already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (flattened)
mScript->sendMessage("Unflatten");
// use WriteAsBuffer of the script
v = TTValue(mScript);
aTextHandler->setAttributeValue(kTTSym_object, v);
aTextHandler->sendMessage(TTSymbol("Write"));
return kTTErrNone;
}
TTErr TTPreset::ReadFromText(const TTValue& inputValue, TTValue& outputValue)
{
TTTextHandlerPtr aTextHandler;
TTDictionaryBasePtr line;
TTValue v;
aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);
// if it is the first line :
if (aTextHandler->mFirstLine)
Clear();
if (inputValue.size() == 0)
return kTTErrGeneric;
// if needed : parse the buffer line into TTDictionary
if ((*(aTextHandler->mLine))[0].type() != kTypePointer) {
line = TTScriptParseLine(*(aTextHandler->mLine));
if (line)
// replace the buffer line value by the parsed line dictionary
aTextHandler->mLine = new TTValue((TTPtr)line);
}
else
line = TTDictionaryBasePtr((TTPtr)aTextHandler->mLine[0]);
// match description or tag flag lines :
if (line->getSchema() == kTTSym_flag) {
line->lookup(kTTSym_name, v);
TTSymbol flagName = v[0];
if (flagName == TTSymbol("description")) {
// get description
if (!line->getValue(v)) {
mDescription = v[0];
}
}
}
// use ReadFromText of the script
v = TTValue(mScript);
aTextHandler->setAttributeValue(kTTSym_object, v);
aTextHandler->sendMessage(TTSymbol("Read"));
return kTTErrNone;
}
#if 0
#pragma mark -
#pragma mark Some Methods
#endif
TTBoolean TTPresetTestObject(TTNodePtr node, TTPtr args)
{
TTObjectBasePtr o;
TTValue v;
TTSymbol s;
// Here we decide to keep nodes which binds on :
// - Data with @service == parameter
o = node->getObject();
if (o) {
if (o->getName() == kTTSym_Data) {
o->getAttributeValue(kTTSym_service, v);
s = v[0];
return s == kTTSym_parameter;
}
}
return NO;
}
TTErr TTPresetInterpolate(TTPreset* preset1, TTPreset* preset2, TTFloat64 position)
{
TTBoolean flattened1, flattened2;
TTValue v, none;
// is the preset1 already flattened ?
preset1->mScript->getAttributeValue(kTTSym_flattened, v);
flattened1 = v[0];
if (!flattened1)
preset1->mScript->sendMessage(kTTSym_Flatten, preset1->mAddress, none);
// is the preset2 already flattened ?
preset2->mScript->getAttributeValue(kTTSym_flattened, v);
flattened2 = v[0];
if (!flattened2)
preset2->mScript->sendMessage(kTTSym_Flatten, preset2->mAddress, none);
return TTScriptInterpolate(preset1->mScript, preset2->mScript, position);
}
TTErr TTPresetMix(const TTValue& presets, const TTValue& factors)
{
TTPresetPtr aPreset;
TTValue scripts;
TTBoolean flattened;
TTValue v, none;
TTUInt32 i;
for (i = 0; i < presets.size(); i++) {
aPreset = TTPresetPtr((TTObjectBasePtr)presets[i]);
// is the preset1 already flattened ?
aPreset->mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
aPreset->mScript->sendMessage(kTTSym_Flatten, aPreset->mAddress, none);
scripts.append(aPreset->mScript);
}
return TTScriptMix(scripts, factors);
}
TTErr TTPresetCopy(TTPreset* aPresetToCopy, TTPreset* aPresetCopy)
{
TTValue v, args;
aPresetCopy->mName = aPresetToCopy->mName;
aPresetCopy->mAddress = aPresetToCopy->mAddress;
aPresetCopy->mDirectory = aPresetToCopy->mDirectory;
return TTScriptCopy(aPresetToCopy->mScript, aPresetCopy->mScript);
}
<commit_msg>Fixing JamomaMax #724 issue<commit_after>/** @file
*
* @ingroup modularLibrary
*
* @brief A Preset Object
*
* @details
*
* @authors Théo de la Hogue
*
* @copyright © 2010, Théo de la Hogue @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTPreset.h"
#define thisTTClass TTPreset
#define thisTTClassName "Preset"
#define thisTTClassTags "preset"
TT_MODULAR_CONSTRUCTOR,
mName(kTTSymEmpty),
mDescription("something about this preset"),
mAddress(kTTAdrsEmpty),
mDirectory(NULL),
mScript(NULL)
{
TT_ASSERT("Correct number of args to create TTPreset", arguments.size() == 0 || arguments.size() == 1);
addAttribute(Name, kTypeSymbol);
addAttribute(Description, kTypeSymbol);
addAttributeWithSetter(Address, kTypeSymbol);
addMessage(Clear);
addMessage(Store);
addMessage(Update);
addMessageWithArguments(Recall);
addMessageWithArguments(Output);
// needed to be handled by a TTXmlHandler
addMessageWithArguments(WriteAsXml);
addMessageProperty(WriteAsXml, hidden, YES);
addMessageWithArguments(ReadFromXml);
addMessageProperty(ReadFromXml, hidden, YES);
// needed to be handled by a TTTextHandler
addMessageWithArguments(WriteAsText);
addMessageProperty(WriteAsText, hidden, YES);
addMessageWithArguments(ReadFromText);
addMessageProperty(ReadFromText, hidden, YES);
TTObjectBaseInstantiate(kTTSym_Script, TTObjectBaseHandle(&mScript), arguments);
}
TTPreset::~TTPreset()
{
if (mScript) {
TTObjectBaseRelease(TTObjectBaseHandle(&mScript));
mScript = NULL;
}
}
TTErr TTPreset::setAddress(const TTValue& value)
{
Clear();
mAddress = value[0];
mDirectory = getDirectoryFrom(mAddress);
if (mDirectory) {
mScript->setAttributeValue(kTTSym_address, mAddress);
return kTTErrNone;
}
else
return kTTErrGeneric; // else wait for directory or not ?
}
TTErr TTPreset::Store()
{
TTNodePtr aNode;
TTObjectBasePtr anObject;
TTList aNodeList, allObjectNodes;
TTAddress aRelativeAddress;
TTValue v, parsedLine;
Clear();
if (mDirectory) {
// 1. Append a preset flag with the name
v = TTValue(TTSymbol("preset"));
v.append(mName);
mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);
// 2. Append a description flag with the description
v = TTValue(TTSymbol("description"));
v.append(mDescription);
mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);
// 3. Append a comment line at the beginning
v = TTValue(TTSymbol("###########################################"));
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
// 4. Append an empty comment line
v.clear();
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
// 5. Look for all Objects under the address into the directory
mDirectory->Lookup(mAddress, aNodeList, &aNode);
mDirectory->LookFor(&aNodeList, &TTPresetTestObject, NULL, allObjectNodes, &aNode);
// 6. Sort the NodeList using object priority order
allObjectNodes.sort(&compareNodePriorityThenNameThenInstance);
// 7. Append a script line for each object found
for (allObjectNodes.begin(); allObjectNodes.end(); allObjectNodes.next()) {
aNode = TTNodePtr((TTPtr)allObjectNodes.current()[0]);
// get relative address
aNode->getAddress(aRelativeAddress, mAddress);
// get object
anObject = aNode->getObject();
// append command line
if (anObject) {
// DATA case
if (anObject->getName() == kTTSym_Data) {
v.clear();
anObject->getAttributeValue(kTTSym_value, v);
if (v.empty())
continue;
v.prepend(aRelativeAddress);
mScript->sendMessage(TTSymbol("AppendCommand"), v, parsedLine);
}
}
}
// 8. Append an empty comment line
v.clear();
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
// 9. Append a comment line at the end
v = TTValue(TTSymbol("###########################################"));
mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);
return kTTErrNone;
}
else
return kTTErrGeneric;
}
TTErr TTPreset::Update()
{
TTValue v, none;
TTBoolean flattened;
// is the preset already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
mScript->sendMessage(kTTSym_Flatten, mAddress, none);
return processUpdate(mScript);
}
TTErr TTPreset::processUpdate(TTObjectBasePtr aScript)
{
TTListPtr lines;
TTDictionaryBasePtr aLine;
TTAddress anAddress;
TTNodePtr aNode;
TTObjectBasePtr anObject;
TTSymbol service;
TTValue v;
TTErr err;
aScript->getAttributeValue(TTSymbol("flattenedLines"), v);
lines = TTListPtr((TTPtr)v[0]);
// lookat each line of the script
for (lines->begin(); lines->end(); lines->next()) {
aLine = TTDictionaryBasePtr((TTPtr)lines->current()[0]);
// if it is a Data object
if (!aLine->lookup(kTTSym_target, v)) {
anAddress = v[0];
err = getDirectoryFrom(anAddress)->getTTNode(anAddress, &aNode);
if (!err) {
anObject = aNode->getObject();
if (anObject) {
if (anObject->getName() == kTTSym_Data) {
// get his service attribute value
anObject->getAttributeValue(kTTSym_service, v);
service = v[0];
// update only parameters
if (service == kTTSym_parameter) {
// get his current value
err = anObject->getAttributeValue(kTTSym_value, v);
if (!err) {
// replace the former value
aLine->remove(kTTSym_value);
aLine->append(kTTSym_value, v);
}
}
}
}
}
}
}
return kTTErrNone;
}
TTErr TTPreset::Clear()
{
return mScript->sendMessage(TTSymbol("Clear"));
}
TTErr TTPreset::Recall(const TTValue& inputValue, TTValue& outputValue)
{
TTAddress anAddress = kTTAdrsRoot;
TTBoolean flattened;
TTValue v, none;
if (inputValue.size() == 1)
if (inputValue[0].type() == kTypeSymbol)
anAddress = inputValue[0];
// is the cue already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
mScript->sendMessage(kTTSym_Flatten, mAddress, none);
// if an address is passed, run the line at address
if (anAddress != kTTAdrsRoot)
return mScript->sendMessage(TTSymbol("RunCommand"), inputValue, none);
// else run all the script
else
return mScript->sendMessage(kTTSym_Run, mAddress, none);
}
TTErr TTPreset::Output(const TTValue& inputValue, TTValue& outputValue)
{
TTAddress anAddress = kTTAdrsRoot;
TTBoolean flattened;
TTValue v, none;
if (inputValue.size() == 1)
if (inputValue[0].type() == kTypeSymbol)
anAddress = inputValue[0];
// is the preset already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
mScript->sendMessage(kTTSym_Flatten, kTTAdrsRoot, none);
// if an address is passed, dump the line at address
if (anAddress != kTTAdrsRoot)
return mScript->sendMessage(TTSymbol("DumpLine"), inputValue, none);
// else dump all the script
else
return mScript->sendMessage(kTTSym_Dump, inputValue, none);
}
TTErr TTPreset::WriteAsXml(const TTValue& inputValue, TTValue& outputValue)
{
TTXmlHandlerPtr aXmlHandler = NULL;
TTValue v;
aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);
// use WriteAsXml of the script
v = TTValue(mScript);
aXmlHandler->setAttributeValue(kTTSym_object, v);
aXmlHandler->sendMessage(TTSymbol("Write"));
return kTTErrNone;
}
TTErr TTPreset::ReadFromXml(const TTValue& inputValue, TTValue& outputValue)
{
TTXmlHandlerPtr aXmlHandler = NULL;
TTValue v, parsedLine;
aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);
// Preset node : append a preset flag with the name
if (aXmlHandler->mXmlNodeName == TTSymbol("preset")) {
if (!aXmlHandler->mXmlNodeStart)
return kTTErrNone;
v = TTValue(TTSymbol("preset"));
v.append(mName);
mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);
return kTTErrNone;
}
// use ReadFromXml of the script
v = TTValue(mScript);
aXmlHandler->setAttributeValue(kTTSym_object, v);
aXmlHandler->sendMessage(TTSymbol("Read"));
return kTTErrNone;
}
TTErr TTPreset::WriteAsText(const TTValue& inputValue, TTValue& outputValue)
{
TTTextHandlerPtr aTextHandler;
TTBoolean flattened;
TTValue v;
aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);
// théo - since the workshop in june 2014 in Albi we decide to force the script to be flattened
// but we should review all the #TTCue and #TTScript architecture to improve this
// so here we need to unflatten the script before to write it ...
// is the preset already flattened ?
mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (flattened)
mScript->sendMessage("Unflatten");
// use WriteAsBuffer of the script
v = TTValue(mScript);
aTextHandler->setAttributeValue(kTTSym_object, v);
aTextHandler->sendMessage(TTSymbol("Write"));
return kTTErrNone;
}
TTErr TTPreset::ReadFromText(const TTValue& inputValue, TTValue& outputValue)
{
TTTextHandlerPtr aTextHandler;
TTDictionaryBasePtr line;
TTValue v;
aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);
// if it is the first line :
if (aTextHandler->mFirstLine)
Clear();
if (inputValue.size() == 0)
return kTTErrGeneric;
// if needed : parse the buffer line into TTDictionary
if ((*(aTextHandler->mLine))[0].type() != kTypePointer) {
line = TTScriptParseLine(*(aTextHandler->mLine));
if (line)
// replace the buffer line value by the parsed line dictionary
aTextHandler->mLine = new TTValue((TTPtr)line);
}
else
line = TTDictionaryBasePtr((TTPtr)aTextHandler->mLine[0]);
// match description or tag flag lines :
if (line) {
if (line->getSchema() == kTTSym_flag) {
line->lookup(kTTSym_name, v);
TTSymbol flagName = v[0];
if (flagName == TTSymbol("description")) {
// get description
if (!line->getValue(v)) {
mDescription = v[0];
}
}
}
}
// use ReadFromText of the script
v = TTValue(mScript);
aTextHandler->setAttributeValue(kTTSym_object, v);
aTextHandler->sendMessage(TTSymbol("Read"));
return kTTErrNone;
}
#if 0
#pragma mark -
#pragma mark Some Methods
#endif
TTBoolean TTPresetTestObject(TTNodePtr node, TTPtr args)
{
TTObjectBasePtr o;
TTValue v;
TTSymbol s;
// Here we decide to keep nodes which binds on :
// - Data with @service == parameter
o = node->getObject();
if (o) {
if (o->getName() == kTTSym_Data) {
o->getAttributeValue(kTTSym_service, v);
s = v[0];
return s == kTTSym_parameter;
}
}
return NO;
}
TTErr TTPresetInterpolate(TTPreset* preset1, TTPreset* preset2, TTFloat64 position)
{
TTBoolean flattened1, flattened2;
TTValue v, none;
// is the preset1 already flattened ?
preset1->mScript->getAttributeValue(kTTSym_flattened, v);
flattened1 = v[0];
if (!flattened1)
preset1->mScript->sendMessage(kTTSym_Flatten, preset1->mAddress, none);
// is the preset2 already flattened ?
preset2->mScript->getAttributeValue(kTTSym_flattened, v);
flattened2 = v[0];
if (!flattened2)
preset2->mScript->sendMessage(kTTSym_Flatten, preset2->mAddress, none);
return TTScriptInterpolate(preset1->mScript, preset2->mScript, position);
}
TTErr TTPresetMix(const TTValue& presets, const TTValue& factors)
{
TTPresetPtr aPreset;
TTValue scripts;
TTBoolean flattened;
TTValue v, none;
TTUInt32 i;
for (i = 0; i < presets.size(); i++) {
aPreset = TTPresetPtr((TTObjectBasePtr)presets[i]);
// is the preset1 already flattened ?
aPreset->mScript->getAttributeValue(kTTSym_flattened, v);
flattened = v[0];
if (!flattened)
aPreset->mScript->sendMessage(kTTSym_Flatten, aPreset->mAddress, none);
scripts.append(aPreset->mScript);
}
return TTScriptMix(scripts, factors);
}
TTErr TTPresetCopy(TTPreset* aPresetToCopy, TTPreset* aPresetCopy)
{
TTValue v, args;
aPresetCopy->mName = aPresetToCopy->mName;
aPresetCopy->mAddress = aPresetToCopy->mAddress;
aPresetCopy->mDirectory = aPresetToCopy->mDirectory;
return TTScriptCopy(aPresetToCopy->mScript, aPresetCopy->mScript);
}
<|endoftext|> |
<commit_before>//===- ReaderWrappers.cpp - Parse bytecode from file or buffer -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements loading and parsing a bytecode file and parsing a
// bytecode module from a given buffer.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Analyzer.h"
#include "llvm/Bytecode/Reader.h"
#include "Reader.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/unistd.h"
#include <cerrno>
using namespace llvm;
//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//
namespace {
/// BytecodeFileReader - parses a bytecode file from a file
///
class BytecodeFileReader : public BytecodeReader {
private:
unsigned char *Buffer;
unsigned Length;
BytecodeFileReader(const BytecodeFileReader&); // Do not implement
void operator=(const BytecodeFileReader &BFR); // Do not implement
public:
BytecodeFileReader(const std::string &Filename, llvm::BytecodeHandler* H=0);
~BytecodeFileReader();
};
}
static std::string ErrnoMessage (int savedErrNum, std::string descr) {
return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
}
BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
llvm::BytecodeHandler* H )
: BytecodeReader(H)
{
Buffer = (unsigned char*)ReadFileIntoAddressSpace(Filename, Length);
if (Buffer == 0)
throw "Error reading file '" + Filename + "'.";
try {
// Parse the bytecode we mmapped in
ParseBytecode(Buffer, Length, Filename);
} catch (...) {
UnmapFileFromAddressSpace(Buffer, Length);
throw;
}
}
BytecodeFileReader::~BytecodeFileReader() {
// Unmmap the bytecode...
UnmapFileFromAddressSpace(Buffer, Length);
}
//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//
namespace {
/// BytecodeBufferReader - parses a bytecode file from a buffer
///
class BytecodeBufferReader : public BytecodeReader {
private:
const unsigned char *Buffer;
bool MustDelete;
BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
void operator=(const BytecodeBufferReader &BFR); // Do not implement
public:
BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
const std::string &ModuleID,
llvm::BytecodeHandler* Handler = 0);
~BytecodeBufferReader();
};
}
BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
unsigned Length,
const std::string &ModuleID,
llvm::BytecodeHandler* H )
: BytecodeReader(H)
{
// If not aligned, allocate a new buffer to hold the bytecode...
const unsigned char *ParseBegin = 0;
if (reinterpret_cast<uint64_t>(Buf) & 3) {
Buffer = new unsigned char[Length+4];
unsigned Offset = 4 - ((intptr_t)Buffer & 3); // Make sure it's aligned
ParseBegin = Buffer + Offset;
memcpy((unsigned char*)ParseBegin, Buf, Length); // Copy it over
MustDelete = true;
} else {
// If we don't need to copy it over, just use the caller's copy
ParseBegin = Buffer = Buf;
MustDelete = false;
}
try {
ParseBytecode(ParseBegin, Length, ModuleID);
} catch (...) {
if (MustDelete) delete [] Buffer;
throw;
}
}
BytecodeBufferReader::~BytecodeBufferReader() {
if (MustDelete) delete [] Buffer;
}
//===----------------------------------------------------------------------===//
// BytecodeStdinReader - Read bytecode from Standard Input
//
namespace {
/// BytecodeStdinReader - parses a bytecode file from stdin
///
class BytecodeStdinReader : public BytecodeReader {
private:
std::vector<unsigned char> FileData;
unsigned char *FileBuf;
BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
void operator=(const BytecodeStdinReader &BFR); // Do not implement
public:
BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
};
}
BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H )
: BytecodeReader(H)
{
int BlockSize;
unsigned char Buffer[4096*4];
// Read in all of the data from stdin, we cannot mmap stdin...
while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
if (BlockSize == -1)
throw ErrnoMessage(errno, "read from standard input");
FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
}
if (FileData.empty())
throw std::string("Standard Input empty!");
FileBuf = &FileData[0];
ParseBytecode(FileBuf, FileData.size(), "<stdin>");
}
//===----------------------------------------------------------------------===//
// Varargs transmogrification code...
//
// CheckVarargs - This is used to automatically translate old-style varargs to
// new style varargs for backwards compatibility.
static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
Module *M = MP->getModule();
// Check to see if va_start takes arguments...
Function *F = M->getNamedFunction("llvm.va_start");
if (F == 0) return MP; // No varargs use, just return.
if (F->getFunctionType()->getNumParams() == 0)
return MP; // Modern varargs processing, just return.
// If we get to this point, we know that we have an old-style module.
// Materialize the whole thing to perform the rewriting.
MP->materializeModule();
// If the user is making use of obsolete varargs intrinsics, adjust them for
// the user.
if (Function *F = M->getNamedFunction("llvm.va_start")) {
assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
const Type *RetTy = F->getFunctionType()->getParamType(0);
RetTy = cast<PointerType>(RetTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_end")) {
assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new LoadInst(CI->getOperand(1), "", CI);
new CallInst(NF, V, "", CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_copy")) {
assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
return MP;
}
//===----------------------------------------------------------------------===//
// Wrapper functions
//===----------------------------------------------------------------------===//
/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
unsigned Length,
const std::string &ModuleID,
BytecodeHandler* H ) {
return CheckVarargs(
new BytecodeBufferReader(Buffer, Length, ModuleID, H));
}
/// ParseBytecodeBuffer - Parse a given bytecode buffer
///
Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
const std::string &ModuleID,
std::string *ErrorStr){
try {
std::auto_ptr<ModuleProvider>
AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
/// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
///
ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
BytecodeHandler* H) {
if (Filename != std::string("-")) // Read from a file...
return CheckVarargs(new BytecodeFileReader(Filename,H));
else // Read from stdin
return CheckVarargs(new BytecodeStdinReader(H));
}
/// ParseBytecodeFile - Parse the given bytecode file
///
Module *llvm::ParseBytecodeFile(const std::string &Filename,
std::string *ErrorStr) {
try {
std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
// AnalyzeBytecodeFile - analyze one file
Module* llvm::AnalyzeBytecodeFile(
const std::string &Filename, ///< File to analyze
BytecodeAnalysis& bca, ///< Statistical output
std::string *ErrorStr, ///< Error output
std::ostream* output ///< Dump output
)
{
try {
BytecodeHandler* analyzerHandler = createBytecodeAnalyzerHandler(bca,output);
std::auto_ptr<ModuleProvider> AMP(
getBytecodeModuleProvider(Filename,analyzerHandler));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
// AnalyzeBytecodeBuffer - analyze a buffer
Module* llvm::AnalyzeBytecodeBuffer(
const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
unsigned Length, ///< Size of the bytecode buffer
const std::string& ModuleID, ///< Identifier for the module
BytecodeAnalysis& bca, ///< The results of the analysis
std::string* ErrorStr, ///< Errors, if any.
std::ostream* output ///< Dump output, if any
)
{
try {
BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
std::auto_ptr<ModuleProvider>
AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
bool llvm::GetBytecodeDependentLibraries(const std::string &fname,
std::vector<std::string>& deplibs) {
try {
std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
Module* M = AMP->releaseModule();
deplibs = M->getLibraries();
delete M;
return true;
} catch (...) {
deplibs.clear();
return false;
}
}
// vim: sw=2 ai
<commit_msg>Change interface to use correct typedef so it will always compile.<commit_after>//===- ReaderWrappers.cpp - Parse bytecode from file or buffer -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements loading and parsing a bytecode file and parsing a
// bytecode module from a given buffer.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Analyzer.h"
#include "llvm/Bytecode/Reader.h"
#include "Reader.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/unistd.h"
#include <cerrno>
using namespace llvm;
//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//
namespace {
/// BytecodeFileReader - parses a bytecode file from a file
///
class BytecodeFileReader : public BytecodeReader {
private:
unsigned char *Buffer;
unsigned Length;
BytecodeFileReader(const BytecodeFileReader&); // Do not implement
void operator=(const BytecodeFileReader &BFR); // Do not implement
public:
BytecodeFileReader(const std::string &Filename, llvm::BytecodeHandler* H=0);
~BytecodeFileReader();
};
}
static std::string ErrnoMessage (int savedErrNum, std::string descr) {
return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
}
BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
llvm::BytecodeHandler* H )
: BytecodeReader(H)
{
Buffer = (unsigned char*)ReadFileIntoAddressSpace(Filename, Length);
if (Buffer == 0)
throw "Error reading file '" + Filename + "'.";
try {
// Parse the bytecode we mmapped in
ParseBytecode(Buffer, Length, Filename);
} catch (...) {
UnmapFileFromAddressSpace(Buffer, Length);
throw;
}
}
BytecodeFileReader::~BytecodeFileReader() {
// Unmmap the bytecode...
UnmapFileFromAddressSpace(Buffer, Length);
}
//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//
namespace {
/// BytecodeBufferReader - parses a bytecode file from a buffer
///
class BytecodeBufferReader : public BytecodeReader {
private:
const unsigned char *Buffer;
bool MustDelete;
BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
void operator=(const BytecodeBufferReader &BFR); // Do not implement
public:
BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
const std::string &ModuleID,
llvm::BytecodeHandler* Handler = 0);
~BytecodeBufferReader();
};
}
BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
unsigned Length,
const std::string &ModuleID,
llvm::BytecodeHandler* H )
: BytecodeReader(H)
{
// If not aligned, allocate a new buffer to hold the bytecode...
const unsigned char *ParseBegin = 0;
if (reinterpret_cast<uint64_t>(Buf) & 3) {
Buffer = new unsigned char[Length+4];
unsigned Offset = 4 - ((intptr_t)Buffer & 3); // Make sure it's aligned
ParseBegin = Buffer + Offset;
memcpy((unsigned char*)ParseBegin, Buf, Length); // Copy it over
MustDelete = true;
} else {
// If we don't need to copy it over, just use the caller's copy
ParseBegin = Buffer = Buf;
MustDelete = false;
}
try {
ParseBytecode(ParseBegin, Length, ModuleID);
} catch (...) {
if (MustDelete) delete [] Buffer;
throw;
}
}
BytecodeBufferReader::~BytecodeBufferReader() {
if (MustDelete) delete [] Buffer;
}
//===----------------------------------------------------------------------===//
// BytecodeStdinReader - Read bytecode from Standard Input
//
namespace {
/// BytecodeStdinReader - parses a bytecode file from stdin
///
class BytecodeStdinReader : public BytecodeReader {
private:
std::vector<unsigned char> FileData;
unsigned char *FileBuf;
BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
void operator=(const BytecodeStdinReader &BFR); // Do not implement
public:
BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
};
}
BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H )
: BytecodeReader(H)
{
int BlockSize;
unsigned char Buffer[4096*4];
// Read in all of the data from stdin, we cannot mmap stdin...
while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
if (BlockSize == -1)
throw ErrnoMessage(errno, "read from standard input");
FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
}
if (FileData.empty())
throw std::string("Standard Input empty!");
FileBuf = &FileData[0];
ParseBytecode(FileBuf, FileData.size(), "<stdin>");
}
//===----------------------------------------------------------------------===//
// Varargs transmogrification code...
//
// CheckVarargs - This is used to automatically translate old-style varargs to
// new style varargs for backwards compatibility.
static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
Module *M = MP->getModule();
// Check to see if va_start takes arguments...
Function *F = M->getNamedFunction("llvm.va_start");
if (F == 0) return MP; // No varargs use, just return.
if (F->getFunctionType()->getNumParams() == 0)
return MP; // Modern varargs processing, just return.
// If we get to this point, we know that we have an old-style module.
// Materialize the whole thing to perform the rewriting.
MP->materializeModule();
// If the user is making use of obsolete varargs intrinsics, adjust them for
// the user.
if (Function *F = M->getNamedFunction("llvm.va_start")) {
assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
const Type *RetTy = F->getFunctionType()->getParamType(0);
RetTy = cast<PointerType>(RetTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_end")) {
assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new LoadInst(CI->getOperand(1), "", CI);
new CallInst(NF, V, "", CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_copy")) {
assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
return MP;
}
//===----------------------------------------------------------------------===//
// Wrapper functions
//===----------------------------------------------------------------------===//
/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
unsigned Length,
const std::string &ModuleID,
BytecodeHandler* H ) {
return CheckVarargs(
new BytecodeBufferReader(Buffer, Length, ModuleID, H));
}
/// ParseBytecodeBuffer - Parse a given bytecode buffer
///
Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
const std::string &ModuleID,
std::string *ErrorStr){
try {
std::auto_ptr<ModuleProvider>
AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
/// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
///
ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
BytecodeHandler* H) {
if (Filename != std::string("-")) // Read from a file...
return CheckVarargs(new BytecodeFileReader(Filename,H));
else // Read from stdin
return CheckVarargs(new BytecodeStdinReader(H));
}
/// ParseBytecodeFile - Parse the given bytecode file
///
Module *llvm::ParseBytecodeFile(const std::string &Filename,
std::string *ErrorStr) {
try {
std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
// AnalyzeBytecodeFile - analyze one file
Module* llvm::AnalyzeBytecodeFile(
const std::string &Filename, ///< File to analyze
BytecodeAnalysis& bca, ///< Statistical output
std::string *ErrorStr, ///< Error output
std::ostream* output ///< Dump output
)
{
try {
BytecodeHandler* analyzerHandler = createBytecodeAnalyzerHandler(bca,output);
std::auto_ptr<ModuleProvider> AMP(
getBytecodeModuleProvider(Filename,analyzerHandler));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
// AnalyzeBytecodeBuffer - analyze a buffer
Module* llvm::AnalyzeBytecodeBuffer(
const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
unsigned Length, ///< Size of the bytecode buffer
const std::string& ModuleID, ///< Identifier for the module
BytecodeAnalysis& bca, ///< The results of the analysis
std::string* ErrorStr, ///< Errors, if any.
std::ostream* output ///< Dump output, if any
)
{
try {
BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
std::auto_ptr<ModuleProvider>
AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
bool llvm::GetBytecodeDependentLibraries(const std::string &fname,
Module::LibraryListType& deplibs) {
try {
std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
Module* M = AMP->releaseModule();
deplibs = M->getLibraries();
delete M;
return true;
} catch (...) {
deplibs.clear();
return false;
}
}
// vim: sw=2 ai
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: udlnitem.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-05-10 14:33: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
*
************************************************************************/
#ifndef _SVX_UDLNITEM_HXX
#define _SVX_UDLNITEM_HXX
// include ---------------------------------------------------------------
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _VCL_VCLENUM_HXX
#include <vcl/vclenum.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
class SvXMLUnitConverter;
namespace rtl
{
class OUString;
}
// class SvxUnderlineItem ------------------------------------------------
/* [Beschreibung]
Dieses Item beschreibt, ob und wie unterstrichen ist.
*/
class SVX_DLLPUBLIC SvxUnderlineItem : public SfxEnumItem
{
Color mColor;
public:
TYPEINFO();
SvxUnderlineItem( const FontUnderline eSt /*= UNDERLINE_NONE*/,
const USHORT nId );
// "pure virtual Methoden" vom SfxPoolItem
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText, const IntlWrapper * = 0 ) const;
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT) const;
virtual SvStream& Store(SvStream &, USHORT nItemVersion) const;
virtual String GetValueTextByPos( USHORT nPos ) const;
virtual USHORT GetValueCount() const;
virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal,
BYTE nMemberId = 0 ) const;
virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal,
BYTE nMemberId = 0 );
// MS VC4.0 kommt durcheinander
void SetValue( USHORT nNewVal )
{SfxEnumItem::SetValue(nNewVal); }
virtual int HasBoolValue() const;
virtual BOOL GetBoolValue() const;
virtual void SetBoolValue( BOOL bVal );
virtual int operator==( const SfxPoolItem& ) const;
inline SvxUnderlineItem& operator=(const SvxUnderlineItem& rUnderline)
{
SetValue( rUnderline.GetValue() );
SetColor( rUnderline.GetColor() );
return *this;
}
// enum cast
FontUnderline GetUnderline() const
{ return (FontUnderline)GetValue(); }
void SetUnderline ( FontUnderline eNew )
{ SetValue((USHORT) eNew); }
const Color& GetColor() const { return mColor; }
void SetColor( const Color& rCol ) { mColor = rCol; }
};
#endif // #ifndef _SVX_UDLNITEM_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.446); FILE MERGED 2008/04/01 15:49:41 thb 1.3.446.3: #i85898# Stripping all external header guards 2008/04/01 12:47:01 thb 1.3.446.2: #i85898# Stripping all external header guards 2008/03/31 14:18:21 rt 1.3.446.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: udlnitem.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVX_UDLNITEM_HXX
#define _SVX_UDLNITEM_HXX
// include ---------------------------------------------------------------
#include <svtools/eitem.hxx>
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#include <vcl/vclenum.hxx>
#include <tools/color.hxx>
#include "svx/svxdllapi.h"
class SvXMLUnitConverter;
namespace rtl
{
class OUString;
}
// class SvxUnderlineItem ------------------------------------------------
/* [Beschreibung]
Dieses Item beschreibt, ob und wie unterstrichen ist.
*/
class SVX_DLLPUBLIC SvxUnderlineItem : public SfxEnumItem
{
Color mColor;
public:
TYPEINFO();
SvxUnderlineItem( const FontUnderline eSt /*= UNDERLINE_NONE*/,
const USHORT nId );
// "pure virtual Methoden" vom SfxPoolItem
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText, const IntlWrapper * = 0 ) const;
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT) const;
virtual SvStream& Store(SvStream &, USHORT nItemVersion) const;
virtual String GetValueTextByPos( USHORT nPos ) const;
virtual USHORT GetValueCount() const;
virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal,
BYTE nMemberId = 0 ) const;
virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal,
BYTE nMemberId = 0 );
// MS VC4.0 kommt durcheinander
void SetValue( USHORT nNewVal )
{SfxEnumItem::SetValue(nNewVal); }
virtual int HasBoolValue() const;
virtual BOOL GetBoolValue() const;
virtual void SetBoolValue( BOOL bVal );
virtual int operator==( const SfxPoolItem& ) const;
inline SvxUnderlineItem& operator=(const SvxUnderlineItem& rUnderline)
{
SetValue( rUnderline.GetValue() );
SetColor( rUnderline.GetColor() );
return *this;
}
// enum cast
FontUnderline GetUnderline() const
{ return (FontUnderline)GetValue(); }
void SetUnderline ( FontUnderline eNew )
{ SetValue((USHORT) eNew); }
const Color& GetColor() const { return mColor; }
void SetColor( const Color& rCol ) { mColor = rCol; }
};
#endif // #ifndef _SVX_UDLNITEM_HXX
<|endoftext|> |
<commit_before>// Battery Arduino library
//
// Copyright (c) 2013,2014 Dave Sieh
// See LICENSE.txt for details.
#include <Arduino.h>
#include "Battery.h"
#include "LEDBlinker.h"
#include "Move.h"
#include "pspc_support.h"
Battery::Battery(int monitorPin, int chargerPin, LEDBlinker *ledBlinker) {
pin = monitorPin;
chargePin = chargerPin;
led = ledBlinker;
}
void Battery::begin() {
if (led) {
led->begin();
}
}
void Battery::check(Move *mover) {
int mv = batteryMv(); // Get battery level in millivolts
Serial.print(P("mv = "));
Serial.print(mv);
if (chargePin >= 0 && digitalRead(chargePin) == HIGH) {
// Got here if charger detect is enabled and charger is plugged in
while (digitalRead(chargePin) == HIGH) {
// While charger is plugged in
if (mover) {
mover->stop();
}
mv = batteryMv();
Serial.print(P(", charger detected, voltage = "));
int percent = map(mv, batteryCritical, batteryFull, 50, 100);
percent = constrain(percent, 0, 100);
Serial.println(percent);
led->flash(percent);
}
} else {
if (mv < batteryCritical) {
Serial.println(P("Critical"));
if (mover) {
// Shut down the robot
mover->stop();
}
while (1) {
led->flashCritical();
// Check if the charger is plugged in
if (chargePin >= 0 && digitalRead(chargePin) == HIGH) {
return; // Exit if charging
}
delay(5000); // Wait 5 seconds
}
} else if (mv < batteryWarning) {
int percent = map(mv, batteryCritical, batteryWarning, 10, 50);
led->flash(percent);
}
}
delay(1000);
Serial.println();
}
int Battery::batteryMv() {
#if defined(__AVR_ATmega32U4__) // Is this a Leonardo board?
const long INTERNAL_REFERENCE_MV = 2560; // Leo reference is 2.56 volts
#else
const long INTERNAL_REFERENCE_MV = 1100; // ATmega328 is 1.1 volts
#endif
const float R1 = 18.0; // Voltage divider values
const float R2 = 2.2;
const float DIVISOR = R2 / (R1 + R2);
analogReference(INTERNAL); // Set reference to internal (1.1V)
analogRead(pin); // Allow the ADC to settle
delay(10);
int value = 0;
for (int i=0; i < 8; i++) {
value = value + analogRead(pin);
}
value = value / 8; // Get the average of 8 readings
int mv = map(value, 0, 1023, 0, INTERNAL_REFERENCE_MV / DIVISOR);
analogReference(DEFAULT); // Set the reference back to default (Vcc)
analogRead(pin); // Just to let the ADC settle ready for next reading
delay(10); // Allow reference to stabilise
return mv;
}
<commit_msg>Pre-compiled out debug output.<commit_after>// Battery Arduino library
//
// Copyright (c) 2013,2014 Dave Sieh
// See LICENSE.txt for details.
#include <Arduino.h>
#include "Battery.h"
#include "LEDBlinker.h"
#include "Move.h"
#include "pspc_support.h"
Battery::Battery(int monitorPin, int chargerPin, LEDBlinker *ledBlinker) {
pin = monitorPin;
chargePin = chargerPin;
led = ledBlinker;
}
void Battery::begin() {
if (led) {
led->begin();
}
}
void Battery::check(Move *mover) {
int mv = batteryMv(); // Get battery level in millivolts
#ifdef BATTERY_DEBUG
Serial.print(P("mv = "));
Serial.print(mv);
#endif
if (chargePin >= 0 && digitalRead(chargePin) == HIGH) {
// Got here if charger detect is enabled and charger is plugged in
while (digitalRead(chargePin) == HIGH) {
// While charger is plugged in
if (mover) {
mover->stop();
}
mv = batteryMv();
#ifdef BATTERY_DEBUG
Serial.print(P(", charger detected, voltage = "));
#endif
int percent = map(mv, batteryCritical, batteryFull, 50, 100);
percent = constrain(percent, 0, 100);
#ifdef BATTERY_DEBUG
Serial.println(percent);
#endif
led->flash(percent);
}
} else {
if (mv < batteryCritical) {
#ifdef BATTERY_DEBUG
Serial.println(P("Critical"));
#endif
if (mover) {
// Shut down the robot
mover->stop();
}
while (1) {
led->flashCritical();
// Check if the charger is plugged in
if (chargePin >= 0 && digitalRead(chargePin) == HIGH) {
return; // Exit if charging
}
delay(5000); // Wait 5 seconds
}
} else if (mv < batteryWarning) {
int percent = map(mv, batteryCritical, batteryWarning, 10, 50);
led->flash(percent);
}
}
delay(1000);
#ifdef BATTERY_DEBUG
Serial.println();
#endif
}
int Battery::batteryMv() {
#if defined(__AVR_ATmega32U4__) // Is this a Leonardo board?
const long INTERNAL_REFERENCE_MV = 2560; // Leo reference is 2.56 volts
#else
const long INTERNAL_REFERENCE_MV = 1100; // ATmega328 is 1.1 volts
#endif
const float R1 = 18.0; // Voltage divider values
const float R2 = 2.2;
const float DIVISOR = R2 / (R1 + R2);
analogReference(INTERNAL); // Set reference to internal (1.1V)
analogRead(pin); // Allow the ADC to settle
delay(10);
int value = 0;
for (int i=0; i < 8; i++) {
value = value + analogRead(pin);
}
value = value / 8; // Get the average of 8 readings
int mv = map(value, 0, 1023, 0, INTERNAL_REFERENCE_MV / DIVISOR);
analogReference(DEFAULT); // Set the reference back to default (Vcc)
analogRead(pin); // Just to let the ADC settle ready for next reading
delay(10); // Allow reference to stabilise
return mv;
}
<|endoftext|> |
<commit_before><commit_msg>✨ Wasteful (but needed) .is() implementation<commit_after><|endoftext|> |
<commit_before>#include "position.h"
#include <cstring>
#include <cstdlib>
#include <stdexcept>
namespace {
Piece translate_fen_piece(char c) {
Color color = std::isupper(c) ? WHITE : BLACK;
c = std::tolower(c);
PieceKind piece;
switch (c) {
case 'p': piece = PAWN; break;
case 'n': piece = KNIGHT; break;
case 'b': piece = BISHOP; break;
case 'r': piece = ROOK; break;
case 'q': piece = QUEEN; break;
case 'k': piece = KING; break;
default: throw std::runtime_error{"Invalid piece"};
}
return Piece{color, piece};
}
} // ~anonymous namespace
Position::Position() noexcept
: moves(1u)
, halfmoves(0u)
, wtm(1u)
, epsq(Position::ENPASSANT_NONE)
, castle(Position::CASTLE_NONE)
{
memset(bbrd, 0, sizeof(bbrd));
memset(side, 0, sizeof(side));
memset(ksqs, 0, sizeof(ksqs));
memset(sq2p, EMPTY_SQUARE, sizeof(sq2p));
}
Position Position::from_fen(std::string_view fen) {
Position position;
auto it = fen.begin();
const auto last = fen.end();
auto expect = [last](std::string_view::iterator it, char c) {
if (it == last || *it != c) {
std::string msg = "Expected '";
msg += c;
msg += "', received '";
if (it == last) {
msg += "<eof>";
} else {
msg += *it;
}
msg += "'";
throw std::runtime_error(msg.c_str());
}
++it;
return it;
};
for (int rank = 7; rank >= 0; --rank) {
for (int file = 0; file < 8; ++file) {
if (it == last) {
throw std::runtime_error("Board specification too short");
}
char c = *it++;
if (c >= '1' && c <= '8') {
file += c - '0' - 1;
if (file >= 8) {
throw std::runtime_error("Invalid board specification");
}
} else {
Piece piece = translate_fen_piece(c);
Square sq{static_cast<u8>(file), static_cast<u8>(rank)};
position.sq2p[sq.value()] = piece.value();
position.side[piece.color()] |= sq.mask();
if (piece.kind() == KING) {
position.ksqs[piece.color()] = sq.value();
} else {
position.bbrd[piece.value()] |= sq.mask();
}
}
}
if (it < last && *it == '/') {
++it;
}
}
it = expect(it, ' ');
// Active Color
if (it == last) {
throw std::runtime_error("Expected color specification");
}
switch (*it++) {
case 'W':
case 'w':
position._set_white_to_move(true);
break;
case 'B':
case 'b':
position._set_white_to_move(false);
break;
default:
throw std::runtime_error("Invalid character in color specification");
}
it = expect(it, ' ');
// Castling Availability
if (it == last) {
throw std::runtime_error("Expected castling availability specification");
} else if (*it == '-') {
position._set_castle_flags(Position::CASTLE_NONE);
++it;
} else {
u8 flags = 0;
while (it < last && *it != ' ') {
char c = *it++;
switch (c) {
case 'K':
flags |= Position::CASTLE_WHITE_KING_SIDE;
break;
case 'k':
flags |= Position::CASTLE_BLACK_KING_SIDE;
break;
case 'Q':
flags |= Position::CASTLE_WHITE_QUEEN_SIDE;
break;
case 'q':
flags |= Position::CASTLE_BLACK_QUEEN_SIDE;
break;
default:
throw std::runtime_error("Invalid character in castling specification");
}
}
position._set_castle_flags(flags);
}
it = expect(it, ' ');
// En passant Target Square
if (it == last) {
throw std::runtime_error("Expected en passant target square");
} else if (*it == '-') {
position._set_enpassant_square(Position::ENPASSANT_NONE);
++it;
} else {
char c = *it++;
if (!(c >= 'a' && c <= 'h')) {
throw std::runtime_error("Invalid file for enpassant target square");
}
u8 file = c - 'a';
u8 rank = *it++ - '1';
assert(file >= 0 && file <= 7);
assert(rank >= 0 && rank <= 7);
Square square{file, rank};
if (rank == RANK_3) {
assert(square.value() >= A3 && square.value() <= H3);
position._set_enpassant_square(square.value() - A3);
} else if (rank == RANK_6) {
assert(square.value() >= A6 && square.value() <= H6);
position._set_enpassant_square(square.value() - A6);
} else {
throw std::runtime_error("Invalid rank for enpassant target square");
}
}
// may or may not have halfmove and move specifications
bool has_halfmove = it != last && *it++ == ' ';
if (has_halfmove && it != last) {
// Halfmove spec (50-move rule)
while (it != last && *it != ' ') {
if (*it < '0' && *it > '9') {
throw std::runtime_error("Invalid halfmove specification");
}
position.halfmoves *= 10;
position.halfmoves += *it - '0';
++it;
}
// assuming that if halfmove is there then move spec is also there
it = expect(it, ' ');
position.moves = 0;
while (it != last && *it != ' ') {
if (*it < '0' && *it > '9') {
throw std::runtime_error("Invalid move specification");
}
position.moves *= 10;
position.moves += *it - '0';
++it;
}
}
return position;
}
void make_move(Savepos& sp, Move move) {
}
void undo_move(const Savepos& sp, Move move) {
}
<commit_msg>Begin move generation<commit_after>#include "position.h"
#include <cstring>
#include <cstdlib>
#include <stdexcept>
namespace {
Piece translate_fen_piece(char c) {
Color color = std::isupper(c) ? WHITE : BLACK;
c = std::tolower(c);
PieceKind piece;
switch (c) {
case 'p': piece = PAWN; break;
case 'n': piece = KNIGHT; break;
case 'b': piece = BISHOP; break;
case 'r': piece = ROOK; break;
case 'q': piece = QUEEN; break;
case 'k': piece = KING; break;
default: throw std::runtime_error{"Invalid piece"};
}
return Piece{color, piece};
}
} // ~anonymous namespace
Position::Position() noexcept
: moves(1u)
, halfmoves(0u)
, wtm(1u)
, epsq(Position::ENPASSANT_NONE)
, castle(Position::CASTLE_NONE)
{
memset(bbrd, 0, sizeof(bbrd));
memset(side, 0, sizeof(side));
memset(ksqs, 0, sizeof(ksqs));
memset(sq2p, EMPTY_SQUARE, sizeof(sq2p));
}
Position Position::from_fen(std::string_view fen) {
Position position;
auto it = fen.begin();
const auto last = fen.end();
auto expect = [last](std::string_view::iterator it, char c) {
if (it == last || *it != c) {
std::string msg = "Expected '";
msg += c;
msg += "', received '";
if (it == last) {
msg += "<eof>";
} else {
msg += *it;
}
msg += "'";
throw std::runtime_error(msg.c_str());
}
++it;
return it;
};
for (int rank = 7; rank >= 0; --rank) {
for (int file = 0; file < 8; ++file) {
if (it == last) {
throw std::runtime_error("Board specification too short");
}
char c = *it++;
if (c >= '1' && c <= '8') {
file += c - '0' - 1;
if (file >= 8) {
throw std::runtime_error("Invalid board specification");
}
} else {
Piece piece = translate_fen_piece(c);
Square sq{static_cast<u8>(file), static_cast<u8>(rank)};
position.sq2p[sq.value()] = piece.value();
position.side[piece.color()] |= sq.mask();
if (piece.kind() == KING) {
position.ksqs[piece.color()] = sq.value();
} else {
position.bbrd[piece.value()] |= sq.mask();
}
}
}
if (it < last && *it == '/') {
++it;
}
}
it = expect(it, ' ');
// Active Color
if (it == last) {
throw std::runtime_error("Expected color specification");
}
switch (*it++) {
case 'W':
case 'w':
position._set_white_to_move(true);
break;
case 'B':
case 'b':
position._set_white_to_move(false);
break;
default:
throw std::runtime_error("Invalid character in color specification");
}
it = expect(it, ' ');
// Castling Availability
if (it == last) {
throw std::runtime_error("Expected castling availability specification");
} else if (*it == '-') {
position._set_castle_flags(Position::CASTLE_NONE);
++it;
} else {
u8 flags = 0;
while (it < last && *it != ' ') {
char c = *it++;
switch (c) {
case 'K':
flags |= Position::CASTLE_WHITE_KING_SIDE;
break;
case 'k':
flags |= Position::CASTLE_BLACK_KING_SIDE;
break;
case 'Q':
flags |= Position::CASTLE_WHITE_QUEEN_SIDE;
break;
case 'q':
flags |= Position::CASTLE_BLACK_QUEEN_SIDE;
break;
default:
throw std::runtime_error("Invalid character in castling specification");
}
}
position._set_castle_flags(flags);
}
it = expect(it, ' ');
// En passant Target Square
if (it == last) {
throw std::runtime_error("Expected en passant target square");
} else if (*it == '-') {
position._set_enpassant_square(Position::ENPASSANT_NONE);
++it;
} else {
char c = *it++;
if (!(c >= 'a' && c <= 'h')) {
throw std::runtime_error("Invalid file for enpassant target square");
}
u8 file = c - 'a';
u8 rank = *it++ - '1';
assert(file >= 0 && file <= 7);
assert(rank >= 0 && rank <= 7);
Square square{file, rank};
if (rank == RANK_3) {
assert(square.value() >= A3 && square.value() <= H3);
position._set_enpassant_square(square.value() - A3);
} else if (rank == RANK_6) {
assert(square.value() >= A6 && square.value() <= H6);
position._set_enpassant_square(square.value() - A6);
} else {
throw std::runtime_error("Invalid rank for enpassant target square");
}
}
// may or may not have halfmove and move specifications
bool has_halfmove = it != last && *it++ == ' ';
if (has_halfmove && it != last) {
// Halfmove spec (50-move rule)
while (it != last && *it != ' ') {
if (*it < '0' && *it > '9') {
throw std::runtime_error("Invalid halfmove specification");
}
position.halfmoves *= 10;
position.halfmoves += *it - '0';
++it;
}
// assuming that if halfmove is there then move spec is also there
it = expect(it, ' ');
position.moves = 0;
while (it != last && *it != ' ') {
if (*it < '0' && *it > '9') {
throw std::runtime_error("Invalid move specification");
}
position.moves *= 10;
position.moves += *it - '0';
++it;
}
}
return position;
}
void Position::make_move(Savepos& sp, Move move) {
}
void Position::undo_move(const Savepos& sp, Move move) {
}
<|endoftext|> |
<commit_before>// Each task is represented by a front-end given back to the user, which can be
// used to access the result of the computation. This file defines this front
// end.
//
// The only thing the user has access is to the type of result provided by the
// computing unit used to create the task, as it identifies which time it can be
// converted.
//
// The usual method to access the result is just to cast the task, like:
// Task<int> t = ...;
// int bar = ...;
// int foo = t + bar;
//
// This automatically coerces the task to its type. If the result hasn't been
// computed yet (maybe because the task manager hasn't run), it is computed
// locally at the time of coercion.
//
// The operator() is provided and behaves like coercing, but some functions,
// like printf, will give error because they don't explicit allows type
// conversion.
#ifndef __TASK_DISTRIBUTION__TASK_HPP__
#define __TASK_DISTRIBUTION__TASK_HPP__
#include "key.hpp"
namespace TaskDistribution {
class TaskManager;
template <class T>
class Task {
public:
Task(): task_manager_(nullptr) { }
Task(Task<T> const& other) {
task_key_ = other.task_key_;
task_manager_ = other.task_manager_;
}
Task<T> const& operator=(Task<T> const& other) {
task_key_ = other.task_key_;
task_manager_ = other.task_manager_;
return *this;
}
// Can't use operator== as it may force type coercion
bool is_same_task(Task<T> const& other) const {
return task_key_ == other.task_key_ &&
task_manager_ == other.task_manager_;
}
template <class Other>
bool is_same_task(Task<Other> const& other) const {
return false;
}
operator T() const;
T operator()() const {
return (T)*this;
}
private:
friend class TaskManager;
Task(Key task_key, TaskManager* task_manager):
task_key_(task_key),
task_manager_(task_manager) { }
Key task_key_;
TaskManager* task_manager_;
};
};
#include "task_impl.hpp"
#endif
<commit_msg>Added documentation to task.hpp.<commit_after>// Each task is represented by a front-end given back to the user, which can be
// used to access the result of the computation. This file defines this front
// end.
//
// The only thing the user has access is to the type of result provided by the
// computing unit used to create the task, as it identifies which time it can be
// converted.
//
// The usual method to access the result is just to cast the task, like:
// Task<int> t = ...;
// int bar = ...;
// int foo = t + bar;
//
// This automatically coerces the task to its type. If the result hasn't been
// computed yet (maybe because the task manager hasn't run), it is computed
// locally at the time of coercion.
//
// The operator() is provided and behaves like coercing, but some functions,
// like printf, will give error because they don't implicitly perform type
// conversion.
#ifndef __TASK_DISTRIBUTION__TASK_HPP__
#define __TASK_DISTRIBUTION__TASK_HPP__
#include "key.hpp"
namespace TaskDistribution {
class TaskManager;
template <class T>
class Task {
public:
Task(): task_manager_(nullptr) { }
Task(Task<T> const& other) {
task_key_ = other.task_key_;
task_manager_ = other.task_manager_;
}
Task<T> const& operator=(Task<T> const& other) {
task_key_ = other.task_key_;
task_manager_ = other.task_manager_;
return *this;
}
// Can't use operator== as it may force type coercion
bool is_same_task(Task<T> const& other) const {
return task_key_ == other.task_key_ &&
task_manager_ == other.task_manager_;
}
template <class Other>
bool is_same_task(Task<Other> const& other) const {
return false;
}
operator T() const;
T operator()() const {
return (T)*this;
}
private:
friend class TaskManager;
Task(Key task_key, TaskManager* task_manager):
task_key_(task_key),
task_manager_(task_manager) { }
Key task_key_;
TaskManager* task_manager_;
};
};
#include "task_impl.hpp"
#endif
<|endoftext|> |
<commit_before>// Copyright (C) 2016 xaizek <xaizek@openmailbox.org>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#include "printing.hpp"
#include <cstddef>
#include <iomanip>
#include <ostream>
#include <string>
#include <unordered_map>
#include <utility>
#include "decoration.hpp"
namespace {
const std::unordered_map<std::string, decor::Decoration> highlightGroups = {
{ "linesbad", decor::bold + decor::red_fg },
{ "linesok", decor::bold + decor::black_fg },
{ "linesgood", decor::bold + decor::green_fg },
{ "lineschanged", decor::yellow_fg },
{ "covbad", decor::bold + decor::red_fg },
{ "covok", decor::bold + decor::black_fg },
{ "covgood", decor::bold + decor::green_fg },
{ "lineno", decor::white_bg + decor::black_fg },
{ "missed", decor::red_fg + decor::inv + decor::bold },
{ "covered", decor::green_fg + decor::inv + decor::bold },
{ "silentmissed", decor::red_fg + decor::bold },
{ "silentcovered", decor::green_fg + decor::bold },
{ "added", decor::green_fg + decor::bold },
{ "removed", decor::red_fg + decor::bold },
{ "header", decor::white_fg + decor::black_bg + decor::bold +
decor::inv },
{ "error", decor::red_bg + decor::inv + decor::bold },
{ "label", decor::bold },
{ "revision", decor::none },
{ "time", decor::none },
};
class Highlight
{
public:
Highlight(std::string groupName) : groupName(std::move(groupName))
{
}
Highlight(Highlight &&hi, std::function<void(std::ostream&)> app)
: groupName(std::move(hi.groupName)), apps(std::move(hi.apps))
{
apps.push_back(app);
}
public:
std::ostream & decorate(std::ostream &os) const
{
os << highlightGroups.at(groupName);
for (const auto app : apps) {
app(os);
}
os << decor::def;
return os;
}
private:
const std::string groupName;
std::vector<std::function<void(std::ostream&)>> apps;
};
template <typename T>
Highlight
operator<<(Highlight &&hi, const T &val)
{
return Highlight(std::move(hi), [val](std::ostream &os) { os << val; });
}
inline std::ostream &
operator<<(std::ostream &os, const Highlight &hi)
{
return hi.decorate(os);
}
std::ostream &
printHits(std::ostream &os, int hits, bool silent)
{
std::string prefix = silent ? "silent" : "";
if (hits == 0) {
return os << (Highlight(prefix + "missed") << "x0" << ' ');
} else if (hits > 0) {
// 'x' and number must be output as a single unit here so that field
// width applies correctly.
return os << (Highlight(prefix + "covered")
<< 'x' + std::to_string(hits) << ' ');
} else {
return os << "" << ' ';
}
}
}
std::ostream &
operator<<(std::ostream &os, const CLinesChange &change)
{
if (change.data < 0) {
return os << (Highlight("linesbad") << change.data);
} else if (change.data == 0) {
return os << (Highlight("linesok") << change.data);
} else {
return os << std::showpos
<< (Highlight("linesgood") << change.data)
<< std::noshowpos;
}
}
std::ostream &
operator<<(std::ostream &os, const ULinesChange &change)
{
if (change.data > 0) {
return os << std::showpos
<< (Highlight("linesbad") << change.data)
<< std::noshowpos;
} else if (change.data == 0) {
return os << (Highlight("linesok") << change.data);
} else {
return os << (Highlight("linesgood") << change.data);
}
}
std::ostream &
operator<<(std::ostream &os, const RLinesChange &change)
{
if (change.data > 0) {
os << std::showpos;
}
return os << (Highlight("lineschanged") << change.data) << std::noshowpos;
}
std::ostream &
operator<<(std::ostream &os, const CoverageChange &change)
{
if (change.data < 0) {
return os << (Highlight("covbad") << change.data << '%');
} else if (change.data == 0) {
return os << (Highlight("covok") << change.data << '%');
} else {
return os << (Highlight("covgood") << change.data << '%');
}
}
std::ostream &
operator<<(std::ostream &os, const Coverage &coverage)
{
// XXX: hard-coded coverage thresholds.
if (coverage.data < 70.0f) {
return os << (Highlight("covbad") << coverage.data << '%');
} else if (coverage.data < 90.0f) {
return os << (Highlight("covok") << coverage.data << '%');
} else {
return os << (Highlight("covgood") << coverage.data << '%');
}
}
std::ostream &
operator<<(std::ostream &os, const Label &label)
{
return os << (Highlight("label") << label.data);
}
std::ostream &
operator<<(std::ostream &os, const ErrorMsg &errMsg)
{
return os << (Highlight("error") << errMsg.data);
}
std::ostream &
operator<<(std::ostream &os, const TableHeader &th)
{
return os << (Highlight("header") << th.data);
}
std::ostream &
operator<<(std::ostream &os, const LineNo &lineNo)
{
return os << (Highlight("lineno") << lineNo.data << ' ');
}
std::ostream &
operator<<(std::ostream &os, const LineAdded &line)
{
return os << (Highlight("added") << '+') << line.data;
}
std::ostream &
operator<<(std::ostream &os, const LineRemoved &line)
{
return os << (Highlight("removed") << '-') << line.data;
}
std::ostream &
operator<<(std::ostream &os, const HitsCount &hits)
{
return printHits(os, hits.data, false);
}
std::ostream &
operator<<(std::ostream &os, const SilentHitsCount &hits)
{
return printHits(os, hits.data, true);
}
std::ostream &
operator<<(std::ostream &os, const Revision &rev)
{
return os << (Highlight("revision") << rev.data);
}
std::ostream &
operator<<(std::ostream &os, const Time &t)
{
// XXX: hard-coded time format.
return os << (Highlight("time")
<< std::put_time(std::localtime(&t.data), "%Y-%m-%d %H:%M:%S"));
}
<commit_msg>Restore "+" sign on coverage change printing<commit_after>// Copyright (C) 2016 xaizek <xaizek@openmailbox.org>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#include "printing.hpp"
#include <cstddef>
#include <iomanip>
#include <ostream>
#include <string>
#include <unordered_map>
#include <utility>
#include "decoration.hpp"
namespace {
const std::unordered_map<std::string, decor::Decoration> highlightGroups = {
{ "linesbad", decor::bold + decor::red_fg },
{ "linesok", decor::bold + decor::black_fg },
{ "linesgood", decor::bold + decor::green_fg },
{ "lineschanged", decor::yellow_fg },
{ "covbad", decor::bold + decor::red_fg },
{ "covok", decor::bold + decor::black_fg },
{ "covgood", decor::bold + decor::green_fg },
{ "lineno", decor::white_bg + decor::black_fg },
{ "missed", decor::red_fg + decor::inv + decor::bold },
{ "covered", decor::green_fg + decor::inv + decor::bold },
{ "silentmissed", decor::red_fg + decor::bold },
{ "silentcovered", decor::green_fg + decor::bold },
{ "added", decor::green_fg + decor::bold },
{ "removed", decor::red_fg + decor::bold },
{ "header", decor::white_fg + decor::black_bg + decor::bold +
decor::inv },
{ "error", decor::red_bg + decor::inv + decor::bold },
{ "label", decor::bold },
{ "revision", decor::none },
{ "time", decor::none },
};
class Highlight
{
public:
Highlight(std::string groupName) : groupName(std::move(groupName))
{
}
Highlight(Highlight &&hi, std::function<void(std::ostream&)> app)
: groupName(std::move(hi.groupName)), apps(std::move(hi.apps))
{
apps.push_back(app);
}
public:
std::ostream & decorate(std::ostream &os) const
{
os << highlightGroups.at(groupName);
for (const auto app : apps) {
app(os);
}
os << decor::def;
return os;
}
private:
const std::string groupName;
std::vector<std::function<void(std::ostream&)>> apps;
};
template <typename T>
Highlight
operator<<(Highlight &&hi, const T &val)
{
return Highlight(std::move(hi), [val](std::ostream &os) { os << val; });
}
inline std::ostream &
operator<<(std::ostream &os, const Highlight &hi)
{
return hi.decorate(os);
}
std::ostream &
printHits(std::ostream &os, int hits, bool silent)
{
std::string prefix = silent ? "silent" : "";
if (hits == 0) {
return os << (Highlight(prefix + "missed") << "x0" << ' ');
} else if (hits > 0) {
// 'x' and number must be output as a single unit here so that field
// width applies correctly.
return os << (Highlight(prefix + "covered")
<< 'x' + std::to_string(hits) << ' ');
} else {
return os << "" << ' ';
}
}
}
std::ostream &
operator<<(std::ostream &os, const CLinesChange &change)
{
if (change.data < 0) {
return os << (Highlight("linesbad") << change.data);
} else if (change.data == 0) {
return os << (Highlight("linesok") << change.data);
} else {
return os << std::showpos
<< (Highlight("linesgood") << change.data)
<< std::noshowpos;
}
}
std::ostream &
operator<<(std::ostream &os, const ULinesChange &change)
{
if (change.data > 0) {
return os << std::showpos
<< (Highlight("linesbad") << change.data)
<< std::noshowpos;
} else if (change.data == 0) {
return os << (Highlight("linesok") << change.data);
} else {
return os << (Highlight("linesgood") << change.data);
}
}
std::ostream &
operator<<(std::ostream &os, const RLinesChange &change)
{
if (change.data > 0) {
os << std::showpos;
}
return os << (Highlight("lineschanged") << change.data) << std::noshowpos;
}
std::ostream &
operator<<(std::ostream &os, const CoverageChange &change)
{
if (change.data < 0) {
return os << (Highlight("covbad") << change.data << '%');
} else if (change.data == 0) {
return os << (Highlight("covok") << change.data << '%');
} else {
return os << std::showpos
<< (Highlight("covgood") << change.data << '%')
<< std::noshowpos;
}
}
std::ostream &
operator<<(std::ostream &os, const Coverage &coverage)
{
// XXX: hard-coded coverage thresholds.
if (coverage.data < 70.0f) {
return os << (Highlight("covbad") << coverage.data << '%');
} else if (coverage.data < 90.0f) {
return os << (Highlight("covok") << coverage.data << '%');
} else {
return os << (Highlight("covgood") << coverage.data << '%');
}
}
std::ostream &
operator<<(std::ostream &os, const Label &label)
{
return os << (Highlight("label") << label.data);
}
std::ostream &
operator<<(std::ostream &os, const ErrorMsg &errMsg)
{
return os << (Highlight("error") << errMsg.data);
}
std::ostream &
operator<<(std::ostream &os, const TableHeader &th)
{
return os << (Highlight("header") << th.data);
}
std::ostream &
operator<<(std::ostream &os, const LineNo &lineNo)
{
return os << (Highlight("lineno") << lineNo.data << ' ');
}
std::ostream &
operator<<(std::ostream &os, const LineAdded &line)
{
return os << (Highlight("added") << '+') << line.data;
}
std::ostream &
operator<<(std::ostream &os, const LineRemoved &line)
{
return os << (Highlight("removed") << '-') << line.data;
}
std::ostream &
operator<<(std::ostream &os, const HitsCount &hits)
{
return printHits(os, hits.data, false);
}
std::ostream &
operator<<(std::ostream &os, const SilentHitsCount &hits)
{
return printHits(os, hits.data, true);
}
std::ostream &
operator<<(std::ostream &os, const Revision &rev)
{
return os << (Highlight("revision") << rev.data);
}
std::ostream &
operator<<(std::ostream &os, const Time &t)
{
// XXX: hard-coded time format.
return os << (Highlight("time")
<< std::put_time(std::localtime(&t.data), "%Y-%m-%d %H:%M:%S"));
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
if (!tr) return;
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
void Delete(Node **Tree, T &value)
{
Node *q;
if (*Tree == nullptr) return;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
q = *Tree;
if ((*q).right ==nullptr) { *Tree = (*q).left; delete q; }
else
if ((*q).left == nullptr) { *Tree = (*q).right; delete q; }
else Delete_(&((*q).left), &q);
}
}
void Delete_(Node **r, Node **q)
{
Node *s;
if ((**r).right == nullptr)
{
(**q).value_ = (**r).value_; *q = *r;
s = *r; *r = (**r).left; delete s;
}
else Delete_(&((**r).right), q);
}
public:
Tree()
{
root = nullptr;
};
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool del(T value)
{
Delete(&root, value);
return find(value);
}
void pr(char* name) const;
};
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<commit_msg>Update tree.hpp<commit_after>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
try
{
if (!tr) throw 1;
}
catch (int i = 1)
{
return;
}
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
void Delete(Node **Tree, T &value)
{
Node *q;
if (*Tree == nullptr) return;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
q = *Tree;
if ((*q).right ==nullptr) { *Tree = (*q).left; delete q; }
else
if ((*q).left == nullptr) { *Tree = (*q).right; delete q; }
else Delete_(&((*q).left), &q);
}
}
void Delete_(Node **r, Node **q)
{
Node *s;
if ((**r).right == nullptr)
{
(**q).value_ = (**r).value_; *q = *r;
s = *r; *r = (**r).left; delete s;
}
else Delete_(&((**r).right), q);
}
public:
Tree()
{
root = nullptr;
};
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool del(T value)
{
try
{
if (find(value) == 0) throw 1;
}
catch (int i = 1)
{
return 0;
}
Delete(&root, value);
return !find(value);
}
void pr(char* name) const;
};
void main()
{
Tree<int>a;
a.add(7);
bool b=a.del(2);
cout << b;
system("pause");
}
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
try
{
if (file.is_open()==0) throw 1;
}
catch (int i = 1)
{
return 0;
}
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
try
{
if (!tr) throw 1;
}
catch (int)
{
return;
}
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
bool Delete(Node **Tree, T &value)
{
Node *tr;
if (*Tree == nullptr) return false;
if (find(value)==0) return false;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
tr = *Tree;
if ((*tr).right ==nullptr) { *Tree = (*tr).left; delete tr; }
else
if ((*tr).left == nullptr) { *Tree = (*tr).right; delete tr; }
else Delete_(&((*tr).left), &tr);
}
return true;
}
void Delete_(Node **r, Node **tr)
{
Node *tr_;
if ((**r).right == nullptr)
{
(**tr).value_ = (**r).value_; *tr= *r;
tr_ = *r; *r = (**r).left; delete tr_;
}
else Delete_(&((**r).right), tr);
}
bool isEqual(Node* root2, const Node* root1)
{
return (root2&&root1 ? root2->value_ == root1->value_&&isEqual(root2->left, root1->left) && isEqual(root2->right, root1->right) : !root2 && !root1);
};
public:
Tree()
{
root = nullptr;
};
Tree(std::initializer_list<T> list)
{
root = nullptr;
for (auto& item : list)
{
add(item);
}
}
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool operator ==(const Tree<T> &a)
{
return isEqual(root, a.root);
}
bool del(T value)
{
return Delete(&root, value);
}
void pr(char* name) const;
};
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
else {
throw "";
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<commit_msg>Update tree.hpp<commit_after>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
try
{
if (!tr) throw 1;
}
catch (int)
{
return;
}
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
bool Delete(Node **Tree, T &value)
{
Node *tr;
if (*Tree == nullptr) return false;
if (find(value)==0) return false;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
tr = *Tree;
if ((*tr).right ==nullptr) { *Tree = (*tr).left; delete tr; }
else
if ((*tr).left == nullptr) { *Tree = (*tr).right; delete tr; }
else Delete_(&((*tr).left), &tr);
}
return true;
}
void Delete_(Node **r, Node **tr)
{
Node *tr_;
if ((**r).right == nullptr)
{
(**tr).value_ = (**r).value_; *tr= *r;
tr_ = *r; *r = (**r).left; delete tr_;
}
else Delete_(&((**r).right), tr);
}
bool isEqual(Node* root2, const Node* root1)
{
return (root2&&root1 ? root2->value_ == root1->value_&&isEqual(root2->left, root1->left) && isEqual(root2->right, root1->right) : !root2 && !root1);
};
public:
Tree()
{
root = nullptr;
};
Tree(std::initializer_list<T> list)
{
root = nullptr;
for (auto& item : list)
{
add(item);
}
}
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool isEmpty()
{
Node* root1 = nullptr;
return isEqual(root, root1);
}
bool operator ==(const Tree<T> &a)
{
return isEqual(root, a.root);
}
bool del(T value)
{
return Delete(&root, value);
}
void pr(char* name) const;
};
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
else {
throw "";
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2007, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "pyinterp.h"
#include "pyutils.h"
#include "amount.h"
#include <boost/python/exception_translator.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/args.hpp>
namespace ledger {
using namespace boost::python;
amount_t py_round_0(const amount_t& amount) {
return amount.round();
}
amount_t py_round_1(const amount_t& amount, amount_t::precision_t prec) {
return amount.round(prec);
}
double py_to_double_0(amount_t& amount) {
return amount.to_double();
}
double py_to_double_1(amount_t& amount, bool no_check) {
return amount.to_double(no_check);
}
long py_to_long_0(amount_t& amount) {
return amount.to_long();
}
long py_to_long_1(amount_t& amount, bool no_check) {
return amount.to_long(no_check);
}
boost::optional<amount_t> py_value_0(const amount_t& amount) {
return amount.value();
}
boost::optional<amount_t> py_value_1(const amount_t& amount,
const boost::optional<moment_t>& moment) {
return amount.value(moment);
}
void py_parse_2(amount_t& amount, object in, unsigned char flags) {
if (PyFile_Check(in.ptr())) {
pyifstream instr(reinterpret_cast<PyFileObject *>(in.ptr()));
amount.parse(instr, flags);
} else {
PyErr_SetString(PyExc_IOError,
"Argument to amount.parse(file) is not a file object");
}
}
void py_parse_1(amount_t& amount, object in) {
py_parse_2(amount, in, 0);
}
void py_parse_str_1(amount_t& amount, const string& str) {
amount.parse(str);
}
void py_parse_str_2(amount_t& amount, const string& str, unsigned char flags) {
amount.parse(str, flags);
}
void py_read_1(amount_t& amount, object in) {
if (PyFile_Check(in.ptr())) {
pyifstream instr(reinterpret_cast<PyFileObject *>(in.ptr()));
amount.read(instr);
} else {
PyErr_SetString(PyExc_IOError,
"Argument to amount.parse(file) is not a file object");
}
}
void py_read_2(amount_t& amount, const std::string& str) {
const char * p = str.c_str();
amount.read(p);
}
#define EXC_TRANSLATOR(type) \
void exc_translate_ ## type(const type& err) { \
PyErr_SetString(PyExc_ArithmeticError, err.what()); \
}
EXC_TRANSLATOR(amount_error)
void export_amount()
{
scope().attr("AMOUNT_PARSE_NO_MIGRATE") = AMOUNT_PARSE_NO_MIGRATE;
scope().attr("AMOUNT_PARSE_NO_REDUCE") = AMOUNT_PARSE_NO_REDUCE;
class_< amount_t > ("amount")
#if 0
.def("initialize", &amount_t::initialize)
.staticmethod("initialize")
.def("shutdown", &amount_t::shutdown)
.staticmethod("shutdown")
#endif
.add_static_property("current_pool",
make_getter(&amount_t::current_pool,
return_value_policy<reference_existing_object>()))
.add_static_property("keep_base", &amount_t::keep_base)
.add_static_property("keep_price", &amount_t::keep_price)
.add_static_property("keep_date", &amount_t::keep_date)
.add_static_property("keep_tag", &amount_t::keep_tag)
.add_static_property("stream_fullstrings", &amount_t::stream_fullstrings)
.def(init<double>())
.def(init<long>())
.def(init<std::string>())
.def("exact", &amount_t::exact, boost::python::arg("value"),
"Construct an amount object whose display precision is always equal to its\n\
internal precision.")
.staticmethod("exact")
.def(init<amount_t>())
.def("compare", &amount_t::compare)
.def(self == self)
.def(self == long())
.def(long() == self)
.def(self == double())
.def(double() == self)
.def(self != self)
.def(self != long())
.def(long() != self)
.def(self != double())
.def(double() != self)
.def(! self)
.def(self < self)
.def(self < long())
.def(long() < self)
.def(self < double())
.def(double() < self)
.def(self <= self)
.def(self <= long())
.def(long() <= self)
.def(self <= double())
.def(double() <= self)
.def(self > self)
.def(self > long())
.def(long() > self)
.def(self > double())
.def(double() > self)
.def(self >= self)
.def(self >= long())
.def(long() >= self)
.def(self >= double())
.def(double() >= self)
.def(self += self)
.def(self += long())
.def(self += double())
.def(self + self)
.def(self + long())
.def(long() + self)
.def(self + double())
.def(double() + self)
.def(self -= self)
.def(self -= long())
.def(self -= double())
.def(self - self)
.def(self - long())
.def(long() - self)
.def(self - double())
.def(double() - self)
.def(self *= self)
.def(self *= long())
.def(self *= double())
.def(self * self)
.def(self * long())
.def(long() * self)
.def(self * double())
.def(double() * self)
.def(self /= self)
.def(self /= long())
.def(self /= double())
.def(self / self)
.def(self / long())
.def(long() / self)
.def(self / double())
.def(double() / self)
.add_property("precision", &amount_t::precision)
.def("negate", &amount_t::negate)
.def("in_place_negate", &amount_t::in_place_negate,
return_value_policy<reference_existing_object>())
.def(- self)
.def("abs", &amount_t::abs)
.def("__abs__", &amount_t::abs)
.def("round", py_round_0)
.def("round", py_round_1)
.def("unround", &amount_t::unround)
.def("reduce", &amount_t::reduce)
.def("in_place_reduce", &amount_t::in_place_reduce,
return_value_policy<reference_existing_object>())
.def("unreduce", &amount_t::unreduce)
.def("in_place_unreduce", &amount_t::in_place_unreduce,
return_value_policy<reference_existing_object>())
.def("value", py_value_0)
.def("value", py_value_1)
.def("sign", &amount_t::sign)
.def("__nonzero__", &amount_t::is_nonzero)
.def("is_nonzero", &amount_t::is_nonzero)
.def("is_zero", &amount_t::is_zero)
.def("is_realzero", &amount_t::is_realzero)
.def("is_null", &amount_t::is_null)
.def("to_double", py_to_double_0)
.def("to_double", py_to_double_1)
.def("__float__", py_to_double_0)
.def("to_long", py_to_long_0)
.def("to_long", py_to_long_1)
.def("__int__", py_to_long_0)
.def("to_string", &amount_t::to_string)
.def("__str__", &amount_t::to_string)
.def("to_fullstring", &amount_t::to_fullstring)
.def("__repr__", &amount_t::to_fullstring)
.def("fits_in_double", &amount_t::fits_in_double)
.def("fits_in_long", &amount_t::fits_in_long)
.add_property("quantity_string", &amount_t::quantity_string)
.add_property("commodity",
make_function(&amount_t::commodity,
return_value_policy<reference_existing_object>()),
make_function(&amount_t::set_commodity,
with_custodian_and_ward<1, 2>()))
.def("has_commodity", &amount_t::has_commodity)
.def("clear_commodity", &amount_t::clear_commodity)
.add_property("number", &amount_t::number)
.def("annotate_commodity", &amount_t::annotate_commodity)
.def("commodity_annotated", &amount_t::commodity_annotated)
.add_property("annotation_details", &amount_t::annotation_details)
.def("strip_annotations", &amount_t::strip_annotations)
.def("parse", py_parse_1)
.def("parse", py_parse_2)
.def("parse", py_parse_str_1)
.def("parse", py_parse_str_2)
.def("parse_conversion", &amount_t::parse_conversion)
.staticmethod("parse_conversion")
.def("read", py_read_1)
.def("read", py_read_2)
.def("write", &amount_t::write)
.def("valid", &amount_t::valid)
;
register_optional_to_python<amount_t>();
implicitly_convertible<double, amount_t>();
implicitly_convertible<long, amount_t>();
implicitly_convertible<string, amount_t>();
#define EXC_TRANSLATE(type) \
register_exception_translator<type>(&exc_translate_ ## type);
EXC_TRANSLATE(amount_error);
}
} // namespace ledger
<commit_msg>*** no comment ***<commit_after>/*
* Copyright (c) 2003-2007, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "pyinterp.h"
#include "pyutils.h"
#include "amount.h"
#include <boost/python/exception_translator.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/args.hpp>
namespace ledger {
using namespace boost::python;
amount_t py_round_0(const amount_t& amount) {
return amount.round();
}
amount_t py_round_1(const amount_t& amount, amount_t::precision_t prec) {
return amount.round(prec);
}
double py_to_double_0(amount_t& amount) {
return amount.to_double();
}
double py_to_double_1(amount_t& amount, bool no_check) {
return amount.to_double(no_check);
}
long py_to_long_0(amount_t& amount) {
return amount.to_long();
}
long py_to_long_1(amount_t& amount, bool no_check) {
return amount.to_long(no_check);
}
boost::optional<amount_t> py_value_0(const amount_t& amount) {
return amount.value();
}
boost::optional<amount_t> py_value_1(const amount_t& amount,
const boost::optional<moment_t>& moment) {
return amount.value(moment);
}
void py_parse_2(amount_t& amount, object in, unsigned char flags) {
if (PyFile_Check(in.ptr())) {
pyifstream instr(reinterpret_cast<PyFileObject *>(in.ptr()));
amount.parse(instr, flags);
} else {
PyErr_SetString(PyExc_IOError,
"Argument to amount.parse(file) is not a file object");
}
}
void py_parse_1(amount_t& amount, object in) {
py_parse_2(amount, in, 0);
}
void py_parse_str_1(amount_t& amount, const string& str) {
amount.parse(str);
}
void py_parse_str_2(amount_t& amount, const string& str, unsigned char flags) {
amount.parse(str, flags);
}
void py_read_1(amount_t& amount, object in) {
if (PyFile_Check(in.ptr())) {
pyifstream instr(reinterpret_cast<PyFileObject *>(in.ptr()));
amount.read(instr);
} else {
PyErr_SetString(PyExc_IOError,
"Argument to amount.parse(file) is not a file object");
}
}
void py_read_2(amount_t& amount, const std::string& str) {
const char * p = str.c_str();
amount.read(p);
}
#define EXC_TRANSLATOR(type) \
void exc_translate_ ## type(const type& err) { \
PyErr_SetString(PyExc_ArithmeticError, err.what()); \
}
EXC_TRANSLATOR(amount_error)
void export_amount()
{
scope().attr("AMOUNT_PARSE_NO_MIGRATE") = AMOUNT_PARSE_NO_MIGRATE;
scope().attr("AMOUNT_PARSE_NO_REDUCE") = AMOUNT_PARSE_NO_REDUCE;
class_< amount_t > ("amount")
#if 0
.def("initialize", &amount_t::initialize)
.staticmethod("initialize")
.def("shutdown", &amount_t::shutdown)
.staticmethod("shutdown")
#endif
.add_static_property("current_pool",
make_getter(&amount_t::current_pool,
return_value_policy<reference_existing_object>()))
.add_static_property("keep_base", &amount_t::keep_base)
.add_static_property("keep_price", &amount_t::keep_price)
.add_static_property("keep_date", &amount_t::keep_date)
.add_static_property("keep_tag", &amount_t::keep_tag)
.add_static_property("stream_fullstrings", &amount_t::stream_fullstrings)
.def(init<double>())
.def(init<long>())
.def(init<std::string>())
.def("exact", &amount_t::exact, args("value"),
"Construct an amount object whose display precision is always equal to its\n\
internal precision.")
.staticmethod("exact")
.def(init<amount_t>())
.def("compare", &amount_t::compare)
.def(self == self)
.def(self == long())
.def(long() == self)
.def(self == double())
.def(double() == self)
.def(self != self)
.def(self != long())
.def(long() != self)
.def(self != double())
.def(double() != self)
.def(! self)
.def(self < self)
.def(self < long())
.def(long() < self)
.def(self < double())
.def(double() < self)
.def(self <= self)
.def(self <= long())
.def(long() <= self)
.def(self <= double())
.def(double() <= self)
.def(self > self)
.def(self > long())
.def(long() > self)
.def(self > double())
.def(double() > self)
.def(self >= self)
.def(self >= long())
.def(long() >= self)
.def(self >= double())
.def(double() >= self)
.def(self += self)
.def(self += long())
.def(self += double())
.def(self + self)
.def(self + long())
.def(long() + self)
.def(self + double())
.def(double() + self)
.def(self -= self)
.def(self -= long())
.def(self -= double())
.def(self - self)
.def(self - long())
.def(long() - self)
.def(self - double())
.def(double() - self)
.def(self *= self)
.def(self *= long())
.def(self *= double())
.def(self * self)
.def(self * long())
.def(long() * self)
.def(self * double())
.def(double() * self)
.def(self /= self)
.def(self /= long())
.def(self /= double())
.def(self / self)
.def(self / long())
.def(long() / self)
.def(self / double())
.def(double() / self)
.add_property("precision", &amount_t::precision)
.def("negate", &amount_t::negate)
.def("in_place_negate", &amount_t::in_place_negate,
return_value_policy<reference_existing_object>())
.def(- self)
.def("abs", &amount_t::abs)
.def("__abs__", &amount_t::abs)
.def("round", py_round_0)
.def("round", py_round_1)
.def("unround", &amount_t::unround)
.def("reduce", &amount_t::reduce)
.def("in_place_reduce", &amount_t::in_place_reduce,
return_value_policy<reference_existing_object>())
.def("unreduce", &amount_t::unreduce)
.def("in_place_unreduce", &amount_t::in_place_unreduce,
return_value_policy<reference_existing_object>())
.def("value", py_value_0)
.def("value", py_value_1)
.def("sign", &amount_t::sign)
.def("__nonzero__", &amount_t::is_nonzero)
.def("is_nonzero", &amount_t::is_nonzero)
.def("is_zero", &amount_t::is_zero)
.def("is_realzero", &amount_t::is_realzero)
.def("is_null", &amount_t::is_null)
.def("to_double", py_to_double_0)
.def("to_double", py_to_double_1)
.def("__float__", py_to_double_0)
.def("to_long", py_to_long_0)
.def("to_long", py_to_long_1)
.def("__int__", py_to_long_0)
.def("to_string", &amount_t::to_string)
.def("__str__", &amount_t::to_string)
.def("to_fullstring", &amount_t::to_fullstring)
.def("__repr__", &amount_t::to_fullstring)
.def("fits_in_double", &amount_t::fits_in_double)
.def("fits_in_long", &amount_t::fits_in_long)
.add_property("quantity_string", &amount_t::quantity_string)
.add_property("commodity",
make_function(&amount_t::commodity,
return_value_policy<reference_existing_object>()),
make_function(&amount_t::set_commodity,
with_custodian_and_ward<1, 2>()))
.def("has_commodity", &amount_t::has_commodity)
.def("clear_commodity", &amount_t::clear_commodity)
.add_property("number", &amount_t::number)
.def("annotate_commodity", &amount_t::annotate_commodity)
.def("commodity_annotated", &amount_t::commodity_annotated)
.add_property("annotation_details", &amount_t::annotation_details)
.def("strip_annotations", &amount_t::strip_annotations)
.def("parse", py_parse_1)
.def("parse", py_parse_2)
.def("parse", py_parse_str_1)
.def("parse", py_parse_str_2)
.def("parse_conversion", &amount_t::parse_conversion)
.staticmethod("parse_conversion")
.def("read", py_read_1)
.def("read", py_read_2)
.def("write", &amount_t::write)
.def("valid", &amount_t::valid)
;
register_optional_to_python<amount_t>();
implicitly_convertible<double, amount_t>();
implicitly_convertible<long, amount_t>();
implicitly_convertible<string, amount_t>();
#define EXC_TRANSLATE(type) \
register_exception_translator<type>(&exc_translate_ ## type);
EXC_TRANSLATE(amount_error);
}
} // namespace ledger
<|endoftext|> |
<commit_before>//===--- Multilib.cpp - Multilib Implementation ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Multilib.h"
#include "Tools.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace clang::driver;
using namespace clang;
using namespace llvm::opt;
using namespace llvm::sys;
/// normalize Segment to "/foo/bar" or "".
static void normalizePathSegment(std::string &Segment) {
StringRef seg = Segment;
// Prune trailing "/" or "./"
while (1) {
StringRef last = *--path::end(seg);
if (last != ".")
break;
seg = path::parent_path(seg);
}
if (seg.empty() || seg == "/") {
Segment = "";
return;
}
// Add leading '/'
if (seg.front() != '/') {
Segment = "/" + seg.str();
} else {
Segment = seg;
}
}
Multilib::Multilib(StringRef GCCSuffix, StringRef OSSuffix,
StringRef IncludeSuffix)
: GCCSuffix(GCCSuffix), OSSuffix(OSSuffix), IncludeSuffix(IncludeSuffix) {
normalizePathSegment(this->GCCSuffix);
normalizePathSegment(this->OSSuffix);
normalizePathSegment(this->IncludeSuffix);
}
Multilib &Multilib::gccSuffix(StringRef S) {
GCCSuffix = S;
normalizePathSegment(GCCSuffix);
return *this;
}
Multilib &Multilib::osSuffix(StringRef S) {
OSSuffix = S;
normalizePathSegment(OSSuffix);
return *this;
}
Multilib &Multilib::includeSuffix(StringRef S) {
IncludeSuffix = S;
normalizePathSegment(IncludeSuffix);
return *this;
}
void Multilib::print(raw_ostream &OS) const {
assert(GCCSuffix.empty() || (StringRef(GCCSuffix).front() == '/'));
if (GCCSuffix.empty())
OS << ".";
else {
OS << StringRef(GCCSuffix).drop_front();
}
OS << ";";
for (flags_list::const_iterator I = Flags.begin(), E = Flags.end(); I != E;
++I) {
if (StringRef(*I).front() == '+')
OS << "@" << I->substr(1);
}
}
bool Multilib::isValid() const {
llvm::StringMap<int> FlagSet;
for (unsigned I = 0, N = Flags.size(); I != N; ++I) {
StringRef Flag(Flags[I]);
llvm::StringMap<int>::iterator SI = FlagSet.find(Flag.substr(1));
assert(StringRef(Flag).front() == '+' || StringRef(Flag).front() == '-');
if (SI == FlagSet.end())
FlagSet[Flag.substr(1)] = I;
else if (Flags[I] != Flags[SI->getValue()])
return false;
}
return true;
}
bool Multilib::operator==(const Multilib &Other) const {
// Check whether the flags sets match
// allowing for the match to be order invariant
llvm::StringSet<> MyFlags;
for (flags_list::const_iterator I = Flags.begin(), E = Flags.end(); I != E;
++I) {
MyFlags.insert(*I);
}
for (flags_list::const_iterator I = Other.Flags.begin(),
E = Other.Flags.end();
I != E; ++I) {
if (MyFlags.find(*I) == MyFlags.end())
return false;
}
if (osSuffix() != Other.osSuffix())
return false;
if (gccSuffix() != Other.gccSuffix())
return false;
if (includeSuffix() != Other.includeSuffix())
return false;
return true;
}
raw_ostream &clang::driver::operator<<(raw_ostream &OS, const Multilib &M) {
M.print(OS);
return OS;
}
MultilibSet &MultilibSet::Maybe(const Multilib &M) {
Multilib Opposite;
// Negate any '+' flags
for (Multilib::flags_list::const_iterator I = M.flags().begin(),
E = M.flags().end();
I != E; ++I) {
StringRef Flag(*I);
if (Flag.front() == '+')
Opposite.flags().push_back(("-" + Flag.substr(1)).str());
}
return Either(M, Opposite);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
return Either(Ms);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
Ms.push_back(M3);
return Either(Ms);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
Ms.push_back(M3);
Ms.push_back(M4);
return Either(Ms);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4,
const Multilib &M5) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
Ms.push_back(M3);
Ms.push_back(M4);
Ms.push_back(M5);
return Either(Ms);
}
static Multilib compose(const Multilib &Base, const Multilib &New) {
SmallString<128> GCCSuffix;
llvm::sys::path::append(GCCSuffix, "/", Base.gccSuffix(), New.gccSuffix());
SmallString<128> OSSuffix;
llvm::sys::path::append(OSSuffix, "/", Base.osSuffix(), New.osSuffix());
SmallString<128> IncludeSuffix;
llvm::sys::path::append(IncludeSuffix, "/", Base.includeSuffix(),
New.includeSuffix());
Multilib Composed(GCCSuffix.str(), OSSuffix.str(), IncludeSuffix.str());
Multilib::flags_list &Flags = Composed.flags();
Flags.insert(Flags.end(), Base.flags().begin(), Base.flags().end());
Flags.insert(Flags.end(), New.flags().begin(), New.flags().end());
return Composed;
}
MultilibSet &
MultilibSet::Either(const std::vector<Multilib> &MultilibSegments) {
multilib_list Composed;
if (Multilibs.empty())
Multilibs.insert(Multilibs.end(), MultilibSegments.begin(),
MultilibSegments.end());
else {
for (std::vector<Multilib>::const_iterator NewI = MultilibSegments.begin(),
NewE = MultilibSegments.end();
NewI != NewE; ++NewI) {
for (const_iterator BaseI = begin(), BaseE = end(); BaseI != BaseE;
++BaseI) {
Multilib MO = compose(*BaseI, *NewI);
if (MO.isValid())
Composed.push_back(MO);
}
}
Multilibs = Composed;
}
return *this;
}
MultilibSet &MultilibSet::FilterOut(const MultilibSet::FilterCallback &F) {
filterInPlace(F, Multilibs);
return *this;
}
MultilibSet &MultilibSet::FilterOut(std::string Regex) {
class REFilter : public MultilibSet::FilterCallback {
mutable llvm::Regex R;
public:
REFilter(std::string Regex) : R(Regex) {}
bool operator()(const Multilib &M) const override {
std::string Error;
if (!R.isValid(Error)) {
llvm::errs() << Error;
assert(false);
return false;
}
return R.match(M.gccSuffix());
}
};
REFilter REF(Regex);
filterInPlace(REF, Multilibs);
return *this;
}
void MultilibSet::push_back(const Multilib &M) { Multilibs.push_back(M); }
void MultilibSet::combineWith(const MultilibSet &Other) {
Multilibs.insert(Multilibs.end(), Other.begin(), Other.end());
}
bool MultilibSet::select(const Multilib::flags_list &Flags, Multilib &M) const {
class FilterFlagsMismatch : public MultilibSet::FilterCallback {
llvm::StringMap<bool> FlagSet;
public:
FilterFlagsMismatch(const std::vector<std::string> &Flags) {
// Stuff all of the flags into the FlagSet such that a true mappend
// indicates the flag was enabled, and a false mappend indicates the
// flag was disabled
for (Multilib::flags_list::const_iterator I = Flags.begin(),
E = Flags.end();
I != E; ++I) {
FlagSet[StringRef(*I).substr(1)] = isFlagEnabled(*I);
}
}
bool operator()(const Multilib &M) const override {
for (Multilib::flags_list::const_iterator I = M.flags().begin(),
E = M.flags().end();
I != E; ++I) {
StringRef Flag(*I);
llvm::StringMap<bool>::const_iterator SI = FlagSet.find(Flag.substr(1));
if (SI != FlagSet.end())
if ((*SI).getValue() != isFlagEnabled(Flag))
return true;
}
return false;
}
private:
bool isFlagEnabled(StringRef Flag) const {
char Indicator = Flag.front();
assert(Indicator == '+' || Indicator == '-');
return Indicator == '+';
}
};
FilterFlagsMismatch FlagsMismatch(Flags);
multilib_list Filtered = filterCopy(FlagsMismatch, Multilibs);
if (Filtered.size() == 0) {
return false;
} else if (Filtered.size() == 1) {
M = Filtered[0];
return true;
}
// TODO: pick the "best" multlib when more than one is suitable
assert(false);
return false;
}
void MultilibSet::print(raw_ostream &OS) const {
for (const_iterator I = begin(), E = end(); I != E; ++I)
OS << *I << "\n";
}
MultilibSet::multilib_list
MultilibSet::filterCopy(const MultilibSet::FilterCallback &F,
const multilib_list &Ms) {
multilib_list Copy(Ms);
filterInPlace(F, Copy);
return Copy;
}
void MultilibSet::filterInPlace(const MultilibSet::FilterCallback &F,
multilib_list &Ms) {
Ms.erase(std::remove_if(Ms.begin(), Ms.end(),
[&F](const Multilib &M) { return F(M); }),
Ms.end());
}
raw_ostream &clang::driver::operator<<(raw_ostream &OS, const MultilibSet &MS) {
MS.print(OS);
return OS;
}
<commit_msg>[C++11] Replace trivial lambda with std::cref.<commit_after>//===--- Multilib.cpp - Multilib Implementation ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Multilib.h"
#include "Tools.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace clang::driver;
using namespace clang;
using namespace llvm::opt;
using namespace llvm::sys;
/// normalize Segment to "/foo/bar" or "".
static void normalizePathSegment(std::string &Segment) {
StringRef seg = Segment;
// Prune trailing "/" or "./"
while (1) {
StringRef last = *--path::end(seg);
if (last != ".")
break;
seg = path::parent_path(seg);
}
if (seg.empty() || seg == "/") {
Segment = "";
return;
}
// Add leading '/'
if (seg.front() != '/') {
Segment = "/" + seg.str();
} else {
Segment = seg;
}
}
Multilib::Multilib(StringRef GCCSuffix, StringRef OSSuffix,
StringRef IncludeSuffix)
: GCCSuffix(GCCSuffix), OSSuffix(OSSuffix), IncludeSuffix(IncludeSuffix) {
normalizePathSegment(this->GCCSuffix);
normalizePathSegment(this->OSSuffix);
normalizePathSegment(this->IncludeSuffix);
}
Multilib &Multilib::gccSuffix(StringRef S) {
GCCSuffix = S;
normalizePathSegment(GCCSuffix);
return *this;
}
Multilib &Multilib::osSuffix(StringRef S) {
OSSuffix = S;
normalizePathSegment(OSSuffix);
return *this;
}
Multilib &Multilib::includeSuffix(StringRef S) {
IncludeSuffix = S;
normalizePathSegment(IncludeSuffix);
return *this;
}
void Multilib::print(raw_ostream &OS) const {
assert(GCCSuffix.empty() || (StringRef(GCCSuffix).front() == '/'));
if (GCCSuffix.empty())
OS << ".";
else {
OS << StringRef(GCCSuffix).drop_front();
}
OS << ";";
for (flags_list::const_iterator I = Flags.begin(), E = Flags.end(); I != E;
++I) {
if (StringRef(*I).front() == '+')
OS << "@" << I->substr(1);
}
}
bool Multilib::isValid() const {
llvm::StringMap<int> FlagSet;
for (unsigned I = 0, N = Flags.size(); I != N; ++I) {
StringRef Flag(Flags[I]);
llvm::StringMap<int>::iterator SI = FlagSet.find(Flag.substr(1));
assert(StringRef(Flag).front() == '+' || StringRef(Flag).front() == '-');
if (SI == FlagSet.end())
FlagSet[Flag.substr(1)] = I;
else if (Flags[I] != Flags[SI->getValue()])
return false;
}
return true;
}
bool Multilib::operator==(const Multilib &Other) const {
// Check whether the flags sets match
// allowing for the match to be order invariant
llvm::StringSet<> MyFlags;
for (flags_list::const_iterator I = Flags.begin(), E = Flags.end(); I != E;
++I) {
MyFlags.insert(*I);
}
for (flags_list::const_iterator I = Other.Flags.begin(),
E = Other.Flags.end();
I != E; ++I) {
if (MyFlags.find(*I) == MyFlags.end())
return false;
}
if (osSuffix() != Other.osSuffix())
return false;
if (gccSuffix() != Other.gccSuffix())
return false;
if (includeSuffix() != Other.includeSuffix())
return false;
return true;
}
raw_ostream &clang::driver::operator<<(raw_ostream &OS, const Multilib &M) {
M.print(OS);
return OS;
}
MultilibSet &MultilibSet::Maybe(const Multilib &M) {
Multilib Opposite;
// Negate any '+' flags
for (Multilib::flags_list::const_iterator I = M.flags().begin(),
E = M.flags().end();
I != E; ++I) {
StringRef Flag(*I);
if (Flag.front() == '+')
Opposite.flags().push_back(("-" + Flag.substr(1)).str());
}
return Either(M, Opposite);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
return Either(Ms);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
Ms.push_back(M3);
return Either(Ms);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
Ms.push_back(M3);
Ms.push_back(M4);
return Either(Ms);
}
MultilibSet &MultilibSet::Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4,
const Multilib &M5) {
std::vector<Multilib> Ms;
Ms.push_back(M1);
Ms.push_back(M2);
Ms.push_back(M3);
Ms.push_back(M4);
Ms.push_back(M5);
return Either(Ms);
}
static Multilib compose(const Multilib &Base, const Multilib &New) {
SmallString<128> GCCSuffix;
llvm::sys::path::append(GCCSuffix, "/", Base.gccSuffix(), New.gccSuffix());
SmallString<128> OSSuffix;
llvm::sys::path::append(OSSuffix, "/", Base.osSuffix(), New.osSuffix());
SmallString<128> IncludeSuffix;
llvm::sys::path::append(IncludeSuffix, "/", Base.includeSuffix(),
New.includeSuffix());
Multilib Composed(GCCSuffix.str(), OSSuffix.str(), IncludeSuffix.str());
Multilib::flags_list &Flags = Composed.flags();
Flags.insert(Flags.end(), Base.flags().begin(), Base.flags().end());
Flags.insert(Flags.end(), New.flags().begin(), New.flags().end());
return Composed;
}
MultilibSet &
MultilibSet::Either(const std::vector<Multilib> &MultilibSegments) {
multilib_list Composed;
if (Multilibs.empty())
Multilibs.insert(Multilibs.end(), MultilibSegments.begin(),
MultilibSegments.end());
else {
for (std::vector<Multilib>::const_iterator NewI = MultilibSegments.begin(),
NewE = MultilibSegments.end();
NewI != NewE; ++NewI) {
for (const_iterator BaseI = begin(), BaseE = end(); BaseI != BaseE;
++BaseI) {
Multilib MO = compose(*BaseI, *NewI);
if (MO.isValid())
Composed.push_back(MO);
}
}
Multilibs = Composed;
}
return *this;
}
MultilibSet &MultilibSet::FilterOut(const MultilibSet::FilterCallback &F) {
filterInPlace(F, Multilibs);
return *this;
}
MultilibSet &MultilibSet::FilterOut(std::string Regex) {
class REFilter : public MultilibSet::FilterCallback {
mutable llvm::Regex R;
public:
REFilter(std::string Regex) : R(Regex) {}
bool operator()(const Multilib &M) const override {
std::string Error;
if (!R.isValid(Error)) {
llvm::errs() << Error;
assert(false);
return false;
}
return R.match(M.gccSuffix());
}
};
REFilter REF(Regex);
filterInPlace(REF, Multilibs);
return *this;
}
void MultilibSet::push_back(const Multilib &M) { Multilibs.push_back(M); }
void MultilibSet::combineWith(const MultilibSet &Other) {
Multilibs.insert(Multilibs.end(), Other.begin(), Other.end());
}
bool MultilibSet::select(const Multilib::flags_list &Flags, Multilib &M) const {
class FilterFlagsMismatch : public MultilibSet::FilterCallback {
llvm::StringMap<bool> FlagSet;
public:
FilterFlagsMismatch(const std::vector<std::string> &Flags) {
// Stuff all of the flags into the FlagSet such that a true mappend
// indicates the flag was enabled, and a false mappend indicates the
// flag was disabled
for (Multilib::flags_list::const_iterator I = Flags.begin(),
E = Flags.end();
I != E; ++I) {
FlagSet[StringRef(*I).substr(1)] = isFlagEnabled(*I);
}
}
bool operator()(const Multilib &M) const override {
for (Multilib::flags_list::const_iterator I = M.flags().begin(),
E = M.flags().end();
I != E; ++I) {
StringRef Flag(*I);
llvm::StringMap<bool>::const_iterator SI = FlagSet.find(Flag.substr(1));
if (SI != FlagSet.end())
if ((*SI).getValue() != isFlagEnabled(Flag))
return true;
}
return false;
}
private:
bool isFlagEnabled(StringRef Flag) const {
char Indicator = Flag.front();
assert(Indicator == '+' || Indicator == '-');
return Indicator == '+';
}
};
FilterFlagsMismatch FlagsMismatch(Flags);
multilib_list Filtered = filterCopy(FlagsMismatch, Multilibs);
if (Filtered.size() == 0) {
return false;
} else if (Filtered.size() == 1) {
M = Filtered[0];
return true;
}
// TODO: pick the "best" multlib when more than one is suitable
assert(false);
return false;
}
void MultilibSet::print(raw_ostream &OS) const {
for (const_iterator I = begin(), E = end(); I != E; ++I)
OS << *I << "\n";
}
MultilibSet::multilib_list
MultilibSet::filterCopy(const MultilibSet::FilterCallback &F,
const multilib_list &Ms) {
multilib_list Copy(Ms);
filterInPlace(F, Copy);
return Copy;
}
void MultilibSet::filterInPlace(const MultilibSet::FilterCallback &F,
multilib_list &Ms) {
Ms.erase(std::remove_if(Ms.begin(), Ms.end(), std::cref(F)), Ms.end());
}
raw_ostream &clang::driver::operator<<(raw_ostream &OS, const MultilibSet &MS) {
MS.print(OS);
return OS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "intro.h"
#include "ui_intro.h"
#include "guiutil.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void Intro::pickDataDirectory()
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, tr("Fastcoin Core"),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %n GB needed)", "", BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<commit_msg>Update intro.cpp<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "intro.h"
#include "ui_intro.h"
#include "guiutil.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void Intro::pickDataDirectory()
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, tr("Fastcoin Core"),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %n GB needed)", "", BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<|endoftext|> |
<commit_before>#ifndef __CHIP_8__
#define __CHIP_8__
#include <string>
#include <stack>
#include <istream>
#include <atomic>
#include <array>
#include <stdexcept>
#include <iomanip>
#include <tuple>
#include <chrono>
#include "Memory.hpp"
#include "Timer.hpp"
#include "Display.hpp"
#include "Backend.hpp"
namespace Chip8
{
class VM
{
public:
static const unsigned int OPCODE_SIZE = 2;
static const std::chrono::milliseconds runningRate;
VM(Backend& backend, std::istream& stream);
VM(Backend& backend, const std::string& filename);
void run();
static bool platformIsLittleEndian();
static void swapBytes(uint16_t& v);
class InvalidInstruction : public std::runtime_error
{
public:
InvalidInstruction(uint16_t opCode);
static std::string opCodeToHexStr(uint16_t opCode);
};
private:
void init();
void runExec();
void loadProgram(std::istream& stream);
void previousInst();
void nextInst();
void handle8xyOps(uint16_t opCode, uint8_t x, uint8_t y, uint8_t LSHB);
void handleFxOps(uint16_t opCode, uint8_t x);
void execReturn();
bool execDraw(uint8_t x, uint8_t y, uint8_t n);
void execKeyCheck(uint8_t x, uint16_t opCode);
void execGetKey(uint8_t x);
void execRegDump(uint8_t x);
void execRegLoad(uint8_t x);
Backend& mBackend;
std::stack<Memory::addr_t> mStack;
Memory mMemory;
Timer mDelayTimer;
Timer mSoundTimer;
Display mDisplay;
struct Registers
{
using register_t = uint8_t;
uint16_t pc;
uint16_t I;
std::array<register_t, 16> V;
} mRegisters;
};
}
#endif
<commit_msg>remove old stuff<commit_after>#ifndef __CHIP_8__
#define __CHIP_8__
#include <string>
#include <stack>
#include <istream>
#include <atomic>
#include <array>
#include <stdexcept>
#include <iomanip>
#include <tuple>
#include <chrono>
#include "Memory.hpp"
#include "Timer.hpp"
#include "Display.hpp"
#include "Backend.hpp"
namespace Chip8
{
class VM
{
public:
static const unsigned int OPCODE_SIZE = 2;
static const std::chrono::milliseconds runningRate;
VM(Backend& backend, std::istream& stream);
VM(Backend& backend, const std::string& filename);
void run();
class InvalidInstruction : public std::runtime_error
{
public:
InvalidInstruction(uint16_t opCode);
static std::string opCodeToHexStr(uint16_t opCode);
};
private:
void init();
void runExec();
void loadProgram(std::istream& stream);
void previousInst();
void nextInst();
void handle8xyOps(uint16_t opCode, uint8_t x, uint8_t y, uint8_t LSHB);
void handleFxOps(uint16_t opCode, uint8_t x);
void execReturn();
bool execDraw(uint8_t x, uint8_t y, uint8_t n);
void execKeyCheck(uint8_t x, uint16_t opCode);
void execGetKey(uint8_t x);
void execRegDump(uint8_t x);
void execRegLoad(uint8_t x);
Backend& mBackend;
std::stack<Memory::addr_t> mStack;
Memory mMemory;
Timer mDelayTimer;
Timer mSoundTimer;
Display mDisplay;
struct Registers
{
using register_t = uint8_t;
uint16_t pc;
uint16_t I;
std::array<register_t, 16> V;
} mRegisters;
};
}
#endif
<|endoftext|> |
<commit_before>/* Siconos-sample version 3.0.0, Copyright INRIA 2005-2008.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a 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.
* Siconos 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
/*!\file Disks.cpp
Some Disks (2D), friction, and walls.
Direct description of the model without XML input. Simulation with
a Time-Stepping scheme.
*/
// Siconos
#include <SiconosKernel.hpp>
#include <SiconosPointers.hpp>
#include "Disks.hpp"
using namespace std;
/* do nothing if solver does not converge */
void localCheckSolverOuput(int, Simulation*)
{};
double A(double t)
{
return 0. ;
}
double B(double t)
{
return 1. ;
}
double C(double t)
{
return 0.0;//1.1*cos(32.*M_PI*t) ;
}
double DA(double t)
{
return 0. ;
}
double DB(double t)
{
return 0. ;
}
double DC(double t)
{
return 0.0;//-1.1*32.*M_PI*sin(32.*M_PI*t) ;
}
// ================= Creation of the model =======================
void Disks::init()
{
SP::TimeDiscretisation timedisc_;
SP::TimeStepping simulation_;
SP::FrictionContact osnspb_;
// User-defined main parameters
double t0 = 0; // initial computation time
double T = 0.02;
double h = 0.01; // time step
double g = 9.81;
double theta = 0.5; // theta for Moreau integrator
std::string solverName = "NSGS";
// -----------------------------------------
// --- Dynamical systems && interactions ---
// -----------------------------------------
unsigned int j;
int interCounter = 0;
double R;
double m;
try
{
// ------------
// --- Init ---
// ------------
std::cout << "====> Model loading ..." << std::endl << std::endl;
_plans.reset(new SimpleMatrix("plans.dat", true));
if (_plans->size(0) == 0)
{
/* default plans */
double A1 = P1A;
double B1 = P1B;
double C1 = P1C;
double A2 = P2A;
double B2 = P2B;
double C2 = P2C;
_plans.reset(new SimpleMatrix(6, 6));
_plans->zero();
(*_plans)(0, 0) = 0;
(*_plans)(0, 1) = 1;
(*_plans)(0, 2) = -GROUND;
(*_plans)(1, 0) = 1;
(*_plans)(1, 1) = 0;
(*_plans)(1, 2) = WALL;
(*_plans)(2, 0) = 1;
(*_plans)(2, 1) = 0;
(*_plans)(2, 2) = -WALL;
(*_plans)(3, 0) = 0;
(*_plans)(3, 1) = 1;
(*_plans)(3, 2) = -TOP;
(*_plans)(4, 0) = A1;
(*_plans)(4, 1) = B1;
(*_plans)(4, 2) = C1;
(*_plans)(5, 0) = A2;
(*_plans)(5, 1) = B2;
(*_plans)(5, 2) = C2;
}
/* set center positions */
for (unsigned int i = 0 ; i < _plans->size(0); ++i)
{
SP::DiskPlanR tmpr;
tmpr.reset(new DiskPlanR(1, (*_plans)(i, 0), (*_plans)(i, 1), (*_plans)(i, 2),
(*_plans)(i, 3), (*_plans)(i, 4), (*_plans)(i, 5)));
(*_plans)(i, 3) = tmpr->getXCenter();
(*_plans)(i, 4) = tmpr->getYCenter();
}
/* _moving_plans.reset(new FMatrix(1,6));
(*_moving_plans)(0,0) = &A;
(*_moving_plans)(0,1) = &B;
(*_moving_plans)(0,2) = &C;
(*_moving_plans)(0,3) = &DA;
(*_moving_plans)(0,4) = &DB;
(*_moving_plans)(0,5) = &DC;*/
SP::SiconosMatrix Disks;
Disks.reset(new SimpleMatrix("disks.dat", true));
// -- OneStepIntegrators --
SP::OneStepIntegrator osi;
osi.reset(new Moreau(theta));
// -- Model --
_model.reset(new Model(t0, T));
for (unsigned int i = 0; i < Disks->size(0); i++)
{
R = Disks->getValue(i, 2);
m = Disks->getValue(i, 3);
SP::SiconosVector qTmp;
SP::SiconosVector vTmp;
qTmp.reset(new SimpleVector(NDOF));
vTmp.reset(new SimpleVector(NDOF));
vTmp->zero();
(*qTmp)(0) = (*Disks)(i, 0);
(*qTmp)(1) = (*Disks)(i, 1);
SP::LagrangianDS body;
if (R > 0)
body.reset(new Disk(R, m, qTmp, vTmp));
else
body.reset(new Circle(-R, m, qTmp, vTmp));
// -- Set external forces (weight) --
SP::SimpleVector FExt;
FExt.reset(new SimpleVector(NDOF));
FExt->zero();
FExt->setValue(1, -m * g);
body->setFExtPtr(FExt);
// add the dynamical system to the one step integrator
osi->insertDynamicalSystem(body);
// add the dynamical system in the non smooth dynamical system
_model->nonSmoothDynamicalSystem()->insertDynamicalSystem(body);
}
_model->nonSmoothDynamicalSystem()->setSymmetric(true);
// ------------------
// --- Simulation ---
// ------------------
// -- Time discretisation --
timedisc_.reset(new TimeDiscretisation(t0, h));
// -- OneStepNsProblem --
osnspb_.reset(new FrictionContact(2));
osnspb_->numericsSolverOptions()->iparam[0] = 100; // Max number of
// iterations
osnspb_->numericsSolverOptions()->iparam[1] = 20; // compute error
// iterations
osnspb_->numericsSolverOptions()->dparam[0] = 1e-3; // Tolerance
osnspb_->setMaxSize(6 * ((3 * Ll * Ll + 3 * Ll) / 2 - Ll));
osnspb_->setMStorageType(1); // Sparse storage
osnspb_->setNumericsVerboseMode(0);
osnspb_->setKeepLambdaAndYState(true); // inject previous solution
// -- Simulation --
simulation_.reset(new TimeStepping(timedisc_));
boost::static_pointer_cast<TimeStepping>(simulation_)->setNewtonMaxIteration(3);
simulation_->insertIntegrator(osi);
simulation_->insertNonSmoothProblem(osnspb_);
simulation_->setCheckSolverFunction(localCheckSolverOuput);
// --- Simulation initialization ---
std::cout << "====> Simulation initialisation ..." << std::endl << std::endl;
SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(0, 0, 0.9, 2));
_playground.reset(new SpaceFilter(3, 6, _model->nonSmoothDynamicalSystem(), nslaw, _plans, _moving_plans));
_model->initialize(simulation_);
}
catch (SiconosException e)
{
std::cout << e.report() << std::endl;
exit(1);
}
catch (...)
{
std::cout << "Exception caught in Disks::init()" << std::endl;
exit(1);
}
}
// =========================== End of model definition ===========================
// ================================= Computation =================================
void Disks::compute()
{
try
{
_playground->buildInteractions(_model->currentTime());
_model->simulation()->updateInteractions();
_model->simulation()->advanceToEvent();
_model->simulation()->processEvents();
}
catch (SiconosException e)
{
std::cout << e.report() << std::endl;
}
catch (...)
{
std::cout << "Exception caught in SiconosBodies::compute()" << std::endl;
}
}
<commit_msg>tol=1e-3 maxiter=100000 ... still one failure<commit_after>/* Siconos-sample version 3.0.0, Copyright INRIA 2005-2008.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a 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.
* Siconos 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 Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY vincent.acary@inrialpes.fr
*/
/*!\file Disks.cpp
Some Disks (2D), friction, and walls.
Direct description of the model without XML input. Simulation with
a Time-Stepping scheme.
*/
// Siconos
#include <SiconosKernel.hpp>
#include <SiconosPointers.hpp>
#include "Disks.hpp"
using namespace std;
/* do nothing if solver does not converge */
void localCheckSolverOuput(int, Simulation*)
{};
double A(double t)
{
return 0. ;
}
double B(double t)
{
return 1. ;
}
double C(double t)
{
return 0.0;//1.1*cos(32.*M_PI*t) ;
}
double DA(double t)
{
return 0. ;
}
double DB(double t)
{
return 0. ;
}
double DC(double t)
{
return 0.0;//-1.1*32.*M_PI*sin(32.*M_PI*t) ;
}
// ================= Creation of the model =======================
void Disks::init()
{
SP::TimeDiscretisation timedisc_;
SP::TimeStepping simulation_;
SP::FrictionContact osnspb_;
// User-defined main parameters
double t0 = 0; // initial computation time
double T = 0.02;
double h = 0.01; // time step
double g = 9.81;
double theta = 0.5; // theta for Moreau integrator
std::string solverName = "NSGS";
// -----------------------------------------
// --- Dynamical systems && interactions ---
// -----------------------------------------
double R;
double m;
try
{
// ------------
// --- Init ---
// ------------
std::cout << "====> Model loading ..." << std::endl << std::endl;
_plans.reset(new SimpleMatrix("plans.dat", true));
if (_plans->size(0) == 0)
{
/* default plans */
double A1 = P1A;
double B1 = P1B;
double C1 = P1C;
double A2 = P2A;
double B2 = P2B;
double C2 = P2C;
_plans.reset(new SimpleMatrix(6, 6));
_plans->zero();
(*_plans)(0, 0) = 0;
(*_plans)(0, 1) = 1;
(*_plans)(0, 2) = -GROUND;
(*_plans)(1, 0) = 1;
(*_plans)(1, 1) = 0;
(*_plans)(1, 2) = WALL;
(*_plans)(2, 0) = 1;
(*_plans)(2, 1) = 0;
(*_plans)(2, 2) = -WALL;
(*_plans)(3, 0) = 0;
(*_plans)(3, 1) = 1;
(*_plans)(3, 2) = -TOP;
(*_plans)(4, 0) = A1;
(*_plans)(4, 1) = B1;
(*_plans)(4, 2) = C1;
(*_plans)(5, 0) = A2;
(*_plans)(5, 1) = B2;
(*_plans)(5, 2) = C2;
}
/* set center positions */
for (unsigned int i = 0 ; i < _plans->size(0); ++i)
{
SP::DiskPlanR tmpr;
tmpr.reset(new DiskPlanR(1, (*_plans)(i, 0), (*_plans)(i, 1), (*_plans)(i, 2),
(*_plans)(i, 3), (*_plans)(i, 4), (*_plans)(i, 5)));
(*_plans)(i, 3) = tmpr->getXCenter();
(*_plans)(i, 4) = tmpr->getYCenter();
}
/* _moving_plans.reset(new FMatrix(1,6));
(*_moving_plans)(0,0) = &A;
(*_moving_plans)(0,1) = &B;
(*_moving_plans)(0,2) = &C;
(*_moving_plans)(0,3) = &DA;
(*_moving_plans)(0,4) = &DB;
(*_moving_plans)(0,5) = &DC;*/
SP::SiconosMatrix Disks;
Disks.reset(new SimpleMatrix("disks.dat", true));
// -- OneStepIntegrators --
SP::OneStepIntegrator osi;
osi.reset(new Moreau(theta));
// -- Model --
_model.reset(new Model(t0, T));
for (unsigned int i = 0; i < Disks->size(0); i++)
{
R = Disks->getValue(i, 2);
m = Disks->getValue(i, 3);
SP::SiconosVector qTmp;
SP::SiconosVector vTmp;
qTmp.reset(new SimpleVector(NDOF));
vTmp.reset(new SimpleVector(NDOF));
vTmp->zero();
(*qTmp)(0) = (*Disks)(i, 0);
(*qTmp)(1) = (*Disks)(i, 1);
SP::LagrangianDS body;
if (R > 0)
body.reset(new Disk(R, m, qTmp, vTmp));
else
body.reset(new Circle(-R, m, qTmp, vTmp));
// -- Set external forces (weight) --
SP::SimpleVector FExt;
FExt.reset(new SimpleVector(NDOF));
FExt->zero();
FExt->setValue(1, -m * g);
body->setFExtPtr(FExt);
// add the dynamical system to the one step integrator
osi->insertDynamicalSystem(body);
// add the dynamical system in the non smooth dynamical system
_model->nonSmoothDynamicalSystem()->insertDynamicalSystem(body);
}
_model->nonSmoothDynamicalSystem()->setSymmetric(true);
// ------------------
// --- Simulation ---
// ------------------
// -- Time discretisation --
timedisc_.reset(new TimeDiscretisation(t0, h));
// -- OneStepNsProblem --
osnspb_.reset(new FrictionContact(2));
osnspb_->numericsSolverOptions()->iparam[0] = 100000; // Max number of
// iterations
osnspb_->numericsSolverOptions()->iparam[1] = 20; // compute error
// iterations
osnspb_->numericsSolverOptions()->dparam[0] = 1e-3; // Tolerance
osnspb_->setMaxSize(6 * ((3 * Ll * Ll + 3 * Ll) / 2 - Ll));
osnspb_->setMStorageType(1); // Sparse storage
osnspb_->setNumericsVerboseMode(0);
osnspb_->setKeepLambdaAndYState(true); // inject previous solution
// -- Simulation --
simulation_.reset(new TimeStepping(timedisc_));
boost::static_pointer_cast<TimeStepping>(simulation_)->setNewtonMaxIteration(3);
simulation_->insertIntegrator(osi);
simulation_->insertNonSmoothProblem(osnspb_);
simulation_->setCheckSolverFunction(localCheckSolverOuput);
// --- Simulation initialization ---
std::cout << "====> Simulation initialisation ..." << std::endl << std::endl;
SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(0, 0, 0.9, 2));
_playground.reset(new SpaceFilter(3, 6, _model->nonSmoothDynamicalSystem(), nslaw, _plans, _moving_plans));
_model->initialize(simulation_);
}
catch (SiconosException e)
{
std::cout << e.report() << std::endl;
exit(1);
}
catch (...)
{
std::cout << "Exception caught in Disks::init()" << std::endl;
exit(1);
}
}
// =========================== End of model definition ===========================
// ================================= Computation =================================
void Disks::compute()
{
try
{
_playground->buildInteractions(_model->currentTime());
_model->simulation()->updateInteractions();
_model->simulation()->advanceToEvent();
_model->simulation()->processEvents();
}
catch (SiconosException e)
{
std::cout << e.report() << std::endl;
}
catch (...)
{
std::cout << "Exception caught in SiconosBodies::compute()" << std::endl;
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Name : OOI CHOON HO
* Student ID : 4805604
* Coursework Title : CSCI336 Assignment 1
* Objecttive : Develop a simple 2D Paint program
*******************************************************************************/
#include <GL/glut.h>
#include <vector>
#include <iostream>
#include "Button.h"
const int MAX_BUTTON_COUNT = 8;
int windowWidth = 640;
int windowHeight = 480;
ShapeType shapeTypeSelected = NONE;
Vertex2F mouseDownPoint;
Vertex2F mouseUpPoint;
std::vector<Button*> ptrButtons;
Icon makeIcon(ShapeType shapeType, float width, float height, Vertex2F centerPoint) {
const double MATH_PI = 3.141592;
Icon icon;
icon.setCenterPoint(centerPoint);
icon.setHeight(height);
icon.setWidth(width);
float halfWidth = width / 2;
float halfHeight = height / 2;
Shape shape;
shape.setShapeType(shapeType);
switch (shapeType) {
case S_POINT:
shape.addVertex(centerPoint);
break;
case LINE:
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y + halfHeight));
break;
case TRIANGLE_F:
shape.setIsFilled(true);
case TRIANGLE:
shape.addVertex((centerPoint.x), (centerPoint.y + halfHeight));
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y - halfHeight));
break;
case RECTANGLE_F:
shape.setIsFilled(true);
case RECTANGLE:
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y + halfHeight));
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y + halfHeight));
break;
case OVAL_F:
shape.setIsFilled(true);
case OVAL:
float radiusX = halfWidth;
float radiusY = halfHeight / 2;
for (int i = 0; i < 360; i++) {
float angle = i * MATH_PI / 180;
shape.addVertex((centerPoint.x + (cos(angle) * radiusX)), (centerPoint.y + (sin(angle) * radiusY)));
}
break;
}
icon.setShape(shape);
return icon;
}
void initUIButton() {
const float BUTTON_HEIGHT = 70.0;
const float BUTTON_WIDTH = 70.0;
const float BUTTON_PADDING = 5.0;
const ShapeType SHAPE_TYPES[MAX_BUTTON_COUNT] = { S_POINT, LINE, TRIANGLE, TRIANGLE_F, RECTANGLE, RECTANGLE_F, OVAL, OVAL_F };
Vertex2F vertex;
vertex.x = 0.0f;
vertex.y = windowHeight - BUTTON_PADDING;
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
vertex.x += BUTTON_PADDING;
Button* ptrButton = new Button();
ptrButton->setWidth(BUTTON_WIDTH);
ptrButton->setHeight(BUTTON_HEIGHT);
ptrButton->addShapeType(SHAPE_TYPES[i]);
ptrButton->addShapeVertex(vertex.x + BUTTON_WIDTH, vertex.y);
ptrButton->addShapeVertex(vertex.x + BUTTON_WIDTH, vertex.y - BUTTON_HEIGHT);
ptrButton->addShapeVertex(vertex.x, vertex.y - BUTTON_HEIGHT);
ptrButton->addShapeVertex(vertex.x, vertex.y);
ptrButtons.push_back(ptrButton);
Vertex2F centerPoint;
centerPoint.x = vertex.x + (BUTTON_WIDTH / 2.0);
centerPoint.y = vertex.y - (BUTTON_HEIGHT / 2.0);
float iconHeight = BUTTON_HEIGHT - 20.0;
float iconWidth = BUTTON_WIDTH - 20.0;
ptrButton->setIcon(makeIcon(SHAPE_TYPES[i], iconWidth, iconHeight, centerPoint));
vertex.x += BUTTON_WIDTH;
}
}
void disposeUIButton() {
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
delete ptrButtons.back();
ptrButtons.pop_back();
}
}
void renderButton() {
glPointSize(2);
glLineWidth(2);
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
if (ptrButtons[i]->getShape().getShapeType() == shapeTypeSelected) {
glColor3f(1.0, 0.0, 0.0);
}
else {
glColor3f(0.0, 0.0, 0.0);
}
glBegin(GL_LINE_LOOP);
glVertex2f(ptrButtons[i]->getShape().getVertex(0).x, ptrButtons[i]->getShape().getVertex(0).y);
glVertex2f(ptrButtons[i]->getShape().getVertex(1).x, ptrButtons[i]->getShape().getVertex(1).y);
glVertex2f(ptrButtons[i]->getShape().getVertex(2).x, ptrButtons[i]->getShape().getVertex(2).y);
glVertex2f(ptrButtons[i]->getShape().getVertex(3).x, ptrButtons[i]->getShape().getVertex(3).y);
glEnd();
std::vector<Vertex2F> iconVertices = ptrButtons[i]->getIcon().getShape().getAllVertices();
glColor3f(0.0, 0.0, 0.0);
if (ptrButtons[i]->getIcon().getShape().getShapeType() == S_POINT) {
glBegin(GL_POINTS);
glVertex2f(iconVertices[0].x, iconVertices[0].y);
glEnd();
}
else {
if (ptrButtons[i]->getIcon().getShape().getIsFilled()) {
glBegin(GL_POLYGON);
for (int j = 0; j < iconVertices.size(); j++) {
glVertex2f(iconVertices[j].x, iconVertices[j].y);
}
glEnd();
}
else {
glBegin(GL_LINE_LOOP);
for (int j = 0; j < iconVertices.size(); j++) {
glVertex2f(iconVertices[j].x, iconVertices[j].y);
}
glEnd();
}
}
}
}
void setUIButtonClicked() {
std::cout << "Clicked" << std::endl;
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
Vertex2F topLeftPoint = ptrButtons[i]->getShape().getVertex(3);
Vertex2F bottomRightPoint = ptrButtons[i]->getShape().getVertex(1);
if ((mouseUpPoint.x > topLeftPoint.x && mouseUpPoint.x < bottomRightPoint.x) &&
(mouseUpPoint.y > bottomRightPoint.y && mouseUpPoint.y < topLeftPoint.y)) {
shapeTypeSelected = ptrButtons[i]->getShape().getShapeType();
}
}
}
void mouseClick(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON) {
if (state == GLUT_DOWN) {
mouseDownPoint.x = x;
mouseDownPoint.y = windowHeight - y;
}
if (state == GLUT_UP) {
mouseUpPoint.x = x;
mouseUpPoint.y = windowHeight - y;
}
}
}
void renderScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
setUIButtonClicked();
renderButton();
glFlush();
}
void reshapeScene(int width, int height) {
if (height == 0) {
height = 1;
}
float ratio = 1.0 * width / height;
windowWidth = width;
windowHeight = height;
disposeUIButton();
initUIButton();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, width, height);
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
}
void init(void) {
glClearColor(0.8, 0.8, 0.8, 0.0);
glColor3f(1.0f, 1.0f, 1.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, windowWidth, 0, windowHeight);
}
int main(int argc, char** argv) {
initUIButton();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH);
glutInitWindowPosition(100, 100);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("CSCI336-Assignment1 Simple Paint");
init();
glutDisplayFunc(renderScene);
glutReshapeFunc(reshapeScene);
glutMouseFunc(mouseClick);
glutMainLoop();
disposeUIButton();
return 0;
}<commit_msg>Renamed Button to UIButton; Minor change in renderUIButton function<commit_after>/*******************************************************************************
* Name : OOI CHOON HO
* Student ID : 4805604
* Coursework Title : CSCI336 Assignment 1
* Objecttive : Develop a simple 2D Paint program
*******************************************************************************/
#include <GL/glut.h>
#include <vector>
#include <iostream>
#include "Button.h"
const int MAX_BUTTON_COUNT = 8;
int windowWidth = 640;
int windowHeight = 480;
ShapeType shapeTypeSelected = NONE;
Vertex2F mouseDownPoint;
Vertex2F mouseUpPoint;
std::vector<Button*> ptrUIButtons;
Icon makeIcon(ShapeType shapeType, float width, float height, Vertex2F centerPoint) {
const double MATH_PI = 3.141592;
Icon icon;
icon.setCenterPoint(centerPoint);
icon.setHeight(height);
icon.setWidth(width);
float halfWidth = width / 2;
float halfHeight = height / 2;
Shape shape;
shape.setShapeType(shapeType);
switch (shapeType) {
case S_POINT:
shape.addVertex(centerPoint);
break;
case LINE:
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y + halfHeight));
break;
case TRIANGLE_F:
shape.setIsFilled(true);
case TRIANGLE:
shape.addVertex((centerPoint.x), (centerPoint.y + halfHeight));
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y - halfHeight));
break;
case RECTANGLE_F:
shape.setIsFilled(true);
case RECTANGLE:
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y + halfHeight));
shape.addVertex((centerPoint.x + halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y - halfHeight));
shape.addVertex((centerPoint.x - halfWidth), (centerPoint.y + halfHeight));
break;
case OVAL_F:
shape.setIsFilled(true);
case OVAL:
float radiusX = halfWidth;
float radiusY = halfHeight / 2;
for (int i = 0; i < 360; i++) {
float angle = i * MATH_PI / 180;
shape.addVertex((centerPoint.x + (cos(angle) * radiusX)), (centerPoint.y + (sin(angle) * radiusY)));
}
break;
}
icon.setShape(shape);
return icon;
}
void initUIButton() {
const float BUTTON_HEIGHT = 70.0;
const float BUTTON_WIDTH = 70.0;
const float BUTTON_PADDING = 5.0;
const ShapeType SHAPE_TYPES[MAX_BUTTON_COUNT] = { S_POINT, LINE, TRIANGLE, TRIANGLE_F, RECTANGLE, RECTANGLE_F, OVAL, OVAL_F };
Vertex2F vertex;
vertex.x = 0.0f;
vertex.y = windowHeight - BUTTON_PADDING;
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
vertex.x += BUTTON_PADDING;
Button* ptrUIButton = new Button();
ptrUIButton->setWidth(BUTTON_WIDTH);
ptrUIButton->setHeight(BUTTON_HEIGHT);
ptrUIButton->addShapeType(SHAPE_TYPES[i]);
ptrUIButton->addShapeVertex(vertex.x + BUTTON_WIDTH, vertex.y);
ptrUIButton->addShapeVertex(vertex.x + BUTTON_WIDTH, vertex.y - BUTTON_HEIGHT);
ptrUIButton->addShapeVertex(vertex.x, vertex.y - BUTTON_HEIGHT);
ptrUIButton->addShapeVertex(vertex.x, vertex.y);
ptrUIButtons.push_back(ptrUIButton);
Vertex2F centerPoint;
centerPoint.x = vertex.x + (BUTTON_WIDTH / 2.0);
centerPoint.y = vertex.y - (BUTTON_HEIGHT / 2.0);
float iconHeight = BUTTON_HEIGHT - 20.0;
float iconWidth = BUTTON_WIDTH - 20.0;
ptrUIButton->setIcon(makeIcon(SHAPE_TYPES[i], iconWidth, iconHeight, centerPoint));
vertex.x += BUTTON_WIDTH;
}
}
void disposeUIButton() {
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
delete ptrUIButtons.back();
ptrUIButtons.pop_back();
}
}
void renderUIButton() {
glPointSize(2);
glLineWidth(2);
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
std::vector<Vertex2F> buttonVertices = ptrUIButtons[i]->getShape().getAllVertices();
std::vector<Vertex2F> iconVertices = ptrUIButtons[i]->getIcon().getShape().getAllVertices();
if (ptrUIButtons[i]->getShape().getShapeType() == shapeTypeSelected) {
glColor3f(1.0, 0.0, 0.0);
}
else {
glColor3f(0.0, 0.0, 0.0);
}
glBegin(GL_LINE_LOOP);
for (int j = 0; j < buttonVertices.size(); j++) {
glVertex2f(buttonVertices[j].x, buttonVertices[j].y);
}
glEnd();
glColor3f(0.0, 0.0, 0.0);
if (ptrUIButtons[i]->getIcon().getShape().getShapeType() == S_POINT) {
glBegin(GL_POINTS);
glVertex2f(iconVertices[0].x, iconVertices[0].y);
glEnd();
}
else {
if (ptrUIButtons[i]->getIcon().getShape().getIsFilled()) {
glBegin(GL_POLYGON);
for (int j = 0; j < iconVertices.size(); j++) {
glVertex2f(iconVertices[j].x, iconVertices[j].y);
}
glEnd();
}
else {
glBegin(GL_LINE_LOOP);
for (int j = 0; j < iconVertices.size(); j++) {
glVertex2f(iconVertices[j].x, iconVertices[j].y);
}
glEnd();
}
}
}
}
void setUIButtonClicked() {
for (int i = 0; i < MAX_BUTTON_COUNT; i++) {
Vertex2F topLeftPoint = ptrUIButtons[i]->getShape().getVertex(3);
Vertex2F bottomRightPoint = ptrUIButtons[i]->getShape().getVertex(1);
if ((mouseUpPoint.x > topLeftPoint.x && mouseUpPoint.x < bottomRightPoint.x) &&
(mouseUpPoint.y > bottomRightPoint.y && mouseUpPoint.y < topLeftPoint.y)) {
shapeTypeSelected = ptrUIButtons[i]->getShape().getShapeType();
}
}
}
void mouseClick(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON) {
if (state == GLUT_DOWN) {
mouseDownPoint.x = x;
mouseDownPoint.y = windowHeight - y;
}
if (state == GLUT_UP) {
mouseUpPoint.x = x;
mouseUpPoint.y = windowHeight - y;
}
}
}
void renderScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
setUIButtonClicked();
renderUIButton();
glFlush();
}
void reshapeScene(int width, int height) {
if (height == 0) {
height = 1;
}
float ratio = 1.0 * width / height;
windowWidth = width;
windowHeight = height;
disposeUIButton();
initUIButton();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, width, height);
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
}
void init(void) {
glClearColor(0.8, 0.8, 0.8, 0.0);
glColor3f(1.0f, 1.0f, 1.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, windowWidth, 0, windowHeight);
}
int main(int argc, char** argv) {
initUIButton();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH);
glutInitWindowPosition(100, 100);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("CSCI336-Assignment1 Simple Paint");
init();
glutDisplayFunc(renderScene);
glutReshapeFunc(reshapeScene);
glutMouseFunc(mouseClick);
glutMainLoop();
disposeUIButton();
return 0;
}<|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: AliCorrQADataMakerRec.cxx 27570 2008-07-24 21:49:27Z cvetan $ */
/*
Produces the data needed to calculate the quality assurance.
All data must be mergeable objects.
Y. Schutz CERN July 2007
*/
// --- ROOT system ---
#include <TClonesArray.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TH2F.h>
#include <TNtupleD.h>
#include <TParameter.h>
#include <TMath.h>
// --- Standard library ---
// --- AliRoot header files ---
#include "AliLog.h"
#include "AliCorrQADataMakerRec.h"
#include "AliQAChecker.h"
ClassImp(AliCorrQADataMakerRec)
//____________________________________________________________________________
AliCorrQADataMakerRec::AliCorrQADataMakerRec(AliQADataMaker ** qadm ) :
AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kCORR), "Corr Quality Assurance Data Maker"),
fMaxRawVar(0),
fqadm(qadm)
{
// ctor
fCorrNt = new TNtupleD *[AliRecoParam::kNSpecies] ;
for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++)
fCorrNt[specie] = NULL ;
}
//____________________________________________________________________________
AliCorrQADataMakerRec::AliCorrQADataMakerRec(const AliCorrQADataMakerRec& qadm) :
AliQADataMakerRec(),
fMaxRawVar(qadm.fMaxRawVar),
fqadm(qadm.fqadm)
{
//copy ctor
SetName((const char*)qadm.GetName()) ;
SetTitle((const char*)qadm.GetTitle());
}
//__________________________________________________________________
AliCorrQADataMakerRec& AliCorrQADataMakerRec::operator = (const AliCorrQADataMakerRec& qadm )
{
// assign operator.
this->~AliCorrQADataMakerRec();
new(this) AliCorrQADataMakerRec(qadm);
return *this;
}
//____________________________________________________________________________
AliCorrQADataMakerRec::~AliCorrQADataMakerRec()
{
// dtor only destroy the ntuple
if ( fCorrNt ) {
for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) {
if ( fCorrNt[specie] != NULL )
delete fCorrNt[specie] ;
}
delete[] fCorrNt ;
fCorrNt = 0x0;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::EndOfDetectorCycle(AliQAv1::TASKINDEX_t task, TObjArray ** /*list*/)
{
//Detector specific actions at end of cycle
// do the QA checking
if (task == AliQAv1::kRAWS) {
AliQAChecker::Instance()->Run(AliQAv1::kCORR, task, fCorrNt) ;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::InitESDs()
{
//Create histograms to controll ESD
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::InitRecPoints()
{
// create Reconstructed Points histograms in RecPoints subdir
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::InitRaws()
{
// createa ntuple taking all the parameters declared by detectors
if (fCorrNt[AliRecoParam::AConvert(fEventSpecie)])
return ;
delete fRawsQAList ; // not needed for the time being
fRawsQAList = NULL ;
TString varlist("") ;
for ( Int_t detIndex = 0 ; detIndex < AliQAv1::kNDET ; detIndex++ ) {
AliQADataMaker * qadm = fqadm[detIndex] ;
if ( ! qadm )
continue ;
TList * list = qadm->GetParameterList() ;
if (list) {
TIter next(list) ;
TParameter<double> * p ;
while ( (p = static_cast<TParameter<double>*>(next()) ) ) {
varlist.Append(p->GetName()) ;
varlist.Append(":") ;
fMaxRawVar++ ;
}
}
}
varlist = varlist.Strip(TString::kTrailing, ':') ;
if (fMaxRawVar == 0) {
AliWarning("NTUPLE not created") ;
} else {
char * name = Form("%s_%s", AliQAv1::GetQACorrName(), AliRecoParam::GetEventSpecieName(fEventSpecie)) ;
fCorrNt[AliRecoParam::AConvert(fEventSpecie)] = new TNtupleD(name, "Raws data correlation among detectors", varlist.Data()) ;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::MakeESDs(AliESDEvent * /*esd*/)
{
// make QA data from ESDs
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::MakeRaws(AliRawReader *)
{
//Fill prepared histograms with Raw digit properties
if ( ! fCorrNt[AliRecoParam::AConvert(fEventSpecie)])
InitRaws() ;
if ( fMaxRawVar > 0 ) {
const Int_t kSize = fMaxRawVar ;
Double_t *varvalue = new Double_t[kSize] ;
Int_t index = 0 ;
for ( Int_t detIndex = 0 ; detIndex < AliQAv1::kNDET ; detIndex++ ) {
AliQADataMaker * qadm = fqadm[detIndex] ;
if ( ! qadm )
continue ;
TList * list = qadm->GetParameterList() ;
TIter next(list) ;
TParameter<double> * p ;
while ( (p = static_cast<TParameter<double>*>(next()) ) ) {
varvalue[index++] = p->GetVal() ;
}
}
static_cast<TNtupleD*>(fCorrNt[AliRecoParam::AConvert(fEventSpecie)])->Fill(varvalue);
delete [] varvalue;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::MakeRecPoints(TTree * /*clustersTree*/)
{
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::StartOfDetectorCycle()
{
//Detector specific actions at start of cycle
}
<commit_msg>remove delete of TNutple in fCorrNt. It is deleted when file to which it is save is closed<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: AliCorrQADataMakerRec.cxx 27570 2008-07-24 21:49:27Z cvetan $ */
/*
Produces the data needed to calculate the quality assurance.
All data must be mergeable objects.
Y. Schutz CERN July 2007
*/
// --- ROOT system ---
#include <TClonesArray.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TH2F.h>
#include <TNtupleD.h>
#include <TParameter.h>
#include <TMath.h>
// --- Standard library ---
// --- AliRoot header files ---
#include "AliLog.h"
#include "AliCorrQADataMakerRec.h"
#include "AliQAChecker.h"
ClassImp(AliCorrQADataMakerRec)
//____________________________________________________________________________
AliCorrQADataMakerRec::AliCorrQADataMakerRec(AliQADataMaker ** qadm ) :
AliQADataMakerRec(AliQAv1::GetDetName(AliQAv1::kCORR), "Corr Quality Assurance Data Maker"),
fMaxRawVar(0),
fqadm(qadm)
{
// ctor
fCorrNt = new TNtupleD *[AliRecoParam::kNSpecies] ;
for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++)
fCorrNt[specie] = NULL ;
}
//____________________________________________________________________________
AliCorrQADataMakerRec::AliCorrQADataMakerRec(const AliCorrQADataMakerRec& qadm) :
AliQADataMakerRec(),
fMaxRawVar(qadm.fMaxRawVar),
fqadm(qadm.fqadm)
{
//copy ctor
SetName((const char*)qadm.GetName()) ;
SetTitle((const char*)qadm.GetTitle());
}
//__________________________________________________________________
AliCorrQADataMakerRec& AliCorrQADataMakerRec::operator = (const AliCorrQADataMakerRec& qadm )
{
// assign operator.
this->~AliCorrQADataMakerRec();
new(this) AliCorrQADataMakerRec(qadm);
return *this;
}
//____________________________________________________________________________
AliCorrQADataMakerRec::~AliCorrQADataMakerRec()
{
// dtor only destroy the ntuple
if ( fCorrNt ) {
// for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) {
// if ( fCorrNt[specie] != NULL )
// delete fCorrNt[specie] ;
// }
delete[] fCorrNt ;
fCorrNt = 0x0;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::EndOfDetectorCycle(AliQAv1::TASKINDEX_t task, TObjArray ** /*list*/)
{
//Detector specific actions at end of cycle
// do the QA checking
if (task == AliQAv1::kRAWS) {
AliQAChecker::Instance()->Run(AliQAv1::kCORR, task, fCorrNt) ;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::InitESDs()
{
//Create histograms to controll ESD
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::InitRecPoints()
{
// create Reconstructed Points histograms in RecPoints subdir
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::InitRaws()
{
// createa ntuple taking all the parameters declared by detectors
if (fCorrNt[AliRecoParam::AConvert(fEventSpecie)])
return ;
delete fRawsQAList ; // not needed for the time being
fRawsQAList = NULL ;
TString varlist("") ;
for ( Int_t detIndex = 0 ; detIndex < AliQAv1::kNDET ; detIndex++ ) {
AliQADataMaker * qadm = fqadm[detIndex] ;
if ( ! qadm )
continue ;
TList * list = qadm->GetParameterList() ;
if (list) {
TIter next(list) ;
TParameter<double> * p ;
while ( (p = static_cast<TParameter<double>*>(next()) ) ) {
varlist.Append(p->GetName()) ;
varlist.Append(":") ;
fMaxRawVar++ ;
}
}
}
varlist = varlist.Strip(TString::kTrailing, ':') ;
if (fMaxRawVar == 0) {
AliWarning("NTUPLE not created") ;
} else {
char * name = Form("%s_%s", AliQAv1::GetQACorrName(), AliRecoParam::GetEventSpecieName(fEventSpecie)) ;
fCorrNt[AliRecoParam::AConvert(fEventSpecie)] = new TNtupleD(name, "Raws data correlation among detectors", varlist.Data()) ;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::MakeESDs(AliESDEvent * /*esd*/)
{
// make QA data from ESDs
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::MakeRaws(AliRawReader *)
{
//Fill prepared histograms with Raw digit properties
if ( ! fCorrNt[AliRecoParam::AConvert(fEventSpecie)])
InitRaws() ;
if ( fMaxRawVar > 0 ) {
const Int_t kSize = fMaxRawVar ;
Double_t *varvalue = new Double_t[kSize] ;
Int_t index = 0 ;
for ( Int_t detIndex = 0 ; detIndex < AliQAv1::kNDET ; detIndex++ ) {
AliQADataMaker * qadm = fqadm[detIndex] ;
if ( ! qadm )
continue ;
TList * list = qadm->GetParameterList() ;
TIter next(list) ;
TParameter<double> * p ;
while ( (p = static_cast<TParameter<double>*>(next()) ) ) {
varvalue[index++] = p->GetVal() ;
}
}
static_cast<TNtupleD*>(fCorrNt[AliRecoParam::AConvert(fEventSpecie)])->Fill(varvalue);
delete [] varvalue;
}
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::MakeRecPoints(TTree * /*clustersTree*/)
{
AliInfo("TO BE IMPLEMENTED") ;
}
//____________________________________________________________________________
void AliCorrQADataMakerRec::StartOfDetectorCycle()
{
//Detector specific actions at start of cycle
}
<|endoftext|> |
<commit_before>//===--- Options.cpp - Option info table --------------------------------*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Options.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Option.h"
#include <algorithm>
#include <cassert>
using namespace clang::driver;
using namespace clang::driver::options;
// Ordering on Info. The ordering is *almost* lexicographic, with two
// exceptions. First, '\0' comes at the end of the alphabet instead of
// the beginning (thus options preceed any other options which prefix
// them). Second, for options with the same name, the less permissive
// version should come first; a Flag option should preceed a Joined
// option, for example.
static int StrCmpOptionName(const char *A, const char *B) {
char a = *A, b = *B;
while (a == b) {
if (a == '\0')
return 0;
a = *++A;
b = *++B;
}
if (a == '\0') // A is a prefix of B.
return 1;
if (b == '\0') // B is a prefix of A.
return -1;
// Otherwise lexicographic.
return (a < b) ? -1 : 1;
}
static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
if (&A == &B)
return false;
if (int N = StrCmpOptionName(A.Name, B.Name))
return N == -1;
// Names are the same, check that classes are in order; exactly one
// should be joined, and it should succeed the other.
assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
"Unexpected classes for options with same name.");
return B.Kind == Option::JoinedClass;
}
//
OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos)
: OptionInfos(_OptionInfos), NumOptionInfos(_NumOptionInfos),
Options(new Option*[NumOptionInfos]),
TheInputOption(0), TheUnknownOption(0), FirstSearchableIndex(0)
{
// Explicitly zero initialize the error to work around a bug in array
// value-initialization on MinGW with gcc 4.3.5.
memset(Options, 0, sizeof(*Options) * NumOptionInfos);
// Find start of normal options.
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Kind = getInfo(i + 1).Kind;
if (Kind == Option::InputClass) {
assert(!TheInputOption && "Cannot have multiple input options!");
TheInputOption = getOption(i + 1);
} else if (Kind == Option::UnknownClass) {
assert(!TheUnknownOption && "Cannot have multiple input options!");
TheUnknownOption = getOption(i + 1);
} else if (Kind != Option::GroupClass) {
FirstSearchableIndex = i;
break;
}
}
assert(FirstSearchableIndex != 0 && "No searchable options?");
#ifndef NDEBUG
// Check that everything after the first searchable option is a
// regular option class.
for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
Kind != Option::GroupClass) &&
"Special options should be defined first!");
}
// Check that options are in order.
for (unsigned i = FirstSearchableIndex+1, e = getNumOptions(); i != e; ++i) {
if (!(getInfo(i) < getInfo(i + 1))) {
getOption(i)->dump();
getOption(i + 1)->dump();
assert(0 && "Options are not in order!");
}
}
#endif
}
OptTable::~OptTable() {
for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
delete Options[i];
delete[] Options;
}
Option *OptTable::CreateOption(unsigned id) const {
const Info &info = getInfo(id);
const OptionGroup *Group =
cast_or_null<OptionGroup>(getOption(info.GroupID));
const Option *Alias = getOption(info.AliasID);
Option *Opt = 0;
switch (info.Kind) {
case Option::InputClass:
Opt = new InputOption(); break;
case Option::UnknownClass:
Opt = new UnknownOption(); break;
case Option::GroupClass:
Opt = new OptionGroup(id, info.Name, Group); break;
case Option::FlagClass:
Opt = new FlagOption(id, info.Name, Group, Alias); break;
case Option::JoinedClass:
Opt = new JoinedOption(id, info.Name, Group, Alias); break;
case Option::SeparateClass:
Opt = new SeparateOption(id, info.Name, Group, Alias); break;
case Option::CommaJoinedClass:
Opt = new CommaJoinedOption(id, info.Name, Group, Alias); break;
case Option::MultiArgClass:
Opt = new MultiArgOption(id, info.Name, Group, Alias, info.Param); break;
case Option::JoinedOrSeparateClass:
Opt = new JoinedOrSeparateOption(id, info.Name, Group, Alias); break;
case Option::JoinedAndSeparateClass:
Opt = new JoinedAndSeparateOption(id, info.Name, Group, Alias); break;
}
if (info.Flags & DriverOption)
Opt->setDriverOption(true);
if (info.Flags & LinkerInput)
Opt->setLinkerInput(true);
if (info.Flags & NoArgumentUnused)
Opt->setNoArgumentUnused(true);
if (info.Flags & RenderAsInput)
Opt->setNoOptAsInput(true);
if (info.Flags & RenderJoined) {
assert(info.Kind == Option::SeparateClass && "Invalid option.");
Opt->setForceJoinedRender(true);
}
if (info.Flags & RenderSeparate) {
assert(info.Kind == Option::JoinedClass && "Invalid option.");
Opt->setForceSeparateRender(true);
}
if (info.Flags & Unsupported)
Opt->setUnsupported(true);
return Opt;
}
// Support lower_bound between info and an option name.
namespace clang {
namespace driver {
static inline bool operator<(const OptTable::Info &I, const char *Name) {
return StrCmpOptionName(I.Name, Name) == -1;
}
static inline bool operator<(const char *Name, const OptTable::Info &I) {
return StrCmpOptionName(Name, I.Name) == -1;
}
}
}
Arg *OptTable::ParseOneArg(const InputArgList &Args, unsigned &Index) const {
unsigned Prev = Index;
const char *Str = Args.getArgString(Index);
// Anything that doesn't start with '-' is an input, as is '-' itself.
if (Str[0] != '-' || Str[1] == '\0')
return new PositionalArg(TheInputOption, Index++);
const Info *Start = OptionInfos + FirstSearchableIndex;
const Info *End = OptionInfos + LastOption - 1;
// Search for the first next option which could be a prefix.
Start = std::lower_bound(Start, End, Str);
// Options are stored in sorted order, with '\0' at the end of the
// alphabet. Since the only options which can accept a string must
// prefix it, we iteratively search for the next option which could
// be a prefix.
//
// FIXME: This is searching much more than necessary, but I am
// blanking on the simplest way to make it fast. We can solve this
// problem when we move to TableGen.
for (; Start != End; ++Start) {
// Scan for first option which is a proper prefix.
for (; Start != End; ++Start)
if (memcmp(Str, Start->Name, strlen(Start->Name)) == 0)
break;
if (Start == End)
break;
// See if this option matches.
options::ID id = (options::ID) (Start - OptionInfos + 1);
if (Arg *A = getOption(id)->accept(Args, Index))
return A;
// Otherwise, see if this argument was missing values.
if (Prev != Index)
return 0;
}
return new PositionalArg(TheUnknownOption, Index++);
}
//
static OptTable::Info InfoTable[] = {
// The InputOption info
{ "<input>", 0, 0, Option::InputClass, DriverOption, 0, OPT_INVALID, OPT_INVALID },
// The UnknownOption info
{ "<unknown>", 0, 0, Option::UnknownClass, 0, 0, OPT_INVALID, OPT_INVALID },
#define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ NAME, HELPTEXT, METAVAR, Option::KIND##Class, FLAGS, PARAM, \
OPT_##GROUP, OPT_##ALIAS },
#include "clang/Driver/Options.def"
};
namespace {
class DriverOptTable : public OptTable {
public:
DriverOptTable()
: OptTable(InfoTable, sizeof(InfoTable) / sizeof(InfoTable[0])) {}
};
}
OptTable *clang::driver::createDriverOptTable() {
return new DriverOptTable();
}
<commit_msg>Make MSVC happy.<commit_after>//===--- Options.cpp - Option info table --------------------------------*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Options.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Option.h"
#include <algorithm>
#include <cassert>
using namespace clang::driver;
using namespace clang::driver::options;
// Ordering on Info. The ordering is *almost* lexicographic, with two
// exceptions. First, '\0' comes at the end of the alphabet instead of
// the beginning (thus options preceed any other options which prefix
// them). Second, for options with the same name, the less permissive
// version should come first; a Flag option should preceed a Joined
// option, for example.
static int StrCmpOptionName(const char *A, const char *B) {
char a = *A, b = *B;
while (a == b) {
if (a == '\0')
return 0;
a = *++A;
b = *++B;
}
if (a == '\0') // A is a prefix of B.
return 1;
if (b == '\0') // B is a prefix of A.
return -1;
// Otherwise lexicographic.
return (a < b) ? -1 : 1;
}
namespace clang {
namespace driver {
static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
if (&A == &B)
return false;
if (int N = StrCmpOptionName(A.Name, B.Name))
return N == -1;
// Names are the same, check that classes are in order; exactly one
// should be joined, and it should succeed the other.
assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
"Unexpected classes for options with same name.");
return B.Kind == Option::JoinedClass;
}
// Support lower_bound between info and an option name.
static inline bool operator<(const OptTable::Info &I, const char *Name) {
return StrCmpOptionName(I.Name, Name) == -1;
}
static inline bool operator<(const char *Name, const OptTable::Info &I) {
return StrCmpOptionName(Name, I.Name) == -1;
}
}
}
//
OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos)
: OptionInfos(_OptionInfos), NumOptionInfos(_NumOptionInfos),
Options(new Option*[NumOptionInfos]),
TheInputOption(0), TheUnknownOption(0), FirstSearchableIndex(0)
{
// Explicitly zero initialize the error to work around a bug in array
// value-initialization on MinGW with gcc 4.3.5.
memset(Options, 0, sizeof(*Options) * NumOptionInfos);
// Find start of normal options.
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Kind = getInfo(i + 1).Kind;
if (Kind == Option::InputClass) {
assert(!TheInputOption && "Cannot have multiple input options!");
TheInputOption = getOption(i + 1);
} else if (Kind == Option::UnknownClass) {
assert(!TheUnknownOption && "Cannot have multiple input options!");
TheUnknownOption = getOption(i + 1);
} else if (Kind != Option::GroupClass) {
FirstSearchableIndex = i;
break;
}
}
assert(FirstSearchableIndex != 0 && "No searchable options?");
#ifndef NDEBUG
// Check that everything after the first searchable option is a
// regular option class.
for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
Kind != Option::GroupClass) &&
"Special options should be defined first!");
}
// Check that options are in order.
for (unsigned i = FirstSearchableIndex+1, e = getNumOptions(); i != e; ++i) {
if (!(getInfo(i) < getInfo(i + 1))) {
getOption(i)->dump();
getOption(i + 1)->dump();
assert(0 && "Options are not in order!");
}
}
#endif
}
OptTable::~OptTable() {
for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
delete Options[i];
delete[] Options;
}
Option *OptTable::CreateOption(unsigned id) const {
const Info &info = getInfo(id);
const OptionGroup *Group =
cast_or_null<OptionGroup>(getOption(info.GroupID));
const Option *Alias = getOption(info.AliasID);
Option *Opt = 0;
switch (info.Kind) {
case Option::InputClass:
Opt = new InputOption(); break;
case Option::UnknownClass:
Opt = new UnknownOption(); break;
case Option::GroupClass:
Opt = new OptionGroup(id, info.Name, Group); break;
case Option::FlagClass:
Opt = new FlagOption(id, info.Name, Group, Alias); break;
case Option::JoinedClass:
Opt = new JoinedOption(id, info.Name, Group, Alias); break;
case Option::SeparateClass:
Opt = new SeparateOption(id, info.Name, Group, Alias); break;
case Option::CommaJoinedClass:
Opt = new CommaJoinedOption(id, info.Name, Group, Alias); break;
case Option::MultiArgClass:
Opt = new MultiArgOption(id, info.Name, Group, Alias, info.Param); break;
case Option::JoinedOrSeparateClass:
Opt = new JoinedOrSeparateOption(id, info.Name, Group, Alias); break;
case Option::JoinedAndSeparateClass:
Opt = new JoinedAndSeparateOption(id, info.Name, Group, Alias); break;
}
if (info.Flags & DriverOption)
Opt->setDriverOption(true);
if (info.Flags & LinkerInput)
Opt->setLinkerInput(true);
if (info.Flags & NoArgumentUnused)
Opt->setNoArgumentUnused(true);
if (info.Flags & RenderAsInput)
Opt->setNoOptAsInput(true);
if (info.Flags & RenderJoined) {
assert(info.Kind == Option::SeparateClass && "Invalid option.");
Opt->setForceJoinedRender(true);
}
if (info.Flags & RenderSeparate) {
assert(info.Kind == Option::JoinedClass && "Invalid option.");
Opt->setForceSeparateRender(true);
}
if (info.Flags & Unsupported)
Opt->setUnsupported(true);
return Opt;
}
Arg *OptTable::ParseOneArg(const InputArgList &Args, unsigned &Index) const {
unsigned Prev = Index;
const char *Str = Args.getArgString(Index);
// Anything that doesn't start with '-' is an input, as is '-' itself.
if (Str[0] != '-' || Str[1] == '\0')
return new PositionalArg(TheInputOption, Index++);
const Info *Start = OptionInfos + FirstSearchableIndex;
const Info *End = OptionInfos + LastOption - 1;
// Search for the first next option which could be a prefix.
Start = std::lower_bound(Start, End, Str);
// Options are stored in sorted order, with '\0' at the end of the
// alphabet. Since the only options which can accept a string must
// prefix it, we iteratively search for the next option which could
// be a prefix.
//
// FIXME: This is searching much more than necessary, but I am
// blanking on the simplest way to make it fast. We can solve this
// problem when we move to TableGen.
for (; Start != End; ++Start) {
// Scan for first option which is a proper prefix.
for (; Start != End; ++Start)
if (memcmp(Str, Start->Name, strlen(Start->Name)) == 0)
break;
if (Start == End)
break;
// See if this option matches.
options::ID id = (options::ID) (Start - OptionInfos + 1);
if (Arg *A = getOption(id)->accept(Args, Index))
return A;
// Otherwise, see if this argument was missing values.
if (Prev != Index)
return 0;
}
return new PositionalArg(TheUnknownOption, Index++);
}
//
static OptTable::Info InfoTable[] = {
// The InputOption info
{ "<input>", 0, 0, Option::InputClass, DriverOption, 0, OPT_INVALID, OPT_INVALID },
// The UnknownOption info
{ "<unknown>", 0, 0, Option::UnknownClass, 0, 0, OPT_INVALID, OPT_INVALID },
#define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ NAME, HELPTEXT, METAVAR, Option::KIND##Class, FLAGS, PARAM, \
OPT_##GROUP, OPT_##ALIAS },
#include "clang/Driver/Options.def"
};
namespace {
class DriverOptTable : public OptTable {
public:
DriverOptTable()
: OptTable(InfoTable, sizeof(InfoTable) / sizeof(InfoTable[0])) {}
};
}
OptTable *clang::driver::createDriverOptTable() {
return new DriverOptTable();
}
<|endoftext|> |
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <gadget/gadgetConfig.h>
#include <vpr/vpr.h>
#include <gadget/Type/DeviceFactory.h>
// Platform-independent devices.
#include <gadget/Devices/Ascension/MotionStar.h>
// Sims
#include <gadget/Devices/Sim/SimAnalog.h>
#include <gadget/Devices/Sim/SimDigital.h>
#include <gadget/Devices/Sim/SimPosition.h>
#include <gadget/Devices/Sim/SimGloveGesture.h>
//#include <gadget/Devices/Sim/SimKeyboardDigital.h>
#include <gadget/Devices/Sim/SimRelativePosition.h>
#include <gadget/Devices/Sim/SimSetablePosition.h>
#include <gadget/Devices/Sim/SimDigitalGlove.h>
// RemoteInputManager Dependency Checker
#include <jccl/Plugins/ConfigManager/DependencyManager.h>
#include <gadget/RemoteInputManager/RmtMgrDepChecker.h>
/* Physical devices */
#ifndef VPR_OS_Win32
# include <gadget/Devices/Ascension/Flock.h>
# include <gadget/Devices/Intersense/Intersense.h>
# ifdef VPR_OS_Darwin
# include <gadget/Devices/Keyboard/OSXKeyboard.h>
# else
# include <gadget/Devices/Immersion/Ibox.h>
//# include <gadget/Devices/VirtualTechnologies/CyberGlove.h>
# include <gadget/Devices/Fakespace/PinchGlove.h>
# include <gadget/Devices/Keyboard/KeyboardXWin.h>
# include <gadget/Devices/Keyboard/KeyboardDepCheckerXWin.h>
# include <gadget/Devices/Open/Trackd/TrackdController.h>
# include <gadget/Devices/Open/Trackd/TrackdSensor.h>
# endif
# include <gadget/Devices/Logitech/logiclass.h>
#else
# include <gadget/Devices/Keyboard/KeyboardWin32.h>
#endif
/* PThread Dependant Driver */
#ifdef GADGET_HAVE_DTK
# include <gadget/Devices/Open/DTK/DTK.h>
#endif
#include <typeinfo>
namespace gadget
{
// Initialize the singleton ptr
//vjDeviceFactory* DeviceFactory::mInstance = NULL;
//vjSingletonImp( DeviceFactory ); //kevin
vprSingletonImpWithInitFunc( DeviceFactory, hackLoadKnownDevices );
template <class DEV>
DeviceConstructor<DEV>::DeviceConstructor()
{
vprASSERT(DeviceFactory::instance() != NULL);
DeviceFactory::instance()->registerDevice(this);
}
// Register all the devices that I know about
//!NOTE: This should really be moved to dynamic library loading code.
void DeviceFactory::hackLoadKnownDevices()
{
// NOTE: These will all given unused variable errors in compiling.
// That is okay, because the don't actually have to do anything.
// They just register themselves in their constructor.
// Platform-independent devices.
DeviceConstructor<MotionStar>* motion_star = new DeviceConstructor<MotionStar>;
DeviceConstructor<SimAnalog>* sim_analog = new DeviceConstructor<SimAnalog>;
DeviceConstructor<SimDigital>* sim_digital = new DeviceConstructor<SimDigital>;
DeviceConstructor<SimPosition>* sim_position = new DeviceConstructor<SimPosition>;
//vjDeviceConstructor<SimKeyboardDigital>* sim_keyboard_digital = new DeviceConstructor<SimKeyboardDigital>;
DeviceConstructor<SimSetablePosition>* sim_setable = new DeviceConstructor<SimSetablePosition>;
DeviceConstructor<SimRelativePosition>* sim_relative = new DeviceConstructor<SimRelativePosition>;
DeviceConstructor<SimGloveGesture>* sim_glove = new DeviceConstructor<SimGloveGesture>;
DeviceConstructor<SimDigitalGlove>* simpinch_glove = new DeviceConstructor<SimDigitalGlove>;
if( (NULL == sim_analog) ||
(NULL == sim_digital) ||
(NULL == sim_position) ||
(NULL == sim_glove) ||
(NULL == simpinch_glove) ||
(NULL == sim_setable) ||
(NULL == sim_relative) )
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
jccl::DependencyManager::instance()->registerChecker(new RmtMgrDepChecker());
#ifndef VPR_OS_Win32
#ifdef VPR_OS_Darwin
DeviceConstructor<OSXKeyboard>* osx_keyboard = new DeviceConstructor<OSXKeyboard>;
if( (NULL == osx_keyboard) )
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#else
DeviceConstructor<TrackdSensor>* trackd_sensor = new DeviceConstructor<TrackdSensor>;
DeviceConstructor<TrackdController>* trackd_controller = new DeviceConstructor<TrackdController>;
DeviceConstructor<IBox>* ibox = new DeviceConstructor<IBox>;
DeviceConstructor<PinchGlove>* pinch_glove = new DeviceConstructor<PinchGlove>;
// DeviceConstructor<CyberGlove>* cyber_glove = new DeviceConstructor<CyberGlove>;
DeviceConstructor<KeyboardXWin>* xwin_key = new DeviceConstructor<KeyboardXWin>;
jccl::DependencyManager::instance()->registerChecker(new KeyboardDepCheckerXWin());
DeviceConstructor<ThreeDMouse>* threed_mouse = new DeviceConstructor<ThreeDMouse>;
if( (NULL == trackd_sensor) ||
(NULL == trackd_controller) ||
(NULL == ibox) ||
(NULL == pinch_glove) ||
// (NULL == cyber_glove) ||
(NULL == xwin_key) ||
(NULL == threed_mouse))
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#endif
DeviceConstructor<Flock>* flock = new DeviceConstructor<Flock>;
DeviceConstructor<Intersense>* intersense = new DeviceConstructor<Intersense>;
if( (NULL == flock) ||
(NULL == intersense) ||
(NULL == motion_star) )
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#else
DeviceConstructor<KeyboardWin32>* key_win32 = new DeviceConstructor<KeyboardWin32>;
if( (NULL == key_win32))
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#endif
#ifdef GADGET_HAVE_DTK
DeviceConstructor<DTK>* dtk_wrapper = new DeviceConstructor<DTK>;
if( (NULL == dtk_wrapper))
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#endif
}
void DeviceFactory::registerDevice(DeviceConstructorBase* constructor)
{
vprASSERT(constructor != NULL);
mConstructors.push_back(constructor); // Add the constructor to the list
vprDEBUG(gadgetDBG_INPUT_MGR,1)
<< "gadget::DeviceFactory: Registered: "
<< std::setiosflags(std::ios::right) << std::setw(25)
<< std::setfill(' ') << constructor->getChunkType()
<< std::setiosflags(std::ios::right)
//<< " :" << (void*)constructor
<< " type: " << typeid(*constructor).name() << std::endl
<< vprDEBUG_FLUSH;
}
// Simply query all device constructors registered looking
// for one that knows how to load the device
bool DeviceFactory::recognizeDevice(jccl::ConfigChunkPtr chunk)
{
if(findConstructor(chunk) == -1)
return false;
else
return true;
}
//: Load the specified device
//!PRE: recognizeDevice(chunk) == true
//!ARGS: chunk - specification of the device to load
//!RETURNS: null - Device failed to load
//+ other - Pointer to the loaded device
Input* DeviceFactory::loadDevice(jccl::ConfigChunkPtr chunk)
{
vprASSERT(recognizeDevice(chunk));
int index = findConstructor(chunk);
Input* new_dev;
DeviceConstructorBase* constructor = mConstructors[index];
vprDEBUG(gadgetDBG_INPUT_MGR,3)
<< "gadget::DeviceFactory::loadDevice: Loading device: "
<< chunk->getType() << " with: " << typeid(*constructor).name()
<< std::endl << vprDEBUG_FLUSH;
new_dev = constructor->createDevice(chunk);
return new_dev;
}
int DeviceFactory::findConstructor(jccl::ConfigChunkPtr chunk)
{
std::string chunk_type;
chunk_type = (std::string)chunk->getType();
for(unsigned int i=0;i<mConstructors.size();i++)
{
// Get next constructor
DeviceConstructorBase* construct = mConstructors[i];
vprASSERT(construct != NULL);
if(construct->getChunkType() == chunk_type)
return i;
}
return -1;
}
void DeviceFactory::debugDump()
{
vprDEBUG_BEGIN(gadgetDBG_INPUT_MGR,0)
<< "gadget::DeviceFactory::debugDump\n" << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_INPUT_MGR,0) << "num constructors:"
<< mConstructors.size() << "\n"
<< vprDEBUG_FLUSH;
for(unsigned int cNum=0;cNum<mConstructors.size();cNum++)
{
DeviceConstructorBase* dev_constr = mConstructors[cNum];
vprDEBUG(gadgetDBG_INPUT_MGR,0)
<< cNum << ": Constructor:" << (void*)dev_constr
<< " type:" << typeid(*dev_constr).name() << "\n" << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_INPUT_MGR,0) << " recog:"
<< dev_constr->getChunkType() << "\n"
<< vprDEBUG_FLUSH;
}
vprDEBUG_END(gadgetDBG_INPUT_MGR,0) << "------ END DUMP ------\n"
<< vprDEBUG_FLUSH;
}
};
<commit_msg>Bug fixed: The Intersense driver was not enabled on Win32. This seems like a pretty big oversight and may also be a bug in 1.0.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <gadget/gadgetConfig.h>
#include <vpr/vpr.h>
#include <gadget/Type/DeviceFactory.h>
// Platform-independent devices.
#include <gadget/Devices/Ascension/MotionStar.h>
#include <gadget/Devices/Intersense/Intersense.h>
// Sims
#include <gadget/Devices/Sim/SimAnalog.h>
#include <gadget/Devices/Sim/SimDigital.h>
#include <gadget/Devices/Sim/SimPosition.h>
#include <gadget/Devices/Sim/SimGloveGesture.h>
//#include <gadget/Devices/Sim/SimKeyboardDigital.h>
#include <gadget/Devices/Sim/SimRelativePosition.h>
#include <gadget/Devices/Sim/SimSetablePosition.h>
#include <gadget/Devices/Sim/SimDigitalGlove.h>
// RemoteInputManager Dependency Checker
#include <jccl/Plugins/ConfigManager/DependencyManager.h>
#include <gadget/RemoteInputManager/RmtMgrDepChecker.h>
/* Physical devices */
#ifndef VPR_OS_Win32
# include <gadget/Devices/Ascension/Flock.h>
# ifdef VPR_OS_Darwin
# include <gadget/Devices/Keyboard/OSXKeyboard.h>
# else
# include <gadget/Devices/Immersion/Ibox.h>
//# include <gadget/Devices/VirtualTechnologies/CyberGlove.h>
# include <gadget/Devices/Fakespace/PinchGlove.h>
# include <gadget/Devices/Keyboard/KeyboardXWin.h>
# include <gadget/Devices/Keyboard/KeyboardDepCheckerXWin.h>
# include <gadget/Devices/Open/Trackd/TrackdController.h>
# include <gadget/Devices/Open/Trackd/TrackdSensor.h>
# endif
# include <gadget/Devices/Logitech/logiclass.h>
#else
# include <gadget/Devices/Keyboard/KeyboardWin32.h>
#endif
/* PThread Dependant Driver */
#ifdef GADGET_HAVE_DTK
# include <gadget/Devices/Open/DTK/DTK.h>
#endif
#include <typeinfo>
namespace gadget
{
// Initialize the singleton ptr
//vjDeviceFactory* DeviceFactory::mInstance = NULL;
//vjSingletonImp( DeviceFactory ); //kevin
vprSingletonImpWithInitFunc( DeviceFactory, hackLoadKnownDevices );
template <class DEV>
DeviceConstructor<DEV>::DeviceConstructor()
{
vprASSERT(DeviceFactory::instance() != NULL);
DeviceFactory::instance()->registerDevice(this);
}
// Register all the devices that I know about
//!NOTE: This should really be moved to dynamic library loading code.
void DeviceFactory::hackLoadKnownDevices()
{
// NOTE: These will all given unused variable errors in compiling.
// That is okay, because the don't actually have to do anything.
// They just register themselves in their constructor.
// Platform-independent devices.
DeviceConstructor<MotionStar>* motion_star = new DeviceConstructor<MotionStar>;
DeviceConstructor<Intersense>* intersense = new DeviceConstructor<Intersense>;
DeviceConstructor<SimAnalog>* sim_analog = new DeviceConstructor<SimAnalog>;
DeviceConstructor<SimDigital>* sim_digital = new DeviceConstructor<SimDigital>;
DeviceConstructor<SimPosition>* sim_position = new DeviceConstructor<SimPosition>;
//vjDeviceConstructor<SimKeyboardDigital>* sim_keyboard_digital = new DeviceConstructor<SimKeyboardDigital>;
DeviceConstructor<SimSetablePosition>* sim_setable = new DeviceConstructor<SimSetablePosition>;
DeviceConstructor<SimRelativePosition>* sim_relative = new DeviceConstructor<SimRelativePosition>;
DeviceConstructor<SimGloveGesture>* sim_glove = new DeviceConstructor<SimGloveGesture>;
DeviceConstructor<SimDigitalGlove>* simpinch_glove = new DeviceConstructor<SimDigitalGlove>;
if( (NULL == sim_analog) ||
(NULL == sim_digital) ||
(NULL == sim_position) ||
(NULL == sim_glove) ||
(NULL == simpinch_glove) ||
(NULL == sim_setable) ||
(NULL == sim_relative) )
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
jccl::DependencyManager::instance()->registerChecker(new RmtMgrDepChecker());
#ifndef VPR_OS_Win32
#ifdef VPR_OS_Darwin
DeviceConstructor<OSXKeyboard>* osx_keyboard = new DeviceConstructor<OSXKeyboard>;
if( (NULL == osx_keyboard) )
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#else
DeviceConstructor<TrackdSensor>* trackd_sensor = new DeviceConstructor<TrackdSensor>;
DeviceConstructor<TrackdController>* trackd_controller = new DeviceConstructor<TrackdController>;
DeviceConstructor<IBox>* ibox = new DeviceConstructor<IBox>;
DeviceConstructor<PinchGlove>* pinch_glove = new DeviceConstructor<PinchGlove>;
// DeviceConstructor<CyberGlove>* cyber_glove = new DeviceConstructor<CyberGlove>;
DeviceConstructor<KeyboardXWin>* xwin_key = new DeviceConstructor<KeyboardXWin>;
jccl::DependencyManager::instance()->registerChecker(new KeyboardDepCheckerXWin());
DeviceConstructor<ThreeDMouse>* threed_mouse = new DeviceConstructor<ThreeDMouse>;
if( (NULL == trackd_sensor) ||
(NULL == trackd_controller) ||
(NULL == ibox) ||
(NULL == pinch_glove) ||
// (NULL == cyber_glove) ||
(NULL == xwin_key) ||
(NULL == threed_mouse))
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#endif
DeviceConstructor<Flock>* flock = new DeviceConstructor<Flock>;
if( (NULL == flock) ||
(NULL == intersense) ||
(NULL == motion_star) )
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#else
DeviceConstructor<KeyboardWin32>* key_win32 = new DeviceConstructor<KeyboardWin32>;
if( (NULL == key_win32))
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#endif
#ifdef GADGET_HAVE_DTK
DeviceConstructor<DTK>* dtk_wrapper = new DeviceConstructor<DTK>;
if( (NULL == dtk_wrapper))
{
vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
}
#endif
}
void DeviceFactory::registerDevice(DeviceConstructorBase* constructor)
{
vprASSERT(constructor != NULL);
mConstructors.push_back(constructor); // Add the constructor to the list
vprDEBUG(gadgetDBG_INPUT_MGR,1)
<< "gadget::DeviceFactory: Registered: "
<< std::setiosflags(std::ios::right) << std::setw(25)
<< std::setfill(' ') << constructor->getChunkType()
<< std::setiosflags(std::ios::right)
//<< " :" << (void*)constructor
<< " type: " << typeid(*constructor).name() << std::endl
<< vprDEBUG_FLUSH;
}
// Simply query all device constructors registered looking
// for one that knows how to load the device
bool DeviceFactory::recognizeDevice(jccl::ConfigChunkPtr chunk)
{
if(findConstructor(chunk) == -1)
return false;
else
return true;
}
//: Load the specified device
//!PRE: recognizeDevice(chunk) == true
//!ARGS: chunk - specification of the device to load
//!RETURNS: null - Device failed to load
//+ other - Pointer to the loaded device
Input* DeviceFactory::loadDevice(jccl::ConfigChunkPtr chunk)
{
vprASSERT(recognizeDevice(chunk));
int index = findConstructor(chunk);
Input* new_dev;
DeviceConstructorBase* constructor = mConstructors[index];
vprDEBUG(gadgetDBG_INPUT_MGR,3)
<< "gadget::DeviceFactory::loadDevice: Loading device: "
<< chunk->getType() << " with: " << typeid(*constructor).name()
<< std::endl << vprDEBUG_FLUSH;
new_dev = constructor->createDevice(chunk);
return new_dev;
}
int DeviceFactory::findConstructor(jccl::ConfigChunkPtr chunk)
{
std::string chunk_type;
chunk_type = (std::string)chunk->getType();
for(unsigned int i=0;i<mConstructors.size();i++)
{
// Get next constructor
DeviceConstructorBase* construct = mConstructors[i];
vprASSERT(construct != NULL);
if(construct->getChunkType() == chunk_type)
return i;
}
return -1;
}
void DeviceFactory::debugDump()
{
vprDEBUG_BEGIN(gadgetDBG_INPUT_MGR,0)
<< "gadget::DeviceFactory::debugDump\n" << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_INPUT_MGR,0) << "num constructors:"
<< mConstructors.size() << "\n"
<< vprDEBUG_FLUSH;
for(unsigned int cNum=0;cNum<mConstructors.size();cNum++)
{
DeviceConstructorBase* dev_constr = mConstructors[cNum];
vprDEBUG(gadgetDBG_INPUT_MGR,0)
<< cNum << ": Constructor:" << (void*)dev_constr
<< " type:" << typeid(*dev_constr).name() << "\n" << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_INPUT_MGR,0) << " recog:"
<< dev_constr->getChunkType() << "\n"
<< vprDEBUG_FLUSH;
}
vprDEBUG_END(gadgetDBG_INPUT_MGR,0) << "------ END DUMP ------\n"
<< vprDEBUG_FLUSH;
}
};
<|endoftext|> |
<commit_before><commit_msg>qt: Add test for version info<commit_after><|endoftext|> |
<commit_before>//
// download_manager.cpp
// Cooloi_Assets_Downloader
//
// Created by ESoragoto on 11/17/15.
//
//
#include "download_manager.hpp"
#include "assets_downloader.hpp"
#include "SimpleAudioEngine.h"
#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <stdio.h>
#include "json/rapidjson.h"
#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"
using namespace cocos2d;
using namespace CocosDenshion;
#pragma mark - Initialization
DownloadManager::DownloadManager():
downloader_(nullptr),
stage_(DownloadStage ::kNull),
conf_(),
finished_(),
update_(),
now_downloading_(""),
now_number_(0)
{
} // DownloadManager
DownloadManager::~DownloadManager()
{
if (downloader_)
CC_SAFE_DELETE(downloader_);
} // ~DownloadManager
// on "init" you need to initialize your instance
bool DownloadManager::init()
{
if ( !Scene::init() )
{
return false;
}
LoadConfig();
InitDownloader();
LoadUpdate();
return true;
} // init
DownloadManager* DownloadManager::Create()
{
auto d = new DownloadManager();
if(d->init())
return d;
CC_SAFE_DELETE(d);
return nullptr;
} // Create
void DownloadManager::update(float dt)
{
if (downloader_->downloading()) return;
unscheduleUpdate();
switch (downloader()->status())
{
// case AssetsManager::ErrorCode::CREATE_FILE:
// {
// return;
// }
// break;
case AssetsManager::ErrorCode::UNCOMPRESS:
{
set_stage(DownloadStage::kNull);
return;
}
break;
case AssetsManager::ErrorCode::NETWORK:
{
set_stage(DownloadStage::kNull);
return;
}
break;
default:
break;
}
switch (stage())
{
case DownloadStage ::kLoadUpdate:
{
CheckUpdate();
}
break;
case DownloadStage ::kGetUpdate:
{
GetUpdate();
}
break;
default:
break;
}
} // update
#pragma mark - Member Function
#pragma mark -stage
int DownloadManager::LoadConfig()
{
log("\nStage : Load config info.\n");
set_stage(DownloadStage::kLoadConfig);
auto ret = 0;
std::string file_name = "";
//#if COCOS2D_DEBUG
// file_name = "Cooloi_ASDL_DEBUG.conf";
//// file_name = "Cooloi_ASDL.conf";
//#else
// file_name = "Cooloi_ASDL.conf";
//#endif
// ret = ReadConf(file_name,
// conf_);
#if COCOS2D_DEBUG
file_name = "Cooloi_ASDL_DEBUG.json";
// file_name = "Cooloi_ASDL.json";
#else
file_name = "Cooloi_ASDL.json";
#endif
ret = ReadConfigFromJson(file_name,
conf_);
if (0 != ret)
{
set_stage(DownloadStage::kNull);
}
return ret;
} // LoadConfig
int DownloadManager::InitDownloader()
{
log("\nStage : Initialization Downloader.\n");
set_stage(DownloadStage::kInitDownloader);
downloader_ = new AssetsDownloader(conf_["URL"],
conf_["VER"],
conf_["DIR"],
std::stoi(conf_["TRY"]));
downloader_->Init();
return 0;
} // InitDownloader
int DownloadManager::LoadUpdate()
{
log("\nStage : Download update info.\n");
set_stage(DownloadStage::kLoadUpdate);
Download(conf_["URL"]);
return 0;
} // LoadUpdate
int DownloadManager::CheckUpdate()
{
log("\nStage : Check update info.\n");
set_stage(DownloadStage::kCheckUpdate);
auto ret = 0;
if ("" != now_downloading_) push_finished(now_downloading());
// ret = ReadConf(conf_["NAME"], pkg_map_);
// ret = ReadConf(conf_["LOCAL_NAME"], loc_map_);
ret = ReadConfigFromJson(conf_["NAME"], pkg_map_);
ret = ReadConfigFromJson(conf_["LOCAL_NAME"], loc_map_);
for (auto p : pkg_map())
{
if (p.second != loc_map_[p.first])
{
push_update(p.first);
}
}
if (update().empty())
{
set_stage(DownloadStage::kFinished);
}
else
{
log("New package find!");
// GetUpdate();
}
return ret;
} // CheckUpdate
int DownloadManager::GetUpdate()
{
log("\nStage : Get update package.\n");
set_stage(DownloadStage::kGetUpdate);
auto ret = 0;
if ("" != now_downloading_) push_finished(now_downloading());
for (auto u : update())
{
auto jump = false;
for (auto f : finished())
{
if (u == f)
{
jump = true;
break;
}
}
if (jump) continue;
set_now_downloading(u);
Download(conf().at("SER") + pkg_map_[u]);
break;
}
if (update().size() == finished().size())
{
std::string content = "#loacl list\n";
for (auto p : pkg_map())
{
content += (p.first + " = " + p.second + "\n");
}
WriteFile(conf_["LOCAL_NAME"], content);
auto s = FileUtils::getInstance()->getStringFromFile(conf_["LOCAL_NAME"]);
log("%s", s.c_str());
set_stage(DownloadStage::kFinished);
}
return ret;
} // GetUpdate
void DownloadManager::Close()
{
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
} // Close
#pragma mark -other
int DownloadManager::Download(const std::string pkg_url)
{
log("Request to download resource : %s", pkg_url.c_str());
downloader_->Download(pkg_url);
scheduleUpdate();
return 0;
} // Download
int DownloadManager::ReadConf(const std::string file_name,
std::map<std::string, std::string> &conf_map)
{
log("Read config file : %s", file_name.c_str());
std::string path_with_file = "";
FindPathWithFile(file_name, path_with_file);
if ("" == path_with_file)
{
WriteFile(file_name, "");
return 1;
}
auto str = FileUtils::getInstance()->getStringFromFile(file_name);
log("getStringFromFile\n%s",str.c_str());
std::ifstream in_file(path_with_file);
if(in_file.fail())
return 1001;
std::string str_by_line = "";
while (std::getline(in_file, str_by_line))
{
std::string arg;
std::string value;
ConfRegex(str_by_line, arg, value);
conf_map[arg] = value;
}
return 0;
} // ReadConf
int DownloadManager::ConfRegex(const std::string str,
std::string &arg,
std::string &value)
{
log("Regex line : %s", str.c_str());
std::regex rgx("^(\\w+)\\s*\\=\\s*([^\\s]+)$");
std::smatch match;
if (std::regex_search(str.begin(), str.end(), match, rgx))
{
for(auto q : match)
{
log("\t%s", q.str().c_str());
}
log("----");
arg = match[1].str();
value = match[2].str();
}
return 0;
} // ConfRegex
int DownloadManager::ReadConfigFromJson(const std::string file_name,
std::map<std::string, std::string> &conf_map)
{
std::string file_with_path = "";
FindPathWithFile(file_name, file_with_path);
auto str = FileUtils::getInstance()->getStringFromFile(file_with_path.c_str());
log("getStringFromFile : %s", str.c_str());
rapidjson::Document d;
d.Parse<0>(str.c_str());
if(!d.IsObject())
{
set_stage(DownloadStage::kFileNotFound);
return 1404;
}
for (auto iter = d.MemberBegin() ; iter != d.MemberEnd() ; iter++)
{
log("\tKey\t : %s\n\tValue : %s\n\t----",
iter->name.GetString(),
iter->value.GetString());
conf_map[iter->name.GetString()] = iter->value.GetString();
}
return 0;
}
int DownloadManager::WriteConfigToJson(const std::string file_name,
std::map<std::string, std::string> &conf_map)
{
std::string file_with_path = "";
FindPathWithFile(file_name, file_with_path);
rapidjson::Document d;
d.SetObject();
for(auto c : conf_map)
{
log("write config name is %s, value is %s", c.first.c_str(), c.second.c_str());
rapidjson::Value name(rapidjson::kStringType);
name.SetString(c.first.c_str(), (int)c.first.length());
rapidjson::Value value(rapidjson::kStringType);
value.SetString(c.second.c_str(), (int)c.second.length());
d.AddMember(name, value, d.GetAllocator());
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> write(buffer);
d.Accept(write);
log("now write config is %s", buffer.GetString());
if ("" == file_with_path)
{
file_with_path = FileUtils::getInstance()->getWritablePath() + file_name;
}
FILE* file = fopen(file_with_path.c_str(), "wb");
if (file)
{
fputs(buffer.GetString(), file);
fclose(file);
}
return 0;
}
int DownloadManager::ReadFile(const std::string file_name,
std::string &content)
{
log("Preparing Read file : %s", file_name.c_str());
std::string file_with_path = "";
FindPathWithFile(file_name, file_with_path);
if ("" == file_with_path)
return 1404;
log("Full path: %s", file_with_path.c_str());
auto file = FileUtils::getInstance()->getStringFromFile(file_with_path);
if ("" == file)
{
std::ifstream infile(file_with_path);
if (infile.fail())
{
log("Open file fail, file name: %s", file_name.c_str());
return 1001;
}
std::string str((std::istreambuf_iterator<char>(infile)),
std::istreambuf_iterator<char>());
file = str.c_str();
infile.close();
}
log("open file:\n----\n%s\n----", file.c_str());
content = file;
return 0;
} // ReadFile
int DownloadManager::WriteFile(const std::string file_name,
const std::string content)
{
log("Preparing write file : %s", file_name.c_str());
std::string file_to_write = "";
FindPathWithFile(file_name, file_to_write);
if ("" == file_to_write)
{
file_to_write = FileUtils::getInstance()->getWritablePath();
// file_to_write += conf_["Dir"];
file_to_write += file_name;
}
log("Write path : %s", file_to_write.c_str());
std::ofstream outfile;
outfile.open(file_to_write);
if (outfile.fail())
{
log("Open file fail, file name: %s", file_name.c_str());
return 1001;
}
std::string str = "#" + file_name + "\n" + content;
outfile << str;
log("write file with fstream : \n----\n%s\n----", str.c_str());
outfile.close();
return 0;
} // WriteFile
int DownloadManager::AppendFile(const std::string file_name,
const std::string content)
{
auto ret = 0;
std::string path_with_file = "";
FindPathWithFile(file_name, path_with_file);
if ("" == path_with_file)
{
return 1404;
}
log("Full path: %s", path_with_file.c_str());
std::string front_content = "";
ret = ReadFile(file_name,
front_content);
if (0 != ret)
return ret;
ret = WriteFile(file_name, front_content + "\n" + content);
return ret;
} // AppendFile
int DownloadManager::FindPathWithFile(const std::string file_name,
std::string &path_with_file)
{
auto path = FileUtils::getInstance()->fullPathForFilename(file_name);
if ("" == path)
{
auto temp_name = FileUtils::getInstance()->getWritablePath() + file_name;
path = FileUtils::getInstance()->fullPathForFilename(temp_name);
if ("" == path) log("File not exist!");
}
if ("" != path)
log("Find file with : %s", path.c_str());
path_with_file = path;
return 0;
} // FindPathWithFile
<commit_msg>some fix<commit_after>//
// download_manager.cpp
// Cooloi_Assets_Downloader
//
// Created by ESoragoto on 11/17/15.
//
//
#include "download_manager.hpp"
#include "assets_downloader.hpp"
#include "SimpleAudioEngine.h"
#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <stdio.h>
#include "json/rapidjson.h"
#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"
using namespace cocos2d;
using namespace CocosDenshion;
#pragma mark - Initialization
DownloadManager::DownloadManager():
downloader_(nullptr),
stage_(DownloadStage ::kNull),
conf_(),
finished_(),
update_(),
now_downloading_(""),
now_number_(0)
{
} // DownloadManager
DownloadManager::~DownloadManager()
{
if (downloader_)
CC_SAFE_DELETE(downloader_);
} // ~DownloadManager
// on "init" you need to initialize your instance
bool DownloadManager::init()
{
if ( !Scene::init() )
{
return false;
}
LoadConfig();
InitDownloader();
LoadUpdate();
return true;
} // init
DownloadManager* DownloadManager::Create()
{
auto d = new DownloadManager();
if(d->init())
return d;
CC_SAFE_DELETE(d);
return nullptr;
} // Create
void DownloadManager::update(float dt)
{
if (downloader_->downloading()) return;
unscheduleUpdate();
switch (downloader()->status())
{
// case AssetsManager::ErrorCode::CREATE_FILE:
// {
// return;
// }
// break;
case AssetsManager::ErrorCode::UNCOMPRESS:
{
set_stage(DownloadStage::kNull);
return;
}
break;
case AssetsManager::ErrorCode::NETWORK:
{
set_stage(DownloadStage::kNull);
return;
}
break;
default:
break;
}
switch (stage())
{
case DownloadStage ::kLoadUpdate:
{
CheckUpdate();
}
break;
case DownloadStage ::kGetUpdate:
{
GetUpdate();
}
break;
default:
break;
}
} // update
#pragma mark - Member Function
#pragma mark -stage
int DownloadManager::LoadConfig()
{
log("\nStage : Load config info.\n");
set_stage(DownloadStage::kLoadConfig);
auto ret = 0;
std::string file_name = "";
//#if COCOS2D_DEBUG
// file_name = "Cooloi_ASDL_DEBUG.conf";
//// file_name = "Cooloi_ASDL.conf";
//#else
// file_name = "Cooloi_ASDL.conf";
//#endif
// ret = ReadConf(file_name,
// conf_);
#if COCOS2D_DEBUG
file_name = "Cooloi_ASDL_DEBUG.json";
// file_name = "Cooloi_ASDL.json";
#else
file_name = "Cooloi_ASDL.json";
#endif
ret = ReadConfigFromJson(file_name,
conf_);
if (0 != ret)
{
set_stage(DownloadStage::kNull);
}
return ret;
} // LoadConfig
int DownloadManager::InitDownloader()
{
log("\nStage : Initialization Downloader.\n");
set_stage(DownloadStage::kInitDownloader);
downloader_ = new AssetsDownloader(conf_["URL"],
conf_["VER"],
conf_["DIR"],
std::stoi(conf_["TRY"]));
downloader_->Init();
return 0;
} // InitDownloader
int DownloadManager::LoadUpdate()
{
log("\nStage : Download update info.\n");
set_stage(DownloadStage::kLoadUpdate);
Download(conf_["URL"]);
return 0;
} // LoadUpdate
int DownloadManager::CheckUpdate()
{
log("\nStage : Check update info.\n");
set_stage(DownloadStage::kCheckUpdate);
auto ret = 0;
if ("" != now_downloading_) push_finished(now_downloading());
// ret = ReadConf(conf_["NAME"], pkg_map_);
// ret = ReadConf(conf_["LOCAL_NAME"], loc_map_);
ret = ReadConfigFromJson(conf_["NAME"], pkg_map_);
ret = ReadConfigFromJson(conf_["LOCAL_NAME"], loc_map_);
for (auto p : pkg_map())
{
if (p.second != loc_map_[p.first])
{
push_update(p.first);
}
}
if (update().empty())
{
set_stage(DownloadStage::kFinished);
}
else
{
log("New package find!");
// GetUpdate();
}
return ret;
} // CheckUpdate
int DownloadManager::GetUpdate()
{
log("\nStage : Get update package.\n");
set_stage(DownloadStage::kGetUpdate);
auto ret = 0;
if ("" != now_downloading_) push_finished(now_downloading());
for (auto u : update())
{
auto jump = false;
for (auto f : finished())
{
if (u == f)
{
jump = true;
break;
}
}
if (jump) continue;
set_now_downloading(u);
Download(conf().at("SER") + pkg_map_[u]);
break;
}
if (update().size() == finished().size())
{
std::string content = "";
for (auto p : pkg_map())
{
content += (p.first + " = " + p.second + "\n");
}
WriteFile(conf_["LOCAL_NAME"], content);
auto s = FileUtils::getInstance()->getStringFromFile(conf_["LOCAL_NAME"]);
log("%s", s.c_str());
set_stage(DownloadStage::kFinished);
}
return ret;
} // GetUpdate
void DownloadManager::Close()
{
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
} // Close
#pragma mark -other
int DownloadManager::Download(const std::string pkg_url)
{
log("Request to download resource : %s", pkg_url.c_str());
downloader_->Download(pkg_url);
scheduleUpdate();
return 0;
} // Download
int DownloadManager::ReadConf(const std::string file_name,
std::map<std::string, std::string> &conf_map)
{
log("Read config file : %s", file_name.c_str());
std::string path_with_file = "";
FindPathWithFile(file_name, path_with_file);
if ("" == path_with_file)
{
WriteFile(file_name, "");
return 1;
}
auto str = FileUtils::getInstance()->getStringFromFile(file_name);
log("getStringFromFile\n%s",str.c_str());
std::ifstream in_file(path_with_file);
if(in_file.fail())
return 1001;
std::string str_by_line = "";
while (std::getline(in_file, str_by_line))
{
std::string arg;
std::string value;
ConfRegex(str_by_line, arg, value);
conf_map[arg] = value;
}
return 0;
} // ReadConf
int DownloadManager::ConfRegex(const std::string str,
std::string &arg,
std::string &value)
{
log("Regex line : %s", str.c_str());
std::regex rgx("^(\\w+)\\s*\\=\\s*([^\\s]+)$");
std::smatch match;
if (std::regex_search(str.begin(), str.end(), match, rgx))
{
for(auto q : match)
{
log("\t%s", q.str().c_str());
}
log("----");
arg = match[1].str();
value = match[2].str();
}
return 0;
} // ConfRegex
int DownloadManager::ReadConfigFromJson(const std::string file_name,
std::map<std::string, std::string> &conf_map)
{
std::string file_with_path = "";
FindPathWithFile(file_name, file_with_path);
auto str = FileUtils::getInstance()->getStringFromFile(file_with_path.c_str());
log("getStringFromFile : %s", str.c_str());
rapidjson::Document d;
d.Parse<0>(str.c_str());
if(!d.IsObject())
{
set_stage(DownloadStage::kFileNotFound);
return 1404;
}
for (auto iter = d.MemberBegin() ; iter != d.MemberEnd() ; iter++)
{
log("\tKey\t : %s\n\tValue : %s\n\t----",
iter->name.GetString(),
iter->value.GetString());
conf_map[iter->name.GetString()] = iter->value.GetString();
}
return 0;
}
int DownloadManager::WriteConfigToJson(const std::string file_name,
std::map<std::string, std::string> &conf_map)
{
std::string file_with_path = "";
FindPathWithFile(file_name, file_with_path);
rapidjson::Document d;
d.SetObject();
for(auto c : conf_map)
{
log("write config name is %s, value is %s", c.first.c_str(), c.second.c_str());
rapidjson::Value name(rapidjson::kStringType);
name.SetString(c.first.c_str(), (int)c.first.length());
rapidjson::Value value(rapidjson::kStringType);
value.SetString(c.second.c_str(), (int)c.second.length());
d.AddMember(name, value, d.GetAllocator());
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> write(buffer);
d.Accept(write);
log("now write config is %s", buffer.GetString());
if ("" == file_with_path)
{
file_with_path = FileUtils::getInstance()->getWritablePath() + file_name;
}
FILE* file = fopen(file_with_path.c_str(), "wb");
if (file)
{
fputs(buffer.GetString(), file);
fclose(file);
}
return 0;
}
int DownloadManager::ReadFile(const std::string file_name,
std::string &content)
{
log("Preparing Read file : %s", file_name.c_str());
std::string file_with_path = "";
FindPathWithFile(file_name, file_with_path);
if ("" == file_with_path)
return 1404;
log("Full path: %s", file_with_path.c_str());
auto file = FileUtils::getInstance()->getStringFromFile(file_with_path);
if ("" == file)
{
std::ifstream infile(file_with_path);
if (infile.fail())
{
log("Open file fail, file name: %s", file_name.c_str());
return 1001;
}
std::string str((std::istreambuf_iterator<char>(infile)),
std::istreambuf_iterator<char>());
file = str.c_str();
infile.close();
}
log("open file:\n----\n%s\n----", file.c_str());
content = file;
return 0;
} // ReadFile
int DownloadManager::WriteFile(const std::string file_name,
const std::string content)
{
log("Preparing write file : %s", file_name.c_str());
std::string file_to_write = "";
FindPathWithFile(file_name, file_to_write);
if ("" == file_to_write)
{
file_to_write = FileUtils::getInstance()->getWritablePath();
// file_to_write += conf_["Dir"];
file_to_write += file_name;
}
log("Write path : %s", file_to_write.c_str());
std::ofstream outfile;
outfile.open(file_to_write);
if (outfile.fail())
{
log("Open file fail, file name: %s", file_name.c_str());
return 1001;
}
std::string str = "";
// str += "#" + file_name + "\n";
str += content;
outfile << str;
log("write file with fstream : \n----\n%s\n----", str.c_str());
outfile.close();
return 0;
} // WriteFile
int DownloadManager::AppendFile(const std::string file_name,
const std::string content)
{
auto ret = 0;
std::string path_with_file = "";
FindPathWithFile(file_name, path_with_file);
if ("" == path_with_file)
{
return 1404;
}
log("Full path: %s", path_with_file.c_str());
std::string front_content = "";
ret = ReadFile(file_name,
front_content);
if (0 != ret)
return ret;
ret = WriteFile(file_name, front_content + "\n" + content);
return ret;
} // AppendFile
int DownloadManager::FindPathWithFile(const std::string file_name,
std::string &path_with_file)
{
auto path = FileUtils::getInstance()->fullPathForFilename(file_name);
if ("" == path)
{
auto temp_name = FileUtils::getInstance()->getWritablePath() + file_name;
path = FileUtils::getInstance()->fullPathForFilename(temp_name);
if ("" == path) log("File not exist!");
}
if ("" != path)
log("Find file with : %s", path.c_str());
path_with_file = path;
return 0;
} // FindPathWithFile
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <map>
#include <vector>
#include <utility>
using namespace std;
typedef pair<string,double> P;
struct node
{
std::vector<struct node *> parents; //for 0 or N-parents; if the vector is empty, the event is Independient
std::map<string, double> probabilityTable; //key is X in P(X)
};
int main(int argc, char *argv[])
{
std::map<string, struct node*> nodes;
string buffer, builder, aux;
char devourer;
double readerProb;
int sect = 0;
cout << "STARTING...\n";
while(sect < 3){
getline(cin,buffer);
//cout << "Reading std\n";
if(buffer.compare("[Nodes]")==0){
cout << "Nodes:\n";
getline(cin,buffer);
for(int i=0;i < buffer.length();i++){
if(buffer[i]==','){
nodes[builder] = new node;
cout << builder << "\n";
}else if(i==(buffer.length()-1)){
builder+=buffer[i];
cout << builder << "\n";
nodes[builder] = new node;
}else if(buffer[i]==' '){
builder="";
}else{
builder+=buffer[i];
}
}
cout << '\n';
sect++;
}else if(buffer.compare("[Probabilities]")==0){
cout << "Probabilities:\n";
while(buffer.compare("")!=0){
getline(cin,buffer);
builder="";
//link nodes with their parents
//cout << "----\n";
bool indexNode=false;
for(int i=0;i < buffer.length();i++){
if(buffer[i]=='|'){
indexNode = true; //the node have a parent
aux = builder;
builder="";
cout << "\nNode is: " << aux <<'\n';
cout << "Its parents are: ";
}
if(buffer[i]=='+'||buffer[i]=='-'||buffer[i]==' '||buffer[i]=='='||buffer[i]==','||buffer[i]=='|'||(buffer[i]>=48&&buffer[i]<=57));
else{
builder+=buffer[i]; //construct the string key for the map of nodes
//cout << '.';
}
if(indexNode){ //to make the conection in base of the dependece
if(buffer[i]==','){
(nodes[aux])->parents.push_back(nodes[builder]); //to create N parents
cout << builder <<' ';
builder="";
}else if (buffer[i]=='=')
{
(nodes[aux])->parents.push_back(nodes[builder]); //if there is only one parent
cout << builder <<' ';
builder="";
}
}
if(buffer[i]=='='){
if(!indexNode){
aux=builder; //the node is root P(X) is independient
cout << "\nNode: " << aux <<" is a root\n";
}
break; //finish the creation of the edges
}
}
cout << '\n';
//probability table
builder="";
for(int i=0;i < buffer.length();i++){
if(buffer[i]=='='){
break;
}else if(buffer[i]==' '&&buffer[i+1]=='=');
else{
builder+=buffer[i];
}
}
if(builder.compare("")!=0){
stringstream extract(buffer);
do{
extract >> devourer; //eats all chars
}while(devourer!='=');
extract >> readerProb;
(nodes[aux])->probabilityTable[builder]=readerProb;
cout << "P("<< builder << ")= " << (nodes[aux])->probabilityTable[builder] << "\n";
}
}
sect++;
}else if (buffer.compare("[Queries]")==0){
cout << "Queries:\n";
sect++;
}
}
return 0;
}<commit_msg>No duplications in the vector of parents<commit_after>#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#include <map>
#include <vector>
#include <utility>
using namespace std;
typedef pair<string,double> P;
struct node
{
std::vector<struct node *> parents; //for 0 or N-parents; if the vector is empty, the event is Independient
std::map<string, double> probabilityTable; //key is X in P(X)
};
void createNodes(map<string, struct node*> &nodes,string buffer){
string builder;
getline(cin,buffer);
for(int i=0;i < buffer.length();i++){
if(buffer[i]==','){
nodes[builder] = new node;
cout << builder << "\n";
}else if(i==(buffer.length()-1)){
builder+=buffer[i];
cout << builder << "\n";
nodes[builder] = new node;
}else if(buffer[i]==' '){
builder="";
}else{
builder+=buffer[i];
}
}
}
void createBayesNetwork(map<string, struct node*> &nodes,string buffer){
string builder, aux;
char devourer;
double readerProb;
while(buffer.compare("")!=0){
getline(cin,buffer);
builder="";
//link nodes with their parents
//cout << "----\n";
bool indexNode=false;
for(int i=0;i < buffer.length();i++){
if(buffer[i]=='|'){
indexNode = true; //the node have a parent
aux = builder;
builder="";
cout << "\nNode is: " << aux <<'\n';
cout << "Its parents are: ";
}
if(buffer[i]=='+'||buffer[i]=='-'||buffer[i]==' '||buffer[i]=='='||buffer[i]==','||buffer[i]=='|'||(buffer[i]>=48&&buffer[i]<=57));
else{
builder+=buffer[i]; //construct the string key for the map of nodes
//cout << '.';
}
if(indexNode){ //to make the conection in base of the dependece
if(find((nodes[aux])->parents.begin(),(nodes[aux])->parents.end(),nodes[builder])!=(nodes[aux])->parents.end()){
cout << " [A.K.] ";
builder = "";
}
else{
if(buffer[i]==','){
(nodes[aux])->parents.push_back(nodes[builder]); //to create N parents
cout << builder <<' ';
builder="";
}else if (buffer[i]=='=')
{
(nodes[aux])->parents.push_back(nodes[builder]); //if there is only one parent
cout << builder <<' ';
builder="";
}
}
}
if(buffer[i]=='='){
if(!indexNode){
aux=builder; //the node is root P(X) is independient
cout << "\nNode: " << aux <<" is a root\n";
}
break; //finish the creation of the edges
}
}
cout << '\n';
//probability table
builder="";
for(int i=0;i < buffer.length();i++){
if(buffer[i]=='='){
break;
}else if(buffer[i]==' '&&buffer[i+1]=='='); //to ignore the last blank space " ="
else{
builder+=buffer[i];
}
}
if(builder.compare("")!=0){
stringstream extract(buffer);
do{
extract >> devourer; //eats all chars
}while(devourer!='=');
extract >> readerProb;
(nodes[aux])->probabilityTable[builder]=readerProb; //store the true values P(+X|Y)
cout << "P("<< builder << ")= " << (nodes[aux])->probabilityTable[builder] << "\n";
}
}
}
int main(int argc, char *argv[])
{
std::map<string, struct node*> nodes;
string buffer, builder, aux;
char devourer;
double readerProb;
int sect = 0;
cout << "STARTING...\n";
while(sect < 3){
getline(cin,buffer);
//cout << "Reading std\n";
if(buffer.compare("[Nodes]")==0){
cout << "Nodes:\n";
/*
getline(cin,buffer);
for(int i=0;i < buffer.length();i++){
if(buffer[i]==','){
nodes[builder] = new node;
cout << builder << "\n";
}else if(i==(buffer.length()-1)){
builder+=buffer[i];
cout << builder << "\n";
nodes[builder] = new node;
}else if(buffer[i]==' '){
builder="";
}else{
builder+=buffer[i];
}
}
*/
createNodes(nodes,buffer);
cout << '\n';
sect++;
}else if(buffer.compare("[Probabilities]")==0){
cout << "Probabilities:\n";
/*
while(buffer.compare("")!=0){
getline(cin,buffer);
builder="";
//link nodes with their parents
//cout << "----\n";
bool indexNode=false;
for(int i=0;i < buffer.length();i++){
if(buffer[i]=='|'){
indexNode = true; //the node have a parent
aux = builder;
builder="";
cout << "\nNode is: " << aux <<'\n';
cout << "Its parents are: ";
}
if(buffer[i]=='+'||buffer[i]=='-'||buffer[i]==' '||buffer[i]=='='||buffer[i]==','||buffer[i]=='|'||(buffer[i]>=48&&buffer[i]<=57));
else{
builder+=buffer[i]; //construct the string key for the map of nodes
//cout << '.';
}
if(indexNode){ //to make the conection in base of the dependece
if(find((nodes[aux])->parents.begin(),(nodes[aux])->parents.end(),nodes[builder])!=(nodes[aux])->parents.end()){
cout << " [A.K.] ";
builder = "";
}
else{
if(buffer[i]==','){
(nodes[aux])->parents.push_back(nodes[builder]); //to create N parents
cout << builder <<' ';
builder="";
}else if (buffer[i]=='=')
{
(nodes[aux])->parents.push_back(nodes[builder]); //if there is only one parent
cout << builder <<' ';
builder="";
}
}
}
if(buffer[i]=='='){
if(!indexNode){
aux=builder; //the node is root P(X) is independient
cout << "\nNode: " << aux <<" is a root\n";
}
break; //finish the creation of the edges
}
}
cout << '\n';
//probability table
builder="";
for(int i=0;i < buffer.length();i++){
if(buffer[i]=='='){
break;
}else if(buffer[i]==' '&&buffer[i+1]=='='); //to ignore the last blank space " ="
else{
builder+=buffer[i];
}
}
if(builder.compare("")!=0){
stringstream extract(buffer);
do{
extract >> devourer; //eats all chars
}while(devourer!='=');
extract >> readerProb;
(nodes[aux])->probabilityTable[builder]=readerProb; //store the true values P(+X|Y)
cout << "P("<< builder << ")= " << (nodes[aux])->probabilityTable[builder] << "\n";
}
}*/
createBayesNetwork(nodes,buffer);
sect++;
}else if (buffer.compare("[Queries]")==0){
cout << "Queries:\n";
getline(cin,buffer);
sect++;
}
}
return 0;
}<|endoftext|> |
<commit_before><commit_msg>restore missing frame borders<commit_after><|endoftext|> |
<commit_before>// Always goes first
#define _CUSTOM_UINT64
#include "stdint.h"
// ROS
#include <ros/ros.h>
// bCAP (Always last)
#include "bcap_client.h"
#define PERIOD (100) /* Period Cycle */
#define AMPLITUDE (10) /* Amplitude */
#define E_BUF_FULL (0x83201483)
int main(void)
{
int i, fd;
long *plData;
uint32_t hCtrl, hRob;
double *pdData, dAng[8];
BSTR bstr1, bstr2, bstr3, bstr4;
VARIANT vntParam, vntRet;
HRESULT hr;
/* Open connection */
hr = bCap_Open_Client("tcp:192.168.0.1:5007", 1000, 3, &fd);
if(SUCCEEDED(hr)){
bstr1 = SysAllocString(L",WDT=400");
/* Send SERVICE_START packet */
bCap_ServiceStart(fd, NULL);
SysFreeString(bstr1);
bstr1 = SysAllocString(L"RC8"); // Name
bstr2 = SysAllocString(L"CaoProv.DENSO.VRC"); // Provider
bstr3 = SysAllocString(L"localhost"); // Machine
bstr4 = SysAllocString(L""); // Option
/* Connect RC8 */
hr = bCap_ControllerConnect(fd, bstr1, bstr2, bstr3, bstr4, &hCtrl);
SysFreeString(bstr1);
SysFreeString(bstr2);
SysFreeString(bstr3);
SysFreeString(bstr4);
if(SUCCEEDED(hr)){
bstr1 = SysAllocString(L"Robot"); // Name
bstr2 = SysAllocString(L""); // Option
/* Get robot handle */
hr = bCap_ControllerGetRobot(fd, hCtrl, bstr1, bstr2, &hRob);
SysFreeString(bstr1);
SysFreeString(bstr2);
if(SUCCEEDED(hr)){
bstr1 = SysAllocString(L"Takearm");
VariantInit(&vntParam);
vntParam.vt = (VT_I4 | VT_ARRAY);
vntParam.parray = SafeArrayCreateVector(VT_I4, 0, 2);
SafeArrayAccessData(vntParam.parray, (void **)&plData);
plData[0] = 0; plData[1] = 1;
SafeArrayUnaccessData(vntParam.parray);
/* Get arm control authority */
hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
if(SUCCEEDED(hr)){
bstr1 = SysAllocString(L"Motor");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = 1;
/* Motor on */
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
VariantInit(&vntParam);
vntParam.vt = VT_BSTR;
vntParam.bstrVal = SysAllocString(L"@E J1");
/* Move to first pose */
bCap_RobotMove(fd, hRob, 1, vntParam, NULL);
VariantClear(&vntParam);
bstr1 = SysAllocString(L"CurJnt");
VariantInit(&vntParam);
vntParam.vt = VT_EMPTY;
/* Get current angle */
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SafeArrayAccessData(vntRet.parray, (void **)&pdData);
memcpy(dAng, pdData, 8 * sizeof(double));
SafeArrayUnaccessData(vntRet.parray);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
bstr1 = SysAllocString(L"slvChangeMode");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = 2;
/* Start slave mode (Mode 0, J Type) */
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
bstr1 = SysAllocString(L"slvMove");
VariantInit(&vntParam);
vntParam.vt = (VT_R8 | VT_ARRAY);
vntParam.parray = SafeArrayCreateVector(VT_R8, 0, 8);
for(i = 0; i < PERIOD; i++){
SafeArrayAccessData(vntParam.parray, (void **)&pdData);
memcpy(pdData, dAng, 8 * sizeof(double));
pdData[0] = dAng[0] + i / 10.0;
pdData[1] = dAng[1] + AMPLITUDE * sin(2*M_PI*i/PERIOD);
SafeArrayUnaccessData(vntParam.parray);
hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
VariantClear(&vntRet);
/* if return code is not S_OK, then keep the message sending process waiting for 8 msec */
if(hr != S_OK){
usleep(8000);
/* if return code is E_BUF_FULL, then retry previous packet */
if(FAILED(hr)){
if(hr == E_BUF_FULL){
i--;
}else{
break;
}
}
}
}
/* Stop robot */
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
bstr1 = SysAllocString(L"slvChangeMode");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = 0;
/* Stop slave mode */
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
bstr1 = SysAllocString(L"Motor");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = 0;
/* Motor off */
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
bstr1 = SysAllocString(L"Givearm");
VariantInit(&vntParam);
vntParam.vt = VT_EMPTY;
/* Release arm control authority */
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
}
/* Release robot handle */
bCap_RobotRelease(fd, &hRob);
}
/* Disconnect RC8 */
bCap_ControllerDisconnect(fd, &hCtrl);
}
/* Send SERVICE_STOP packet */
bCap_ServiceStop(fd);
/* Close connection */
bCap_Close_Client(&fd);
}
return 0;
};
<commit_msg>Cleaned-up slave_mode.cpp<commit_after>// Always goes first
#define _CUSTOM_UINT64
#include "stdint.h"
// ROS
#include <ros/ros.h>
// bCAP (Always last)
#include "bcap_client.h"
#define E_BUF_FULL (0x83201483)
namespace SlaveMode
{
enum Modes
{
P0 = 0x001,
J0 = 0x002,
T0 = 0x003,
P1 = 0x101,
J1 = 0x102,
T1 = 0x103,
P2 = 0x201,
J2 = 0x202,
T2 = 0x203
};
enum Formats
{
None = 0x0000,
HandIO = 0x0020,
Electric = 0x0020,
MiniIO = 0x0100,
MiniAndHandIO = 0x0120,
UserIO = 0x0200,
UserAndHandIO = 0x0220,
Ptype = 0x0001,
Jtype = 0x0002,
Ttype = 0x0003,
PJtypes = 0x0004,
TJtypes = 0x0005,
Timestamp = 0x0010
};
}
int main(int argc, char **argv)
{
ros::init (argc, argv, "slave_mode");
ros::NodeHandle nh_;
int i, fd;
long *plData;
uint32_t hCtrl, hRob;
double *pdData, dAng[8], dElectric[16];
BSTR bstr1, bstr2, bstr3, bstr4;
VARIANT vntParam, vntRet;
HRESULT hr;
// Open connection
hr = bCap_Open_Client("tcp:192.168.0.21:5007", 1000, 3, &fd);
if(SUCCEEDED(hr)){
// Send SERVICE_START packet
bstr1 = SysAllocString(L",WDT=400");
bCap_ServiceStart(fd, NULL);
SysFreeString(bstr1);
// Connect to RC8
bstr1 = SysAllocString(L"RC8"); // Name
bstr2 = SysAllocString(L"CaoProv.DENSO.VRC"); // Provider
bstr3 = SysAllocString(L"localhost"); // Machine
bstr4 = SysAllocString(L""); // Options
hr = bCap_ControllerConnect(fd, bstr1, bstr2, bstr3, bstr4, &hCtrl);
SysFreeString(bstr1);
SysFreeString(bstr2);
SysFreeString(bstr3);
SysFreeString(bstr4);
if(SUCCEEDED(hr)){
// Get robot handle
bstr1 = SysAllocString(L"Robot"); // Name
bstr2 = SysAllocString(L""); // Option
hr = bCap_ControllerGetRobot(fd, hCtrl, bstr1, bstr2, &hRob);
SysFreeString(bstr1);
SysFreeString(bstr2);
if(SUCCEEDED(hr)){
// Get arm control authority
bstr1 = SysAllocString(L"Takearm");
VariantInit(&vntParam);
vntParam.vt = (VT_I4 | VT_ARRAY);
vntParam.parray = SafeArrayCreateVector(VT_I4, 0, 2);
SafeArrayAccessData(vntParam.parray, (void **)&plData);
plData[0] = 0; plData[1] = 1;
SafeArrayUnaccessData(vntParam.parray);
hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
if(SUCCEEDED(hr)){
// Motor ON
bstr1 = SysAllocString(L"Motor");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = 1;
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
// Get current angles
bstr1 = SysAllocString(L"CurJnt");
VariantInit(&vntParam);
vntParam.vt = VT_EMPTY;
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SafeArrayAccessData(vntRet.parray, (void **)&pdData);
memcpy(dAng, pdData, 8 * sizeof(double));
SafeArrayUnaccessData(vntRet.parray);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
// Change slvRecvFormat
bstr1 = SysAllocString(L"slvRecvFormat");
VariantInit(&vntParam);
vntParam.vt = (VT_I4 | VT_ARRAY);
vntParam.parray = SafeArrayCreateVector(VT_I4, 0, 2);
SafeArrayAccessData(vntParam.parray, (void **)&plData);
plData[0] = SlaveMode::Ptype;
plData[1] = 0;
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
// Start slave mode
bstr1 = SysAllocString(L"slvChangeMode");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = SlaveMode::J1;
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
// Send commands
bstr1 = SysAllocString(L"slvMove");
VariantInit(&vntParam);
vntParam.vt = (VT_R8 | VT_ARRAY);
vntParam.parray = SafeArrayCreateVector(VT_R8, 0, 8);
ros::Rate rate(125);
while (ros::ok())
{
SafeArrayAccessData(vntParam.parray, (void **)&pdData);
memcpy(pdData, dAng, 8 * sizeof(double));
SafeArrayUnaccessData(vntParam.parray);
hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
VariantClear(&vntRet);
// Sleep
rate.sleep();
}
// Stop robot
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
// Stop slave mode
bstr1 = SysAllocString(L"slvChangeMode");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = 0;
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
// Motor off
bstr1 = SysAllocString(L"Motor");
VariantInit(&vntParam);
vntParam.vt = VT_I4;
vntParam.lVal = 0;
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
// Release arm control authority
bstr1 = SysAllocString(L"Givearm");
VariantInit(&vntParam);
vntParam.vt = VT_EMPTY;
bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
SysFreeString(bstr1);
VariantClear(&vntParam);
VariantClear(&vntRet);
}
// Release robot handle
bCap_RobotRelease(fd, &hRob);
}
// Disconnect RC8
bCap_ControllerDisconnect(fd, &hCtrl);
}
// Send SERVICE_STOP packet
bCap_ServiceStop(fd);
// Close connection
bCap_Close_Client(&fd);
}
return 0;
};
<|endoftext|> |
<commit_before>//===-- ElimAvailExtern.cpp - DCE unreachable internal functions ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate available external global
// definitions from the program, turning them into declarations.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/Pass.h"
using namespace llvm;
#define DEBUG_TYPE "elim-avail-extern"
STATISTIC(NumAliases , "Number of global aliases removed");
STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");
namespace {
struct EliminateAvailableExternally : public ModulePass {
static char ID; // Pass identification, replacement for typeid
EliminateAvailableExternally() : ModulePass(ID) {
initializeEliminateAvailableExternallyPass(
*PassRegistry::getPassRegistry());
}
// run - Do the EliminateAvailableExternally pass on the specified module,
// optionally updating the specified callgraph to reflect the changes.
//
bool runOnModule(Module &M) override;
};
}
char EliminateAvailableExternally::ID = 0;
INITIALIZE_PASS(EliminateAvailableExternally, "elim-avail-extern",
"Eliminate Available Externally Globals", false, false)
ModulePass *llvm::createEliminateAvailableExternallyPass() {
return new EliminateAvailableExternally();
}
bool EliminateAvailableExternally::runOnModule(Module &M) {
bool Changed = false;
// Drop initializers of available externally global variables.
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) {
if (!I->hasAvailableExternallyLinkage())
continue;
if (I->hasInitializer()) {
Constant *Init = I->getInitializer();
I->setInitializer(nullptr);
if (isSafeToDestroyConstant(Init))
Init->destroyConstant();
}
I->removeDeadConstantUsers();
I->setLinkage(GlobalValue::ExternalLinkage);
NumVariables++;
}
// Drop the bodies of available externally functions.
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (!I->hasAvailableExternallyLinkage())
continue;
if (!I->isDeclaration())
// This will set the linkage to external
I->deleteBody();
I->removeDeadConstantUsers();
NumFunctions++;
}
// Drop targets of available externally aliases.
for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
++I) {
if (!I->hasAvailableExternallyLinkage())
continue;
I->setAliasee(nullptr);
I->removeDeadConstantUsers();
I->setLinkage(GlobalValue::ExternalLinkage);
NumAliases++;
}
return Changed;
}
<commit_msg>Aliases don't have available_externally linkage.<commit_after>//===-- ElimAvailExtern.cpp - DCE unreachable internal functions ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate available external global
// definitions from the program, turning them into declarations.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/Pass.h"
using namespace llvm;
#define DEBUG_TYPE "elim-avail-extern"
STATISTIC(NumAliases , "Number of global aliases removed");
STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");
namespace {
struct EliminateAvailableExternally : public ModulePass {
static char ID; // Pass identification, replacement for typeid
EliminateAvailableExternally() : ModulePass(ID) {
initializeEliminateAvailableExternallyPass(
*PassRegistry::getPassRegistry());
}
// run - Do the EliminateAvailableExternally pass on the specified module,
// optionally updating the specified callgraph to reflect the changes.
//
bool runOnModule(Module &M) override;
};
}
char EliminateAvailableExternally::ID = 0;
INITIALIZE_PASS(EliminateAvailableExternally, "elim-avail-extern",
"Eliminate Available Externally Globals", false, false)
ModulePass *llvm::createEliminateAvailableExternallyPass() {
return new EliminateAvailableExternally();
}
bool EliminateAvailableExternally::runOnModule(Module &M) {
bool Changed = false;
// Drop initializers of available externally global variables.
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) {
if (!I->hasAvailableExternallyLinkage())
continue;
if (I->hasInitializer()) {
Constant *Init = I->getInitializer();
I->setInitializer(nullptr);
if (isSafeToDestroyConstant(Init))
Init->destroyConstant();
}
I->removeDeadConstantUsers();
I->setLinkage(GlobalValue::ExternalLinkage);
NumVariables++;
}
// Drop the bodies of available externally functions.
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (!I->hasAvailableExternallyLinkage())
continue;
if (!I->isDeclaration())
// This will set the linkage to external
I->deleteBody();
I->removeDeadConstantUsers();
NumFunctions++;
}
return Changed;
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Fangfang Bai, fangfang@multicorewareinc.com
// Jin Ma, jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "perf_precomp.hpp"
using namespace perf;
using namespace std;
using namespace cv::ocl;
using namespace cv;
#if defined(HAVE_XINE) || \
defined(HAVE_GSTREAMER) || \
defined(HAVE_QUICKTIME) || \
defined(HAVE_AVFOUNDATION) || \
defined(HAVE_FFMPEG) || \
defined(WIN32)
# define BUILD_WITH_VIDEO_INPUT_SUPPORT 1
#else
# define BUILD_WITH_VIDEO_INPUT_SUPPORT 0
#endif
static void cvtFrameFmt(vector<Mat>& input, vector<Mat>& output, int output_cn)
{
for(int i = 0; i< (int)(input.size()); i++)
{
if(output_cn == 1)
cvtColor(input[i], output[i], COLOR_RGB2GRAY);
else
cvtColor(input[i], output[i], COLOR_RGB2RGBA);
}
}
static void prepareData(VideoCapture& cap, int cn, vector<Mat>& frame_buffer, vector<oclMat>& frame_buffer_ocl)
{
cv::Mat frame;
std::vector<Mat> frame_buffer_init;
int nFrame = (int)frame_buffer.size();
for(int i = 0; i < nFrame; i++)
{
cap >> frame;
ASSERT_FALSE(frame.empty());
frame_buffer_init.push_back(frame);
}
if(cn == 1)
cvtFrameFmt(frame_buffer_init, frame_buffer, 1);
else
frame_buffer = frame_buffer_init;
for(int i = 0; i < nFrame; i++)
frame_buffer_ocl.push_back(cv::ocl::oclMat(frame_buffer[i]));
}
///////////// MOG ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT
typedef tuple<string, int, double> VideoMOGParamType;
typedef TestBaseWithParam<VideoMOGParamType> VideoMOGFixture;
PERF_TEST_P(VideoMOGFixture, MOG,
::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
::testing::Values(1, 3),
::testing::Values(0.0, 0.01)))
{
VideoMOGParamType params = GetParam();
const string inputFile = perf::TestBase::getDataPath(get<0>(params));
const int cn = get<1>(params);
const float learningRate = static_cast<float>(get<2>(params));
const int nFrame = 5;
Mat foreground_cpu;
std::vector<Mat> frame_buffer(nFrame);
std::vector<oclMat> frame_buffer_ocl;
cv::VideoCapture cap(inputFile);
ASSERT_TRUE(cap.isOpened());
prepareData(cap, cn, frame_buffer, frame_buffer_ocl);
if(RUN_PLAIN_IMPL)
{
cv::BackgroundSubtractorMOG mog;
cv::Mat foreground;
TEST_CYCLE()
{
for (int i = 0; i < nFrame; i++)
{
mog(frame_buffer[i], foreground, learningRate);
}
}
SANITY_CHECK(foreground);
}else if(RUN_OCL_IMPL)
{
cv::ocl::MOG d_mog;
cv::ocl::oclMat foreground;
cv::Mat foreground_h;
OCL_TEST_CYCLE()
{
for (int i = 0; i < nFrame; ++i)
{
d_mog(frame_buffer_ocl[i], foreground, learningRate);
}
}
foreground.download(foreground_h);
SANITY_CHECK(foreground_h);
}else
OCL_PERF_ELSE
}
#endif
///////////// MOG2 ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT
typedef tuple<string, int> VideoMOG2ParamType;
typedef TestBaseWithParam<VideoMOG2ParamType> VideoMOG2Fixture;
PERF_TEST_P(VideoMOG2Fixture, MOG2,
::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
::testing::Values(1, 3)))
{
VideoMOG2ParamType params = GetParam();
const string inputFile = perf::TestBase::getDataPath(get<0>(params));
const int cn = get<1>(params);
int nFrame = 5;
std::vector<cv::Mat> frame_buffer(nFrame);
std::vector<cv::ocl::oclMat> frame_buffer_ocl;
cv::VideoCapture cap(inputFile);
ASSERT_TRUE(cap.isOpened());
prepareData(cap, cn, frame_buffer, frame_buffer_ocl);
if(RUN_PLAIN_IMPL)
{
cv::BackgroundSubtractorMOG2 mog2;
cv::Mat foreground;
mog2.set("detectShadows", false);
TEST_CYCLE()
{
for (int i = 0; i < nFrame; i++)
{
mog2(frame_buffer[i], foreground);
}
}
SANITY_CHECK(foreground);
}else if(RUN_OCL_IMPL)
{
cv::ocl::MOG2 d_mog2;
cv::ocl::oclMat foreground;
cv::Mat foreground_h;
OCL_TEST_CYCLE()
{
for (int i = 0; i < nFrame; i++)
{
d_mog2(frame_buffer_ocl[i], foreground);
}
}
foreground.download(foreground_h);
SANITY_CHECK(foreground_h);
}else
OCL_PERF_ELSE
}
#endif
///////////// MOG2_GetBackgroundImage //////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT
typedef TestBaseWithParam<VideoMOG2ParamType> Video_MOG2GetBackgroundImage;
PERF_TEST_P(Video_MOG2GetBackgroundImage, MOG2,
::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
::testing::Values(1, 3)))
{
VideoMOG2ParamType params = GetParam();
const string inputFile = perf::TestBase::getDataPath(get<0>(params));
const int cn = get<1>(params);
int nFrame = 5;
std::vector<cv::Mat> frame_buffer(nFrame);
std::vector<cv::ocl::oclMat> frame_buffer_ocl;
cv::VideoCapture cap(inputFile);
ASSERT_TRUE(cap.isOpened());
prepareData(cap, cn, frame_buffer, frame_buffer_ocl);
if(RUN_PLAIN_IMPL)
{
cv::BackgroundSubtractorMOG2 mog2;
cv::Mat foreground;
cv::Mat background;
mog2.set("detectShadows", false);
TEST_CYCLE()
{
for (int i = 0; i < nFrame; i++)
{
mog2(frame_buffer[i], foreground);
}
mog2.getBackgroundImage(background);
}
SANITY_CHECK(background);
}else if(RUN_OCL_IMPL)
{
cv::ocl::MOG2 d_mog2;
cv::ocl::oclMat foreground;
cv::Mat background_h;
cv::ocl::oclMat background;
OCL_TEST_CYCLE()
{
for (int i = 0; i < nFrame; i++)
{
d_mog2(frame_buffer_ocl[i], foreground);
}
d_mog2.getBackgroundImage(background);
}
background.download(background_h);
SANITY_CHECK(background_h);
}else
OCL_PERF_ELSE
}
#endif<commit_msg>Revised performance test according to the feedback of the community.<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Fangfang Bai, fangfang@multicorewareinc.com
// Jin Ma, jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "perf_precomp.hpp"
using namespace perf;
using namespace std;
using namespace cv::ocl;
using namespace cv;
using std::tr1::tuple;
using std::tr1::get;
#if defined(HAVE_XINE) || \
defined(HAVE_GSTREAMER) || \
defined(HAVE_QUICKTIME) || \
defined(HAVE_AVFOUNDATION) || \
defined(HAVE_FFMPEG) || \
defined(WIN32)
# define BUILD_WITH_VIDEO_INPUT_SUPPORT 1
#else
# define BUILD_WITH_VIDEO_INPUT_SUPPORT 0
#endif
#if BUILD_WITH_VIDEO_INPUT_SUPPORT
static void cvtFrameFmt(vector<Mat>& input, vector<Mat>& output, int output_cn)
{
for(int i = 0; i< (int)(input.size()); i++)
{
if(output_cn == 1)
cvtColor(input[i], output[i], COLOR_RGB2GRAY);
else
cvtColor(input[i], output[i], COLOR_RGB2RGBA);
}
}
//prepare data for CPU
static void prepareData(VideoCapture& cap, int cn, vector<Mat>& frame_buffer)
{
cv::Mat frame;
std::vector<Mat> frame_buffer_init;
int nFrame = (int)frame_buffer.size();
for(int i = 0; i < nFrame; i++)
{
cap >> frame;
ASSERT_FALSE(frame.empty());
frame_buffer_init.push_back(frame);
}
if(cn == 1)
cvtFrameFmt(frame_buffer_init, frame_buffer, 1);
else
frame_buffer = frame_buffer_init;
}
//copy CPU data to GPU
static void prepareData(vector<Mat>& frame_buffer, vector<oclMat>& frame_buffer_ocl)
{
for(int i = 0; i < (int)frame_buffer.size(); i++)
frame_buffer_ocl.push_back(cv::ocl::oclMat(frame_buffer[i]));
}
#endif
///////////// MOG ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT
typedef tuple<string, int, double> VideoMOGParamType;
typedef TestBaseWithParam<VideoMOGParamType> VideoMOGFixture;
PERF_TEST_P(VideoMOGFixture, MOG,
::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
::testing::Values(1, 3),
::testing::Values(0.0, 0.01)))
{
VideoMOGParamType params = GetParam();
const string inputFile = perf::TestBase::getDataPath(get<0>(params));
const int cn = get<1>(params);
const float learningRate = static_cast<float>(get<2>(params));
const int nFrame = 5;
Mat foreground_cpu;
std::vector<Mat> frame_buffer(nFrame);
std::vector<oclMat> frame_buffer_ocl;
cv::VideoCapture cap(inputFile);
ASSERT_TRUE(cap.isOpened());
prepareData(cap, cn, frame_buffer);
cv::Mat foreground;
cv::ocl::oclMat foreground_d;
if(RUN_PLAIN_IMPL)
{
TEST_CYCLE()
{
cv::BackgroundSubtractorMOG mog;
foreground.release();
for (int i = 0; i < nFrame; i++)
{
mog(frame_buffer[i], foreground, learningRate);
}
}
SANITY_CHECK(foreground);
}else if(RUN_OCL_IMPL)
{
prepareData(frame_buffer, frame_buffer_ocl);
CV_Assert((int)(frame_buffer_ocl.size()) == nFrame);
OCL_TEST_CYCLE()
{
cv::ocl::MOG d_mog;
foreground_d.release();
for (int i = 0; i < nFrame; ++i)
{
d_mog(frame_buffer_ocl[i], foreground_d, learningRate);
}
}
foreground_d.download(foreground);
SANITY_CHECK(foreground);
}else
OCL_PERF_ELSE
}
#endif
///////////// MOG2 ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT
typedef tuple<string, int> VideoMOG2ParamType;
typedef TestBaseWithParam<VideoMOG2ParamType> VideoMOG2Fixture;
PERF_TEST_P(VideoMOG2Fixture, MOG2,
::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
::testing::Values(1, 3)))
{
VideoMOG2ParamType params = GetParam();
const string inputFile = perf::TestBase::getDataPath(get<0>(params));
const int cn = get<1>(params);
int nFrame = 5;
std::vector<cv::Mat> frame_buffer(nFrame);
std::vector<cv::ocl::oclMat> frame_buffer_ocl;
cv::VideoCapture cap(inputFile);
ASSERT_TRUE(cap.isOpened());
prepareData(cap, cn, frame_buffer);
cv::Mat foreground;
cv::ocl::oclMat foreground_d;
if(RUN_PLAIN_IMPL)
{
TEST_CYCLE()
{
cv::BackgroundSubtractorMOG2 mog2;
mog2.set("detectShadows", false);
foreground.release();
for (int i = 0; i < nFrame; i++)
{
mog2(frame_buffer[i], foreground);
}
}
SANITY_CHECK(foreground);
}else if(RUN_OCL_IMPL)
{
prepareData(frame_buffer, frame_buffer_ocl);
CV_Assert((int)(frame_buffer_ocl.size()) == nFrame);
OCL_TEST_CYCLE()
{
cv::ocl::MOG2 d_mog2;
foreground_d.release();
for (int i = 0; i < nFrame; i++)
{
d_mog2(frame_buffer_ocl[i], foreground_d);
}
}
foreground_d.download(foreground);
SANITY_CHECK(foreground);
}else
OCL_PERF_ELSE
}
#endif
///////////// MOG2_GetBackgroundImage //////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT
typedef TestBaseWithParam<VideoMOG2ParamType> Video_MOG2GetBackgroundImage;
PERF_TEST_P(Video_MOG2GetBackgroundImage, MOG2,
::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
::testing::Values(3)))
{
VideoMOG2ParamType params = GetParam();
const string inputFile = perf::TestBase::getDataPath(get<0>(params));
const int cn = get<1>(params);
int nFrame = 5;
std::vector<cv::Mat> frame_buffer(nFrame);
std::vector<cv::ocl::oclMat> frame_buffer_ocl;
cv::VideoCapture cap(inputFile);
ASSERT_TRUE(cap.isOpened());
prepareData(cap, cn, frame_buffer);
cv::Mat foreground;
cv::Mat background;
cv::ocl::oclMat foreground_d;
cv::ocl::oclMat background_d;
if(RUN_PLAIN_IMPL)
{
TEST_CYCLE()
{
cv::BackgroundSubtractorMOG2 mog2;
mog2.set("detectShadows", false);
foreground.release();
background.release();
for (int i = 0; i < nFrame; i++)
{
mog2(frame_buffer[i], foreground);
}
mog2.getBackgroundImage(background);
}
SANITY_CHECK(background);
}else if(RUN_OCL_IMPL)
{
prepareData(frame_buffer, frame_buffer_ocl);
CV_Assert((int)(frame_buffer_ocl.size()) == nFrame);
OCL_TEST_CYCLE()
{
cv::ocl::MOG2 d_mog2;
foreground_d.release();
background_d.release();
for (int i = 0; i < nFrame; i++)
{
d_mog2(frame_buffer_ocl[i], foreground_d);
}
d_mog2.getBackgroundImage(background_d);
}
background_d.download(background);
SANITY_CHECK(background);
}else
OCL_PERF_ELSE
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mnemonic.cxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: hr $ $Date: 2007-06-27 20:32:25 $
*
* 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_vcl.hxx"
#include <string.h>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <vcl/mnemonic.hxx>
#include <vcl/unohelp.hxx>
#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif
using namespace ::com::sun::star;
// =======================================================================
MnemonicGenerator::MnemonicGenerator()
{
memset( maMnemonics, 1, sizeof( maMnemonics ) );
}
// -----------------------------------------------------------------------
USHORT MnemonicGenerator::ImplGetMnemonicIndex( sal_Unicode c )
{
static USHORT const aImplMnemonicRangeTab[MNEMONIC_RANGES*2] =
{
MNEMONIC_RANGE_1_START, MNEMONIC_RANGE_1_END,
MNEMONIC_RANGE_2_START, MNEMONIC_RANGE_2_END,
MNEMONIC_RANGE_3_START, MNEMONIC_RANGE_3_END,
MNEMONIC_RANGE_4_START, MNEMONIC_RANGE_4_END
};
USHORT nMnemonicIndex = 0;
for ( USHORT i = 0; i < MNEMONIC_RANGES; i++ )
{
if ( (c >= aImplMnemonicRangeTab[i*2]) &&
(c <= aImplMnemonicRangeTab[i*2+1]) )
return nMnemonicIndex+c-aImplMnemonicRangeTab[i*2];
nMnemonicIndex += aImplMnemonicRangeTab[i*2+1]-aImplMnemonicRangeTab[i*2];
}
return MNEMONIC_INDEX_NOTFOUND;
}
// -----------------------------------------------------------------------
sal_Unicode MnemonicGenerator::ImplFindMnemonic( const XubString& rKey )
{
xub_StrLen nIndex = 0;
while ( (nIndex = rKey.Search( MNEMONIC_CHAR, nIndex )) != STRING_NOTFOUND )
{
sal_Unicode cMnemonic = rKey.GetChar( nIndex+1 );
if ( cMnemonic != MNEMONIC_CHAR )
return cMnemonic;
nIndex += 2;
}
return 0;
}
// -----------------------------------------------------------------------
void MnemonicGenerator::RegisterMnemonic( const XubString& rKey )
{
const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();
// Don't crash even when we don't have access to i18n service
if ( !xCharClass.is() )
return;
XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );
// If we find a Mnemonic, set the flag. In other case count the
// characters, because we need this to set most as possible
// Mnemonics
sal_Unicode cMnemonic = ImplFindMnemonic( aKey );
if ( cMnemonic )
{
USHORT nMnemonicIndex = ImplGetMnemonicIndex( cMnemonic );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
maMnemonics[nMnemonicIndex] = 0;
}
else
{
xub_StrLen nIndex = 0;
xub_StrLen nLen = aKey.Len();
while ( nIndex < nLen )
{
sal_Unicode c = aKey.GetChar( nIndex );
USHORT nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] && (maMnemonics[nMnemonicIndex] < 0xFF) )
maMnemonics[nMnemonicIndex]++;
}
nIndex++;
}
}
}
// -----------------------------------------------------------------------
BOOL MnemonicGenerator::CreateMnemonic( XubString& rKey )
{
if ( !rKey.Len() || ImplFindMnemonic( rKey ) )
return FALSE;
const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();
// Don't crash even when we don't have access to i18n service
if ( !xCharClass.is() )
return FALSE;
XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );
BOOL bChanged = FALSE;
xub_StrLen nLen = aKey.Len();
BOOL bCJK = FALSE;
switch( Application::GetSettings().GetUILanguage() )
{
case LANGUAGE_JAPANESE:
case LANGUAGE_CHINESE_TRADITIONAL:
case LANGUAGE_CHINESE_SIMPLIFIED:
case LANGUAGE_CHINESE_HONGKONG:
case LANGUAGE_CHINESE_SINGAPORE:
case LANGUAGE_CHINESE_MACAU:
case LANGUAGE_KOREAN:
case LANGUAGE_KOREAN_JOHAB:
bCJK = TRUE;
break;
default:
break;
}
// #107889# in CJK versions ALL strings (even those that contain latin characters)
// will get mnemonics in the form: xyz (M)
// thus steps 1) and 2) are skipped for CJK locales
// #110720#, avoid CJK-style mnemonics for latin-only strings that do not contain useful mnemonic chars
if( bCJK )
{
BOOL bLatinOnly = TRUE;
BOOL bMnemonicIndexFound = FALSE;
sal_Unicode c;
xub_StrLen nIndex;
for( nIndex=0; nIndex < nLen; nIndex++ )
{
c = aKey.GetChar( nIndex );
if ( ((c >= 0x3000) && (c <= 0xD7FF)) || // cjk
((c >= 0xFF61) && (c <= 0xFFDC)) ) // halfwidth forms
{
bLatinOnly = FALSE;
break;
}
if( ImplGetMnemonicIndex( c ) != MNEMONIC_INDEX_NOTFOUND )
bMnemonicIndexFound = TRUE;
}
if( bLatinOnly && !bMnemonicIndexFound )
return FALSE;
}
int nCJK = 0;
USHORT nMnemonicIndex;
sal_Unicode c;
xub_StrLen nIndex = 0;
if( !bCJK )
{
// 1) first try the first character of a word
do
{
c = aKey.GetChar( nIndex );
if ( nCJK != 2 )
{
if ( ((c >= 0x3000) && (c <= 0xD7FF)) || // cjk
((c >= 0xFF61) && (c <= 0xFFDC)) ) // halfwidth forms
nCJK = 1;
else if ( ((c >= 0x0030) && (c <= 0x0039)) || // digits
((c >= 0x0041) && (c <= 0x005A)) || // latin capitals
((c >= 0x0061) && (c <= 0x007A)) || // latin small
((c >= 0x0370) && (c <= 0x037F)) || // greek numeral signs
((c >= 0x0400) && (c <= 0x04FF)) ) // cyrillic
nCJK = 2;
}
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] )
{
maMnemonics[nMnemonicIndex] = 0;
rKey.Insert( MNEMONIC_CHAR, nIndex );
bChanged = TRUE;
break;
}
}
// Search for next word
do
{
nIndex++;
c = aKey.GetChar( nIndex );
if ( c == ' ' )
break;
}
while ( nIndex < nLen );
nIndex++;
}
while ( nIndex < nLen );
// 2) search for a unique/uncommon character
if ( !bChanged )
{
USHORT nBestCount = 0xFFFF;
USHORT nBestMnemonicIndex = 0;
xub_StrLen nBestIndex = 0;
nIndex = 0;
do
{
c = aKey.GetChar( nIndex );
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] )
{
if ( maMnemonics[nMnemonicIndex] < nBestCount )
{
nBestCount = maMnemonics[nMnemonicIndex];
nBestIndex = nIndex;
nBestMnemonicIndex = nMnemonicIndex;
if ( nBestCount == 2 )
break;
}
}
}
nIndex++;
}
while ( nIndex < nLen );
if ( nBestCount != 0xFFFF )
{
maMnemonics[nBestMnemonicIndex] = 0;
rKey.Insert( MNEMONIC_CHAR, nBestIndex );
bChanged = TRUE;
}
}
}
else
nCJK = 1;
// 3) Add English Mnemonic for CJK Text
if ( !bChanged && (nCJK == 1) && rKey.Len() )
{
// Append Ascii Mnemonic
for ( c = MNEMONIC_RANGE_2_START; c <= MNEMONIC_RANGE_2_END; c++ )
{
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] )
{
maMnemonics[nMnemonicIndex] = 0;
UniString aStr( '(' );
aStr += MNEMONIC_CHAR;
aStr += c;
aStr += ')';
nIndex = rKey.Len();
if( nIndex >= 2 )
{
static sal_Unicode cGreaterGreater[] = { 0xFF1E, 0xFF1E };
if ( rKey.EqualsAscii( ">>", nIndex-2, 2 ) ||
rKey.Equals( cGreaterGreater, nIndex-2, 2 ) )
nIndex -= 2;
}
if( nIndex >= 3 )
{
static sal_Unicode cDotDotDot[] = { 0xFF0E, 0xFF0E, 0xFF0E };
if ( rKey.EqualsAscii( "...", nIndex-3, 3 ) ||
rKey.Equals( cDotDotDot, nIndex-3, 3 ) )
nIndex -= 3;
}
if( nIndex >= 1)
{
sal_Unicode cLastChar = rKey.GetChar( nIndex-1 );
if ( (cLastChar == ':') || (cLastChar == 0xFF1A) ||
(cLastChar == '.') || (cLastChar == 0xFF0E) ||
(cLastChar == '?') || (cLastChar == 0xFF1F) ||
(cLastChar == ' ') )
nIndex--;
}
rKey.Insert( aStr, nIndex );
bChanged = TRUE;
break;
}
}
}
}
if( ! bChanged )
{
/*
* #97809# if all else fails use the first character of a word
* anyway and live with duplicate mnemonics
*/
nIndex = 0;
do
{
c = aKey.GetChar( nIndex );
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
maMnemonics[nMnemonicIndex] = 0;
rKey.Insert( MNEMONIC_CHAR, nIndex );
bChanged = TRUE;
break;
}
// Search for next word
do
{
nIndex++;
c = aKey.GetChar( nIndex );
if ( c == ' ' )
break;
}
while ( nIndex < nLen );
nIndex++;
}
while ( nIndex < nLen );
}
return bChanged;
}
// -----------------------------------------------------------------------
uno::Reference< i18n::XCharacterClassification > MnemonicGenerator::GetCharClass()
{
if ( !mxCharClass.is() )
mxCharClass = vcl::unohelper::CreateCharacterClassification();
return mxCharClass;
}
// -----------------------------------------------------------------------
String MnemonicGenerator::EraseAllMnemonicChars( const String& rStr )
{
String aStr = rStr;
xub_StrLen nLen = aStr.Len();
xub_StrLen i = 0;
while ( i < nLen )
{
if ( aStr.GetChar( i ) == '~' )
{
// check for CJK-style mnemonic
if( i > 0 && (i+2) < nLen )
{
sal_Unicode c = aStr.GetChar(i+1);
if( aStr.GetChar( i-1 ) == '(' &&
aStr.GetChar( i+2 ) == ')' &&
c >= MNEMONIC_RANGE_2_START && c <= MNEMONIC_RANGE_2_END )
{
aStr.Erase( i-1, 4 );
nLen -= 4;
i--;
continue;
}
}
// remove standard mnemonics
aStr.Erase( i, 1 );
nLen--;
}
else
i++;
}
return aStr;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.21.248); FILE MERGED 2008/04/01 13:01:47 thb 1.21.248.2: #i85898# Stripping all external header guards 2008/03/28 15:45:02 rt 1.21.248.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mnemonic.cxx,v $
* $Revision: 1.22 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <string.h>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <vcl/mnemonic.hxx>
#include <vcl/unohelp.hxx>
#include <com/sun/star/i18n/XCharacterClassification.hpp>
using namespace ::com::sun::star;
// =======================================================================
MnemonicGenerator::MnemonicGenerator()
{
memset( maMnemonics, 1, sizeof( maMnemonics ) );
}
// -----------------------------------------------------------------------
USHORT MnemonicGenerator::ImplGetMnemonicIndex( sal_Unicode c )
{
static USHORT const aImplMnemonicRangeTab[MNEMONIC_RANGES*2] =
{
MNEMONIC_RANGE_1_START, MNEMONIC_RANGE_1_END,
MNEMONIC_RANGE_2_START, MNEMONIC_RANGE_2_END,
MNEMONIC_RANGE_3_START, MNEMONIC_RANGE_3_END,
MNEMONIC_RANGE_4_START, MNEMONIC_RANGE_4_END
};
USHORT nMnemonicIndex = 0;
for ( USHORT i = 0; i < MNEMONIC_RANGES; i++ )
{
if ( (c >= aImplMnemonicRangeTab[i*2]) &&
(c <= aImplMnemonicRangeTab[i*2+1]) )
return nMnemonicIndex+c-aImplMnemonicRangeTab[i*2];
nMnemonicIndex += aImplMnemonicRangeTab[i*2+1]-aImplMnemonicRangeTab[i*2];
}
return MNEMONIC_INDEX_NOTFOUND;
}
// -----------------------------------------------------------------------
sal_Unicode MnemonicGenerator::ImplFindMnemonic( const XubString& rKey )
{
xub_StrLen nIndex = 0;
while ( (nIndex = rKey.Search( MNEMONIC_CHAR, nIndex )) != STRING_NOTFOUND )
{
sal_Unicode cMnemonic = rKey.GetChar( nIndex+1 );
if ( cMnemonic != MNEMONIC_CHAR )
return cMnemonic;
nIndex += 2;
}
return 0;
}
// -----------------------------------------------------------------------
void MnemonicGenerator::RegisterMnemonic( const XubString& rKey )
{
const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();
// Don't crash even when we don't have access to i18n service
if ( !xCharClass.is() )
return;
XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );
// If we find a Mnemonic, set the flag. In other case count the
// characters, because we need this to set most as possible
// Mnemonics
sal_Unicode cMnemonic = ImplFindMnemonic( aKey );
if ( cMnemonic )
{
USHORT nMnemonicIndex = ImplGetMnemonicIndex( cMnemonic );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
maMnemonics[nMnemonicIndex] = 0;
}
else
{
xub_StrLen nIndex = 0;
xub_StrLen nLen = aKey.Len();
while ( nIndex < nLen )
{
sal_Unicode c = aKey.GetChar( nIndex );
USHORT nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] && (maMnemonics[nMnemonicIndex] < 0xFF) )
maMnemonics[nMnemonicIndex]++;
}
nIndex++;
}
}
}
// -----------------------------------------------------------------------
BOOL MnemonicGenerator::CreateMnemonic( XubString& rKey )
{
if ( !rKey.Len() || ImplFindMnemonic( rKey ) )
return FALSE;
const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();
// Don't crash even when we don't have access to i18n service
if ( !xCharClass.is() )
return FALSE;
XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );
BOOL bChanged = FALSE;
xub_StrLen nLen = aKey.Len();
BOOL bCJK = FALSE;
switch( Application::GetSettings().GetUILanguage() )
{
case LANGUAGE_JAPANESE:
case LANGUAGE_CHINESE_TRADITIONAL:
case LANGUAGE_CHINESE_SIMPLIFIED:
case LANGUAGE_CHINESE_HONGKONG:
case LANGUAGE_CHINESE_SINGAPORE:
case LANGUAGE_CHINESE_MACAU:
case LANGUAGE_KOREAN:
case LANGUAGE_KOREAN_JOHAB:
bCJK = TRUE;
break;
default:
break;
}
// #107889# in CJK versions ALL strings (even those that contain latin characters)
// will get mnemonics in the form: xyz (M)
// thus steps 1) and 2) are skipped for CJK locales
// #110720#, avoid CJK-style mnemonics for latin-only strings that do not contain useful mnemonic chars
if( bCJK )
{
BOOL bLatinOnly = TRUE;
BOOL bMnemonicIndexFound = FALSE;
sal_Unicode c;
xub_StrLen nIndex;
for( nIndex=0; nIndex < nLen; nIndex++ )
{
c = aKey.GetChar( nIndex );
if ( ((c >= 0x3000) && (c <= 0xD7FF)) || // cjk
((c >= 0xFF61) && (c <= 0xFFDC)) ) // halfwidth forms
{
bLatinOnly = FALSE;
break;
}
if( ImplGetMnemonicIndex( c ) != MNEMONIC_INDEX_NOTFOUND )
bMnemonicIndexFound = TRUE;
}
if( bLatinOnly && !bMnemonicIndexFound )
return FALSE;
}
int nCJK = 0;
USHORT nMnemonicIndex;
sal_Unicode c;
xub_StrLen nIndex = 0;
if( !bCJK )
{
// 1) first try the first character of a word
do
{
c = aKey.GetChar( nIndex );
if ( nCJK != 2 )
{
if ( ((c >= 0x3000) && (c <= 0xD7FF)) || // cjk
((c >= 0xFF61) && (c <= 0xFFDC)) ) // halfwidth forms
nCJK = 1;
else if ( ((c >= 0x0030) && (c <= 0x0039)) || // digits
((c >= 0x0041) && (c <= 0x005A)) || // latin capitals
((c >= 0x0061) && (c <= 0x007A)) || // latin small
((c >= 0x0370) && (c <= 0x037F)) || // greek numeral signs
((c >= 0x0400) && (c <= 0x04FF)) ) // cyrillic
nCJK = 2;
}
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] )
{
maMnemonics[nMnemonicIndex] = 0;
rKey.Insert( MNEMONIC_CHAR, nIndex );
bChanged = TRUE;
break;
}
}
// Search for next word
do
{
nIndex++;
c = aKey.GetChar( nIndex );
if ( c == ' ' )
break;
}
while ( nIndex < nLen );
nIndex++;
}
while ( nIndex < nLen );
// 2) search for a unique/uncommon character
if ( !bChanged )
{
USHORT nBestCount = 0xFFFF;
USHORT nBestMnemonicIndex = 0;
xub_StrLen nBestIndex = 0;
nIndex = 0;
do
{
c = aKey.GetChar( nIndex );
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] )
{
if ( maMnemonics[nMnemonicIndex] < nBestCount )
{
nBestCount = maMnemonics[nMnemonicIndex];
nBestIndex = nIndex;
nBestMnemonicIndex = nMnemonicIndex;
if ( nBestCount == 2 )
break;
}
}
}
nIndex++;
}
while ( nIndex < nLen );
if ( nBestCount != 0xFFFF )
{
maMnemonics[nBestMnemonicIndex] = 0;
rKey.Insert( MNEMONIC_CHAR, nBestIndex );
bChanged = TRUE;
}
}
}
else
nCJK = 1;
// 3) Add English Mnemonic for CJK Text
if ( !bChanged && (nCJK == 1) && rKey.Len() )
{
// Append Ascii Mnemonic
for ( c = MNEMONIC_RANGE_2_START; c <= MNEMONIC_RANGE_2_END; c++ )
{
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
if ( maMnemonics[nMnemonicIndex] )
{
maMnemonics[nMnemonicIndex] = 0;
UniString aStr( '(' );
aStr += MNEMONIC_CHAR;
aStr += c;
aStr += ')';
nIndex = rKey.Len();
if( nIndex >= 2 )
{
static sal_Unicode cGreaterGreater[] = { 0xFF1E, 0xFF1E };
if ( rKey.EqualsAscii( ">>", nIndex-2, 2 ) ||
rKey.Equals( cGreaterGreater, nIndex-2, 2 ) )
nIndex -= 2;
}
if( nIndex >= 3 )
{
static sal_Unicode cDotDotDot[] = { 0xFF0E, 0xFF0E, 0xFF0E };
if ( rKey.EqualsAscii( "...", nIndex-3, 3 ) ||
rKey.Equals( cDotDotDot, nIndex-3, 3 ) )
nIndex -= 3;
}
if( nIndex >= 1)
{
sal_Unicode cLastChar = rKey.GetChar( nIndex-1 );
if ( (cLastChar == ':') || (cLastChar == 0xFF1A) ||
(cLastChar == '.') || (cLastChar == 0xFF0E) ||
(cLastChar == '?') || (cLastChar == 0xFF1F) ||
(cLastChar == ' ') )
nIndex--;
}
rKey.Insert( aStr, nIndex );
bChanged = TRUE;
break;
}
}
}
}
if( ! bChanged )
{
/*
* #97809# if all else fails use the first character of a word
* anyway and live with duplicate mnemonics
*/
nIndex = 0;
do
{
c = aKey.GetChar( nIndex );
nMnemonicIndex = ImplGetMnemonicIndex( c );
if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
{
maMnemonics[nMnemonicIndex] = 0;
rKey.Insert( MNEMONIC_CHAR, nIndex );
bChanged = TRUE;
break;
}
// Search for next word
do
{
nIndex++;
c = aKey.GetChar( nIndex );
if ( c == ' ' )
break;
}
while ( nIndex < nLen );
nIndex++;
}
while ( nIndex < nLen );
}
return bChanged;
}
// -----------------------------------------------------------------------
uno::Reference< i18n::XCharacterClassification > MnemonicGenerator::GetCharClass()
{
if ( !mxCharClass.is() )
mxCharClass = vcl::unohelper::CreateCharacterClassification();
return mxCharClass;
}
// -----------------------------------------------------------------------
String MnemonicGenerator::EraseAllMnemonicChars( const String& rStr )
{
String aStr = rStr;
xub_StrLen nLen = aStr.Len();
xub_StrLen i = 0;
while ( i < nLen )
{
if ( aStr.GetChar( i ) == '~' )
{
// check for CJK-style mnemonic
if( i > 0 && (i+2) < nLen )
{
sal_Unicode c = aStr.GetChar(i+1);
if( aStr.GetChar( i-1 ) == '(' &&
aStr.GetChar( i+2 ) == ')' &&
c >= MNEMONIC_RANGE_2_START && c <= MNEMONIC_RANGE_2_END )
{
aStr.Erase( i-1, 4 );
nLen -= 4;
i--;
continue;
}
}
// remove standard mnemonics
aStr.Erase( i, 1 );
nLen--;
}
else
i++;
}
return aStr;
}
<|endoftext|> |
<commit_before>
#include <imgui.cpp>
<commit_msg>Include all imgui files<commit_after>
#include <imgui.cpp>
#include <imgui_draw.cpp>
#include <imgui_demo.cpp>
<|endoftext|> |
<commit_before><commit_msg>init members in correct order<commit_after><|endoftext|> |
<commit_before>#include <pistache/stream.h>
#include "gtest/gtest.h"
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
using namespace Pistache;
TEST(stream, test_buffer) {
char str[] = "test_string";
size_t len = strlen(str);
RawBuffer buffer1(str, len, false);
RawBuffer buffer2 = buffer1.detach(0);
ASSERT_EQ(buffer2.size(), len);
ASSERT_EQ(buffer2.isDetached(), true);
RawBuffer buffer3;
ASSERT_EQ(buffer3.size(), 0u);
ASSERT_EQ(buffer3.isDetached(), false);
RawBuffer buffer4 = buffer3.detach(0);
ASSERT_EQ(buffer4.size(), 0u);
ASSERT_EQ(buffer4.isDetached(), false);
ASSERT_THROW(buffer1.detach(2 * len);, std::range_error);
}
TEST(stream, test_file_buffer) {
char fileName[PATH_MAX] = "/tmp/pistacheioXXXXXX";
if (!mkstemp(fileName)) {
std::cerr << "No suitable filename can be generated!" << std::endl;
}
std::cout << "Temporary file name: " << fileName << std::endl;
const std::string dataToWrite("Hello World!");
std::ofstream tmpFile;
tmpFile.open(fileName);
tmpFile << dataToWrite;
tmpFile.close();
FileBuffer fileBuffer(fileName);
ASSERT_NE(fileBuffer.fd(), -1);
ASSERT_EQ(fileBuffer.size(), dataToWrite.size());
std::remove(fileName);
}
TEST(stream, test_dyn_buffer) {
DynamicStreamBuf buf(128);
{
std::ostream os(&buf);
for (unsigned i = 0; i < 128; ++i) {
os << "A";
}
}
auto rawbuf = buf.buffer();
ASSERT_EQ(rawbuf.size(), 128u);
ASSERT_EQ(rawbuf.isDetached(), false);
ASSERT_EQ(rawbuf.data().size(), 128u);
ASSERT_EQ(strlen(rawbuf.data().c_str()), 128u);
}
TEST(stream, test_cursor_advance_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* part1 = "abcd";
buffer.feed(part1, strlen(part1));
ASSERT_EQ(cursor.current(), 'a');
ASSERT_TRUE(cursor.advance(1));
ASSERT_EQ(cursor.current(), 'b');
ASSERT_TRUE(cursor.advance(0));
ASSERT_EQ(cursor.current(), 'b');
ASSERT_TRUE(cursor.advance(1));
ASSERT_EQ(cursor.current(), 'c');
const char* part2 = "efgh";
buffer.feed(part2, strlen(part2));
ASSERT_TRUE(cursor.advance(2));
ASSERT_EQ(cursor.current(), 'e');
ASSERT_FALSE(cursor.advance(5));
}
TEST(stream, test_cursor_remaining_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* data = "abcd";
buffer.feed(data, strlen(data));
ASSERT_EQ(cursor.remaining(), 4u);
cursor.advance(2);
ASSERT_EQ(cursor.remaining(), 2u);
cursor.advance(1);
ASSERT_EQ(cursor.remaining(), 1u);
cursor.advance(1);
ASSERT_EQ(cursor.remaining(), 0u);
}
TEST(stream, test_cursor_eol_eof_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* data = "abcd\r\nefgh";
buffer.feed(data, strlen(data));
cursor.advance(4);
ASSERT_TRUE(cursor.eol());
ASSERT_FALSE(cursor.eof());
cursor.advance(2);
ASSERT_FALSE(cursor.eol());
ASSERT_FALSE(cursor.eof());
cursor.advance(4);
ASSERT_FALSE(cursor.eol());
ASSERT_TRUE(cursor.eof());
}
TEST(stream, test_cursor_offset_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* data = "abcdefgh";
buffer.feed(data, strlen(data));
cursor.advance(4);
ASSERT_TRUE(strcmp(cursor.offset(), "efgh"));
}
TEST(stream, test_cursor_diff_for_array) {
ArrayStreamBuf<char> buffer1;
StreamCursor first_cursor{&buffer1};
ArrayStreamBuf<char> buffer2;
StreamCursor second_cursor{&buffer2};
const char* data = "abcdefgh";
buffer1.feed(data, strlen(data));
buffer2.feed(data, strlen(data));
ASSERT_EQ(first_cursor.diff(second_cursor), 0u);
ASSERT_EQ(second_cursor.diff(first_cursor), 0u);
first_cursor.advance(4);
ASSERT_EQ(second_cursor.diff(first_cursor), 4u);
second_cursor.advance(4);
ASSERT_EQ(second_cursor.diff(first_cursor), 0u);
}<commit_msg>Fix stream unit test<commit_after>#include <pistache/stream.h>
#include "gtest/gtest.h"
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
using namespace Pistache;
TEST(stream, test_buffer) {
char str[] = "test_string";
size_t len = strlen(str);
RawBuffer buffer1(str, len, false);
RawBuffer buffer2 = buffer1.detach(0);
ASSERT_EQ(buffer2.size(), len);
ASSERT_EQ(buffer2.isDetached(), true);
RawBuffer buffer3;
ASSERT_EQ(buffer3.size(), 0u);
ASSERT_EQ(buffer3.isDetached(), false);
RawBuffer buffer4 = buffer3.detach(0);
ASSERT_EQ(buffer4.size(), 0u);
ASSERT_EQ(buffer4.isDetached(), false);
ASSERT_THROW(buffer1.detach(2 * len);, std::range_error);
}
TEST(stream, test_file_buffer) {
char fileName[PATH_MAX] = "/tmp/pistacheioXXXXXX";
if (!mkstemp(fileName)) {
std::cerr << "No suitable filename can be generated!" << std::endl;
}
std::cout << "Temporary file name: " << fileName << std::endl;
const std::string dataToWrite("Hello World!");
std::ofstream tmpFile;
tmpFile.open(fileName);
tmpFile << dataToWrite;
tmpFile.close();
FileBuffer fileBuffer(fileName);
ASSERT_NE(fileBuffer.fd(), -1);
ASSERT_EQ(fileBuffer.size(), dataToWrite.size());
std::remove(fileName);
}
TEST(stream, test_dyn_buffer) {
DynamicStreamBuf buf(128);
{
std::ostream os(&buf);
for (unsigned i = 0; i < 128; ++i) {
os << "A";
}
}
auto rawbuf = buf.buffer();
ASSERT_EQ(rawbuf.size(), 128u);
ASSERT_EQ(rawbuf.isDetached(), false);
ASSERT_EQ(rawbuf.data().size(), 128u);
ASSERT_EQ(strlen(rawbuf.data().c_str()), 128u);
}
TEST(stream, test_cursor_advance_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* part1 = "abcd";
buffer.feed(part1, strlen(part1));
ASSERT_EQ(cursor.current(), 'a');
ASSERT_TRUE(cursor.advance(1));
ASSERT_EQ(cursor.current(), 'b');
ASSERT_TRUE(cursor.advance(0));
ASSERT_EQ(cursor.current(), 'b');
ASSERT_TRUE(cursor.advance(1));
ASSERT_EQ(cursor.current(), 'c');
const char* part2 = "efgh";
buffer.feed(part2, strlen(part2));
ASSERT_TRUE(cursor.advance(2));
ASSERT_EQ(cursor.current(), 'e');
ASSERT_FALSE(cursor.advance(5));
}
TEST(stream, test_cursor_remaining_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* data = "abcd";
buffer.feed(data, strlen(data));
ASSERT_EQ(cursor.remaining(), 4u);
cursor.advance(2);
ASSERT_EQ(cursor.remaining(), 2u);
cursor.advance(1);
ASSERT_EQ(cursor.remaining(), 1u);
cursor.advance(1);
ASSERT_EQ(cursor.remaining(), 0u);
}
TEST(stream, test_cursor_eol_eof_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* data = "abcd\r\nefgh";
buffer.feed(data, strlen(data));
cursor.advance(4);
ASSERT_TRUE(cursor.eol());
ASSERT_FALSE(cursor.eof());
cursor.advance(2);
ASSERT_FALSE(cursor.eol());
ASSERT_FALSE(cursor.eof());
cursor.advance(4);
ASSERT_FALSE(cursor.eol());
ASSERT_TRUE(cursor.eof());
}
TEST(stream, test_cursor_offset_for_array) {
ArrayStreamBuf<char> buffer;
StreamCursor cursor{&buffer};
const char* data = "abcdefgh";
buffer.feed(data, strlen(data));
size_t shift = 4u;
cursor.advance(shift);
std::string result{cursor.offset(), strlen(data) - shift};
ASSERT_EQ(result, "efgh");
}
TEST(stream, test_cursor_diff_for_array) {
ArrayStreamBuf<char> buffer1;
StreamCursor first_cursor{&buffer1};
ArrayStreamBuf<char> buffer2;
StreamCursor second_cursor{&buffer2};
const char* data = "abcdefgh";
buffer1.feed(data, strlen(data));
buffer2.feed(data, strlen(data));
ASSERT_EQ(first_cursor.diff(second_cursor), 0u);
ASSERT_EQ(second_cursor.diff(first_cursor), 0u);
first_cursor.advance(4);
ASSERT_EQ(second_cursor.diff(first_cursor), 4u);
second_cursor.advance(4);
ASSERT_EQ(second_cursor.diff(first_cursor), 0u);
}
<|endoftext|> |
<commit_before><commit_msg>fix unit tests<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2015 Martin Raiber
*
* 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 "PipeFile.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "../config.h"
#if defined(HAVE_SPAWN_H)
#include <spawn.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#if defined(O_CLOEXEC) && !defined(__APPLE__) && !defined(__FreeBSD__)
#define clopipe(x) pipe2(x, O_CLOEXEC)
#else
int clopipe(int* x)
{
int rc = pipe(x);
if(rc!=0) return rc;
fcntl(x[0], F_SETFD, FD_CLOEXEC);
fcntl(x[1], F_SETFD, FD_CLOEXEC);
return rc;
}
#endif
PipeFile::PipeFile(const std::string& pCmd)
: PipeFileBase(pCmd),
hStderr(0),
hStdout(0)
{
int stdout_pipe[2];
if(clopipe(stdout_pipe) == -1)
{
Server->Log("Error creating stdout pipe: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
int stderr_pipe[2];
if(clopipe(stderr_pipe) == -1)
{
Server->Log("Error creating stderr pipe: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
#if defined(HAVE_SPAWN_H)
posix_spawn_file_actions_t fa;
if(posix_spawn_file_actions_init(&fa)!=0)
{
Server->Log("Error posix_spawn_file_actions_init: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
if(posix_spawn_file_actions_adddup2(&fa, stdout_pipe[1], STDOUT_FILENO)!=0)
{
Server->Log("Error posix_spawn_file_actions_adddup2(1): " + convert(errno), LL_ERROR);
has_error=true;
return;
}
if(posix_spawn_file_actions_adddup2(&fa, stderr_pipe[1], STDERR_FILENO)!=0)
{
Server->Log("Error posix_spawn_file_actions_adddup2(2): " + convert(errno), LL_ERROR);
has_error=true;
return;
}
const char* argv[] = {"sh", "-c", &pCmd[0], NULL};
const char* envp[] = {NULL};
if(posix_spawn(&child_pid, "/bin/sh", &fa, NULL, const_cast<char**>(argv), const_cast<char**>(envp))!=0)
{
Server->Log("Error executing command: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
close(stdout_pipe[1]);
close(stderr_pipe[1]);
hStdout = stdout_pipe[0];
hStderr = stderr_pipe[0];
init();
#else
child_pid = fork();
if(child_pid==-1)
{
Server->Log("Error forking to execute command: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
else if(child_pid==0)
{
while ((dup2(stdout_pipe[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
while ((dup2(stderr_pipe[1], STDERR_FILENO) == -1) && (errno == EINTR)) {}
close(stdout_pipe[0]);
close(stdout_pipe[1]);
close(stderr_pipe[0]);
close(stderr_pipe[1]);
int rc = system(pCmd.c_str());
if(rc>127)
{
rc = 127;
}
_exit(rc);
}
else
{
close(stdout_pipe[1]);
close(stderr_pipe[1]);
hStdout = stdout_pipe[0];
hStderr = stderr_pipe[0];
init();
}
#endif
}
PipeFile::~PipeFile()
{
}
void PipeFile::forceExitWait()
{
if(child_pid!=-1)
{
kill(child_pid, SIGKILL);
int status;
waitpid(child_pid, &status, 0);
}
close(hStdout);
close(hStderr);
waitForExit();
}
bool PipeFile::readIntoBuffer(int hStd, char* buf, size_t buf_avail, size_t& read_bytes)
{
ssize_t rc = read(hStd, buf, buf_avail);
if(rc==0 && errno==EINTR)
{
return readIntoBuffer(hStd, buf, buf_avail, read_bytes);
}
else if(rc<=0)
{
return false;
}
else
{
read_bytes = static_cast<size_t>(rc);
return true;
}
}
bool PipeFile::readStdoutIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes)
{
return readIntoBuffer(hStdout, buf, buf_avail, read_bytes);
}
bool PipeFile::readStderrIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes)
{
return readIntoBuffer(hStderr, buf, buf_avail, read_bytes);
}
bool PipeFile::getExitCode(int& exit_code)
{
int status;
int rc = waitpid(child_pid, &status, WNOHANG);
if(rc==-1)
{
Server->Log("Error while waiting for exit code: " + convert(errno), LL_ERROR);
return false;
}
else if(rc==0)
{
Server->Log("Process is still active", LL_ERROR);
return false;
}
else
{
child_pid=-1;
if(WIFEXITED(status))
{
exit_code = WEXITSTATUS(status);
return true;
}
else if(WIFSIGNALED(status))
{
Server->Log("Script was terminated by signal " + convert(WTERMSIG(status)), LL_ERROR);
return false;
}
else if(WCOREDUMP(status))
{
Server->Log("Script crashed", LL_ERROR);
return false;
}
else if(WIFSTOPPED(status))
{
Server->Log("Script was stopped by signal " + convert(WSTOPSIG(status)), LL_ERROR);
return false;
}
else
{
Server->Log("Unknown process status change", LL_ERROR);
return false;
}
}
}
<commit_msg>Fix build<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2015 Martin Raiber
*
* 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 "PipeFile.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "../config.h"
#if defined(HAVE_SPAWN_H)
#include <spawn.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#if defined(O_CLOEXEC) && !defined(__APPLE__) && !defined(__FreeBSD__)
#define clopipe(x) pipe2(x, O_CLOEXEC)
#else
int clopipe(int* x)
{
int rc = pipe(x);
if(rc!=0) return rc;
fcntl(x[0], F_SETFD, FD_CLOEXEC);
fcntl(x[1], F_SETFD, FD_CLOEXEC);
return rc;
}
#endif
PipeFile::PipeFile(const std::string& pCmd)
: PipeFileBase(pCmd),
hStderr(0),
hStdout(0)
{
int stdout_pipe[2];
if(clopipe(stdout_pipe) == -1)
{
Server->Log("Error creating stdout pipe: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
int stderr_pipe[2];
if(clopipe(stderr_pipe) == -1)
{
Server->Log("Error creating stderr pipe: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
#if defined(HAVE_SPAWN_H)
posix_spawn_file_actions_t fa;
if(posix_spawn_file_actions_init(&fa)!=0)
{
Server->Log("Error posix_spawn_file_actions_init: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
if(posix_spawn_file_actions_adddup2(&fa, stdout_pipe[1], STDOUT_FILENO)!=0)
{
Server->Log("Error posix_spawn_file_actions_adddup2(1): " + convert(errno), LL_ERROR);
has_error=true;
return;
}
if(posix_spawn_file_actions_adddup2(&fa, stderr_pipe[1], STDERR_FILENO)!=0)
{
Server->Log("Error posix_spawn_file_actions_adddup2(2): " + convert(errno), LL_ERROR);
has_error=true;
return;
}
const char* argv[] = {"sh", "-c", &pCmd[0], NULL};
const char* envp[] = {NULL};
if(posix_spawn(&child_pid, "/bin/sh", &fa, NULL, const_cast<char**>(argv), const_cast<char**>(envp))!=0)
{
Server->Log("Error executing command: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
close(stdout_pipe[1]);
close(stderr_pipe[1]);
hStdout = stdout_pipe[0];
hStderr = stderr_pipe[0];
init();
#else
child_pid = fork();
if(child_pid==-1)
{
Server->Log("Error forking to execute command: " + convert(errno), LL_ERROR);
has_error=true;
return;
}
else if(child_pid==0)
{
while ((dup2(stdout_pipe[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
while ((dup2(stderr_pipe[1], STDERR_FILENO) == -1) && (errno == EINTR)) {}
close(stdout_pipe[0]);
close(stdout_pipe[1]);
close(stderr_pipe[0]);
close(stderr_pipe[1]);
int rc = system(pCmd.c_str());
if(rc>127)
{
rc = 127;
}
_exit(rc);
}
else
{
close(stdout_pipe[1]);
close(stderr_pipe[1]);
hStdout = stdout_pipe[0];
hStderr = stderr_pipe[0];
init();
}
#endif
}
PipeFile::~PipeFile()
{
}
void PipeFile::forceExitWait()
{
if(child_pid!=-1)
{
kill(child_pid, SIGKILL);
int status;
waitpid(child_pid, &status, 0);
}
close(hStdout);
close(hStderr);
waitForExit();
}
bool PipeFile::readIntoBuffer(int hStd, char* buf, size_t buf_avail, size_t& read_bytes)
{
ssize_t rc = read(hStd, buf, buf_avail);
if(rc==0 && errno==EINTR)
{
return readIntoBuffer(hStd, buf, buf_avail, read_bytes);
}
else if(rc<=0)
{
return false;
}
else
{
read_bytes = static_cast<size_t>(rc);
return true;
}
}
bool PipeFile::readStdoutIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes)
{
return readIntoBuffer(hStdout, buf, buf_avail, read_bytes);
}
void PipeFile::finishStdout()
{
}
bool PipeFile::readStderrIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes)
{
return readIntoBuffer(hStderr, buf, buf_avail, read_bytes);
}
bool PipeFile::getExitCode(int& exit_code)
{
int status;
int rc = waitpid(child_pid, &status, WNOHANG);
if(rc==-1)
{
Server->Log("Error while waiting for exit code: " + convert(errno), LL_ERROR);
return false;
}
else if(rc==0)
{
Server->Log("Process is still active", LL_ERROR);
return false;
}
else
{
child_pid=-1;
if(WIFEXITED(status))
{
exit_code = WEXITSTATUS(status);
return true;
}
else if(WIFSIGNALED(status))
{
Server->Log("Script was terminated by signal " + convert(WTERMSIG(status)), LL_ERROR);
return false;
}
else if(WCOREDUMP(status))
{
Server->Log("Script crashed", LL_ERROR);
return false;
}
else if(WIFSTOPPED(status))
{
Server->Log("Script was stopped by signal " + convert(WSTOPSIG(status)), LL_ERROR);
return false;
}
else
{
Server->Log("Unknown process status change", LL_ERROR);
return false;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pdfexport.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2007-11-20 17:03:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef PDFEXPORT_HXX
#define PDFEXPORT_HXX
#include "pdffilter.hxx"
#include <tools/multisel.hxx>
#include <vcl/pdfwriter.hxx>
#include <vcl/pdfextoutdevdata.hxx>
#ifndef _COM_SUN_STAR_VIEW_XRENDERABLE_HPP_
#include <com/sun/star/view/XRenderable.hpp>
#endif
class SvEmbeddedObject;
class GDIMetaFile;
class VirtualDevice;
class PolyPolygon;
class Gradient;
class BitmapEx;
class Point;
class Size;
namespace vcl { class PDFWriter; }
// -------------
// - PDFExport -
// -------------
class PDFExport
{
private:
Reference< XComponent > mxSrcDoc;
Reference< lang::XMultiServiceFactory > mxMSF;
Reference< task::XStatusIndicator > mxStatusIndicator;
sal_Bool mbUseTaggedPDF;
sal_Int32 mnPDFTypeSelection;
sal_Bool mbExportNotes;
sal_Bool mbExportNotesPages;
sal_Bool mbEmbedStandardFonts;
sal_Bool mbUseTransitionEffects;
sal_Bool mbExportBookmarks;
sal_Int32 mnOpenBookmarkLevels;
sal_Bool mbUseLosslessCompression;
sal_Bool mbReduceImageResolution;
sal_Bool mbSkipEmptyPages;
sal_Bool mbAddStream;
sal_Int32 mnMaxImageResolution;
sal_Int32 mnQuality;
sal_Int32 mnFormsFormat;
sal_Bool mbExportFormFields;
sal_Int32 mnProgressValue;
sal_Bool mbWatermark;
uno::Any maWatermark;
//these variable are here only to have a location in filter/pdf to set the default
//to be used by the macro (when the FilterData are set by the macro itself)
sal_Bool mbHideViewerToolbar;
sal_Bool mbHideViewerMenubar;
sal_Bool mbHideViewerWindowControls;
sal_Bool mbFitWindow;
sal_Bool mbCenterWindow;
sal_Bool mbOpenInFullScreenMode;
sal_Bool mbDisplayPDFDocumentTitle;
sal_Int32 mnPDFDocumentMode;
sal_Int32 mnPDFDocumentAction;
sal_Int32 mnZoom;
sal_Int32 mnInitialPage;
sal_Int32 mnPDFPageLayout;
sal_Bool mbFirstPageLeft;
sal_Bool mbEncrypt;
rtl::OUString msOpenPassword;
sal_Bool mbRestrictPermissions;
rtl::OUString msPermissionPassword;
sal_Int32 mnPrintAllowed;
sal_Int32 mnChangesAllowed;
sal_Bool mbCanCopyOrExtract;
sal_Bool mbCanExtractForAccessibility;
SvtGraphicFill maCacheFill;
sal_Int32 mnCachePatternId;
//--->i56629
sal_Bool mbExportRelativeFsysLinks;
sal_Int32 mnDefaultLinkAction;
sal_Bool mbConvertOOoTargetToPDFTarget;
sal_Bool mbExportBmkToDest;
//<---
sal_Bool ImplExportPage( ::vcl::PDFWriter& rWriter, ::vcl::PDFExtOutDevData& rPDFExtOutDevData,
const GDIMetaFile& rMtf );
sal_Bool ImplWriteActions( ::vcl::PDFWriter& rWriter, ::vcl::PDFExtOutDevData* pPDFExtOutDevData,
const GDIMetaFile& rMtf, VirtualDevice& rDummyVDev );
void ImplWriteGradient( ::vcl::PDFWriter& rWriter, const PolyPolygon& rPolyPoly,
const Gradient& rGradient, VirtualDevice& rDummyVDev );
void ImplWriteBitmapEx( ::vcl::PDFWriter& rWriter, VirtualDevice& rDummyVDev,
const Point& rPoint, const Size& rSize, const BitmapEx& rBitmap );
void ImplWriteWatermark( ::vcl::PDFWriter& rWriter, const Size& rPageSize );
public:
PDFExport( const Reference< XComponent >& rxSrcDoc, Reference< task::XStatusIndicator >& xStatusIndicator, const Reference< lang::XMultiServiceFactory >& xFact );
~PDFExport();
sal_Bool ExportSelection( vcl::PDFWriter& rPDFWriter, Reference< com::sun::star::view::XRenderable >& rRenderable, Any& rSelection,
MultiSelection aMultiSelection, Sequence< PropertyValue >& rRenderOptions, sal_Int32 nPageCount );
sal_Bool Export( const OUString& rFile, const Sequence< PropertyValue >& rFilterData );
};
#endif
<commit_msg>INTEGRATION: CWS aquavcl05_DEV300 (1.12.54); FILE MERGED 2008/02/19 10:59:58 pl 1.12.54.1: #i85195# report potential problems during PDF export<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pdfexport.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:16:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef PDFEXPORT_HXX
#define PDFEXPORT_HXX
#include "pdffilter.hxx"
#include <tools/multisel.hxx>
#include <vcl/pdfwriter.hxx>
#include <vcl/pdfextoutdevdata.hxx>
#ifndef _COM_SUN_STAR_VIEW_XRENDERABLE_HPP_
#include <com/sun/star/view/XRenderable.hpp>
#endif
class SvEmbeddedObject;
class GDIMetaFile;
class VirtualDevice;
class PolyPolygon;
class Gradient;
class BitmapEx;
class Point;
class Size;
namespace vcl { class PDFWriter; }
// -------------
// - PDFExport -
// -------------
class PDFExport
{
private:
Reference< XComponent > mxSrcDoc;
Reference< lang::XMultiServiceFactory > mxMSF;
Reference< task::XStatusIndicator > mxStatusIndicator;
sal_Bool mbUseTaggedPDF;
sal_Int32 mnPDFTypeSelection;
sal_Bool mbExportNotes;
sal_Bool mbExportNotesPages;
sal_Bool mbEmbedStandardFonts;
sal_Bool mbUseTransitionEffects;
sal_Bool mbExportBookmarks;
sal_Int32 mnOpenBookmarkLevels;
sal_Bool mbUseLosslessCompression;
sal_Bool mbReduceImageResolution;
sal_Bool mbSkipEmptyPages;
sal_Bool mbAddStream;
sal_Int32 mnMaxImageResolution;
sal_Int32 mnQuality;
sal_Int32 mnFormsFormat;
sal_Bool mbExportFormFields;
sal_Int32 mnProgressValue;
sal_Bool mbWatermark;
uno::Any maWatermark;
//these variable are here only to have a location in filter/pdf to set the default
//to be used by the macro (when the FilterData are set by the macro itself)
sal_Bool mbHideViewerToolbar;
sal_Bool mbHideViewerMenubar;
sal_Bool mbHideViewerWindowControls;
sal_Bool mbFitWindow;
sal_Bool mbCenterWindow;
sal_Bool mbOpenInFullScreenMode;
sal_Bool mbDisplayPDFDocumentTitle;
sal_Int32 mnPDFDocumentMode;
sal_Int32 mnPDFDocumentAction;
sal_Int32 mnZoom;
sal_Int32 mnInitialPage;
sal_Int32 mnPDFPageLayout;
sal_Bool mbFirstPageLeft;
sal_Bool mbEncrypt;
rtl::OUString msOpenPassword;
sal_Bool mbRestrictPermissions;
rtl::OUString msPermissionPassword;
sal_Int32 mnPrintAllowed;
sal_Int32 mnChangesAllowed;
sal_Bool mbCanCopyOrExtract;
sal_Bool mbCanExtractForAccessibility;
SvtGraphicFill maCacheFill;
sal_Int32 mnCachePatternId;
//--->i56629
sal_Bool mbExportRelativeFsysLinks;
sal_Int32 mnDefaultLinkAction;
sal_Bool mbConvertOOoTargetToPDFTarget;
sal_Bool mbExportBmkToDest;
//<---
sal_Bool ImplExportPage( ::vcl::PDFWriter& rWriter, ::vcl::PDFExtOutDevData& rPDFExtOutDevData,
const GDIMetaFile& rMtf );
sal_Bool ImplWriteActions( ::vcl::PDFWriter& rWriter, ::vcl::PDFExtOutDevData* pPDFExtOutDevData,
const GDIMetaFile& rMtf, VirtualDevice& rDummyVDev );
void ImplWriteGradient( ::vcl::PDFWriter& rWriter, const PolyPolygon& rPolyPoly,
const Gradient& rGradient, VirtualDevice& rDummyVDev );
void ImplWriteBitmapEx( ::vcl::PDFWriter& rWriter, VirtualDevice& rDummyVDev,
const Point& rPoint, const Size& rSize, const BitmapEx& rBitmap );
void ImplWriteWatermark( ::vcl::PDFWriter& rWriter, const Size& rPageSize );
public:
PDFExport( const Reference< XComponent >& rxSrcDoc, Reference< task::XStatusIndicator >& xStatusIndicator, const Reference< lang::XMultiServiceFactory >& xFact );
~PDFExport();
sal_Bool ExportSelection( vcl::PDFWriter& rPDFWriter, Reference< com::sun::star::view::XRenderable >& rRenderable, Any& rSelection,
MultiSelection aMultiSelection, Sequence< PropertyValue >& rRenderOptions, sal_Int32 nPageCount );
sal_Bool Export( const OUString& rFile, const Sequence< PropertyValue >& rFilterData );
void showErrors( const std::set<vcl::PDFWriter::ErrorCode>& );
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 Pascal Giorgi
*
* Written by Pascal Giorgi <pascal.giorgi@lirmm.fr>
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
#include "linbox/linbox-config.h"
#include "linbox/algorithms/polynomial-matrix/polynomial-fft-transform.h"
#include "linbox/randiter/random-fftprime.h"
#include "linbox/ring/modular.h"
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using namespace LinBox;
/* For pretty printing type */
template<typename T> const char *TypeName();
template<template <typename S> typename T> const char *TypeName();
#define REGISTER_TYPE_NAME(type) \
template<> const char *TypeName<type>(){return #type;}
REGISTER_TYPE_NAME(double);
REGISTER_TYPE_NAME(uint16_t);
REGISTER_TYPE_NAME(uint32_t);
REGISTER_TYPE_NAME(uint64_t);
REGISTER_TYPE_NAME(uint128_t);
REGISTER_TYPE_NAME(NoSimd);
REGISTER_TYPE_NAME(Simd128);
REGISTER_TYPE_NAME(Simd256);
/******************************************************************************/
template<typename Field>
struct Checker {
typedef typename Field::Element Elt;
typedef AlignedAllocator<Elt, Alignment::DEFAULT> _Alignement;
typedef typename std::vector<Elt, _Alignement> EltVector;
const Field& _F;
size_t _k;
size_t _n;
FFT_transform<Field> _fft;
/* ctor */
Checker (const Field& F, size_t k) : _F(F), _k(k), _n(1<<k), _fft(F,k) {
}
/* compute r = P evaluated at x using Horner method */
void horner_eval (Elt& r, EltVector& P, Elt& x) {
_F.assign (r, _F.zero);
for (auto ptr = P.rbegin(); ptr != P.rend(); ptr++ ) {
_F.mulin (r, x);
_F.addin (r, *ptr);
}
}
/* return i with its first _k bits reversed */
size_t bitreversed (size_t i) {
size_t r = 0;
for (size_t j = 0; j < _k; j++, i>>=1)
{
r <<= 1;
r |= i & 1;
}
return r;
}
/* draw random vector and check DIF and DIT for all available SIMD implem */
bool check (unsigned long seed) {
EltVector in(_n), in_br(_n), out(_n), out_br(_n), v(_n);
string s;
bool passed = true;
/* Generate random input */
typename Field::RandIter Gen (_F, 0, seed+_k); /*0 has no meaning here*/
for (auto elt = in.begin(); elt < in.end(); elt++)
Gen.random (*elt);
/* Compute the out vector using a naive polynomial evaluation and set
* the bitreversed version of in and out */
Elt x(1);
for (size_t i = 0; i < _n; _F.mulin (x, _fft._w), i++) {
size_t i_br = bitreversed (i);
in_br[i_br] = in[i];
horner_eval (out[i], in, x);
out_br[i_br] = out[i];
}
/* DIF : natural order => bitreversed order */
#define DIF_CHECK(method) do { \
v = in; \
_fft.method (v.data()); \
for (auto& e: v) /* reduce from < 2p to < p */ \
if (e > _F._p) e-=_F._p; \
bool b = equal (v.begin(), v.end(), out_br.begin()); \
s = " "; s.append (#method); s.append (" "); \
s.append (string (80-(s.size()+16), '.')); \
cout << s << (b ? " success" : " failure") << endl; \
passed &= b; \
} while (0)
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative2x2);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative3x3);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative4x1_SSE);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative4x2_SSE);
#ifdef __LINBOX_HAVE_AVX2_INSTRUCTIONS
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative8x1_AVX);
#endif
/* DIT : bitreversed order => natural order */
#define DIT_CHECK(method) do { \
v = in_br; \
_fft.method (v.data()); \
for (auto& e: v) { /* reduce from < 3p to < p */ \
if (e > _F._p) e-=_F._p; \
if (e > _F._p) e-=_F._p; \
if (e > _F._p) e-=_F._p; \
} \
bool b = equal (v.begin(), v.end(), out.begin()); \
s = " "; s.append (#method); s.append (" "); \
s.append (string (80-(s.size()+16), '.')); \
cout << s << (b ? " success" : " failure") << endl; \
passed &= b; \
} while (0)
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative);
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative2x2);
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative3x3);
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative4x1_SSE);
#ifdef __LINBOX_HAVE_AVX2_INSTRUCTIONS
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative8x1_AVX);
#endif
return passed;
}
};
/* Test FFT on polynomial with coefficients in Modular<T1,T2> with a random
* prime p with the required number of bits and such that 2^k divides p-1
*/
template<typename T1, typename T2>
bool test_one_modular_implem (uint64_t bits, size_t k, unsigned long seed)
{
typedef typename Givaro::Modular<T1, T2> ModImplem;
RandomFFTPrime RandomGen (1<<bits, seed);
T1 p = (T1) RandomGen.randomPrime (k);
ModImplem GFp(p);
cout << endl << string (80, '*') << endl;
cout << "Test FFT with Modular<" << TypeName<T1>() << ", ";
cout << TypeName<T2>() << ">, p=" << GFp._p << " (" << bits << " bits, 2^";
cout << k << " divides p-1)" << endl;
bool b = true;
for (size_t kc = 1; kc <= k; kc++) {
cout << "** with n=2^" << kc << endl;
Checker<ModImplem> C(GFp, kc);
b &= C.check (seed);
}
return b;
}
/******************************************************************************/
/************************************ main ************************************/
/******************************************************************************/
int main (int argc, char *argv[]) {
bool pass = true;
unsigned long seed = time (NULL);
Argument args[] = {
{ 's', "-s seed", "set the seed.", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
parseArguments (argc, argv, args);
cout << "# To rerun this test: test-fft-new -s " << seed << endl;
cout << "# seed = " << seed << endl;
/* Test with Modular<uint32_t, uint64_t>, and 27-bit prime and k=10 */
pass &= test_one_modular_implem<uint32_t, uint64_t> (27, 10, seed);
cout << endl << "Test " << (pass ? "passed" : "failed") << endl;
return pass ? 0 : 1;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>typo in test-fft-old.C<commit_after>/*
* Copyright (C) 2013 Pascal Giorgi
*
* Written by Pascal Giorgi <pascal.giorgi@lirmm.fr>
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
#include "linbox/linbox-config.h"
#include "linbox/algorithms/polynomial-matrix/polynomial-fft-transform.h"
#include "linbox/randiter/random-fftprime.h"
#include "linbox/ring/modular.h"
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using namespace LinBox;
/* For pretty printing type */
template<typename T> const char *TypeName();
template<template <typename S> typename T> const char *TypeName();
#define REGISTER_TYPE_NAME(type) \
template<> const char *TypeName<type>(){return #type;}
REGISTER_TYPE_NAME(double);
REGISTER_TYPE_NAME(uint16_t);
REGISTER_TYPE_NAME(uint32_t);
REGISTER_TYPE_NAME(uint64_t);
REGISTER_TYPE_NAME(uint128_t);
REGISTER_TYPE_NAME(NoSimd);
REGISTER_TYPE_NAME(Simd128);
REGISTER_TYPE_NAME(Simd256);
/******************************************************************************/
template<typename Field>
struct Checker {
typedef typename Field::Element Elt;
typedef AlignedAllocator<Elt, Alignment::DEFAULT> _Alignement;
typedef typename std::vector<Elt, _Alignement> EltVector;
const Field& _F;
size_t _k;
size_t _n;
FFT_transform<Field> _fft;
/* ctor */
Checker (const Field& F, size_t k) : _F(F), _k(k), _n(1<<k), _fft(F,k) {
}
/* compute r = P evaluated at x using Horner method */
void horner_eval (Elt& r, EltVector& P, Elt& x) {
_F.assign (r, _F.zero);
for (auto ptr = P.rbegin(); ptr != P.rend(); ptr++ ) {
_F.mulin (r, x);
_F.addin (r, *ptr);
}
}
/* return i with its first _k bits reversed */
size_t bitreversed (size_t i) {
size_t r = 0;
for (size_t j = 0; j < _k; j++, i>>=1)
{
r <<= 1;
r |= i & 1;
}
return r;
}
/* draw random vector and check DIF and DIT for all available SIMD implem */
bool check (unsigned long seed) {
EltVector in(_n), in_br(_n), out(_n), out_br(_n), v(_n);
string s;
bool passed = true;
/* Generate random input */
typename Field::RandIter Gen (_F, 0, seed+_k); /*0 has no meaning here*/
for (auto elt = in.begin(); elt < in.end(); elt++)
Gen.random (*elt);
/* Compute the out vector using a naive polynomial evaluation and set
* the bitreversed version of in and out */
Elt x(1);
for (size_t i = 0; i < _n; _F.mulin (x, _fft._w), i++) {
size_t i_br = bitreversed (i);
in_br[i_br] = in[i];
horner_eval (out[i], in, x);
out_br[i_br] = out[i];
}
/* DIF : natural order => bitreversed order */
#define DIF_CHECK(method) do { \
v = in; \
_fft.method (v.data()); \
for (auto& e: v) /* reduce from < 2p to < p */ \
if (e > _F._p) e-=_F._p; \
bool b = equal (v.begin(), v.end(), out_br.begin()); \
s = " "; s.append (#method); s.append (" "); \
s.append (string (80-(s.size()+16), '.')); \
cout << s << (b ? " success" : " failure") << endl; \
passed &= b; \
} while (0)
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative2x2);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative3x3);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative4x1_SSE);
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative4x2_SSE);
#ifdef __LINBOX_HAVE_AVX2_INSTRUCTIONS
DIF_CHECK(FFT_DIF_Harvey_mod2p_iterative8x1_AVX);
#endif
/* DIT : bitreversed order => natural order */
#define DIT_CHECK(method) do { \
v = in_br; \
_fft.method (v.data()); \
for (auto& e: v) { /* reduce from < 3p to < p */ \
if (e > _F._p) e-=_F._p; \
if (e > _F._p) e-=_F._p; \
if (e > _F._p) e-=_F._p; \
} \
bool b = equal (v.begin(), v.end(), out.begin()); \
s = " "; s.append (#method); s.append (" "); \
s.append (string (80-(s.size()+16), '.')); \
cout << s << (b ? " success" : " failure") << endl; \
passed &= b; \
} while (0)
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative);
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative2x2);
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative3x3);
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative4x1_SSE);
#ifdef __LINBOX_HAVE_AVX2_INSTRUCTIONS
DIT_CHECK(FFT_DIT_Harvey_mod4p_iterative8x1_AVX);
#endif
return passed;
}
};
/* Test FFT on polynomial with coefficients in Modular<T1,T2> with a random
* prime p with the required number of bits and such that 2^k divides p-1
*/
template<typename T1, typename T2>
bool test_one_modular_implem (uint64_t bits, size_t k, unsigned long seed)
{
typedef typename Givaro::Modular<T1, T2> ModImplem;
RandomFFTPrime RandomGen (1<<bits, seed);
T1 p = (T1) RandomGen.randomPrime (k);
ModImplem GFp(p);
cout << endl << string (80, '*') << endl;
cout << "Test FFT with Modular<" << TypeName<T1>() << ", ";
cout << TypeName<T2>() << ">, p=" << GFp._p << " (" << bits << " bits, 2^";
cout << k << " divides p-1)" << endl;
bool b = true;
for (size_t kc = 1; kc <= k; kc++) {
cout << "** with n=2^" << kc << endl;
Checker<ModImplem> C(GFp, kc);
b &= C.check (seed);
}
return b;
}
/******************************************************************************/
/************************************ main ************************************/
/******************************************************************************/
int main (int argc, char *argv[]) {
bool pass = true;
unsigned long seed = time (NULL);
Argument args[] = {
{ 's', "-s seed", "set the seed.", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
parseArguments (argc, argv, args);
cout << "# To rerun this test: test-fft-old -s " << seed << endl;
cout << "# seed = " << seed << endl;
/* Test with Modular<uint32_t, uint64_t>, and 27-bit prime and k=10 */
pass &= test_one_modular_implem<uint32_t, uint64_t> (27, 10, seed);
cout << endl << "Test " << (pass ? "passed" : "failed") << endl;
return pass ? 0 : 1;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|> |
<commit_before>/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef GRPC_UV
#include "server.h"
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/support/time.h"
#include "call.h"
#include "completion_queue.h"
namespace grpc {
namespace node {
using Nan::Callback;
using Nan::MaybeLocal;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Object;
using v8::Value;
static Callback *shutdown_callback = NULL;
class ServerShutdownOp : public Op {
public:
ServerShutdownOp(grpc_server *server): server(server) {
}
~ServerShutdownOp() {
}
Local<Value> GetNodeValue() const {
return Nan::New<External>(reinterpret_cast<void *>(server));
}
bool ParseOp(Local<Value> value, grpc_op *out) {
return true;
}
bool IsFinalOp() {
return false;
}
void OnComplete() {
}
grpc_server *server;
protected:
std::string GetTypeString() const { return "shutdown"; }
};
Server::Server(grpc_server *server) : wrapped_server(server) {
}
Server::~Server() {
this->ShutdownServer();
}
NAN_METHOD(ServerShutdownCallback) {
if (!info[0]->IsNull()) {
return Nan::ThrowError("forceShutdown failed somehow");
}
MaybeLocal<Object> maybe_result = Nan::To<Object>(info[1]);
Local<Object> result = maybe_result.ToLocalChecked();
Local<Value> server_val = Nan::Get(
result, Nan::New("shutdown").ToLocalChecked()).ToLocalChecked();
Local<External> server_extern = server_val.As<External>();
grpc_server *server = reinterpret_cast<grpc_server *>(server_extern->Value());
grpc_server_destroy(server);
}
void Server::ShutdownServer() {
Nan::HandleScope scope;
if (this->wrapped_server != NULL) {
if (shutdown_callback == NULL) {
Local<FunctionTemplate>callback_tpl =
Nan::New<FunctionTemplate>(ServerShutdownCallback);
shutdown_callback = new Callback(
Nan::GetFunction(callback_tpl).ToLocalChecked());
}
ServerShutdownOp *op = new ServerShutdownOp(this->wrapped_server);
unique_ptr<OpVec> ops(new OpVec());
ops->push_back(unique_ptr<Op>(op));
grpc_server_shutdown_and_notify(
this->wrapped_server, GetCompletionQueue(),
new struct tag(new Callback(**shutdown_callback), ops.release(), NULL,
Nan::Null()));
grpc_server_cancel_all_calls(this->wrapped_server);
CompletionQueueNext();
this->wrapped_server = NULL;
}
}
} // namespace grpc
} // namespace node
#endif /* GRPC_UV */
<commit_msg>Move ForceShutdown completion handling to new OnComplete method<commit_after>/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef GRPC_UV
#include "server.h"
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/support/time.h"
#include "call.h"
#include "completion_queue.h"
namespace grpc {
namespace node {
using Nan::Callback;
using Nan::MaybeLocal;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Object;
using v8::Value;
static Callback *shutdown_callback = NULL;
class ServerShutdownOp : public Op {
public:
ServerShutdownOp(grpc_server *server): server(server) {
}
~ServerShutdownOp() {
}
Local<Value> GetNodeValue() const {
return Nan::Null();
}
bool ParseOp(Local<Value> value, grpc_op *out) {
return true;
}
bool IsFinalOp() {
return false;
}
void OnComplete() {
grpc_server_destroy(server);
}
grpc_server *server;
protected:
std::string GetTypeString() const { return "shutdown"; }
};
Server::Server(grpc_server *server) : wrapped_server(server) {
}
Server::~Server() {
this->ShutdownServer();
}
NAN_METHOD(ServerShutdownCallback) {
if (!info[0]->IsNull()) {
return Nan::ThrowError("forceShutdown failed somehow");
}
}
void Server::ShutdownServer() {
Nan::HandleScope scope;
if (this->wrapped_server != NULL) {
if (shutdown_callback == NULL) {
Local<FunctionTemplate>callback_tpl =
Nan::New<FunctionTemplate>(ServerShutdownCallback);
shutdown_callback = new Callback(
Nan::GetFunction(callback_tpl).ToLocalChecked());
}
ServerShutdownOp *op = new ServerShutdownOp(this->wrapped_server);
unique_ptr<OpVec> ops(new OpVec());
ops->push_back(unique_ptr<Op>(op));
grpc_server_shutdown_and_notify(
this->wrapped_server, GetCompletionQueue(),
new struct tag(new Callback(**shutdown_callback), ops.release(), NULL,
Nan::Null()));
grpc_server_cancel_all_calls(this->wrapped_server);
CompletionQueueNext();
this->wrapped_server = NULL;
}
}
} // namespace grpc
} // namespace node
#endif /* GRPC_UV */
<|endoftext|> |
<commit_before>#include <ruby.h>
#include <set>
#include <algorithm>
#include <boost/tuple/tuple.hpp>
using namespace boost;
using namespace std;
static VALUE cValueSet;
static ID id_new;
typedef std::set<VALUE> ValueSet;
static ValueSet& get_wrapped_set(VALUE self)
{
ValueSet* object = 0;
Data_Get_Struct(self, ValueSet, object);
return *object;
}
static void value_set_mark(ValueSet const* set) { std::for_each(set->begin(), set->end(), rb_gc_mark); }
static void value_set_free(ValueSet const* set) { delete set; }
static VALUE value_set_alloc(VALUE klass)
{
ValueSet* cxx_set = new ValueSet;
return Data_Wrap_Struct(klass, value_set_mark, value_set_free, cxx_set);
}
/* call-seq:
* set.empty? => true or false
*
* Checks if this set is empty
*/
static VALUE value_set_empty_p(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
return set.empty() ? Qtrue : Qfalse;
}
/* call-seq:
* set.size => size
*
* Returns this set size
*/
static VALUE value_set_size(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
return INT2NUM(set.size());
}
/* call-seq:
* set.each { |obj| ... } => set
*
*/
static VALUE value_set_each(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
for (ValueSet::iterator it = set.begin(); it != set.end();)
{
// Increment before calling yield() so that
// the current element can be deleted safely
ValueSet::iterator this_it = it++;
rb_yield(*this_it);
}
return self;
}
/* call-seq:
* set.delete_if { |obj| ... } => set
*
* Deletes all objects for which the block returns true
*/
static VALUE value_set_delete_if(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
for (ValueSet::iterator it = set.begin(); it != set.end();)
{
// Increment before calling yield() so that
// the current element can be deleted safely
ValueSet::iterator this_it = it++;
bool do_delete = RTEST(rb_yield(*this_it));
if (do_delete)
set.erase(this_it);
}
return self;
}
/* call-seq:
* set.include?(value) => true or false
*
* Checks if +value+ is in +set+
*/
static VALUE value_set_include_p(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
return self.find(vother) == self.end() ? Qfalse : Qtrue;
}
/* call-seq:
* set.to_value_set => set
*/
static VALUE value_set_to_value_set(VALUE self) { return self; }
/* call-seq:
* set.include_all?(other) => true or false
*
* Checks if all elements of +other+ are in +set+
*/
static VALUE value_set_include_all_p(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
return std::includes(self.begin(), self.end(), other.begin(), other.end()) ? Qtrue : Qfalse;
}
/* call-seq:
* set.union(other) => union_set
* set | other => union_set
*
* Computes the union of +set+ and +other+. This operation is O(N + M)
* is +other+ is a ValueSet
*/
static VALUE value_set_union(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
std::set_union(self.begin(), self.end(), other.begin(), other.end(),
std::inserter(result, result.end()));
return vresult;
}
/* call-seq:
* set.merge(other) => set
*
* Merges the elements of +other+ into +self+. If +other+ is a ValueSet, the operation is O(N + M)
*/
static VALUE value_set_merge(VALUE vself, VALUE vother)
{
ValueSet& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
self.insert(other.begin(), other.end());
return vself;
}
/* call-seq:
* set.intersection(other) => intersection_set
* set & other => intersection_set
*
* Computes the intersection of +set+ and +other+. This operation
* is O(N + M) if +other+ is a ValueSet
*/
static VALUE value_set_intersection(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
std::set_intersection(self.begin(), self.end(), other.begin(), other.end(),
std::inserter(result, result.end()));
return vresult;
}
/* call-seq:
* set.intersects?(other) => true or false
*
* Returns true if there is elements in +set+ that are also in +other
*/
static VALUE value_set_intersects(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
ValueSet::const_iterator
self_it = self.begin(),
self_end = self.end(),
other_it = other.begin(),
other_end = other.end();
while(self_it != self_end && other_it != other_end)
{
if (*self_it < *other_it)
++self_it;
else if (*other_it < *self_it)
++other_it;
else
return Qtrue;
}
return Qfalse;
}
/* call-seq:
* set.difference(other) => difference_set
* set - other => difference_set
*
* Computes the set of all elements of +set+ not in +other+. This operation
* is O(N + M) if +other+ is a ValueSet
*/
static VALUE value_set_difference(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
std::set_difference(self.begin(), self.end(), other.begin(), other.end(),
std::inserter(result, result.end()));
return vresult;
}
/* call-seq:
* set.insert(value) => true or false
*
* Inserts +value+ into +set+. Returns true if the value did not exist
* in the set yet (it has actually been inserted), and false otherwise.
* This operation is O(log N)
*/
static VALUE value_set_insert(VALUE vself, VALUE v)
{
ValueSet& self = get_wrapped_set(vself);
bool exists;
tie(tuples::ignore, exists) = self.insert(v);
return exists ? Qtrue : Qfalse;
}
/* call-seq:
* set.delete(value) => true or false
*
* Removes +value+ from +set+. Returns true if the value did exist
* in the set yet (it has actually been removed), and false otherwise.
*/
static VALUE value_set_delete(VALUE vself, VALUE v)
{
ValueSet& self = get_wrapped_set(vself);
size_t count = self.erase(v);
return count > 0 ? Qtrue : Qfalse;
}
/* call-seq:
* set == other => true or false
*
* Equality
*/
static VALUE value_set_equal(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
return Qfalse;
ValueSet const& other = get_wrapped_set(vother);
return (self == other) ? Qtrue : Qfalse;
}
/* call-seq:
* set.clear => set
*
* Remove all elements of this set
*/
static VALUE value_set_clear(VALUE self)
{
get_wrapped_set(self).clear();
return self;
}
/* call-seq:
* set.initialize_copy(other) => set
*
* Initializes +set+ with the values in +other+. Needed by #dup
*/
static VALUE value_set_initialize_copy(VALUE vself, VALUE vother)
{
ValueSet const& other = get_wrapped_set(vother);
set<VALUE> new_set(other.begin(), other.end());
get_wrapped_set(vself).swap(new_set);
return vself;
}
static VALUE enumerable_to_value_set_i(VALUE i, VALUE* memo)
{
ValueSet& result = *reinterpret_cast<ValueSet*>(memo);
result.insert(i);
return Qnil;
}
/* call-seq:
* enum.to_value_set => value_set
*
* Builds a ValueSet object from this enumerable
*/
static VALUE enumerable_to_value_set(VALUE self)
{
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
rb_iterate(rb_each, self, RUBY_METHOD_FUNC(enumerable_to_value_set_i), reinterpret_cast<VALUE>(&result));
return vresult;
}
/*
* Document-class: ValueSet
*
* ValueSet is a wrapper around the C++ set<> template. set<> is an ordered container,
* for which union(), intersection() and difference() is done in linear time. For performance
* reasons, in the case of ValueSet, the values are ordered by their VALUE, which roughly is
* their object_id.
*/
extern "C" void Init_value_set()
{
rb_define_method(rb_mEnumerable, "to_value_set", RUBY_METHOD_FUNC(enumerable_to_value_set), 0);
cValueSet = rb_define_class("ValueSet", rb_cObject);
id_new = rb_intern("new");
rb_define_alloc_func(cValueSet, value_set_alloc);
rb_define_method(cValueSet, "each", RUBY_METHOD_FUNC(value_set_each), 0);
rb_define_method(cValueSet, "include?", RUBY_METHOD_FUNC(value_set_include_p), 1);
rb_define_method(cValueSet, "include_all?", RUBY_METHOD_FUNC(value_set_include_all_p), 1);
rb_define_method(cValueSet, "union", RUBY_METHOD_FUNC(value_set_union), 1);
rb_define_method(cValueSet, "intersection", RUBY_METHOD_FUNC(value_set_intersection), 1);
rb_define_method(cValueSet, "intersects?", RUBY_METHOD_FUNC(value_set_intersects), 1);
rb_define_method(cValueSet, "difference", RUBY_METHOD_FUNC(value_set_difference), 1);
rb_define_method(cValueSet, "insert", RUBY_METHOD_FUNC(value_set_insert), 1);
rb_define_method(cValueSet, "merge", RUBY_METHOD_FUNC(value_set_merge), 1);
rb_define_method(cValueSet, "delete", RUBY_METHOD_FUNC(value_set_delete), 1);
rb_define_method(cValueSet, "==", RUBY_METHOD_FUNC(value_set_equal), 1);
rb_define_method(cValueSet, "to_value_set", RUBY_METHOD_FUNC(value_set_to_value_set), 0);
rb_define_method(cValueSet, "empty?", RUBY_METHOD_FUNC(value_set_empty_p), 0);
rb_define_method(cValueSet, "size", RUBY_METHOD_FUNC(value_set_size), 0);
rb_define_method(cValueSet, "clear", RUBY_METHOD_FUNC(value_set_clear), 0);
rb_define_method(cValueSet, "initialize_copy", RUBY_METHOD_FUNC(value_set_initialize_copy), 1);
rb_define_method(cValueSet, "delete_if", RUBY_METHOD_FUNC(value_set_delete_if), 0);
}
<commit_msg>[value_set] define a more efficient ValueSet#dup<commit_after>#include <ruby.h>
#include <set>
#include <algorithm>
#include <boost/tuple/tuple.hpp>
using namespace boost;
using namespace std;
static VALUE cValueSet;
static ID id_new;
typedef std::set<VALUE> ValueSet;
static ValueSet& get_wrapped_set(VALUE self)
{
ValueSet* object = 0;
Data_Get_Struct(self, ValueSet, object);
return *object;
}
static void value_set_mark(ValueSet const* set) { std::for_each(set->begin(), set->end(), rb_gc_mark); }
static void value_set_free(ValueSet const* set) { delete set; }
static VALUE value_set_alloc(VALUE klass)
{
ValueSet* cxx_set = new ValueSet;
return Data_Wrap_Struct(klass, value_set_mark, value_set_free, cxx_set);
}
/* call-seq:
* set.empty? => true or false
*
* Checks if this set is empty
*/
static VALUE value_set_empty_p(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
return set.empty() ? Qtrue : Qfalse;
}
/* call-seq:
* set.size => size
*
* Returns this set size
*/
static VALUE value_set_size(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
return INT2NUM(set.size());
}
/* call-seq:
* set.each { |obj| ... } => set
*
*/
static VALUE value_set_each(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
for (ValueSet::iterator it = set.begin(); it != set.end();)
{
// Increment before calling yield() so that
// the current element can be deleted safely
ValueSet::iterator this_it = it++;
rb_yield(*this_it);
}
return self;
}
/* call-seq:
* set.delete_if { |obj| ... } => set
*
* Deletes all objects for which the block returns true
*/
static VALUE value_set_delete_if(VALUE self)
{
ValueSet& set = get_wrapped_set(self);
for (ValueSet::iterator it = set.begin(); it != set.end();)
{
// Increment before calling yield() so that
// the current element can be deleted safely
ValueSet::iterator this_it = it++;
bool do_delete = RTEST(rb_yield(*this_it));
if (do_delete)
set.erase(this_it);
}
return self;
}
/* call-seq:
* set.include?(value) => true or false
*
* Checks if +value+ is in +set+
*/
static VALUE value_set_include_p(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
return self.find(vother) == self.end() ? Qfalse : Qtrue;
}
/* call-seq:
* set.to_value_set => set
*/
static VALUE value_set_to_value_set(VALUE self) { return self; }
/* call-seq:
* set.dup => other_set
*
* Duplicates this set, without duplicating the pointed-to objects
*/
static VALUE value_set_dup(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
for (ValueSet::const_iterator it = self.begin(); it != self.end(); ++it)
result.insert(result.end(), *it);
return vresult;
}
/* call-seq:
* set.include_all?(other) => true or false
*
* Checks if all elements of +other+ are in +set+
*/
static VALUE value_set_include_all_p(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
return std::includes(self.begin(), self.end(), other.begin(), other.end()) ? Qtrue : Qfalse;
}
/* call-seq:
* set.union(other) => union_set
* set | other => union_set
*
* Computes the union of +set+ and +other+. This operation is O(N + M)
* is +other+ is a ValueSet
*/
static VALUE value_set_union(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
std::set_union(self.begin(), self.end(), other.begin(), other.end(),
std::inserter(result, result.end()));
return vresult;
}
/* call-seq:
* set.merge(other) => set
*
* Merges the elements of +other+ into +self+. If +other+ is a ValueSet, the operation is O(N + M)
*/
static VALUE value_set_merge(VALUE vself, VALUE vother)
{
ValueSet& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
self.insert(other.begin(), other.end());
return vself;
}
/* call-seq:
* set.intersection(other) => intersection_set
* set & other => intersection_set
*
* Computes the intersection of +set+ and +other+. This operation
* is O(N + M) if +other+ is a ValueSet
*/
static VALUE value_set_intersection(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
std::set_intersection(self.begin(), self.end(), other.begin(), other.end(),
std::inserter(result, result.end()));
return vresult;
}
/* call-seq:
* set.intersects?(other) => true or false
*
* Returns true if there is elements in +set+ that are also in +other
*/
static VALUE value_set_intersects(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
ValueSet::const_iterator
self_it = self.begin(),
self_end = self.end(),
other_it = other.begin(),
other_end = other.end();
while(self_it != self_end && other_it != other_end)
{
if (*self_it < *other_it)
++self_it;
else if (*other_it < *self_it)
++other_it;
else
return Qtrue;
}
return Qfalse;
}
/* call-seq:
* set.difference(other) => difference_set
* set - other => difference_set
*
* Computes the set of all elements of +set+ not in +other+. This operation
* is O(N + M) if +other+ is a ValueSet
*/
static VALUE value_set_difference(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
rb_raise(rb_eArgError, "expected a ValueSet");
ValueSet const& other = get_wrapped_set(vother);
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
std::set_difference(self.begin(), self.end(), other.begin(), other.end(),
std::inserter(result, result.end()));
return vresult;
}
/* call-seq:
* set.insert(value) => true or false
*
* Inserts +value+ into +set+. Returns true if the value did not exist
* in the set yet (it has actually been inserted), and false otherwise.
* This operation is O(log N)
*/
static VALUE value_set_insert(VALUE vself, VALUE v)
{
ValueSet& self = get_wrapped_set(vself);
bool exists;
tie(tuples::ignore, exists) = self.insert(v);
return exists ? Qtrue : Qfalse;
}
/* call-seq:
* set.delete(value) => true or false
*
* Removes +value+ from +set+. Returns true if the value did exist
* in the set yet (it has actually been removed), and false otherwise.
*/
static VALUE value_set_delete(VALUE vself, VALUE v)
{
ValueSet& self = get_wrapped_set(vself);
size_t count = self.erase(v);
return count > 0 ? Qtrue : Qfalse;
}
/* call-seq:
* set == other => true or false
*
* Equality
*/
static VALUE value_set_equal(VALUE vself, VALUE vother)
{
ValueSet const& self = get_wrapped_set(vself);
if (!RTEST(rb_obj_is_kind_of(vother, cValueSet)))
return Qfalse;
ValueSet const& other = get_wrapped_set(vother);
return (self == other) ? Qtrue : Qfalse;
}
/* call-seq:
* set.clear => set
*
* Remove all elements of this set
*/
static VALUE value_set_clear(VALUE self)
{
get_wrapped_set(self).clear();
return self;
}
/* call-seq:
* set.initialize_copy(other) => set
*
* Initializes +set+ with the values in +other+. Needed by #dup
*/
static VALUE value_set_initialize_copy(VALUE vself, VALUE vother)
{
ValueSet const& other = get_wrapped_set(vother);
set<VALUE> new_set(other.begin(), other.end());
get_wrapped_set(vself).swap(new_set);
return vself;
}
static VALUE enumerable_to_value_set_i(VALUE i, VALUE* memo)
{
ValueSet& result = *reinterpret_cast<ValueSet*>(memo);
result.insert(i);
return Qnil;
}
/* call-seq:
* enum.to_value_set => value_set
*
* Builds a ValueSet object from this enumerable
*/
static VALUE enumerable_to_value_set(VALUE self)
{
VALUE vresult = rb_funcall(cValueSet, id_new, 0);
ValueSet& result = get_wrapped_set(vresult);
rb_iterate(rb_each, self, RUBY_METHOD_FUNC(enumerable_to_value_set_i), reinterpret_cast<VALUE>(&result));
return vresult;
}
/*
* Document-class: ValueSet
*
* ValueSet is a wrapper around the C++ set<> template. set<> is an ordered container,
* for which union(), intersection() and difference() is done in linear time. For performance
* reasons, in the case of ValueSet, the values are ordered by their VALUE, which roughly is
* their object_id.
*/
extern "C" void Init_value_set()
{
rb_define_method(rb_mEnumerable, "to_value_set", RUBY_METHOD_FUNC(enumerable_to_value_set), 0);
cValueSet = rb_define_class("ValueSet", rb_cObject);
id_new = rb_intern("new");
rb_define_alloc_func(cValueSet, value_set_alloc);
rb_define_method(cValueSet, "each", RUBY_METHOD_FUNC(value_set_each), 0);
rb_define_method(cValueSet, "include?", RUBY_METHOD_FUNC(value_set_include_p), 1);
rb_define_method(cValueSet, "include_all?", RUBY_METHOD_FUNC(value_set_include_all_p), 1);
rb_define_method(cValueSet, "union", RUBY_METHOD_FUNC(value_set_union), 1);
rb_define_method(cValueSet, "intersection", RUBY_METHOD_FUNC(value_set_intersection), 1);
rb_define_method(cValueSet, "intersects?", RUBY_METHOD_FUNC(value_set_intersects), 1);
rb_define_method(cValueSet, "difference", RUBY_METHOD_FUNC(value_set_difference), 1);
rb_define_method(cValueSet, "insert", RUBY_METHOD_FUNC(value_set_insert), 1);
rb_define_method(cValueSet, "merge", RUBY_METHOD_FUNC(value_set_merge), 1);
rb_define_method(cValueSet, "delete", RUBY_METHOD_FUNC(value_set_delete), 1);
rb_define_method(cValueSet, "==", RUBY_METHOD_FUNC(value_set_equal), 1);
rb_define_method(cValueSet, "to_value_set", RUBY_METHOD_FUNC(value_set_to_value_set), 0);
rb_define_method(cValueSet, "dup", RUBY_METHOD_FUNC(value_set_dup), 0);
rb_define_method(cValueSet, "empty?", RUBY_METHOD_FUNC(value_set_empty_p), 0);
rb_define_method(cValueSet, "size", RUBY_METHOD_FUNC(value_set_size), 0);
rb_define_method(cValueSet, "clear", RUBY_METHOD_FUNC(value_set_clear), 0);
rb_define_method(cValueSet, "initialize_copy", RUBY_METHOD_FUNC(value_set_initialize_copy), 1);
rb_define_method(cValueSet, "delete_if", RUBY_METHOD_FUNC(value_set_delete_if), 0);
}
<|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 *
******************************************************************************/
#include <sofa/helper/Utils.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/system/Locale.h>
#include <sofa/helper/Logger.h>
#ifdef WIN32
# include <Windows.h>
# include <StrSafe.h>
#elif defined _XBOX
# include <xtl.h>
#elif defined __APPLE__
# include <mach-o/dyld.h> // for _NSGetExecutablePath()
# include <errno.h>
#else
# include <unistd.h> // for readlink()
# include <errno.h>
# include <linux/limits.h> // for PATH_MAX
#endif
#include <cstdlib>
#include <vector>
#include <iostream>
#include <fstream>
using sofa::helper::system::FileSystem;
namespace sofa
{
namespace helper
{
std::wstring Utils::widenString(const std::string& s)
{
// Set LC_CTYPE according to the environnement variable, for mbsrtowcs().
system::TemporaryLocale locale(LC_CTYPE, "");
const char * src = s.c_str();
// Call mbsrtowcs() once to find out the length of the converted string.
size_t length = mbsrtowcs(NULL, &src, 0, NULL);
if (length == size_t(-1)) {
int error = errno;
Logger::getMainLogger().log(Logger::Warning, strerror(error), "Utils::widenString()");
return L"";
}
// Call mbsrtowcs() again with a correctly sized buffer to actually do the conversion.
wchar_t * buffer = new wchar_t[length + 1];
length = mbsrtowcs(buffer, &src, length + 1, NULL);
if (length == size_t(-1)) {
int error = errno;
Logger::getMainLogger().log(Logger::Warning, strerror(error), "Utils::widenString()");
delete[] buffer;
return L"";
}
if (src != NULL) {
Logger::getMainLogger().log(Logger::Warning, "Conversion failed (\"" + s + "\")", "Utils::widenString()");
delete[] buffer;
return L"";
}
std::wstring result(buffer);
delete[] buffer;
return result;
}
std::string Utils::narrowString(const std::wstring& ws)
{
// Set LC_CTYPE according to the environnement variable, for wcstombs().
system::TemporaryLocale locale(LC_CTYPE, "");
const wchar_t * src = ws.c_str();
// Call wcstombs() once to find out the length of the converted string.
size_t length = wcstombs(NULL, src, 0);
if (length == size_t(-1)) {
Logger::getMainLogger().log(Logger::Warning, "Conversion failed", "Utils::narrowString()");
return "";
}
// Call wcstombs() again with a correctly sized buffer to actually do the conversion.
char * buffer = new char[length + 1];
length = wcstombs(buffer, src, length + 1);
if (length == size_t(-1)) {
Logger::getMainLogger().log(Logger::Warning, "Conversion failed", "Utils::narrowString()");
delete[] buffer;
return "";
}
std::string result(buffer);
delete[] buffer;
return result;
}
std::string Utils::downcaseString(const std::string& s)
{
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), ::tolower);
return result;
}
std::string Utils::upcaseString(const std::string& s)
{
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
return result;
}
#if defined WIN32 || defined _XBOX
# ifdef WIN32
std::string Utils::GetLastError() {
LPVOID lpErrMsgBuf;
LPVOID lpMessageBuf;
DWORD dwErrorCode = ::GetLastError();
// Get the string corresponding to the error code
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpErrMsgBuf,
0,
NULL);
// Allocate a bigger buffer
lpMessageBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpErrMsgBuf)+40)*sizeof(TCHAR));
// Format the message like so: "error 'code': 'message'"
StringCchPrintf((LPTSTR)lpMessageBuf,
LocalSize(lpMessageBuf) / sizeof(TCHAR),
TEXT("error %d: %s"),
dwErrorCode, lpErrMsgBuf);
std::wstring wsMessage((LPCTSTR)lpMessageBuf);
LocalFree(lpErrMsgBuf);
LocalFree(lpMessageBuf);
return narrowString(wsMessage);
}
# else // XBOX
std::string Utils::GetLastError() {
DWORD dwErrorCode = ::GetLastError();
char buffer[32];
sprintf_s(buffer, 32, "0x%08.8X", dwErrorCode);
return buffer;
}
# endif
#endif
static std::string computeExecutablePath()
{
std::string path = "";
#if defined(_XBOX) || defined(PS3)
Logger::getMainLogger().log(Logger::Error, "Utils::getExecutablePath() is not implemented on this platform.");
#elif defined(WIN32)
std::vector<TCHAR> lpFilename(MAX_PATH);
int ret = GetModuleFileName(NULL, /* NULL --> executable of the current process */
&lpFilename[0],
MAX_PATH);
if (ret == 0 || ret == MAX_PATH) {
Logger::getMainLogger().log(Logger::Error, Utils::GetLastError(), "Utils::getExecutablePath()");
} else {
path = Utils::narrowString(std::wstring(&lpFilename[0]));
}
#elif defined(__APPLE__)
std::vector<char> buffer(PATH_MAX);
std::vector<char> real_path(PATH_MAX);
uint32_t size = buffer.size();
if (_NSGetExecutablePath(&buffer[0], &size) != 0) {
Logger::getMainLogger().log(Logger::Error, "_NSGetExecutablePath() failed", "Utils::getExecutablePath()");
}
if (realpath(&buffer[0], &real_path[0]) == 0) {
Logger::getMainLogger().log(Logger::Error, "realpath() failed", "Utils::getExecutablePath()");
}
path = std::string(&real_path[0]);
#else // Linux
std::vector<char> buffer(PATH_MAX);
if (readlink("/proc/self/exe", &buffer[0], buffer.size()) == -1) {
int error = errno;
Logger::getMainLogger().log(Logger::Error, strerror(error), "Utils::getExecutablePath()");
} else {
path = std::string(&buffer[0]);
}
#endif
return FileSystem::cleanPath(path);
}
const std::string& Utils::getExecutablePath()
{
static const std::string path = computeExecutablePath();
return path;
}
const std::string& Utils::getExecutableDirectory()
{
static const std::string path = FileSystem::getParentDirectory(getExecutablePath());
return path;
}
static std::string computeSofaPathPrefix()
{
const std::string exePath = Utils::getExecutablePath();
std::size_t pos = exePath.rfind("/bin/");
if (pos == std::string::npos) {
Logger::getMainLogger().log(Logger::Error, "failed to deduce the root path of Sofa from the application path: (" + exePath + ")", "Utils::getSofaPathPrefix()");
// Safest thing to return in this case, I guess.
return Utils::getExecutableDirectory();
}
else {
return exePath.substr(0, pos);
}
}
const std::string& Utils::getSofaPathPrefix()
{
static const std::string prefix = computeSofaPathPrefix();
return prefix;
}
std::map<std::string, std::string> Utils::readBasicIniFile(const std::string& path)
{
std::map<std::string, std::string> map;
std::ifstream iniFile(path.c_str());
if (!iniFile.good())
{
Logger::getMainLogger().log(Logger::Error, "Error while trying to read file (" + path + ")", "Utils::readBasicIniFile()");
}
std::string line;
while (std::getline(iniFile, line))
{
size_t equalPos = line.find_first_of('=');
if (equalPos != std::string::npos)
{
const std::string key = line.substr(0, equalPos);
const std::string value = line.substr(equalPos + 1, std::string::npos);
map[key] = value;
}
}
return map;
}
} // namespace helper
} // namespace sofa
<commit_msg>[helper] if environment variable SOFA_ROOT is defined, this value will be used to compute the SofaPathPrefix<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 *
******************************************************************************/
#include <sofa/helper/Utils.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/system/Locale.h>
#include <sofa/helper/Logger.h>
#ifdef WIN32
# include <Windows.h>
# include <StrSafe.h>
#elif defined _XBOX
# include <xtl.h>
#elif defined __APPLE__
# include <mach-o/dyld.h> // for _NSGetExecutablePath()
# include <errno.h>
#else
# include <unistd.h> // for readlink()
# include <errno.h>
# include <linux/limits.h> // for PATH_MAX
#endif
#include <cstdlib>
#include <vector>
#include <iostream>
#include <fstream>
using sofa::helper::system::FileSystem;
namespace sofa
{
namespace helper
{
std::wstring Utils::widenString(const std::string& s)
{
// Set LC_CTYPE according to the environnement variable, for mbsrtowcs().
system::TemporaryLocale locale(LC_CTYPE, "");
const char * src = s.c_str();
// Call mbsrtowcs() once to find out the length of the converted string.
size_t length = mbsrtowcs(NULL, &src, 0, NULL);
if (length == size_t(-1)) {
int error = errno;
Logger::getMainLogger().log(Logger::Warning, strerror(error), "Utils::widenString()");
return L"";
}
// Call mbsrtowcs() again with a correctly sized buffer to actually do the conversion.
wchar_t * buffer = new wchar_t[length + 1];
length = mbsrtowcs(buffer, &src, length + 1, NULL);
if (length == size_t(-1)) {
int error = errno;
Logger::getMainLogger().log(Logger::Warning, strerror(error), "Utils::widenString()");
delete[] buffer;
return L"";
}
if (src != NULL) {
Logger::getMainLogger().log(Logger::Warning, "Conversion failed (\"" + s + "\")", "Utils::widenString()");
delete[] buffer;
return L"";
}
std::wstring result(buffer);
delete[] buffer;
return result;
}
std::string Utils::narrowString(const std::wstring& ws)
{
// Set LC_CTYPE according to the environnement variable, for wcstombs().
system::TemporaryLocale locale(LC_CTYPE, "");
const wchar_t * src = ws.c_str();
// Call wcstombs() once to find out the length of the converted string.
size_t length = wcstombs(NULL, src, 0);
if (length == size_t(-1)) {
Logger::getMainLogger().log(Logger::Warning, "Conversion failed", "Utils::narrowString()");
return "";
}
// Call wcstombs() again with a correctly sized buffer to actually do the conversion.
char * buffer = new char[length + 1];
length = wcstombs(buffer, src, length + 1);
if (length == size_t(-1)) {
Logger::getMainLogger().log(Logger::Warning, "Conversion failed", "Utils::narrowString()");
delete[] buffer;
return "";
}
std::string result(buffer);
delete[] buffer;
return result;
}
std::string Utils::downcaseString(const std::string& s)
{
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), ::tolower);
return result;
}
std::string Utils::upcaseString(const std::string& s)
{
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
return result;
}
#if defined WIN32 || defined _XBOX
# ifdef WIN32
std::string Utils::GetLastError() {
LPVOID lpErrMsgBuf;
LPVOID lpMessageBuf;
DWORD dwErrorCode = ::GetLastError();
// Get the string corresponding to the error code
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpErrMsgBuf,
0,
NULL);
// Allocate a bigger buffer
lpMessageBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpErrMsgBuf)+40)*sizeof(TCHAR));
// Format the message like so: "error 'code': 'message'"
StringCchPrintf((LPTSTR)lpMessageBuf,
LocalSize(lpMessageBuf) / sizeof(TCHAR),
TEXT("error %d: %s"),
dwErrorCode, lpErrMsgBuf);
std::wstring wsMessage((LPCTSTR)lpMessageBuf);
LocalFree(lpErrMsgBuf);
LocalFree(lpMessageBuf);
return narrowString(wsMessage);
}
# else // XBOX
std::string Utils::GetLastError() {
DWORD dwErrorCode = ::GetLastError();
char buffer[32];
sprintf_s(buffer, 32, "0x%08.8X", dwErrorCode);
return buffer;
}
# endif
#endif
static std::string computeExecutablePath()
{
std::string path = "";
#if defined(_XBOX) || defined(PS3)
Logger::getMainLogger().log(Logger::Error, "Utils::getExecutablePath() is not implemented on this platform.");
#elif defined(WIN32)
std::vector<TCHAR> lpFilename(MAX_PATH);
int ret = GetModuleFileName(NULL, /* NULL --> executable of the current process */
&lpFilename[0],
MAX_PATH);
if (ret == 0 || ret == MAX_PATH) {
Logger::getMainLogger().log(Logger::Error, Utils::GetLastError(), "Utils::getExecutablePath()");
} else {
path = Utils::narrowString(std::wstring(&lpFilename[0]));
}
#elif defined(__APPLE__)
std::vector<char> buffer(PATH_MAX);
std::vector<char> real_path(PATH_MAX);
uint32_t size = buffer.size();
if (_NSGetExecutablePath(&buffer[0], &size) != 0) {
Logger::getMainLogger().log(Logger::Error, "_NSGetExecutablePath() failed", "Utils::getExecutablePath()");
}
if (realpath(&buffer[0], &real_path[0]) == 0) {
Logger::getMainLogger().log(Logger::Error, "realpath() failed", "Utils::getExecutablePath()");
}
path = std::string(&real_path[0]);
#else // Linux
std::vector<char> buffer(PATH_MAX);
if (readlink("/proc/self/exe", &buffer[0], buffer.size()) == -1) {
int error = errno;
Logger::getMainLogger().log(Logger::Error, strerror(error), "Utils::getExecutablePath()");
} else {
path = std::string(&buffer[0]);
}
#endif
return FileSystem::cleanPath(path);
}
const std::string& Utils::getExecutablePath()
{
static const std::string path = computeExecutablePath();
return path;
}
const std::string& Utils::getExecutableDirectory()
{
static const std::string path = FileSystem::getParentDirectory(getExecutablePath());
return path;
}
static std::string computeSofaPathPrefix()
{
char* pathVar = getenv("SOFA_ROOT");
if (pathVar != NULL && FileSystem::exists(pathVar))
{
return std::string(pathVar);
}
else {
const std::string exePath = Utils::getExecutablePath();
std::size_t pos = exePath.rfind("/bin/");
if (pos == std::string::npos) {
Logger::getMainLogger().log(Logger::Error, "failed to deduce the root path of Sofa from the application path: (" + exePath + ")", "Utils::getSofaPathPrefix()");
// Safest thing to return in this case, I guess.
return Utils::getExecutableDirectory();
}
else {
return exePath.substr(0, pos);
}
}
}
const std::string& Utils::getSofaPathPrefix()
{
static const std::string prefix = computeSofaPathPrefix();
return prefix;
}
std::map<std::string, std::string> Utils::readBasicIniFile(const std::string& path)
{
std::map<std::string, std::string> map;
std::ifstream iniFile(path.c_str());
if (!iniFile.good())
{
Logger::getMainLogger().log(Logger::Error, "Error while trying to read file (" + path + ")", "Utils::readBasicIniFile()");
}
std::string line;
while (std::getline(iniFile, line))
{
size_t equalPos = line.find_first_of('=');
if (equalPos != std::string::npos)
{
const std::string key = line.substr(0, equalPos);
const std::string value = line.substr(equalPos + 1, std::string::npos);
map[key] = value;
}
}
return map;
}
} // namespace helper
} // namespace sofa
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin
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 "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include <curl/curl.h>
using namespace flusspferd;
// Put everything in an anon-namespace so typeid wont clash ever.
namespace {
class curl : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
static char const *full_name() { return "cURL"; }
typedef boost::mpl::bool_<false> constructible;
static char const *constructor_name() { return "cURL"; }
static void augment_constructor(object &ctor);
};
};
///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
return load_class<curl>(container);
}
///////////////////////////
void curl::class_info::augment_constructor(object &ctor)
{
curl_version_info_data* data = curl_version_info(CURLVERSION_NOW);
if (!data)
// Very unlikely to happen, but deal with it
throw exception("Unable to get curl_version_info");
array protocols = create_array();
ctor.define_property("supportedProtocols", protocols, read_only_property );
size_t i = 0;
for(const char* const* p = data->protocols; *p != NULL; p++, i++) {
protocols.set_element(i, string( *p ) );
}
// Make the properties of the array read only too
//protocols.seal(false);
// Arse. Can't in 1.8
ctor.define_property("versionHex", (int)data->version_num, read_only_property);
ctor.define_property("versionStr", string( (const char*)data->version), read_only_property);
}
} // End of anon namespace
<commit_msg>Plugins/curl: Initial setup and stub JS and curl callback methods<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin
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 "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include <curl/curl.h>
using namespace flusspferd;
// Put everything in an anon-namespace so typeid wont clash ever.
namespace {
class curl : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
static char const *full_name() { return "cURL"; }
typedef boost::mpl::bool_<true> constructible;
static char const *constructor_name() { return "cURL"; }
static void augment_constructor(object &ctor);
static object create_prototype();
};
curl(object const &obj, call_context &x);
virtual ~curl();
protected:
CURL *curlHandle;
char* error_buffer;
typedef size_t (*curl_callback_t)(void *, size_t, size_t, void *);
template<size_t (curl::*Method)(void*, size_t)>
static size_t c_handle_curl(void *ptr, size_t size, size_t nmemb, void *stream);
// Data is avilable
size_t handle_curl_data( void* data, size_t size );
// Header is available
size_t handle_curl_header( void* data, size_t size );
// Data is needed by curl (i.e. upload/request body)
size_t handle_curl_data_needed( void* buff, size_t size );
private: // JS methods
void set_url(string url);
void set_method(string meth);
int perform();
};
template<size_t (curl::*Method)(void*, size_t)>
size_t curl::c_handle_curl(void *ptr, size_t size, size_t nmemb, void *stream) {
curl *self = static_cast<curl*>(stream);
return (self->*Method)(ptr, size * nmemb);
}
///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
return load_class<curl>(container);
}
///////////////////////////
void curl::class_info::augment_constructor(object &ctor)
{
curl_version_info_data* data = curl_version_info(CURLVERSION_NOW);
if (!data)
// Very unlikely to happen, but deal with it
throw exception("Unable to get curl_version_info");
array protocols = create_array();
ctor.define_property("supportedProtocols", protocols, read_only_property );
size_t i = 0;
for(const char* const* p = data->protocols; *p != NULL; p++, i++) {
protocols.set_element(i, string( *p ) );
}
// Make the properties of the array read only too
//protocols.seal(false);
// Arse. Can't in 1.8
ctor.define_property("versionHex", (int)data->version_num, read_only_property);
ctor.define_property("versionStr", string( (const char*)data->version), read_only_property);
}
///////////////////////////
object curl::class_info::create_prototype() {
object proto = create_object();
create_native_method( proto, "setURL", 1);
create_native_method( proto, "setMethod", 1);
create_native_method( proto, "perform", 0);
return proto;
}
///////////////////////////
curl::curl(object const &obj, call_context &)
: native_object_base(obj),
error_buffer(NULL)
{
register_native_method("setURL", &curl::set_url);
register_native_method("setMethod", &curl::set_method);
register_native_method("perform", &curl::perform);
curlHandle = curl_easy_init();
if (!curlHandle)
throw exception("curl_easy_init() failed");
error_buffer = new char[CURL_ERROR_SIZE];
curl_callback_t fn_ptr = &curl::c_handle_curl<&curl::handle_curl_data>;
curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, fn_ptr);
fn_ptr = &curl::c_handle_curl<&curl::handle_curl_header>;
curl_easy_setopt(curlHandle, CURLOPT_HEADERFUNCTION, fn_ptr);
fn_ptr = &curl::c_handle_curl<&curl::handle_curl_data_needed>;
curl_easy_setopt(curlHandle, CURLOPT_READFUNCTION, fn_ptr);
curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curlHandle, CURLOPT_HEADERDATA, this);
curl_easy_setopt(curlHandle, CURLOPT_READDATA, this);
curl_easy_setopt(curlHandle, CURLOPT_ERRORBUFFER, error_buffer);
curl_easy_setopt(curlHandle, CURLOPT_ENCODING, "");
}
///////////////////////////
curl::~curl() {
delete [] error_buffer;
}
///////////////////////////
void curl::set_url(string url ) {
}
///////////////////////////
void curl::set_method(string f_meth) {
}
///////////////////////////
int curl::perform() {
return 0;
}
size_t curl::handle_curl_data( void*, size_t ) {
return 0;
}
size_t curl::handle_curl_header( void*, size_t ) {
return 0;
}
size_t curl::handle_curl_data_needed( void*, size_t ) {
return 0;
}
} // End of anon namespace
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.