text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#include "BufferDirect3D11.hpp"
#include "Pomdog/Graphics/BufferUsage.hpp"
#include "Pomdog/Utility/Assert.hpp"
#include "Pomdog/Utility/Exception.hpp"
#include <utility>
namespace Pomdog {
namespace Detail {
namespace Direct3D11 {
namespace {
static ID3D11Buffer* CreateNativeBuffer(
ID3D11Device* device,
std::size_t sizeInBytes,
void const* data,
BufferUsage bufferUsage,
D3D11_BIND_FLAG bindFlag)
{
POMDOG_ASSERT(bindFlag == D3D11_BIND_CONSTANT_BUFFER
|| bindFlag == D3D11_BIND_INDEX_BUFFER
|| bindFlag == D3D11_BIND_VERTEX_BUFFER);
#if defined(DEBUG) && !defined(NDEBUG)
if (bindFlag == D3D11_BIND_CONSTANT_BUFFER) {
POMDOG_ASSERT_MESSAGE(sizeInBytes % 16 == 0,
"You must set the sizeInBytes value in multiples of 16.");
POMDOG_ASSERT_MESSAGE(sizeInBytes <= D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT,
"You must set the sizeInBytes value less than or equal to D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT.");
}
#endif
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = static_cast<::UINT>(sizeInBytes);
bufferDesc.BindFlags = bindFlag;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
switch (bufferUsage) {
case BufferUsage::Dynamic:
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
break;
case BufferUsage::Immutable:
bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
bufferDesc.CPUAccessFlags = 0;
break;
default:
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.CPUAccessFlags = 0;
break;
}
D3D11_SUBRESOURCE_DATA subresourceData;
subresourceData.pSysMem = data;
subresourceData.SysMemPitch = 0;
subresourceData.SysMemSlicePitch = 0;
POMDOG_ASSERT(device != nullptr);
POMDOG_ASSERT((bufferDesc.Usage != D3D11_USAGE_IMMUTABLE)
|| ((bufferDesc.Usage == D3D11_USAGE_IMMUTABLE) && (data != nullptr)));
auto initialData = (data != nullptr) ? &subresourceData : nullptr;
ID3D11Buffer* buffer = nullptr;
HRESULT hr = device->CreateBuffer(&bufferDesc, initialData, &buffer);
if (FAILED(hr)) {
// FUS RO DAH!
POMDOG_THROW_EXCEPTION(std::runtime_error,
"Failed to create ID3D11Buffer");
}
return std::move(buffer);
}
} // unnamed namespace
//-----------------------------------------------------------------------
BufferDirect3D11::BufferDirect3D11(
ID3D11Device* device,
Microsoft::WRL::ComPtr<ID3D11DeviceContext> const& deviceContextIn,
std::size_t sizeInBytes,
BufferUsage bufferUsage,
D3D11_BIND_FLAG bindFlag)
: deviceContext(deviceContextIn)
{
buffer = CreateNativeBuffer(device, sizeInBytes,
nullptr, bufferUsage, bindFlag);
}
//-----------------------------------------------------------------------
BufferDirect3D11::BufferDirect3D11(
ID3D11Device* device,
Microsoft::WRL::ComPtr<ID3D11DeviceContext> const& deviceContextIn,
void const* sourceData,
std::size_t sizeInBytes,
BufferUsage bufferUsage,
D3D11_BIND_FLAG bindFlag)
: deviceContext(deviceContextIn)
{
buffer = CreateNativeBuffer(device, sizeInBytes,
sourceData, bufferUsage, bindFlag);
}
//-----------------------------------------------------------------------
void BufferDirect3D11::GetData(std::size_t offsetInBytes,
void* destination, std::size_t sizeInBytes) const
{
POMDOG_ASSERT(buffer);
POMDOG_ASSERT(deviceContext);
POMDOG_ASSERT(destination != nullptr);
POMDOG_ASSERT(sizeInBytes > 0);
D3D11_MAPPED_SUBRESOURCE mappedResource;
auto hr = deviceContext->Map(buffer.Get(), 0,
D3D11_MAP_READ, 0, &mappedResource);
if (FAILED(hr)) {
// FUS RO DAH!
POMDOG_THROW_EXCEPTION(std::runtime_error, "Failed to map buffer");
}
auto mappedMemory = reinterpret_cast<std::uint8_t*>(mappedResource.pData)
+ offsetInBytes;
std::memcpy(destination, mappedMemory, sizeInBytes);
deviceContext->Unmap(buffer.Get(), 0);
}
//-----------------------------------------------------------------------
void BufferDirect3D11::SetData(std::size_t offsetInBytes,
void const* source, std::size_t sizeInBytes)
{
POMDOG_ASSERT(buffer);
POMDOG_ASSERT(deviceContext);
POMDOG_ASSERT(source != nullptr);
POMDOG_ASSERT(sizeInBytes > 0);
D3D11_MAPPED_SUBRESOURCE mappedResource;
auto hr = deviceContext->Map(buffer.Get(), 0,
D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(hr)) {
// FUS RO DAH!
POMDOG_THROW_EXCEPTION(std::runtime_error, "Failed to map buffer");
}
auto mappedMemory = reinterpret_cast<std::uint8_t*>(mappedResource.pData)
+ offsetInBytes;
std::memcpy(mappedMemory, source, sizeInBytes);
deviceContext->Unmap(buffer.Get(), 0);
}
//-----------------------------------------------------------------------
ID3D11Buffer* BufferDirect3D11::GetBuffer() const
{
POMDOG_ASSERT(buffer);
return buffer.Get();
}
//-----------------------------------------------------------------------
} // namespace Direct3D11
} // namespace Detail
} // namespace Pomdog
<commit_msg>Fix SetVertexBuffer() function on Direct3D 11<commit_after>// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#include "BufferDirect3D11.hpp"
#include "Pomdog/Graphics/BufferUsage.hpp"
#include "Pomdog/Utility/Assert.hpp"
#include "Pomdog/Utility/Exception.hpp"
#include <utility>
namespace Pomdog {
namespace Detail {
namespace Direct3D11 {
namespace {
static ID3D11Buffer* CreateNativeBuffer(
ID3D11Device* device,
std::size_t sizeInBytes,
void const* data,
BufferUsage bufferUsage,
D3D11_BIND_FLAG bindFlag)
{
POMDOG_ASSERT(bindFlag == D3D11_BIND_CONSTANT_BUFFER
|| bindFlag == D3D11_BIND_INDEX_BUFFER
|| bindFlag == D3D11_BIND_VERTEX_BUFFER);
#if defined(DEBUG) && !defined(NDEBUG)
if (bindFlag == D3D11_BIND_CONSTANT_BUFFER) {
POMDOG_ASSERT_MESSAGE(sizeInBytes % 16 == 0,
"You must set the sizeInBytes value in multiples of 16.");
POMDOG_ASSERT_MESSAGE(sizeInBytes <= D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT,
"You must set the sizeInBytes value less than or equal to D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT.");
}
#endif
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = static_cast<::UINT>(sizeInBytes);
bufferDesc.BindFlags = bindFlag;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
switch (bufferUsage) {
case BufferUsage::Dynamic:
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
break;
case BufferUsage::Immutable:
bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
bufferDesc.CPUAccessFlags = 0;
break;
default:
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.CPUAccessFlags = 0;
break;
}
D3D11_SUBRESOURCE_DATA subresourceData;
subresourceData.pSysMem = data;
subresourceData.SysMemPitch = 0;
subresourceData.SysMemSlicePitch = 0;
POMDOG_ASSERT(device != nullptr);
POMDOG_ASSERT((bufferDesc.Usage != D3D11_USAGE_IMMUTABLE)
|| ((bufferDesc.Usage == D3D11_USAGE_IMMUTABLE) && (data != nullptr)));
auto initialData = (data != nullptr) ? &subresourceData : nullptr;
ID3D11Buffer* buffer = nullptr;
HRESULT hr = device->CreateBuffer(&bufferDesc, initialData, &buffer);
if (FAILED(hr)) {
// FUS RO DAH!
POMDOG_THROW_EXCEPTION(std::runtime_error,
"Failed to create ID3D11Buffer");
}
return std::move(buffer);
}
} // unnamed namespace
//-----------------------------------------------------------------------
BufferDirect3D11::BufferDirect3D11(
ID3D11Device* device,
Microsoft::WRL::ComPtr<ID3D11DeviceContext> const& deviceContextIn,
std::size_t sizeInBytes,
BufferUsage bufferUsage,
D3D11_BIND_FLAG bindFlag)
: deviceContext(deviceContextIn)
{
buffer = CreateNativeBuffer(device, sizeInBytes,
nullptr, bufferUsage, bindFlag);
}
//-----------------------------------------------------------------------
BufferDirect3D11::BufferDirect3D11(
ID3D11Device* device,
Microsoft::WRL::ComPtr<ID3D11DeviceContext> const& deviceContextIn,
void const* sourceData,
std::size_t sizeInBytes,
BufferUsage bufferUsage,
D3D11_BIND_FLAG bindFlag)
: deviceContext(deviceContextIn)
{
buffer = CreateNativeBuffer(device, sizeInBytes,
sourceData, bufferUsage, bindFlag);
}
//-----------------------------------------------------------------------
void BufferDirect3D11::GetData(std::size_t offsetInBytes,
void* destination, std::size_t sizeInBytes) const
{
POMDOG_ASSERT(buffer);
POMDOG_ASSERT(deviceContext);
POMDOG_ASSERT(destination != nullptr);
POMDOG_ASSERT(sizeInBytes > 0);
D3D11_MAPPED_SUBRESOURCE mappedResource;
auto hr = deviceContext->Map(buffer.Get(), 0,
D3D11_MAP_READ, 0, &mappedResource);
if (FAILED(hr)) {
// FUS RO DAH!
POMDOG_THROW_EXCEPTION(std::runtime_error, "Failed to map buffer");
}
auto mappedMemory = reinterpret_cast<std::uint8_t*>(mappedResource.pData)
+ offsetInBytes;
std::memcpy(destination, mappedMemory, sizeInBytes);
deviceContext->Unmap(buffer.Get(), 0);
}
//-----------------------------------------------------------------------
void BufferDirect3D11::SetData(std::size_t offsetInBytes,
void const* source, std::size_t sizeInBytes)
{
POMDOG_ASSERT(buffer);
POMDOG_ASSERT(deviceContext);
POMDOG_ASSERT(source != nullptr);
POMDOG_ASSERT(sizeInBytes > 0);
//constexpr D3D11_MAP mapType = D3D11_MAP_WRITE_DISCARD;
constexpr D3D11_MAP mapType = D3D11_MAP_WRITE_NO_OVERWRITE;
D3D11_MAPPED_SUBRESOURCE mappedResource;
auto hr = deviceContext->Map(buffer.Get(), 0,
mapType, 0, &mappedResource);
if (FAILED(hr)) {
// FUS RO DAH!
POMDOG_THROW_EXCEPTION(std::runtime_error, "Failed to map buffer");
}
auto mappedMemory = reinterpret_cast<std::uint8_t*>(mappedResource.pData)
+ offsetInBytes;
std::memcpy(mappedMemory, source, sizeInBytes);
deviceContext->Unmap(buffer.Get(), 0);
}
//-----------------------------------------------------------------------
ID3D11Buffer* BufferDirect3D11::GetBuffer() const
{
POMDOG_ASSERT(buffer);
return buffer.Get();
}
//-----------------------------------------------------------------------
} // namespace Direct3D11
} // namespace Detail
} // namespace Pomdog
<|endoftext|>
|
<commit_before>/**
** \file binder/binder.cc
** \brief Implementation of binder::Binder.
*/
#include <boost/bind.hpp>
#include <boost/optional.hpp>
#include <libport/foreach.hh>
#include <ast/print.hh>
#include <binder/binder.hh>
#include <object/symbols.hh>
#include <object/object.hh>
namespace binder
{
Binder::Binder()
: unbind_()
, env_()
, depth_(1)
{
unbind_.push_back(libport::Finally());
setOnSelf_.push_back(true);
}
Binder::~Binder()
{}
unsigned Binder::depth_get(const libport::Symbol& name)
{
if (env_[name].empty())
return 0;
else
{
assert(env_[name].back().second > 0);
return env_[name].back().second;
}
}
ast::rDeclaration Binder::decl_get(const libport::Symbol& name)
{
assert (!env_[name].empty());
return env_[name].back().first;
}
ast::rCall Binder::changeSlot (const ast::loc& l,
const libport::Symbol& name,
const libport::Symbol& method,
ast::rConstExp value)
{
ast::exps_type* args = new ast::exps_type();
args->push_back(new ast::String(l, name));
super_type::operator() (value);
args->push_back(result_.unsafe_cast<ast::Exp>());
return new ast::Call(l, new ast::Implicit(l), method, args);
}
void Binder::visit(ast::rConstAssignment input)
{
assert(!input->declaration_get());
libport::Symbol name = input->what_get();
if (unsigned depth = depth_get(name))
{
super_type::visit(input);
ast::rAssignment res = result_.unsafe_cast<ast::Assignment>();
res->depth_set(depth_ - depth);
res->declaration_set(decl_get(name));
}
else
{
ast::rCall res = changeSlot(input->location_get(),
input->what_get(),
SYMBOL(updateSlot),
input->value_get());
result_ = res;
}
}
void Binder::visit(ast::rConstDeclaration input)
{
if (setOnSelf_.back())
{
ast::rCall res = changeSlot(input->location_get(),
input->what_get(),
SYMBOL(setSlot),
input->value_get());
result_ = res;
}
else
{
super_type::visit(input);
ast::rDeclaration res = result_.unsafe_cast<ast::Declaration>();
bind(res);
// FIXME: How should we handle the toplevel?
if (!function_stack_.empty())
function()->local_variables_get()->
push_back(res);
}
}
void Binder::visit (ast::rConstCall input)
{
libport::Symbol name = input->name_get();
bool implicit = input->target_implicit();
// If this is a qualified call, nothing particular to do
if (implicit)
{
unsigned depth = depth_get(name);
if (name == SYMBOL(call)
|| name == SYMBOL(self))
{
depth = depth_;
}
if (depth)
{
// This is a closed variable
function_stack_type::iterator it = function_stack_.end();
for (int i = depth_ - depth; i; --i, --it)
decl_get(name)->closed_set(true);
const ast::exps_type* args = input->arguments_get();
ast::rLocal res = new ast::Local(
input->location_get(), name,
args ? recurse_collection(*args) : 0,
depth_ - depth);
res->declaration_set(decl_get(name));
result_ = res;
return;
}
else
super_type::visit (input);
}
else
super_type::visit (input);
}
void Binder::visit (ast::rConstForeach input)
{
libport::Finally finally;
unbind_.push_back(libport::Finally());
finally << boost::bind(&unbind_type::pop_back, &unbind_);
setOnSelf_.push_back(false);
finally << boost::bind(&set_on_self_type::pop_back, &setOnSelf_);
bind(input->index_get());
super_type::visit(input);
}
void Binder::visit (ast::rConstScope input)
{
result_ = new ast::Scope(input->location_get(), handleScope(input, false));
}
void Binder::visit (ast::rConstDo input)
{
operator() (input->target_get());
ast::rExp target = result_.unsafe_cast<ast::Exp>();
result_ = new ast::Do(input->location_get(),
handleScope(input, true),
target);
}
ast::rExp Binder::handleScope(ast::rConstAbstractScope scope, bool setOnSelf)
{
libport::Finally finally;
// Push a finally on unbind_, and destroy it at the scope
// exit. Since bound variables register themselves for unbinding
// in unbind_'s top element, they will be unbound at scope exit.
unbind_.push_back(libport::Finally());
finally << boost::bind(&unbind_type::pop_back, &unbind_);
setOnSelf_.push_back(setOnSelf);
finally << boost::bind(&set_on_self_type::pop_back, &setOnSelf_);
operator() (scope->body_get());
return result_.unsafe_cast<ast::Exp>();
}
static void decrement(unsigned* n)
{
(*n)--;
}
void Binder::visit(ast::rConstFunction input)
{
libport::Finally finally;
// Clone and push the function, without filling its body and arguments
ast::rFunction res = new ast::Function(input->location_get(), 0, 0);
res->local_variables_set(new ast::declarations_type());
push_function(res);
finally << boost::bind(&Binder::pop_function, this);
// Open a new scope
unbind_.push_back(libport::Finally());
finally << boost::bind(&unbind_type::pop_back, &unbind_);
// Do not setOnSelf in this scope
setOnSelf_.push_back(false);
finally << boost::bind(&set_on_self_type::pop_back, &setOnSelf_);
// Increase the nested functions depth
depth_++;
finally << boost::bind(decrement, &depth_);
// Bind and clone arguments
ast::declarations_type* formals =
input->formals_get () ? recurse_collection (*input->formals_get ()) : 0;
// Bind and clone the body
ast::rAbstractScope body = recurse (input->body_get ());
// Assemble the result
res->formals_set(formals);
res->body_set(body);
result_ = res;
// Index local and closed variables
int local = 2;
int closed = 0;
foreach (ast::rDeclaration dec, *res->local_variables_get())
if (dec->closed_get())
dec->local_index_set(closed++);
else
dec->local_index_set(local++);
}
void Binder::visit(ast::rConstClosure input)
{
assert(!input->local_variables_get());
ast::declarations_type* formals =
input->formals_get () ? recurse_collection (*input->formals_get ()) : 0;
if (formals)
foreach (ast::rDeclaration arg, *formals)
bind(arg);
ast::rAbstractScope body = recurse (input->body_get ());
ast::rClosure res = new ast::Closure (input->location_get(), formals, body);
result_ = res;
}
void Binder::bind(ast::rDeclaration decl)
{
assert(decl);
env_[decl->what_get()].push_back(std::make_pair(decl, depth_));
unbind_.back() <<
boost::bind(&Bindings::pop_back, &env_[decl->what_get()]);
}
void Binder::push_function(ast::rFunction f)
{
function_stack_.push_back(f);
}
void Binder::pop_function()
{
function_stack_.pop_back();
}
ast::rFunction Binder::function() const
{
assert(!function_stack_.empty());
return function_stack_.back();
}
} // namespace binder
<commit_msg>Remove obsolete test on self and call.<commit_after>/**
** \file binder/binder.cc
** \brief Implementation of binder::Binder.
*/
#include <boost/bind.hpp>
#include <boost/optional.hpp>
#include <libport/foreach.hh>
#include <ast/print.hh>
#include <binder/binder.hh>
#include <object/symbols.hh>
#include <object/object.hh>
namespace binder
{
Binder::Binder()
: unbind_()
, env_()
, depth_(1)
{
unbind_.push_back(libport::Finally());
setOnSelf_.push_back(true);
}
Binder::~Binder()
{}
unsigned Binder::depth_get(const libport::Symbol& name)
{
if (env_[name].empty())
return 0;
else
{
assert(env_[name].back().second > 0);
return env_[name].back().second;
}
}
ast::rDeclaration Binder::decl_get(const libport::Symbol& name)
{
assert (!env_[name].empty());
return env_[name].back().first;
}
ast::rCall Binder::changeSlot (const ast::loc& l,
const libport::Symbol& name,
const libport::Symbol& method,
ast::rConstExp value)
{
ast::exps_type* args = new ast::exps_type();
args->push_back(new ast::String(l, name));
super_type::operator() (value);
args->push_back(result_.unsafe_cast<ast::Exp>());
return new ast::Call(l, new ast::Implicit(l), method, args);
}
void Binder::visit(ast::rConstAssignment input)
{
assert(!input->declaration_get());
libport::Symbol name = input->what_get();
if (unsigned depth = depth_get(name))
{
super_type::visit(input);
ast::rAssignment res = result_.unsafe_cast<ast::Assignment>();
res->depth_set(depth_ - depth);
res->declaration_set(decl_get(name));
}
else
{
ast::rCall res = changeSlot(input->location_get(),
input->what_get(),
SYMBOL(updateSlot),
input->value_get());
result_ = res;
}
}
void Binder::visit(ast::rConstDeclaration input)
{
if (setOnSelf_.back())
{
ast::rCall res = changeSlot(input->location_get(),
input->what_get(),
SYMBOL(setSlot),
input->value_get());
result_ = res;
}
else
{
super_type::visit(input);
ast::rDeclaration res = result_.unsafe_cast<ast::Declaration>();
bind(res);
// FIXME: How should we handle the toplevel?
if (!function_stack_.empty())
function()->local_variables_get()->
push_back(res);
}
}
void Binder::visit (ast::rConstCall input)
{
libport::Symbol name = input->name_get();
bool implicit = input->target_implicit();
// If this is a qualified call, nothing particular to do
if (implicit)
{
unsigned depth = depth_get(name);
if (depth)
{
// This is a closed variable
function_stack_type::iterator it = function_stack_.end();
for (int i = depth_ - depth; i; --i, --it)
decl_get(name)->closed_set(true);
const ast::exps_type* args = input->arguments_get();
ast::rLocal res = new ast::Local(
input->location_get(), name,
args ? recurse_collection(*args) : 0,
depth_ - depth);
res->declaration_set(decl_get(name));
result_ = res;
return;
}
else
super_type::visit (input);
}
else
super_type::visit (input);
}
void Binder::visit (ast::rConstForeach input)
{
libport::Finally finally;
unbind_.push_back(libport::Finally());
finally << boost::bind(&unbind_type::pop_back, &unbind_);
setOnSelf_.push_back(false);
finally << boost::bind(&set_on_self_type::pop_back, &setOnSelf_);
bind(input->index_get());
super_type::visit(input);
}
void Binder::visit (ast::rConstScope input)
{
result_ = new ast::Scope(input->location_get(), handleScope(input, false));
}
void Binder::visit (ast::rConstDo input)
{
operator() (input->target_get());
ast::rExp target = result_.unsafe_cast<ast::Exp>();
result_ = new ast::Do(input->location_get(),
handleScope(input, true),
target);
}
ast::rExp Binder::handleScope(ast::rConstAbstractScope scope, bool setOnSelf)
{
libport::Finally finally;
// Push a finally on unbind_, and destroy it at the scope
// exit. Since bound variables register themselves for unbinding
// in unbind_'s top element, they will be unbound at scope exit.
unbind_.push_back(libport::Finally());
finally << boost::bind(&unbind_type::pop_back, &unbind_);
setOnSelf_.push_back(setOnSelf);
finally << boost::bind(&set_on_self_type::pop_back, &setOnSelf_);
operator() (scope->body_get());
return result_.unsafe_cast<ast::Exp>();
}
static void decrement(unsigned* n)
{
(*n)--;
}
void Binder::visit(ast::rConstFunction input)
{
libport::Finally finally;
// Clone and push the function, without filling its body and arguments
ast::rFunction res = new ast::Function(input->location_get(), 0, 0);
res->local_variables_set(new ast::declarations_type());
push_function(res);
finally << boost::bind(&Binder::pop_function, this);
// Open a new scope
unbind_.push_back(libport::Finally());
finally << boost::bind(&unbind_type::pop_back, &unbind_);
// Do not setOnSelf in this scope
setOnSelf_.push_back(false);
finally << boost::bind(&set_on_self_type::pop_back, &setOnSelf_);
// Increase the nested functions depth
depth_++;
finally << boost::bind(decrement, &depth_);
// Bind and clone arguments
ast::declarations_type* formals =
input->formals_get () ? recurse_collection (*input->formals_get ()) : 0;
// Bind and clone the body
ast::rAbstractScope body = recurse (input->body_get ());
// Assemble the result
res->formals_set(formals);
res->body_set(body);
result_ = res;
// Index local and closed variables
int local = 2;
int closed = 0;
foreach (ast::rDeclaration dec, *res->local_variables_get())
if (dec->closed_get())
dec->local_index_set(closed++);
else
dec->local_index_set(local++);
}
void Binder::visit(ast::rConstClosure input)
{
assert(!input->local_variables_get());
ast::declarations_type* formals =
input->formals_get () ? recurse_collection (*input->formals_get ()) : 0;
if (formals)
foreach (ast::rDeclaration arg, *formals)
bind(arg);
ast::rAbstractScope body = recurse (input->body_get ());
ast::rClosure res = new ast::Closure (input->location_get(), formals, body);
result_ = res;
}
void Binder::bind(ast::rDeclaration decl)
{
assert(decl);
env_[decl->what_get()].push_back(std::make_pair(decl, depth_));
unbind_.back() <<
boost::bind(&Bindings::pop_back, &env_[decl->what_get()]);
}
void Binder::push_function(ast::rFunction f)
{
function_stack_.push_back(f);
}
void Binder::pop_function()
{
function_stack_.pop_back();
}
ast::rFunction Binder::function() const
{
assert(!function_stack_.empty());
return function_stack_.back();
}
} // namespace binder
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
using namespace fnord;
typedef Tuple<
String,
String,
uint64_t,
uint64_t,
double,
double,
double,
double> OutputRow;
typedef HashMap<String, cm::CTRCounter> CounterMap;
/* read all input sstables */
void importInputTables(const Vector<String> sstables, CounterMap* counters) {
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable heade r*/
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
sstable::SSTableColumnSchema schema;
schema.loadIndex(&reader);
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
int row_idx = 0;
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.ctrstats",
"[$1/$2] [$0%] Reading sstable... rows=$3",
(size_t) ((cursor->position() / (double) body_size) * 100),
tbl_idx + 1, sstables.size(), row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto key = cursor->getKeyString();
auto val = cursor->getDataBuffer();
sstable::SSTableColumnReader cols(&schema, val);
auto& counter = (*counters)[key];
auto num_views = cols.getUInt64Column(schema.columnID("num_views"));
auto num_clicks= cols.getUInt64Column(schema.columnID("num_clicks"));
counter.num_views += num_views;
counter.num_clicks += num_clicks;
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
}
/* write output table */
void writeOutputTable(const String& filename, const Vector<OutputRow>& rows) {
/* prepare output sstable schema */
sstable::SSTableColumnSchema sstable_schema;
sstable_schema.addColumn("num_views", 1, sstable::SSTableColumnType::UINT64);
sstable_schema.addColumn("num_clicks", 2, sstable::SSTableColumnType::UINT64);
sstable_schema.addColumn("p_view_base", 3, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn("p_view_dim1", 4, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn("p_click", 5, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn(
"p_click_normalized",
6,
sstable::SSTableColumnType::FLOAT);
/* open output sstable */
fnord::logInfo("cm.ctrstats", "Writing results to: $0", filename);
auto sstable_writer = sstable::SSTableWriter::create(
filename,
sstable::IndexProvider{},
nullptr,
0);
/* write output sstable */
for (const auto& r : rows) {
sstable::SSTableColumnWriter cols(&sstable_schema);
cols.addStringColumn(1, std::get<1>(r));
cols.addUInt64Column(2, std::get<2>(r));
cols.addUInt64Column(3, std::get<3>(r));
cols.addFloatColumn(4, std::get<4>(r));
cols.addFloatColumn(5, std::get<5>(r));
cols.addFloatColumn(6, std::get<6>(r));
cols.addFloatColumn(7, std::get<7>(r));
sstable_writer->appendRow(std::get<0>(r), cols);
}
sstable_schema.writeIndex(sstable_writer.get());
sstable_writer->finalize();
}
/* aggregate ctr counters (flat) */
void aggregateCounters(CounterMap* counters, Vector<OutputRow>* rows) {
const auto& global_counter_iter = counters->find("__GLOBAL");
if (global_counter_iter == counters->end()) {
fnord::logCritical("cm.ctrstatsexport", "missing global counter");
exit(1);
}
const auto& global_counter = global_counter_iter->second;
for (const auto& row : *counters) {
const auto& ctr = row.second;
auto sep = row.first.find("~");
if (sep == std::string::npos) {
continue;
}
auto dim1 = row.first.substr(0, sep);
auto dim2 = row.first.substr(sep + 1);
if (dim1.length() == 0 || dim2.length() == 0) {
continue;
}
const auto& group_counter_iter = counters->find(dim1);
if (group_counter_iter == counters->end()) {
fnord::logWarning("cm.ctrstatsexport", "missing row: $0", dim1);
continue;
}
const auto& group_counter = group_counter_iter->second;
double p_base = ctr.num_views / (double) global_counter.num_views;
double p_base_dim2 = ctr.num_views / (double) group_counter.num_views;
double p_click = ctr.num_clicks / (double) ctr.num_views;
double p_click_n = ctr.num_clicks / (double) group_counter.num_clicks;
rows->emplace_back(
dim1,
dim2,
row.second.num_views,
row.second.num_clicks,
p_base,
p_base_dim2,
p_click,
p_click_n);
}
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"output_file",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"output file path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* read input tables */
HashMap<String, cm::CTRCounter> counters;
importInputTables(flags.getArgv(), &counters);
/* aggregate counters */
Vector<OutputRow> rows;
aggregateCounters(&counters, &rows);
/* write output table */
writeOutputTable(flags.getString("output_file"), rows);
return 0;
}
<commit_msg>correct output sstable schema<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
using namespace fnord;
typedef Tuple<
String,
String,
uint64_t,
uint64_t,
double,
double,
double,
double> OutputRow;
typedef HashMap<String, cm::CTRCounter> CounterMap;
/* read all input sstables */
void importInputTables(const Vector<String> sstables, CounterMap* counters) {
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable heade r*/
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
sstable::SSTableColumnSchema schema;
schema.loadIndex(&reader);
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
int row_idx = 0;
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.ctrstats",
"[$1/$2] [$0%] Reading sstable... rows=$3",
(size_t) ((cursor->position() / (double) body_size) * 100),
tbl_idx + 1, sstables.size(), row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto key = cursor->getKeyString();
auto val = cursor->getDataBuffer();
sstable::SSTableColumnReader cols(&schema, val);
auto& counter = (*counters)[key];
auto num_views = cols.getUInt64Column(schema.columnID("num_views"));
auto num_clicks= cols.getUInt64Column(schema.columnID("num_clicks"));
counter.num_views += num_views;
counter.num_clicks += num_clicks;
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
}
/* write output table */
void writeOutputTable(const String& filename, const Vector<OutputRow>& rows) {
/* prepare output sstable schema */
sstable::SSTableColumnSchema sstable_schema;
sstable_schema.addColumn("dim1", 1, sstable::SSTableColumnType::STRING);
sstable_schema.addColumn("num_views", 2, sstable::SSTableColumnType::UINT64);
sstable_schema.addColumn("num_clicks", 3, sstable::SSTableColumnType::UINT64);
sstable_schema.addColumn("p_view_base", 4, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn("p_view_dim1", 5, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn("p_click", 6, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn(
"p_click_normalized",
7,
sstable::SSTableColumnType::FLOAT);
/* open output sstable */
fnord::logInfo("cm.ctrstats", "Writing results to: $0", filename);
auto sstable_writer = sstable::SSTableWriter::create(
filename,
sstable::IndexProvider{},
nullptr,
0);
/* write output sstable */
for (const auto& r : rows) {
sstable::SSTableColumnWriter cols(&sstable_schema);
cols.addStringColumn(1, std::get<1>(r));
cols.addUInt64Column(2, std::get<2>(r));
cols.addUInt64Column(3, std::get<3>(r));
cols.addFloatColumn(4, std::get<4>(r));
cols.addFloatColumn(5, std::get<5>(r));
cols.addFloatColumn(6, std::get<6>(r));
cols.addFloatColumn(7, std::get<7>(r));
sstable_writer->appendRow(std::get<0>(r), cols);
}
sstable_schema.writeIndex(sstable_writer.get());
sstable_writer->finalize();
}
/* aggregate ctr counters (flat) */
void aggregateCounters(CounterMap* counters, Vector<OutputRow>* rows) {
const auto& global_counter_iter = counters->find("__GLOBAL");
if (global_counter_iter == counters->end()) {
fnord::logCritical("cm.ctrstatsexport", "missing global counter");
exit(1);
}
const auto& global_counter = global_counter_iter->second;
for (const auto& row : *counters) {
const auto& ctr = row.second;
auto sep = row.first.find("~");
if (sep == std::string::npos) {
continue;
}
auto dim1 = row.first.substr(0, sep);
auto dim2 = row.first.substr(sep + 1);
if (dim1.length() == 0 || dim2.length() == 0) {
continue;
}
const auto& group_counter_iter = counters->find(dim1);
if (group_counter_iter == counters->end()) {
fnord::logWarning("cm.ctrstatsexport", "missing row: $0", dim1);
continue;
}
const auto& group_counter = group_counter_iter->second;
double p_base = ctr.num_views / (double) global_counter.num_views;
double p_base_dim2 = ctr.num_views / (double) group_counter.num_views;
double p_click = ctr.num_clicks / (double) ctr.num_views;
double p_click_n = ctr.num_clicks / (double) group_counter.num_clicks;
rows->emplace_back(
dim1,
dim2,
row.second.num_views,
row.second.num_clicks,
p_base,
p_base_dim2,
p_click,
p_click_n);
}
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"output_file",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"output file path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* read input tables */
HashMap<String, cm::CTRCounter> counters;
importInputTables(flags.getArgv(), &counters);
/* aggregate counters */
Vector<OutputRow> rows;
aggregateCounters(&counters, &rows);
/* write output table */
writeOutputTable(flags.getString("output_file"), rows);
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef ITER_SORTED_HPP_
#define ITER_SORTED_HPP_
#include "internal/iterbase.hpp"
#include "internal/iteratoriterator.hpp"
#include <iterator>
#include <algorithm>
#include <vector>
namespace iter {
namespace impl {
template <typename Container>
class SortedView;
}
template <typename Container, typename CompareFunc>
impl::SortedView<Container> sorted(Container&&, CompareFunc);
}
template <typename Container>
class iter::impl::SortedView {
private:
using IterIterWrap = IterIterWrapper<std::vector<iterator_type<Container>>>;
using ItIt = iterator_type<IterIterWrap>;
template <typename C, typename F>
friend SortedView<C> iter::sorted(C&&, F);
Container container;
IterIterWrap sorted_iters;
template <typename CompareFunc>
SortedView(Container&& in_container, CompareFunc compare_func)
: container(std::forward<Container>(in_container)) {
// Fill the sorted_iters vector with an iterator to each
// element in the container
for (auto iter = std::begin(this->container);
iter != std::end(this->container); ++iter) {
this->sorted_iters.get().push_back(iter);
}
// sort by comparing the elements that the iterators point to
std::sort(std::begin(sorted_iters.get()), std::end(sorted_iters.get()),
[compare_func](const iterator_type<Container>& it1,
const iterator_type<Container>& it2) {
return compare_func(*it1, *it2);
});
}
public:
ItIt begin() {
return std::begin(sorted_iters);
}
ItIt end() {
return std::end(sorted_iters);
}
};
template <typename Container, typename CompareFunc>
iter::impl::SortedView<Container> iter::sorted(
Container&& container, CompareFunc compare_func) {
return {std::forward<Container>(container), compare_func};
}
namespace iter {
template <typename Container>
auto sorted(Container&& container)
-> decltype(sorted(std::forward<Container>(container),
std::less<impl::const_iterator_deref<Container>>())) {
return sorted(std::forward<Container>(container),
std::less<impl::const_iterator_deref<Container>>());
}
}
#endif
<commit_msg>makes sorted impl class move-only<commit_after>#ifndef ITER_SORTED_HPP_
#define ITER_SORTED_HPP_
#include "internal/iterbase.hpp"
#include "internal/iteratoriterator.hpp"
#include <iterator>
#include <algorithm>
#include <vector>
namespace iter {
namespace impl {
template <typename Container>
class SortedView;
}
template <typename Container, typename CompareFunc>
impl::SortedView<Container> sorted(Container&&, CompareFunc);
}
template <typename Container>
class iter::impl::SortedView {
private:
using IterIterWrap = IterIterWrapper<std::vector<iterator_type<Container>>>;
using ItIt = iterator_type<IterIterWrap>;
template <typename C, typename F>
friend SortedView<C> iter::sorted(C&&, F);
Container container;
IterIterWrap sorted_iters;
template <typename CompareFunc>
SortedView(Container&& in_container, CompareFunc compare_func)
: container(std::forward<Container>(in_container)) {
// Fill the sorted_iters vector with an iterator to each
// element in the container
for (auto iter = std::begin(this->container);
iter != std::end(this->container); ++iter) {
this->sorted_iters.get().push_back(iter);
}
// sort by comparing the elements that the iterators point to
std::sort(std::begin(sorted_iters.get()), std::end(sorted_iters.get()),
[compare_func](const iterator_type<Container>& it1,
const iterator_type<Container>& it2) {
return compare_func(*it1, *it2);
});
}
public:
SortedView(SortedView&&) = default;
ItIt begin() {
return std::begin(sorted_iters);
}
ItIt end() {
return std::end(sorted_iters);
}
};
template <typename Container, typename CompareFunc>
iter::impl::SortedView<Container> iter::sorted(
Container&& container, CompareFunc compare_func) {
return {std::forward<Container>(container), compare_func};
}
namespace iter {
template <typename Container>
auto sorted(Container&& container)
-> decltype(sorted(std::forward<Container>(container),
std::less<impl::const_iterator_deref<Container>>())) {
return sorted(std::forward<Container>(container),
std::less<impl::const_iterator_deref<Container>>());
}
}
#endif
<|endoftext|>
|
<commit_before>#include <vector>
#include "quicksort.h"
namespace quicksort
{
template <class T> int getMedianIndex( std::vector<T> &items, int firstIndex, int secondIndex, int thirdIndex )
{//Returns the index of the median value of the values at the three indexes or thirdIndex.
if( (items[firstIndex] <= items[secondIndex]) && (items[firstIndex] >= items[thirdIndex]) )
{//The object at firstIndex is a median of the three because it's less than or equal to the object at secondIndex and greater than or equal to the object at thirdIndex. Since it counts as a median, return it.
return firstIndex;
}
else if( (items[firstIndex] >= items[secondIndex]) && (items[firstIndex] <= items[thirdIndex]) )
{//The object at firstIndex is a median of the three because it's greater than or equal to the object at secondIndex and less than or equal to the object at thirdIndex. Since it counts as a median, return it.
return firstIndex;
}
else if( (items[secondIndex] <= items[firstIndex]) && (items[secondIndex] >= items[thirdIndex]) )
{//The object at secondIndex is a median of the three because it's less than or equal to the object at firstIndex and greater than or equal to the object at thirdIndex. Since it counts as a median, return it.
return secondIndex;
}
else if( (items[secondIndex] >= items[firstIndex]) && (items[secondIndex] <= items[thirdIndex]) )
{//The object at secondIndex is a median of the three because it's greater than or equal to the object at firstIndex and less than or equal to the object at thirdIndex. Since it counts as a median, return it.
return secondIndex;
}
else
{//thirdIndex is probably the median if execution is here, but even if it's not the method needs to return something so might as well be thirdIndex.
return thirdIndex;
}
}
template <class T> void swap( std::vector<T> &items, int firstIndex, int secondIndex )
{//Swap items at first and second index.
T tempVal = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = tempVal;
}
template <class T> int partition( std::vector<T> &items, int leftIndex, int rightIndex, int pivotIndex )
{//Sort from left to right around pivot.
int newIndex = leftIndex;
T pivVal = items[pivotIndex];
swap(items, pivotIndex, rightIndex );
for( int i = leftIndex; i < rightIndex; i++ )
{
if( items[i] < pivVal )
{//If the element at index i is less than the pivot value, it should be before the pivot, so switch it.
swap( items, i, newIndex );
newIndex++;
}
}
//Move pivot from location right to the location it should end up.
swap( items, newIndex, rightIndex );
return newIndex;
}
template <class T> void quicksort( std::vector<T> &items, int left, int right )
{//Main quicksort function. Call this to sort a list of items.
int pivotPoint, newPivotPoint;
if( left < right )
{//If the list has at least 2 more items, keep running quicksort.
pivotPoint = getMedianIndex( items, left, (left+right)/2, right );//Get the median of the left, middle and right.
newPivotPoint = partition( items, left, right, pivotPoint );
quicksort( items, left, newPivotPoint - 1 );
quicksort( items, newPivotPoint + 1, right );
}
}
}
<commit_msg>Changed the name of the function quicksort to quickSort.<commit_after>#include <vector>
#include "quicksort.h"
namespace quicksort
{
template <class T> int getMedianIndex( std::vector<T> &items, int firstIndex, int secondIndex, int thirdIndex )
{//Returns the index of the median value of the values at the three indexes or thirdIndex.
if( (items[firstIndex] <= items[secondIndex]) && (items[firstIndex] >= items[thirdIndex]) )
{//The object at firstIndex is a median of the three because it's less than or equal to the object at secondIndex and greater than or equal to the object at thirdIndex. Since it counts as a median, return it.
return firstIndex;
}
else if( (items[firstIndex] >= items[secondIndex]) && (items[firstIndex] <= items[thirdIndex]) )
{//The object at firstIndex is a median of the three because it's greater than or equal to the object at secondIndex and less than or equal to the object at thirdIndex. Since it counts as a median, return it.
return firstIndex;
}
else if( (items[secondIndex] <= items[firstIndex]) && (items[secondIndex] >= items[thirdIndex]) )
{//The object at secondIndex is a median of the three because it's less than or equal to the object at firstIndex and greater than or equal to the object at thirdIndex. Since it counts as a median, return it.
return secondIndex;
}
else if( (items[secondIndex] >= items[firstIndex]) && (items[secondIndex] <= items[thirdIndex]) )
{//The object at secondIndex is a median of the three because it's greater than or equal to the object at firstIndex and less than or equal to the object at thirdIndex. Since it counts as a median, return it.
return secondIndex;
}
else
{//thirdIndex is probably the median if execution is here, but even if it's not the method needs to return something so might as well be thirdIndex.
return thirdIndex;
}
}
template <class T> void swap( std::vector<T> &items, int firstIndex, int secondIndex )
{//Swap items at first and second index.
T tempVal = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = tempVal;
}
template <class T> int partition( std::vector<T> &items, int leftIndex, int rightIndex, int pivotIndex )
{//Sort from left to right around pivot.
int newIndex = leftIndex;
T pivVal = items[pivotIndex];
swap(items, pivotIndex, rightIndex );
for( int i = leftIndex; i < rightIndex; i++ )
{
if( items[i] < pivVal )
{//If the element at index i is less than the pivot value, it should be before the pivot, so switch it.
swap( items, i, newIndex );
newIndex++;
}
}
//Move pivot from location right to the location it should end up.
swap( items, newIndex, rightIndex );
return newIndex;
}
template <class T> void quickSort( std::vector<T> &items, int left, int right )
{//Main quicksort function. Call this to sort a list of items.
int pivotPoint, newPivotPoint;
if( left < right )
{//If the list has at least 2 more items, keep running quicksort.
pivotPoint = getMedianIndex( items, left, (left+right)/2, right );//Get the median of the left, middle and right.
newPivotPoint = partition( items, left, right, pivotPoint );
quicksort( items, left, newPivotPoint - 1 );
quicksort( items, newPivotPoint + 1, right );
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "quic/tools/quic_client_epoll_network_helper.h"
#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>
#include "quic/core/crypto/quic_random.h"
#include "quic/core/http/spdy_utils.h"
#include "quic/core/quic_connection.h"
#include "quic/core/quic_data_reader.h"
#include "quic/core/quic_epoll_alarm_factory.h"
#include "quic/core/quic_epoll_connection_helper.h"
#include "quic/core/quic_packets.h"
#include "quic/core/quic_server_id.h"
#include "quic/core/quic_udp_socket.h"
#include "quic/platform/api/quic_bug_tracker.h"
#include "quic/platform/api/quic_logging.h"
#include "quic/platform/api/quic_system_event_loop.h"
namespace quic {
namespace {
const int kEpollFlags = EPOLLIN | EPOLLOUT | EPOLLET;
} // namespace
QuicClientEpollNetworkHelper::QuicClientEpollNetworkHelper(
QuicEpollServer* epoll_server,
QuicClientBase* client)
: epoll_server_(epoll_server),
packets_dropped_(0),
overflow_supported_(false),
packet_reader_(new QuicPacketReader()),
client_(client),
max_reads_per_epoll_loop_(std::numeric_limits<int>::max()) {}
QuicClientEpollNetworkHelper::~QuicClientEpollNetworkHelper() {
if (client_->connected()) {
client_->session()->connection()->CloseConnection(
QUIC_PEER_GOING_AWAY, "Client being torn down",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
CleanUpAllUDPSockets();
}
std::string QuicClientEpollNetworkHelper::Name() const {
return "QuicClientEpollNetworkHelper";
}
bool QuicClientEpollNetworkHelper::CreateUDPSocketAndBind(
QuicSocketAddress server_address,
QuicIpAddress bind_to_address,
int bind_to_port) {
epoll_server_->set_timeout_in_us(50 * 1000);
int fd = CreateUDPSocket(server_address, &overflow_supported_);
if (fd < 0) {
return false;
}
QuicSocketAddress client_address;
if (bind_to_address.IsInitialized()) {
client_address = QuicSocketAddress(bind_to_address, client_->local_port());
} else if (server_address.host().address_family() == IpAddressFamily::IP_V4) {
client_address = QuicSocketAddress(QuicIpAddress::Any4(), bind_to_port);
} else {
client_address = QuicSocketAddress(QuicIpAddress::Any6(), bind_to_port);
}
sockaddr_storage addr = client_address.generic_address();
int rc = bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
if (rc < 0) {
QUIC_LOG(ERROR) << "Bind failed: " << strerror(errno)
<< " bind_to_address:" << bind_to_address
<< ", bind_to_port:" << bind_to_port
<< ", client_address:" << client_address;
return false;
}
if (client_address.FromSocket(fd) != 0) {
QUIC_LOG(ERROR) << "Unable to get self address. Error: "
<< strerror(errno);
}
fd_address_map_[fd] = client_address;
epoll_server_->RegisterFD(fd, this, kEpollFlags);
return true;
}
void QuicClientEpollNetworkHelper::CleanUpUDPSocket(int fd) {
CleanUpUDPSocketImpl(fd);
fd_address_map_.erase(fd);
}
void QuicClientEpollNetworkHelper::CleanUpAllUDPSockets() {
for (std::pair<int, QuicSocketAddress> fd_address : fd_address_map_) {
CleanUpUDPSocketImpl(fd_address.first);
}
fd_address_map_.clear();
}
void QuicClientEpollNetworkHelper::CleanUpUDPSocketImpl(int fd) {
if (fd > -1) {
epoll_server_->UnregisterFD(fd);
int rc = close(fd);
QUICHE_DCHECK_EQ(0, rc);
}
}
void QuicClientEpollNetworkHelper::RunEventLoop() {
QuicRunSystemEventLoopIteration();
epoll_server_->WaitForEventsAndExecuteCallbacks();
}
void QuicClientEpollNetworkHelper::OnRegistration(QuicEpollServer* /*eps*/,
int /*fd*/,
int /*event_mask*/) {}
void QuicClientEpollNetworkHelper::OnModification(int /*fd*/,
int /*event_mask*/) {}
void QuicClientEpollNetworkHelper::OnUnregistration(int /*fd*/,
bool /*replaced*/) {}
void QuicClientEpollNetworkHelper::OnShutdown(QuicEpollServer* /*eps*/,
int /*fd*/) {}
void QuicClientEpollNetworkHelper::OnEvent(int fd, QuicEpollEvent* event) {
if (event->in_events & EPOLLIN) {
QUIC_DVLOG(1) << "Read packets on EPOLLIN";
int times_to_read = max_reads_per_epoll_loop_;
bool more_to_read = true;
QuicPacketCount packets_dropped = 0;
while (client_->connected() && more_to_read && times_to_read > 0) {
more_to_read = packet_reader_->ReadAndDispatchPackets(
fd, GetLatestClientAddress().port(), *client_->helper()->GetClock(),
this, overflow_supported_ ? &packets_dropped : nullptr);
--times_to_read;
}
if (packets_dropped_ < packets_dropped) {
QUIC_LOG(ERROR)
<< packets_dropped - packets_dropped_
<< " more packets are dropped in the socket receive buffer.";
packets_dropped_ = packets_dropped;
}
if (client_->connected() && more_to_read) {
event->out_ready_mask |= EPOLLIN;
}
}
if (client_->connected() && (event->in_events & EPOLLOUT)) {
client_->writer()->SetWritable();
client_->session()->connection()->OnCanWrite();
}
if (event->in_events & EPOLLERR) {
QUIC_DLOG(INFO) << "Epollerr";
}
}
QuicPacketWriter* QuicClientEpollNetworkHelper::CreateQuicPacketWriter() {
return new QuicDefaultPacketWriter(GetLatestFD());
}
void QuicClientEpollNetworkHelper::SetClientPort(int port) {
fd_address_map_.back().second =
QuicSocketAddress(GetLatestClientAddress().host(), port);
}
QuicSocketAddress QuicClientEpollNetworkHelper::GetLatestClientAddress() const {
if (fd_address_map_.empty()) {
return QuicSocketAddress();
}
return fd_address_map_.back().second;
}
int QuicClientEpollNetworkHelper::GetLatestFD() const {
if (fd_address_map_.empty()) {
return -1;
}
return fd_address_map_.back().first;
}
void QuicClientEpollNetworkHelper::ProcessPacket(
const QuicSocketAddress& self_address,
const QuicSocketAddress& peer_address,
const QuicReceivedPacket& packet) {
client_->session()->ProcessUdpPacket(self_address, peer_address, packet);
}
int QuicClientEpollNetworkHelper::CreateUDPSocket(
QuicSocketAddress server_address,
bool* overflow_supported) {
QuicUdpSocketApi api;
int fd = api.Create(server_address.host().AddressFamilyToInt(),
/*receive_buffer_size =*/kDefaultSocketReceiveBuffer,
/*send_buffer_size =*/kDefaultSocketReceiveBuffer);
if (fd < 0) {
return fd;
}
*overflow_supported = api.EnableDroppedPacketCount(fd);
api.EnableReceiveTimestamp(fd);
return fd;
}
} // namespace quic
<commit_msg>When binding a quic client's socket, set the addrlen to the exact length of the sockaddr struct being passed in.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "quic/tools/quic_client_epoll_network_helper.h"
#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>
#include "quic/core/crypto/quic_random.h"
#include "quic/core/http/spdy_utils.h"
#include "quic/core/quic_connection.h"
#include "quic/core/quic_data_reader.h"
#include "quic/core/quic_epoll_alarm_factory.h"
#include "quic/core/quic_epoll_connection_helper.h"
#include "quic/core/quic_packets.h"
#include "quic/core/quic_server_id.h"
#include "quic/core/quic_udp_socket.h"
#include "quic/platform/api/quic_bug_tracker.h"
#include "quic/platform/api/quic_logging.h"
#include "quic/platform/api/quic_system_event_loop.h"
namespace quic {
namespace {
const int kEpollFlags = EPOLLIN | EPOLLOUT | EPOLLET;
} // namespace
QuicClientEpollNetworkHelper::QuicClientEpollNetworkHelper(
QuicEpollServer* epoll_server,
QuicClientBase* client)
: epoll_server_(epoll_server),
packets_dropped_(0),
overflow_supported_(false),
packet_reader_(new QuicPacketReader()),
client_(client),
max_reads_per_epoll_loop_(std::numeric_limits<int>::max()) {}
QuicClientEpollNetworkHelper::~QuicClientEpollNetworkHelper() {
if (client_->connected()) {
client_->session()->connection()->CloseConnection(
QUIC_PEER_GOING_AWAY, "Client being torn down",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
CleanUpAllUDPSockets();
}
std::string QuicClientEpollNetworkHelper::Name() const {
return "QuicClientEpollNetworkHelper";
}
bool QuicClientEpollNetworkHelper::CreateUDPSocketAndBind(
QuicSocketAddress server_address,
QuicIpAddress bind_to_address,
int bind_to_port) {
epoll_server_->set_timeout_in_us(50 * 1000);
int fd = CreateUDPSocket(server_address, &overflow_supported_);
if (fd < 0) {
return false;
}
QuicSocketAddress client_address;
if (bind_to_address.IsInitialized()) {
client_address = QuicSocketAddress(bind_to_address, client_->local_port());
} else if (server_address.host().address_family() == IpAddressFamily::IP_V4) {
client_address = QuicSocketAddress(QuicIpAddress::Any4(), bind_to_port);
} else {
client_address = QuicSocketAddress(QuicIpAddress::Any6(), bind_to_port);
}
// Some platforms expect that the addrlen given to bind() exactly matches the
// size of the associated protocol family's sockaddr struct.
// TODO(b/179430548): Revert this when affected platforms are updated to
// to support binding with an addrelen of sizeof(sockaddr_storage)
socklen_t addrlen;
switch (client_address.host().address_family()) {
case IpAddressFamily::IP_V4:
addrlen = sizeof(sockaddr_in);
break;
case IpAddressFamily::IP_V6:
addrlen = sizeof(sockaddr_in6);
break;
case IpAddressFamily::IP_UNSPEC:
addrlen = 0;
break;
}
sockaddr_storage addr = client_address.generic_address();
int rc = bind(fd, reinterpret_cast<sockaddr*>(&addr), addrlen);
if (rc < 0) {
QUIC_LOG(ERROR) << "Bind failed: " << strerror(errno)
<< " bind_to_address:" << bind_to_address
<< ", bind_to_port:" << bind_to_port
<< ", client_address:" << client_address;
return false;
}
if (client_address.FromSocket(fd) != 0) {
QUIC_LOG(ERROR) << "Unable to get self address. Error: "
<< strerror(errno);
}
fd_address_map_[fd] = client_address;
epoll_server_->RegisterFD(fd, this, kEpollFlags);
return true;
}
void QuicClientEpollNetworkHelper::CleanUpUDPSocket(int fd) {
CleanUpUDPSocketImpl(fd);
fd_address_map_.erase(fd);
}
void QuicClientEpollNetworkHelper::CleanUpAllUDPSockets() {
for (std::pair<int, QuicSocketAddress> fd_address : fd_address_map_) {
CleanUpUDPSocketImpl(fd_address.first);
}
fd_address_map_.clear();
}
void QuicClientEpollNetworkHelper::CleanUpUDPSocketImpl(int fd) {
if (fd > -1) {
epoll_server_->UnregisterFD(fd);
int rc = close(fd);
QUICHE_DCHECK_EQ(0, rc);
}
}
void QuicClientEpollNetworkHelper::RunEventLoop() {
QuicRunSystemEventLoopIteration();
epoll_server_->WaitForEventsAndExecuteCallbacks();
}
void QuicClientEpollNetworkHelper::OnRegistration(QuicEpollServer* /*eps*/,
int /*fd*/,
int /*event_mask*/) {}
void QuicClientEpollNetworkHelper::OnModification(int /*fd*/,
int /*event_mask*/) {}
void QuicClientEpollNetworkHelper::OnUnregistration(int /*fd*/,
bool /*replaced*/) {}
void QuicClientEpollNetworkHelper::OnShutdown(QuicEpollServer* /*eps*/,
int /*fd*/) {}
void QuicClientEpollNetworkHelper::OnEvent(int fd, QuicEpollEvent* event) {
if (event->in_events & EPOLLIN) {
QUIC_DVLOG(1) << "Read packets on EPOLLIN";
int times_to_read = max_reads_per_epoll_loop_;
bool more_to_read = true;
QuicPacketCount packets_dropped = 0;
while (client_->connected() && more_to_read && times_to_read > 0) {
more_to_read = packet_reader_->ReadAndDispatchPackets(
fd, GetLatestClientAddress().port(), *client_->helper()->GetClock(),
this, overflow_supported_ ? &packets_dropped : nullptr);
--times_to_read;
}
if (packets_dropped_ < packets_dropped) {
QUIC_LOG(ERROR)
<< packets_dropped - packets_dropped_
<< " more packets are dropped in the socket receive buffer.";
packets_dropped_ = packets_dropped;
}
if (client_->connected() && more_to_read) {
event->out_ready_mask |= EPOLLIN;
}
}
if (client_->connected() && (event->in_events & EPOLLOUT)) {
client_->writer()->SetWritable();
client_->session()->connection()->OnCanWrite();
}
if (event->in_events & EPOLLERR) {
QUIC_DLOG(INFO) << "Epollerr";
}
}
QuicPacketWriter* QuicClientEpollNetworkHelper::CreateQuicPacketWriter() {
return new QuicDefaultPacketWriter(GetLatestFD());
}
void QuicClientEpollNetworkHelper::SetClientPort(int port) {
fd_address_map_.back().second =
QuicSocketAddress(GetLatestClientAddress().host(), port);
}
QuicSocketAddress QuicClientEpollNetworkHelper::GetLatestClientAddress() const {
if (fd_address_map_.empty()) {
return QuicSocketAddress();
}
return fd_address_map_.back().second;
}
int QuicClientEpollNetworkHelper::GetLatestFD() const {
if (fd_address_map_.empty()) {
return -1;
}
return fd_address_map_.back().first;
}
void QuicClientEpollNetworkHelper::ProcessPacket(
const QuicSocketAddress& self_address,
const QuicSocketAddress& peer_address,
const QuicReceivedPacket& packet) {
client_->session()->ProcessUdpPacket(self_address, peer_address, packet);
}
int QuicClientEpollNetworkHelper::CreateUDPSocket(
QuicSocketAddress server_address,
bool* overflow_supported) {
QuicUdpSocketApi api;
int fd = api.Create(server_address.host().AddressFamilyToInt(),
/*receive_buffer_size =*/kDefaultSocketReceiveBuffer,
/*send_buffer_size =*/kDefaultSocketReceiveBuffer);
if (fd < 0) {
return fd;
}
*overflow_supported = api.EnableDroppedPacketCount(fd);
api.EnableReceiveTimestamp(fd);
return fd;
}
} // namespace quic
<|endoftext|>
|
<commit_before>#include "rapid_perception/icp_fitness_functions.h"
#include <cmath>
#include <vector>
#include "Eigen/Core"
#include "Eigen/Geometry"
#include "pcl/filters/crop_box.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl/search/kdtree.h"
#include "rapid_msgs/Roi3D.h"
typedef pcl::PointXYZRGB PointC;
typedef pcl::PointCloud<PointC> PointCloudC;
typedef pcl::search::KdTree<PointC> PointCTree;
using std::vector;
namespace rapid {
namespace perception {
double ComputeIcpFitness(PointCloudC::Ptr& scene, PointCloudC::Ptr& object,
const rapid_msgs::Roi3D& roi) {
Eigen::Vector4f min;
min.x() = -roi.dimensions.x / 2;
min.y() = -roi.dimensions.y / 2;
min.z() = -roi.dimensions.z / 2;
Eigen::Vector4f max;
max.x() = roi.dimensions.x / 2;
max.y() = roi.dimensions.y / 2;
max.z() = roi.dimensions.z / 2;
Eigen::Vector3f translation;
translation.x() = roi.transform.translation.x;
translation.y() = roi.transform.translation.y;
translation.z() = roi.transform.translation.z;
Eigen::Quaternionf rotation;
rotation.w() = roi.transform.rotation.w;
rotation.x() = roi.transform.rotation.x;
rotation.y() = roi.transform.rotation.y;
rotation.z() = roi.transform.rotation.z;
Eigen::Matrix3f rot_mat = rotation.toRotationMatrix();
Eigen::Vector3f ea;
ea.x() = atan2(rot_mat(2, 1), rot_mat(1, 1));
ea.y() = atan2(rot_mat(2, 0), rot_mat(0, 0));
ea.z() = atan2(rot_mat(1, 0), rot_mat(0, 0));
pcl::CropBox<PointC> crop;
crop.setInputCloud(scene);
crop.setMin(min);
crop.setMax(max);
crop.setTranslation(translation);
crop.setRotation(ea);
vector<int> indices;
crop.filter(indices);
// if (debug_) {
// std::cout << "Press enter to view cropped area" << std::endl;
// string input;
// std::getline(std::cin, input);
// PointCloudC::Ptr cropped(new PointCloudC);
// crop.filter(*cropped);
// viz::PublishCloud(alignment_pub_, *cropped);
// std::cout << "Press enter to finish viewing cropped area" << std::endl;
// std::getline(std::cin, input);
//}
PointCTree object_tree;
object_tree.setInputCloud(object);
vector<int> nn_indices(1);
vector<float> nn_dists(1);
double fitness = 0;
for (size_t index_i = 0; index_i < indices.size(); ++index_i) {
int index = indices[index_i];
const PointC& scene_pt = scene->at(index);
object_tree.nearestKSearch(scene_pt, 1, nn_indices, nn_dists);
fitness += nn_dists[0];
}
fitness /= indices.size();
return fitness;
}
} // namespace perception
} // namespace rapid
<commit_msg>Get average error distance instead of squared distance.<commit_after>#include "rapid_perception/icp_fitness_functions.h"
#include <cmath>
#include <vector>
#include "Eigen/Core"
#include "Eigen/Geometry"
#include "pcl/filters/crop_box.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl/search/kdtree.h"
#include "rapid_msgs/Roi3D.h"
typedef pcl::PointXYZRGB PointC;
typedef pcl::PointCloud<PointC> PointCloudC;
typedef pcl::search::KdTree<PointC> PointCTree;
using std::vector;
namespace rapid {
namespace perception {
double ComputeIcpFitness(PointCloudC::Ptr& scene, PointCloudC::Ptr& object,
const rapid_msgs::Roi3D& roi) {
Eigen::Vector4f min;
min.x() = -roi.dimensions.x / 2;
min.y() = -roi.dimensions.y / 2;
min.z() = -roi.dimensions.z / 2;
Eigen::Vector4f max;
max.x() = roi.dimensions.x / 2;
max.y() = roi.dimensions.y / 2;
max.z() = roi.dimensions.z / 2;
Eigen::Vector3f translation;
translation.x() = roi.transform.translation.x;
translation.y() = roi.transform.translation.y;
translation.z() = roi.transform.translation.z;
Eigen::Quaternionf rotation;
rotation.w() = roi.transform.rotation.w;
rotation.x() = roi.transform.rotation.x;
rotation.y() = roi.transform.rotation.y;
rotation.z() = roi.transform.rotation.z;
Eigen::Matrix3f rot_mat = rotation.toRotationMatrix();
Eigen::Vector3f ea;
ea.x() = atan2(rot_mat(2, 1), rot_mat(1, 1));
ea.y() = atan2(rot_mat(2, 0), rot_mat(0, 0));
ea.z() = atan2(rot_mat(1, 0), rot_mat(0, 0));
pcl::CropBox<PointC> crop;
crop.setInputCloud(scene);
crop.setMin(min);
crop.setMax(max);
crop.setTranslation(translation);
crop.setRotation(ea);
vector<int> indices;
crop.filter(indices);
// if (debug_) {
// std::cout << "Press enter to view cropped area" << std::endl;
// string input;
// std::getline(std::cin, input);
// PointCloudC::Ptr cropped(new PointCloudC);
// crop.filter(*cropped);
// viz::PublishCloud(alignment_pub_, *cropped);
// std::cout << "Press enter to finish viewing cropped area" << std::endl;
// std::getline(std::cin, input);
//}
PointCTree object_tree;
object_tree.setInputCloud(object);
vector<int> nn_indices(1);
vector<float> nn_dists(1);
double fitness = 0;
for (size_t index_i = 0; index_i < indices.size(); ++index_i) {
int index = indices[index_i];
const PointC& scene_pt = scene->at(index);
object_tree.nearestKSearch(scene_pt, 1, nn_indices, nn_dists);
fitness += sqrt(nn_dists[0]);
}
fitness /= indices.size();
return fitness;
}
} // namespace perception
} // namespace rapid
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_GLOBAL_FORCE_FIELD
#define MJOLNIR_GLOBAL_FORCE_FIELD
#include "GlobalInteractionBase.hpp"
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <array>
#include <memory>
namespace mjolnir
{
template<typename traitsT>
class GlobalForceField
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef typename traits_type::boundary_type boundary_type;
typedef typename system_type::particle_type particle_type;
typedef GlobalInteractionBase<traitsT> interaction_base;
typedef std::unique_ptr<interaction_base> interaction_ptr;
public:
GlobalForceField() = default;
~GlobalForceField() = default;
GlobalForceField(const GlobalForceField&) = delete;
GlobalForceField(GlobalForceField&&) = default;
GlobalForceField& operator=(const GlobalForceField&) = delete;
GlobalForceField& operator=(GlobalForceField&&) = default;
void emplace(interaction_ptr&& inter)
{
interactions_.emplace_back(std::move(inter));
}
void initialize(const system_type& sys, const real_type dt)
{
for(auto& item : this->interactions_)
item->initialize(sys, dt);
}
void calc_force(system_type& sys)
{
for(const auto& item : this->interactions_)
item->calc_force(sys);
return;
}
real_type calc_energy(const system_type& sys) const
{
real_type energy = 0.;
for(const auto& item : this->interactions_)
energy += item->calc_energy(sys);
return energy;
}
private:
std::vector<interaction_ptr> interactions_;
static
Logger& logger_;
};
template<typename traitsT>
Logger& GlobalForceField<traitsT>::logger_ =
LoggerManager<char>::get_logger("GlobalForceField");
} // mjolnir
#endif /* MJOLNIR_GLOBAL_FORCE_FIELD */
<commit_msg>add dump energy (for debug) to globalforcefield<commit_after>#ifndef MJOLNIR_GLOBAL_FORCE_FIELD
#define MJOLNIR_GLOBAL_FORCE_FIELD
#include "GlobalInteractionBase.hpp"
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <array>
#include <memory>
namespace mjolnir
{
template<typename traitsT>
class GlobalForceField
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef typename traits_type::boundary_type boundary_type;
typedef typename system_type::particle_type particle_type;
typedef GlobalInteractionBase<traitsT> interaction_base;
typedef std::unique_ptr<interaction_base> interaction_ptr;
public:
GlobalForceField() = default;
~GlobalForceField() = default;
GlobalForceField(const GlobalForceField&) = delete;
GlobalForceField(GlobalForceField&&) = default;
GlobalForceField& operator=(const GlobalForceField&) = delete;
GlobalForceField& operator=(GlobalForceField&&) = default;
void emplace(interaction_ptr&& inter)
{
interactions_.emplace_back(std::move(inter));
}
void initialize(const system_type& sys, const real_type dt)
{
for(auto& item : this->interactions_)
item->initialize(sys, dt);
}
void calc_force(system_type& sys)
{
for(const auto& item : this->interactions_)
item->calc_force(sys);
return;
}
real_type calc_energy(const system_type& sys) const
{
real_type energy = 0.;
for(const auto& item : this->interactions_)
energy += item->calc_energy(sys);
return energy;
}
// TODO simplify
std::string list_energy() const
{
std::string retval;
for(const auto& i : interactions_)
{
retval += i->name();
retval += ' ';
}
return retval;
}
std::string dump_energy(const system_type& sys) const
{
std::string retval;
for(const auto& i : interactions_)
{
retval += std::to_string(i->calc_energy(sys));
retval += ' ';
}
return retval;
}
private:
std::vector<interaction_ptr> interactions_;
static
Logger& logger_;
};
template<typename traitsT>
Logger& GlobalForceField<traitsT>::logger_ =
LoggerManager<char>::get_logger("GlobalForceField");
} // mjolnir
#endif /* MJOLNIR_GLOBAL_FORCE_FIELD */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gen_info.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:23:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <gen_info.hxx>
#include <gi_list.hxx>
GenericInfo::GenericInfo( const Simstr & i_sKey,
const Simstr & i_sValue,
const Simstr & i_sComment )
: sKey(i_sKey),
sValue(i_sValue),
sComment(i_sComment),
dpSubList(0)
{
}
GenericInfo::GenericInfo( const GenericInfo & i_rInfo )
: sKey(i_rInfo.sKey),
sValue(i_rInfo.sValue),
sComment(i_rInfo.sComment),
dpSubList(0)
{
if ( i_rInfo.HasSubList() )
{
dpSubList = new List_GenericInfo(i_rInfo.SubList());
}
}
GenericInfo::~GenericInfo()
{
if ( dpSubList != 0 )
delete dpSubList;
}
GenericInfo &
GenericInfo::operator=( const GenericInfo & i_rInfo )
{
sKey = i_rInfo.sKey;
sValue = i_rInfo.sValue;
sComment = i_rInfo.sComment;
if ( dpSubList != 0 )
delete dpSubList;
if ( i_rInfo.HasSubList() )
{
dpSubList = new List_GenericInfo(i_rInfo.SubList());
}
else
dpSubList = 0;
return *this;
}
List_GenericInfo &
GenericInfo::CreateMyList() const
{
return * ( const_cast<GenericInfo&>(*this).dpSubList = new List_GenericInfo);
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.2.30); FILE MERGED 2006/09/01 17:40:15 kaib 1.2.30.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gen_info.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:33:09 $
*
* 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_soltools.hxx"
#include <gen_info.hxx>
#include <gi_list.hxx>
GenericInfo::GenericInfo( const Simstr & i_sKey,
const Simstr & i_sValue,
const Simstr & i_sComment )
: sKey(i_sKey),
sValue(i_sValue),
sComment(i_sComment),
dpSubList(0)
{
}
GenericInfo::GenericInfo( const GenericInfo & i_rInfo )
: sKey(i_rInfo.sKey),
sValue(i_rInfo.sValue),
sComment(i_rInfo.sComment),
dpSubList(0)
{
if ( i_rInfo.HasSubList() )
{
dpSubList = new List_GenericInfo(i_rInfo.SubList());
}
}
GenericInfo::~GenericInfo()
{
if ( dpSubList != 0 )
delete dpSubList;
}
GenericInfo &
GenericInfo::operator=( const GenericInfo & i_rInfo )
{
sKey = i_rInfo.sKey;
sValue = i_rInfo.sValue;
sComment = i_rInfo.sComment;
if ( dpSubList != 0 )
delete dpSubList;
if ( i_rInfo.HasSubList() )
{
dpSubList = new List_GenericInfo(i_rInfo.SubList());
}
else
dpSubList = 0;
return *this;
}
List_GenericInfo &
GenericInfo::CreateMyList() const
{
return * ( const_cast<GenericInfo&>(*this).dpSubList = new List_GenericInfo);
}
<|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/.
*/
#include "stdafx.h"
#include "parser.h"
#include "utilities.h"
#include "Logs.h"
#include "scenenodegroups.h"
/*
MaSzyna EU07 locomotive simulator parser
Copyright (C) 2003 TOLARIS
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////
// cParser -- generic class for parsing text data.
// constructors
cParser::cParser( std::string const &Stream, buffertype const Type, std::string Path, bool const Loadtraction, std::vector<std::string> Parameters ) :
mPath(Path),
LoadTraction( Loadtraction ) {
// store to calculate sub-sequent includes from relative path
if( Type == buffertype::buffer_FILE ) {
mFile = Stream;
}
// reset pointers and attach proper type of buffer
switch (Type) {
case buffer_FILE: {
Path.append( Stream );
mStream = std::make_shared<std::ifstream>( Path, std::ios_base::binary );
// content of *.inc files is potentially grouped together
if( ( Stream.size() >= 4 )
&& ( ToLower( Stream.substr( Stream.size() - 4 ) ) == ".inc" ) ) {
mIncFile = true;
scene::Groups.create();
}
break;
}
case buffer_TEXT: {
mStream = std::make_shared<std::istringstream>( Stream );
break;
}
default: {
break;
}
}
// calculate stream size
if (mStream)
{
if( true == mStream->fail() ) {
ErrorLog( "Failed to open file \"" + Path + "\"" );
}
else {
mSize = mStream->rdbuf()->pubseekoff( 0, std::ios_base::end );
mStream->rdbuf()->pubseekoff( 0, std::ios_base::beg );
mLine = 1;
}
}
// set parameter set if one was provided
if( false == Parameters.empty() ) {
parameters.swap( Parameters );
}
}
// destructor
cParser::~cParser() {
if( true == mIncFile ) {
// wrap up the node group holding content of processed file
scene::Groups.close();
}
}
template <>
glm::vec3
cParser::getToken( bool const ToLower, char const *Break ) {
// NOTE: this specialization ignores default arguments
getTokens( 3, false, "\n\r\t ,;[]" );
glm::vec3 output;
*this
>> output.x
>> output.y
>> output.z;
return output;
};
template<>
cParser&
cParser::operator>>( std::string &Right ) {
if( true == this->tokens.empty() ) { return *this; }
Right = this->tokens.front();
this->tokens.pop_front();
return *this;
}
template<>
cParser&
cParser::operator>>( bool &Right ) {
if( true == this->tokens.empty() ) { return *this; }
Right = ( ( this->tokens.front() == "true" )
|| ( this->tokens.front() == "yes" )
|| ( this->tokens.front() == "1" ) );
this->tokens.pop_front();
return *this;
}
template <>
bool
cParser::getToken<bool>( bool const ToLower, const char *Break ) {
auto const token = getToken<std::string>( true, Break );
return ( ( token == "true" )
|| ( token == "yes" )
|| ( token == "1" ) );
}
// methods
cParser &
cParser::autoclear( bool const Autoclear ) {
m_autoclear = Autoclear;
if( mIncludeParser ) { mIncludeParser->autoclear( Autoclear ); }
return *this;
}
bool cParser::getTokens(unsigned int Count, bool ToLower, const char *Break)
{
if( true == m_autoclear ) {
// legacy parser behaviour
tokens.clear();
}
/*
if (LoadTraction==true)
trtest="niemaproblema"; //wczytywać
else
trtest="x"; //nie wczytywać
*/
/*
int i;
this->str("");
this->clear();
*/
for (unsigned int i = tokens.size(); i < Count; ++i)
{
std::string token = readToken(ToLower, Break);
if( true == token.empty() ) {
// no more tokens
break;
}
// collect parameters
tokens.emplace_back( token );
/*
if (i == 0)
this->str(token);
else
{
std::string temp = this->str();
temp.append("\n");
temp.append(token);
this->str(temp);
}
*/
}
if (tokens.size() < Count)
return false;
else
return true;
}
std::string cParser::readToken( bool ToLower, const char *Break ) {
std::string token;
if( mIncludeParser ) {
// see if there's include parsing going on. clean up when it's done.
token = mIncludeParser->readToken( ToLower, Break );
if( true == token.empty() ) {
mIncludeParser = nullptr;
}
}
if( true == token.empty() ) {
// get the token yourself if the delegation attempt failed
char c { 0 };
do {
while( mStream->peek() != EOF && strchr( Break, c = mStream->get() ) == NULL ) {
if( ToLower )
c = tolower( c );
token += c;
if( findQuotes( token ) ) // do glue together words enclosed in quotes
continue;
if( trimComments( token ) ) // don't glue together words separated with comment
break;
}
if( c == '\n' ) {
// update line counter
++mLine;
}
} while( token == "" && mStream->peek() != EOF ); // double check in case of consecutive separators
}
if( false == parameters.empty() ) {
// if there's parameter list, check the token for potential parameters to replace
size_t pos; // początek podmienianego ciągu
while( ( pos = token.find( "(p" ) ) != std::string::npos ) {
// check if the token is a parameter which should be replaced with stored true value
auto const parameter{ token.substr( pos + 2, token.find( ")", pos ) - ( pos + 2 ) ) }; // numer parametru
token.erase( pos, token.find( ")", pos ) - pos + 1 ); // najpierw usunięcie "(pN)"
size_t nr = atoi( parameter.c_str() ) - 1;
if( nr < parameters.size() ) {
token.insert( pos, parameters.at( nr ) ); // wklejenie wartości parametru
if( ToLower )
for( ; pos < parameters.at( nr ).size(); ++pos )
token[ pos ] = tolower( token[ pos ] );
}
else
token.insert( pos, "none" ); // zabezpieczenie przed brakiem parametru
}
}
if( expandIncludes && token == "include" ) {
// launch child parser if include directive found.
// NOTE: parameter collecting uses default set of token separators.
std::string includefile = readToken(ToLower); // nazwa pliku
std::replace(includefile.begin(), includefile.end(), '\\', '/');
if( ( true == LoadTraction )
|| ( ( includefile.find( "tr/" ) == std::string::npos )
&& ( includefile.find( "tra/" ) == std::string::npos ) ) ) {
// get parameter list for the child parser
std::vector<std::string> includeparameters;
std::string parameter = readToken( false ); // w parametrach nie zmniejszamy
while( ( parameter.empty() == false )
&& ( parameter != "end" ) ) {
includeparameters.emplace_back( parameter );
parameter = readToken( false );
}
mIncludeParser = std::make_shared<cParser>( includefile, buffer_FILE, mPath, LoadTraction, includeparameters );
mIncludeParser->autoclear( m_autoclear );
if( mIncludeParser->mSize <= 0 ) {
ErrorLog( "Bad include: can't open file \"" + includefile + "\"" );
}
}
else {
while( token != "end" ) {
token = readToken( true ); // minimize risk of case mismatch on comparison
}
}
token = readToken(ToLower, Break);
}
// all done
return token;
}
std::string cParser::readQuotes(char const Quote) { // read the stream until specified char or stream end
std::string token = "";
char c { 0 };
while( mStream->peek() != EOF && Quote != (c = mStream->get()) ) { // get all chars until the quote mark
if( c == '\n' ) {
// update line counter
++mLine;
}
token += c;
}
return token;
}
void cParser::skipComment( std::string const &Endmark ) { // pobieranie znaków aż do znalezienia znacznika końca
std::string input = "";
char c { 0 };
auto const endmarksize = Endmark.size();
while( mStream->peek() != EOF ) {
// o ile nie koniec pliku
c = mStream->get(); // pobranie znaku
if( c == '\n' ) {
// update line counter
++mLine;
}
input += c;
if( input.find( Endmark ) != std::string::npos ) // szukanie znacznika końca
break;
if( input.size() >= endmarksize ) {
// keep the read text short, to avoid pointless string re-allocations on longer comments
input = input.substr( 1 );
}
}
return;
}
bool cParser::findQuotes( std::string &String ) {
if( String.rfind( '\"' ) != std::string::npos ) {
String.erase( String.rfind( '\"' ), 1 );
String += readQuotes();
return true;
}
return false;
}
bool cParser::trimComments(std::string &String)
{
for (commentmap::iterator cmIt = mComments.begin(); cmIt != mComments.end(); ++cmIt)
{
if (String.rfind((*cmIt).first) != std::string::npos)
{
skipComment((*cmIt).second);
String.resize(String.rfind((*cmIt).first));
return true;
}
}
return false;
}
void cParser::injectString(const std::string &str)
{
if (mIncludeParser) {
mIncludeParser->injectString(str);
}
else {
mIncludeParser = std::make_shared<cParser>( str, buffer_TEXT, "", LoadTraction );
mIncludeParser->autoclear( m_autoclear );
}
}
int cParser::getProgress() const
{
return static_cast<int>( mStream->rdbuf()->pubseekoff(0, std::ios_base::cur) * 100 / mSize );
}
int cParser::getFullProgress() const {
int progress = getProgress();
if( mIncludeParser ) return progress + ( ( 100 - progress )*( mIncludeParser->getProgress() ) / 100 );
else return progress;
}
std::size_t cParser::countTokens( std::string const &Stream, std::string Path ) {
return cParser( Stream, buffer_FILE, Path ).count();
}
std::size_t cParser::count() {
std::string token;
size_t count { 0 };
do {
token = "";
token = readToken( false );
++count;
} while( false == token.empty() );
return count - 1;
}
void cParser::addCommentStyle( std::string const &Commentstart, std::string const &Commentend ) {
mComments.insert( commentmap::value_type(Commentstart, Commentend) );
}
// returns name of currently open file, or empty string for text type stream
std::string
cParser::Name() const {
if( mIncludeParser ) { return mIncludeParser->Name(); }
else { return mPath + mFile; }
}
// returns number of currently processed line
std::size_t
cParser::Line() const {
if( mIncludeParser ) { return mIncludeParser->Line(); }
else { return mLine; }
}
int cParser::LineMain() const {
return mIncludeParser ? -1 : mLine;
}
<commit_msg>support escape sequence \ in parser<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/.
*/
#include "stdafx.h"
#include "parser.h"
#include "utilities.h"
#include "Logs.h"
#include "scenenodegroups.h"
/*
MaSzyna EU07 locomotive simulator parser
Copyright (C) 2003 TOLARIS
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////
// cParser -- generic class for parsing text data.
// constructors
cParser::cParser( std::string const &Stream, buffertype const Type, std::string Path, bool const Loadtraction, std::vector<std::string> Parameters ) :
mPath(Path),
LoadTraction( Loadtraction ) {
// store to calculate sub-sequent includes from relative path
if( Type == buffertype::buffer_FILE ) {
mFile = Stream;
}
// reset pointers and attach proper type of buffer
switch (Type) {
case buffer_FILE: {
Path.append( Stream );
mStream = std::make_shared<std::ifstream>( Path, std::ios_base::binary );
// content of *.inc files is potentially grouped together
if( ( Stream.size() >= 4 )
&& ( ToLower( Stream.substr( Stream.size() - 4 ) ) == ".inc" ) ) {
mIncFile = true;
scene::Groups.create();
}
break;
}
case buffer_TEXT: {
mStream = std::make_shared<std::istringstream>( Stream );
break;
}
default: {
break;
}
}
// calculate stream size
if (mStream)
{
if( true == mStream->fail() ) {
ErrorLog( "Failed to open file \"" + Path + "\"" );
}
else {
mSize = mStream->rdbuf()->pubseekoff( 0, std::ios_base::end );
mStream->rdbuf()->pubseekoff( 0, std::ios_base::beg );
mLine = 1;
}
}
// set parameter set if one was provided
if( false == Parameters.empty() ) {
parameters.swap( Parameters );
}
}
// destructor
cParser::~cParser() {
if( true == mIncFile ) {
// wrap up the node group holding content of processed file
scene::Groups.close();
}
}
template <>
glm::vec3
cParser::getToken( bool const ToLower, char const *Break ) {
// NOTE: this specialization ignores default arguments
getTokens( 3, false, "\n\r\t ,;[]" );
glm::vec3 output;
*this
>> output.x
>> output.y
>> output.z;
return output;
};
template<>
cParser&
cParser::operator>>( std::string &Right ) {
if( true == this->tokens.empty() ) { return *this; }
Right = this->tokens.front();
this->tokens.pop_front();
return *this;
}
template<>
cParser&
cParser::operator>>( bool &Right ) {
if( true == this->tokens.empty() ) { return *this; }
Right = ( ( this->tokens.front() == "true" )
|| ( this->tokens.front() == "yes" )
|| ( this->tokens.front() == "1" ) );
this->tokens.pop_front();
return *this;
}
template <>
bool
cParser::getToken<bool>( bool const ToLower, const char *Break ) {
auto const token = getToken<std::string>( true, Break );
return ( ( token == "true" )
|| ( token == "yes" )
|| ( token == "1" ) );
}
// methods
cParser &
cParser::autoclear( bool const Autoclear ) {
m_autoclear = Autoclear;
if( mIncludeParser ) { mIncludeParser->autoclear( Autoclear ); }
return *this;
}
bool cParser::getTokens(unsigned int Count, bool ToLower, const char *Break)
{
if( true == m_autoclear ) {
// legacy parser behaviour
tokens.clear();
}
/*
if (LoadTraction==true)
trtest="niemaproblema"; //wczytywać
else
trtest="x"; //nie wczytywać
*/
/*
int i;
this->str("");
this->clear();
*/
for (unsigned int i = tokens.size(); i < Count; ++i)
{
std::string token = readToken(ToLower, Break);
if( true == token.empty() ) {
// no more tokens
break;
}
// collect parameters
tokens.emplace_back( token );
/*
if (i == 0)
this->str(token);
else
{
std::string temp = this->str();
temp.append("\n");
temp.append(token);
this->str(temp);
}
*/
}
if (tokens.size() < Count)
return false;
else
return true;
}
std::string cParser::readToken( bool ToLower, const char *Break ) {
std::string token;
if( mIncludeParser ) {
// see if there's include parsing going on. clean up when it's done.
token = mIncludeParser->readToken( ToLower, Break );
if( true == token.empty() ) {
mIncludeParser = nullptr;
}
}
if( true == token.empty() ) {
// get the token yourself if the delegation attempt failed
char c { 0 };
do {
while( mStream->peek() != EOF && strchr( Break, c = mStream->get() ) == NULL ) {
if( ToLower )
c = tolower( c );
token += c;
if( findQuotes( token ) ) // do glue together words enclosed in quotes
continue;
if( trimComments( token ) ) // don't glue together words separated with comment
break;
}
if( c == '\n' ) {
// update line counter
++mLine;
}
} while( token == "" && mStream->peek() != EOF ); // double check in case of consecutive separators
}
if( false == parameters.empty() ) {
// if there's parameter list, check the token for potential parameters to replace
size_t pos; // początek podmienianego ciągu
while( ( pos = token.find( "(p" ) ) != std::string::npos ) {
// check if the token is a parameter which should be replaced with stored true value
auto const parameter{ token.substr( pos + 2, token.find( ")", pos ) - ( pos + 2 ) ) }; // numer parametru
token.erase( pos, token.find( ")", pos ) - pos + 1 ); // najpierw usunięcie "(pN)"
size_t nr = atoi( parameter.c_str() ) - 1;
if( nr < parameters.size() ) {
token.insert( pos, parameters.at( nr ) ); // wklejenie wartości parametru
if( ToLower )
for( ; pos < parameters.at( nr ).size(); ++pos )
token[ pos ] = tolower( token[ pos ] );
}
else
token.insert( pos, "none" ); // zabezpieczenie przed brakiem parametru
}
}
if( expandIncludes && token == "include" ) {
// launch child parser if include directive found.
// NOTE: parameter collecting uses default set of token separators.
std::string includefile = readToken(ToLower); // nazwa pliku
std::replace(includefile.begin(), includefile.end(), '\\', '/');
if( ( true == LoadTraction )
|| ( ( includefile.find( "tr/" ) == std::string::npos )
&& ( includefile.find( "tra/" ) == std::string::npos ) ) ) {
// get parameter list for the child parser
std::vector<std::string> includeparameters;
std::string parameter = readToken( false ); // w parametrach nie zmniejszamy
while( ( parameter.empty() == false )
&& ( parameter != "end" ) ) {
includeparameters.emplace_back( parameter );
parameter = readToken( false );
}
mIncludeParser = std::make_shared<cParser>( includefile, buffer_FILE, mPath, LoadTraction, includeparameters );
mIncludeParser->autoclear( m_autoclear );
if( mIncludeParser->mSize <= 0 ) {
ErrorLog( "Bad include: can't open file \"" + includefile + "\"" );
}
}
else {
while( token != "end" ) {
token = readToken( true ); // minimize risk of case mismatch on comparison
}
}
token = readToken(ToLower, Break);
}
// all done
return token;
}
std::string cParser::readQuotes(char const Quote) { // read the stream until specified char or stream end
std::string token = "";
char c { 0 };
bool escaped = false;
while( mStream->peek() != EOF ) { // get all chars until the quote mark
c = mStream->get();
if (escaped) {
escaped = false;
}
else {
if (c == '\\') {
escaped = true;
continue;
}
else if (c == Quote)
break;
}
if (c == '\n')
++mLine; // update line counter
token += c;
}
return token;
}
void cParser::skipComment( std::string const &Endmark ) { // pobieranie znaków aż do znalezienia znacznika końca
std::string input = "";
char c { 0 };
auto const endmarksize = Endmark.size();
while( mStream->peek() != EOF ) {
// o ile nie koniec pliku
c = mStream->get(); // pobranie znaku
if( c == '\n' ) {
// update line counter
++mLine;
}
input += c;
if( input.find( Endmark ) != std::string::npos ) // szukanie znacznika końca
break;
if( input.size() >= endmarksize ) {
// keep the read text short, to avoid pointless string re-allocations on longer comments
input = input.substr( 1 );
}
}
return;
}
bool cParser::findQuotes( std::string &String ) {
if( String.rfind( '\"' ) != std::string::npos ) {
String.erase( String.rfind( '\"' ), 1 );
String += readQuotes();
return true;
}
return false;
}
bool cParser::trimComments(std::string &String)
{
for (commentmap::iterator cmIt = mComments.begin(); cmIt != mComments.end(); ++cmIt)
{
if (String.rfind((*cmIt).first) != std::string::npos)
{
skipComment((*cmIt).second);
String.resize(String.rfind((*cmIt).first));
return true;
}
}
return false;
}
void cParser::injectString(const std::string &str)
{
if (mIncludeParser) {
mIncludeParser->injectString(str);
}
else {
mIncludeParser = std::make_shared<cParser>( str, buffer_TEXT, "", LoadTraction );
mIncludeParser->autoclear( m_autoclear );
}
}
int cParser::getProgress() const
{
return static_cast<int>( mStream->rdbuf()->pubseekoff(0, std::ios_base::cur) * 100 / mSize );
}
int cParser::getFullProgress() const {
int progress = getProgress();
if( mIncludeParser ) return progress + ( ( 100 - progress )*( mIncludeParser->getProgress() ) / 100 );
else return progress;
}
std::size_t cParser::countTokens( std::string const &Stream, std::string Path ) {
return cParser( Stream, buffer_FILE, Path ).count();
}
std::size_t cParser::count() {
std::string token;
size_t count { 0 };
do {
token = "";
token = readToken( false );
++count;
} while( false == token.empty() );
return count - 1;
}
void cParser::addCommentStyle( std::string const &Commentstart, std::string const &Commentend ) {
mComments.insert( commentmap::value_type(Commentstart, Commentend) );
}
// returns name of currently open file, or empty string for text type stream
std::string
cParser::Name() const {
if( mIncludeParser ) { return mIncludeParser->Name(); }
else { return mPath + mFile; }
}
// returns number of currently processed line
std::size_t
cParser::Line() const {
if( mIncludeParser ) { return mIncludeParser->Line(); }
else { return mLine; }
}
int cParser::LineMain() const {
return mIncludeParser ? -1 : mLine;
}
<|endoftext|>
|
<commit_before>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <memory>
namespace parser{
using namespace std;
bool isFirst = true;
class Rule{
string s;
vector<vector<shared_ptr<Rule>>> f;
bool isTerm_;
bool epsilon;
public:
Rule(string s):
s(s),isTerm_(true),epsilon(false){};
Rule(string s,bool isTerm):
s(s),isTerm_(isTerm),epsilon(false){};
Rule(vector< vector<shared_ptr<Rule>>> f):
f(f),isTerm_(false),epsilon(false){};
Rule():isTerm_(false),epsilon(true){};
void add(vector<shared_ptr<Rule>> a){
epsilon = false;
f.push_back(a);
}
bool isTerm() const{
return isTerm_;
}
vector<vector<shared_ptr<Rule>>> rules() const{
return f;
}
operator string() const{
return s;
}
};
unordered_map<string, vector<shared_ptr<Rule>>> follow_table;
// Rules
vector<shared_ptr<Rule>> rules;
shared_ptr<Rule> Epsilon(new Rule("Epsilon"));
shared_ptr<Rule> FIN(new Rule("FIN"));
shared_ptr<Rule> E(new Rule("E", false));
shared_ptr<Rule> Eq(new Rule("Eq", false));
shared_ptr<Rule> T(new Rule("T", false));
shared_ptr<Rule> Tq(new Rule("Tq",false));
shared_ptr<Rule> F(new Rule("F",false));
vector<shared_ptr<Rule>> first(shared_ptr<Rule> Rs){
if(Rs->isTerm()){
return {Rs};
}
vector<shared_ptr<Rule>> res;
for(auto& r : Rs->rules()){
if(!r.empty()){
auto ext = first(r[0]);
if(find(ext.begin(), ext.end(), Epsilon) != ext.end()){
ext.erase(remove(ext.begin(), ext.end(), Epsilon), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(r.size() >= 2){
auto nxt = first(r[1]);
res.insert(res.end(), nxt.begin(), nxt.end());
}else{
res.push_back(Epsilon);
}
}
res.insert(res.end(), ext.begin(), ext.end());
}
}
return res;
}
vector<shared_ptr<Rule>> first(initializer_list<shared_ptr<Rule>> l){
if(l.size() == 0)
return {Epsilon};
vector<shared_ptr<Rule>> res;
auto it = l.begin();
if(*it == Epsilon) return {Epsilon};
if((*it)->isTerm()) return {*it};
auto ext = first(*it);
if(find(ext.begin(), ext.end(), Epsilon) != ext.end()){
ext.erase(remove(ext.begin(), ext.end(), Epsilon), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(l.size() >= 2 ){
it++;
auto next = first(*it);
res.insert(res.end(), next.begin(), next.end());
}
return res;
}else{
return ext;
}
}
vector<shared_ptr<Rule>> follow(shared_ptr<Rule> Rs){
vector<shared_ptr<Rule>> res;
if(Rs == E){
res.push_back(FIN);
}
for(auto rule : rules){
if(rule == Rs) continue;
for(auto r : rule->rules()){
for(size_t i = 1; i < r.size(); i++){
if(string(*r[i]) == string(*Rs)){
if(i + 1 < r.size()){
auto ext = first(r[i+1]);
if(find(ext.begin(), ext.end(), Epsilon) != ext.end()){
auto left = follow(rule);
res.insert(res.end(), left.begin(), left.end());
}
ext.erase(remove(ext.begin(), ext.end(), Epsilon), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
}else{
auto left = follow(rule);
res.insert(res.end(), left.begin(), left.end());
}
}
}
}
}
return res;
}
shared_ptr<Rule> mR(string v){
return shared_ptr<Rule>(new Rule(v));
}
void setup(){
E->add(
{T, Eq}
);
Eq->add(
{mR("+"), T, Eq}
);
Eq->add(
{Epsilon}
);
T->add(
{F, Tq}
);
Tq->add(
{mR("*"), F, Tq}
);
Tq->add(
{Epsilon}
);
F->add(
{mR("("), E, mR(")")}
);
F->add(
{mR("i")}
);
rules.push_back(E);
rules.push_back(Eq);
rules.push_back(T);
rules.push_back(Tq);
rules.push_back(F);
}
void test(shared_ptr<Rule> R){
cout << "==== "<<string(*R)<< " ===\n";
for(auto r: first(R)){
cout << string(*r) << endl;
}
cout<<"===\n";
for(auto r: follow(R)){
cout << string(*r) << endl;
}
}
void parser(){
setup();
test(E);
test(Eq);
test(T);
test(Tq);
test(F);
cout<<"===\n";
for(auto r: first({mR("*"),F,Tq})){
cout << string(*r) << endl;
}
}
}
int main(){
parser::parser();
return 0;
}<commit_msg>[WIP] mile stone<commit_after>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <memory>
namespace parser{
using namespace std;
bool isFirst = true;
class Rule{
string s;
vector<vector<shared_ptr<Rule>>> f;
bool isTerm_;
bool epsilon;
public:
Rule(string s):
s(s),isTerm_(true),epsilon(false){};
Rule(string s,bool isTerm):
s(s),isTerm_(isTerm),epsilon(false){};
Rule(vector< vector<shared_ptr<Rule>>> f):
f(f),isTerm_(false),epsilon(false){};
Rule():isTerm_(false),epsilon(true){};
Rule(string name,initializer_list<shared_ptr<Rule>> lr):
s(name),isTerm_(false){
vector<shared_ptr<Rule>> ext(lr.begin(), lr.end());
f.push_back(ext);
}
void add(vector<shared_ptr<Rule>> a){
epsilon = false;
f.push_back(a);
}
bool isTerm() const{
return isTerm_;
}
vector<vector<shared_ptr<Rule>>> rules() const{
return f;
}
size_t size() const{
return f.size();
}
operator string() const{
return s;
}
string name()const{
return s;
}
friend ostream& operator<<(ostream &out, const Rule &r){
if(r.isTerm()){
out << string(r);
}else{
for(auto rule : r.rules()){
out << string(r) << " -> ";
for(auto s : rule){
out << string(*s) <<" ";
}
out << "\n";
}
}
return out;
}
};
unordered_map<string, vector<shared_ptr<Rule>>> follow_table;
// Rules
vector<shared_ptr<Rule>> rules;
shared_ptr<Rule> Epsilon(new Rule("Epsilon"));
shared_ptr<Rule> FIN(new Rule("FIN"));
shared_ptr<Rule> E(new Rule("E", false));
shared_ptr<Rule> Eq(new Rule("Eq", false));
shared_ptr<Rule> T(new Rule("T", false));
shared_ptr<Rule> Tq(new Rule("Tq",false));
shared_ptr<Rule> F(new Rule("F",false));
vector<shared_ptr<Rule>> first(shared_ptr<Rule> Rs){
if(Rs->isTerm()){
return {Rs};
}
vector<shared_ptr<Rule>> res;
for(auto& r : Rs->rules()){
if(!r.empty()){
auto ext = first(r[0]);
if(find(ext.begin(), ext.end(), Epsilon) != ext.end()){
ext.erase(remove(ext.begin(), ext.end(), Epsilon), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(r.size() >= 2){
auto nxt = first(r[1]);
res.insert(res.end(), nxt.begin(), nxt.end());
}else{
res.push_back(Epsilon);
}
}
res.insert(res.end(), ext.begin(), ext.end());
}
}
return res;
}
vector<shared_ptr<Rule>> first(initializer_list<shared_ptr<Rule>> l){
if(l.size() == 0)
return {Epsilon};
vector<shared_ptr<Rule>> res;
auto it = l.begin();
if(*it == Epsilon) return {Epsilon};
if((*it)->isTerm()) return {*it};
auto ext = first(*it);
if(find(ext.begin(), ext.end(), Epsilon) != ext.end()){
ext.erase(remove(ext.begin(), ext.end(), Epsilon), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(l.size() >= 2 ){
it++;
auto next = first(*it);
res.insert(res.end(), next.begin(), next.end());
}
return res;
}else{
return ext;
}
}
vector<shared_ptr<Rule>> follow(shared_ptr<Rule> Rs){
vector<shared_ptr<Rule>> res;
if(Rs == E){
res.push_back(FIN);
}
for(auto rule : rules){
if(rule == Rs) continue;
for(auto r : rule->rules()){
for(size_t i = 1; i < r.size(); i++){
if(string(*r[i]) == string(*Rs)){
if(i + 1 < r.size()){
auto ext = first(r[i+1]);
if(find(ext.begin(), ext.end(), Epsilon) != ext.end()){
auto left = follow(rule);
res.insert(res.end(), left.begin(), left.end());
}
ext.erase(remove(ext.begin(), ext.end(), Epsilon), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
}else{
auto left = follow(rule);
res.insert(res.end(), left.begin(), left.end());
}
}
}
}
}
return res;
}
void closure(shared_ptr<Rule> I){
int size = I->size();
int c = 0;
while(c<1){
c++;
for(auto rule : I->rules()){
if(rule.size() >= 2){
auto X = rule[0];
cout<<"===\n";
cout<< *X;
cout<<"===\n";
if(!X->isTerm()){
for(auto ext : X->rules()){
I->add(ext);
}
}
}
}
if(size == I->size()) return;
size = I->size();
}
}
shared_ptr<Rule> mR(string v){
return shared_ptr<Rule>(new Rule(v));
}
shared_ptr<Rule> mR(string name,initializer_list<shared_ptr<Rule>> l){
return shared_ptr<Rule>(new Rule(name,l));
}
void setup(){
E->add(
{T, Eq}
);
Eq->add(
{mR("+"), T, Eq}
);
Eq->add(
{Epsilon}
);
T->add(
{F, Tq}
);
Tq->add(
{mR("*"), F, Tq}
);
Tq->add(
{Epsilon}
);
F->add(
{mR("("), E, mR(")")}
);
F->add(
{mR("i")}
);
rules.push_back(E);
rules.push_back(Eq);
rules.push_back(T);
rules.push_back(Tq);
rules.push_back(F);
}
void test(shared_ptr<Rule> R){
cout << "==== "<<string(*R)<< " ===\n";
for(auto r: first(R)){
cout << string(*r) << endl;
}
cout<<"===\n";
for(auto r: follow(R)){
cout << string(*r) << endl;
}
}
void parser(){
setup();
/*
test(E);
test(Eq);
test(T);
test(Tq);
test(F);
cout<<"===\n";
for(auto r: first({F,Tq})){
cout << *r << endl;
}
cout <<"~~~~~~~\n";
*/
auto items = mR("S",{E,FIN});
cout << *items;
cout <<"~~~~~~~\n";
closure(items);
cout << *items;
}
}
int main(){
parser::parser();
return 0;
}<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2009 Mark Borgerding mark a borgerding net
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <unsupported/Eigen/FFT>
using namespace std;
float norm(float x) {return x*x;}
double norm(double x) {return x*x;}
long double norm(long double x) {return x*x;}
template < typename T>
complex<long double> promote(complex<T> x) { return complex<long double>(x.real(),x.imag()); }
complex<long double> promote(float x) { return complex<long double>( x); }
complex<long double> promote(double x) { return complex<long double>( x); }
complex<long double> promote(long double x) { return complex<long double>( x); }
template <typename VectorType1,typename VectorType2>
long double fft_rmse( const VectorType1 & fftbuf,const VectorType2 & timebuf)
{
long double totalpower=0;
long double difpower=0;
cerr <<"idx\ttruth\t\tvalue\t|dif|=\n";
for (size_t k0=0;k0<size_t(fftbuf.size());++k0) {
complex<long double> acc = 0;
#ifdef _GNU_SOURCE
long double phinc = -2.*k0* M_PIl / timebuf.size();
#else
long double phinc = -2.*k0* M_PI / timebuf.size();
#endif
for (size_t k1=0;k1<size_t(timebuf.size());++k1) {
acc += promote( timebuf[k1] ) * exp( complex<long double>(0,k1*phinc) );
}
totalpower += norm(acc);
complex<long double> x = promote(fftbuf[k0]);
complex<long double> dif = acc - x;
difpower += norm(dif);
cerr << k0 << "\t" << acc << "\t" << x << "\t" << sqrt(norm(dif)) << endl;
}
cerr << "rmse:" << sqrt(difpower/totalpower) << endl;
return sqrt(difpower/totalpower);
}
template <typename VectorType1,typename VectorType2>
long double dif_rmse( const VectorType1& buf1,const VectorType2& buf2)
{
long double totalpower=0;
long double difpower=0;
size_t n = min( buf1.size(),buf2.size() );
for (size_t k=0;k<n;++k) {
totalpower += (norm( buf1[k] ) + norm(buf2[k]) )/2.;
difpower += norm(buf1[k] - buf2[k]);
}
return sqrt(difpower/totalpower);
}
enum { StdVectorContainer, EigenVectorContainer };
template<int Container, typename Scalar> struct VectorType;
template<typename Scalar> struct VectorType<StdVectorContainer,Scalar>
{
typedef vector<Scalar> type;
};
template<typename Scalar> struct VectorType<EigenVectorContainer,Scalar>
{
typedef Matrix<Scalar,Dynamic,1> type;
};
template <int Container, typename T>
void test_scalar_generic(int nfft)
{
typedef typename FFT<T>::Complex Complex;
typedef typename FFT<T>::Scalar Scalar;
typedef typename VectorType<Container,Scalar>::type ScalarVector;
typedef typename VectorType<Container,Complex>::type ComplexVector;
FFT<T> fft;
ScalarVector inbuf(nfft);
ComplexVector outbuf;
for (int k=0;k<nfft;++k)
inbuf[k]= (T)(rand()/(double)RAND_MAX - .5);
// make sure it DOESN'T give the right full spectrum answer
// if we've asked for half-spectrum
fft.SetFlag(fft.HalfSpectrum );
fft.fwd( outbuf,inbuf);
VERIFY(outbuf.size() == (nfft>>1)+1);
VERIFY( fft_rmse(outbuf,inbuf) < test_precision<T>() );// gross check
fft.ClearFlag(fft.HalfSpectrum );
fft.fwd( outbuf,inbuf);
VERIFY( fft_rmse(outbuf,inbuf) < test_precision<T>() );// gross check
ScalarVector buf3;
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
// verify that the Unscaled flag takes effect
ComplexVector buf4;
fft.SetFlag(fft.Unscaled);
fft.inv( buf4 , outbuf);
for (int k=0;k<nfft;++k)
buf4[k] *= T(1./nfft);
VERIFY( dif_rmse(inbuf,buf4) < test_precision<T>() );// gross check
// verify that ClearFlag works
fft.ClearFlag(fft.Unscaled);
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
}
template <typename T>
void test_scalar(int nfft)
{
test_scalar_generic<StdVectorContainer,T>(nfft);
test_scalar_generic<EigenVectorContainer,T>(nfft);
}
template <int Container, typename T>
void test_complex_generic(int nfft)
{
typedef typename FFT<T>::Complex Complex;
typedef typename VectorType<Container,Complex>::type ComplexVector;
FFT<T> fft;
ComplexVector inbuf(nfft);
ComplexVector outbuf;
ComplexVector buf3;
for (int k=0;k<nfft;++k)
inbuf[k]= Complex( (T)(rand()/(double)RAND_MAX - .5), (T)(rand()/(double)RAND_MAX - .5) );
fft.fwd( outbuf , inbuf);
VERIFY( fft_rmse(outbuf,inbuf) < test_precision<T>() );// gross check
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
// verify that the Unscaled flag takes effect
ComplexVector buf4;
fft.SetFlag(fft.Unscaled);
fft.inv( buf4 , outbuf);
for (int k=0;k<nfft;++k)
buf4[k] *= T(1./nfft);
VERIFY( dif_rmse(inbuf,buf4) < test_precision<T>() );// gross check
// verify that ClearFlag works
fft.ClearFlag(fft.Unscaled);
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
}
template <typename T>
void test_complex(int nfft)
{
test_complex_generic<StdVectorContainer,T>(nfft);
test_complex_generic<EigenVectorContainer,T>(nfft);
}
void test_FFT()
{
CALL_SUBTEST( test_complex<float>(32) );
CALL_SUBTEST( test_complex<double>(32) );
CALL_SUBTEST( test_complex<long double>(32) );
CALL_SUBTEST( test_complex<float>(256) );
CALL_SUBTEST( test_complex<double>(256) );
CALL_SUBTEST( test_complex<long double>(256) );
CALL_SUBTEST( test_complex<float>(3*8) );
CALL_SUBTEST( test_complex<double>(3*8) );
CALL_SUBTEST( test_complex<long double>(3*8) );
CALL_SUBTEST( test_complex<float>(5*32) );
CALL_SUBTEST( test_complex<double>(5*32) );
CALL_SUBTEST( test_complex<long double>(5*32) );
CALL_SUBTEST( test_complex<float>(2*3*4) );
CALL_SUBTEST( test_complex<double>(2*3*4) );
CALL_SUBTEST( test_complex<long double>(2*3*4) );
CALL_SUBTEST( test_complex<float>(2*3*4*5) );
CALL_SUBTEST( test_complex<double>(2*3*4*5) );
CALL_SUBTEST( test_complex<long double>(2*3*4*5) );
CALL_SUBTEST( test_complex<float>(2*3*4*5*7) );
CALL_SUBTEST( test_complex<double>(2*3*4*5*7) );
CALL_SUBTEST( test_complex<long double>(2*3*4*5*7) );
CALL_SUBTEST( test_scalar<float>(32) );
CALL_SUBTEST( test_scalar<double>(32) );
CALL_SUBTEST( test_scalar<long double>(32) );
CALL_SUBTEST( test_scalar<float>(45) );
CALL_SUBTEST( test_scalar<double>(45) );
CALL_SUBTEST( test_scalar<long double>(45) );
CALL_SUBTEST( test_scalar<float>(50) );
CALL_SUBTEST( test_scalar<double>(50) );
CALL_SUBTEST( test_scalar<long double>(50) );
CALL_SUBTEST( test_scalar<float>(256) );
CALL_SUBTEST( test_scalar<double>(256) );
CALL_SUBTEST( test_scalar<long double>(256) );
CALL_SUBTEST( test_scalar<float>(2*3*4*5*7) );
CALL_SUBTEST( test_scalar<double>(2*3*4*5*7) );
CALL_SUBTEST( test_scalar<long double>(2*3*4*5*7) );
}
<commit_msg>quieted signed/unsigned comparison warning<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2009 Mark Borgerding mark a borgerding net
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <unsupported/Eigen/FFT>
using namespace std;
float norm(float x) {return x*x;}
double norm(double x) {return x*x;}
long double norm(long double x) {return x*x;}
template < typename T>
complex<long double> promote(complex<T> x) { return complex<long double>(x.real(),x.imag()); }
complex<long double> promote(float x) { return complex<long double>( x); }
complex<long double> promote(double x) { return complex<long double>( x); }
complex<long double> promote(long double x) { return complex<long double>( x); }
template <typename VectorType1,typename VectorType2>
long double fft_rmse( const VectorType1 & fftbuf,const VectorType2 & timebuf)
{
long double totalpower=0;
long double difpower=0;
cerr <<"idx\ttruth\t\tvalue\t|dif|=\n";
for (size_t k0=0;k0<size_t(fftbuf.size());++k0) {
complex<long double> acc = 0;
#ifdef _GNU_SOURCE
long double phinc = -2.*k0* M_PIl / timebuf.size();
#else
long double phinc = -2.*k0* M_PI / timebuf.size();
#endif
for (size_t k1=0;k1<size_t(timebuf.size());++k1) {
acc += promote( timebuf[k1] ) * exp( complex<long double>(0,k1*phinc) );
}
totalpower += norm(acc);
complex<long double> x = promote(fftbuf[k0]);
complex<long double> dif = acc - x;
difpower += norm(dif);
cerr << k0 << "\t" << acc << "\t" << x << "\t" << sqrt(norm(dif)) << endl;
}
cerr << "rmse:" << sqrt(difpower/totalpower) << endl;
return sqrt(difpower/totalpower);
}
template <typename VectorType1,typename VectorType2>
long double dif_rmse( const VectorType1& buf1,const VectorType2& buf2)
{
long double totalpower=0;
long double difpower=0;
size_t n = min( buf1.size(),buf2.size() );
for (size_t k=0;k<n;++k) {
totalpower += (norm( buf1[k] ) + norm(buf2[k]) )/2.;
difpower += norm(buf1[k] - buf2[k]);
}
return sqrt(difpower/totalpower);
}
enum { StdVectorContainer, EigenVectorContainer };
template<int Container, typename Scalar> struct VectorType;
template<typename Scalar> struct VectorType<StdVectorContainer,Scalar>
{
typedef vector<Scalar> type;
};
template<typename Scalar> struct VectorType<EigenVectorContainer,Scalar>
{
typedef Matrix<Scalar,Dynamic,1> type;
};
template <int Container, typename T>
void test_scalar_generic(int nfft)
{
typedef typename FFT<T>::Complex Complex;
typedef typename FFT<T>::Scalar Scalar;
typedef typename VectorType<Container,Scalar>::type ScalarVector;
typedef typename VectorType<Container,Complex>::type ComplexVector;
FFT<T> fft;
ScalarVector inbuf(nfft);
ComplexVector outbuf;
for (int k=0;k<nfft;++k)
inbuf[k]= (T)(rand()/(double)RAND_MAX - .5);
// make sure it DOESN'T give the right full spectrum answer
// if we've asked for half-spectrum
fft.SetFlag(fft.HalfSpectrum );
fft.fwd( outbuf,inbuf);
VERIFY(outbuf.size() == (size_t)( (nfft>>1)+1) );
VERIFY( fft_rmse(outbuf,inbuf) < test_precision<T>() );// gross check
fft.ClearFlag(fft.HalfSpectrum );
fft.fwd( outbuf,inbuf);
VERIFY( fft_rmse(outbuf,inbuf) < test_precision<T>() );// gross check
ScalarVector buf3;
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
// verify that the Unscaled flag takes effect
ComplexVector buf4;
fft.SetFlag(fft.Unscaled);
fft.inv( buf4 , outbuf);
for (int k=0;k<nfft;++k)
buf4[k] *= T(1./nfft);
VERIFY( dif_rmse(inbuf,buf4) < test_precision<T>() );// gross check
// verify that ClearFlag works
fft.ClearFlag(fft.Unscaled);
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
}
template <typename T>
void test_scalar(int nfft)
{
test_scalar_generic<StdVectorContainer,T>(nfft);
test_scalar_generic<EigenVectorContainer,T>(nfft);
}
template <int Container, typename T>
void test_complex_generic(int nfft)
{
typedef typename FFT<T>::Complex Complex;
typedef typename VectorType<Container,Complex>::type ComplexVector;
FFT<T> fft;
ComplexVector inbuf(nfft);
ComplexVector outbuf;
ComplexVector buf3;
for (int k=0;k<nfft;++k)
inbuf[k]= Complex( (T)(rand()/(double)RAND_MAX - .5), (T)(rand()/(double)RAND_MAX - .5) );
fft.fwd( outbuf , inbuf);
VERIFY( fft_rmse(outbuf,inbuf) < test_precision<T>() );// gross check
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
// verify that the Unscaled flag takes effect
ComplexVector buf4;
fft.SetFlag(fft.Unscaled);
fft.inv( buf4 , outbuf);
for (int k=0;k<nfft;++k)
buf4[k] *= T(1./nfft);
VERIFY( dif_rmse(inbuf,buf4) < test_precision<T>() );// gross check
// verify that ClearFlag works
fft.ClearFlag(fft.Unscaled);
fft.inv( buf3 , outbuf);
VERIFY( dif_rmse(inbuf,buf3) < test_precision<T>() );// gross check
}
template <typename T>
void test_complex(int nfft)
{
test_complex_generic<StdVectorContainer,T>(nfft);
test_complex_generic<EigenVectorContainer,T>(nfft);
}
void test_FFT()
{
CALL_SUBTEST( test_complex<float>(32) );
CALL_SUBTEST( test_complex<double>(32) );
CALL_SUBTEST( test_complex<long double>(32) );
CALL_SUBTEST( test_complex<float>(256) );
CALL_SUBTEST( test_complex<double>(256) );
CALL_SUBTEST( test_complex<long double>(256) );
CALL_SUBTEST( test_complex<float>(3*8) );
CALL_SUBTEST( test_complex<double>(3*8) );
CALL_SUBTEST( test_complex<long double>(3*8) );
CALL_SUBTEST( test_complex<float>(5*32) );
CALL_SUBTEST( test_complex<double>(5*32) );
CALL_SUBTEST( test_complex<long double>(5*32) );
CALL_SUBTEST( test_complex<float>(2*3*4) );
CALL_SUBTEST( test_complex<double>(2*3*4) );
CALL_SUBTEST( test_complex<long double>(2*3*4) );
CALL_SUBTEST( test_complex<float>(2*3*4*5) );
CALL_SUBTEST( test_complex<double>(2*3*4*5) );
CALL_SUBTEST( test_complex<long double>(2*3*4*5) );
CALL_SUBTEST( test_complex<float>(2*3*4*5*7) );
CALL_SUBTEST( test_complex<double>(2*3*4*5*7) );
CALL_SUBTEST( test_complex<long double>(2*3*4*5*7) );
CALL_SUBTEST( test_scalar<float>(32) );
CALL_SUBTEST( test_scalar<double>(32) );
CALL_SUBTEST( test_scalar<long double>(32) );
CALL_SUBTEST( test_scalar<float>(45) );
CALL_SUBTEST( test_scalar<double>(45) );
CALL_SUBTEST( test_scalar<long double>(45) );
CALL_SUBTEST( test_scalar<float>(50) );
CALL_SUBTEST( test_scalar<double>(50) );
CALL_SUBTEST( test_scalar<long double>(50) );
CALL_SUBTEST( test_scalar<float>(256) );
CALL_SUBTEST( test_scalar<double>(256) );
CALL_SUBTEST( test_scalar<long double>(256) );
CALL_SUBTEST( test_scalar<float>(2*3*4*5*7) );
CALL_SUBTEST( test_scalar<double>(2*3*4*5*7) );
CALL_SUBTEST( test_scalar<long double>(2*3*4*5*7) );
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (c) 2012, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * 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 Hobu, Inc. or Flaxen Consulting 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 <pdal/drivers/nitf/Reader.hpp>
#ifdef PDAL_HAVE_GDAL
#include <pdal/PointBuffer.hpp>
#include <pdal/StreamFactory.hpp>
#include <pdal/drivers/las/Reader.hpp>
// local
#include "NitfFile.hpp"
#include "nitflib.h"
// gdal
#include "gdal.h"
#include "cpl_vsi.h"
#include "cpl_conv.h"
#include "cpl_string.h"
namespace pdal { namespace drivers { namespace nitf {
// References:
// - NITF 2.1 standard: MIL-STD-2500C (01 May 2006)
// - Lidar implementation profile v1.0 (2010-09-07)
//
// There must be at least one Image segment ("IM").
// There must be at least one DES segment ("DE") named LIDARA.
//
// You could have multiple image segments and LIDARA segments, but
// the standard doesn't seem to say anything about how you associate which
// image segment(s) with which LIDARA segment(s). We will assume only
// one image segment and only one LIDARA segment.
//
// We don't support LIDARA segments that are split into multiple DES segments
// via the DES INDEX mechanism.
//
// Metadata: we store...
// - the file header fields - namespace <root>.FH.fieldname
// - the file header TREs - namespace <root>.FH.TRE.TREname
// - the IM segment fields - namespace <root>.IM.1.fieldname
// - the IM segment TREs - namespace <root>.IM.1.TRE.TREname
// - the DES fields - namespace <root>.DE.1.fieldname
// - the DES TREs - namespace <root>.DE.1.fieldname
// Note we use a number to indicate which segment is being used,
// so there is no ambiuity with multisegment NITFs
//
// We also store some basic info for the IM segment: pixel width,
// pixel height, and number of bands.
// BUG: this is commented out right now (see processImageInfo()),
// because NITFImageDeaccess() leaks memory?
//
// We do not parse out the TRE fields; we leave the data as a byte stream
// (This would be easy enough to do later, at least for those TREs we have documentation on).
//
// The dimensions we write out are (precisely) the LAS dimensions; we use the same
// names, so as not to require upstream stgaes to understand both LAS dimension
// names and NITF dimension names.
//
// BUG: we should provide an option to set the SRS of the Stage using the IGEOLO
// field, but the GDAL C API doesn't provide an easy way to get the SRS. (When we
// add this option, the default will be to use NITF.)
//
// Need to test on all the other NITF LAS files
//
// BUG: need to implement addDefaultDimensions() so it does what LAS does.
//
// BUG: findIMSegment() allows "None" as an image type (for now, just to
// support the autzen test input)
// ==========================================================================
Reader::Reader(const Options& options)
: pdal::Reader(options)
, m_filename(options.getValueOrThrow<std::string>("filename"))
, m_streamFactory(NULL)
, m_lasReader(NULL)
{
addDefaultDimensions();
return;
}
Reader::~Reader()
{
delete m_streamFactory;
delete m_lasReader;
}
void Reader::addDefaultDimensions()
{
// BUG: implement this to inherit from LAS
return;
}
void Reader::initialize()
{
pdal::Reader::initialize();
boost::uint64_t offset, length;
{
NitfFile nitf(m_filename);
nitf.open();
nitf.getLasPosition(offset, length);
nitf.extractMetadata(getMetadataRef());
nitf.close();
}
m_streamFactory = new FilenameSubsetStreamFactory(m_filename, offset, length);
m_lasReader = new pdal::drivers::las::Reader(m_streamFactory);
m_lasReader->initialize();
setCoreProperties(*m_lasReader);
return;
}
const Options Reader::getDefaultOptions() const
{
Options options;
return options;
}
pdal::StageSequentialIterator* Reader::createSequentialIterator(PointBuffer& buffer) const
{
pdal::StageSequentialIterator* lasIter = m_lasReader->createSequentialIterator(buffer);
return lasIter;
}
boost::property_tree::ptree Reader::toPTree() const
{
boost::property_tree::ptree tree = pdal::Reader::toPTree();
// add stuff here specific to this stage type
return tree;
}
} } } // namespaces
#endif
<commit_msg>comment<commit_after>/******************************************************************************
* Copyright (c) 2012, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * 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 Hobu, Inc. or Flaxen Consulting 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 <pdal/drivers/nitf/Reader.hpp>
#ifdef PDAL_HAVE_GDAL
#include <pdal/PointBuffer.hpp>
#include <pdal/StreamFactory.hpp>
#include <pdal/drivers/las/Reader.hpp>
// local
#include "NitfFile.hpp"
#include "nitflib.h"
// gdal
#include "gdal.h"
#include "cpl_vsi.h"
#include "cpl_conv.h"
#include "cpl_string.h"
namespace pdal { namespace drivers { namespace nitf {
// References:
// - NITF 2.1 standard: MIL-STD-2500C (01 May 2006)
// - Lidar implementation profile v1.0 (2010-09-07)
//
// There must be at least one Image segment ("IM").
// There must be at least one DES segment ("DE") named LIDARA.
//
// You could have multiple image segments and LIDARA segments, but
// the standard doesn't seem to say anything about how you associate which
// image segment(s) with which LIDARA segment(s). We will assume only
// one image segment and only one LIDARA segment.
//
// We don't support LIDARA segments that are split into multiple DES segments
// via the DES INDEX mechanism.
//
// Metadata: we store...
// - the file header fields - namespace <root>.FH.fieldname
// - the file header TREs - namespace <root>.FH.TRE.TREname
// - the IM segment fields - namespace <root>.IM.1.fieldname
// - the IM segment TREs - namespace <root>.IM.1.TRE.TREname
// - the DES fields - namespace <root>.DE.1.fieldname
// - the DES TREs - namespace <root>.DE.1.fieldname
// Note we use a number to indicate which segment is being used,
// so there is no ambiuity with multisegment NITFs
//
// We also store some basic info for the IM segment: pixel width,
// pixel height, and number of bands.
// BUG: this is commented out right now (see processImageInfo()),
// because NITFImageDeaccess() leaks memory?
//
// We do not parse out the TRE fields; we leave the data as a byte stream
// (This would be easy enough to do later, at least for those TREs we have documentation on).
//
// The dimensions we write out are (precisely) the LAS dimensions; we use the same
// names, so as not to require upstream stgaes to understand both LAS dimension
// names and NITF dimension names.
//
// BUG: we should provide an option to set the SRS of the Stage using the IGEOLO
// field, but the GDAL C API doesn't provide an easy way to get the SRS. (When we
// add this option, the default will be to use NITF.)
//
// Need to test on all the other NITF LAS files
//
// BUG: need to implement addDefaultDimensions() so it does what LAS does.
//
// BUG: findIMSegment() allows "None" as an image type (for now, just to
// support the autzen test input)
//
// BUG: fix the reader test that asserts 80 pieces of metadata coming out
// ==========================================================================
Reader::Reader(const Options& options)
: pdal::Reader(options)
, m_filename(options.getValueOrThrow<std::string>("filename"))
, m_streamFactory(NULL)
, m_lasReader(NULL)
{
addDefaultDimensions();
return;
}
Reader::~Reader()
{
delete m_streamFactory;
delete m_lasReader;
}
void Reader::addDefaultDimensions()
{
// BUG: implement this to inherit from LAS
return;
}
void Reader::initialize()
{
pdal::Reader::initialize();
boost::uint64_t offset, length;
{
NitfFile nitf(m_filename);
nitf.open();
nitf.getLasPosition(offset, length);
nitf.extractMetadata(getMetadataRef());
nitf.close();
}
m_streamFactory = new FilenameSubsetStreamFactory(m_filename, offset, length);
m_lasReader = new pdal::drivers::las::Reader(m_streamFactory);
m_lasReader->initialize();
setCoreProperties(*m_lasReader);
return;
}
const Options Reader::getDefaultOptions() const
{
Options options;
return options;
}
pdal::StageSequentialIterator* Reader::createSequentialIterator(PointBuffer& buffer) const
{
pdal::StageSequentialIterator* lasIter = m_lasReader->createSequentialIterator(buffer);
return lasIter;
}
boost::property_tree::ptree Reader::toPTree() const
{
boost::property_tree::ptree tree = pdal::Reader::toPTree();
// add stuff here specific to this stage type
return tree;
}
} } } // namespaces
#endif
<|endoftext|>
|
<commit_before>// Some part of the code is from
// jjlammi@netti.fi
// http://www.sci.fi/~benefon/rscalc_cpp.html
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
double pi = 3.141592653589793238463;
double tpi = 2 * pi;
double degs = 180.0/pi;
double rads = pi/180.0;
double L,g,daylen;
double SunDia = 0.53; // Sunradius degrees
double AirRefr = 34.0/60.0; // athmospheric refraction degrees //
// Get the days to J2000
// h is UT in decimal hours
// FNday only works between 1901 to 2099 - see Meeus chapter 7
double FNday (int y, int m, int d, float h) {
long int luku = - 7 * (y + (m + 9)/12)/4 + 275*m/9 + d;
// Typecasting needed for TClite on PC DOS at least, to avoid product overflow
luku+= (long int)y*367;
return (double)luku - 730531.5 + h/24.0;
};
// the function below returns an angle in the range
// 0 to 2*pi
double FNrange (double x) {
double b = x / tpi;
double a = tpi * (b - (long)(b));
if (a < 0) a = tpi + a;
return a;
};
// Calculating the hourangle
double f0(double lat, double declin) {
double fo,dfo;
// Correction: different sign at S HS
dfo = rads*(0.5*SunDia + AirRefr); if (lat < 0.0) dfo = -dfo;
fo = tan(declin + dfo) * tan(lat*rads);
if (fo > 0.99999) fo=1.0; // to avoid overflow //
fo = asin(fo) + pi/2.0;
return fo;
};
// Calculating the hourangle for twilight times
//
double f1(double lat, double declin) {
double fi,df1;
// Correction: different sign at S HS
df1 = rads * 6.0; if (lat < 0.0) df1 = -df1;
fi = tan(declin + df1) * tan(lat*rads);
if (fi > 0.99999) fi=1.0; // to avoid overflow //
fi = asin(fi) + pi/2.0;
return fi;
};
// Find the ecliptic longitude of the Sun
double FNsun (double d) {
// mean longitude of the Sun
L = FNrange(280.461 * rads + .9856474 * rads * d);
// mean anomaly of the Sun
g = FNrange(357.528 * rads + .9856003 * rads * d);
// Ecliptic longitude of the Sun
return FNrange(L + 1.915 * rads * sin(g) + .02 * rads * sin(2 * g));
};
// Display decimal hours in hours and minutes
void showhrmn(double dhr) {
int hr,mn;
hr=(int) dhr;
mn = (dhr - (double) hr)*60;
printf("%02d:%02d",hr,mn);
};
// Display decimal hours in hours and minutes, but return a string instead
string hhmm(double dhr) {
int hr,mn;
char buffer[10];
hr=(int) dhr;
mn = (dhr - (double) hr)*60;
snprintf(buffer,sizeof(buffer),"%02d%02d",hr,mn);
return buffer;
}
// Write the given values into a file. This is rather hacky but does the job.
void writelightsettings(double time,double lights, double riseordawn, double red,double green, double blue) {
char buffer[50];
ofstream filehandler;
string filename;
filename = hhmm(time);
snprintf(buffer,sizeof(buffer),"%1.0f %1.0f %1.5f %1.5f %1.5f\n",lights,riseordawn,red,green,blue);
filehandler.open(filename.c_str());
filehandler << buffer;
filehandler.close();
}
void writerisedawntimes(double dawnstart, double daystart, double daystop, double duskstop, double adstart, double adstop) {
ofstream filehandler;
string filename;
filename = "times";
filehandler.open(filename.c_str());
filehandler << hhmm(dawnstart) << "\n";
filehandler << hhmm(daystart) << "\n";
filehandler << hhmm(daystop) << "\n";
filehandler << hhmm(duskstop) << "\n";
filehandler << hhmm(adstart) << "\n";
filehandler << hhmm(adstop) << "\n";
filehandler.close();
}
int main(void) {
double y,m,day,h,latit,longit;
time_t sekunnit;
struct tm *p;
// get the date and time from the user
// read system date and extract the year
/** First get current time **/
time(&sekunnit);
/** Next get localtime **/
p=localtime(&sekunnit);
// this is Y2K compliant algorithm
y = 1900 + p->tm_year;
m = p->tm_mon + 1;
day = p->tm_mday;
h = 12;
// magdeburg
// latit = 52.8;
// madagascar
latit = 20.0;
// we leave longitude as it is, that will only affect time zone
longit= 11.37;
// we will go for utc
double tzone = 0;
double d = FNday(y, m, day, h);
// Use FNsun to find the ecliptic longitude of the
// Sun
double lambda = FNsun(d);
// Obliquity of the ecliptic
double obliq = 23.439 * rads - .0000004 * rads * d;
// Find the RA and DEC of the Sun
double alpha = atan2(cos(obliq) * sin(lambda), cos(lambda));
double delta = asin(sin(obliq) * sin(lambda));
// Find the Equation of Time in minutes
// Correction suggested by David Smith
double LL = L - alpha;
if (L < pi) LL += tpi;
double equation = 1440.0 * (1.0 - LL / tpi);
double ha = f0(latit,delta);
double hb = f1(latit,delta);
double twx = hb - ha; // length of twilight in radians
twx = 12.0*twx/pi; // length of twilight in degrees
// Conversion of angle to hours and minutes //
daylen = degs * ha / 7.5;
if (daylen<0.0001) {daylen = 0.0;}
// arctic winter //
double riset = 12.0 - 12.0 * ha/pi + tzone - longit/15.0 + equation/60.0;
double settm = 12.0 + 12.0 * ha/pi + tzone - longit/15.0 + equation/60.0;
// shift by two hours - that's to have the day of the terrarium more
// aligned to the day of the owners
riset+=2;
settm+=2;
double twam = riset - twx; // morning twilight begin
double twpm = settm + twx; // evening twilight end
if (riset > 24.0) riset-= 24.0;
if (settm > 24.0) settm-= 24.0;
// debug output
/*
printf("\n Sunrise and set\n");
printf("yyyy-mm-dd : %04.0f-%02.0f-%02.0f\n",y,m,day);
printf("Daylength : ");
showhrmn(daylen);
printf(" hours\n");
printf("Begin twilight: ");
showhrmn(twam);
printf("\nSunrise : ");
showhrmn(riset);
printf("\nSunset : ");
showhrmn(settm);
printf("\nEnd twiglight : ");
showhrmn(twpm);
printf("\n");
*/
// most of those values could be int, though...
int colorsteps=1;
double minutestep=1.0/60.0*1;
double dayhour=0;
double red=0,green=0,blue=0;
double lights=0,riseordawn=0;
double riseduration_red=1.5;
double riseduration_green=riseduration_red*0.8;
double riseduration_blue=riseduration_red*0.6;
double rperc=1/riseduration_red*colorsteps;
double gperc=1/riseduration_green*colorsteps;
double bperc=1/riseduration_blue*colorsteps;
double perc=0;
writerisedawntimes(twam,twam+riseduration_red,twpm-riseduration_red,twpm,riset,settm);
for (dayhour=0; dayhour<24; dayhour+=minutestep) {
// first check if the main lights should be turned on or off
if ((dayhour<(twam+riseduration_red)) || (dayhour>(twpm-riseduration_red))) {
lights=0;
} else {
lights=1;
}
// now check if we are in sunrise
if ((dayhour>=twam) && (dayhour<(twam+riseduration_red))) {
riseordawn=1;
red=(dayhour-twam)*rperc;
if (dayhour>=(twam+(riseduration_red-riseduration_green))) {
green=(dayhour-(twam+(riseduration_red-riseduration_green)))*gperc;
}
if (dayhour>=(twam+(riseduration_red-riseduration_blue))) {
blue=(dayhour-(twam+(riseduration_red-riseduration_blue)))*bperc;
}
} else if ((dayhour>=(twpm-riseduration_red)) && (dayhour<=twpm)) {
// or are we in sunset
red=colorsteps-((dayhour-(twpm-riseduration_red))*rperc);
green=colorsteps-((dayhour-(twpm-riseduration_red))*gperc);
blue=colorsteps-((dayhour-(twpm-riseduration_red))*bperc);
riseordawn=1;
} else {
// or no twilight
riseordawn=0;
red=green=blue=0;
}
// failsafe if calculations took a wrong direction somewhere
if (red>colorsteps) { red=colorsteps; }
if (green>colorsteps) { green=colorsteps; }
if (blue>colorsteps) { blue=colorsteps; }
if (red<0) { red=0; }
if (green<0) { green=0; }
if (blue<0) { blue=0; }
// now write the calculated values into a file
writelightsettings(dayhour,lights,riseordawn,red,green,blue);
}
return 0;
}
<commit_msg>one hour time shift is better than two<commit_after>// Some part of the code is from
// jjlammi@netti.fi
// http://www.sci.fi/~benefon/rscalc_cpp.html
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
double pi = 3.141592653589793238463;
double tpi = 2 * pi;
double degs = 180.0/pi;
double rads = pi/180.0;
double L,g,daylen;
double SunDia = 0.53; // Sunradius degrees
double AirRefr = 34.0/60.0; // athmospheric refraction degrees //
// Get the days to J2000
// h is UT in decimal hours
// FNday only works between 1901 to 2099 - see Meeus chapter 7
double FNday (int y, int m, int d, float h) {
long int luku = - 7 * (y + (m + 9)/12)/4 + 275*m/9 + d;
// Typecasting needed for TClite on PC DOS at least, to avoid product overflow
luku+= (long int)y*367;
return (double)luku - 730531.5 + h/24.0;
};
// the function below returns an angle in the range
// 0 to 2*pi
double FNrange (double x) {
double b = x / tpi;
double a = tpi * (b - (long)(b));
if (a < 0) a = tpi + a;
return a;
};
// Calculating the hourangle
double f0(double lat, double declin) {
double fo,dfo;
// Correction: different sign at S HS
dfo = rads*(0.5*SunDia + AirRefr); if (lat < 0.0) dfo = -dfo;
fo = tan(declin + dfo) * tan(lat*rads);
if (fo > 0.99999) fo=1.0; // to avoid overflow //
fo = asin(fo) + pi/2.0;
return fo;
};
// Calculating the hourangle for twilight times
//
double f1(double lat, double declin) {
double fi,df1;
// Correction: different sign at S HS
df1 = rads * 6.0; if (lat < 0.0) df1 = -df1;
fi = tan(declin + df1) * tan(lat*rads);
if (fi > 0.99999) fi=1.0; // to avoid overflow //
fi = asin(fi) + pi/2.0;
return fi;
};
// Find the ecliptic longitude of the Sun
double FNsun (double d) {
// mean longitude of the Sun
L = FNrange(280.461 * rads + .9856474 * rads * d);
// mean anomaly of the Sun
g = FNrange(357.528 * rads + .9856003 * rads * d);
// Ecliptic longitude of the Sun
return FNrange(L + 1.915 * rads * sin(g) + .02 * rads * sin(2 * g));
};
// Display decimal hours in hours and minutes
void showhrmn(double dhr) {
int hr,mn;
hr=(int) dhr;
mn = (dhr - (double) hr)*60;
printf("%02d:%02d",hr,mn);
};
// Display decimal hours in hours and minutes, but return a string instead
string hhmm(double dhr) {
int hr,mn;
char buffer[10];
hr=(int) dhr;
mn = (dhr - (double) hr)*60;
snprintf(buffer,sizeof(buffer),"%02d%02d",hr,mn);
return buffer;
}
// Write the given values into a file. This is rather hacky but does the job.
void writelightsettings(double time,double lights, double riseordawn, double red,double green, double blue) {
char buffer[50];
ofstream filehandler;
string filename;
filename = hhmm(time);
snprintf(buffer,sizeof(buffer),"%1.0f %1.0f %1.5f %1.5f %1.5f\n",lights,riseordawn,red,green,blue);
filehandler.open(filename.c_str());
filehandler << buffer;
filehandler.close();
}
void writerisedawntimes(double dawnstart, double daystart, double daystop, double duskstop, double adstart, double adstop) {
ofstream filehandler;
string filename;
filename = "times";
filehandler.open(filename.c_str());
filehandler << hhmm(dawnstart) << "\n";
filehandler << hhmm(daystart) << "\n";
filehandler << hhmm(daystop) << "\n";
filehandler << hhmm(duskstop) << "\n";
filehandler << hhmm(adstart) << "\n";
filehandler << hhmm(adstop) << "\n";
filehandler.close();
}
int main(void) {
double y,m,day,h,latit,longit;
time_t sekunnit;
struct tm *p;
// get the date and time from the user
// read system date and extract the year
/** First get current time **/
time(&sekunnit);
/** Next get localtime **/
p=localtime(&sekunnit);
// this is Y2K compliant algorithm
y = 1900 + p->tm_year;
m = p->tm_mon + 1;
day = p->tm_mday;
h = 12;
// magdeburg
// latit = 52.8;
// madagascar
latit = 20.0;
// we leave longitude as it is, that will only affect time zone
longit= 11.37;
// we will go for utc
double tzone = 0;
double d = FNday(y, m, day, h);
// Use FNsun to find the ecliptic longitude of the
// Sun
double lambda = FNsun(d);
// Obliquity of the ecliptic
double obliq = 23.439 * rads - .0000004 * rads * d;
// Find the RA and DEC of the Sun
double alpha = atan2(cos(obliq) * sin(lambda), cos(lambda));
double delta = asin(sin(obliq) * sin(lambda));
// Find the Equation of Time in minutes
// Correction suggested by David Smith
double LL = L - alpha;
if (L < pi) LL += tpi;
double equation = 1440.0 * (1.0 - LL / tpi);
double ha = f0(latit,delta);
double hb = f1(latit,delta);
double twx = hb - ha; // length of twilight in radians
twx = 12.0*twx/pi; // length of twilight in degrees
// Conversion of angle to hours and minutes //
daylen = degs * ha / 7.5;
if (daylen<0.0001) {daylen = 0.0;}
// arctic winter //
double riset = 12.0 - 12.0 * ha/pi + tzone - longit/15.0 + equation/60.0;
double settm = 12.0 + 12.0 * ha/pi + tzone - longit/15.0 + equation/60.0;
// shift by one hour - that's to have the day of the terrarium more
// aligned to the day of the owners
riset+=1;
settm+=1;
double twam = riset - twx; // morning twilight begin
double twpm = settm + twx; // evening twilight end
if (riset > 24.0) riset-= 24.0;
if (settm > 24.0) settm-= 24.0;
// debug output
/*
printf("\n Sunrise and set\n");
printf("yyyy-mm-dd : %04.0f-%02.0f-%02.0f\n",y,m,day);
printf("Daylength : ");
showhrmn(daylen);
printf(" hours\n");
printf("Begin twilight: ");
showhrmn(twam);
printf("\nSunrise : ");
showhrmn(riset);
printf("\nSunset : ");
showhrmn(settm);
printf("\nEnd twiglight : ");
showhrmn(twpm);
printf("\n");
*/
// most of those values could be int, though...
int colorsteps=1;
double minutestep=1.0/60.0*1;
double dayhour=0;
double red=0,green=0,blue=0;
double lights=0,riseordawn=0;
double riseduration_red=1.5;
double riseduration_green=riseduration_red*0.8;
double riseduration_blue=riseduration_red*0.6;
double rperc=1/riseduration_red*colorsteps;
double gperc=1/riseduration_green*colorsteps;
double bperc=1/riseduration_blue*colorsteps;
double perc=0;
writerisedawntimes(twam,twam+riseduration_red,twpm-riseduration_red,twpm,riset,settm);
for (dayhour=0; dayhour<24; dayhour+=minutestep) {
// first check if the main lights should be turned on or off
if ((dayhour<(twam+riseduration_red)) || (dayhour>(twpm-riseduration_red))) {
lights=0;
} else {
lights=1;
}
// now check if we are in sunrise
if ((dayhour>=twam) && (dayhour<(twam+riseduration_red))) {
riseordawn=1;
red=(dayhour-twam)*rperc;
if (dayhour>=(twam+(riseduration_red-riseduration_green))) {
green=(dayhour-(twam+(riseduration_red-riseduration_green)))*gperc;
}
if (dayhour>=(twam+(riseduration_red-riseduration_blue))) {
blue=(dayhour-(twam+(riseduration_red-riseduration_blue)))*bperc;
}
} else if ((dayhour>=(twpm-riseduration_red)) && (dayhour<=twpm)) {
// or are we in sunset
red=colorsteps-((dayhour-(twpm-riseduration_red))*rperc);
green=colorsteps-((dayhour-(twpm-riseduration_red))*gperc);
blue=colorsteps-((dayhour-(twpm-riseduration_red))*bperc);
riseordawn=1;
} else {
// or no twilight
riseordawn=0;
red=green=blue=0;
}
// failsafe if calculations took a wrong direction somewhere
if (red>colorsteps) { red=colorsteps; }
if (green>colorsteps) { green=colorsteps; }
if (blue>colorsteps) { blue=colorsteps; }
if (red<0) { red=0; }
if (green<0) { green=0; }
if (blue<0) { blue=0; }
// now write the calculated values into a file
writelightsettings(dayhour,lights,riseordawn,red,green,blue);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <condition_variable>
#include "cpp_redis/network/tcp_client.hpp"
namespace cpp_redis {
namespace network {
io_service tcp_client::m_io_service;
tcp_client::tcp_client(void)
: m_socket(m_io_service.get())
, m_is_connected(false)
, m_read_buffer(READ_SIZE) {}
tcp_client::~tcp_client(void) {
if (m_is_connected)
disconnect();
}
void
tcp_client::connect(const std::string& host, unsigned int port) {
if (m_is_connected)
throw redis_error("Already connected");
std::condition_variable conn_cond_var;
//! resolve host name
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
//! async connect
m_socket.async_connect(endpoint, [&](boost::system::error_code error) {
if (not error) {
m_is_connected = true;
async_read();
}
conn_cond_var.notify_one();
});
//! start loop and wait for async connect result
std::mutex conn_mutex;
std::unique_lock<std::mutex> lock(conn_mutex);
m_io_service.run();
conn_cond_var.wait(lock);
if (not m_is_connected)
throw redis_error("Fail to connect to " + host + ":" + std::to_string(port));
}
void
tcp_client::disconnect(void) {
if (not m_is_connected)
throw redis_error("Not connected");
m_is_connected = false;
std::mutex close_socket_mutex;
std::condition_variable close_socket_cond_var;
std::unique_lock<std::mutex> lock(close_socket_mutex);
m_io_service.post([this, &close_socket_cond_var]() {
m_socket.close();
close_socket_cond_var.notify_one();
});
close_socket_cond_var.wait(lock);
}
void
tcp_client::async_read(void) {
boost::asio::async_read(m_socket, boost::asio::buffer(m_read_buffer.data(), READ_SIZE),
[](const boost::system::error_code& error, std::size_t bytes) -> std::size_t {
//! break if bytes have been received, continue otherwise
return error or bytes ? 0 : READ_SIZE;
},
[=](boost::system::error_code error, std::size_t length) {
if (error) {
process_disconnection();
return ;
}
std::lock_guard<std::mutex> lock(m_receive_handler_mutex);
if (m_receive_handler)
if (not m_receive_handler(*this, { m_read_buffer.begin(), m_read_buffer.begin() + length })) {
process_disconnection();
return ;
}
//! keep waiting for incoming bytes
async_read();
});
}
void
tcp_client::send(const std::string& buffer) {
send(std::vector<char>{ buffer.begin(), buffer.end() });
}
void
tcp_client::send(const std::vector<char>& buffer) {
if (not m_is_connected)
throw redis_error("Not connected");
if (not buffer.size())
return ;
std::lock_guard<std::mutex> lock(m_write_buffer_mutex);
bool bytes_in_buffer = m_write_buffer.size() > 0;
//! concat buffer
m_write_buffer.insert(m_write_buffer.end(), buffer.begin(), buffer.end());
//! if there were already bytes in buffer, simply return
//! async_write callback will process the new buffer
if (bytes_in_buffer)
return;
async_write();
}
void
tcp_client::async_write(void) {
boost::asio::async_write(m_socket, boost::asio::buffer(m_write_buffer.data(), m_write_buffer.size()),
[this](boost::system::error_code error, std::size_t length) {
if (error) {
process_disconnection();
return ;
}
std::lock_guard<std::mutex> lock(m_write_buffer_mutex);
m_write_buffer.erase(m_write_buffer.begin(), m_write_buffer.begin() + length);
if (m_write_buffer.size())
async_write();
});
}
void
tcp_client::process_disconnection(void) {
m_is_connected = false;
m_socket.close();
std::lock_guard<std::mutex> lock(m_disconnection_handler_mutex);
if (m_disconnection_handler)
m_disconnection_handler(*this);
}
void
tcp_client::set_receive_handler(const receive_handler& handler) {
std::lock_guard<std::mutex> lock(m_receive_handler_mutex);
m_receive_handler = handler;
}
void
tcp_client::set_disconnection_handler(const disconnection_handler& handler) {
std::lock_guard<std::mutex> lock(m_disconnection_handler_mutex);
m_disconnection_handler = handler;
}
bool
tcp_client::is_connected(void) {
return m_is_connected;
}
} //! network
} //! cpp_redis
<commit_msg>#4 add is_notified atomic variable to avoid locking is conditional variable has already been notified<commit_after>#include <condition_variable>
#include "cpp_redis/network/tcp_client.hpp"
namespace cpp_redis {
namespace network {
io_service tcp_client::m_io_service;
tcp_client::tcp_client(void)
: m_socket(m_io_service.get())
, m_is_connected(false)
, m_read_buffer(READ_SIZE) {}
tcp_client::~tcp_client(void) {
if (m_is_connected)
disconnect();
}
void
tcp_client::connect(const std::string& host, unsigned int port) {
if (m_is_connected)
throw redis_error("Already connected");
std::condition_variable conn_cond_var;
//! resolve host name
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
//! async connect
std::atomic_bool is_notified(false);
m_socket.async_connect(endpoint, [&](boost::system::error_code error) {
if (not error) {
m_is_connected = true;
async_read();
}
is_notified = true;
conn_cond_var.notify_one();
});
//! start loop and wait for async connect result
std::mutex conn_mutex;
std::unique_lock<std::mutex> lock(conn_mutex);
m_io_service.run();
if (not is_notified)
conn_cond_var.wait(lock);
if (not m_is_connected)
throw redis_error("Fail to connect to " + host + ":" + std::to_string(port));
}
void
tcp_client::disconnect(void) {
if (not m_is_connected)
throw redis_error("Not connected");
m_is_connected = false;
std::mutex close_socket_mutex;
std::condition_variable close_socket_cond_var;
std::unique_lock<std::mutex> lock(close_socket_mutex);
std::atomic_bool is_notified(false);
m_io_service.post([this, &close_socket_cond_var, &is_notified]() {
m_socket.close();
is_notified = true;
close_socket_cond_var.notify_one();
});
if (not is_notified)
close_socket_cond_var.wait(lock);
}
void
tcp_client::async_read(void) {
boost::asio::async_read(m_socket, boost::asio::buffer(m_read_buffer.data(), READ_SIZE),
[](const boost::system::error_code& error, std::size_t bytes) -> std::size_t {
//! break if bytes have been received, continue otherwise
return error or bytes ? 0 : READ_SIZE;
},
[=](boost::system::error_code error, std::size_t length) {
if (error) {
process_disconnection();
return ;
}
std::lock_guard<std::mutex> lock(m_receive_handler_mutex);
if (m_receive_handler)
if (not m_receive_handler(*this, { m_read_buffer.begin(), m_read_buffer.begin() + length })) {
process_disconnection();
return ;
}
//! keep waiting for incoming bytes
async_read();
});
}
void
tcp_client::send(const std::string& buffer) {
send(std::vector<char>{ buffer.begin(), buffer.end() });
}
void
tcp_client::send(const std::vector<char>& buffer) {
if (not m_is_connected)
throw redis_error("Not connected");
if (not buffer.size())
return ;
std::lock_guard<std::mutex> lock(m_write_buffer_mutex);
bool bytes_in_buffer = m_write_buffer.size() > 0;
//! concat buffer
m_write_buffer.insert(m_write_buffer.end(), buffer.begin(), buffer.end());
//! if there were already bytes in buffer, simply return
//! async_write callback will process the new buffer
if (bytes_in_buffer)
return;
async_write();
}
void
tcp_client::async_write(void) {
boost::asio::async_write(m_socket, boost::asio::buffer(m_write_buffer.data(), m_write_buffer.size()),
[this](boost::system::error_code error, std::size_t length) {
if (error) {
process_disconnection();
return ;
}
std::lock_guard<std::mutex> lock(m_write_buffer_mutex);
m_write_buffer.erase(m_write_buffer.begin(), m_write_buffer.begin() + length);
if (m_write_buffer.size())
async_write();
});
}
void
tcp_client::process_disconnection(void) {
m_is_connected = false;
m_socket.close();
std::lock_guard<std::mutex> lock(m_disconnection_handler_mutex);
if (m_disconnection_handler)
m_disconnection_handler(*this);
}
void
tcp_client::set_receive_handler(const receive_handler& handler) {
std::lock_guard<std::mutex> lock(m_receive_handler_mutex);
m_receive_handler = handler;
}
void
tcp_client::set_disconnection_handler(const disconnection_handler& handler) {
std::lock_guard<std::mutex> lock(m_disconnection_handler_mutex);
m_disconnection_handler = handler;
}
bool
tcp_client::is_connected(void) {
return m_is_connected;
}
} //! network
} //! cpp_redis
<|endoftext|>
|
<commit_before>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-10-30 GONG Chen <chen.sst@gmail.com>
//
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/schema.h>
#include <rime/impl/syllablizer.h>
#include <rime/impl/user_db.h>
#include <rime/impl/user_dictionary.h>
namespace rime {
// UserDictionary members
UserDictionary::UserDictionary(const shared_ptr<UserDb> &user_db)
: db_(user_db), tick_(0) {
}
UserDictionary::~UserDictionary() {
}
void UserDictionary::Attach(const shared_ptr<Table> &table, const shared_ptr<Prism> &prism) {
table_ = table;
prism_ = prism;
}
bool UserDictionary::Load() {
if (!db_ || !db_->Open())
return false;
if (!GetTickCount() && !Initialize())
return false;
return true;
}
bool UserDictionary::loaded() const {
return db_ && db_->loaded();
}
shared_ptr<UserDictEntryCollector> UserDictionary::Lookup(const SyllableGraph &syllable_graph, int start_pos) {
if (!table_ || !prism_ || !loaded())
return shared_ptr<UserDictEntryCollector>();
shared_ptr<UserDictEntryCollector> collector(new UserDictEntryCollector);
// TODO:
return collector;
}
bool UserDictionary::UpdateEntry(const DictEntry &entry, int commit) {
std::string code_str(TranslateCodeToString(entry.code));
std::string key(code_str + " " + entry.text);
double weight = entry.weight;
int commit_count = entry.commit_count;
if (commit > 0) {
// TODO:
weight += commit;
commit_count += commit;
}
else if (commit < 0) {
commit_count = (std::min)(-1, -commit_count);
}
std::string value(boost::str(boost::format("c=%1% w=%2% t=%3%") % commit_count % weight % tick_));
return db_->Update(key, value);
}
bool UserDictionary::UpdateTickCount(TickCount increment) {
tick_ += increment;
try {
return db_->Update("\0x01/tick", boost::lexical_cast<std::string>(tick_));
}
catch (...) {
return false;
}
}
bool UserDictionary::Initialize() {
// TODO:
return db_->Update("\0x01/tick", "0");
}
bool UserDictionary::FetchTickCount() {
std::string value;
try {
if (!db_->Fetch("\0x1/tick", &value))
return false;
tick_ = boost::lexical_cast<TickCount>(value);
return true;
}
catch (...) {
tick_ = 0;
return false;
}
}
const std::string UserDictionary::TranslateCodeToString(const Code &code) {
// TODO:
return "TODO";
}
// UserDictionaryComponent members
UserDictionaryComponent::UserDictionaryComponent() {
}
UserDictionary* UserDictionaryComponent::Create(Schema *schema) {
if (!schema) return NULL;
Config *config = schema->config();
const std::string &schema_id(schema->schema_id());
std::string dict_name;
if (!config->GetString("translator/dictionary", &dict_name)) {
EZLOGGERPRINT("Error: dictionary not specified in schema '%s'.",
schema_id.c_str());
return NULL;
}
// obtain userdb object
shared_ptr<UserDb> user_db(user_db_pool_[dict_name].lock());
if (!user_db) {
user_db.reset(new UserDb(dict_name));
user_db_pool_[dict_name] = user_db;
}
return new UserDictionary(user_db);
}
} // namespace rime
<commit_msg>Updated Weasel build instructions; uploaded vs2008 patch to kyotocabinet.<commit_after>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-10-30 GONG Chen <chen.sst@gmail.com>
//
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/schema.h>
#include <rime/impl/syllablizer.h>
#include <rime/impl/user_db.h>
#include <rime/impl/user_dictionary.h>
namespace rime {
// UserDictionary members
UserDictionary::UserDictionary(const shared_ptr<UserDb> &user_db)
: db_(user_db), tick_(0) {
}
UserDictionary::~UserDictionary() {
}
void UserDictionary::Attach(const shared_ptr<Table> &table, const shared_ptr<Prism> &prism) {
table_ = table;
prism_ = prism;
}
bool UserDictionary::Load() {
if (!db_ || !db_->Open())
return false;
if (!GetTickCount() && !Initialize())
return false;
return true;
}
bool UserDictionary::loaded() const {
return db_ && db_->loaded();
}
shared_ptr<UserDictEntryCollector> UserDictionary::Lookup(const SyllableGraph &syllable_graph, int start_pos) {
if (!table_ || !prism_ || !loaded())
return shared_ptr<UserDictEntryCollector>();
shared_ptr<UserDictEntryCollector> collector(new UserDictEntryCollector);
// TODO:
return collector;
}
bool UserDictionary::UpdateEntry(const DictEntry &entry, int commit) {
std::string code_str(TranslateCodeToString(entry.code));
std::string key(code_str + " " + entry.text);
double weight = entry.weight;
int commit_count = entry.commit_count;
if (commit > 0) {
// TODO:
weight += commit;
commit_count += commit;
}
else if (commit < 0) {
commit_count = (std::min)(-1, -commit_count);
}
std::string value(boost::str(boost::format("c=%1% w=%2% t=%3%") % commit_count % weight % tick_));
return db_->Update(key, value);
}
bool UserDictionary::UpdateTickCount(TickCount increment) {
tick_ += increment;
try {
return db_->Update("\0x01/tick", boost::lexical_cast<std::string>(tick_));
}
catch (...) {
return false;
}
}
bool UserDictionary::Initialize() {
// TODO:
return db_->Update("\0x01/tick", "0");
}
bool UserDictionary::FetchTickCount() {
std::string value;
try {
if (!db_->Fetch("\0x01/tick", &value))
return false;
tick_ = boost::lexical_cast<TickCount>(value);
return true;
}
catch (...) {
tick_ = 0;
return false;
}
}
const std::string UserDictionary::TranslateCodeToString(const Code &code) {
// TODO:
return "TODO";
}
// UserDictionaryComponent members
UserDictionaryComponent::UserDictionaryComponent() {
}
UserDictionary* UserDictionaryComponent::Create(Schema *schema) {
if (!schema) return NULL;
Config *config = schema->config();
const std::string &schema_id(schema->schema_id());
std::string dict_name;
if (!config->GetString("translator/dictionary", &dict_name)) {
EZLOGGERPRINT("Error: dictionary not specified in schema '%s'.",
schema_id.c_str());
return NULL;
}
// obtain userdb object
shared_ptr<UserDb> user_db(user_db_pool_[dict_name].lock());
if (!user_db) {
user_db.reset(new UserDb(dict_name));
user_db_pool_[dict_name] = user_db;
}
return new UserDictionary(user_db);
}
} // namespace rime
<|endoftext|>
|
<commit_before>/*
* Ceph string constants
*/
#include "types.h"
const char *ceph_entity_type_name(int type)
{
switch (type) {
case CEPH_ENTITY_TYPE_MDS: return "mds";
case CEPH_ENTITY_TYPE_OSD: return "osd";
case CEPH_ENTITY_TYPE_MON: return "mon";
case CEPH_ENTITY_TYPE_CLIENT: return "client";
case CEPH_ENTITY_TYPE_AUTH: return "auth";
default: return "unknown";
}
}
const char *ceph_osd_op_name(int op)
{
switch (op) {
case CEPH_OSD_OP_READ: return "read";
case CEPH_OSD_OP_STAT: return "stat";
case CEPH_OSD_OP_MASKTRUNC: return "masktrunc";
case CEPH_OSD_OP_WRITE: return "write";
case CEPH_OSD_OP_DELETE: return "delete";
case CEPH_OSD_OP_TRUNCATE: return "truncate";
case CEPH_OSD_OP_ZERO: return "zero";
case CEPH_OSD_OP_WRITEFULL: return "writefull";
case CEPH_OSD_OP_APPEND: return "append";
case CEPH_OSD_OP_STARTSYNC: return "startsync";
case CEPH_OSD_OP_SETTRUNC: return "settrunc";
case CEPH_OSD_OP_TRIMTRUNC: return "trimtrunc";
case CEPH_OSD_OP_TMAPUP: return "tmapup";
case CEPH_OSD_OP_TMAPGET: return "tmapget";
case CEPH_OSD_OP_TMAPPUT: return "tmapput";
case CEPH_OSD_OP_GETXATTR: return "getxattr";
case CEPH_OSD_OP_GETXATTRS: return "getxattrs";
case CEPH_OSD_OP_SETXATTR: return "setxattr";
case CEPH_OSD_OP_SETXATTRS: return "setxattrs";
case CEPH_OSD_OP_RESETXATTRS: return "resetxattrs";
case CEPH_OSD_OP_RMXATTR: return "rmxattr";
case CEPH_OSD_OP_CMPXATTR: return "cmpxattr";
case CEPH_OSD_OP_PULL: return "pull";
case CEPH_OSD_OP_PUSH: return "push";
case CEPH_OSD_OP_BALANCEREADS: return "balance-reads";
case CEPH_OSD_OP_UNBALANCEREADS: return "unbalance-reads";
case CEPH_OSD_OP_SCRUB: return "scrub";
case CEPH_OSD_OP_WRLOCK: return "wrlock";
case CEPH_OSD_OP_WRUNLOCK: return "wrunlock";
case CEPH_OSD_OP_RDLOCK: return "rdlock";
case CEPH_OSD_OP_RDUNLOCK: return "rdunlock";
case CEPH_OSD_OP_UPLOCK: return "uplock";
case CEPH_OSD_OP_DNLOCK: return "dnlock";
case CEPH_OSD_OP_CALL: return "call";
case CEPH_OSD_OP_PGLS: return "pgls";
}
return "???";
}
const char *ceph_mds_state_name(int s)
{
switch (s) {
/* down and out */
case CEPH_MDS_STATE_DNE: return "down:dne";
case CEPH_MDS_STATE_STOPPED: return "down:stopped";
/* up and out */
case CEPH_MDS_STATE_BOOT: return "up:boot";
case CEPH_MDS_STATE_STANDBY: return "up:standby";
case CEPH_MDS_STATE_STANDBY_REPLAY: return "up:standby-replay";
case CEPH_MDS_STATE_CREATING: return "up:creating";
case CEPH_MDS_STATE_STARTING: return "up:starting";
/* up and in */
case CEPH_MDS_STATE_REPLAY: return "up:replay";
case CEPH_MDS_STATE_RESOLVE: return "up:resolve";
case CEPH_MDS_STATE_RECONNECT: return "up:reconnect";
case CEPH_MDS_STATE_REJOIN: return "up:rejoin";
case CEPH_MDS_STATE_CLIENTREPLAY: return "up:clientreplay";
case CEPH_MDS_STATE_ACTIVE: return "up:active";
case CEPH_MDS_STATE_STOPPING: return "up:stopping";
}
return "???";
}
const char *ceph_session_op_name(int op)
{
switch (op) {
case CEPH_SESSION_REQUEST_OPEN: return "request_open";
case CEPH_SESSION_OPEN: return "open";
case CEPH_SESSION_REQUEST_CLOSE: return "request_close";
case CEPH_SESSION_CLOSE: return "close";
case CEPH_SESSION_REQUEST_RENEWCAPS: return "request_renewcaps";
case CEPH_SESSION_RENEWCAPS: return "renewcaps";
case CEPH_SESSION_STALE: return "stale";
case CEPH_SESSION_RECALL_STATE: return "recall_state";
}
return "???";
}
const char *ceph_mds_op_name(int op)
{
switch (op) {
case CEPH_MDS_OP_LOOKUP: return "lookup";
case CEPH_MDS_OP_LOOKUPHASH: return "lookuphash";
case CEPH_MDS_OP_LOOKUPPARENT: return "lookupparent";
case CEPH_MDS_OP_GETATTR: return "getattr";
case CEPH_MDS_OP_SETXATTR: return "setxattr";
case CEPH_MDS_OP_SETATTR: return "setattr";
case CEPH_MDS_OP_RMXATTR: return "rmxattr";
case CEPH_MDS_OP_READDIR: return "readdir";
case CEPH_MDS_OP_MKNOD: return "mknod";
case CEPH_MDS_OP_LINK: return "link";
case CEPH_MDS_OP_UNLINK: return "unlink";
case CEPH_MDS_OP_RENAME: return "rename";
case CEPH_MDS_OP_MKDIR: return "mkdir";
case CEPH_MDS_OP_RMDIR: return "rmdir";
case CEPH_MDS_OP_SYMLINK: return "symlink";
case CEPH_MDS_OP_CREATE: return "create";
case CEPH_MDS_OP_OPEN: return "open";
case CEPH_MDS_OP_LOOKUPSNAP: return "lookupsnap";
case CEPH_MDS_OP_LSSNAP: return "lssnap";
case CEPH_MDS_OP_MKSNAP: return "mksnap";
case CEPH_MDS_OP_RMSNAP: return "rmsnap";
}
return "???";
}
const char *ceph_cap_op_name(int op)
{
switch (op) {
case CEPH_CAP_OP_GRANT: return "grant";
case CEPH_CAP_OP_REVOKE: return "revoke";
case CEPH_CAP_OP_TRUNC: return "trunc";
case CEPH_CAP_OP_EXPORT: return "export";
case CEPH_CAP_OP_IMPORT: return "import";
case CEPH_CAP_OP_UPDATE: return "update";
case CEPH_CAP_OP_DROP: return "drop";
case CEPH_CAP_OP_FLUSH: return "flush";
case CEPH_CAP_OP_FLUSH_ACK: return "flush_ack";
case CEPH_CAP_OP_FLUSHSNAP: return "flushsnap";
case CEPH_CAP_OP_FLUSHSNAP_ACK: return "flushsnap_ack";
case CEPH_CAP_OP_RELEASE: return "release";
case CEPH_CAP_OP_RENEW: return "renew";
}
return "???";
}
const char *ceph_lease_op_name(int o)
{
switch (o) {
case CEPH_MDS_LEASE_REVOKE: return "revoke";
case CEPH_MDS_LEASE_RELEASE: return "release";
case CEPH_MDS_LEASE_RENEW: return "renew";
case CEPH_MDS_LEASE_REVOKE_ACK: return "revoke_ack";
}
return "???";
}
const char *ceph_snap_op_name(int o)
{
switch (o) {
case CEPH_SNAP_OP_UPDATE: return "update";
case CEPH_SNAP_OP_CREATE: return "create";
case CEPH_SNAP_OP_DESTROY: return "destroy";
case CEPH_SNAP_OP_SPLIT: return "split";
}
return "???";
}
const char *ceph_pool_op_name(int op) {
switch (op) {
case POOL_OP_CREATE:
return "create pool";
case POOL_OP_DELETE:
return "delete pool";
case POOL_OP_AUID_CHANGE:
return "change auid";
case POOL_OP_CREATE_SNAP:
return "create snap";
case POOL_OP_DELETE_SNAP:
return "delete snap";
case POOL_OP_CREATE_UNMANAGED_SNAP:
return "create unmanaged snap";
case POOL_OP_DELETE_UNMANAGED_SNAP:
return "delete unmanaged snap";
default:
return "unknown";
}
}
<commit_msg>ceph_strings: checkpatch fix<commit_after>/*
* Ceph string constants
*/
#include "types.h"
const char *ceph_entity_type_name(int type)
{
switch (type) {
case CEPH_ENTITY_TYPE_MDS: return "mds";
case CEPH_ENTITY_TYPE_OSD: return "osd";
case CEPH_ENTITY_TYPE_MON: return "mon";
case CEPH_ENTITY_TYPE_CLIENT: return "client";
case CEPH_ENTITY_TYPE_AUTH: return "auth";
default: return "unknown";
}
}
const char *ceph_osd_op_name(int op)
{
switch (op) {
case CEPH_OSD_OP_READ: return "read";
case CEPH_OSD_OP_STAT: return "stat";
case CEPH_OSD_OP_MASKTRUNC: return "masktrunc";
case CEPH_OSD_OP_WRITE: return "write";
case CEPH_OSD_OP_DELETE: return "delete";
case CEPH_OSD_OP_TRUNCATE: return "truncate";
case CEPH_OSD_OP_ZERO: return "zero";
case CEPH_OSD_OP_WRITEFULL: return "writefull";
case CEPH_OSD_OP_APPEND: return "append";
case CEPH_OSD_OP_STARTSYNC: return "startsync";
case CEPH_OSD_OP_SETTRUNC: return "settrunc";
case CEPH_OSD_OP_TRIMTRUNC: return "trimtrunc";
case CEPH_OSD_OP_TMAPUP: return "tmapup";
case CEPH_OSD_OP_TMAPGET: return "tmapget";
case CEPH_OSD_OP_TMAPPUT: return "tmapput";
case CEPH_OSD_OP_GETXATTR: return "getxattr";
case CEPH_OSD_OP_GETXATTRS: return "getxattrs";
case CEPH_OSD_OP_SETXATTR: return "setxattr";
case CEPH_OSD_OP_SETXATTRS: return "setxattrs";
case CEPH_OSD_OP_RESETXATTRS: return "resetxattrs";
case CEPH_OSD_OP_RMXATTR: return "rmxattr";
case CEPH_OSD_OP_CMPXATTR: return "cmpxattr";
case CEPH_OSD_OP_PULL: return "pull";
case CEPH_OSD_OP_PUSH: return "push";
case CEPH_OSD_OP_BALANCEREADS: return "balance-reads";
case CEPH_OSD_OP_UNBALANCEREADS: return "unbalance-reads";
case CEPH_OSD_OP_SCRUB: return "scrub";
case CEPH_OSD_OP_WRLOCK: return "wrlock";
case CEPH_OSD_OP_WRUNLOCK: return "wrunlock";
case CEPH_OSD_OP_RDLOCK: return "rdlock";
case CEPH_OSD_OP_RDUNLOCK: return "rdunlock";
case CEPH_OSD_OP_UPLOCK: return "uplock";
case CEPH_OSD_OP_DNLOCK: return "dnlock";
case CEPH_OSD_OP_CALL: return "call";
case CEPH_OSD_OP_PGLS: return "pgls";
}
return "???";
}
const char *ceph_mds_state_name(int s)
{
switch (s) {
/* down and out */
case CEPH_MDS_STATE_DNE: return "down:dne";
case CEPH_MDS_STATE_STOPPED: return "down:stopped";
/* up and out */
case CEPH_MDS_STATE_BOOT: return "up:boot";
case CEPH_MDS_STATE_STANDBY: return "up:standby";
case CEPH_MDS_STATE_STANDBY_REPLAY: return "up:standby-replay";
case CEPH_MDS_STATE_CREATING: return "up:creating";
case CEPH_MDS_STATE_STARTING: return "up:starting";
/* up and in */
case CEPH_MDS_STATE_REPLAY: return "up:replay";
case CEPH_MDS_STATE_RESOLVE: return "up:resolve";
case CEPH_MDS_STATE_RECONNECT: return "up:reconnect";
case CEPH_MDS_STATE_REJOIN: return "up:rejoin";
case CEPH_MDS_STATE_CLIENTREPLAY: return "up:clientreplay";
case CEPH_MDS_STATE_ACTIVE: return "up:active";
case CEPH_MDS_STATE_STOPPING: return "up:stopping";
}
return "???";
}
const char *ceph_session_op_name(int op)
{
switch (op) {
case CEPH_SESSION_REQUEST_OPEN: return "request_open";
case CEPH_SESSION_OPEN: return "open";
case CEPH_SESSION_REQUEST_CLOSE: return "request_close";
case CEPH_SESSION_CLOSE: return "close";
case CEPH_SESSION_REQUEST_RENEWCAPS: return "request_renewcaps";
case CEPH_SESSION_RENEWCAPS: return "renewcaps";
case CEPH_SESSION_STALE: return "stale";
case CEPH_SESSION_RECALL_STATE: return "recall_state";
}
return "???";
}
const char *ceph_mds_op_name(int op)
{
switch (op) {
case CEPH_MDS_OP_LOOKUP: return "lookup";
case CEPH_MDS_OP_LOOKUPHASH: return "lookuphash";
case CEPH_MDS_OP_LOOKUPPARENT: return "lookupparent";
case CEPH_MDS_OP_GETATTR: return "getattr";
case CEPH_MDS_OP_SETXATTR: return "setxattr";
case CEPH_MDS_OP_SETATTR: return "setattr";
case CEPH_MDS_OP_RMXATTR: return "rmxattr";
case CEPH_MDS_OP_READDIR: return "readdir";
case CEPH_MDS_OP_MKNOD: return "mknod";
case CEPH_MDS_OP_LINK: return "link";
case CEPH_MDS_OP_UNLINK: return "unlink";
case CEPH_MDS_OP_RENAME: return "rename";
case CEPH_MDS_OP_MKDIR: return "mkdir";
case CEPH_MDS_OP_RMDIR: return "rmdir";
case CEPH_MDS_OP_SYMLINK: return "symlink";
case CEPH_MDS_OP_CREATE: return "create";
case CEPH_MDS_OP_OPEN: return "open";
case CEPH_MDS_OP_LOOKUPSNAP: return "lookupsnap";
case CEPH_MDS_OP_LSSNAP: return "lssnap";
case CEPH_MDS_OP_MKSNAP: return "mksnap";
case CEPH_MDS_OP_RMSNAP: return "rmsnap";
}
return "???";
}
const char *ceph_cap_op_name(int op)
{
switch (op) {
case CEPH_CAP_OP_GRANT: return "grant";
case CEPH_CAP_OP_REVOKE: return "revoke";
case CEPH_CAP_OP_TRUNC: return "trunc";
case CEPH_CAP_OP_EXPORT: return "export";
case CEPH_CAP_OP_IMPORT: return "import";
case CEPH_CAP_OP_UPDATE: return "update";
case CEPH_CAP_OP_DROP: return "drop";
case CEPH_CAP_OP_FLUSH: return "flush";
case CEPH_CAP_OP_FLUSH_ACK: return "flush_ack";
case CEPH_CAP_OP_FLUSHSNAP: return "flushsnap";
case CEPH_CAP_OP_FLUSHSNAP_ACK: return "flushsnap_ack";
case CEPH_CAP_OP_RELEASE: return "release";
case CEPH_CAP_OP_RENEW: return "renew";
}
return "???";
}
const char *ceph_lease_op_name(int o)
{
switch (o) {
case CEPH_MDS_LEASE_REVOKE: return "revoke";
case CEPH_MDS_LEASE_RELEASE: return "release";
case CEPH_MDS_LEASE_RENEW: return "renew";
case CEPH_MDS_LEASE_REVOKE_ACK: return "revoke_ack";
}
return "???";
}
const char *ceph_snap_op_name(int o)
{
switch (o) {
case CEPH_SNAP_OP_UPDATE: return "update";
case CEPH_SNAP_OP_CREATE: return "create";
case CEPH_SNAP_OP_DESTROY: return "destroy";
case CEPH_SNAP_OP_SPLIT: return "split";
}
return "???";
}
const char *ceph_pool_op_name(int op)
{
switch (op) {
case POOL_OP_CREATE:
return "create pool";
case POOL_OP_DELETE:
return "delete pool";
case POOL_OP_AUID_CHANGE:
return "change auid";
case POOL_OP_CREATE_SNAP:
return "create snap";
case POOL_OP_DELETE_SNAP:
return "delete snap";
case POOL_OP_CREATE_UNMANAGED_SNAP:
return "create unmanaged snap";
case POOL_OP_DELETE_UNMANAGED_SNAP:
return "delete unmanaged snap";
default:
return "unknown";
}
}
<|endoftext|>
|
<commit_before>/*
* Concatenate several istreams.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_cat.hxx"
#include "istream_internal.hxx"
#include "util/Cast.hxx"
#include <assert.h>
#include <stdarg.h>
struct CatIstream;
struct CatInput {
CatIstream *cat;
struct istream *istream;
};
struct CatIstream {
struct istream output;
bool reading;
unsigned current, num;
CatInput inputs[1];
CatInput &GetCurrent() {
return inputs[current];
}
const CatInput &GetCurrent() const {
return inputs[current];
}
bool IsCurrent(const CatInput &input) const {
return &GetCurrent() == &input;
}
CatInput &Shift() {
return inputs[current++];
}
bool IsEOF() const {
return current == num;
}
void CloseAllInputs() {
while (!IsEOF()) {
auto &input = Shift();
if (input.istream != nullptr)
istream_close_handler(input.istream);
}
}
};
/*
* istream handler
*
*/
static size_t
cat_input_data(const void *data, size_t length, void *ctx)
{
auto *input = (CatInput *)ctx;
CatIstream *cat = input->cat;
assert(input->istream != nullptr);
if (!cat->IsCurrent(*input))
return 0;
return istream_invoke_data(&cat->output, data, length);
}
static ssize_t
cat_input_direct(FdType type, int fd, size_t max_length,
void *ctx)
{
auto *input = (CatInput *)ctx;
CatIstream *cat = input->cat;
assert(input->istream != nullptr);
assert(cat->IsCurrent(*input));
return istream_invoke_direct(&cat->output, type, fd, max_length);
}
static void
cat_input_eof(void *ctx)
{
auto *input = (CatInput *)ctx;
CatIstream *cat = input->cat;
assert(input->istream != nullptr);
input->istream = nullptr;
if (cat->IsCurrent(*input)) {
do {
cat->Shift();
} while (!cat->IsEOF() && cat->GetCurrent().istream == nullptr);
if (cat->IsEOF()) {
istream_deinit_eof(&cat->output);
} else if (!cat->reading) {
/* only call istream_read() if this function was not
called from istream_cat_read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
istream_read(cat->GetCurrent().istream);
}
}
}
static void
cat_input_abort(GError *error, void *ctx)
{
auto *input = (CatInput *)ctx;
CatIstream *cat = input->cat;
assert(input->istream != nullptr);
input->istream = nullptr;
cat->CloseAllInputs();
istream_deinit_abort(&cat->output, error);
}
static const struct istream_handler cat_input_handler = {
.data = cat_input_data,
.direct = cat_input_direct,
.eof = cat_input_eof,
.abort = cat_input_abort,
};
/*
* istream implementation
*
*/
static inline CatIstream *
istream_to_cat(struct istream *istream)
{
return &ContainerCast2(*istream, &CatIstream::output);
}
static off_t
istream_cat_available(struct istream *istream, bool partial)
{
CatIstream *cat = istream_to_cat(istream);
off_t available = 0;
for (auto *input = &cat->GetCurrent(), *end = &cat->inputs[cat->num];
input < end; ++input) {
if (input->istream == nullptr)
continue;
const off_t a = istream_available(input->istream, partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
static void
istream_cat_read(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
pool_ref(cat->output.pool);
cat->reading = true;
unsigned prev;
do {
while (!cat->IsEOF() && cat->GetCurrent().istream == nullptr)
++cat->current;
if (cat->IsEOF()) {
istream_deinit_eof(&cat->output);
break;
}
istream_handler_set_direct(cat->GetCurrent().istream,
cat->output.handler_direct);
prev = cat->current;
istream_read(cat->GetCurrent().istream);
} while (!cat->IsEOF() && cat->current != prev);
cat->reading = false;
pool_unref(cat->output.pool);
}
static int
istream_cat_as_fd(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (cat->current != cat->num - 1)
/* not on last input */
return -1;
auto &i = cat->GetCurrent();
int fd = istream_as_fd(i.istream);
if (fd >= 0)
istream_deinit(&cat->output);
return fd;
}
static void
istream_cat_close(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
cat->CloseAllInputs();
istream_deinit(&cat->output);
}
static const struct istream_class istream_cat = {
.available = istream_cat_available,
.read = istream_cat_read,
.as_fd = istream_cat_as_fd,
.close = istream_cat_close,
};
/*
* constructor
*
*/
struct istream *
istream_cat_new(struct pool *pool, ...)
{
unsigned num = 0;
va_list ap;
va_start(ap, pool);
while (va_arg(ap, struct istream *) != nullptr)
++num;
va_end(ap);
assert(num > 0);
CatIstream *cat = (CatIstream *)
istream_new(pool, &istream_cat,
sizeof(*cat) + (num - 1) * sizeof(cat->inputs));
cat->reading = false;
cat->current = 0;
cat->num = num;
va_start(ap, pool);
num = 0;
struct istream *istream;
while ((istream = va_arg(ap, struct istream *)) != nullptr) {
assert(!istream_has_handler(istream));
CatInput *input = &cat->inputs[num++];
input->cat = cat;
istream_assign_handler(&input->istream, istream,
&cat_input_handler, input,
0);
}
va_end(ap);
return &cat->output;
}
<commit_msg>istream_cat: use MakeIstreamHandler<commit_after>/*
* Concatenate several istreams.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_cat.hxx"
#include "istream_oo.hxx"
#include "util/Cast.hxx"
#include <assert.h>
#include <stdarg.h>
struct CatIstream;
struct CatInput {
CatIstream *cat;
struct istream *istream;
/* handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(FdType type, int fd, size_t max_length);
void OnEof();
void OnError(GError *error);
};
struct CatIstream {
struct istream output;
bool reading;
unsigned current, num;
CatInput inputs[1];
CatInput &GetCurrent() {
return inputs[current];
}
const CatInput &GetCurrent() const {
return inputs[current];
}
bool IsCurrent(const CatInput &input) const {
return &GetCurrent() == &input;
}
CatInput &Shift() {
return inputs[current++];
}
bool IsEOF() const {
return current == num;
}
void CloseAllInputs() {
while (!IsEOF()) {
auto &input = Shift();
if (input.istream != nullptr)
istream_close_handler(input.istream);
}
}
};
/*
* istream handler
*
*/
inline size_t
CatInput::OnData(const void *data, size_t length)
{
assert(istream != nullptr);
if (!cat->IsCurrent(*this))
return 0;
return istream_invoke_data(&cat->output, data, length);
}
inline ssize_t
CatInput::OnDirect(FdType type, int fd, size_t max_length)
{
assert(istream != nullptr);
assert(cat->IsCurrent(*this));
return istream_invoke_direct(&cat->output, type, fd, max_length);
}
inline void
CatInput::OnEof()
{
assert(istream != nullptr);
istream = nullptr;
if (cat->IsCurrent(*this)) {
do {
cat->Shift();
} while (!cat->IsEOF() && cat->GetCurrent().istream == nullptr);
if (cat->IsEOF()) {
istream_deinit_eof(&cat->output);
} else if (!cat->reading) {
/* only call istream_read() if this function was not
called from istream_cat_read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
istream_read(cat->GetCurrent().istream);
}
}
}
inline void
CatInput::OnError(GError *error)
{
assert(istream != nullptr);
istream = nullptr;
cat->CloseAllInputs();
istream_deinit_abort(&cat->output, error);
}
/*
* istream implementation
*
*/
static inline CatIstream *
istream_to_cat(struct istream *istream)
{
return &ContainerCast2(*istream, &CatIstream::output);
}
static off_t
istream_cat_available(struct istream *istream, bool partial)
{
CatIstream *cat = istream_to_cat(istream);
off_t available = 0;
for (auto *input = &cat->GetCurrent(), *end = &cat->inputs[cat->num];
input < end; ++input) {
if (input->istream == nullptr)
continue;
const off_t a = istream_available(input->istream, partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
static void
istream_cat_read(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
pool_ref(cat->output.pool);
cat->reading = true;
unsigned prev;
do {
while (!cat->IsEOF() && cat->GetCurrent().istream == nullptr)
++cat->current;
if (cat->IsEOF()) {
istream_deinit_eof(&cat->output);
break;
}
istream_handler_set_direct(cat->GetCurrent().istream,
cat->output.handler_direct);
prev = cat->current;
istream_read(cat->GetCurrent().istream);
} while (!cat->IsEOF() && cat->current != prev);
cat->reading = false;
pool_unref(cat->output.pool);
}
static int
istream_cat_as_fd(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (cat->current != cat->num - 1)
/* not on last input */
return -1;
auto &i = cat->GetCurrent();
int fd = istream_as_fd(i.istream);
if (fd >= 0)
istream_deinit(&cat->output);
return fd;
}
static void
istream_cat_close(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
cat->CloseAllInputs();
istream_deinit(&cat->output);
}
static const struct istream_class istream_cat = {
.available = istream_cat_available,
.read = istream_cat_read,
.as_fd = istream_cat_as_fd,
.close = istream_cat_close,
};
/*
* constructor
*
*/
struct istream *
istream_cat_new(struct pool *pool, ...)
{
unsigned num = 0;
va_list ap;
va_start(ap, pool);
while (va_arg(ap, struct istream *) != nullptr)
++num;
va_end(ap);
assert(num > 0);
CatIstream *cat = (CatIstream *)
istream_new(pool, &istream_cat,
sizeof(*cat) + (num - 1) * sizeof(cat->inputs));
cat->reading = false;
cat->current = 0;
cat->num = num;
va_start(ap, pool);
num = 0;
struct istream *istream;
while ((istream = va_arg(ap, struct istream *)) != nullptr) {
assert(!istream_has_handler(istream));
CatInput *input = &cat->inputs[num++];
input->cat = cat;
istream_assign_handler(&input->istream, istream,
&MakeIstreamHandler<CatInput>::handler, input,
0);
}
va_end(ap);
return &cat->output;
}
<|endoftext|>
|
<commit_before>/*
* Concatenate several istreams.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_cat.hxx"
#include "istream_oo.hxx"
#include "util/Cast.hxx"
#include <assert.h>
#include <stdarg.h>
struct CatIstream;
struct CatInput {
CatIstream *cat;
struct istream *istream;
/* handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(FdType type, int fd, size_t max_length);
void OnEof();
void OnError(GError *error);
};
struct CatIstream {
struct istream output;
bool reading = false;
unsigned current = 0;
const unsigned num;
CatInput inputs[1];
CatIstream(struct pool &p, unsigned _num, va_list ap);
CatInput &GetCurrent() {
return inputs[current];
}
const CatInput &GetCurrent() const {
return inputs[current];
}
bool IsCurrent(const CatInput &input) const {
return &GetCurrent() == &input;
}
CatInput &Shift() {
return inputs[current++];
}
bool IsEOF() const {
return current == num;
}
/**
* Call Shift() repeatedly until a non-empty input is found.
*
* @return false if there are no more inputs
*/
bool AutoShift() {
while (true) {
if (IsEOF())
return false;
if (GetCurrent().istream != nullptr)
return true;
Shift();
}
}
void CloseAllInputs() {
while (!IsEOF()) {
auto &input = Shift();
if (input.istream != nullptr)
istream_close_handler(input.istream);
}
}
};
/*
* istream handler
*
*/
inline size_t
CatInput::OnData(const void *data, size_t length)
{
assert(istream != nullptr);
if (!cat->IsCurrent(*this))
return 0;
return istream_invoke_data(&cat->output, data, length);
}
inline ssize_t
CatInput::OnDirect(FdType type, int fd, size_t max_length)
{
assert(istream != nullptr);
assert(cat->IsCurrent(*this));
return istream_invoke_direct(&cat->output, type, fd, max_length);
}
inline void
CatInput::OnEof()
{
assert(istream != nullptr);
istream = nullptr;
if (cat->IsCurrent(*this)) {
if (!cat->AutoShift()) {
istream_deinit_eof(&cat->output);
} else if (!cat->reading) {
/* only call istream_read() if this function was not
called from istream_cat_read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
istream_read(cat->GetCurrent().istream);
}
}
}
inline void
CatInput::OnError(GError *error)
{
assert(istream != nullptr);
istream = nullptr;
cat->CloseAllInputs();
istream_deinit_abort(&cat->output, error);
}
/*
* istream implementation
*
*/
static inline CatIstream *
istream_to_cat(struct istream *istream)
{
return &ContainerCast2(*istream, &CatIstream::output);
}
static off_t
istream_cat_available(struct istream *istream, bool partial)
{
CatIstream *cat = istream_to_cat(istream);
off_t available = 0;
for (auto *input = &cat->GetCurrent(), *end = &cat->inputs[cat->num];
input < end; ++input) {
if (input->istream == nullptr)
continue;
const off_t a = istream_available(input->istream, partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
static void
istream_cat_read(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
const ScopePoolRef ref(*cat->output.pool TRACE_ARGS);
cat->reading = true;
unsigned prev;
do {
if (!cat->AutoShift()) {
istream_deinit_eof(&cat->output);
break;
}
istream_handler_set_direct(cat->GetCurrent().istream,
cat->output.handler_direct);
prev = cat->current;
istream_read(cat->GetCurrent().istream);
} while (!cat->IsEOF() && cat->current != prev);
cat->reading = false;
}
static int
istream_cat_as_fd(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (cat->current != cat->num - 1)
/* not on last input */
return -1;
auto &i = cat->GetCurrent();
int fd = istream_as_fd(i.istream);
if (fd >= 0)
istream_deinit(&cat->output);
return fd;
}
static void
istream_cat_close(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
cat->CloseAllInputs();
istream_deinit(&cat->output);
}
static const struct istream_class istream_cat = {
.available = istream_cat_available,
.read = istream_cat_read,
.as_fd = istream_cat_as_fd,
.close = istream_cat_close,
};
/*
* constructor
*
*/
inline CatIstream::CatIstream(struct pool &p, unsigned _num, va_list ap)
:num(_num)
{
istream_init(&output, &istream_cat, &p);
unsigned i = 0;
struct istream *istream;
while ((istream = va_arg(ap, struct istream *)) != nullptr) {
assert(!istream_has_handler(istream));
CatInput *input = &inputs[i++];
input->cat = this;
istream_assign_handler(&input->istream, istream,
&MakeIstreamHandler<CatInput>::handler, input,
0);
}
assert(i == num);
}
struct istream *
istream_cat_new(struct pool *pool, ...)
{
unsigned num = 0;
va_list ap;
va_start(ap, pool);
while (va_arg(ap, struct istream *) != nullptr)
++num;
va_end(ap);
assert(num > 0);
CatIstream *cat;
auto p = p_malloc(pool, sizeof(*cat) + (num - 1) * sizeof(cat->inputs));
va_start(ap, pool);
cat = new(p) CatIstream(*pool, num, ap);
va_end(ap);
return &cat->output;
}
<commit_msg>istream_cat: use boost::intrusive::slist instead of variable-length array<commit_after>/*
* Concatenate several istreams.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_cat.hxx"
#include "istream_oo.hxx"
#include "util/Cast.hxx"
#include <boost/intrusive/slist.hpp>
#include <iterator>
#include <assert.h>
#include <stdarg.h>
struct CatIstream;
struct CatInput
: boost::intrusive::slist_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
CatIstream *cat;
struct istream *istream;
/* handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(FdType type, int fd, size_t max_length);
void OnEof();
void OnError(GError *error);
struct Disposer {
void operator()(CatInput *input) {
if (input->istream != nullptr)
istream_close_handler(input->istream);
}
};
};
struct CatIstream {
struct istream output;
bool reading = false;
typedef boost::intrusive::slist<CatInput,
boost::intrusive::constant_time_size<false>> InputList;
InputList inputs;
CatIstream(struct pool &p, va_list ap);
CatInput &GetCurrent() {
return inputs.front();
}
const CatInput &GetCurrent() const {
return inputs.front();
}
bool IsCurrent(const CatInput &input) const {
return &GetCurrent() == &input;
}
bool IsEOF() const {
return inputs.empty();
}
/**
* Remove all nulled leading inputs.
*
* @return false if there are no more inputs
*/
bool AutoShift() {
while (true) {
if (IsEOF())
return false;
if (GetCurrent().istream != nullptr)
return true;
inputs.pop_front();
}
}
void CloseAllInputs() {
inputs.clear_and_dispose(CatInput::Disposer());
}
};
/*
* istream handler
*
*/
inline size_t
CatInput::OnData(const void *data, size_t length)
{
assert(istream != nullptr);
if (!cat->IsCurrent(*this))
return 0;
return istream_invoke_data(&cat->output, data, length);
}
inline ssize_t
CatInput::OnDirect(FdType type, int fd, size_t max_length)
{
assert(istream != nullptr);
assert(cat->IsCurrent(*this));
return istream_invoke_direct(&cat->output, type, fd, max_length);
}
inline void
CatInput::OnEof()
{
assert(istream != nullptr);
istream = nullptr;
if (cat->IsCurrent(*this)) {
if (!cat->AutoShift()) {
istream_deinit_eof(&cat->output);
} else if (!cat->reading) {
/* only call istream_read() if this function was not
called from istream_cat_read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
istream_read(cat->GetCurrent().istream);
}
}
}
inline void
CatInput::OnError(GError *error)
{
assert(istream != nullptr);
istream = nullptr;
cat->CloseAllInputs();
istream_deinit_abort(&cat->output, error);
}
/*
* istream implementation
*
*/
static inline CatIstream *
istream_to_cat(struct istream *istream)
{
return &ContainerCast2(*istream, &CatIstream::output);
}
static off_t
istream_cat_available(struct istream *istream, bool partial)
{
CatIstream *cat = istream_to_cat(istream);
off_t available = 0;
for (const auto &input : cat->inputs) {
if (input.istream == nullptr)
continue;
const off_t a = istream_available(input.istream, partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
static void
istream_cat_read(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
const ScopePoolRef ref(*cat->output.pool TRACE_ARGS);
cat->reading = true;
CatIstream::InputList::const_iterator prev;
do {
if (!cat->AutoShift()) {
istream_deinit_eof(&cat->output);
break;
}
istream_handler_set_direct(cat->GetCurrent().istream,
cat->output.handler_direct);
prev = cat->inputs.begin();
istream_read(cat->GetCurrent().istream);
} while (!cat->IsEOF() && cat->inputs.begin() != prev);
cat->reading = false;
}
static int
istream_cat_as_fd(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (std::next(cat->inputs.begin()) != cat->inputs.end())
/* not on last input */
return -1;
auto &i = cat->GetCurrent();
int fd = istream_as_fd(i.istream);
if (fd >= 0)
istream_deinit(&cat->output);
return fd;
}
static void
istream_cat_close(struct istream *istream)
{
CatIstream *cat = istream_to_cat(istream);
cat->CloseAllInputs();
istream_deinit(&cat->output);
}
static const struct istream_class istream_cat = {
.available = istream_cat_available,
.read = istream_cat_read,
.as_fd = istream_cat_as_fd,
.close = istream_cat_close,
};
/*
* constructor
*
*/
inline CatIstream::CatIstream(struct pool &p, va_list ap)
{
istream_init(&output, &istream_cat, &p);
auto i = inputs.before_begin();
struct istream *istream;
while ((istream = va_arg(ap, struct istream *)) != nullptr) {
assert(!istream_has_handler(istream));
auto *input = NewFromPool<CatInput>(p);
i = inputs.insert_after(i, *input);
input->cat = this;
istream_assign_handler(&input->istream, istream,
&MakeIstreamHandler<CatInput>::handler, input,
0);
}
}
struct istream *
istream_cat_new(struct pool *pool, ...)
{
va_list ap;
va_start(ap, pool);
auto cat = NewFromPool<CatIstream>(*pool, *pool, ap);
va_end(ap);
return &cat->output;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "log.h"
#include "datetime.h"
#include "utils.h"
#include <stdarg.h>
#include <unistd.h>
#include <stdio.h>
#define BUFFER_SIZE (10 * 1024)
const std::regex filter_re("\033\\[[;\\d]*m");
const char *priorities[] = {
EMERG_COL "█" NO_COL, // LOG_EMERG 0 = System is unusable
ALERT_COL "▉" NO_COL, // LOG_ALERT 1 = Action must be taken immediately
CRIT_COL "▊" NO_COL, // LOG_CRIT 2 = Critical conditions
ERR_COL "▋" NO_COL, // LOG_ERR 3 = Error conditions
WARNING_COL "▌" NO_COL, // LOG_WARNING 4 = Warning conditions
NOTICE_COL "▍" NO_COL, // LOG_NOTICE 5 = Normal but significant condition
INFO_COL "▎" NO_COL, // LOG_INFO 6 = Informational
DEBUG_COL "▏" NO_COL, // LOG_DEBUG 7 = Debug-level messages
};
void
StreamLogger::log(int priority, const std::string& str)
{
ofs << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
void
StderrLogger::log(int priority, const std::string& str)
{
if (isatty(fileno(stderr))) {
std::cerr << priorities[priority < 0 ? -priority : priority] + str << std::endl;
} else {
std::cerr << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
}
SysLog::SysLog(const char *ident, int option, int facility)
{
openlog(ident, option, facility);
}
SysLog::~SysLog()
{
closelog();
}
void
SysLog::log(int priority, const std::string& str)
{
syslog(priority, "%s", std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "").c_str());
}
int Log::log_level = DEFAULT_LOG_LEVEL;
std::vector<std::unique_ptr<Logger>> Log::handlers;
Log::Log(const std::string& str, bool cleanup_, std::chrono::time_point<std::chrono::system_clock> wakeup_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)
: cleanup(cleanup_),
created_at(created_at_),
wakeup(wakeup_),
str_start(str),
priority(priority_),
finished(false) { }
Log::~Log()
{
bool f = false;
finished.compare_exchange_strong(f, cleanup);
}
long double
Log::age()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - created_at).count();
}
/*
* https://isocpp.org/wiki/faq/ctors#static-init-order
* Avoid the "static initialization order fiasco"
*/
LogThread&
Log::_thread()
{
static LogThread* thread = new LogThread();
return *thread;
}
std::string
Log::str_format(int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr)
{
char* buffer = new char[BUFFER_SIZE];
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
std::string msg(buffer);
auto iso8601 = "[" + Datetime::to_string(std::chrono::system_clock::now()) + "]";
auto tid = " (" + get_thread_name() + ")";
std::string result = iso8601 + tid;
#ifdef LOG_OBJ_ADDRESS
if (obj) {
snprintf(buffer, BUFFER_SIZE, " [%p]", obj);
result += buffer;
}
#endif
#ifdef TRACEBACK
auto location = (priority >= LOCATION_LOG_LEVEL) ? " " + std::string(file) + ":" + std::to_string(line) : std::string();
result += location + ": ";
#else
result += " ";
(void)obj;
#endif
result += prefix + msg + suffix;
delete []buffer;
if (priority < 0) {
if (exc.empty()) {
result += DARK_GREY + traceback(file, line) + NO_COL;
} else {
result += NO_COL + exc + NO_COL;
}
}
return result;
}
std::shared_ptr<Log>
Log::log(bool cleanup, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
std::string str(str_format(priority, exc, file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
return print(str, cleanup, wakeup, priority);
}
void
Log::clear()
{
finished = true;
}
void
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
if (finished.exchange(true)) {
va_list argptr;
va_start(argptr, format);
std::string str(str_format(priority, std::string(), file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
print(str, false, 0, priority, created_at);
}
}
std::shared_ptr<Log>
Log::add(const std::string& str, bool cleanup, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
auto l_ptr = std::make_shared<Log>(str, cleanup, wakeup, priority, created_at);
static LogThread& thread = _thread();
thread.add(l_ptr);
return l_ptr;
}
void
Log::log(int priority, const std::string& str)
{
static std::mutex log_mutex;
std::lock_guard<std::mutex> lk(log_mutex);
for (auto& handler : Log::handlers) {
handler->log(priority, str);
}
}
std::shared_ptr<Log>
Log::print(const std::string& str, bool cleanup, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
if (priority > Log::log_level) {
return std::make_shared<Log>(str, cleanup, wakeup, priority, created_at);
}
if (!Log::handlers.size()) {
Log::handlers.push_back(std::make_unique<StderrLogger>());
}
if (priority >= ASYNC_LOG_LEVEL || wakeup > std::chrono::system_clock::now()) {
return add(str, cleanup, wakeup, priority, created_at);
} else {
log(priority, str);
return std::make_shared<Log>(str, cleanup, wakeup, priority, created_at);
}
}
void
Log::finish(int wait)
{
static LogThread& thread = _thread();
thread.finish(wait);
}
LogThread::LogThread()
: running(-1),
inner_thread(&LogThread::thread_function, this) { }
LogThread::~LogThread()
{
finish(true);
}
void
LogThread::finish(int wait)
{
running = wait;
wakeup_signal.notify_all();
if (wait) {
try {
inner_thread.join();
} catch (const std::system_error&) { }
}
}
void
LogThread::add(const std::shared_ptr<Log>& l_ptr)
{
if (running != 0) {
log_list.push_back(l_ptr->shared_from_this());
if (std::chrono::system_clock::from_time_t(wakeup) >= l_ptr->wakeup) {
wakeup_signal.notify_all();
}
}
}
void
LogThread::thread_function()
{
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
auto now = std::chrono::system_clock::now();
auto next_wakeup = now + 3s;
while (running != 0) {
if (--running < 0) {
running = -1;
}
wakeup = std::chrono::system_clock::to_time_t(next_wakeup);
wakeup_signal.wait_until(lk, next_wakeup);
now = std::chrono::system_clock::now();
if (running < 0) {
next_wakeup = now + 3s;
} else {
next_wakeup = now + 1s;
}
for (auto it = log_list.begin(); it != log_list.end(); ) {
auto& l_ptr = *it;
if (!l_ptr || l_ptr->finished) {
it = log_list.erase(it);
} else if (l_ptr->wakeup <= now) {
l_ptr->finished = true;
auto msg = l_ptr->str_start;
auto age = l_ptr->age();
if (age > 2e8) {
msg += " ~" + delta_string(age);
}
Log::log(l_ptr->priority, msg);
it = log_list.erase(it);
} else if (next_wakeup > l_ptr->wakeup) {
next_wakeup = l_ptr->wakeup;
++it;
} else {
++it;
}
}
if (next_wakeup < now + 100ms) {
next_wakeup = now + 100ms;
}
}
}
<commit_msg>Log: faster waking up when running is flagged<commit_after>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "log.h"
#include "datetime.h"
#include "utils.h"
#include <stdarg.h>
#include <unistd.h>
#include <stdio.h>
#define BUFFER_SIZE (10 * 1024)
const std::regex filter_re("\033\\[[;\\d]*m");
const char *priorities[] = {
EMERG_COL "█" NO_COL, // LOG_EMERG 0 = System is unusable
ALERT_COL "▉" NO_COL, // LOG_ALERT 1 = Action must be taken immediately
CRIT_COL "▊" NO_COL, // LOG_CRIT 2 = Critical conditions
ERR_COL "▋" NO_COL, // LOG_ERR 3 = Error conditions
WARNING_COL "▌" NO_COL, // LOG_WARNING 4 = Warning conditions
NOTICE_COL "▍" NO_COL, // LOG_NOTICE 5 = Normal but significant condition
INFO_COL "▎" NO_COL, // LOG_INFO 6 = Informational
DEBUG_COL "▏" NO_COL, // LOG_DEBUG 7 = Debug-level messages
};
void
StreamLogger::log(int priority, const std::string& str)
{
ofs << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
void
StderrLogger::log(int priority, const std::string& str)
{
if (isatty(fileno(stderr))) {
std::cerr << priorities[priority < 0 ? -priority : priority] + str << std::endl;
} else {
std::cerr << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "") << std::endl;
}
}
SysLog::SysLog(const char *ident, int option, int facility)
{
openlog(ident, option, facility);
}
SysLog::~SysLog()
{
closelog();
}
void
SysLog::log(int priority, const std::string& str)
{
syslog(priority, "%s", std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, "").c_str());
}
int Log::log_level = DEFAULT_LOG_LEVEL;
std::vector<std::unique_ptr<Logger>> Log::handlers;
Log::Log(const std::string& str, bool cleanup_, std::chrono::time_point<std::chrono::system_clock> wakeup_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)
: cleanup(cleanup_),
created_at(created_at_),
wakeup(wakeup_),
str_start(str),
priority(priority_),
finished(false) { }
Log::~Log()
{
bool f = false;
finished.compare_exchange_strong(f, cleanup);
}
long double
Log::age()
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - created_at).count();
}
/*
* https://isocpp.org/wiki/faq/ctors#static-init-order
* Avoid the "static initialization order fiasco"
*/
LogThread&
Log::_thread()
{
static LogThread* thread = new LogThread();
return *thread;
}
std::string
Log::str_format(int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr)
{
char* buffer = new char[BUFFER_SIZE];
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
std::string msg(buffer);
auto iso8601 = "[" + Datetime::to_string(std::chrono::system_clock::now()) + "]";
auto tid = " (" + get_thread_name() + ")";
std::string result = iso8601 + tid;
#ifdef LOG_OBJ_ADDRESS
if (obj) {
snprintf(buffer, BUFFER_SIZE, " [%p]", obj);
result += buffer;
}
#endif
#ifdef TRACEBACK
auto location = (priority >= LOCATION_LOG_LEVEL) ? " " + std::string(file) + ":" + std::to_string(line) : std::string();
result += location + ": ";
#else
result += " ";
(void)obj;
#endif
result += prefix + msg + suffix;
delete []buffer;
if (priority < 0) {
if (exc.empty()) {
result += DARK_GREY + traceback(file, line) + NO_COL;
} else {
result += NO_COL + exc + NO_COL;
}
}
return result;
}
std::shared_ptr<Log>
Log::log(bool cleanup, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
std::string str(str_format(priority, exc, file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
return print(str, cleanup, wakeup, priority);
}
void
Log::clear()
{
finished = true;
}
void
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
if (finished.exchange(true)) {
va_list argptr;
va_start(argptr, format);
std::string str(str_format(priority, std::string(), file, line, suffix, prefix, obj, format, argptr));
va_end(argptr);
print(str, false, 0, priority, created_at);
}
}
std::shared_ptr<Log>
Log::add(const std::string& str, bool cleanup, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
auto l_ptr = std::make_shared<Log>(str, cleanup, wakeup, priority, created_at);
static LogThread& thread = _thread();
thread.add(l_ptr);
return l_ptr;
}
void
Log::log(int priority, const std::string& str)
{
static std::mutex log_mutex;
std::lock_guard<std::mutex> lk(log_mutex);
for (auto& handler : Log::handlers) {
handler->log(priority, str);
}
}
std::shared_ptr<Log>
Log::print(const std::string& str, bool cleanup, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
if (priority > Log::log_level) {
return std::make_shared<Log>(str, cleanup, wakeup, priority, created_at);
}
if (!Log::handlers.size()) {
Log::handlers.push_back(std::make_unique<StderrLogger>());
}
if (priority >= ASYNC_LOG_LEVEL || wakeup > std::chrono::system_clock::now()) {
return add(str, cleanup, wakeup, priority, created_at);
} else {
log(priority, str);
return std::make_shared<Log>(str, cleanup, wakeup, priority, created_at);
}
}
void
Log::finish(int wait)
{
static LogThread& thread = _thread();
thread.finish(wait);
}
LogThread::LogThread()
: running(-1),
inner_thread(&LogThread::thread_function, this) { }
LogThread::~LogThread()
{
finish(true);
}
void
LogThread::finish(int wait)
{
running = wait;
wakeup_signal.notify_all();
if (wait) {
try {
inner_thread.join();
} catch (const std::system_error&) { }
}
}
void
LogThread::add(const std::shared_ptr<Log>& l_ptr)
{
if (running != 0) {
log_list.push_back(l_ptr->shared_from_this());
if (std::chrono::system_clock::from_time_t(wakeup) >= l_ptr->wakeup) {
wakeup_signal.notify_all();
}
}
}
void
LogThread::thread_function()
{
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
auto now = std::chrono::system_clock::now();
auto next_wakeup = now + 3s;
while (running != 0) {
if (--running < 0) {
running = -1;
}
wakeup = std::chrono::system_clock::to_time_t(next_wakeup);
wakeup_signal.wait_until(lk, next_wakeup);
now = std::chrono::system_clock::now();
if (running < 0) {
next_wakeup = now + 3s;
} else {
next_wakeup = now + 100ms;
}
for (auto it = log_list.begin(); it != log_list.end(); ) {
auto& l_ptr = *it;
if (!l_ptr || l_ptr->finished) {
it = log_list.erase(it);
} else if (l_ptr->wakeup <= now) {
l_ptr->finished = true;
auto msg = l_ptr->str_start;
auto age = l_ptr->age();
if (age > 2e8) {
msg += " ~" + delta_string(age);
}
Log::log(l_ptr->priority, msg);
it = log_list.erase(it);
} else if (next_wakeup > l_ptr->wakeup) {
next_wakeup = l_ptr->wakeup;
++it;
} else {
++it;
}
}
if (next_wakeup < now + 100ms) {
next_wakeup = now + 100ms;
}
}
}
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include <iomanip>
#include <pwd.h>
#include <grp.h>
#include <locale>
#include <algorithm>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <boost/tokenizer.hpp>
#include <vector>
#include <list>
#include <set>
#include <ctype.h>
#include <map>
void NormalList(std::map<std::string, int, std::locale> files);
// print single line of a longlist output
std::string LongList(std::string file, size_t padding);
// manages a directory of longlist output
void LongListBundle(std::map<std::string, int, std::locale> files,
std::string dir);
// puts the argv input from the program into a list
std::list<std::string> GetInput(int argc, char **argcv);
void StripDotfiles(std::map<std::string, int, std::locale> &names);
void Print(std::string file, std::set<std::string> args, bool multifile);
// outputs parameters to the program for debugging
void OutputElements(std::list<std::string> input);
void OutputArgs(std::set<std::string> args);
// grabbed from UserHostInfo from rshell.cpp
// the gains from refactoring aren't worth bothering
std::string CurrentPwd();
// iterate each character of each element with a - to look for unknown args
bool UnknownArgs(std::list<std::string> input);
std::set<std::string> Split(std::list<std::string> &input);
int main(int argc, char **argv) {
using namespace std;
auto input = GetInput(argc, argv);
if (UnknownArgs(input)) {
cout << "Unknown/unimplemented arg sent (not l, a or R)" << endl;
exit(1);
}
auto args = Split(input);
// empty input case, append . so it works as current directory
if (input.empty())
input.push_front(".");
bool multifile;
for (auto &filearg : input) {
if (input.size() > 1) {
cout << filearg << ": " << endl;
multifile = true;
}
else
multifile = false;
Print(filearg, args, multifile);
}
}
std::list<std::string> GetInput(int argc, char **argv) {
using namespace std;
list<string> input;
for (int i = 0; i < argc; i++) {
string piece(argv[i]);
input.push_back(piece);
}
return input;
}
void OutputElements(std::list<std::string> input) {
using namespace std;
cout << "inputs: " << endl;
for (const auto &element : input)
cout << element << endl;
}
std::string CurrentPwd() {
char *rawpwd = get_current_dir_name();
if (rawpwd == NULL) {
perror("get_current_dir_name returned NULL");
exit(1);
}
std::string pwd(rawpwd);
delete rawpwd;
return pwd;
}
std::set<std::string> Split(std::list<std::string> &input) {
std::set<std::string> args;
input.pop_front();
for (auto &item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for (const auto &letter : item) {
args.insert(std::string(1, letter));
}
// todo
item.erase(0);
}
}
for (auto itr = input.begin(); itr != input.end(); ++itr) {
if (itr->empty()) {
input.erase(itr);
--itr;
}
}
return args;
}
bool UnknownArgs(std::list<std::string> input) {
for (auto &item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for (const auto &letter : item) {
if (letter != 'l' && letter != 'a' && letter != 'R')
return true;
}
}
}
return false;
}
void OutputArgs(std::set<std::string> args) {
using namespace std;
cout << "args: " << endl;
for (const auto &arg : args)
cout << arg << endl;
}
void StripDotfiles(std::map<std::string, int, std::locale> &names) {
// iterate past . and ..
auto target = names.find(".");
names.erase(target);
target = names.find("..");
names.erase(target);
auto nameitr = names.begin();
while (nameitr != names.end()) {
if ((*nameitr).first[0] == '.') {
names.erase(nameitr);
nameitr = names.begin();
}
++nameitr;
}
}
void Print(std::string file, std::set<std::string> args, bool multifile) {
using namespace std;
map<string, int, std::locale> names(std::locale("en_US.UTF-8"));
DIR *dirp = opendir(file.c_str());
if (errno != 0) {
perror("opendir error");
exit(1);
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (errno != 0) {
perror("readdir error");
exit(1);
}
names.emplace(make_pair(direntp->d_name, direntp->d_type));
}
closedir(dirp);
if (errno != 0) {
perror("closedir error");
exit(1);
}
auto argcheck = args.find("a");
if (argcheck == std::end(args))
StripDotfiles(names);
bool longlist;
argcheck = args.find("l");
if (argcheck == std::end(args)) {
longlist = false;
} else {
longlist = true;
}
argcheck = args.find("R");
if (argcheck == std::end(args)) {
if (longlist == true) {
LongListBundle(names, file);
} else {
NormalList(names);
}
} else {
// recursive
if (!multifile)
cout << endl << file << ": " << endl;
if (longlist) {
LongListBundle(names, file);
} else {
NormalList(names);
}
// check empty filelist before compariing iterators
if (names.empty())
return;
auto itr = names.begin();
string append_dir;
while (!names.empty() && itr != names.end()) {
// if . / .. are in the list iterate over them
if (itr->first == "." || itr->first == "..") {
++itr;
}
if (itr->second == DT_DIR) {
// append / to directory if it doesn't already have. makes concatenation
// simpler down the road
if (file.back() != '/')
file.push_back('/');
append_dir = itr->first;
names.erase(itr++);
Print(file + append_dir, args, false);
} else {
++itr;
}
}
}
}
std::string LongList(std::string file, size_t padding) {
using namespace std;
struct stat buf;
lstat(file.c_str(), &buf);
if (errno != 0) {
perror("longlist lstat error");
exit(1);
}
// filetype
string filetype;
if (S_ISBLK(buf.st_mode))
filetype = "b";
else if (S_ISCHR(buf.st_mode))
filetype = "c";
else if (S_ISFIFO(buf.st_mode))
filetype = "f";
else if (S_ISREG(buf.st_mode))
filetype = "-";
else if (S_ISDIR(buf.st_mode))
filetype = "d";
else if (S_ISLNK(buf.st_mode))
filetype = "l";
else if (S_ISSOCK(buf.st_mode))
filetype = "s";
// permissions
string permissions = "---------";
if (buf.st_mode & S_IRUSR)
permissions[0] = 'r'; // owner has read permission
if (buf.st_mode & S_IWUSR)
permissions[1] = 'w'; // owner has write permission
if (buf.st_mode & S_IXUSR)
permissions[2] = 'x'; // owner has execute permission
if (buf.st_mode & S_IRGRP)
permissions[3] = 'r'; // group has read permission
if (buf.st_mode & S_IWGRP)
permissions[4] = 'w'; // group has write permission
if (buf.st_mode & S_IXGRP)
permissions[5] = 'x'; // group has execute permission
if (buf.st_mode & S_IROTH)
permissions[6] = 'r'; // others have read permission
if (buf.st_mode & S_IWOTH)
permissions[7] = 'w'; // others have write permission
if (buf.st_mode & S_IXOTH)
permissions[8] = 'x'; // others have execute permission
// num file links
// giving 3 characters of space hardcoded for time purposes
string links = to_string(buf.st_nlink);
if (links.size() == 1)
links.insert(links.begin(), 2, ' ');
else if (links.size() == 2)
links.insert(links.begin(), 1, ' ');
// username and groupname
struct passwd user;
user = *getpwuid(buf.st_uid);
if (errno != 0) {
perror("pwuid error");
exit(1);
}
struct group grp;
grp = *getgrgid(buf.st_gid);
if (errno != 0) {
perror("groupid error");
exit(1);
}
string username(user.pw_name);
string groupname(grp.gr_name);
// filesize
string filesize = to_string(buf.st_size);
filesize.insert(filesize.begin(), padding - filesize.size(), ' ');
// modification date vs creation date depending on which is newer
auto date = (buf.st_mtime > buf.st_ctime) ? buf.st_mtime : buf.st_ctime;
char *rawtime = ctime(&date);
string thetime(rawtime);
// remove day of week + space e.g. 'Sat '
thetime.erase(0, 4);
// remove the ':ss yyyy\n' piece of the date. this is 9 chars until the year
// 10000
thetime.erase(thetime.size() - 9);
// erase prepended directories from filename
auto last_slash = file.begin();
for (auto itr = file.begin(); itr != file.end(); ++itr) {
if (*itr == '/') {
last_slash = itr;
}
}
// the range is [first, last)
last_slash++;
file.erase(file.begin(), last_slash);
string merged_string = filetype + permissions + " " + links + " " + username +
" " + groupname + " " + filesize + " " + thetime +
" " + file + "\n";
cout << merged_string;
return merged_string;
}
void LongListBundle(std::map<std::string, int, std::locale> files,
std::string dir) {
// append / to directory if it doesn't already have. makes concatenation
// simpler down the road
if (dir.back() != '/')
dir.push_back('/');
using namespace std;
// return early if empty
if (files.empty()) {
cout << "total 0" << endl;
return;
}
long largest_filesize = 0;
long block_total = 0;
long size_total = 0;
struct stat sizecheck;
for (const auto &file : files) {
std::string path = dir + file.first;
lstat(path.c_str(), &sizecheck);
if (errno != 0) {
perror("longlist lstat error");
exit(1);
}
if (sizecheck.st_size > largest_filesize) {
largest_filesize = sizecheck.st_size;
}
cout << "blocksize" << sizecheck.st_blksize << endl;
cout << "num blocks" << sizecheck.st_blocks << endl;
size_total += sizecheck.st_size;
block_total += sizecheck.st_blocks;
}
block_total/= 2;
// Output total block size before doing individual longlist lines
// TODO: fix this the numbers don't match!
cout << "total " << block_total << endl;
string filesize_width = to_string(largest_filesize);
for (const auto &file : files) {
string information = LongList(dir + file.first, filesize_width.size());
}
}
// TODO columns based on filesize
// width assumed as 80 col
void NormalList(std::map<std::string, int, std::locale> files) {
using namespace std;
// fixed columnsize
// return early if empty
if (files.empty()) {
return;
}
const size_t COLSIZE = 80;
size_t widest_file = 0;
for (const auto &pair : files) {
if (pair.first.size() > widest_file)
widest_file = pair.first.size();
}
size_t file_columns = COLSIZE / (widest_file + 2);
size_t count = 0;
// multirow case
if (file_columns < files.size()) {
for (const auto &pair : files) {
cout << setw(widest_file) << left << pair.first << " ";
if (count == file_columns) {
cout << endl;
count = 0;
continue;
}
count++;
}
cout << endl;
}
// single row case
else {
for (const auto &pair : files) {
cout << pair.first << " ";
}
cout << endl;
}
}
<commit_msg>fixed regression in . .. recursive print, fixed printing issues when one column prints occur<commit_after>#include <stdlib.h>
#include <iomanip>
#include <pwd.h>
#include <grp.h>
#include <locale>
#include <algorithm>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <boost/tokenizer.hpp>
#include <vector>
#include <list>
#include <set>
#include <ctype.h>
#include <map>
void NormalList(std::map<std::string, int, std::locale> files);
// print single line of a longlist output
std::string LongList(std::string file, size_t padding);
// manages a directory of longlist output
void LongListBundle(std::map<std::string, int, std::locale> files,
std::string dir);
// puts the argv input from the program into a list
std::list<std::string> GetInput(int argc, char **argcv);
void StripDotfiles(std::map<std::string, int, std::locale> &names);
void Print(std::string file, std::set<std::string> args, bool multifile);
// outputs parameters to the program for debugging
void OutputElements(std::list<std::string> input);
void OutputArgs(std::set<std::string> args);
// grabbed from UserHostInfo from rshell.cpp
// the gains from refactoring aren't worth bothering
std::string CurrentPwd();
// iterate each character of each element with a - to look for unknown args
bool UnknownArgs(std::list<std::string> input);
std::set<std::string> Split(std::list<std::string> &input);
int main(int argc, char **argv) {
using namespace std;
auto input = GetInput(argc, argv);
if (UnknownArgs(input)) {
cout << "Unknown/unimplemented arg sent (not l, a or R)" << endl;
exit(1);
}
auto args = Split(input);
// empty input case, append . so it works as current directory
if (input.empty())
input.push_front(".");
bool multifile;
for (auto &filearg : input) {
if (input.size() > 1) {
cout << filearg << ": " << endl;
multifile = true;
} else
multifile = false;
Print(filearg, args, multifile);
}
}
std::list<std::string> GetInput(int argc, char **argv) {
using namespace std;
list<string> input;
for (int i = 0; i < argc; i++) {
string piece(argv[i]);
input.push_back(piece);
}
return input;
}
void OutputElements(std::list<std::string> input) {
using namespace std;
cout << "inputs: " << endl;
for (const auto &element : input)
cout << element << endl;
}
std::string CurrentPwd() {
char *rawpwd = get_current_dir_name();
if (rawpwd == NULL) {
perror("get_current_dir_name returned NULL");
exit(1);
}
std::string pwd(rawpwd);
delete rawpwd;
return pwd;
}
std::set<std::string> Split(std::list<std::string> &input) {
std::set<std::string> args;
input.pop_front();
for (auto &item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for (const auto &letter : item) {
args.insert(std::string(1, letter));
}
// todo
item.erase(0);
}
}
for (auto itr = input.begin(); itr != input.end(); ++itr) {
if (itr->empty()) {
input.erase(itr);
--itr;
}
}
return args;
}
bool UnknownArgs(std::list<std::string> input) {
for (auto &item : input) {
if (item[0] == '-') {
item.erase(item.begin());
for (const auto &letter : item) {
if (letter != 'l' && letter != 'a' && letter != 'R')
return true;
}
}
}
return false;
}
void OutputArgs(std::set<std::string> args) {
using namespace std;
cout << "args: " << endl;
for (const auto &arg : args)
cout << arg << endl;
}
void StripDotfiles(std::map<std::string, int, std::locale> &names) {
// iterate past . and ..
auto target = names.find(".");
names.erase(target);
target = names.find("..");
names.erase(target);
auto nameitr = names.begin();
while (nameitr != names.end()) {
if ((*nameitr).first[0] == '.') {
names.erase(nameitr);
nameitr = names.begin();
}
++nameitr;
}
}
void Print(std::string file, std::set<std::string> args, bool multifile) {
using namespace std;
map<string, int, std::locale> names(std::locale("en_US.UTF-8"));
DIR *dirp = opendir(file.c_str());
if (errno != 0) {
perror("opendir error");
exit(1);
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (errno != 0) {
perror("readdir error");
exit(1);
}
names.emplace(make_pair(direntp->d_name, direntp->d_type));
}
closedir(dirp);
if (errno != 0) {
perror("closedir error");
exit(1);
}
auto argcheck = args.find("a");
if (argcheck == std::end(args))
StripDotfiles(names);
bool longlist;
argcheck = args.find("l");
if (argcheck == std::end(args)) {
longlist = false;
} else {
longlist = true;
}
argcheck = args.find("R");
if (argcheck == std::end(args)) {
if (longlist == true) {
LongListBundle(names, file);
} else {
NormalList(names);
}
} else {
// recursive
if (!multifile)
cout << endl << file << ": " << endl;
if (longlist) {
LongListBundle(names, file);
} else {
NormalList(names);
}
// check empty filelist before compariing iterators
if (names.empty())
return;
auto itr = names.begin();
string append_dir;
while (!names.empty() && itr != names.end()) {
// if . / .. are in the list iterate over them
if (itr->first == "." || itr->first == "..") {
++itr;
continue;
}
if (itr->second == DT_DIR) {
// append / to directory if it doesn't already have. makes concatenation
// simpler down the road
if (file.back() != '/')
file.push_back('/');
append_dir = itr->first;
names.erase(itr++);
Print(file + append_dir, args, false);
} else {
++itr;
}
}
}
}
std::string LongList(std::string file, size_t padding) {
using namespace std;
struct stat buf;
lstat(file.c_str(), &buf);
if (errno != 0) {
perror("longlist lstat error");
exit(1);
}
// filetype
string filetype;
if (S_ISBLK(buf.st_mode))
filetype = "b";
else if (S_ISCHR(buf.st_mode))
filetype = "c";
else if (S_ISFIFO(buf.st_mode))
filetype = "f";
else if (S_ISREG(buf.st_mode))
filetype = "-";
else if (S_ISDIR(buf.st_mode))
filetype = "d";
else if (S_ISLNK(buf.st_mode))
filetype = "l";
else if (S_ISSOCK(buf.st_mode))
filetype = "s";
// permissions
string permissions = "---------";
if (buf.st_mode & S_IRUSR)
permissions[0] = 'r'; // owner has read permission
if (buf.st_mode & S_IWUSR)
permissions[1] = 'w'; // owner has write permission
if (buf.st_mode & S_IXUSR)
permissions[2] = 'x'; // owner has execute permission
if (buf.st_mode & S_IRGRP)
permissions[3] = 'r'; // group has read permission
if (buf.st_mode & S_IWGRP)
permissions[4] = 'w'; // group has write permission
if (buf.st_mode & S_IXGRP)
permissions[5] = 'x'; // group has execute permission
if (buf.st_mode & S_IROTH)
permissions[6] = 'r'; // others have read permission
if (buf.st_mode & S_IWOTH)
permissions[7] = 'w'; // others have write permission
if (buf.st_mode & S_IXOTH)
permissions[8] = 'x'; // others have execute permission
// num file links
// giving 3 characters of space hardcoded for time purposes
string links = to_string(buf.st_nlink);
if (links.size() == 1)
links.insert(links.begin(), 2, ' ');
else if (links.size() == 2)
links.insert(links.begin(), 1, ' ');
// username and groupname
struct passwd user;
user = *getpwuid(buf.st_uid);
if (errno != 0) {
perror("pwuid error");
exit(1);
}
struct group grp;
grp = *getgrgid(buf.st_gid);
if (errno != 0) {
perror("groupid error");
exit(1);
}
string username(user.pw_name);
string groupname(grp.gr_name);
// filesize
string filesize = to_string(buf.st_size);
filesize.insert(filesize.begin(), padding - filesize.size(), ' ');
// modification date vs creation date depending on which is newer
auto date = (buf.st_mtime > buf.st_ctime) ? buf.st_mtime : buf.st_ctime;
char *rawtime = ctime(&date);
string thetime(rawtime);
// remove day of week + space e.g. 'Sat '
thetime.erase(0, 4);
// remove the ':ss yyyy\n' piece of the date. this is 9 chars until the year
// 10000
thetime.erase(thetime.size() - 9);
// erase prepended directories from filename
auto last_slash = file.begin();
for (auto itr = file.begin(); itr != file.end(); ++itr) {
if (*itr == '/') {
last_slash = itr;
}
}
// the range is [first, last)
last_slash++;
file.erase(file.begin(), last_slash);
string merged_string = filetype + permissions + " " + links + " " + username +
" " + groupname + " " + filesize + " " + thetime +
" " + file + "\n";
cout << merged_string;
return merged_string;
}
void LongListBundle(std::map<std::string, int, std::locale> files,
std::string dir) {
// append / to directory if it doesn't already have. makes concatenation
// simpler down the road
if (dir.back() != '/')
dir.push_back('/');
using namespace std;
// return early if empty
if (files.empty()) {
cout << "total 0" << endl;
return;
}
long largest_filesize = 0;
long block_total = 0;
long size_total = 0;
struct stat sizecheck;
for (const auto &file : files) {
std::string path = dir + file.first;
lstat(path.c_str(), &sizecheck);
if (errno != 0) {
perror("longlist lstat error");
exit(1);
}
if (sizecheck.st_size > largest_filesize) {
largest_filesize = sizecheck.st_size;
}
cout << "blocksize" << sizecheck.st_blksize << endl;
cout << "num blocks" << sizecheck.st_blocks << endl;
size_total += sizecheck.st_size;
block_total += sizecheck.st_blocks;
}
block_total /= 2;
// Output total block size before doing individual longlist lines
// TODO: fix this the numbers don't match!
cout << "total " << block_total << endl;
string filesize_width = to_string(largest_filesize);
for (const auto &file : files) {
string information = LongList(dir + file.first, filesize_width.size());
}
}
void NormalList(std::map<std::string, int, std::locale> files) {
using namespace std;
// fixed columnsize
// return early if empty
if (files.empty()) {
return;
}
//there are insecure ways of acquiring current terminal's column size
//that I am avoiding purposely
const size_t COLSIZE = 80;
size_t widest_file = 0;
for (const auto &pair : files) {
if (pair.first.size() > widest_file)
widest_file = pair.first.size();
}
// adding 2 accounts for the guaranteed 2 spaces gap
widest_file += 2;
size_t file_columns = COLSIZE / (widest_file);
size_t count = 0;
if (file_columns == 0) {
file_columns = 1;
}
// multirow case
if (file_columns < files.size()) {
for (const auto &pair : files) {
count++;
if (count == file_columns) {
cout << left << pair.first << endl;
count = 0;
continue;
}
cout << left << setw(widest_file) << pair.first;
}
cout << left << endl;
}
// single row case
else {
for (const auto &pair : files) {
cout << pair.first << " ";
}
cout << endl;
}
}
<|endoftext|>
|
<commit_before>#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <pwd.h>
#include <grp.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>
#include <clocale>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
//TODO:
//Format the output left to right in columns
//Sort output alphabetically where capitals don't matter
//Allow multiple files to be input and then output them properly
// this means mult. separate files, not a path of numerous files
//If passed in file doesn't exist, print error
//Note: Input is as follows:
//bin/ls <FLAGS> <FILES/DIR> "bin/ls -al"
//or bin/ls <FILES/DIR> <FLAGS> "bin/ls test.cpp -l"
int main(int argc, char** argv){
//Main variables and setup for later
int flags = 0;
struct stat statbuf;
bool isSysLink = false;
bool isDir = false;
char const *dirName = "."; //if no dir named, then sets it to curr dir
//FIXME - Below is an outine of how I think dirNames should be held
// both it an fileName should be arrays/vectors that can hold unlimited values
// Vectors makes more sense with pushback now that I think on it
//char const dirName[BUFSIZ];
//int cnt = 0;
//dirName[cnt] = ".";
string fileName = "";
setlocale(LC_ALL, "en_US.UTF-8");
//Flag assignment and optional param check
for(int i = 1; i < argc; i++){
lstat(argv[i], &statbuf);
//Checks if param is a dir, reg, link, or a flag
if(S_ISDIR(statbuf.st_mode)){
statbuf.st_mode = 0;
isDir = true;
dirName = argv[i];
}else if(S_ISREG(statbuf.st_mode)){
statbuf.st_mode = 0;//Resets statbuf
fileName = argv[i]; //Holds file name if reg file is passed in
}else if(S_ISLNK(statbuf.st_mode)){
if(lstat(".", &statbuf) == -1){
perror("lstat2 failed");
exit(1);
}
fileName = argv[i]; //Holds file name if sys link
isSysLink = true;
statbuf.st_mode = 0;//Resets statbuf
//Flag checking
}else{
statbuf.st_mode = 0;//Resets statbuf
if(argv[i][0] == '-'){
for(int j = 1; argv[i][j] != 0; j++){
if(argv[i][j] == 'a'){
flags |= FLAG_a;
}else if(argv[i][j] == 'l'){
flags |= FLAG_l;
}else if(argv[i][j] == 'R'){
flags |= FLAG_R;
}
}
}else{
//Assigns garbage value to dirName so it will
//return an error on opendir
dirName = argv[i];
}
}
}
vector<string> v; //Vector to hold output
char temp[512];
DIR *dirp;
dirent *direntp;
if((dirp = opendir(dirName)));
else{
perror("opendir failed");
exit(1);
}
if((flags == 0) || (flags == 2) || (flags == 4)){ //handles . and ..
if(direntp = readdir(dirp)){
}else{
perror("readdir1 failed");
}
if(direntp = readdir(dirp)){
}else{
perror("readdir2 failed");
}
}
errno = 0;
while((direntp = readdir(dirp))){
v.push_back(direntp->d_name);
}
if(errno != 0){
perror("readdir3 failed");
}
//Closes directory
if(closedir(dirp) == -1){
perror("closedir error");
}
sort(v.begin(), v.end());
for(unsigned i = 0; i < v.size(); i++){
bool isValid = true; //Used to check with fileName's passed in
if((flags == 0) || (flags == 1)){//ls or ls -a
if(fileName != ""){//if File passed in
isValid = false;
if(fileName == v.at(i)){ //if this IS the file
isValid = true;
}
}
if(isValid){//no file passed in
cout << v.at(i) << endl;
}
}else if((flags == 2) || (flags == 3)){//ls -l or ls -al
if(fileName != ""){//if file passed
isValid = false;
if(fileName == v.at(i)){//of this IS file
isValid = true;
}
}
if(isValid){//no file passed
if(isSysLink){
cout << "l";
}else if(S_ISDIR(statbuf.st_mode)){ //Checks for dir
cout << "d";
}else{
cout << "-";
}//End file type check
char str[sizeof(dirName) + sizeof(v.at(i)) + 128];
strcpy(str, "./");
strcat(str, dirName);
strcat(str, "/");
string str1 = v.at(i);
strcat(str, str1.c_str());
if(stat(str, &statbuf) == -1){//Sets statbuf
perror("stat() failed");
exit(1);
}
if(statbuf.st_mode & S_IRUSR){//Owner permissions
cout << "r";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IWUSR){
cout << "w";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IXUSR){
cout << "x";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IRGRP){//Group permissions
cout << "r";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IWGRP){
cout << "w";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IXGRP){
cout << "x";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IROTH){//Other permissions
cout << "r";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IWOTH){
cout << "w";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IXOTH){
cout << "x";
}else{
cout << "-";
}
int num = 0;
if(num = statbuf.st_nlink){//Num system links
cout << " " << num << " ";
}else{
perror("st_nlink error");
exit(1);
}
struct passwd *pwd;
if((pwd = getpwuid(statbuf.st_uid)) != NULL){//User ID
cout << pwd->pw_name << " ";
}else{
perror("getpwuid failed");
exit(1);
}
struct group *grp;
if((grp = getgrgid(statbuf.st_gid)) != NULL){//Group ID
cout << grp->gr_name << " ";
}else{
perror("getgrgid failed");
exit(1);
}
cout << statbuf.st_size << " "; //File size in bytes
if(num = statbuf.st_mtime){//Time of last modification
time_t rawtime = statbuf.st_mtime;
char buffer [80];
struct tm *timeinfo;
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%b %e %H:%M", timeinfo);
cout << buffer << " ";
}else{
perror("st_mtime failed");
exit(1);
}
cout << v.at(i) << endl;
}else if((flags == 4) || (flags == 5)){
//if FileName is a directory
//if Curr file is directory - enter it
}else if((flags == 6) || (flags == 7)){//ls -lR and ls -alR
//-l AND -R are set
//if curr file is dir; enter it
//output with -l info
}
}
}
return 0;
}
<commit_msg>Continued cleaning up ls.cpp<commit_after>#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <pwd.h>
#include <grp.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>
#include <clocale>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
//TODO:
//Format the output left to right in columns
//Sort output alphabetically case insensitive
//Allow multiple files to be input and then output them properly
// this means mult. separate files, not a path of numerous files
//Note: Input is as follows:
//bin/ls <FLAGS> <FILES/DIR> "bin/ls -al"
//or bin/ls <FILES/DIR> <FLAGS> "bin/ls test.cpp -l"
int main(int argc, char** argv){
//Main variables and setup for later
int flags = 0;
struct stat statbuf;
bool isSysLink = false;
bool isDir = false;
char const *dirName = "."; //if no dir named, then sets it to curr dir
//FIXME - Below is an outine of how I think dirNames should be held
// both it an fileName should be arrays/vectors that can hold unlimited values
// Vectors makes more sense with pushback now that I think on it
string fileName = "";
setlocale(LC_ALL, "en_US.UTF-8");
//Flag assignment and Optional param check
for(int i = 1; i < argc; i++){
lstat(argv[i], &statbuf);
//Checks if param is a dir, reg, link, or a flag
if(S_ISDIR(statbuf.st_mode)){
statbuf.st_mode = 0;
isDir = true;
dirName = argv[i];
}else if(S_ISREG(statbuf.st_mode)){
statbuf.st_mode = 0;//Resets statbuf
fileName = argv[i]; //Holds file name if reg file is passed in
}else if(S_ISLNK(statbuf.st_mode)){
if(lstat(".", &statbuf) == -1){
perror("lstat2 failed");
exit(1);
}
fileName = argv[i]; //Holds file name if sys link
isSysLink = true;
statbuf.st_mode = 0;//Resets statbuf
//Flag checking
}else{
statbuf.st_mode = 0;//Resets statbuf
if(argv[i][0] == '-'){
for(int j = 1; argv[i][j] != 0; j++){
if(argv[i][j] == 'a'){
flags |= FLAG_a;
}else if(argv[i][j] == 'l'){
flags |= FLAG_l;
}else if(argv[i][j] == 'R'){
flags |= FLAG_R;
}
}
}else{
//Assigns garbage value to dirName so it will
//return an error on opendir
dirName = argv[i];
}
}
}
//Output vector
vector<string> v;
char temp[512];
//Checks validity of directory
DIR *dirp;
dirent *direntp;
if((dirp = opendir(dirName)));
else{
perror("opendir failed");
exit(1);
}
//Skips . and .. if -a not passed
if((flags == 0) || (flags == 2) || (flags == 4)){
if(direntp = readdir(dirp)){
}else{
perror("readdir1 failed");
}
if(direntp = readdir(dirp)){
}else{
perror("readdir2 failed");
}
}
//Remaining part of dir is read
errno = 0;
while((direntp = readdir(dirp))){
v.push_back(direntp->d_name);
}
if(errno != 0){
perror("readdir3 failed");
}
//Closes dir
if(closedir(dirp) == -1){
perror("closedir error");
}
//FIXME - Make case insensitive later
sort(v.begin(), v.end());
//Output Handler
for(unsigned i = 0; i < v.size(); i++){
bool isValid = true; //Used to check with fileName's passed in
//ls or ls -a
if((flags == 0) || (flags == 1)){
if(fileName != ""){//if a file was passed
isValid = false;
if(fileName == v.at(i)){ //if this matches that file
isValid = true;
}
}
//No file passed or a match found, print
if(isValid){
cout << v.at(i) << endl;
}
//ls -l or ls -la
}else if((flags == 2) || (flags == 3)){
if(fileName != ""){//if file passed
isValid = false;
if(fileName == v.at(i)){//of this IS file
isValid = true;
}
}
if(isValid){//no file passed
//File type check
if(isSysLink){
cout << "l";
}else if(S_ISDIR(statbuf.st_mode)){
cout << "d";
}else{
cout << "-";
}
//FIXME - Use dirName.at().size() + v.at(i).size() + 1?
//Appends ./ and prepends / to dirName
char str[sizeof(dirName) + sizeof(v.at(i)) + 128];
strcpy(str, "./");
strcat(str, dirName);
strcat(str, "/");
string str1 = v.at(i);
strcat(str, str1.c_str());
if(stat(str, &statbuf) == -1){//Sets statbuf
perror("stat() failed");
exit(1);
}
if(statbuf.st_mode & S_IRUSR){//Owner permissions
cout << "r";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IWUSR){
cout << "w";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IXUSR){
cout << "x";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IRGRP){//Group permissions
cout << "r";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IWGRP){
cout << "w";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IXGRP){
cout << "x";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IROTH){//Other permissions
cout << "r";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IWOTH){
cout << "w";
}else{
cout << "-";
}
if(statbuf.st_mode & S_IXOTH){
cout << "x";
}else{
cout << "-";
}
int num = 0;
if(num = statbuf.st_nlink){//Num system links
cout << " " << num << " ";
}else{
perror("st_nlink error");
exit(1);
}
struct passwd *pwd;
if((pwd = getpwuid(statbuf.st_uid)) != NULL){//User ID
cout << pwd->pw_name << " ";
}else{
perror("getpwuid failed");
exit(1);
}
struct group *grp;
if((grp = getgrgid(statbuf.st_gid)) != NULL){//Group ID
cout << grp->gr_name << " ";
}else{
perror("getgrgid failed");
exit(1);
}
cout << statbuf.st_size << " "; //File size in bytes
if(num = statbuf.st_mtime){//Time of last modification
time_t rawtime = statbuf.st_mtime;
char buffer [80];
struct tm *timeinfo;
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%b %e %H:%M", timeinfo);
cout << buffer << " ";
}else{
perror("st_mtime failed");
exit(1);
}
cout << v.at(i) << endl;
}else if((flags == 4) || (flags == 5)){
//if FileName is a directory
//if Curr file is directory - enter it
}else if((flags == 6) || (flags == 7)){//ls -lR and ls -alR
//-l AND -R are set
//if curr file is dir; enter it
//output with -l info
}
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* NCG written in 2015 by Maciej A. Czyzewski
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>. */
#include "../include/random.h"
#include <cstring>
#include <ctime>
#include <unistd.h>
// S - seed, I - increment, t - mask, i - temporary
static uint32_t S, I, t, i;
// The length of the initial states
#define SIZE 16
// Abbreviation for getting values from the matrix
#define M(i) ((i) & (SIZE - 1))
// Bit rotation
#define R(x, y) (((x) << (y)) | ((x) >> (16 - (y))))
// XOR gate, relationships
#define L(x, y) { \
(y) ^= ((x) << 5) ^ ((y) >> 3) ^ ((x) >> 1); \
(x) ^= ((y) << 8) ^ ((x) << 3) ^ ((y) << 9); \
}
// Variebles in the algorithm
static uint16_t a, b, c, d;
// Initial state matrix (pi digits)
static uint16_t G[SIZE], Q[SIZE] = { 1, 4, 1, 5, 9, 2, 6, 5,
3, 5, 8, 9, 7, 9, 3, 2 };
void push(uint32_t seed) {
// Preparation
I = seed * 0x3C6EF35F;
for (S = seed, i = 0; i < SIZE; i++) {
// Reinforcement
G[M(i)] ^= ((I * (S - 1)) ^ S) >> 16;
G[M(i)] ^= ((I * (S + 1)) ^ S) >> 00;
// Finalization
I ^= ((G[M(I - 1)] + G[M(i)]) << 16)
^ ((G[M(I + 1)] - G[M(i)]) << 00);
}
}
uint32_t pull() {
// Variebles
a = G[M(I + 0)]; b = G[M(I + 1)];
c = G[M(I - 2)]; d = G[M(I + 2)];
// Initialization
t = (a + I) * (b - S);
// Allowance
t ^= a ^ (b << 8) ^ (c << 16) ^ (d & 0xff) ^ ((d >> 8) << 24);
// Mixing
L(G[M(I + 0)], G[M(I - 2)]);
L(G[M(I + 0)], G[M(I + 2)]);
// Transformation
G[M(I + 0)] = G[M(t - 1)] ^ R(c, M(t)) ^ R(d, M(t)) ^ a;
G[M(I + 1)] = (b >> 1) ^ (-(b & 1u) & 0xB400u); // LFSR
// Increment
I += 2;
return t;
}
void reset() {
// Copying defaults
memcpy(G, Q, 2 * SIZE);
}
void ncg(uint32_t seed) {
// Cleaning state matrix
reset();
// Push to NCG structure
push(seed);
}
static uint32_t getSeed() noexcept {
uint32_t seed;
if (readRandomBytes_nothrow(&seed, sizeof(seed)) == -1)
seed = time(nullptr) ^ getpid() + errno;
return seed;
}
// Initialise generator on program start up
static int startup = (ncg(getSeed()), 0);
<commit_msg>Fix compilation error<commit_after>/* NCG written in 2015 by Maciej A. Czyzewski
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>. */
#include "../include/random.h"
#include <cstring>
#include <ctime>
#include <unistd.h>
// S - seed, I - increment, t - mask, i - temporary
static uint32_t S, I, t, i;
// The length of the initial states
#define SIZE 16
// Abbreviation for getting values from the matrix
#define M(i) ((i) & (SIZE - 1))
// Bit rotation
#define R(x, y) (((x) << (y)) | ((x) >> (16 - (y))))
// XOR gate, relationships
#define L(x, y) { \
(y) ^= ((x) << 5) ^ ((y) >> 3) ^ ((x) >> 1); \
(x) ^= ((y) << 8) ^ ((x) << 3) ^ ((y) << 9); \
}
// Variebles in the algorithm
static uint16_t a, b, c, d;
// Initial state matrix (pi digits)
static uint16_t G[SIZE], Q[SIZE] = { 1, 4, 1, 5, 9, 2, 6, 5,
3, 5, 8, 9, 7, 9, 3, 2 };
void push(uint32_t seed) {
// Preparation
I = seed * 0x3C6EF35F;
for (S = seed, i = 0; i < SIZE; i++) {
// Reinforcement
G[M(i)] ^= ((I * (S - 1)) ^ S) >> 16;
G[M(i)] ^= ((I * (S + 1)) ^ S) >> 00;
// Finalization
I ^= ((G[M(I - 1)] + G[M(i)]) << 16)
^ ((G[M(I + 1)] - G[M(i)]) << 00);
}
}
uint32_t pull() {
// Variebles
a = G[M(I + 0)]; b = G[M(I + 1)];
c = G[M(I - 2)]; d = G[M(I + 2)];
// Initialization
t = (a + I) * (b - S);
// Allowance
t ^= a ^ (b << 8) ^ (c << 16) ^ (d & 0xff) ^ ((d >> 8) << 24);
// Mixing
L(G[M(I + 0)], G[M(I - 2)]);
L(G[M(I + 0)], G[M(I + 2)]);
// Transformation
G[M(I + 0)] = G[M(t - 1)] ^ R(c, M(t)) ^ R(d, M(t)) ^ a;
G[M(I + 1)] = (b >> 1) ^ (-(b & 1u) & 0xB400u); // LFSR
// Increment
I += 2;
return t;
}
void reset() {
// Copying defaults
memcpy(G, Q, 2 * SIZE);
}
void ncg(uint32_t seed) {
// Cleaning state matrix
reset();
// Push to NCG structure
push(seed);
}
static uint32_t getSeed() noexcept {
uint32_t seed;
if (readRandomBytes_nothrow(&seed, sizeof(seed)) == -1)
seed = (time(nullptr) * errno) ^ getpid();
return seed;
}
// Initialise generator on program start up
static int startup = (ncg(getSeed()), 0);
<|endoftext|>
|
<commit_before>#include "nonsocket.h"
// LuaSocket
extern "C" {
#include "luasocket.h"
#include "mime.h"
}
// Quick macro for adding functions to
// the preloder.
#define PRELOAD(name, function) \
lua_getglobal(L, "package"); \
lua_getfield(L, -1, "preload"); \
lua_pushcfunction(L, function); \
lua_setfield(L, -2, name); \
lua_pop(L, 2);
int open_luasocket(lua_State * L)
{
PRELOAD("socket.core", luaopen_socket_core);
PRELOAD("mime.core", luaopen_mime_core);
PRELOAD("socket", open_luasocket_socket);
PRELOAD("socket.headers", open_luasocket_headers);
PRELOAD("socket.ftp", open_luasocket_ftp)
PRELOAD("socket.http", open_luasocket_http);
PRELOAD("ltn12", open_luasocket_ltn12);
PRELOAD("mime", open_luasocket_mime)
PRELOAD("socket.smtp", open_luasocket_smtp);
PRELOAD("socket.tp", open_luasocket_tp)
PRELOAD("socket.url", open_luasocket_url)
return 0;
}
int open_luasocket_socket(lua_State * L)
{
#include <luasocket/socket.lua.h>
return 1;
}
int open_luasocket_headers(lua_State * L)
{
#include <luasocket/headers.lua.h>
return 1;
}
int open_luasocket_ftp(lua_State * L)
{
#include <luasocket/ftp.lua.h>
return 1;
}
int open_luasocket_http(lua_State * L)
{
#include <luasocket/http.lua.h>
return 1;
}
int open_luasocket_ltn12(lua_State * L)
{
#include <luasocket/ltn12.lua.h>
return 1;
}
int open_luasocket_mime(lua_State * L)
{
#include <luasocket/mime.lua.h>
return 1;
}
int open_luasocket_smtp(lua_State * L)
{
#include <luasocket/smtp.lua.h>
return 1;
}
int open_luasocket_tp(lua_State * L)
{
#include <luasocket/tp.lua.h>
return 1;
}
int open_luasocket_url(lua_State * L)
{
#include <luasocket/url.lua.h>
return 1;
}
<commit_msg>Another include path fixes<commit_after>#include "nonsocket.h"
extern "C" {
#include "luasocket.h"
#include "mime.h"
}
#define PRELOAD(name, function) \
lua_getglobal(L, "package"); \
lua_getfield(L, -1, "preload"); \
lua_pushcfunction(L, function); \
lua_setfield(L, -2, name); \
lua_pop(L, 2);
int open_luasocket(lua_State * L)
{
PRELOAD("socket.core", luaopen_socket_core);
PRELOAD("mime.core", luaopen_mime_core);
PRELOAD("socket", open_luasocket_socket);
PRELOAD("socket.headers", open_luasocket_headers);
PRELOAD("socket.ftp", open_luasocket_ftp)
PRELOAD("socket.http", open_luasocket_http);
PRELOAD("ltn12", open_luasocket_ltn12);
PRELOAD("mime", open_luasocket_mime)
PRELOAD("socket.smtp", open_luasocket_smtp);
PRELOAD("socket.tp", open_luasocket_tp)
PRELOAD("socket.url", open_luasocket_url)
return 0;
}
int open_luasocket_socket(lua_State * L)
{
#include "socket.lua.h"
return 1;
}
int open_luasocket_headers(lua_State * L)
{
#include "headers.lua.h"
return 1;
}
int open_luasocket_ftp(lua_State * L)
{
#include "ftp.lua.h"
return 1;
}
int open_luasocket_http(lua_State * L)
{
#include "http.lua.h"
return 1;
}
int open_luasocket_ltn12(lua_State * L)
{
#include "ltn12.lua.h"
return 1;
}
int open_luasocket_mime(lua_State * L)
{
#include "mime.lua.h"
return 1;
}
int open_luasocket_smtp(lua_State * L)
{
#include "smtp.lua.h"
return 1;
}
int open_luasocket_tp(lua_State * L)
{
#include "tp.lua.h"
return 1;
}
int open_luasocket_url(lua_State * L)
{
#include "url.lua.h"
return 1;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <Aclapi.h>
#include <windows.h>
#include <string>
#include "sandbox/win/tests/validation_tests/commands.h"
#include "sandbox/win/tests/common/controller.h"
namespace {
// Returns the HKEY corresponding to name. If there is no HKEY corresponding
// to the name it returns NULL.
HKEY GetHKEYFromString(const base::string16 &name) {
if (L"HKLM" == name)
return HKEY_LOCAL_MACHINE;
else if (L"HKCR" == name)
return HKEY_CLASSES_ROOT;
else if (L"HKCC" == name)
return HKEY_CURRENT_CONFIG;
else if (L"HKCU" == name)
return HKEY_CURRENT_USER;
else if (L"HKU" == name)
return HKEY_USERS;
return NULL;
}
// Modifies string to remove the leading and trailing quotes.
void trim_quote(base::string16* string) {
base::string16::size_type pos1 = string->find_first_not_of(L'"');
base::string16::size_type pos2 = string->find_last_not_of(L'"');
if (base::string16::npos == pos1 || base::string16::npos == pos2)
(*string) = L"";
else
(*string) = string->substr(pos1, pos2 + 1);
}
int TestOpenFile(base::string16 path, bool for_write) {
wchar_t path_expanded[MAX_PATH + 1] = {0};
DWORD size = ::ExpandEnvironmentStrings(path.c_str(), path_expanded,
MAX_PATH);
if (!size)
return sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
HANDLE file;
file = ::CreateFile(path_expanded,
for_write ? GENERIC_READ | GENERIC_WRITE : GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, // No security attributes.
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL); // No template.
if (INVALID_HANDLE_VALUE != file) {
::CloseHandle(file);
return sandbox::SBOX_TEST_SUCCEEDED;
} else {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return sandbox::SBOX_TEST_DENIED;
} else {
return sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
}
}
} // namespace
namespace sandbox {
SBOX_TESTS_COMMAND int ValidWindow(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
HWND window = reinterpret_cast<HWND>(static_cast<ULONG_PTR>(_wtoi(argv[0])));
return TestValidWindow(window);
}
int TestValidWindow(HWND window) {
if (::IsWindow(window))
return SBOX_TEST_SUCCEEDED;
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int OpenProcessCmd(int argc, wchar_t **argv) {
if (2 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
DWORD process_id = _wtol(argv[0]);
DWORD access_mask = _wtol(argv[1]);
return TestOpenProcess(process_id, access_mask);
}
int TestOpenProcess(DWORD process_id, DWORD access_mask) {
HANDLE process = ::OpenProcess(access_mask,
FALSE, // Do not inherit handle.
process_id);
if (NULL == process) {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return SBOX_TEST_DENIED;
} else {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
} else {
::CloseHandle(process);
return SBOX_TEST_SUCCEEDED;
}
}
SBOX_TESTS_COMMAND int OpenThreadCmd(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
DWORD thread_id = _wtoi(argv[0]);
return TestOpenThread(thread_id);
}
int TestOpenThread(DWORD thread_id) {
HANDLE thread = ::OpenThread(THREAD_QUERY_INFORMATION,
FALSE, // Do not inherit handles.
thread_id);
if (NULL == thread) {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return SBOX_TEST_DENIED;
} else {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
} else {
::CloseHandle(thread);
return SBOX_TEST_SUCCEEDED;
}
}
SBOX_TESTS_COMMAND int OpenFileCmd(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
base::string16 path = argv[0];
trim_quote(&path);
return TestOpenReadFile(path);
}
int TestOpenReadFile(const base::string16& path) {
return TestOpenFile(path, false);
}
int TestOpenWriteFile(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
base::string16 path = argv[0];
trim_quote(&path);
return TestOpenWriteFile(path);
}
int TestOpenWriteFile(const base::string16& path) {
return TestOpenFile(path, true);
}
SBOX_TESTS_COMMAND int OpenKey(int argc, wchar_t **argv) {
if (0 == argc || argc > 2)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
// Get the hive.
HKEY base_key = GetHKEYFromString(argv[0]);
// Get the subkey.
base::string16 subkey;
if (2 == argc) {
subkey = argv[1];
trim_quote(&subkey);
}
return TestOpenKey(base_key, subkey);
}
int TestOpenKey(HKEY base_key, base::string16 subkey) {
HKEY key;
LONG err_code = ::RegOpenKeyEx(base_key,
subkey.c_str(),
0, // Reserved, must be 0.
MAXIMUM_ALLOWED,
&key);
if (ERROR_SUCCESS == err_code) {
::RegCloseKey(key);
return SBOX_TEST_SUCCEEDED;
} else if (ERROR_INVALID_HANDLE == err_code ||
ERROR_ACCESS_DENIED == err_code) {
return SBOX_TEST_DENIED;
} else {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
}
// Returns true if the current's thread desktop is the interactive desktop.
// In Vista there is a more direct test but for XP and w2k we need to check
// the object name.
bool IsInteractiveDesktop(bool* is_interactive) {
HDESK current_desk = ::GetThreadDesktop(::GetCurrentThreadId());
if (NULL == current_desk) {
return false;
}
wchar_t current_desk_name[256] = {0};
if (!::GetUserObjectInformationW(current_desk, UOI_NAME, current_desk_name,
sizeof(current_desk_name), NULL)) {
return false;
}
*is_interactive = (0 == _wcsicmp(L"default", current_desk_name));
return true;
}
SBOX_TESTS_COMMAND int OpenInteractiveDesktop(int, wchar_t **) {
return TestOpenInputDesktop();
}
int TestOpenInputDesktop() {
bool is_interactive = false;
if (IsInteractiveDesktop(&is_interactive) && is_interactive) {
return SBOX_TEST_SUCCEEDED;
}
HDESK desk = ::OpenInputDesktop(0, FALSE, DESKTOP_CREATEWINDOW);
if (desk) {
::CloseDesktop(desk);
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int SwitchToSboxDesktop(int, wchar_t **) {
return TestSwitchDesktop();
}
int TestSwitchDesktop() {
HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId());
if (NULL == desktop) {
return SBOX_TEST_FAILED;
}
if (::SwitchDesktop(desktop)) {
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int OpenAlternateDesktop(int, wchar_t **argv) {
return TestOpenAlternateDesktop(argv[0]);
}
int TestOpenAlternateDesktop(wchar_t *desktop_name) {
// Test for WRITE_DAC permission on the handle.
HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId());
if (desktop) {
HANDLE test_handle;
if (::DuplicateHandle(::GetCurrentProcess(), desktop,
::GetCurrentProcess(), &test_handle,
WRITE_DAC, FALSE, 0)) {
DWORD result = ::SetSecurityInfo(test_handle, SE_WINDOW_OBJECT,
DACL_SECURITY_INFORMATION, NULL, NULL,
NULL, NULL);
::CloseHandle(test_handle);
if (result != ERROR_ACCESS_DENIED) {
return SBOX_TEST_SUCCEEDED;
}
} else if (::GetLastError() != ERROR_ACCESS_DENIED) {
return SBOX_TEST_FAILED;
}
}
// Open by name with WRITE_DAC.
desktop = ::OpenDesktop(desktop_name, 0, FALSE, WRITE_DAC);
if (desktop || ::GetLastError() != ERROR_ACCESS_DENIED) {
::CloseDesktop(desktop);
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
BOOL CALLBACK DesktopTestEnumProc(LPTSTR desktop_name, LPARAM result) {
return TRUE;
}
SBOX_TESTS_COMMAND int EnumAlternateWinsta(int, wchar_t **) {
return TestEnumAlternateWinsta();
}
int TestEnumAlternateWinsta() {
int result = SBOX_TEST_DENIED;
// Try to enumerate the destops on the alternate windowstation.
if (::EnumDesktopsW(NULL, DesktopTestEnumProc, 0)) {
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int SleepCmd(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
::Sleep(_wtoi(argv[0]));
return SBOX_TEST_SUCCEEDED;
}
SBOX_TESTS_COMMAND int AllocateCmd(int argc, wchar_t **argv) {
if (argc != 1)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
size_t mem_size = static_cast<size_t>(_wtoll(argv[0]));
void* memory = ::VirtualAlloc(NULL, mem_size, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!memory) {
// We need to give the broker a chance to kill our process on failure.
::Sleep(5000);
return SBOX_TEST_DENIED;
}
if (!::VirtualFree(memory, 0, MEM_RELEASE))
return SBOX_TEST_FAILED;
return SBOX_TEST_SUCCEEDED;
}
} // namespace sandbox
<commit_msg>Fix sbox_validation_tests for Server 2012R2<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <Aclapi.h>
#include <windows.h>
#include <string>
#include "sandbox/win/tests/validation_tests/commands.h"
#include "sandbox/win/tests/common/controller.h"
namespace {
// Returns the HKEY corresponding to name. If there is no HKEY corresponding
// to the name it returns NULL.
HKEY GetHKEYFromString(const base::string16 &name) {
if (L"HKLM" == name)
return HKEY_LOCAL_MACHINE;
else if (L"HKCR" == name)
return HKEY_CLASSES_ROOT;
else if (L"HKCC" == name)
return HKEY_CURRENT_CONFIG;
else if (L"HKCU" == name)
return HKEY_CURRENT_USER;
else if (L"HKU" == name)
return HKEY_USERS;
return NULL;
}
// Modifies string to remove the leading and trailing quotes.
void trim_quote(base::string16* string) {
base::string16::size_type pos1 = string->find_first_not_of(L'"');
base::string16::size_type pos2 = string->find_last_not_of(L'"');
if (base::string16::npos == pos1 || base::string16::npos == pos2)
(*string) = L"";
else
(*string) = string->substr(pos1, pos2 + 1);
}
int TestOpenFile(base::string16 path, bool for_write) {
wchar_t path_expanded[MAX_PATH + 1] = {0};
DWORD size = ::ExpandEnvironmentStrings(path.c_str(), path_expanded,
MAX_PATH);
if (!size)
return sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
HANDLE file;
file = ::CreateFile(path_expanded,
for_write ? GENERIC_READ | GENERIC_WRITE : GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, // No security attributes.
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL); // No template.
if (INVALID_HANDLE_VALUE != file) {
::CloseHandle(file);
return sandbox::SBOX_TEST_SUCCEEDED;
} else {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return sandbox::SBOX_TEST_DENIED;
} else {
return sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
}
}
} // namespace
namespace sandbox {
SBOX_TESTS_COMMAND int ValidWindow(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
HWND window = reinterpret_cast<HWND>(static_cast<ULONG_PTR>(_wtoi(argv[0])));
return TestValidWindow(window);
}
int TestValidWindow(HWND window) {
if (::IsWindow(window))
return SBOX_TEST_SUCCEEDED;
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int OpenProcessCmd(int argc, wchar_t **argv) {
if (2 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
DWORD process_id = _wtol(argv[0]);
DWORD access_mask = _wtol(argv[1]);
return TestOpenProcess(process_id, access_mask);
}
int TestOpenProcess(DWORD process_id, DWORD access_mask) {
HANDLE process = ::OpenProcess(access_mask,
FALSE, // Do not inherit handle.
process_id);
if (NULL == process) {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return SBOX_TEST_DENIED;
} else {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
} else {
::CloseHandle(process);
return SBOX_TEST_SUCCEEDED;
}
}
SBOX_TESTS_COMMAND int OpenThreadCmd(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
DWORD thread_id = _wtoi(argv[0]);
return TestOpenThread(thread_id);
}
int TestOpenThread(DWORD thread_id) {
HANDLE thread = ::OpenThread(THREAD_QUERY_INFORMATION,
FALSE, // Do not inherit handles.
thread_id);
if (NULL == thread) {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
return SBOX_TEST_DENIED;
} else {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
} else {
::CloseHandle(thread);
return SBOX_TEST_SUCCEEDED;
}
}
SBOX_TESTS_COMMAND int OpenFileCmd(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
base::string16 path = argv[0];
trim_quote(&path);
return TestOpenReadFile(path);
}
int TestOpenReadFile(const base::string16& path) {
return TestOpenFile(path, false);
}
int TestOpenWriteFile(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
base::string16 path = argv[0];
trim_quote(&path);
return TestOpenWriteFile(path);
}
int TestOpenWriteFile(const base::string16& path) {
return TestOpenFile(path, true);
}
SBOX_TESTS_COMMAND int OpenKey(int argc, wchar_t **argv) {
if (0 == argc || argc > 2)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
// Get the hive.
HKEY base_key = GetHKEYFromString(argv[0]);
// Get the subkey.
base::string16 subkey;
if (2 == argc) {
subkey = argv[1];
trim_quote(&subkey);
}
return TestOpenKey(base_key, subkey);
}
int TestOpenKey(HKEY base_key, base::string16 subkey) {
HKEY key;
LONG err_code = ::RegOpenKeyEx(base_key,
subkey.c_str(),
0, // Reserved, must be 0.
MAXIMUM_ALLOWED,
&key);
if (ERROR_SUCCESS == err_code) {
::RegCloseKey(key);
return SBOX_TEST_SUCCEEDED;
} else if (ERROR_INVALID_HANDLE == err_code ||
ERROR_ACCESS_DENIED == err_code) {
return SBOX_TEST_DENIED;
} else {
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
}
// Returns true if the current's thread desktop is the interactive desktop.
// In Vista there is a more direct test but for XP and w2k we need to check
// the object name.
bool IsInteractiveDesktop(bool* is_interactive) {
HDESK current_desk = ::GetThreadDesktop(::GetCurrentThreadId());
if (NULL == current_desk) {
return false;
}
wchar_t current_desk_name[256] = {0};
if (!::GetUserObjectInformationW(current_desk, UOI_NAME, current_desk_name,
sizeof(current_desk_name), NULL)) {
return false;
}
*is_interactive = (0 == _wcsicmp(L"default", current_desk_name));
return true;
}
SBOX_TESTS_COMMAND int OpenInteractiveDesktop(int, wchar_t **) {
return TestOpenInputDesktop();
}
int TestOpenInputDesktop() {
bool is_interactive = false;
if (IsInteractiveDesktop(&is_interactive) && is_interactive) {
return SBOX_TEST_SUCCEEDED;
}
HDESK desk = ::OpenInputDesktop(0, FALSE, DESKTOP_CREATEWINDOW);
if (desk) {
::CloseDesktop(desk);
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int SwitchToSboxDesktop(int, wchar_t **) {
return TestSwitchDesktop();
}
int TestSwitchDesktop() {
HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId());
if (NULL == desktop) {
return SBOX_TEST_FAILED;
}
if (::SwitchDesktop(desktop)) {
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int OpenAlternateDesktop(int, wchar_t **argv) {
return TestOpenAlternateDesktop(argv[0]);
}
int TestOpenAlternateDesktop(wchar_t *desktop_name) {
// Test for WRITE_DAC permission on the handle.
HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId());
if (desktop) {
HANDLE test_handle;
if (::DuplicateHandle(::GetCurrentProcess(), desktop,
::GetCurrentProcess(), &test_handle,
WRITE_DAC, FALSE, 0)) {
DWORD result = ::SetSecurityInfo(test_handle, SE_WINDOW_OBJECT,
DACL_SECURITY_INFORMATION, NULL, NULL,
NULL, NULL);
::CloseHandle(test_handle);
if (result == ERROR_SUCCESS) {
return SBOX_TEST_SUCCEEDED;
}
} else if (::GetLastError() != ERROR_ACCESS_DENIED) {
return SBOX_TEST_FAILED;
}
}
// Open by name with WRITE_DAC.
desktop = ::OpenDesktop(desktop_name, 0, FALSE, WRITE_DAC);
if (desktop || ::GetLastError() != ERROR_ACCESS_DENIED) {
::CloseDesktop(desktop);
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
BOOL CALLBACK DesktopTestEnumProc(LPTSTR desktop_name, LPARAM result) {
return TRUE;
}
SBOX_TESTS_COMMAND int EnumAlternateWinsta(int, wchar_t **) {
return TestEnumAlternateWinsta();
}
int TestEnumAlternateWinsta() {
int result = SBOX_TEST_DENIED;
// Try to enumerate the destops on the alternate windowstation.
if (::EnumDesktopsW(NULL, DesktopTestEnumProc, 0)) {
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int SleepCmd(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
::Sleep(_wtoi(argv[0]));
return SBOX_TEST_SUCCEEDED;
}
SBOX_TESTS_COMMAND int AllocateCmd(int argc, wchar_t **argv) {
if (argc != 1)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
size_t mem_size = static_cast<size_t>(_wtoll(argv[0]));
void* memory = ::VirtualAlloc(NULL, mem_size, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!memory) {
// We need to give the broker a chance to kill our process on failure.
::Sleep(5000);
return SBOX_TEST_DENIED;
}
if (!::VirtualFree(memory, 0, MEM_RELEASE))
return SBOX_TEST_FAILED;
return SBOX_TEST_SUCCEEDED;
}
} // namespace sandbox
<|endoftext|>
|
<commit_before>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h"
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
// #include "Adafruit_MAX31856.h"
#include "Nanoshield_Termopar.h"
#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288
#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10
#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space
#ifdef SERIAL_EN
#define DEBUG(input) {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif
ISR(WDT_vect) { Sleepy::watchdogEvent(); }
/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 0;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Nanoshield_Termopar tc1(TC1_CS, TC_TYPE_T);
Nanoshield_Termopar tc2(TC2_CS, TC_TYPE_T);
Nanoshield_Termopar tc3(TC3_CS, TC_TYPE_T);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 30000;
const uint16_t REC_INTERVAL = (30000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this
//Data structure for storing data locally (12 bytes)
struct Data {
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
uint32_t timestamp;
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
Payload thePayload;
struct Measurement {
uint16_t tc1 = 22;
uint16_t tc2 = 23;
uint16_t tc3 = 24;
};
Measurement thisMeasurement;
uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
uint32_t saved_time = 0;
uint16_t interval = 1000;
void setup()
{
#ifdef SERIAL_EN
Serial.begin(SERIAL_BAUD);
#endif
randomSeed(analogRead(A4)); //set random seed
NETWORKID += setAddress();
radio.initialize(FREQUENCY,NODEID,NETWORKID);
radio.setHighPower();
radio.encrypt(null);
radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
pinMode(LED, OUTPUT);
// Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
digitalWrite(LED, HIGH); //write LED high to signal attempting connection
while(!getTime()) { //this saves time to the struct which holds the time globally
radio.sleep();
DEBUGFlush();
delay(10000);
}
digitalWrite(LED, LOW); //write low to signal success
DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");
tc1.begin();
tc2.begin();
tc3.begin();
DEBUGln("--Thermocouples are engaged");
DEBUG("--Flash Mem: ");
flash.begin();
uint16_t _name = flash.getChipName();
uint32_t capacity = flash.getCapacity();
DEBUG("W25X"); DEBUG(_name); DEBUG("** ");
DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
DEBUGln("Erasing Chip!"); flash.eraseChip();
// flash.powerDown();
}
void loop()
{
if(sentMeasurement) {
DEBUG("sleep - sleeping for "); DEBUG(REC_INTERVAL); DEBUG(" seconds"); DEBUGln();
DEBUGFlush();
radio.sleep();
count++;
for(int i = 0; i < REC_MIN; i++)
Sleepy::loseSomeTime(REC_MS);
//===========|| MCU WAKES UP HERE
//===========|| RESET TIMER VALUES
sentMeasurement = 0;
current_time = millis();
stop_saved_time = current_time;
h_saved_time = current_time;
log_saved_time = current_time;
h_interval = 0;
getTime();
} else {
current_time = millis();
if(stop_saved_time + stop_time > current_time) {
if (h_saved_time + h_interval < current_time){
if(h_status == 0) { //if it is off, turn it on
digitalWrite(HEATER_EN, HIGH);
h_interval = h_pulse_on; //wait for ON time
h_status = 1;
DEBUG("Heater - On for "); DEBUG(h_interval/1000); DEBUGln("s");
} else if(h_status == 1) {//if heat is on....turn it off
digitalWrite(HEATER_EN, LOW);
h_interval = h_pulse_off; //wait for OFF time
h_status = 0;
DEBUG("Heater - Off for "); DEBUG(h_interval/1000); DEBUGln("s");
}
h_saved_time = current_time;
}
if(log_saved_time + log_interval < current_time) {
tc1.read(); tc2.read(); tc3.read();
DEBUGln(tc1.getExternal());
DEBUGln(tc2.getExternal());
DEBUGln(tc3.getExternal());
if(flash.writeAnything(FLASH_ADDR, thisMeasurement)) {
DEBUG("data - ");
DEBUG(thisMeasurement.tc1); DEBUG(",");
DEBUG(thisMeasurement.tc2); DEBUG(",");
DEBUG(thisMeasurement.tc3); DEBUG(",");
DEBUG("at Address "); DEBUGln(FLASH_ADDR);
}
FLASH_ADDR += sizeof(thisMeasurement);
log_saved_time = current_time;
}
} else {
DEBUGln("SEND MEASUREMENTS");
sentMeasurement = 1;
}
}
}
/**
* [getTime description]
* @return [description]
*/
bool getTime()
{
LED_STATE = true;
digitalWrite(LED, LED_STATE);
//Get the current timestamp from the datalogger
bool TIME_RECIEVED = false;
if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
DEBUG("time - ");
if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
DEBUG("snd . . ");
HANDSHAKE_SENT = true;
}
else {
DEBUGln("failed . . . no ack");
return false; //if there is no response, returns false and exits function
}
}
while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
if (radio.receiveDone()) {
if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
theTimeStamp = *(TimeStamp*)radio.DATA; //save data
DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
DEBUG(theTimeStamp.timestamp);
DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
DEBUGln();
TIME_RECIEVED = true;
LED_STATE = false;
digitalWrite(LED, LED_STATE);
}
if (radio.ACKRequested()) radio.sendACK();
}
}
HANDSHAKE_SENT = false;
return true;
}
/**
* [Blink description]
* @param t [description]
*/
void Blink(uint8_t t) {
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
}
/**
* [setAddress description]
* @return [description]
*/
uint8_t setAddress() {
//sets network address based on which solder jumpers are closed
uint8_t addr01, addr02, addr03;
pinMode(N_SEL_1, INPUT_PULLUP);
pinMode(N_SEL_2, INPUT_PULLUP);
pinMode(N_SEL_4, INPUT_PULLUP);
addr01 = !digitalRead(N_SEL_1);
addr02 = !digitalRead(N_SEL_2) * 2;
addr03 = !digitalRead(N_SEL_4) * 4;
pinMode(N_SEL_1, OUTPUT);
pinMode(N_SEL_2, OUTPUT);
pinMode(N_SEL_4, OUTPUT);
digitalWrite(N_SEL_1, HIGH);
digitalWrite(N_SEL_2, HIGH);
digitalWrite(N_SEL_4, HIGH);
uint8_t addr = addr01 | addr02 | addr03;
return addr;
}
<commit_msg>Fucked again<commit_after>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h"
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
// #include "Adafruit_MAX31856.h"
#include "Nanoshield_Termopar.h"
#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288
#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10
#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space
#ifdef SERIAL_EN
#define DEBUG(input) {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif
ISR(WDT_vect) { Sleepy::watchdogEvent(); }
/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 0;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Nanoshield_Termopar tc1(TC1_CS, TC_TYPE_T, TC_AVG_4_SAMPLES);
Nanoshield_Termopar tc2(TC2_CS, TC_TYPE_T, TC_AVG_4_SAMPLES);
Nanoshield_Termopar tc3(TC3_CS, TC_TYPE_T, TC_AVG_4_SAMPLES);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 30000;
const uint16_t REC_INTERVAL = (30000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this
//Data structure for storing data locally (12 bytes)
struct Data {
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
uint32_t timestamp;
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
Payload thePayload;
struct Measurement {
double tc1 = 22;
double tc2 = 23;
double tc3 = 24;
};
Measurement thisMeasurement;
uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
uint32_t saved_time = 0;
uint16_t interval = 1000;
void setup()
{
#ifdef SERIAL_EN
Serial.begin(SERIAL_BAUD);
#endif
randomSeed(analogRead(A4)); //set random seed
NETWORKID += setAddress();
radio.initialize(FREQUENCY,NODEID,NETWORKID);
radio.setHighPower();
radio.encrypt(null);
radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
pinMode(LED, OUTPUT);
// Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
digitalWrite(LED, HIGH); //write LED high to signal attempting connection
while(!getTime()) { //this saves time to the struct which holds the time globally
radio.sleep();
DEBUGFlush();
delay(10000);
}
digitalWrite(LED, LOW); //write low to signal success
DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");
tc1.begin();
tc2.begin();
tc3.begin();
DEBUGln("--Thermocouples are engaged");
DEBUG("--Flash Mem: ");
flash.begin();
uint16_t _name = flash.getChipName();
uint32_t capacity = flash.getCapacity();
DEBUG("W25X"); DEBUG(_name); DEBUG("** ");
DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
DEBUGln("Erasing Chip!"); flash.eraseChip();
// flash.powerDown();
}
void loop()
{
if(sentMeasurement) {
DEBUG("sleep - sleeping for "); DEBUG(REC_INTERVAL); DEBUG(" seconds"); DEBUGln();
DEBUGFlush();
radio.sleep();
count++;
for(int i = 0; i < REC_MIN; i++)
Sleepy::loseSomeTime(REC_MS);
//===========|| MCU WAKES UP HERE
//===========|| RESET TIMER VALUES
sentMeasurement = 0;
current_time = millis();
stop_saved_time = current_time;
h_saved_time = current_time;
log_saved_time = current_time;
h_interval = 0;
getTime();
} else {
current_time = millis();
if(stop_saved_time + stop_time > current_time) {
if (h_saved_time + h_interval < current_time){
if(h_status == 0) { //if it is off, turn it on
digitalWrite(HEATER_EN, HIGH);
h_interval = h_pulse_on; //wait for ON time
h_status = 1;
DEBUG("Heater - On for "); DEBUG(h_interval/1000); DEBUGln("s");
} else if(h_status == 1) {//if heat is on....turn it off
digitalWrite(HEATER_EN, LOW);
h_interval = h_pulse_off; //wait for OFF time
h_status = 0;
DEBUG("Heater - Off for "); DEBUG(h_interval/1000); DEBUGln("s");
}
h_saved_time = current_time;
}
if(log_saved_time + log_interval < current_time) {
tc1.read(); tc2.read(); tc3.read();
// DEBUG(tc1.getExternal()); DEBUG(",");
// DEBUG(tc2.getExternal()); DEBUG(",");
// DEBUG(tc3.getExternal());
// DEBUGln();
// SPI.endTransaction();
// flash.begin();
// thisMeasurement.tc1 = tc1.getExternal();
// thisMeasurement.tc2 = tc2.getExternal();
// thisMeasurement.tc3 = tc3.getExternal();
if(flash.writeAnything(FLASH_ADDR, thisMeasurement)) {
DEBUGln(".");
// DEBUG(thisMeasurement.tc1); DEBUG(",");
// DEBUG(thisMeasurement.tc2); DEBUG(",");
// DEBUG(thisMeasurement.tc3); DEBUG(",");
// DEBUG("at Address "); DEBUGln(FLASH_ADDR);
}
FLASH_ADDR += sizeof(thisMeasurement);
log_saved_time = current_time;
}
} else {
DEBUGln("SEND MEASUREMENTS");
sentMeasurement = 1;
}
}
}
/**
* [getTime description]
* @return [description]
*/
bool getTime()
{
LED_STATE = true;
digitalWrite(LED, LED_STATE);
//Get the current timestamp from the datalogger
bool TIME_RECIEVED = false;
if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
DEBUG("time - ");
if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
DEBUG("snd . . ");
HANDSHAKE_SENT = true;
}
else {
DEBUGln("failed . . . no ack");
return false; //if there is no response, returns false and exits function
}
}
while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
if (radio.receiveDone()) {
if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
theTimeStamp = *(TimeStamp*)radio.DATA; //save data
DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
DEBUG(theTimeStamp.timestamp);
DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
DEBUGln();
TIME_RECIEVED = true;
LED_STATE = false;
digitalWrite(LED, LED_STATE);
}
if (radio.ACKRequested()) radio.sendACK();
}
}
HANDSHAKE_SENT = false;
return true;
}
/**
* [Blink description]
* @param t [description]
*/
void Blink(uint8_t t) {
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
}
/**
* [setAddress description]
* @return [description]
*/
uint8_t setAddress() {
//sets network address based on which solder jumpers are closed
uint8_t addr01, addr02, addr03;
pinMode(N_SEL_1, INPUT_PULLUP);
pinMode(N_SEL_2, INPUT_PULLUP);
pinMode(N_SEL_4, INPUT_PULLUP);
addr01 = !digitalRead(N_SEL_1);
addr02 = !digitalRead(N_SEL_2) * 2;
addr03 = !digitalRead(N_SEL_4) * 4;
pinMode(N_SEL_1, OUTPUT);
pinMode(N_SEL_2, OUTPUT);
pinMode(N_SEL_4, OUTPUT);
digitalWrite(N_SEL_1, HIGH);
digitalWrite(N_SEL_2, HIGH);
digitalWrite(N_SEL_4, HIGH);
uint8_t addr = addr01 | addr02 | addr03;
return addr;
}
<|endoftext|>
|
<commit_before>/**
* @file Cosa/Trace.hh
* @version 1.0
*
* @section License
* Copyright (C) 2012-2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef COSA_TRACE_HH
#define COSA_TRACE_HH
#include "Cosa/Types.h"
#include "Cosa/IOStream.hh"
/**
* Basic trace support class. Combind IOStream with UART for trace
* output.
*/
class Trace : public IOStream {
public:
/**
* Construct Trace IOStream object and initiate with null device.
* Use begin() to set the trace device. The Trace class is actually
* a singleton, trace, as the trace macro set depends on the variable.
*/
Trace() : IOStream(), EXITCHARACTER(0x1d) {}
/**
* Start trace stream over given iostream device.
* @param[in] dev iostream device.
* @param[in] banner trace begin message.
* @return true(1) if successful otherwise false(0)
*/
bool begin(IOStream::Device* dev, str_P banner = NULL);
/**
* Stop trace stream over current device.
* @return true(1) if successful otherwise false(0)
*/
bool end()
__attribute__((always_inline))
{
set_device(NULL);
return (true);
}
/**
* Set exit character to signal fatal.
* @param[in] c new exit character.
*/
void set_exitcharacter(char c)
{
EXITCHARACTER = c;
}
/**
* Support function for ASSERT failure. Prints give function name,
* func, line number and expression that could not be validated
* to trace output device before calling exit().
* @param[in] file name.
* @param[in] line number.
* @param[in] expr program memory string with expression.
*/
void fatal(const char* file, int line, str_P expr)
__attribute__((noreturn));
/** Result of latest MEASURE */
uint32_t measure;
protected:
/** Exit from miniterm. Default CTRL-ALT GR-] (0x1d) */
char EXITCHARACTER;
};
/**
* Log priorities.
*/
#define LOG_EMERG 0 /* System is unusable */
#define LOG_ALERT 1 /* Action must be taken immediately */
#define LOG_CRIT 2 /* Critical conditions */
#define LOG_ERR 3 /* Error conditions */
#define LOG_WARNING 4 /* Warning conditions */
#define LOG_NOTICE 5 /* Normal but significant condition */
#define LOG_INFO 6 /* Informational */
#define LOG_DEBUG 7 /* Debug-level messages */
/**
* Macros to generate mask for the trace log priorities (LOG_EMERG..
* LOG_DEBUG) setting of trace_log_mask.
* LOG_MASK(prio) bit mask corresponding to the given priority.
* LOG_UPTO(prio) bit mask for all priorities including the given.
*/
#define LOG_MASK(prio) (1 << (prio))
#define LOG_UPTO(prio) (LOG_MASK((prio) + 1) - 1)
extern uint8_t trace_log_mask;
/**
* Prints given message with current file name and line number
* to trace device and the program will terminate. The message
* string is stored in program memory.
* @param[in] msg message string to print.
*/
#define FATAL(msg) \
trace.fatal(__FILE__, \
__LINE__, \
__PSTR(msg))
#ifndef NDEBUG
/**
* Support macro to check that an expression is valid. The expression
* is used as a string and evaluated. If false a message is printed
* to the trace device and the program will terminate.
* @param[in] expr expression to validate.
*/
# define ASSERT(expr) \
do { \
if (UNLIKELY(!(expr))) FATAL("assert:" #expr); \
} while (0)
/**
* Support macro for trace of a string in program memory.
* @param[in] str string literal
*/
# define TRACE_P(str) trace.print(PSTR(str))
/**
* Support macro for trace of an expression. The expression
* is used as a string and evaluated.
* @param[in] expr expression.
*/
# if defined(TRACE_NO_VERBOSE) || defined(BOARD_ATTINY)
# define TRACE(expr) \
do { \
trace.print(__PSTR(#expr " = ")); \
trace.print(expr); \
trace.println(); \
} while (0)
# else
# define TRACE(expr) \
do { \
trace.printf(__PSTR("%d:%s:trace:" #expr " = "), \
__LINE__, \
__PRETTY_FUNCTION__); \
trace.print(expr); \
trace.println(); \
} while (0)
# endif
/**
* Support macro for trace of a log message with line number and
* function name prefix.
* @param[in] msg log message.
*/
# define TRACE_LOG(msg, ...) \
trace.printf(__PSTR("%d:%s:" msg "\r\n"), \
__LINE__, \
__PRETTY_FUNCTION__, \
__VA_ARGS__)
# define IS_LOG_PRIO(prio) (trace_log_mask & LOG_MASK(prio))
# define EMERG(msg, ...) \
if (IS_LOG_PRIO(LOG_EMERG)) TRACE_LOG("emerg:" msg, __VA_ARGS__)
# define ALERT(msg, ...) \
if (IS_LOG_PRIO(LOG_ALERT)) TRACE_LOG("alert:" msg, __VA_ARGS__)
# define CRIT(msg, ...) \
if (IS_LOG_PRIO(LOG_CRIT)) TRACE_LOG("crit:" msg, __VA_ARGS__)
# define ERR(msg, ...) \
if (IS_LOG_PRIO(LOG_ERR)) TRACE_LOG("err:" msg, __VA_ARGS__)
# define WARNING(msg, ...) \
if (IS_LOG_PRIO(LOG_WARNING)) TRACE_LOG("warning:" msg, __VA_ARGS__)
# define NOTICE(msg, ...) \
if (IS_LOG_PRIO(LOG_NOTICE)) TRACE_LOG("notice:" msg, __VA_ARGS__)
# define INFO(msg, ...) \
if (IS_LOG_PRIO(LOG_INFO)) TRACE_LOG("info:" msg, __VA_ARGS__)
# define DEBUG(msg, ...) \
if (IS_LOG_PRIO(LOG_DEBUG)) TRACE_LOG("debug:" msg, __VA_ARGS__)
#else
# define ASSERT(expr)
# define TRACE_P(str)
# define TRACE(expr)
# define TRACE_LOG(msg, ...)
# define EMERG(msg, ...)
# define ALERT(msg, ...)
# define CRIT(msg, ...)
# define ERR(msg, ...)
# define WARNING(msg, ...)
# define NOTICE(msg, ...)
# define INFO(msg, ...)
# define DEBUG(msg, ...)
#endif
/**
* Syntactic sugar for measuring execution time for a block.
* Used in the form:
* @code
* MEASURE("time to execute block", 1) {
* ...
* // Block of code to measure
* ...
* ...
* }
* @endcode
* @param[in] msg measurement prefix string.
* @param[in] cnt number of block calls (max UINT16_MAX).
*/
# if defined(TRACE_NO_VERBOSE) || defined(BOARD_ATTINY)
# define MEASURE(msg,cnt) \
trace.flush(); \
for (uint32_t __stop, __start = RTC::micros(), __i = 1; \
__i != 0; \
__i--, \
__stop = RTC::micros(), \
trace.measure = (__stop - __start) / cnt, \
trace << PSTR(msg) << trace.measure, \
trace << PSTR(" us") << endl) \
for (uint16_t __j = cnt; __j != 0; __j--)
#else
# define MEASURE(msg,cnt) \
trace.flush(); \
for (uint32_t __stop, __start = RTC::micros(), __i = 1; \
__i != 0; \
__i--, \
__stop = RTC::micros(), \
trace.measure = (__stop - __start) / cnt, \
trace << __LINE__ << ':' << __PRETTY_FUNCTION__, \
trace << PSTR(":measure:") << PSTR(msg) << trace.measure, \
trace << PSTR(" us") << endl) \
for (uint16_t __j = cnt; __j != 0; __j--)
#endif
/**
* The Trace class singleton.
*/
extern Trace trace;
#endif
<commit_msg>Improve MEASURE trace macro; flush trace iostream after measurement block.<commit_after>/**
* @file Cosa/Trace.hh
* @version 1.0
*
* @section License
* Copyright (C) 2012-2015, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef COSA_TRACE_HH
#define COSA_TRACE_HH
#include "Cosa/Types.h"
#include "Cosa/IOStream.hh"
/**
* Basic trace support class. Combind IOStream with UART for trace
* output.
*/
class Trace : public IOStream {
public:
/**
* Construct Trace IOStream object and initiate with null device.
* Use begin() to set the trace device. The Trace class is actually
* a singleton, trace, as the trace macro set depends on the variable.
*/
Trace() : IOStream(), EXITCHARACTER(0x1d) {}
/**
* Start trace stream over given iostream device.
* @param[in] dev iostream device.
* @param[in] banner trace begin message.
* @return true(1) if successful otherwise false(0)
*/
bool begin(IOStream::Device* dev, str_P banner = NULL);
/**
* Stop trace stream over current device.
* @return true(1) if successful otherwise false(0)
*/
bool end()
__attribute__((always_inline))
{
set_device(NULL);
return (true);
}
/**
* Set exit character to signal fatal.
* @param[in] c new exit character.
*/
void set_exitcharacter(char c)
{
EXITCHARACTER = c;
}
/**
* Support function for ASSERT failure. Prints give function name,
* func, line number and expression that could not be validated
* to trace output device before calling exit().
* @param[in] file name.
* @param[in] line number.
* @param[in] expr program memory string with expression.
*/
void fatal(const char* file, int line, str_P expr)
__attribute__((noreturn));
/** Result of latest MEASURE */
uint32_t measure;
protected:
/** Exit from miniterm. Default CTRL-ALT GR-] (0x1d) */
char EXITCHARACTER;
};
/**
* Log priorities.
*/
#define LOG_EMERG 0 /* System is unusable */
#define LOG_ALERT 1 /* Action must be taken immediately */
#define LOG_CRIT 2 /* Critical conditions */
#define LOG_ERR 3 /* Error conditions */
#define LOG_WARNING 4 /* Warning conditions */
#define LOG_NOTICE 5 /* Normal but significant condition */
#define LOG_INFO 6 /* Informational */
#define LOG_DEBUG 7 /* Debug-level messages */
/**
* Macros to generate mask for the trace log priorities (LOG_EMERG..
* LOG_DEBUG) setting of trace_log_mask.
* LOG_MASK(prio) bit mask corresponding to the given priority.
* LOG_UPTO(prio) bit mask for all priorities including the given.
*/
#define LOG_MASK(prio) (1 << (prio))
#define LOG_UPTO(prio) (LOG_MASK((prio) + 1) - 1)
extern uint8_t trace_log_mask;
/**
* Prints given message with current file name and line number
* to trace device and the program will terminate. The message
* string is stored in program memory.
* @param[in] msg message string to print.
*/
#define FATAL(msg) \
trace.fatal(__FILE__, \
__LINE__, \
__PSTR(msg))
#ifndef NDEBUG
/**
* Support macro to check that an expression is valid. The expression
* is used as a string and evaluated. If false a message is printed
* to the trace device and the program will terminate.
* @param[in] expr expression to validate.
*/
# define ASSERT(expr) \
do { \
if (UNLIKELY(!(expr))) FATAL("assert:" #expr); \
} while (0)
/**
* Support macro for trace of a string in program memory.
* @param[in] str string literal
*/
# define TRACE_P(str) trace.print(PSTR(str))
/**
* Support macro for trace of an expression. The expression
* is used as a string and evaluated.
* @param[in] expr expression.
*/
# if defined(TRACE_NO_VERBOSE) || defined(BOARD_ATTINY)
# define TRACE(expr) \
do { \
trace.print(__PSTR(#expr " = ")); \
trace.print(expr); \
trace.println(); \
} while (0)
# else
# define TRACE(expr) \
do { \
trace.printf(__PSTR("%d:%s:trace:" #expr " = "), \
__LINE__, \
__PRETTY_FUNCTION__); \
trace.print(expr); \
trace.println(); \
} while (0)
# endif
/**
* Support macro for trace of a log message with line number and
* function name prefix.
* @param[in] msg log message.
*/
# define TRACE_LOG(msg, ...) \
trace.printf(__PSTR("%d:%s:" msg "\r\n"), \
__LINE__, \
__PRETTY_FUNCTION__, \
__VA_ARGS__)
# define IS_LOG_PRIO(prio) (trace_log_mask & LOG_MASK(prio))
# define EMERG(msg, ...) \
if (IS_LOG_PRIO(LOG_EMERG)) TRACE_LOG("emerg:" msg, __VA_ARGS__)
# define ALERT(msg, ...) \
if (IS_LOG_PRIO(LOG_ALERT)) TRACE_LOG("alert:" msg, __VA_ARGS__)
# define CRIT(msg, ...) \
if (IS_LOG_PRIO(LOG_CRIT)) TRACE_LOG("crit:" msg, __VA_ARGS__)
# define ERR(msg, ...) \
if (IS_LOG_PRIO(LOG_ERR)) TRACE_LOG("err:" msg, __VA_ARGS__)
# define WARNING(msg, ...) \
if (IS_LOG_PRIO(LOG_WARNING)) TRACE_LOG("warning:" msg, __VA_ARGS__)
# define NOTICE(msg, ...) \
if (IS_LOG_PRIO(LOG_NOTICE)) TRACE_LOG("notice:" msg, __VA_ARGS__)
# define INFO(msg, ...) \
if (IS_LOG_PRIO(LOG_INFO)) TRACE_LOG("info:" msg, __VA_ARGS__)
# define DEBUG(msg, ...) \
if (IS_LOG_PRIO(LOG_DEBUG)) TRACE_LOG("debug:" msg, __VA_ARGS__)
#else
# define ASSERT(expr)
# define TRACE_P(str)
# define TRACE(expr)
# define TRACE_LOG(msg, ...)
# define EMERG(msg, ...)
# define ALERT(msg, ...)
# define CRIT(msg, ...)
# define ERR(msg, ...)
# define WARNING(msg, ...)
# define NOTICE(msg, ...)
# define INFO(msg, ...)
# define DEBUG(msg, ...)
#endif
/**
* Syntactic sugar for measuring execution time for a block.
* Used in the form:
* @code
* MEASURE("time to execute block", 1) {
* ...
* // Block of code to measure
* ...
* ...
* }
* @endcode
* @param[in] msg measurement prefix string.
* @param[in] cnt number of block calls (max UINT16_MAX).
*/
# if defined(TRACE_NO_VERBOSE) || defined(BOARD_ATTINY)
# define MEASURE(msg,cnt) \
trace.flush(); \
for (uint32_t __stop, __start = RTC::micros(), __i = 1; \
__i != 0; \
__i--, \
__stop = RTC::micros(), \
trace.measure = (__stop - __start) / cnt, \
trace << PSTR(msg) << trace.measure, \
trace << PSTR(" us") << endl, \
trace.flush()) \
for (uint16_t __j = cnt; __j != 0; __j--)
#else
# define MEASURE(msg,cnt) \
trace.flush(); \
for (uint32_t __stop, __start = RTC::micros(), __i = 1; \
__i != 0; \
__i--, \
__stop = RTC::micros(), \
trace.measure = (__stop - __start) / cnt, \
trace << __LINE__ << ':' << __PRETTY_FUNCTION__, \
trace << PSTR(":measure:") << PSTR(msg) << trace.measure, \
trace << PSTR(" us") << endl, \
trace.flush()) \
for (uint16_t __j = cnt; __j != 0; __j--)
#endif
/**
* The Trace class singleton.
*/
extern Trace trace;
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbMultiChannelExtractROI.h"
#include "otbExtractROI.h"
#include "otbStreamingStatisticsImageFilter.h"
#include "otbLabelImageToOGRDataSourceFilter.h"
#include "otbOGRDataSourceWrapper.h"
#include "otbOGRFeatureWrapper.h"
#include "otbSystem.h"
#include <time.h>
#include <vcl_algorithm.h>
namespace otb
{
namespace Wrapper
{
class LSMSVectorization : public Application
{
public:
typedef LSMSVectorization Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef FloatVectorImageType ImageType;
typedef ImageType::InternalPixelType ImagePixelType;
typedef UInt32ImageType LabelImageType;
typedef LabelImageType::InternalPixelType LabelImagePixelType;
typedef otb::ImageFileReader<ImageType> ImageReaderType;
typedef otb::ImageFileReader<LabelImageType> LabelImageReaderType;
typedef otb::MultiChannelExtractROI <ImagePixelType,ImagePixelType > MultiChannelExtractROIFilterType;
typedef otb::ExtractROI<LabelImagePixelType,LabelImagePixelType> ExtractROIFilterType;
typedef otb::StreamingStatisticsImageFilter<LabelImageType> StatisticsImageFilterType;
typedef itk::ImageRegionConstIterator<LabelImageType> LabelImageIterator;
typedef itk::ImageRegionConstIterator<ImageType> ImageIterator;
typedef otb::LabelImageToOGRDataSourceFilter<LabelImageType> LabelImageToOGRDataSourceFilterType;
itkNewMacro(Self);
itkTypeMacro(Vectorization, otb::Application);
private:
void DoInit()
{
SetName("LSMSVectorization");
SetDescription("Fourth step of the exact Large-Scale Mean-Shift segmentation workflow.");
SetDocName("Exact Large-Scale Mean-Shift segmentation, step 4");
SetDocLongDescription("This application performs the fourth step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Given a segmentation result (label image), that may have been processed for small regions merging or not, it will convert it to a GIS vector file containing one polygon per segment. Each polygon contains additional fields: mean and variance of each channels from input image (in parameter), segmentation image label, number of pixels in the polygon. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results.");
SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.");
SetDocAuthors("David Youssefi");
SetDocSeeAlso("MeanShiftSmoothing, LSMSSegmentation, LSMSSmallRegionsMerging");
AddDocTag(Tags::Segmentation);
AddDocTag("LSMS");
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription( "in", "The input image." );
AddParameter(ParameterType_InputImage, "inseg", "Segmented image");
SetParameterDescription( "inseg", " The segmented image input. Segmented image input is the segmentation of the input image." );
AddParameter(ParameterType_OutputFilename, "out", "Output GIS vector file");
SetParameterDescription( "out", "The output GIS vector file, representing the vectorized version of the segmented image where the features of the polygons are the radiometric means and variances." );
AddParameter(ParameterType_Int, "tilesizex", "Size of tiles in pixel (X-axis)");
SetParameterDescription("tilesizex", "Size of tiles along the X-axis.");
SetDefaultParameterInt("tilesizex", 500);
SetMinimumParameterIntValue("tilesizex", 1);
AddParameter(ParameterType_Int, "tilesizey", "Size of tiles in pixel (Y-axis)");
SetParameterDescription("tilesizey", "Size of tiles along the Y-axis.");
SetDefaultParameterInt("tilesizey", 500);
SetMinimumParameterIntValue("tilesizey", 1);
// Doc example parameter settings
SetDocExampleParameterValue("in","avions.tif");
SetDocExampleParameterValue("inseg","merged.tif");
SetDocExampleParameterValue("out","vector.shp");
SetDocExampleParameterValue("tilesizex","256");
SetDocExampleParameterValue("tilesizey","256");
}
void DoUpdateParameters()
{
}
void DoExecute()
{
clock_t tic = clock();
const char * shapefile = GetParameterString("out").c_str();
unsigned long sizeTilesX = GetParameterInt("tilesizex");
unsigned long sizeTilesY = GetParameterInt("tilesizey");
LabelImageType::Pointer labelIn = GetParameterUInt32Image("inseg");
labelIn->UpdateOutputInformation();
unsigned long sizeImageX = labelIn->GetLargestPossibleRegion().GetSize()[0];
unsigned long sizeImageY = labelIn->GetLargestPossibleRegion().GetSize()[1];
unsigned int nbTilesX = sizeImageX/sizeTilesX + (sizeImageX%sizeTilesX > 0 ? 1 : 0);
unsigned int nbTilesY = sizeImageY/sizeTilesY + (sizeImageY%sizeTilesY > 0 ? 1 : 0);
otbAppLogINFO(<<"Number of tiles: "<<nbTilesX<<" x "<<nbTilesY);
StatisticsImageFilterType::Pointer stats = StatisticsImageFilterType::New();
stats->SetInput(labelIn);
stats->Update();
unsigned int regionCount=stats->GetMaximum();
ImageType::Pointer imageIn = GetParameterImage("in");
imageIn->UpdateOutputInformation();
unsigned long numberOfComponentsPerPixel = imageIn->GetNumberOfComponentsPerPixel();
std::string projRef = imageIn->GetProjectionRef();
std::vector<int>nbPixels;
nbPixels.clear();
nbPixels.resize(regionCount+1);
for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel)
{
nbPixels[curLabel] = 0;
}
ImageType::PixelType defaultValue(numberOfComponentsPerPixel);
defaultValue.Fill(0);
std::vector<ImageType::PixelType>sum(regionCount+1,defaultValue);
std::vector<ImageType::PixelType>sum2(regionCount+1,defaultValue);
otb::ogr::DataSource::Pointer ogrDS;
otb::ogr::Layer layer(NULL, false);
OGRSpatialReference oSRS(projRef.c_str());
std::vector<std::string> options;
ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Overwrite);
std::string layername = otb::System::GetShortFileName(shapefile);
std::string extension = otb::System::GetExtension(shapefile);
layername = layername.substr(0,layername.size()-(extension.size()+1));
layer = ogrDS->CreateLayer(layername, &oSRS, wkbMultiPolygon, options);
OGRFieldDefn labelField("label", OFTInteger);
layer.CreateField(labelField, true);
OGRFieldDefn nbPixelsField("nbPixels", OFTInteger);
layer.CreateField(nbPixelsField, true);
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"meanB"<<comp;
OGRFieldDefn field(fieldoss.str().c_str(), OFTReal);
layer.CreateField(field, true);
}
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"varB"<<comp;
OGRFieldDefn field(fieldoss.str().c_str(), OFTReal);
layer.CreateField(field, true);
}
//Vectorization per tile
otbAppLogINFO(<<"Vectorization ...");
for(unsigned int row = 0; row < nbTilesY; row++)
{
for(unsigned int column = 0; column < nbTilesX; column++)
{
unsigned long startX = column*sizeTilesX;
unsigned long startY = row*sizeTilesY;
unsigned long sizeX = vcl_min(sizeTilesX,sizeImageX-startX);
unsigned long sizeY = vcl_min(sizeTilesY,sizeImageY-startY);
//Tiles extraction of the input image
MultiChannelExtractROIFilterType::Pointer imageROI = MultiChannelExtractROIFilterType::New();
imageROI->SetInput(imageIn);
imageROI->SetStartX(startX);
imageROI->SetStartY(startY);
imageROI->SetSizeX(sizeX);
imageROI->SetSizeY(sizeY);
imageROI->Update();
//Tiles extraction of the segmented image
ExtractROIFilterType::Pointer labelImageROI = ExtractROIFilterType::New();
labelImageROI->SetInput(labelIn);
labelImageROI->SetStartX(startX);
labelImageROI->SetStartY(startY);
labelImageROI->SetSizeX(sizeX);
labelImageROI->SetSizeY(sizeY);
labelImageROI->Update();
//Sums calculation for the mean and the variance calculation per label
LabelImageIterator itLabel( labelImageROI->GetOutput(), labelImageROI->GetOutput()->GetLargestPossibleRegion());
ImageIterator itImage( imageROI->GetOutput(), imageROI->GetOutput()->GetLargestPossibleRegion());
for (itLabel.GoToBegin(), itImage.GoToBegin(); !itImage.IsAtEnd(); ++itLabel, ++itImage)
{
nbPixels[itLabel.Value()]++;
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp)
{
sum[itLabel.Value()][comp]+=itImage.Get()[comp];
sum2[itLabel.Value()][comp]+=itImage.Get()[comp]*itImage.Get()[comp];
}
}
labelImageROI = ExtractROIFilterType::New();
labelImageROI->SetInput(labelIn);
labelImageROI->SetStartX(startX);
labelImageROI->SetStartY(startY);
labelImageROI->SetSizeX(sizeX+1);
labelImageROI->SetSizeY(sizeY+1);
labelImageROI->Update();
//Raster->Vecteur conversion
LabelImageToOGRDataSourceFilterType::Pointer labelToOGR = LabelImageToOGRDataSourceFilterType::New();
labelToOGR->SetInput(labelImageROI->GetOutput());
labelToOGR->SetInputMask(labelImageROI->GetOutput());
labelToOGR->SetFieldName("label");
labelToOGR->Update();
otb::ogr::DataSource::ConstPointer ogrDSTmp = labelToOGR->GetOutput();
otb::ogr::Layer layerTmp = ogrDSTmp->GetLayerChecked(0);
otb::ogr::Layer::const_iterator featIt = layerTmp.begin();
for(; featIt!=layerTmp.end(); ++featIt)
{
otb::ogr::Feature dstFeature(layer.GetLayerDefn());
dstFeature.SetFrom( *featIt, TRUE );
layer.CreateFeature( dstFeature );
}
}
}
//Sorting by increasing label of the features
std::ostringstream sqloss;
sqloss.str("");
sqloss<<"SELECT * FROM "<<layername<<" ORDER BY label";
otb::ogr::Layer layerTmp=ogrDS->ExecuteSQL(sqloss.str().c_str(), NULL, NULL);
bool goesOn = true;
int nbFeatures = layerTmp.ogr().GetFeatureCount(true);
int nb = 0;
otb::ogr::Feature firstFeature = layerTmp.ogr().GetNextFeature();
//Geometry fusion
otbAppLogINFO("Merging polygons accross tiles ...");
while(firstFeature.addr())
{
LabelImagePixelType curLabel = firstFeature.ogr().GetFieldAsInteger("label");
//Creation of a multipolygon where are stored the geometries to be merged
OGRMultiPolygon geomToMerge;
geomToMerge.addGeometry(firstFeature.GetGeometry());
bool merging = true;
otb::ogr::Feature nextFeature(NULL);
bool haveMerged=false;
while(merging)
{
nextFeature = layerTmp.ogr().GetNextFeature();
if(nextFeature.addr())
{
LabelImagePixelType newLabel = nextFeature.ogr().GetFieldAsInteger("label");
merging=(newLabel==curLabel);
//Storing of the new geometry if labels are identical
if(merging)
{
geomToMerge.addGeometry(nextFeature.GetGeometry());
layer.DeleteFeature(nextFeature.GetFID());
haveMerged=true;
}
//If storing made and new label -> polygons fusion
else if(haveMerged)
{
otb::ogr::UniqueGeometryPtr fusionPolygon = otb::ogr::UnionCascaded(geomToMerge);
firstFeature.SetGeometry(fusionPolygon.get());
}
}
//If end of list : end of loop
else
{
merging=false;
}
}
//Features calculation
//Number of pixels per label
firstFeature.ogr().SetField("nbPixels",nbPixels[curLabel]);
//Radiometric means per label
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"meanB"<<comp;
firstFeature.ogr().SetField(fieldoss.str().c_str(),sum[curLabel][comp]/nbPixels[curLabel]);
}
//Variances per label
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"varB"<<comp;
float var = 0;
if (nbPixels[curLabel]!=1)
var = (sum2[curLabel][comp]-sum[curLabel][comp]*sum[curLabel][comp]/nbPixels[curLabel])/(nbPixels[curLabel]-1);
firstFeature.ogr().SetField(fieldoss.str().c_str(),var);
}
//Geometries simplification
otb::ogr::UniqueGeometryPtr geom = otb::ogr::Simplify(*firstFeature.GetGeometry(),0);
firstFeature.SetGeometryDirectly(otb::ogr::Simplify(*geom,0));
layer.SetFeature(firstFeature);
//Next geometry
firstFeature=nextFeature;
}
layer.ogr().CommitTransaction();
if(extension=="shp"){
sqloss.str("");
sqloss<<"REPACK "<<layername;
ogrDS->ogr().ExecuteSQL(sqloss.str().c_str(), NULL, NULL);
}
ogrDS->SyncToDisk();
clock_t toc = clock();
otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::LSMSVectorization)
<commit_msg>DOC: typo in LSMS vectorization application<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbMultiChannelExtractROI.h"
#include "otbExtractROI.h"
#include "otbStreamingStatisticsImageFilter.h"
#include "otbLabelImageToOGRDataSourceFilter.h"
#include "otbOGRDataSourceWrapper.h"
#include "otbOGRFeatureWrapper.h"
#include "otbSystem.h"
#include <time.h>
#include <vcl_algorithm.h>
namespace otb
{
namespace Wrapper
{
class LSMSVectorization : public Application
{
public:
typedef LSMSVectorization Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef FloatVectorImageType ImageType;
typedef ImageType::InternalPixelType ImagePixelType;
typedef UInt32ImageType LabelImageType;
typedef LabelImageType::InternalPixelType LabelImagePixelType;
typedef otb::ImageFileReader<ImageType> ImageReaderType;
typedef otb::ImageFileReader<LabelImageType> LabelImageReaderType;
typedef otb::MultiChannelExtractROI <ImagePixelType,ImagePixelType > MultiChannelExtractROIFilterType;
typedef otb::ExtractROI<LabelImagePixelType,LabelImagePixelType> ExtractROIFilterType;
typedef otb::StreamingStatisticsImageFilter<LabelImageType> StatisticsImageFilterType;
typedef itk::ImageRegionConstIterator<LabelImageType> LabelImageIterator;
typedef itk::ImageRegionConstIterator<ImageType> ImageIterator;
typedef otb::LabelImageToOGRDataSourceFilter<LabelImageType> LabelImageToOGRDataSourceFilterType;
itkNewMacro(Self);
itkTypeMacro(Vectorization, otb::Application);
private:
void DoInit()
{
SetName("LSMSVectorization");
SetDescription("Fourth step of the exact Large-Scale Mean-Shift segmentation workflow.");
SetDocName("Exact Large-Scale Mean-Shift segmentation, step 4");
SetDocLongDescription("This application performs the fourth step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Given a segmentation result (label image), that may have been processed for small regions merging or not, it will convert it to a GIS vector file containing one polygon per segment. Each polygon contains additional fields: mean and variance of each channels from input image (in parameter), segmentation image label, number of pixels in the polygon. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results.");
SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.");
SetDocAuthors("David Youssefi");
SetDocSeeAlso("MeanShiftSmoothing, LSMSSegmentation, LSMSSmallRegionsMerging");
AddDocTag(Tags::Segmentation);
AddDocTag("LSMS");
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription( "in", "The input image." );
AddParameter(ParameterType_InputImage, "inseg", "Segmented image");
SetParameterDescription( "inseg", " The segmented image input. Segmented image input is the segmentation of the input image." );
AddParameter(ParameterType_OutputFilename, "out", "Output GIS vector file");
SetParameterDescription( "out", "The output GIS vector file, representing the vectorized version of the segmented image where the features of the polygons are the radiometric means and variances." );
AddParameter(ParameterType_Int, "tilesizex", "Size of tiles in pixel (X-axis)");
SetParameterDescription("tilesizex", "Size of tiles along the X-axis.");
SetDefaultParameterInt("tilesizex", 500);
SetMinimumParameterIntValue("tilesizex", 1);
AddParameter(ParameterType_Int, "tilesizey", "Size of tiles in pixel (Y-axis)");
SetParameterDescription("tilesizey", "Size of tiles along the Y-axis.");
SetDefaultParameterInt("tilesizey", 500);
SetMinimumParameterIntValue("tilesizey", 1);
// Doc example parameter settings
SetDocExampleParameterValue("in","avions.tif");
SetDocExampleParameterValue("inseg","merged.tif");
SetDocExampleParameterValue("out","vector.shp");
SetDocExampleParameterValue("tilesizex","256");
SetDocExampleParameterValue("tilesizey","256");
}
void DoUpdateParameters()
{
}
void DoExecute()
{
clock_t tic = clock();
const char * shapefile = GetParameterString("out").c_str();
unsigned long sizeTilesX = GetParameterInt("tilesizex");
unsigned long sizeTilesY = GetParameterInt("tilesizey");
LabelImageType::Pointer labelIn = GetParameterUInt32Image("inseg");
labelIn->UpdateOutputInformation();
unsigned long sizeImageX = labelIn->GetLargestPossibleRegion().GetSize()[0];
unsigned long sizeImageY = labelIn->GetLargestPossibleRegion().GetSize()[1];
unsigned int nbTilesX = sizeImageX/sizeTilesX + (sizeImageX%sizeTilesX > 0 ? 1 : 0);
unsigned int nbTilesY = sizeImageY/sizeTilesY + (sizeImageY%sizeTilesY > 0 ? 1 : 0);
otbAppLogINFO(<<"Number of tiles: "<<nbTilesX<<" x "<<nbTilesY);
StatisticsImageFilterType::Pointer stats = StatisticsImageFilterType::New();
stats->SetInput(labelIn);
stats->Update();
unsigned int regionCount=stats->GetMaximum();
ImageType::Pointer imageIn = GetParameterImage("in");
imageIn->UpdateOutputInformation();
unsigned long numberOfComponentsPerPixel = imageIn->GetNumberOfComponentsPerPixel();
std::string projRef = imageIn->GetProjectionRef();
std::vector<int>nbPixels;
nbPixels.clear();
nbPixels.resize(regionCount+1);
for(LabelImagePixelType curLabel = 1; curLabel <= regionCount; ++curLabel)
{
nbPixels[curLabel] = 0;
}
ImageType::PixelType defaultValue(numberOfComponentsPerPixel);
defaultValue.Fill(0);
std::vector<ImageType::PixelType>sum(regionCount+1,defaultValue);
std::vector<ImageType::PixelType>sum2(regionCount+1,defaultValue);
otb::ogr::DataSource::Pointer ogrDS;
otb::ogr::Layer layer(NULL, false);
OGRSpatialReference oSRS(projRef.c_str());
std::vector<std::string> options;
ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Overwrite);
std::string layername = otb::System::GetShortFileName(shapefile);
std::string extension = otb::System::GetExtension(shapefile);
layername = layername.substr(0,layername.size()-(extension.size()+1));
layer = ogrDS->CreateLayer(layername, &oSRS, wkbMultiPolygon, options);
OGRFieldDefn labelField("label", OFTInteger);
layer.CreateField(labelField, true);
OGRFieldDefn nbPixelsField("nbPixels", OFTInteger);
layer.CreateField(nbPixelsField, true);
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"meanB"<<comp;
OGRFieldDefn field(fieldoss.str().c_str(), OFTReal);
layer.CreateField(field, true);
}
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"varB"<<comp;
OGRFieldDefn field(fieldoss.str().c_str(), OFTReal);
layer.CreateField(field, true);
}
//Vectorization per tile
otbAppLogINFO(<<"Vectorization ...");
for(unsigned int row = 0; row < nbTilesY; row++)
{
for(unsigned int column = 0; column < nbTilesX; column++)
{
unsigned long startX = column*sizeTilesX;
unsigned long startY = row*sizeTilesY;
unsigned long sizeX = vcl_min(sizeTilesX,sizeImageX-startX);
unsigned long sizeY = vcl_min(sizeTilesY,sizeImageY-startY);
//Tiles extraction of the input image
MultiChannelExtractROIFilterType::Pointer imageROI = MultiChannelExtractROIFilterType::New();
imageROI->SetInput(imageIn);
imageROI->SetStartX(startX);
imageROI->SetStartY(startY);
imageROI->SetSizeX(sizeX);
imageROI->SetSizeY(sizeY);
imageROI->Update();
//Tiles extraction of the segmented image
ExtractROIFilterType::Pointer labelImageROI = ExtractROIFilterType::New();
labelImageROI->SetInput(labelIn);
labelImageROI->SetStartX(startX);
labelImageROI->SetStartY(startY);
labelImageROI->SetSizeX(sizeX);
labelImageROI->SetSizeY(sizeY);
labelImageROI->Update();
//Sums calculation for the mean and the variance calculation per label
LabelImageIterator itLabel( labelImageROI->GetOutput(), labelImageROI->GetOutput()->GetLargestPossibleRegion());
ImageIterator itImage( imageROI->GetOutput(), imageROI->GetOutput()->GetLargestPossibleRegion());
for (itLabel.GoToBegin(), itImage.GoToBegin(); !itImage.IsAtEnd(); ++itLabel, ++itImage)
{
nbPixels[itLabel.Value()]++;
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp)
{
sum[itLabel.Value()][comp]+=itImage.Get()[comp];
sum2[itLabel.Value()][comp]+=itImage.Get()[comp]*itImage.Get()[comp];
}
}
labelImageROI = ExtractROIFilterType::New();
labelImageROI->SetInput(labelIn);
labelImageROI->SetStartX(startX);
labelImageROI->SetStartY(startY);
labelImageROI->SetSizeX(sizeX+1);
labelImageROI->SetSizeY(sizeY+1);
labelImageROI->Update();
//Raster->Vecteur conversion
LabelImageToOGRDataSourceFilterType::Pointer labelToOGR = LabelImageToOGRDataSourceFilterType::New();
labelToOGR->SetInput(labelImageROI->GetOutput());
labelToOGR->SetInputMask(labelImageROI->GetOutput());
labelToOGR->SetFieldName("label");
labelToOGR->Update();
otb::ogr::DataSource::ConstPointer ogrDSTmp = labelToOGR->GetOutput();
otb::ogr::Layer layerTmp = ogrDSTmp->GetLayerChecked(0);
otb::ogr::Layer::const_iterator featIt = layerTmp.begin();
for(; featIt!=layerTmp.end(); ++featIt)
{
otb::ogr::Feature dstFeature(layer.GetLayerDefn());
dstFeature.SetFrom( *featIt, TRUE );
layer.CreateFeature( dstFeature );
}
}
}
//Sorting by increasing label of the features
std::ostringstream sqloss;
sqloss.str("");
sqloss<<"SELECT * FROM "<<layername<<" ORDER BY label";
otb::ogr::Layer layerTmp=ogrDS->ExecuteSQL(sqloss.str().c_str(), NULL, NULL);
bool goesOn = true;
int nbFeatures = layerTmp.ogr().GetFeatureCount(true);
int nb = 0;
otb::ogr::Feature firstFeature = layerTmp.ogr().GetNextFeature();
//Geometry fusion
otbAppLogINFO("Merging polygons across tiles ...");
while(firstFeature.addr())
{
LabelImagePixelType curLabel = firstFeature.ogr().GetFieldAsInteger("label");
//Creation of a multipolygon where are stored the geometries to be merged
OGRMultiPolygon geomToMerge;
geomToMerge.addGeometry(firstFeature.GetGeometry());
bool merging = true;
otb::ogr::Feature nextFeature(NULL);
bool haveMerged=false;
while(merging)
{
nextFeature = layerTmp.ogr().GetNextFeature();
if(nextFeature.addr())
{
LabelImagePixelType newLabel = nextFeature.ogr().GetFieldAsInteger("label");
merging=(newLabel==curLabel);
//Storing of the new geometry if labels are identical
if(merging)
{
geomToMerge.addGeometry(nextFeature.GetGeometry());
layer.DeleteFeature(nextFeature.GetFID());
haveMerged=true;
}
//If storing made and new label -> polygons fusion
else if(haveMerged)
{
otb::ogr::UniqueGeometryPtr fusionPolygon = otb::ogr::UnionCascaded(geomToMerge);
firstFeature.SetGeometry(fusionPolygon.get());
}
}
//If end of list : end of loop
else
{
merging=false;
}
}
//Features calculation
//Number of pixels per label
firstFeature.ogr().SetField("nbPixels",nbPixels[curLabel]);
//Radiometric means per label
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"meanB"<<comp;
firstFeature.ogr().SetField(fieldoss.str().c_str(),sum[curLabel][comp]/nbPixels[curLabel]);
}
//Variances per label
for(unsigned int comp = 0; comp<numberOfComponentsPerPixel; ++comp){
std::ostringstream fieldoss;
fieldoss<<"varB"<<comp;
float var = 0;
if (nbPixels[curLabel]!=1)
var = (sum2[curLabel][comp]-sum[curLabel][comp]*sum[curLabel][comp]/nbPixels[curLabel])/(nbPixels[curLabel]-1);
firstFeature.ogr().SetField(fieldoss.str().c_str(),var);
}
//Geometries simplification
otb::ogr::UniqueGeometryPtr geom = otb::ogr::Simplify(*firstFeature.GetGeometry(),0);
firstFeature.SetGeometryDirectly(otb::ogr::Simplify(*geom,0));
layer.SetFeature(firstFeature);
//Next geometry
firstFeature=nextFeature;
}
layer.ogr().CommitTransaction();
if(extension=="shp"){
sqloss.str("");
sqloss<<"REPACK "<<layername;
ogrDS->ogr().ExecuteSQL(sqloss.str().c_str(), NULL, NULL);
}
ogrDS->SyncToDisk();
clock_t toc = clock();
otbAppLogINFO(<<"Elapsed time: "<<(double)(toc - tic) / CLOCKS_PER_SEC<<" seconds");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::LSMSVectorization)
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cassert>
#include <memory>
#include <unordered_map>
using std::swap;
//
// The classes
struct Shape
{
virtual ~Shape()
{
}
virtual double area() const = 0;
virtual double perimeter() const = 0;
};
static const double pi = 3.14159265359;
class Circle : public Shape
{
const double radius_;
public:
double area() const override
{
return pi * radius_ * radius_;
}
double perimeter() const override
{
return 2 * pi * radius_;
}
Circle(double r) : radius_(r)
{
}
};
//
// The C bridge
extern "C" {
void* Circle_new(double r)
{
return new (std::nothrow) Circle(r);
}
void Shape_delete(const void* shape)
{
delete ((const Shape*)shape);
}
double Shape_area(const void* shape)
{
return ((const Shape*)shape)->area();
}
double Shape_perimeter(const void* shape)
{
return ((const Shape*)shape)->perimeter();
}
}
//
// The handles bridge
using HANDLE = const char*;
enum RC
{
LOOKUP_FAIL = -999,
SUCCESS = 0
};
struct TableEntry
{
void* obj_ = nullptr;
void (*del_)(const void*) = nullptr;
TableEntry& operator=(TableEntry&& t)
{
assert(&t != this);
swap(t.obj_, obj_);
swap(t.del_, del_);
t.~TableEntry();
return *this;
}
~TableEntry()
{
if (del_) del_(obj_);
}
};
class HandleTable // not thread-safe
{
std::unordered_map<std::string, TableEntry> handle_table;
public:
struct LookupFailureException : public std::runtime_error
{
LookupFailureException(HANDLE handle) : std::runtime_error(handle)
{
}
};
void InsertOrOverwrite(HANDLE handle, void* object,
void (*deleter)(const void*))
{
TableEntry t;
t.obj_ = object;
t.del_ = deleter;
handle_table[handle] = std::move(t);
}
void* Lookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
throw LookupFailureException(handle);
}
void* TryLookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
return nullptr;
}
};
static HandleTable handle_table;
extern "C" {
void CircleH_new(HANDLE circle, double r, int* rc)
{
handle_table.InsertOrOverwrite(circle, Circle_new(r), Shape_delete);
*rc = SUCCESS;
}
void ShapeH_delete(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
Shape_delete(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
}
}
double ShapeH_area(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_area(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
double ShapeH_perimeter(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_perimeter(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
}
int main(int argc, char* argv[])
{
int rc;
auto name = "myCircle";
CircleH_new(name, 10, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to construct circle\n";
return -1;
}
double area = ShapeH_area(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle area\n";
return -1;
}
std::cout << "Area=" << area << "\n";
double perimeter = ShapeH_perimeter(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle perimeter\n";
return -1;
}
std::cout << "Perimeter=" << perimeter << "\n";
}
<commit_msg>handled objects can be overwritten<commit_after>#include <iostream>
#include <cassert>
#include <memory>
#include <unordered_map>
using std::swap;
//
// The classes
struct CountInstances
{
CountInstances() { ++instanceCount; std::cout << "Instances: " << instanceCount << "\n"; }
~CountInstances() { --instanceCount; std::cout << "Instances: " << instanceCount << "\n"; }
CountInstances(const CountInstances&)=delete;
CountInstances(CountInstances&&)=delete;
CountInstances& operator=(const CountInstances&)=delete;
CountInstances& operator=(CountInstances&&)=delete;
static size_t instanceCount;
};
size_t CountInstances::instanceCount = 0;
struct Shape : CountInstances
{
virtual ~Shape()
{
}
virtual double area() const = 0;
virtual double perimeter() const = 0;
};
static const double pi = 3.14159265359;
class Circle : public Shape
{
const double radius_;
public:
double area() const override
{
return pi * radius_ * radius_;
}
double perimeter() const override
{
return 2 * pi * radius_;
}
Circle(double r) : radius_(r)
{
}
};
//
// The C bridge
extern "C" {
void* Circle_new(double r)
{
return new (std::nothrow) Circle(r);
}
void Shape_delete(const void* shape)
{
delete ((const Shape*)shape);
}
double Shape_area(const void* shape)
{
return ((const Shape*)shape)->area();
}
double Shape_perimeter(const void* shape)
{
return ((const Shape*)shape)->perimeter();
}
}
//
// The handles bridge
using HANDLE = const char*;
enum RC
{
LOOKUP_FAIL = -999,
SUCCESS = 0
};
struct TableEntry
{
void* obj_ = nullptr;
void (*del_)(const void*) = nullptr;
TableEntry& operator=(TableEntry&& t)
{
assert(&t != this);
swap(t.obj_, obj_);
swap(t.del_, del_);
return *this;
}
~TableEntry()
{
if (del_) del_(obj_);
}
};
class HandleTable // not thread-safe
{
std::unordered_map<std::string, TableEntry> handle_table;
public:
struct LookupFailureException : public std::runtime_error
{
LookupFailureException(HANDLE handle) : std::runtime_error(handle)
{
}
};
void InsertOrOverwrite(HANDLE handle, void* object,
void (*deleter)(const void*))
{
TableEntry t;
t.obj_ = object;
t.del_ = deleter;
handle_table[handle] = std::move(t);
}
void* Lookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
throw LookupFailureException(handle);
}
void* TryLookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
return nullptr;
}
};
static HandleTable handle_table;
extern "C" {
void CircleH_new(HANDLE circle, double r, int* rc)
{
handle_table.InsertOrOverwrite(circle, Circle_new(r), Shape_delete);
*rc = SUCCESS;
}
void ShapeH_delete(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
Shape_delete(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
}
}
double ShapeH_area(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_area(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
double ShapeH_perimeter(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_perimeter(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
}
int main(int argc, char* argv[])
{
int rc;
auto name = "myCircle";
CircleH_new(name, 10, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to construct circle\n";
return -1;
}
CircleH_new(name, 10, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to construct circle\n";
return -1;
}
double area = ShapeH_area(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle area\n";
return -1;
}
std::cout << "Area=" << area << "\n";
double perimeter = ShapeH_perimeter(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle perimeter\n";
return -1;
}
std::cout << "Perimeter=" << perimeter << "\n";
}
<|endoftext|>
|
<commit_before>//
// LinearRamper.hpp
// AudioKit Core
//
// Created by Shane Dunne, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
#pragma once
namespace AudioKitCore
{
struct LinearRamper
{
float value; // current value
float target; // where it is headed
float increment; // per-sample increment
LinearRamper() : value(0.0f), target(0.0f), increment(0.0f) {}
// initialize to a stable value
void init(float v)
{
value = target = v;
increment = 0.0f;
}
// initialize all parameters
void init(float startValue, float targetValue, float intervalSamples)
{
target = targetValue;
if (intervalSamples < 1.0f)
{
value = target;
increment = 0.0f;
}
else
{
value = startValue;
increment = (target - value) / intervalSamples;
}
}
// reset new target and new interval, retaining current value
inline void reinit(float targetValue, float intervalSamples)
{
init(value, targetValue, intervalSamples);
}
inline float isRamping()
{
if (increment == 0.0f) return false;
if (increment > 0.0f) return value < target;
else return value > target;
}
inline float getNextValue()
{
return value += increment;
}
inline void getValues(int count, float* pOut)
{
for (int i=0; i < count; i++) *pOut++ = value += increment;
}
};
}
<commit_msg>AudioKitCore::LinearRamper: support for horizontal segments<commit_after>//
// LinearRamper.hpp
// AudioKit Core
//
// Created by Shane Dunne, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
#pragma once
namespace AudioKitCore
{
struct LinearRamper
{
static float constexpr flagValue = 100000.0f;
float value; // current value
float target; // where it is headed
float increment; // per-sample increment
float constantValue; // special case of horizontal ramp
LinearRamper() : value(0.0f), target(0.0f), increment(0.0f), constantValue(flagValue) {}
// initialize to a stable value
void init(float v)
{
value = target = v;
increment = 0.0f;
constantValue = flagValue;
}
// initialize all parameters
void init(float startValue, float targetValue, float intervalSamples)
{
constantValue = flagValue; // assume startValue != targetValue
target = targetValue;
if (intervalSamples < 1.0f)
{
// target has already been hit, we're already done
value = target;
increment = 0.0f;
}
else if (startValue == targetValue)
{
// special case of horizontal ramp
constantValue = startValue; // remember the constant value here
value = 0.0f; // and let value
increment = 1.0f; // count samples
target = intervalSamples; // to time the interval
}
else
{
// normal case: value ramps to target
value = startValue;
increment = (target - value) / intervalSamples;
}
}
// reset new target and new interval, retaining current value
inline void reinit(float targetValue, float intervalSamples)
{
init(value, targetValue, intervalSamples);
}
inline float isRamping()
{
if (increment == 0.0f) return false;
if (increment > 0.0f) return value < target;
else return value > target;
}
inline float getNextValue()
{
value += increment;
return (constantValue == flagValue) ? value : constantValue;
}
inline void getValues(int count, float* pOut)
{
for (int i=0; i < count; i++) *pOut++ = getNextValue();
}
};
}
<|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 std::tr1::get;
using std::tr1::tuple;
///////////// Blur////////////////////////
typedef Size_MatType BlurFixture;
PERF_TEST_P(BlurFixture, Blur,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params), ksize(3, 3);
const int type = get<1>(params), bordertype = BORDER_CONSTANT;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(5);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::blur(oclSrc, oclDst, ksize, Point(-1, -1), bordertype);
oclDst.download(dst);
SANITY_CHECK(dst, 1 + DBL_EPSILON);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::blur(src, dst, ksize, Point(-1, -1), bordertype);
SANITY_CHECK(dst, 1 + DBL_EPSILON);
}
else
OCL_PERF_ELSE
}
///////////// Laplacian////////////////////////
typedef Size_MatType LaplacianFixture;
PERF_TEST_P(LaplacianFixture, Laplacian,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 3;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(6);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::Laplacian(oclSrc, oclDst, -1, ksize, 1);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize, 1);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Erode ////////////////////
typedef Size_MatType ErodeFixture;
PERF_TEST_P(ErodeFixture, Erode,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 3;
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(5);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type), oclKer(ker);
OCL_TEST_CYCLE() cv::ocl::erode(oclSrc, oclDst, oclKer);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::erode(src, dst, ker);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Sobel ////////////////////////
typedef Size_MatType SobelFixture;
PERF_TEST_P(SobelFixture, Sobel,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 1;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if ((srcSize == OCL_SIZE_2000 && type == CV_8UC4) ||
(srcSize == OCL_SIZE_4000 && type == CV_8UC1))
declare.time(5.5);
else if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(20);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::Sobel(oclSrc, oclDst, -1, dx, dy);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::Sobel(src, dst, -1, dx, dy);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Scharr ////////////////////////
typedef Size_MatType ScharrFixture;
PERF_TEST_P(ScharrFixture, Scharr,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 0;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if ((srcSize == OCL_SIZE_2000 && type == CV_8UC4) ||
(srcSize == OCL_SIZE_4000 && type == CV_8UC1))
declare.time(5.5);
else if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(21);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::Scharr(oclSrc, oclDst, -1, dx, dy);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::Scharr(src, dst, -1, dx, dy);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// GaussianBlur ////////////////////////
typedef Size_MatType GaussianBlurFixture;
PERF_TEST_P(GaussianBlurFixture, GaussianBlur,
::testing::Combine(::testing::Values(OCL_SIZE_1000, OCL_SIZE_2000),
OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 7;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
const double eps = src.depth() == CV_8U ? 1 + DBL_EPSILON : 3e-4;
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::GaussianBlur(oclSrc, oclDst, Size(ksize, ksize), 0);
oclDst.download(dst);
SANITY_CHECK(dst, eps);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::GaussianBlur(src, dst, Size(ksize, ksize), 0);
SANITY_CHECK(dst, eps);
}
else
OCL_PERF_ELSE
}
///////////// filter2D////////////////////////
typedef Size_MatType filter2DFixture;
PERF_TEST_P(filter2DFixture, filter2D,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 3;
Mat src(srcSize, type), dst(srcSize, type), kernel(ksize, ksize, CV_32SC1);
declare.in(src, WARMUP_RNG).in(kernel).out(dst);
randu(kernel, -3.0, 3.0);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(8);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type), oclKernel(kernel);
OCL_TEST_CYCLE() cv::ocl::filter2D(oclSrc, oclDst, -1, oclKernel);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Bilateral////////////////////////
typedef Size_MatType BilateralFixture;
PERF_TEST_P(BilateralFixture, Bilateral,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC3)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), d = 7;
double sigmacolor = 50.0, sigmaspace = 50.0;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC3)
declare.time(8);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::bilateralFilter(oclSrc, oclDst, d, sigmacolor, sigmaspace);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::bilateralFilter(src, dst, d, sigmacolor, sigmaspace);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// adaptiveBilateral////////////////////////
typedef Size_MatType adaptiveBilateralFixture;
PERF_TEST_P(adaptiveBilateralFixture, adaptiveBilateral,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC3)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params);
double sigmaspace = 10.0;
Size ksize(9,9);
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000)
declare.time(15);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::adaptiveBilateralFilter(oclSrc, oclDst, ksize, sigmaspace);
oclDst.download(dst);
SANITY_CHECK(dst, 1.);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::adaptiveBilateralFilter(src, dst, ksize, sigmaspace);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
<commit_msg>fix warnings<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 std::tr1::get;
using std::tr1::tuple;
///////////// Blur////////////////////////
typedef Size_MatType BlurFixture;
PERF_TEST_P(BlurFixture, Blur,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params), ksize(3, 3);
const int type = get<1>(params), bordertype = BORDER_CONSTANT;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(5);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::blur(oclSrc, oclDst, ksize, Point(-1, -1), bordertype);
oclDst.download(dst);
SANITY_CHECK(dst, 1 + DBL_EPSILON);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::blur(src, dst, ksize, Point(-1, -1), bordertype);
SANITY_CHECK(dst, 1 + DBL_EPSILON);
}
else
OCL_PERF_ELSE
}
///////////// Laplacian////////////////////////
typedef Size_MatType LaplacianFixture;
PERF_TEST_P(LaplacianFixture, Laplacian,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 3;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(6);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::Laplacian(oclSrc, oclDst, -1, ksize, 1);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize, 1);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Erode ////////////////////
typedef Size_MatType ErodeFixture;
PERF_TEST_P(ErodeFixture, Erode,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 3;
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(5);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type), oclKer(ker);
OCL_TEST_CYCLE() cv::ocl::erode(oclSrc, oclDst, oclKer);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::erode(src, dst, ker);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Sobel ////////////////////////
typedef Size_MatType SobelFixture;
PERF_TEST_P(SobelFixture, Sobel,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 1;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if ((srcSize == OCL_SIZE_2000 && type == CV_8UC4) ||
(srcSize == OCL_SIZE_4000 && type == CV_8UC1))
declare.time(5.5);
else if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(20);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::Sobel(oclSrc, oclDst, -1, dx, dy);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::Sobel(src, dst, -1, dx, dy);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Scharr ////////////////////////
typedef Size_MatType ScharrFixture;
PERF_TEST_P(ScharrFixture, Scharr,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 0;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if ((srcSize == OCL_SIZE_2000 && type == CV_8UC4) ||
(srcSize == OCL_SIZE_4000 && type == CV_8UC1))
declare.time(5.5);
else if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(21);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::Scharr(oclSrc, oclDst, -1, dx, dy);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::Scharr(src, dst, -1, dx, dy);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// GaussianBlur ////////////////////////
typedef Size_MatType GaussianBlurFixture;
PERF_TEST_P(GaussianBlurFixture, GaussianBlur,
::testing::Combine(::testing::Values(OCL_SIZE_1000, OCL_SIZE_2000),
OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 7;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
const double eps = src.depth() == CV_8U ? 1 + DBL_EPSILON : 3e-4;
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::GaussianBlur(oclSrc, oclDst, Size(ksize, ksize), 0);
oclDst.download(dst);
SANITY_CHECK(dst, eps);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::GaussianBlur(src, dst, Size(ksize, ksize), 0);
SANITY_CHECK(dst, eps);
}
else
OCL_PERF_ELSE
}
///////////// filter2D////////////////////////
typedef Size_MatType filter2DFixture;
PERF_TEST_P(filter2DFixture, filter2D,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = 3;
Mat src(srcSize, type), dst(srcSize, type), kernel(ksize, ksize, CV_32SC1);
declare.in(src, WARMUP_RNG).in(kernel).out(dst);
randu(kernel, -3.0, 3.0);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC4)
declare.time(8);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type), oclKernel(kernel);
OCL_TEST_CYCLE() cv::ocl::filter2D(oclSrc, oclDst, -1, oclKernel);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// Bilateral////////////////////////
typedef Size_MatType BilateralFixture;
PERF_TEST_P(BilateralFixture, Bilateral,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC3)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), d = 7;
double sigmacolor = 50.0, sigmaspace = 50.0;
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000 && type == CV_8UC3)
declare.time(8);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::bilateralFilter(oclSrc, oclDst, d, sigmacolor, sigmaspace);
oclDst.download(dst);
SANITY_CHECK(dst);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::bilateralFilter(src, dst, d, sigmacolor, sigmaspace);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
///////////// adaptiveBilateral////////////////////////
typedef Size_MatType adaptiveBilateralFixture;
PERF_TEST_P(adaptiveBilateralFixture, adaptiveBilateral,
::testing::Combine(OCL_TYPICAL_MAT_SIZES,
OCL_PERF_ENUM(CV_8UC1, CV_8UC3)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params);
double sigmaspace = 10.0;
Size ksize(9,9);
Mat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
if (srcSize == OCL_SIZE_4000)
declare.time(15);
if (RUN_OCL_IMPL)
{
ocl::oclMat oclSrc(src), oclDst(srcSize, type);
OCL_TEST_CYCLE() cv::ocl::adaptiveBilateralFilter(oclSrc, oclDst, ksize, sigmaspace);
oclDst.download(dst);
SANITY_CHECK(dst, 1.);
}
else if (RUN_PLAIN_IMPL)
{
TEST_CYCLE() cv::adaptiveBilateralFilter(src, dst, ksize, sigmaspace);
SANITY_CHECK(dst);
}
else
OCL_PERF_ELSE
}
<|endoftext|>
|
<commit_before>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "iree/compiler/Dialect/Flow/Utils/WorkloadUtils.h"
#include <array>
#include <limits>
#include "iree/compiler/Dialect/Shape/IR/Builders.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeOps.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeTypes.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Support/LLVM.h"
#include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h"
namespace mlir {
namespace iree_compiler {
using Shape::buildOrFindRankedShapeForValue;
using Shape::RankedDimOp;
namespace IREE {
namespace Flow {
Value calculateWorkload(Operation *op, Value baseOperand) {
OpBuilder builder(op->getContext());
auto baseOperandType = baseOperand.getType().cast<ShapedType>();
if (baseOperandType.hasRank() && baseOperandType.hasStaticShape()) {
// Just a constant (note this also covers rank0).
int64_t numElements = baseOperandType.getNumElements();
if (numElements > std::numeric_limits<int32_t>::max()) {
return (op->emitOpError()
<< "total element count > 32bit integer capacity"),
nullptr;
}
builder.setInsertionPointToStart(op->getBlock());
return builder.create<ConstantOp>(
op->getLoc(), builder.getIndexType(),
builder.getIntegerAttr(builder.getIndexType(), numElements));
} else if (baseOperandType.hasRank()) {
// Materialize a ranked shape and compute.
auto rankedShape = buildOrFindRankedShapeForValue(
op->getLoc(), baseOperand, builder.getIndexType(), builder);
if (!rankedShape) return nullptr;
// Ensure to emit with proper dominance.
// TODO(laurenzo): Need to overhaul insertion points generally in
// dispatch region formation.
if (rankedShape.getDefiningOp()) {
builder.setInsertionPointAfter(rankedShape.getDefiningOp());
}
Value numElements;
for (int64_t i = 0, e = baseOperandType.getRank(); i < e; ++i) {
auto dim = builder.create<RankedDimOp>(op->getLoc(), rankedShape, i);
if (!numElements) {
numElements = dim;
continue;
}
numElements = builder.create<MulIOp>(op->getLoc(), numElements, dim);
}
op->getParentOp()->dump();
return numElements;
} else {
op->emitOpError()
<< "unranked shapes not supported for workload calculation";
return nullptr;
}
}
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Another special case for dominance issues in workload calculations.<commit_after>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "iree/compiler/Dialect/Flow/Utils/WorkloadUtils.h"
#include <array>
#include <limits>
#include "iree/compiler/Dialect/Shape/IR/Builders.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeOps.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeTypes.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Support/LLVM.h"
#include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h"
namespace mlir {
namespace iree_compiler {
using Shape::buildOrFindRankedShapeForValue;
using Shape::RankedDimOp;
namespace IREE {
namespace Flow {
Value calculateWorkload(Operation *op, Value baseOperand) {
OpBuilder builder(op->getContext());
auto baseOperandType = baseOperand.getType().cast<ShapedType>();
if (baseOperandType.hasRank() && baseOperandType.hasStaticShape()) {
// Just a constant (note this also covers rank0).
int64_t numElements = baseOperandType.getNumElements();
if (numElements > std::numeric_limits<int32_t>::max()) {
return (op->emitOpError()
<< "total element count > 32bit integer capacity"),
nullptr;
}
builder.setInsertionPointToStart(op->getBlock());
return builder.create<ConstantOp>(
op->getLoc(), builder.getIndexType(),
builder.getIntegerAttr(builder.getIndexType(), numElements));
} else if (baseOperandType.hasRank()) {
// Materialize a ranked shape and compute.
auto rankedShape = buildOrFindRankedShapeForValue(
op->getLoc(), baseOperand, builder.getIndexType(), builder);
if (!rankedShape) return nullptr;
// Set the insertion point to the earliest feasible (either to just after
// the input ranked shape op or the start of the block we are emitting
// into).
// TODO(laurenzo): Need to overhaul insertion points generally in
// dispatch region formation as there are dominance hazards here.
if (rankedShape.getDefiningOp()) {
builder.setInsertionPointAfter(rankedShape.getDefiningOp());
} else {
builder.setInsertionPointToStart(op->getBlock());
}
Value numElements;
for (int64_t i = 0, e = baseOperandType.getRank(); i < e; ++i) {
auto dim = builder.create<RankedDimOp>(op->getLoc(), rankedShape, i);
if (!numElements) {
numElements = dim;
continue;
}
numElements = builder.create<MulIOp>(op->getLoc(), numElements, dim);
}
op->getParentOp()->dump();
return numElements;
} else {
op->emitOpError()
<< "unranked shapes not supported for workload calculation";
return nullptr;
}
}
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|>
|
<commit_before>#include "MediaSessionServiceHandler.h"
#include "log.h"
using namespace ::com::kurento::kms::api;
using ::com::kurento::log::Log;
static Log l("MediaSessionHandler");
#define i(...) aux_info(l, __VA_ARGS__);
namespace com { namespace kurento { namespace kms {
MediaSessionServiceHandler::MediaSessionServiceHandler() {
manager = MediaSessionManager::getInstance();
}
MediaSessionServiceHandler::~MediaSessionServiceHandler() {
MediaSessionManager::releaseInstance(manager);
}
void
MediaSessionServiceHandler::createNetworkConnection(NetworkConnection& _return,
const MediaSession& mediaSession,
const std::vector<NetworkConnectionConfig::type>& config) {
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
_return = session.createNetworkConnection(config);
i("Created NetworkConnection with id: %d", _return.joinable.object.id);
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::deleteNetworkConnection(
const MediaSession& mediaSession,
const NetworkConnection& networkConnection) {
i("deleteNetworkConnection: %d", networkConnection.joinable.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
session.deleteNetworkConnection(networkConnection);
} catch(NetworkConnectionNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::getNetworkConnections(
std::vector<NetworkConnection>& _return,
const MediaSession& mediaSession) {
i("getNetworkConnections");
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
session.getNetworkConnections(_return);
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::createMixer(Mixer& _return,
const MediaSession& mediaSession,
const std::vector<MixerConfig::type>& config) {
i("createMixer");
}
void
MediaSessionServiceHandler::deleteMixer(const MediaSession& mediaSession,
const Mixer& mixer) {
i("deleteMixer");
}
void
MediaSessionServiceHandler::getMixers(std::vector<Mixer>& _return,
const MediaSession& mediaSession) {
i("getMixers");
}
void
MediaSessionServiceHandler::ping(const MediaObject& mediaObject,
const int32_t timeout) {
i("ping");
}
void
MediaSessionServiceHandler::release(const MediaObject& mediaObject) {
i("release");
}
}}} // com::kurento::kms<commit_msg>Implement methods in handler to manage mixers<commit_after>#include "MediaSessionServiceHandler.h"
#include "log.h"
using namespace ::com::kurento::kms::api;
using ::com::kurento::log::Log;
static Log l("MediaSessionHandler");
#define i(...) aux_info(l, __VA_ARGS__);
namespace com { namespace kurento { namespace kms {
MediaSessionServiceHandler::MediaSessionServiceHandler() {
manager = MediaSessionManager::getInstance();
}
MediaSessionServiceHandler::~MediaSessionServiceHandler() {
MediaSessionManager::releaseInstance(manager);
}
void
MediaSessionServiceHandler::createNetworkConnection(NetworkConnection& _return,
const MediaSession& mediaSession,
const std::vector<NetworkConnectionConfig::type>& config) {
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
_return = session.createNetworkConnection(config);
i("Created NetworkConnection with id: %d", _return.joinable.object.id);
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::deleteNetworkConnection(
const MediaSession& mediaSession,
const NetworkConnection& networkConnection) {
i("deleteNetworkConnection: %d", networkConnection.joinable.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
session.deleteNetworkConnection(networkConnection);
} catch(NetworkConnectionNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::getNetworkConnections(
std::vector<NetworkConnection>& _return,
const MediaSession& mediaSession) {
i("getNetworkConnections");
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
session.getNetworkConnections(_return);
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::createMixer(Mixer& _return,
const MediaSession& mediaSession,
const std::vector<MixerConfig::type>& config) {
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
_return = session.createMixer(config);
i("Mixer created with id: %d", _return.joinable.object.id);
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::deleteMixer(const MediaSession& mediaSession,
const Mixer& mixer) {
i("deleteMixer with id: %d", mixer.joinable.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
session.deleteMixer(mixer);
} catch(MixerNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::getMixers(std::vector<Mixer>& _return,
const MediaSession& mediaSession) {
i("getMixers");
try {
MediaSessionImpl &session = manager->getMediaSession(mediaSession);
session.getMixers(_return);
} catch (MediaSessionNotFoundException ex) {
throw ex;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
MediaSessionServiceHandler::ping(const MediaObject& mediaObject,
const int32_t timeout) {
i("ping");
}
void
MediaSessionServiceHandler::release(const MediaObject& mediaObject) {
i("release");
}
}}} // com::kurento::kms<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: appquit.cxx,v $
*
* $Revision: 1.33 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:35:58 $
*
* 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 _BASMGR_HXX //autogen
#include <basic/basmgr.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif
#ifdef WIN
#define _TL_LANG_SPECIAL
#endif
#ifndef _SVDDE_HXX //autogen
#include <svtools/svdde.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#include <svtools/saveopt.hxx>
#include <svtools/misccfg.hxx>
#ifndef GCC
#pragma hdrstop
#endif
#include "app.hrc"
#include "app.hxx"
#include "unoctitm.hxx"
#include "appdata.hxx"
#include "viewsh.hxx"
#include "dispatch.hxx"
#include "printer.hxx"
#include "arrdecl.hxx"
#include "sfxresid.hxx"
#include "newhdl.hxx"
#include "event.hxx"
#include "macrconf.hxx"
#include "mnumgr.hxx"
#include "templdlg.hxx"
#include "msgpool.hxx"
#include "docfile.hxx"
#include "sfxtypes.hxx"
#include "appimp.hxx"
#include "sfxlocal.hrc"
#include "fcontnr.hxx"
#include "nochaos.hxx"
#include "appuno.hxx"
#include "doctempl.hxx"
#include "viewfrm.hxx"
#include "bmkmenu.hxx"
#include "objsh.hxx"
#include "dlgcont.hxx"
#include "scriptcont.hxx"
#include "docfac.hxx"
#ifndef PRODUCT
DECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )
SV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);
#endif
//===================================================================
/*
void SfxApplication::Quit()
{
QueryExit_Impl();
}
*/
//--------------------------------------------------------------------
BOOL SfxApplication::QueryExit_Impl()
/* [Beschreibung]
Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder
der Printer einer SfxViewShell einen laufenden Druckjob hat.
[Anmerkung]
Wenn diese aus StarView stammende virtuelle Methode vom Applikations-
entwickler "uberladen wird, mu"s diese SfxApplication::QueryExit() rufen
und falls diese FALSE zur"uckgibt, ebenfalls FALSE zur"uckgeben.
*/
{
BOOL bQuit = TRUE;
/*
BOOL bPrinting = FALSE;
for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
!bPrinting && pViewSh;
pViewSh = SfxViewShell::GetNext(*pViewSh) )
{
SfxPrinter *pPrinter = pViewSh->GetPrinter();
bPrinting = pPrinter && pPrinter->IsPrinting();
}
if ( bPrinting )
{
// Benutzer fragen, ob abgebrochen werden soll
if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )
{
// alle Jobs canceln
for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
!bPrinting && pViewSh;
pViewSh = SfxViewShell::GetNext(*pViewSh) )
{
SfxPrinter *pPrinter = pViewSh->GetPrinter();
if ( pPrinter && pPrinter->IsPrinting() )
pPrinter->AbortJob();
}
// da das Canceln asynchron ist, Quit erstmal wieder verlassen
GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );
DBG_TRACE( "QueryExit => FALSE (printing)" );
return FALSE;
}
}
*/
// alles canceln was zu canceln ist
GetCancelManager()->Cancel(TRUE);
/*
SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();
if ( bQuit )
{
// Jetzt zur Sicherheit auch hidden Frames abr"aumen
SfxViewFrame::CloseHiddenFrames_Impl();
pLastDocSh = SfxObjectShell::GetFirst();
}
*/
// will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?
if ( !bQuit )
{
// nicht wirklich beenden, nur minimieren
pAppData_Impl->bOLEResize = TRUE;
InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );
aInfoBox.Execute();
DBG_TRACE( "QueryExit => FALSE (in use)" );
return FALSE;
}
return TRUE;
}
//-------------------------------------------------------------------------
void SfxApplication::Deinitialize()
{
if ( bDowning )
return;
// Falls man nochmal beim Runterfahren in ein Reschedule l"auft
pAppData_Impl->EndListening( *this );
if ( pAppData_Impl->pCancelMgr )
pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );
//!Wait();
StarBASIC::Stop();
// ggf. BASIC speichern
BasicManager* pBasMgr = GetAppBasicManager();
if ( pBasMgr && pBasMgr->IsModified() )
SaveBasicManager();
SaveBasicContainer();
SaveDialogContainer();
bDowning = TRUE; // wegen Timer aus DecAliveCount und QueryExit
DELETEZ( pAppData_Impl->pTemplates );
DELETEZ(pImp->pTemplateDlg);
SetViewFrame(0);
bDowning = FALSE;
DBG_ASSERT( !SfxViewFrame::GetFirst(),
"existing SfxViewFrame after Execute" );
DBG_ASSERT( !SfxObjectShell::GetFirst(),
"existing SfxObjectShell after Execute" );
pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );
pAppDispat->Flush();
bDowning = TRUE;
pAppDispat->DoDeactivate_Impl( TRUE );
// call derived application-exit
bInExit = TRUE;
Exit();
// Controller u."a. freigeben
// dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden
DELETEZ( pBasMgr );
SetAppBasicManager( NULL );
if( pImp->pBasicLibContainer )
pImp->pBasicLibContainer->release();
if( pImp->pDialogLibContainer )
pImp->pDialogLibContainer->release();
bInExit = FALSE;
DBG_ASSERT( pViewFrame == 0, "active foreign ViewFrame" );
delete[] pInterfaces, pInterfaces = 0;
// free administration managers
DELETEZ(pAppDispat);
SfxResId::DeleteResMgr();
DELETEZ(pImp->pOfaResMgr);
// ab hier d"urfen keine SvObjects mehr existieren
DELETEZ(pAppData_Impl->pMatcher);
delete pAppData_Impl->pLabelResMgr;
#ifndef PRODUCT
DELETEX(pSlotPool);
DELETEX(pAppData_Impl->pEventConfig);
DELETEX(pAppData_Impl->pMiscConfig);
SfxMacroConfig::Release_Impl();
DELETEX(pAppData_Impl->pFactArr);
DELETEX(pAppData_Impl->pInitLinkList);
#endif
#ifndef PRODUCT
DELETEX(pImp->pTbxCtrlFac);
DELETEX(pImp->pStbCtrlFac);
DELETEX(pImp->pMenuCtrlFac);
DELETEX(pImp->pEventHdl);
SfxNewHdl::Delete();
DELETEX(pImp->pViewFrames);
DELETEX(pImp->pViewShells);
DELETEX(pImp->pObjShells);
#endif
NoChaos::ReleaseItemPool();
pAppData_Impl->pPool = NULL;
}
<commit_msg>INTEGRATION: CWS fwk29 (1.33.96); FILE MERGED 2006/01/31 08:52:16 as 1.33.96.1: #i61403# dont remove global pool as workaround for TestTool->FileExit() use case<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: appquit.cxx,v $
*
* $Revision: 1.34 $
*
* last change: $Author: rt $ $Date: 2006-02-07 10:27:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BASMGR_HXX //autogen
#include <basic/basmgr.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif
#ifdef WIN
#define _TL_LANG_SPECIAL
#endif
#ifndef _SVDDE_HXX //autogen
#include <svtools/svdde.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#include <svtools/saveopt.hxx>
#include <svtools/misccfg.hxx>
#ifndef GCC
#pragma hdrstop
#endif
#include "app.hrc"
#include "app.hxx"
#include "unoctitm.hxx"
#include "appdata.hxx"
#include "viewsh.hxx"
#include "dispatch.hxx"
#include "printer.hxx"
#include "arrdecl.hxx"
#include "sfxresid.hxx"
#include "newhdl.hxx"
#include "event.hxx"
#include "macrconf.hxx"
#include "mnumgr.hxx"
#include "templdlg.hxx"
#include "msgpool.hxx"
#include "docfile.hxx"
#include "sfxtypes.hxx"
#include "appimp.hxx"
#include "sfxlocal.hrc"
#include "fcontnr.hxx"
#include "nochaos.hxx"
#include "appuno.hxx"
#include "doctempl.hxx"
#include "viewfrm.hxx"
#include "bmkmenu.hxx"
#include "objsh.hxx"
#include "dlgcont.hxx"
#include "scriptcont.hxx"
#include "docfac.hxx"
#ifndef PRODUCT
DECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )
SV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);
#endif
//===================================================================
/*
void SfxApplication::Quit()
{
QueryExit_Impl();
}
*/
//--------------------------------------------------------------------
BOOL SfxApplication::QueryExit_Impl()
/* [Beschreibung]
Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder
der Printer einer SfxViewShell einen laufenden Druckjob hat.
[Anmerkung]
Wenn diese aus StarView stammende virtuelle Methode vom Applikations-
entwickler "uberladen wird, mu"s diese SfxApplication::QueryExit() rufen
und falls diese FALSE zur"uckgibt, ebenfalls FALSE zur"uckgeben.
*/
{
BOOL bQuit = TRUE;
/*
BOOL bPrinting = FALSE;
for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
!bPrinting && pViewSh;
pViewSh = SfxViewShell::GetNext(*pViewSh) )
{
SfxPrinter *pPrinter = pViewSh->GetPrinter();
bPrinting = pPrinter && pPrinter->IsPrinting();
}
if ( bPrinting )
{
// Benutzer fragen, ob abgebrochen werden soll
if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )
{
// alle Jobs canceln
for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();
!bPrinting && pViewSh;
pViewSh = SfxViewShell::GetNext(*pViewSh) )
{
SfxPrinter *pPrinter = pViewSh->GetPrinter();
if ( pPrinter && pPrinter->IsPrinting() )
pPrinter->AbortJob();
}
// da das Canceln asynchron ist, Quit erstmal wieder verlassen
GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );
DBG_TRACE( "QueryExit => FALSE (printing)" );
return FALSE;
}
}
*/
// alles canceln was zu canceln ist
GetCancelManager()->Cancel(TRUE);
/*
SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();
if ( bQuit )
{
// Jetzt zur Sicherheit auch hidden Frames abr"aumen
SfxViewFrame::CloseHiddenFrames_Impl();
pLastDocSh = SfxObjectShell::GetFirst();
}
*/
// will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?
if ( !bQuit )
{
// nicht wirklich beenden, nur minimieren
pAppData_Impl->bOLEResize = TRUE;
InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );
aInfoBox.Execute();
DBG_TRACE( "QueryExit => FALSE (in use)" );
return FALSE;
}
return TRUE;
}
//-------------------------------------------------------------------------
void SfxApplication::Deinitialize()
{
if ( bDowning )
return;
// Falls man nochmal beim Runterfahren in ein Reschedule l"auft
pAppData_Impl->EndListening( *this );
if ( pAppData_Impl->pCancelMgr )
pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );
//!Wait();
StarBASIC::Stop();
// ggf. BASIC speichern
BasicManager* pBasMgr = GetAppBasicManager();
if ( pBasMgr && pBasMgr->IsModified() )
SaveBasicManager();
SaveBasicContainer();
SaveDialogContainer();
bDowning = TRUE; // wegen Timer aus DecAliveCount und QueryExit
DELETEZ( pAppData_Impl->pTemplates );
DELETEZ(pImp->pTemplateDlg);
SetViewFrame(0);
bDowning = FALSE;
DBG_ASSERT( !SfxViewFrame::GetFirst(),
"existing SfxViewFrame after Execute" );
DBG_ASSERT( !SfxObjectShell::GetFirst(),
"existing SfxObjectShell after Execute" );
pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );
pAppDispat->Flush();
bDowning = TRUE;
pAppDispat->DoDeactivate_Impl( TRUE );
// call derived application-exit
bInExit = TRUE;
Exit();
// Controller u."a. freigeben
// dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden
DELETEZ( pBasMgr );
SetAppBasicManager( NULL );
if( pImp->pBasicLibContainer )
pImp->pBasicLibContainer->release();
if( pImp->pDialogLibContainer )
pImp->pDialogLibContainer->release();
bInExit = FALSE;
DBG_ASSERT( pViewFrame == 0, "active foreign ViewFrame" );
delete[] pInterfaces, pInterfaces = 0;
// free administration managers
DELETEZ(pAppDispat);
SfxResId::DeleteResMgr();
DELETEZ(pImp->pOfaResMgr);
// ab hier d"urfen keine SvObjects mehr existieren
DELETEZ(pAppData_Impl->pMatcher);
delete pAppData_Impl->pLabelResMgr;
#ifndef PRODUCT
DELETEX(pSlotPool);
DELETEX(pAppData_Impl->pEventConfig);
DELETEX(pAppData_Impl->pMiscConfig);
SfxMacroConfig::Release_Impl();
DELETEX(pAppData_Impl->pFactArr);
DELETEX(pAppData_Impl->pInitLinkList);
#endif
#ifndef PRODUCT
DELETEX(pImp->pTbxCtrlFac);
DELETEX(pImp->pStbCtrlFac);
DELETEX(pImp->pMenuCtrlFac);
DELETEX(pImp->pEventHdl);
SfxNewHdl::Delete();
DELETEX(pImp->pViewFrames);
DELETEX(pImp->pViewShells);
DELETEX(pImp->pObjShells);
#endif
/* This leak is intended !
Otherwise the TestTool cant use .uno:QuitApp ...
because every destructed ItemSet work's on an already
released pool pointer .-)
NoChaos::ReleaseItemPool();
*/
pAppData_Impl->pPool = NULL;
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2017 Maria Glukhova
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// CUDA utilities and system includes
#include <cuda_runtime.h>
#include "device_launch_parameters.h"
// Helper functions
#include <helper_functions.h> // CUDA SDK Helper functions
#include <helper_cuda.h> // CUDA device initialization helper functions
#include <helper_cuda_gl.h> // CUDA device + OpenGL initialization functions
#include <stdlib.h>
#include <stdio.h>
#include <png.h>
#include "imageio.h"
#include "histogram_gpu.h"
#include "histogram_cpu.h"
void probe_image(PixelType* image, png_infop info, unsigned int n) {
/**
* Debug: print every 10th pixel.
*/
PixelType pixel;
for (uint y = 0; y < info->height; y += n){
for (uint x = 0; x < info->width; x += n){
pixel = image[y * info->width + x];
unsigned char* samples = reinterpret_cast<unsigned char*>(&pixel);
printf("[");
#pragma unroll
for (int CHANNEL = 0; CHANNEL < ACTIVE_CHANNELS; ++CHANNEL) {
printf("%4u", (unsigned int) (samples[CHANNEL]));
}
printf("]");
}
printf("\n");
}
}
void print_histogram(unsigned int* hist) {
/**
* Print histogram to the stdout.
*/
printf("Histogram:\n");
printf("########### ");
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("[%3u-%3u]", bin * K_BIN, (bin + 1) * K_BIN - 1);
}
printf("\n");
for (uint ch = 0; ch < ACTIVE_CHANNELS; ch++) {
printf("Channel %u: ", ch + 1);
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("%8u ", hist[ch * NUM_BINS + bin]);
}
printf("\n");
}
}
unsigned int compare_histograms(const unsigned int* hist_a,
const unsigned int* hist_b, unsigned int n) {
while ( --n > 0 && hist_a[n] == hist_b[n]);
return n;
}
void print_help(char* arg0) {
printf("Compute color histogram of PNG image using GPU and CPU.\n\n");
printf("Usage: %s file.png [options]\n", arg0);
printf("Options: \n");
printf("%-30s %-29s", "-t N, --times N", "Run both GPU and CPU "
"version N times; output averaged time and speed. Default = 1.\n");
printf("%-30s %-29s", "-h, --help", "Print this message and exit.\n");
printf("\nReport bugs to siamezzze@gmail.com.\n");
}
int main (int argc, char* argv[]) {
// Main variables initialization.
PixelType* h_pixels;
PixelType* d_pixels;
unsigned int* d_hist;
unsigned int* h_hist;
unsigned int* cpu_hist;
png_infop info;
StopWatchInterface *h_timer = NULL;
unsigned int num_runs = 1;
// Command-line argument parsing.
if(argc < 2) {
printf("Error: No input file specified.\n");
print_help(argv[0]);
return -1;
}
if (strcmp(argv[1], "-h") == 0 or strcmp(argv[1], "--help") == 0) {
print_help(argv[0]);
return 0;
}
unsigned int arg_it = 2;
while (arg_it < argc) {
if (strcmp(argv[arg_it], "-t") == 0 or
strcmp(argv[arg_it], "--times") == 0) {
arg_it++;
num_runs = std::max(1, std::atoi(argv[arg_it]));
}
else if (strcmp(argv[arg_it], "-h") == 0 or
strcmp(argv[arg_it], "--help") == 0) {
print_help(argv[0]);
return 0;
}
else {
printf("Unrecognized argument: %s. Use -h or --help for usage "
"information.\n", argv[arg_it]);
}
arg_it++;
}
// Read image.
if(read_png(argv[1], &info, &h_pixels) == PNG_FAILURE) {
printf("Error reading file (%s).\n", argv[1]);
return -1;
}
size_t number_of_bytes = sizeof(uchar4) * info->width * info->height;
printf("Image %s loaded (%lu x %lu px.)\n", argv[1], info->height, info->width);
sdkCreateTimer(&h_timer);
// CPU
printf("\nCPU: \n");
cpu_hist = (uint* )calloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), sizeof(uint));
sdkResetTimer(&h_timer);
for (unsigned int i = 0; i < num_runs; i++) {
std::fill(cpu_hist, cpu_hist + ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), 0);
sdkStartTimer(&h_timer);
run_cpu(h_pixels, info->width, info->height, cpu_hist);
sdkStopTimer(&h_timer);
}
sdkStopTimer(&h_timer);
double cpu_avg_secs = 1.0e-3 * (double)sdkGetTimerValue(&h_timer) / (double)num_runs;
printf("\nrun_cpu() time (average from %u runs) : %.5f sec, %.4f MB/sec\n\n", num_runs, cpu_avg_secs, ((double)number_of_bytes * 1.0e-6) / cpu_avg_secs);
print_histogram(cpu_hist);
// Copy data to GPU
printf("\nGPU: \n");
printf("Allocating GPU memory and copying input data...");
checkCudaErrors(cudaMalloc((void **)&d_pixels, number_of_bytes));
checkCudaErrors(cudaMalloc((void **)&d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint)));
checkCudaErrors(cudaMemcpy(d_pixels, h_pixels, number_of_bytes, cudaMemcpyHostToDevice));
printf("Done\n");
// Run histogram computing
printf("Computing histogram...");
cudaDeviceSynchronize();
sdkResetTimer(&h_timer);
sdkStartTimer(&h_timer);
for (unsigned int i = 0; i < num_runs; i++) {
run_gmem_atomics(d_pixels, info->width, info->height, d_hist);
}
cudaDeviceSynchronize();
sdkStopTimer(&h_timer);
printf("Done\n");
double d_avg_secs = 1.0e-3 * (double)sdkGetTimerValue(&h_timer) / (double)num_runs;
// Copy result back to CPU
printf("Copying result to CPU...");
h_hist = (uint* )malloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint));
checkCudaErrors(cudaMemcpy(h_hist, d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), cudaMemcpyDeviceToHost));
printf("Done\n");
printf("\nrun_gmem_atomics() time (average from %u runs) : %.5f sec, %.4f MB/sec\n\n", num_runs, d_avg_secs, ((double)number_of_bytes * 1.0e-6) / d_avg_secs);
// Print results.
print_histogram(h_hist);
unsigned int hists_ne = compare_histograms(cpu_hist, h_hist, ACTIVE_CHANNELS * NUM_BINS);
if (hists_ne) {
printf("Histograms differ!\nChannel %u, bin %u:\nCPU histogram: %3u\nGPU histogram: %3u\n",
hists_ne / NUM_BINS, hists_ne % NUM_BINS, cpu_hist[hists_ne], h_hist[hists_ne]);
}
printf("Freeing the memory...");
checkCudaErrors(cudaFree(d_pixels));
checkCudaErrors(cudaFree(d_hist));
free(h_pixels);
free(h_hist);
free(cpu_hist);
printf("Done\n");
return 0;
}
<commit_msg>Commented more of the main().<commit_after>/**
* Copyright 2017 Maria Glukhova
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// CUDA utilities and system includes
#include <cuda_runtime.h>
#include "device_launch_parameters.h"
// Helper functions
#include <helper_functions.h> // CUDA SDK Helper functions
#include <helper_cuda.h> // CUDA device initialization helper functions
#include <helper_cuda_gl.h> // CUDA device + OpenGL initialization functions
#include <stdlib.h>
#include <stdio.h>
#include <png.h>
#include "imageio.h"
#include "histogram_gpu.h"
#include "histogram_cpu.h"
void probe_image(PixelType* image, png_infop info, unsigned int n) {
/**
* Debug: print every nth pixel.
*/
PixelType pixel;
for (uint y = 0; y < info->height; y += n){
for (uint x = 0; x < info->width; x += n){
pixel = image[y * info->width + x];
unsigned char* samples = reinterpret_cast<unsigned char*>(&pixel);
printf("[");
#pragma unroll
for (int CHANNEL = 0; CHANNEL < ACTIVE_CHANNELS; ++CHANNEL) {
printf("%4u", (unsigned int) (samples[CHANNEL]));
}
printf("]");
}
printf("\n");
}
}
void print_histogram(unsigned int* hist) {
/**
* Print histogram to the stdout.
*/
printf("Histogram:\n");
printf("########### ");
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("[%3u-%3u]", bin * K_BIN, (bin + 1) * K_BIN - 1);
}
printf("\n");
for (uint ch = 0; ch < ACTIVE_CHANNELS; ch++) {
printf("Channel %u: ", ch + 1);
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("%8u ", hist[ch * NUM_BINS + bin]);
}
printf("\n");
}
}
unsigned int compare_histograms(const unsigned int* hist_a,
const unsigned int* hist_b, unsigned int n) {
/**
* Compare two arrays (in our case, histograms).
* If they are identical, return 0.
* If they are not, return index of the _last_ differing element.
*/
while ( --n > 0 && hist_a[n] == hist_b[n]);
return n;
}
void print_help(char* arg0) {
/**
* Print standard UNIX-style help message.
*/
printf("Compute color histogram of PNG image using GPU and CPU.\n\n");
printf("Usage: %s file.png [options]\n", arg0);
printf("Options: \n");
printf("%-30s %-29s", "-t N, --times N", "Run both GPU and CPU "
"version N times; output averaged time and speed. Default = 1.\n");
printf("%-30s %-29s", "-h, --help", "Print this message and exit.\n");
printf("\nReport bugs to siamezzze@gmail.com.\n");
}
int main (int argc, char* argv[]) {
// Main variables initialization.
PixelType* h_pixels;
PixelType* d_pixels;
unsigned int* d_hist;
unsigned int* h_hist;
unsigned int* cpu_hist;
png_infop info;
StopWatchInterface *h_timer = NULL;
unsigned int num_runs = 1;
// Command-line argument parsing.
if(argc < 2) {
printf("Error: No input file specified.\n");
print_help(argv[0]);
return -1;
}
if (strcmp(argv[1], "-h") == 0 or strcmp(argv[1], "--help") == 0) {
print_help(argv[0]);
return 0;
}
unsigned int arg_it = 2;
while (arg_it < argc) {
if (strcmp(argv[arg_it], "-t") == 0 or
strcmp(argv[arg_it], "--times") == 0) {
arg_it++;
num_runs = std::max(1, std::atoi(argv[arg_it]));
}
else if (strcmp(argv[arg_it], "-h") == 0 or
strcmp(argv[arg_it], "--help") == 0) {
print_help(argv[0]);
return 0;
}
else {
printf("Unrecognized argument: %s. Use -h or --help for usage "
"information.\n", argv[arg_it]);
}
arg_it++;
}
// Read image.
if(read_png(argv[1], &info, &h_pixels) == PNG_FAILURE) {
printf("Error reading file (%s).\n", argv[1]);
return -1;
}
size_t number_of_bytes = sizeof(uchar4) * info->width * info->height;
printf("Image %s loaded (%lu x %lu px.)\n", argv[1], info->height, info->width);
sdkCreateTimer(&h_timer);
// CPU
printf("\nCPU: \n");
cpu_hist = (uint* )calloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), sizeof(uint));
sdkResetTimer(&h_timer);
for (unsigned int i = 0; i < num_runs; i++) {
std::fill(cpu_hist, cpu_hist + ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), 0);
sdkStartTimer(&h_timer);
run_cpu(h_pixels, info->width, info->height, cpu_hist);
sdkStopTimer(&h_timer);
}
sdkStopTimer(&h_timer);
double cpu_avg_secs = 1.0e-3 * (double)sdkGetTimerValue(&h_timer) / (double)num_runs;
printf("\nrun_cpu() time (average from %u runs) : %.5f sec, %.4f MB/sec\n\n", num_runs, cpu_avg_secs, ((double)number_of_bytes * 1.0e-6) / cpu_avg_secs);
print_histogram(cpu_hist);
// Copy data to GPU
printf("\nGPU: \n");
printf("Allocating GPU memory and copying input data...");
checkCudaErrors(cudaMalloc((void **)&d_pixels, number_of_bytes));
checkCudaErrors(cudaMalloc((void **)&d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint)));
checkCudaErrors(cudaMemcpy(d_pixels, h_pixels, number_of_bytes, cudaMemcpyHostToDevice));
printf("Done\n");
// Run histogram computing
printf("Computing histogram...");
cudaDeviceSynchronize();
sdkResetTimer(&h_timer);
sdkStartTimer(&h_timer);
for (unsigned int i = 0; i < num_runs; i++) {
run_gmem_atomics(d_pixels, info->width, info->height, d_hist);
}
cudaDeviceSynchronize();
sdkStopTimer(&h_timer);
printf("Done\n");
double d_avg_secs = 1.0e-3 * (double)sdkGetTimerValue(&h_timer) / (double)num_runs;
// Copy result back to CPU
printf("Copying result to CPU...");
h_hist = (uint* )malloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint));
checkCudaErrors(cudaMemcpy(h_hist, d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), cudaMemcpyDeviceToHost));
printf("Done\n");
printf("\nrun_gmem_atomics() time (average from %u runs) : %.5f sec, %.4f MB/sec\n\n", num_runs, d_avg_secs, ((double)number_of_bytes * 1.0e-6) / d_avg_secs);
// Print results.
print_histogram(h_hist);
unsigned int hists_ne = compare_histograms(cpu_hist, h_hist, ACTIVE_CHANNELS * NUM_BINS);
if (hists_ne) {
printf("Histograms differ!\nChannel %u, bin %u:\nCPU histogram: %3u\nGPU histogram: %3u\n",
hists_ne / NUM_BINS, hists_ne % NUM_BINS, cpu_hist[hists_ne], h_hist[hists_ne]);
}
printf("Freeing the memory...");
checkCudaErrors(cudaFree(d_pixels));
checkCudaErrors(cudaFree(d_hist));
free(h_pixels);
free(h_hist);
free(cpu_hist);
printf("Done\n");
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014, Georgia Tech Research Corporation
* All rights reserved.
*
* Author: Michael X. Grey <mxgrey@gatech.edu>
* Date: Jan 2014
*
* Humanoid Robotics Lab Georgia Institute of Technology
* Director: Mike Stilman http://www.golems.org
*
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
extern "C" {
#include "../Daemonizer_C.h"
#include "HuboRT/HuboRtParams.h"
#include <syslog.h>
#include <stdlib.h>
}
#include "../Daemonizer.hpp"
using namespace HuboRT;
Daemonizer::Daemonizer(size_t safe_stack_size)
{
_d_status = 0;
_successful_launch = false;
stack_prefault_size = safe_stack_size;
_lock_directory = hubo_rt_default_lock_dir;
_log_directory = hubo_rt_default_log_dir;
}
Daemonizer::~Daemonizer()
{
if(_successful_launch)
close();
}
bool Daemonizer::begin(std::string daemon_name, int priority)
{
return daemonize(daemon_name) && prioritize(priority);
}
bool Daemonizer::daemonize(std::string daemon_name)
{
_daemon_name = daemon_name;
_d_status = hubo_rt_daemonize(daemon_name.c_str(), _lock_directory.c_str(),
_log_directory.c_str());
hubo_rt_stack_prefault(stack_prefault_size);
if(_d_status == 1)
_successful_launch = true;
return _d_status == 1;
}
bool Daemonizer::prioritize(int priority)
{
hubo_rt_stack_prefault(stack_prefault_size);
hubo_rt_lock_memory();
return hubo_rt_prioritize(priority) == 1;
}
int Daemonizer::daemonization_status() const { return _d_status; }
bool Daemonizer::good() const
{
return hubo_rt_sig_quit == 0;
}
bool Daemonizer::usr1()
{
bool _usr1 = hubo_rt_sig_usr1 != 0;
hubo_rt_sig_usr2 = 0;
return _usr1;
}
bool Daemonizer::usr2()
{
bool _usr2 = hubo_rt_sig_usr2 != 0;
hubo_rt_sig_usr2 = 0;
return _usr2;
}
size_t Daemonizer::alarm() const
{
return hubo_rt_sig_alarm;
}
size_t Daemonizer::child_processes_exited() const
{
return hubo_rt_sig_child;
}
bool Daemonizer::check(bool condition, std::string message, bool quit_immediately)
{
if(!condition)
{
std::string output = "Condition failed in process " + _daemon_name + ": " + message;
syslog(LOG_ERR, "%s", output.c_str());
hubo_rt_sig_quit = 1;
if(quit_immediately)
{
close();
exit(1);
}
}
return condition;
}
void Daemonizer::close()
{
hubo_rt_daemon_close(_daemon_name.c_str(), _lock_directory.c_str());
}
void Daemonizer::redirect_signals()
{
hubo_rt_redirect_signals();
}
<commit_msg>better reporting for daemonizer<commit_after>/*
* Copyright (c) 2014, Georgia Tech Research Corporation
* All rights reserved.
*
* Author: Michael X. Grey <mxgrey@gatech.edu>
* Date: Jan 2014
*
* Humanoid Robotics Lab Georgia Institute of Technology
* Director: Mike Stilman http://www.golems.org
*
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
extern "C" {
#include "../Daemonizer_C.h"
#include "HuboRT/HuboRtParams.h"
#include <syslog.h>
#include <stdlib.h>
}
#include <iostream>
#include "../Daemonizer.hpp"
using namespace HuboRT;
Daemonizer::Daemonizer(size_t safe_stack_size)
{
_d_status = 0;
_successful_launch = false;
stack_prefault_size = safe_stack_size;
_lock_directory = hubo_rt_default_lock_dir;
_log_directory = hubo_rt_default_log_dir;
}
Daemonizer::~Daemonizer()
{
if(_successful_launch)
close();
}
bool Daemonizer::begin(std::string daemon_name, int priority)
{
return daemonize(daemon_name) && prioritize(priority);
}
bool Daemonizer::daemonize(std::string daemon_name)
{
_daemon_name = daemon_name;
_d_status = hubo_rt_daemonize(daemon_name.c_str(), _lock_directory.c_str(),
_log_directory.c_str());
hubo_rt_stack_prefault(stack_prefault_size);
if(_d_status == 1)
{
_successful_launch = true;
}
else
{
switch(_d_status)
{
case -1: std::cout << "Requested priority is too high"; break;
case -2: std::cout << "Could not set scheduling for real-time prioritization"; break;
case -3: std::cout << "Could not set user to root"; break;
case -4: std::cout << "Could not find root account??"; break;
case -5: std::cout << "Could not create new session"; break;
case -6: std::cout << "Could not change current directory"; break;
case -7: std::cout << "Could not open lockfile"; break;
case -8: std::cout << "Could not create log files"; break;
case -9: std::cout << "Could not stream output"; break;
}
std::cout << "\n -- Check syslog for details" << std::endl;
}
return _d_status == 1;
}
bool Daemonizer::prioritize(int priority)
{
hubo_rt_stack_prefault(stack_prefault_size);
hubo_rt_lock_memory();
return hubo_rt_prioritize(priority) == 1;
}
int Daemonizer::daemonization_status() const { return _d_status; }
bool Daemonizer::good() const
{
return hubo_rt_sig_quit == 0;
}
bool Daemonizer::usr1()
{
bool _usr1 = hubo_rt_sig_usr1 != 0;
hubo_rt_sig_usr2 = 0;
return _usr1;
}
bool Daemonizer::usr2()
{
bool _usr2 = hubo_rt_sig_usr2 != 0;
hubo_rt_sig_usr2 = 0;
return _usr2;
}
size_t Daemonizer::alarm() const
{
return hubo_rt_sig_alarm;
}
size_t Daemonizer::child_processes_exited() const
{
return hubo_rt_sig_child;
}
bool Daemonizer::check(bool condition, std::string message, bool quit_immediately)
{
if(!condition)
{
std::string output = "Condition failed in process " + _daemon_name + ": " + message;
syslog(LOG_ERR, "%s", output.c_str());
hubo_rt_sig_quit = 1;
if(quit_immediately)
{
close();
exit(1);
}
}
return condition;
}
void Daemonizer::close()
{
hubo_rt_daemon_close(_daemon_name.c_str(), _lock_directory.c_str());
}
void Daemonizer::redirect_signals()
{
hubo_rt_redirect_signals();
}
<|endoftext|>
|
<commit_before>#include "StatefulTimer.h"
#include "BackpropErrorsv2Cached.h"
using namespace std;
#undef STATIC
#define STATIC
#undef VIRTUAL
#define VIRTUAL
VIRTUAL BackpropErrorsv2Cached::~BackpropErrorsv2Cached() {
delete kernel;
delete applyActivationDeriv;
}
VIRTUAL void BackpropErrorsv2Cached::backpropErrors( int batchSize,
CLWrapper *inputDataWrapper, CLWrapper *errorsWrapper, CLWrapper *weightsWrapper,
CLWrapper *errorsForUpstreamWrapper ) {
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached start" );
// const int batchSize,
// global const float *errorsGlobal,
// global const float *filtersGlobal,
// global float *errorsForUpstream,
// local float *_errorBoard,
// local float *_filterBoard ) {
kernel
->in( batchSize )
->in( errorsWrapper )
->in( weightsWrapper )
->out( errorsForUpstreamWrapper )
->localFloats( square( dim.outputBoardSize ) )
->localFloats( square( dim.filterSize ) );
int numWorkgroups = batchSize * dim.inputPlanes;
int workgroupSize = square( dim.inputBoardSize );
workgroupSize = std::max( 32, workgroupSize ); // no point in wasting cores...
int globalSize = numWorkgroups * workgroupSize;
// int globalSize = batchSize * dim.inputCubeSize;
// int workgroupsize = cl->getMaxWorkgroupSize();
// globalSize = ( ( globalSize + workgroupsize - 1 ) / workgroupsize ) * workgroupsize;
// kernel->run_1d(globalSize, workgroupsize);
kernel->run_1d(globalSize, workgroupSize);
cl->finish();
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after first kernel" );
// applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper );
// applyActivationDeriv->run_1d(globalSize, workgroupSize);
applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper );
applyActivationDeriv->run_1d(globalSize, workgroupSize);
cl->finish();
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after applyActivationDeriv" );
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached end" );
}
BackpropErrorsv2Cached::BackpropErrorsv2Cached( OpenCLHelper *cl, LayerDimensions dim, ActivationFunction const *upstreamFn ) :
BackpropErrorsv2( cl, dim, upstreamFn )
{
std::string options = dim.buildOptionsString();
options += " -D " + upstreamFn->getDefineName();
// [[[cog
// import stringify
// stringify.write_kernel2( "kernel", "cl/backproperrorsv2cached.cl", "calcErrorsForUpstreamCached", 'options' )
// # stringify.write_kernel2( "broadcastMultiply", "cl/backproperrorsv2.cl", "broadcast_multiply", 'options' )
// stringify.write_kernel2( "applyActivationDeriv", "cl/applyActivationDeriv.cl", "applyActivationDeriv", 'options' )
// # stringify.write_kernel( "kernelSource", "ClConvolve.cl")
// ]]]
// generated using cog:
const char * kernelSource =
"// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n"
"//\n"
"// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
"// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
"// obtain one at http://mozilla.org/MPL/2.0/.\n"
"\n"
"// as calcErrorsForUpstream, but with local cache\n"
"// convolve weights with errors to produce errorsForUpstream\n"
"// workgroupid: [n][inputPlane]\n"
"// localid: [upstreamrow][upstreamcol]\n"
"// per-thread aggregation: [outPlane][filterRow][filterCol]\n"
"// need to store locally:\n"
"// - _errorBoard. size = outputBoardSizeSquared\n"
"// - _filterBoard. size = filtersizesquared\n"
"// note: currently doesnt use bias as input. thats probably an error?\n"
"// inputs: errors :convolve: filters => errorsForUpstream\n"
"//\n"
"// per workgroup:\n"
"// errors: [outPlane][outRow][outCol] 32 * 19 * 19 * 4 = 46KB\n"
"// weights: [filterId][filterRow][filterCol] 32 * 5 * 5 * 4 = 3.2KB\n"
"void kernel calcErrorsForUpstreamCached(\n"
" const int batchSize,\n"
" global const float *errorsGlobal,\n"
" global const float *filtersGlobal,\n"
" global float *errorsForUpstream,\n"
" local float *_errorBoard,\n"
" local float *_filterBoard ) {\n"
"\n"
" const int globalId = get_global_id(0);\n"
" const int localId = get_local_id(0);\n"
" const int workgroupId = get_group_id(0);\n"
" const int workgroupSize = get_local_size(0);\n"
"\n"
" const int n = workgroupId / gInputPlanes;\n"
" const int upstreamPlane = workgroupId % gInputPlanes;\n"
"\n"
" const int upstreamRow = localId / gInputBoardSize;\n"
" const int upstreamCol = localId % gInputBoardSize;\n"
"\n"
" const int minFilterRow = max( 0, upstreamRow + gMargin - (gOutputBoardSize - 1) );\n"
" const int maxFilterRow = min( gFilterSize - 1, upstreamRow + gMargin );\n"
" const int minFilterCol = max( 0, upstreamCol + gMargin - (gOutputBoardSize -1) );\n"
" const int maxFilterCol = min( gFilterSize - 1, upstreamCol + gMargin );\n"
"\n"
" const int filterPixelCopiesPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
" const int errorPixelCopiesPerThread = ( gOutputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
" const int pixelCopiesPerThread = max( filterPixelCopiesPerThread, errorPixelCopiesPerThread );\n"
"\n"
" float sumWeightTimesOutError = 0;\n"
" for( int outPlane = 0; outPlane < gNumFilters; outPlane++ ) {\n"
" const int filterBoardGlobalOffset =( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;\n"
" const int errorBoardGlobalOffset = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared;\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
" for( int i = 0; i < pixelCopiesPerThread; i++ ) {\n"
" int thisOffset = workgroupSize * i + localId;\n"
" if( thisOffset < gFilterSizeSquared ) {\n"
" _filterBoard[ thisOffset ] = filtersGlobal[ filterBoardGlobalOffset + thisOffset ];\n"
" }\n"
" if( thisOffset < gOutputBoardSizeSquared ) {\n"
" _errorBoard[ thisOffset ] = errorsGlobal[ errorBoardGlobalOffset + thisOffset ];\n"
" }\n"
" }\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
"// if( globalId == 0 ) {\n"
"// for( int i = 0; i < gFilterSizeSquared; i++ ) {\n"
"// errorsForUpstream[ (outPlane+1)*100 + i ] = _filterBoard[i];\n"
"// }\n"
"// }\n"
" for( int filterRow = minFilterRow; filterRow <= maxFilterRow; filterRow++ ) {\n"
" int outRow = upstreamRow + gMargin - filterRow;\n"
" for( int filterCol = minFilterCol; filterCol <= maxFilterCol; filterCol++ ) {\n"
" int outCol = upstreamCol + gMargin - filterCol;\n"
" int resultIndex = outRow * gOutputBoardSize + outCol;\n"
" float thisError = _errorBoard[resultIndex];\n"
" int thisWeightIndex = filterRow * gFilterSize + filterCol;\n"
" float thisWeight = _filterBoard[thisWeightIndex];\n"
" float thisWeightTimesError = thisWeight * thisError;\n"
" sumWeightTimesOutError += thisWeightTimesError;\n"
" }\n"
" }\n"
" }\n"
" const int upstreamBoardGlobalOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;\n"
" if( localId < gInputBoardSizeSquared ) {\n"
" errorsForUpstream[upstreamBoardGlobalOffset + localId] = sumWeightTimesOutError;\n"
" }\n"
"}\n"
"\n"
"";
kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstreamCached", options, "cl/backproperrorsv2cached.cl" );
// generated using cog:
const char * applyActivationDerivSource =
"// Copyright Hugh Perkins 201, 2015 hughperkins at gmail\n"
"//\n"
"// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
"// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
"// obtain one at http://mozilla.org/MPL/2.0/.\n"
"\n"
"// expected defines:\n"
"// one of: [ TANH | RELU | LINEAR | SIGMOID | SCALEDTANH ]\n"
"\n"
"#ifdef TANH\n"
" #define ACTIVATION_DERIV(output) (1 - output * output)\n"
"#elif defined SCALEDTANH\n"
" #define ACTIVATION_DERIV(output) ( 0.66667f * ( 1.7159f - 1 / 1.7159f * output * output ) )\n"
"#elif defined SIGMOID\n"
" #define ACTIVATION_DERIV(output) (output * ( 1 - output ) )\n"
"#elif defined RELU\n"
" #define ACTIVATION_DERIV(output) (output > 0 ? 1 : 0)\n"
"#elif defined LINEAR\n"
" #define ACTIVATION_DERIV(output) (1.0f)\n"
"#endif\n"
"\n"
"//#ifdef ACTIVATION_DERIV\n"
"//void kernel applyActivationDeriv(\n"
"// const int N,\n"
"// global float *inout ) {\n"
"// int globalId = get_global_id(0);\n"
"// inout[globalId] = ACTIVATION_DERIV( inout[globalId] );\n"
"//}\n"
"//#endif\n"
"\n"
"#ifdef ACTIVATION_DERIV\n"
"void kernel applyActivationDeriv(\n"
" const int N,\n"
" global float *target, global const float *source ) {\n"
" int globalId = get_global_id(0);\n"
" target[globalId] *= ACTIVATION_DERIV( source[globalId] );\n"
" // target[globalId] *= source[globalId];\n"
"}\n"
"#endif\n"
"\n"
"";
applyActivationDeriv = cl->buildKernelFromString( applyActivationDerivSource, "applyActivationDeriv", options, "cl/applyActivationDeriv.cl" );
// [[[end]]]
// kernel = cl->buildKernel( "backproperrorsv2.cl", "calcErrorsForUpstream", options );
// kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstream", options );
}
<commit_msg>add debugging<commit_after>#include "StatefulTimer.h"
#include "BackpropErrorsv2Cached.h"
using namespace std;
#undef STATIC
#define STATIC
#undef VIRTUAL
#define VIRTUAL
VIRTUAL BackpropErrorsv2Cached::~BackpropErrorsv2Cached() {
delete kernel;
delete applyActivationDeriv;
}
VIRTUAL void BackpropErrorsv2Cached::backpropErrors( int batchSize,
CLWrapper *inputDataWrapper, CLWrapper *errorsWrapper, CLWrapper *weightsWrapper,
CLWrapper *errorsForUpstreamWrapper ) {
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached start" );
// const int batchSize,
// global const float *errorsGlobal,
// global const float *filtersGlobal,
// global float *errorsForUpstream,
// local float *_errorBoard,
// local float *_filterBoard ) {
kernel
->in( batchSize )
->in( errorsWrapper )
->in( weightsWrapper )
->out( errorsForUpstreamWrapper )
->localFloats( square( dim.outputBoardSize ) )
->localFloats( square( dim.filterSize ) );
int numWorkgroups = batchSize * dim.inputPlanes;
int workgroupSize = square( dim.inputBoardSize );
workgroupSize = std::max( 32, workgroupSize ); // no point in wasting cores...
int globalSize = numWorkgroups * workgroupSize;
// int globalSize = batchSize * dim.inputCubeSize;
// int workgroupsize = cl->getMaxWorkgroupSize();
// globalSize = ( ( globalSize + workgroupsize - 1 ) / workgroupsize ) * workgroupsize;
// kernel->run_1d(globalSize, workgroupsize);
kernel->run_1d(globalSize, workgroupSize);
cl->finish();
errorsForUpstreamWrapper->copyToHost();
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after first kernel" );
for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) {
cout << "efu[" << i << "]=" << errorsForUpstream[i] << endl;
}
// applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper );
// applyActivationDeriv->run_1d(globalSize, workgroupSize);
applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper );
applyActivationDeriv->run_1d(globalSize, workgroupSize);
cl->finish();
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after applyActivationDeriv" );
errorsForUpstreamWrapper->copyToHost();
for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) {
cout << "efu2[" << i << "]=" << errorsForUpstream[i] << endl;
}
StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached end" );
}
BackpropErrorsv2Cached::BackpropErrorsv2Cached( OpenCLHelper *cl, LayerDimensions dim, ActivationFunction const *upstreamFn ) :
BackpropErrorsv2( cl, dim, upstreamFn )
{
std::string options = dim.buildOptionsString();
options += " -D " + upstreamFn->getDefineName();
// [[[cog
// import stringify
// stringify.write_kernel2( "kernel", "cl/backproperrorsv2cached.cl", "calcErrorsForUpstreamCached", 'options' )
// # stringify.write_kernel2( "broadcastMultiply", "cl/backproperrorsv2.cl", "broadcast_multiply", 'options' )
// stringify.write_kernel2( "applyActivationDeriv", "cl/applyActivationDeriv.cl", "applyActivationDeriv", 'options' )
// # stringify.write_kernel( "kernelSource", "ClConvolve.cl")
// ]]]
// generated using cog:
const char * kernelSource =
"// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n"
"//\n"
"// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
"// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
"// obtain one at http://mozilla.org/MPL/2.0/.\n"
"\n"
"// as calcErrorsForUpstream, but with local cache\n"
"// convolve weights with errors to produce errorsForUpstream\n"
"// workgroupid: [n][inputPlane]\n"
"// localid: [upstreamrow][upstreamcol]\n"
"// per-thread aggregation: [outPlane][filterRow][filterCol]\n"
"// need to store locally:\n"
"// - _errorBoard. size = outputBoardSizeSquared\n"
"// - _filterBoard. size = filtersizesquared\n"
"// note: currently doesnt use bias as input. thats probably an error?\n"
"// inputs: errors :convolve: filters => errorsForUpstream\n"
"//\n"
"// global:\n"
"// errors: [n][outPlane][outRow][outCol] 128 * 32 * 19 * 19 * 4\n"
"// weights: [filterId][upstreamplane][filterRow][filterCol] 32 * 32 * 5 * 5 * 4\n"
"// per workgroup:\n"
"// errors: [outPlane][outRow][outCol] 32 * 19 * 19 * 4 = 46KB\n"
"// weights: [filterId][filterRow][filterCol] 32 * 5 * 5 * 4 = 3.2KB\n"
"// errorsforupstream: [n][upstreamPlane][upstreamRow][upstreamCol]\n"
"void kernel calcErrorsForUpstreamCached(\n"
" const int batchSize,\n"
" global const float *errorsGlobal,\n"
" global const float *filtersGlobal,\n"
" global float *errorsForUpstream,\n"
" local float *_errorBoard,\n"
" local float *_filterBoard ) {\n"
"\n"
" const int globalId = get_global_id(0);\n"
" const int localId = get_local_id(0);\n"
" const int workgroupId = get_group_id(0);\n"
" const int workgroupSize = get_local_size(0);\n"
"\n"
" const int n = workgroupId / gInputPlanes;\n"
" const int upstreamPlane = workgroupId % gInputPlanes;\n"
"\n"
" const int upstreamRow = localId / gInputBoardSize;\n"
" const int upstreamCol = localId % gInputBoardSize;\n"
"\n"
" const int minFilterRow = max( 0, upstreamRow + gMargin - (gOutputBoardSize - 1) );\n"
" const int maxFilterRow = min( gFilterSize - 1, upstreamRow + gMargin );\n"
" const int minFilterCol = max( 0, upstreamCol + gMargin - (gOutputBoardSize -1) );\n"
" const int maxFilterCol = min( gFilterSize - 1, upstreamCol + gMargin );\n"
"\n"
" const int filterPixelCopiesPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
" const int errorPixelCopiesPerThread = ( gOutputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;\n"
" const int pixelCopiesPerThread = max( filterPixelCopiesPerThread, errorPixelCopiesPerThread );\n"
"\n"
" float sumWeightTimesOutError = 0;\n"
" for( int outPlane = 0; outPlane < gNumFilters; outPlane++ ) {\n"
" const int filterBoardGlobalOffset =( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;\n"
" const int errorBoardGlobalOffset = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared;\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
" for( int i = 0; i < pixelCopiesPerThread; i++ ) {\n"
" int thisOffset = workgroupSize * i + localId;\n"
" if( thisOffset < gFilterSizeSquared ) {\n"
" _filterBoard[ thisOffset ] = filtersGlobal[ filterBoardGlobalOffset + thisOffset ];\n"
" }\n"
" if( thisOffset < gOutputBoardSizeSquared ) {\n"
" _errorBoard[ thisOffset ] = errorsGlobal[ errorBoardGlobalOffset + thisOffset ];\n"
" }\n"
" }\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
"// if( globalId == 0 ) {\n"
"// for( int i = 0; i < gFilterSizeSquared; i++ ) {\n"
"// errorsForUpstream[ (outPlane+1)*100 + i ] = _filterBoard[i];\n"
"// }\n"
"// }\n"
" for( int filterRow = minFilterRow; filterRow <= maxFilterRow; filterRow++ ) {\n"
" int outRow = upstreamRow + gMargin - filterRow;\n"
" for( int filterCol = minFilterCol; filterCol <= maxFilterCol; filterCol++ ) {\n"
" int outCol = upstreamCol + gMargin - filterCol;\n"
" int resultIndex = outRow * gOutputBoardSize + outCol;\n"
" float thisError = _errorBoard[resultIndex];\n"
" int thisWeightIndex = filterRow * gFilterSize + filterCol;\n"
" float thisWeight = _filterBoard[thisWeightIndex];\n"
" float thisWeightTimesError = thisWeight * thisError;\n"
" sumWeightTimesOutError += thisWeightTimesError;\n"
" }\n"
" }\n"
" }\n"
" const int upstreamBoardGlobalOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;\n"
" if( localId < gInputBoardSizeSquared ) {\n"
" errorsForUpstream[upstreamBoardGlobalOffset + localId] = sumWeightTimesOutError;\n"
" }\n"
"}\n"
"\n"
"";
kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstreamCached", options, "cl/backproperrorsv2cached.cl" );
// generated using cog:
const char * applyActivationDerivSource =
"// Copyright Hugh Perkins 201, 2015 hughperkins at gmail\n"
"//\n"
"// This Source Code Form is subject to the terms of the Mozilla Public License,\n"
"// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n"
"// obtain one at http://mozilla.org/MPL/2.0/.\n"
"\n"
"// expected defines:\n"
"// one of: [ TANH | RELU | LINEAR | SIGMOID | SCALEDTANH ]\n"
"\n"
"#ifdef TANH\n"
" #define ACTIVATION_DERIV(output) (1 - output * output)\n"
"#elif defined SCALEDTANH\n"
" #define ACTIVATION_DERIV(output) ( 0.66667f * ( 1.7159f - 1 / 1.7159f * output * output ) )\n"
"#elif defined SIGMOID\n"
" #define ACTIVATION_DERIV(output) (output * ( 1 - output ) )\n"
"#elif defined RELU\n"
" #define ACTIVATION_DERIV(output) (output > 0 ? 1 : 0)\n"
"#elif defined LINEAR\n"
" #define ACTIVATION_DERIV(output) (1.0f)\n"
"#endif\n"
"\n"
"//#ifdef ACTIVATION_DERIV\n"
"//void kernel applyActivationDeriv(\n"
"// const int N,\n"
"// global float *inout ) {\n"
"// int globalId = get_global_id(0);\n"
"// inout[globalId] = ACTIVATION_DERIV( inout[globalId] );\n"
"//}\n"
"//#endif\n"
"\n"
"#ifdef ACTIVATION_DERIV\n"
"void kernel applyActivationDeriv(\n"
" const int N,\n"
" global float *target, global const float *source ) {\n"
" int globalId = get_global_id(0);\n"
" target[globalId] *= ACTIVATION_DERIV( source[globalId] );\n"
" // target[globalId] *= source[globalId];\n"
"}\n"
"#endif\n"
"\n"
"";
applyActivationDeriv = cl->buildKernelFromString( applyActivationDerivSource, "applyActivationDeriv", options, "cl/applyActivationDeriv.cl" );
// [[[end]]]
// kernel = cl->buildKernel( "backproperrorsv2.cl", "calcErrorsForUpstream", options );
// kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstream", options );
}
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file TransferFunction2D.cpp
\author Jens Krueger
SCI Institute
University of Utah
\version 1.0
\date September 2008
*/
#include "TransferFunction2D.h"
#include <memory.h>
using namespace std;
TransferFunction2D::TransferFunction2D() :
m_iSize(0,0),
m_pColorData(NULL),
m_pCanvas(NULL),
m_pPainter(NULL),
m_vValueBBox(0,0),
m_bUseCachedData(false)
{
Resize(m_iSize);
}
TransferFunction2D::TransferFunction2D(const std::string& filename):
m_iSize(0,0),
m_pColorData(NULL),
m_pCanvas(NULL),
m_pPainter(NULL)
{
Load(filename);
}
TransferFunction2D::TransferFunction2D(const VECTOR2<size_t>& iSize):
m_iSize(iSize),
m_pColorData(NULL),
m_pCanvas(NULL),
m_pPainter(NULL)
{
Resize(m_iSize);
}
void TransferFunction2D::DeleteCanvasData()
{
delete m_pPainter;
delete m_pColorData;
delete m_pCanvas;
}
TransferFunction2D::~TransferFunction2D(void)
{
DeleteCanvasData();
}
void TransferFunction2D::Resize(const VECTOR2<size_t>& iSize) {
m_iSize = iSize;
m_Trans1D.Resize(iSize.x);
m_Trans1D.Clear();
DeleteCanvasData();
}
bool TransferFunction2D::Load(const std::string& filename) {
ifstream file(filename.c_str());
if (!file.is_open()) return false;
// load size
file >> m_iSize.x >> m_iSize.y;
// load 1D Trans
m_Trans1D.Load(file, m_iSize.x);
// load swatch count
UINT32 iSwatchCount;
file >> iSwatchCount;
m_Swatches.resize(iSwatchCount);
// load Swatches
for (size_t i = 0;i<m_Swatches.size();i++) m_Swatches[i].Load(file);
file.close();
return true;
}
bool TransferFunction2D::Save(const std::string& filename) {
ofstream file(filename.c_str());
if (!file.is_open()) return false;
// save size
file << m_iSize.x << " " << m_iSize.y << endl;
// save 1D Trans
m_Trans1D.Save(file);
// save swatch count
file << m_Swatches.size() << endl;
// save Swatches
for (size_t i = 0;i<m_Swatches.size();i++) m_Swatches[i].Save(file);
file.close();
return true;
}
void TransferFunction2D::GetByteArray(unsigned char** pcData) {
if (*pcData == NULL) *pcData = new unsigned char[m_iSize.area()*4];
size_t iSize = m_iSize.area();
unsigned char *pcSourceDataIterator = RenderTransferFunction8Bit();
unsigned char *pcDataIterator = *pcData;
memcpy(pcDataIterator, pcSourceDataIterator, iSize*4);
for (size_t i = 0;i<iSize;i++) {
unsigned char r = *(pcDataIterator+2);
unsigned char b = *(pcDataIterator+0);
*(pcDataIterator+0) = r;
*(pcDataIterator+2) = b;
pcDataIterator+=4;
}
}
void TransferFunction2D::GetByteArray(unsigned char** pcData, unsigned char cUsedRange) {
if (*pcData == NULL) *pcData = new unsigned char[m_iSize.area()*4];
float fScale = 255.0f/float(cUsedRange);
size_t iSize = m_iSize.area();
unsigned char *pcSourceDataIterator = RenderTransferFunction8Bit();
unsigned char *pcDataIterator = *pcData;
memcpy(pcDataIterator, pcSourceDataIterator, iSize*4);
for (size_t i = 0;i<iSize;i++) {
unsigned char r = *(pcDataIterator+2);
unsigned char g = *(pcDataIterator+1);
unsigned char b = *(pcDataIterator+0);
unsigned char a = *(pcDataIterator+3);
*(pcDataIterator+0) = (unsigned char)(float(r)*fScale);
*(pcDataIterator+1) = (unsigned char)(float(g)*fScale);
*(pcDataIterator+2) = (unsigned char)(float(b)*fScale);
*(pcDataIterator+3) = (unsigned char)(float(a)*fScale);
pcDataIterator+=4;
}
}
void TransferFunction2D::GetShortArray(unsigned short** psData, unsigned short sUsedRange) {
if (*psData == NULL) *psData = new unsigned short[m_iSize.area()*4];
RenderTransferFunction();
unsigned short *psDataIterator = *psData;
FLOATVECTOR4 *piSourceIterator = m_pColorData->GetDataPointer();
for (size_t i = 0;i<m_pColorData->GetSize().area();i++) {
*psDataIterator++ = (unsigned short)((*piSourceIterator)[0]*sUsedRange);
*psDataIterator++ = (unsigned short)((*piSourceIterator)[1]*sUsedRange);
*psDataIterator++ = (unsigned short)((*piSourceIterator)[2]*sUsedRange);
*psDataIterator++ = (unsigned short)((*piSourceIterator)[3]*sUsedRange);
piSourceIterator++;
}
}
void TransferFunction2D::GetFloatArray(float** pfData) {
if (*pfData == NULL) *pfData = new float[4*m_iSize.area()];
RenderTransferFunction();
memcpy(*pfData, m_pColorData->GetDataPointer(), 4*sizeof(float)*m_iSize.area());
}
int m_iSwatchBorderSize = 0;
int m_iBorderSize = 0;
INTVECTOR2 TransferFunction2D::Rel2Abs(FLOATVECTOR2 vfCoord) {
return INTVECTOR2(int(m_iSwatchBorderSize/2+ m_iBorderSize/2+vfCoord.x* (m_iSize.x-m_iBorderSize-m_iSwatchBorderSize)),
int(m_iSwatchBorderSize/2+m_iBorderSize/2+vfCoord.y*(m_iSize.y-m_iBorderSize-m_iSwatchBorderSize)));
}
unsigned char* TransferFunction2D::RenderTransferFunction8Bit() {
if (m_pColorData == NULL ) m_pColorData = new ColorData2D(m_iSize);
if (m_pCanvas == NULL ) m_pCanvas = new QImage(int(m_iSize.x), int(m_iSize.y), QImage::Format_ARGB32);
if (m_pPainter == NULL) m_pPainter = new QPainter(m_pCanvas);
if (m_bUseCachedData) return m_pCanvas->bits();
m_pCanvas->fill(0);
// render 1D trans
QRect imageRect(0, 0, int(m_iSize.x), int(m_iSize.y));
m_pPainter->drawImage(imageRect,m_Trans1DImage);
// render swatches
QPen noBorderPen(Qt::NoPen);
m_pPainter->setPen(noBorderPen);
for (size_t i = 0;i<m_Swatches.size();i++) {
TFPolygon& currentSwatch = m_Swatches[i];
std::vector<QPoint> pointList(currentSwatch.pPoints.size());
for (size_t j = 0;j<currentSwatch.pPoints.size();j++) {
INTVECTOR2 vPixelPos = Rel2Abs(currentSwatch.pPoints[j]);
pointList[j] = QPoint(vPixelPos.x, vPixelPos.y);
}
INTVECTOR2 vPixelPos0 = Rel2Abs(currentSwatch.pGradientCoords[0])-m_iSwatchBorderSize, vPixelPos1 = Rel2Abs(currentSwatch.pGradientCoords[1])-m_iSwatchBorderSize;
QLinearGradient linearBrush(vPixelPos0.x, vPixelPos0.y, vPixelPos1.x, vPixelPos1.y);
for (size_t j = 0;j<currentSwatch.pGradientStops.size();j++) {
linearBrush.setColorAt(currentSwatch.pGradientStops[j].first,
QColor(int(currentSwatch.pGradientStops[j].second[0]*255),
int(currentSwatch.pGradientStops[j].second[1]*255),
int(currentSwatch.pGradientStops[j].second[2]*255),
int(currentSwatch.pGradientStops[j].second[3]*255)));
}
m_pPainter->setBrush(linearBrush);
m_pPainter->drawPolygon(&pointList[0], int(currentSwatch.pPoints.size()));
}
m_bUseCachedData = true;
return m_pCanvas->bits();
}
ColorData2D* TransferFunction2D::RenderTransferFunction() {
unsigned char* pPixelData = RenderTransferFunction8Bit();
FLOATVECTOR4* p = (FLOATVECTOR4*)(m_pColorData->GetDataPointer());
for (size_t i = 0;i<m_pColorData->GetSize().area();i++) {
p[i] = FLOATVECTOR4(pPixelData[4*i+2]/255.0f,
pPixelData[4*i+1]/255.0f,
pPixelData[4*i+0]/255.0f,
pPixelData[4*i+3]/255.0f);
}
return m_pColorData;
}
void TransferFunction2D::ComputeNonZeroLimits() {
unsigned char* pPixelData = RenderTransferFunction8Bit();
m_vValueBBox = UINT64VECTOR4(UINT64(m_iSize.x),0,
UINT64(m_iSize.y),0);
size_t i = 3;
for (size_t y = 0;y<m_iSize.y;y++) {
for (size_t x = 0;x<m_iSize.x;x++) {
if (pPixelData[i] != 0) {
m_vValueBBox.x = MIN(m_vValueBBox.x, x);
m_vValueBBox.y = MAX(m_vValueBBox.y, x);
m_vValueBBox.z = MIN(m_vValueBBox.z, y);
m_vValueBBox.w = MAX(m_vValueBBox.w, y);
}
i+=4;
}
}
}
void TransferFunction2D::Update1DTrans(const TransferFunction1D* p1DTrans) {
m_Trans1D = TransferFunction1D(*p1DTrans);
size_t iSize = min<size_t>(m_iSize.x, m_Trans1D.GetSize());
m_Trans1DImage = QImage(int(iSize), 1, QImage::Format_ARGB32);
for (size_t i = 0;i<iSize;i++) {
m_Trans1DImage.setPixel(int(i),0,qRgba(int(m_Trans1D.vColorData[i][0]*255),
int(m_Trans1D.vColorData[i][1]*255),
int(m_Trans1D.vColorData[i][2]*255),
int(m_Trans1D.vColorData[i][3]*255)));
}
}
// ************************************************************************************************************
void TFPolygon::Load(ifstream& file) {
UINT32 iSize;
file >> iSize;
pPoints.resize(iSize);
for(size_t i=0;i<pPoints.size();++i){
for(size_t j=0;j<2;++j){
file >> pPoints[i][j];
}
}
file >> pGradientCoords[0][0] >> pGradientCoords[0][1];
file >> pGradientCoords[1][0] >> pGradientCoords[1][1];
file >> iSize;
pGradientStops.resize(iSize);
for(size_t i=0;i<pGradientStops.size();++i){
file >> pGradientStops[i].first;
for(size_t j=0;j<4;++j){
file >> pGradientStops[i].second[j];
}
}
}
void TFPolygon::Save(ofstream& file) {
file << UINT32(pPoints.size()) << endl;
for(size_t i=0;i<pPoints.size();++i){
for(size_t j=0;j<2;++j){
file << pPoints[i][j] << " ";
}
file << endl;
}
file << pGradientCoords[0][0] << " " << pGradientCoords[0][1] << " ";
file << pGradientCoords[1][0] << " " << pGradientCoords[1][1];
file << endl;
file << pGradientStops.size() << endl;
for(size_t i=0;i<pGradientStops.size();++i){
file << pGradientStops[i].first << " ";
for(size_t j=0;j<4;++j){
file << pGradientStops[i].second[j] << " ";
}
file << endl;
}
}
<commit_msg>Potential uninitialized var: default to not use cached data.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file TransferFunction2D.cpp
\author Jens Krueger
SCI Institute
University of Utah
\version 1.0
\date September 2008
*/
#include "TransferFunction2D.h"
#include <memory.h>
using namespace std;
TransferFunction2D::TransferFunction2D() :
m_iSize(0,0),
m_pColorData(NULL),
m_pCanvas(NULL),
m_pPainter(NULL),
m_vValueBBox(0,0),
m_bUseCachedData(false)
{
Resize(m_iSize);
}
TransferFunction2D::TransferFunction2D(const std::string& filename):
m_iSize(0,0),
m_pColorData(NULL),
m_pCanvas(NULL),
m_pPainter(NULL),
m_bUseCachedData(false)
{
Load(filename);
}
TransferFunction2D::TransferFunction2D(const VECTOR2<size_t>& iSize):
m_iSize(iSize),
m_pColorData(NULL),
m_pCanvas(NULL),
m_pPainter(NULL),
m_bUseCachedData(false)
{
Resize(m_iSize);
}
void TransferFunction2D::DeleteCanvasData()
{
delete m_pPainter;
delete m_pColorData;
delete m_pCanvas;
}
TransferFunction2D::~TransferFunction2D(void)
{
DeleteCanvasData();
}
void TransferFunction2D::Resize(const VECTOR2<size_t>& iSize) {
m_iSize = iSize;
m_Trans1D.Resize(iSize.x);
m_Trans1D.Clear();
DeleteCanvasData();
}
bool TransferFunction2D::Load(const std::string& filename) {
ifstream file(filename.c_str());
if (!file.is_open()) return false;
// load size
file >> m_iSize.x >> m_iSize.y;
// load 1D Trans
m_Trans1D.Load(file, m_iSize.x);
// load swatch count
UINT32 iSwatchCount;
file >> iSwatchCount;
m_Swatches.resize(iSwatchCount);
// load Swatches
for (size_t i = 0;i<m_Swatches.size();i++) m_Swatches[i].Load(file);
file.close();
return true;
}
bool TransferFunction2D::Save(const std::string& filename) {
ofstream file(filename.c_str());
if (!file.is_open()) return false;
// save size
file << m_iSize.x << " " << m_iSize.y << endl;
// save 1D Trans
m_Trans1D.Save(file);
// save swatch count
file << m_Swatches.size() << endl;
// save Swatches
for (size_t i = 0;i<m_Swatches.size();i++) m_Swatches[i].Save(file);
file.close();
return true;
}
void TransferFunction2D::GetByteArray(unsigned char** pcData) {
if (*pcData == NULL) *pcData = new unsigned char[m_iSize.area()*4];
size_t iSize = m_iSize.area();
unsigned char *pcSourceDataIterator = RenderTransferFunction8Bit();
unsigned char *pcDataIterator = *pcData;
memcpy(pcDataIterator, pcSourceDataIterator, iSize*4);
for (size_t i = 0;i<iSize;i++) {
unsigned char r = *(pcDataIterator+2);
unsigned char b = *(pcDataIterator+0);
*(pcDataIterator+0) = r;
*(pcDataIterator+2) = b;
pcDataIterator+=4;
}
}
void TransferFunction2D::GetByteArray(unsigned char** pcData, unsigned char cUsedRange) {
if (*pcData == NULL) *pcData = new unsigned char[m_iSize.area()*4];
float fScale = 255.0f/float(cUsedRange);
size_t iSize = m_iSize.area();
unsigned char *pcSourceDataIterator = RenderTransferFunction8Bit();
unsigned char *pcDataIterator = *pcData;
memcpy(pcDataIterator, pcSourceDataIterator, iSize*4);
for (size_t i = 0;i<iSize;i++) {
unsigned char r = *(pcDataIterator+2);
unsigned char g = *(pcDataIterator+1);
unsigned char b = *(pcDataIterator+0);
unsigned char a = *(pcDataIterator+3);
*(pcDataIterator+0) = (unsigned char)(float(r)*fScale);
*(pcDataIterator+1) = (unsigned char)(float(g)*fScale);
*(pcDataIterator+2) = (unsigned char)(float(b)*fScale);
*(pcDataIterator+3) = (unsigned char)(float(a)*fScale);
pcDataIterator+=4;
}
}
void TransferFunction2D::GetShortArray(unsigned short** psData, unsigned short sUsedRange) {
if (*psData == NULL) *psData = new unsigned short[m_iSize.area()*4];
RenderTransferFunction();
unsigned short *psDataIterator = *psData;
FLOATVECTOR4 *piSourceIterator = m_pColorData->GetDataPointer();
for (size_t i = 0;i<m_pColorData->GetSize().area();i++) {
*psDataIterator++ = (unsigned short)((*piSourceIterator)[0]*sUsedRange);
*psDataIterator++ = (unsigned short)((*piSourceIterator)[1]*sUsedRange);
*psDataIterator++ = (unsigned short)((*piSourceIterator)[2]*sUsedRange);
*psDataIterator++ = (unsigned short)((*piSourceIterator)[3]*sUsedRange);
piSourceIterator++;
}
}
void TransferFunction2D::GetFloatArray(float** pfData) {
if (*pfData == NULL) *pfData = new float[4*m_iSize.area()];
RenderTransferFunction();
memcpy(*pfData, m_pColorData->GetDataPointer(), 4*sizeof(float)*m_iSize.area());
}
int m_iSwatchBorderSize = 0;
int m_iBorderSize = 0;
INTVECTOR2 TransferFunction2D::Rel2Abs(FLOATVECTOR2 vfCoord) {
return INTVECTOR2(int(m_iSwatchBorderSize/2+ m_iBorderSize/2+vfCoord.x* (m_iSize.x-m_iBorderSize-m_iSwatchBorderSize)),
int(m_iSwatchBorderSize/2+m_iBorderSize/2+vfCoord.y*(m_iSize.y-m_iBorderSize-m_iSwatchBorderSize)));
}
unsigned char* TransferFunction2D::RenderTransferFunction8Bit() {
if (m_pColorData == NULL ) m_pColorData = new ColorData2D(m_iSize);
if (m_pCanvas == NULL ) m_pCanvas = new QImage(int(m_iSize.x), int(m_iSize.y), QImage::Format_ARGB32);
if (m_pPainter == NULL) m_pPainter = new QPainter(m_pCanvas);
if (m_bUseCachedData) return m_pCanvas->bits();
m_pCanvas->fill(0);
// render 1D trans
QRect imageRect(0, 0, int(m_iSize.x), int(m_iSize.y));
m_pPainter->drawImage(imageRect,m_Trans1DImage);
// render swatches
QPen noBorderPen(Qt::NoPen);
m_pPainter->setPen(noBorderPen);
for (size_t i = 0;i<m_Swatches.size();i++) {
TFPolygon& currentSwatch = m_Swatches[i];
std::vector<QPoint> pointList(currentSwatch.pPoints.size());
for (size_t j = 0;j<currentSwatch.pPoints.size();j++) {
INTVECTOR2 vPixelPos = Rel2Abs(currentSwatch.pPoints[j]);
pointList[j] = QPoint(vPixelPos.x, vPixelPos.y);
}
INTVECTOR2 vPixelPos0 = Rel2Abs(currentSwatch.pGradientCoords[0])-m_iSwatchBorderSize, vPixelPos1 = Rel2Abs(currentSwatch.pGradientCoords[1])-m_iSwatchBorderSize;
QLinearGradient linearBrush(vPixelPos0.x, vPixelPos0.y, vPixelPos1.x, vPixelPos1.y);
for (size_t j = 0;j<currentSwatch.pGradientStops.size();j++) {
linearBrush.setColorAt(currentSwatch.pGradientStops[j].first,
QColor(int(currentSwatch.pGradientStops[j].second[0]*255),
int(currentSwatch.pGradientStops[j].second[1]*255),
int(currentSwatch.pGradientStops[j].second[2]*255),
int(currentSwatch.pGradientStops[j].second[3]*255)));
}
m_pPainter->setBrush(linearBrush);
m_pPainter->drawPolygon(&pointList[0], int(currentSwatch.pPoints.size()));
}
m_bUseCachedData = true;
return m_pCanvas->bits();
}
ColorData2D* TransferFunction2D::RenderTransferFunction() {
unsigned char* pPixelData = RenderTransferFunction8Bit();
FLOATVECTOR4* p = (FLOATVECTOR4*)(m_pColorData->GetDataPointer());
for (size_t i = 0;i<m_pColorData->GetSize().area();i++) {
p[i] = FLOATVECTOR4(pPixelData[4*i+2]/255.0f,
pPixelData[4*i+1]/255.0f,
pPixelData[4*i+0]/255.0f,
pPixelData[4*i+3]/255.0f);
}
return m_pColorData;
}
void TransferFunction2D::ComputeNonZeroLimits() {
unsigned char* pPixelData = RenderTransferFunction8Bit();
m_vValueBBox = UINT64VECTOR4(UINT64(m_iSize.x),0,
UINT64(m_iSize.y),0);
size_t i = 3;
for (size_t y = 0;y<m_iSize.y;y++) {
for (size_t x = 0;x<m_iSize.x;x++) {
if (pPixelData[i] != 0) {
m_vValueBBox.x = MIN(m_vValueBBox.x, x);
m_vValueBBox.y = MAX(m_vValueBBox.y, x);
m_vValueBBox.z = MIN(m_vValueBBox.z, y);
m_vValueBBox.w = MAX(m_vValueBBox.w, y);
}
i+=4;
}
}
}
void TransferFunction2D::Update1DTrans(const TransferFunction1D* p1DTrans) {
m_Trans1D = TransferFunction1D(*p1DTrans);
size_t iSize = min<size_t>(m_iSize.x, m_Trans1D.GetSize());
m_Trans1DImage = QImage(int(iSize), 1, QImage::Format_ARGB32);
for (size_t i = 0;i<iSize;i++) {
m_Trans1DImage.setPixel(int(i),0,qRgba(int(m_Trans1D.vColorData[i][0]*255),
int(m_Trans1D.vColorData[i][1]*255),
int(m_Trans1D.vColorData[i][2]*255),
int(m_Trans1D.vColorData[i][3]*255)));
}
}
// ************************************************************************************************************
void TFPolygon::Load(ifstream& file) {
UINT32 iSize;
file >> iSize;
pPoints.resize(iSize);
for(size_t i=0;i<pPoints.size();++i){
for(size_t j=0;j<2;++j){
file >> pPoints[i][j];
}
}
file >> pGradientCoords[0][0] >> pGradientCoords[0][1];
file >> pGradientCoords[1][0] >> pGradientCoords[1][1];
file >> iSize;
pGradientStops.resize(iSize);
for(size_t i=0;i<pGradientStops.size();++i){
file >> pGradientStops[i].first;
for(size_t j=0;j<4;++j){
file >> pGradientStops[i].second[j];
}
}
}
void TFPolygon::Save(ofstream& file) {
file << UINT32(pPoints.size()) << endl;
for(size_t i=0;i<pPoints.size();++i){
for(size_t j=0;j<2;++j){
file << pPoints[i][j] << " ";
}
file << endl;
}
file << pGradientCoords[0][0] << " " << pGradientCoords[0][1] << " ";
file << pGradientCoords[1][0] << " " << pGradientCoords[1][1];
file << endl;
file << pGradientStops.size() << endl;
for(size_t i=0;i<pGradientStops.size();++i){
file << pGradientStops[i].first << " ";
for(size_t j=0;j<4;++j){
file << pGradientStops[i].second[j] << " ";
}
file << endl;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Replaced assert with more graceful handling, because key generation does not produce 100% unique id per HIR topology and in case of mis-mapping recompilation just falls back to static profile.<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include "zyre.h"
#include <string>
#include <exception>
#include <vector>
namespace Zyre
{
class ZyreError : public std::runtime_error
{
public:
ZyreError(const std::string& what) : std::runtime_error(what) {}
};
class ZyreEvent
{
public:
ZyreEvent(zyre_event_t* self) : m_self(self) {};
~ZyreEvent()
{
if (m_self)
zyre_event_destroy(&m_self);
}
ZyreEvent(const ZyreEvent& other) = delete;
ZyreEvent operator=(const ZyreEvent& other) = delete;
ZyreEvent(ZyreEvent&& other)
{
m_self = other.m_self;
other.m_self = nullptr;
}
ZyreEvent& operator=(ZyreEvent&& other)
{
if (&other != this)
{
m_self = other.m_self;
other.m_self = nullptr;
}
return *this;
}
void print() const
{
zyre_event_print(m_self);
}
zyre_event_type_t type() const
{
return zyre_event_type(m_self);
}
std::string sender() const
{
return zyre_event_sender(m_self);
}
std::string name() const
{
return zyre_event_name(m_self);
}
std::string address() const
{
return zyre_event_address(m_self);
}
std::string headerValue(const std::string& key) const
{
return zyre_event_header(m_self, key.c_str());
}
std::string group() const
{
return zyre_event_group(m_self);
}
zmsg_t* message() const
{
return zyre_event_msg(m_self);
}
private:
zyre_event_t* m_self;
};
class Zyre
{
public:
Zyre(const std::string& name = "")
{
if (name != "")
m_self = zyre_new(NULL);
else
m_self = zyre_new(name.c_str());
}
~Zyre()
{
if (m_self)
zyre_destroy(&m_self);
}
Zyre(const Zyre& other) = delete;
Zyre operator=(const Zyre& other) = delete;
Zyre(Zyre&& other)
{
m_self = other.m_self;
other.m_self = nullptr;
}
Zyre& operator=(Zyre&& other)
{
if (&other != this)
{
m_self = other.m_self;
other.m_self = nullptr;
}
return *this;
}
void print() const
{
zyre_print(m_self);
}
std::string uuid() const
{
return zyre_uuid(m_self);
}
std::string name() const
{
return zyre_name(m_self);
}
void setHeader(const std::string key, const std::string& value) const
{
zyre_set_header(m_self, key.c_str(), value.c_str());
}
void setVerbose() const
{
zyre_set_verbose(m_self);
}
void setPort(int value) const
{
zyre_set_port(m_self, value);
}
void setInterval(size_t value) const
{
zyre_set_interval(m_self, value);
}
void setInterface(const std::string& value) const
{
zyre_set_interface(m_self, value.c_str());
}
void start() const
{
int rc = zyre_start(m_self);
if (rc == -1)
throw ZyreError("Failed to start Zyre node");
}
void stop() const
{
zyre_stop(m_self);
}
void join(const std::string& group) const
{
zyre_join(m_self, group.c_str());
}
void leave(const std::string& group) const
{
zyre_leave(m_self, group.c_str());
}
void whisper(const std::string& peer, zmsg_t* msg) const
{
zyre_whisper(m_self, peer.c_str(), &msg);
}
void shout(const std::string& group, zmsg_t* msg) const
{
zyre_shout(m_self, group.c_str(), &msg);
}
zmsg_t* recv() const
{
return zyre_recv(m_self);
}
ZyreEvent event() const
{
return ZyreEvent(zyre_event_new(m_self));
}
std::vector<std::string> peers() const
{
zlist_t* peers = zyre_peers(m_self);
std::vector<std::string> ret = toVector(peers);
zlist_destroy(&peers);
return ret;
}
std::vector<std::string> ownGroups() const
{
zlist_t* ownGroups = zyre_own_groups(m_self);
std::vector<std::string> ret = toVector(ownGroups);
zlist_destroy(&ownGroups);
return ret;
}
std::vector<std::string> peerGroups() const
{
zlist_t* peerGroups = zyre_peer_groups(m_self);
std::vector<std::string> ret = toVector(peerGroups);
zlist_destroy(&peerGroups);
return ret;
}
std::string peerAddress(const std::string& peer) const
{
char* val = zyre_peer_address(m_self, peer.c_str());
std::string ret(val);
if (val != NULL)
delete val;
return ret;
}
std::string peerHeaderValue(const std::string& peer, const std::string& name)
{
char* val = zyre_peer_header_value(m_self, peer.c_str(), peer.c_str());
std::string ret(val);
if (val != NULL)
delete val;
return ret;
}
zsock_t* socket() const
{
return zyre_socket(m_self);
}
static void version(int& major, int& minor, int& patch)
{
zyre_version(&major, &minor, &patch);
}
private:
std::vector<std::string> toVector(zlist_t* list) const
{
std::vector<std::string> ret;
void* cursor = zlist_first(list);
while (cursor != NULL)
{
ret.emplace_back(static_cast<char*>(cursor));
cursor = zlist_next(list);
}
return ret;
}
zyre_t* m_self;
};
}<commit_msg>Use zeromq code style<commit_after>#pragma once
#include "zyre.h"
#include <string>
#include <exception>
#include <vector>
namespace zyre
{
class error_t : public std::runtime_error
{
public:
error_t(const std::string& what) : std::runtime_error(what) {}
};
class event_t
{
public:
event_t(zyre_event_t* self) : m_self(self) {};
~event_t()
{
if (m_self)
zyre_event_destroy(&m_self);
}
event_t(const event_t& other) = delete;
event_t operator=(const event_t& other) = delete;
event_t(event_t&& other)
{
m_self = other.m_self;
other.m_self = nullptr;
}
event_t& operator=(event_t&& other)
{
if (&other != this)
{
m_self = other.m_self;
other.m_self = nullptr;
}
return *this;
}
void print() const
{
zyre_event_print(m_self);
}
zyre_event_type_t type() const
{
return zyre_event_type(m_self);
}
std::string sender() const
{
return zyre_event_sender(m_self);
}
std::string name() const
{
return zyre_event_name(m_self);
}
std::string address() const
{
return zyre_event_address(m_self);
}
std::string header_value(const std::string& key) const
{
return zyre_event_header(m_self, key.c_str());
}
std::string group() const
{
return zyre_event_group(m_self);
}
zmsg_t* message() const
{
return zyre_event_msg(m_self);
}
private:
zyre_event_t* m_self;
};
class node_t
{
public:
node_t(const std::string& name = "")
{
if (name != "")
m_self = zyre_new(NULL);
else
m_self = zyre_new(name.c_str());
}
~node_t()
{
if (m_self)
zyre_destroy(&m_self);
}
node_t(const node_t& other) = delete;
node_t operator=(const node_t& other) = delete;
node_t(node_t&& other)
{
m_self = other.m_self;
other.m_self = nullptr;
}
node_t& operator=(node_t&& other)
{
if (&other != this)
{
m_self = other.m_self;
other.m_self = nullptr;
}
return *this;
}
void print() const
{
zyre_print(m_self);
}
std::string uuid() const
{
return zyre_uuid(m_self);
}
std::string name() const
{
return zyre_name(m_self);
}
void set_header(const std::string key, const std::string& value) const
{
zyre_set_header(m_self, key.c_str(), value.c_str());
}
void set_verbose() const
{
zyre_set_verbose(m_self);
}
void set_port(int value) const
{
zyre_set_port(m_self, value);
}
void set_interval(size_t value) const
{
zyre_set_interval(m_self, value);
}
void set_interface(const std::string& value) const
{
zyre_set_interface(m_self, value.c_str());
}
void start() const
{
int rc = zyre_start(m_self);
if (rc == -1)
throw error_t("Failed to start Zyre node");
}
void stop() const
{
zyre_stop(m_self);
}
void join(const std::string& group) const
{
zyre_join(m_self, group.c_str());
}
void leave(const std::string& group) const
{
zyre_leave(m_self, group.c_str());
}
void whisper(const std::string& peer, zmsg_t* msg) const
{
zyre_whisper(m_self, peer.c_str(), &msg);
}
void shout(const std::string& group, zmsg_t* msg) const
{
zyre_shout(m_self, group.c_str(), &msg);
}
zmsg_t* recv() const
{
return zyre_recv(m_self);
}
event_t event() const
{
return event_t(zyre_event_new(m_self));
}
std::vector<std::string> peers() const
{
zlist_t* peers = zyre_peers(m_self);
std::vector<std::string> ret = to_vector(peers);
zlist_destroy(&peers);
return ret;
}
std::vector<std::string> own_groups() const
{
zlist_t* ownGroups = zyre_own_groups(m_self);
std::vector<std::string> ret = to_vector(ownGroups);
zlist_destroy(&ownGroups);
return ret;
}
std::vector<std::string> peer_groups() const
{
zlist_t* peerGroups = zyre_peer_groups(m_self);
std::vector<std::string> ret = to_vector(peerGroups);
zlist_destroy(&peerGroups);
return ret;
}
std::string peer_address(const std::string& peer) const
{
char* val = zyre_peer_address(m_self, peer.c_str());
std::string ret(val);
if (val != NULL)
delete val;
return ret;
}
std::string peer_header_value(const std::string& peer, const std::string& name)
{
char* val = zyre_peer_header_value(m_self, peer.c_str(), peer.c_str());
std::string ret(val);
if (val != NULL)
delete val;
return ret;
}
zsock_t* socket() const
{
return zyre_socket(m_self);
}
static void version(int& major, int& minor, int& patch)
{
zyre_version(&major, &minor, &patch);
}
private:
std::vector<std::string> to_vector(zlist_t* list) const
{
std::vector<std::string> ret;
void* cursor = zlist_first(list);
while (cursor != NULL)
{
ret.emplace_back(static_cast<char*>(cursor));
cursor = zlist_next(list);
}
return ret;
}
zyre_t* m_self;
};
}<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "../client/gles2_lib.h"
#include "../common/thread_local.h"
namespace gles2 {
namespace {
gpu::ThreadLocalKey g_gl_context_key;
} // namespace anonymous
void Initialize() {
g_gl_context_key = gpu::ThreadLocalAlloc();
}
void Terminate() {
gpu::ThreadLocalFree(g_gl_context_key);
g_gl_context_key = 0;
}
gpu::gles2::GLES2Implementation* GetGLContext() {
return static_cast<gpu::gles2::GLES2Implementation*>(
gpu::ThreadLocalGetValue(g_gl_context_key));
}
void SetGLContext(gpu::gles2::GLES2Implementation* context) {
gpu::ThreadLocalSetValue(g_gl_context_key, context);
}
} // namespace gles2
<commit_msg>Work around bug in gcc's name mangling causing linker to crash on Mac OS X.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "../client/gles2_lib.h"
#include "../common/thread_local.h"
namespace gles2 {
// TODO(kbr): the use of this anonymous namespace core dumps the
// linker on Mac OS X 10.6 when the symbol ordering file is used
// namespace {
static gpu::ThreadLocalKey g_gl_context_key;
// } // namespace anonymous
void Initialize() {
g_gl_context_key = gpu::ThreadLocalAlloc();
}
void Terminate() {
gpu::ThreadLocalFree(g_gl_context_key);
g_gl_context_key = 0;
}
gpu::gles2::GLES2Implementation* GetGLContext() {
return static_cast<gpu::gles2::GLES2Implementation*>(
gpu::ThreadLocalGetValue(g_gl_context_key));
}
void SetGLContext(gpu::gles2::GLES2Implementation* context) {
gpu::ThreadLocalSetValue(g_gl_context_key, context);
}
} // namespace gles2
<|endoftext|>
|
<commit_before>#include "text2D.hpp"
#include "shader_loader.hpp"
#include "texture_loader.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#include <glm/gtc/matrix_transform.hpp>
#endif
// Include standard headers
#include <vector> // std::vector
#include <cstring>
#include <stdint.h> // uint32_t etc.
GLuint Text2DTextureID; // Material containing the font
GLuint Text2DVertexBufferID; // Buffer containing the vertices
GLuint Text2DUVBufferID; // Buffer containing the UVs
GLuint Text2DShaderID; // Shader program used to display the text
GLuint vertexPosition_screenspaceID; // Location of the program's "vertexPosition_screenspace" attribute
GLuint vertexUVID; // Location of the program's "vertexUV" attribute
GLuint Text2DUniformID; // Location of the program's texture attribute
GLuint screen_width_uniform_ID; // Location of the program's window width uniform.
GLuint screen_height_uniform_ID; // Location of the program's window height uniform.
namespace text2D
{
void initText2D(
GLuint screen_width,
GLuint screen_height,
const char* texturePath,
const char* char_font_texture_file_format)
{
// Initialize texture
if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0))
{
Text2DTextureID = texture::load_BMP_texture(texturePath);
}
else if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0))
{
Text2DTextureID = texture::load_DDS_texture(texturePath);
}
// Initialize VBO
glGenBuffers(1, &Text2DVertexBufferID);
glGenBuffers(1, &Text2DUVBufferID);
// Initialize Shader
Text2DShaderID = LoadShaders("TextVertexShader.vertexshader", "TextVertexShader.fragmentshader");
// Get a handle for our buffers
vertexPosition_screenspaceID = glGetAttribLocation(Text2DShaderID, "vertexPosition_screenspace");
vertexUVID = glGetAttribLocation(Text2DShaderID, "vertexUV");
// Initialize uniforms' IDs
Text2DUniformID = glGetUniformLocation(Text2DShaderID, "myTextureSampler");
// Initialize uniform window width.
screen_width_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_width");
glUniform1i(screen_width_uniform_ID, screen_width);
// Initialize uniform window height.
screen_height_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_height");
glUniform1i(screen_height_uniform_ID, screen_height);
}
void printText2D(
GLuint screen_width,
GLuint screen_height,
GLuint x,
GLuint y,
GLuint text_size,
GLuint font_size,
const char* text,
const char* char_font_texture_file_format,
const char* horizontal_alignment,
const char* vertical_alignment)
{
// If horizontal alignment is `"left"`, each line begins from the same x coordinate.
// If horizontal alignment is `"left"` and vertical alignment is `"top"`,
// then there is no need to check the text beforehand for newlines.
// Otherwise newlines need to be checked beforehand.
//
// If horizontal alignment is right, each line ends in the same x coordinate.
// Newlines need to be checked beforehand.
uint32_t length = strlen(text);
// Count the number of lines.
uint32_t number_of_lines = 1;
uint32_t i = 0;
while(i < length)
{
char character = text[i++];
if (character == (char) '\\')
{
// OK, this character was backslash, so read the next character.
character = text[i++];
if (character == 'n')
{
number_of_lines++;
}
}
}
GLuint current_left_x;
GLuint current_top_y;
if (strcmp(horizontal_alignment, "left") == 0)
{
current_left_x = x;
}
else if (strcmp(horizontal_alignment, "center") == 0)
{
current_left_x = x - 0.5f * length * text_size;
}
else if (strcmp(horizontal_alignment, "right") == 0)
{
current_left_x = x - length * text_size;
}
if (strcmp(vertical_alignment, "top") == 0)
{
current_top_y = y;
}
else if (strcmp(vertical_alignment, "center") == 0)
{
current_top_y = y + 0.5f * number_of_lines * text_size;
}
else if (strcmp(vertical_alignment, "bottom") == 0)
{
current_top_y = y + number_of_lines * text_size;
}
// Fill buffers
std::vector<glm::vec2> vertices;
std::vector<glm::vec2> UVs;
i = 0;
while(i < length)
{
// Print to the right side of X (so far there is no check for input length).
// Print up of Y.
GLfloat vertex_up_left_x;
GLfloat vertex_up_left_y;
GLfloat vertex_up_right_x;
GLfloat vertex_up_right_y;
GLfloat vertex_down_left_x;
GLfloat vertex_down_left_y;
GLfloat vertex_down_right_x;
GLfloat vertex_down_right_y;
char character = text[i++];
if (character == (char) '\\')
{
// OK, this character was backslash, so read the next character.
character = text[i++];
if (character == 'n')
{
// jump to the beginning of the next line.
// `"left"` horizontal alignment and `"top"` vertical alignment are assumed.
// TODO: implement newline for other horizontal and vertical alignments too!
current_left_x = x;
current_top_y -= text_size;
continue;
}
}
vertex_up_left_x = vertex_down_left_x = current_left_x;
vertex_up_right_x = vertex_down_right_x = current_left_x + text_size;
current_left_x += text_size;
if (strcmp(vertical_alignment, "bottom") == 0)
{
vertex_down_left_y = vertex_down_right_y = current_top_y - text_size;
vertex_up_left_y = vertex_up_right_y = current_top_y;
}
else if (strcmp(vertical_alignment, "top") == 0)
{
vertex_down_left_y = vertex_down_right_y = current_top_y - text_size;
vertex_up_left_y = vertex_up_right_y = current_top_y;
}
else if (strcmp(vertical_alignment, "center") == 0)
{
vertex_down_left_y = vertex_down_right_y = current_top_y - text_size;
vertex_up_left_y = vertex_up_right_y = current_top_y;
}
glm::vec2 vertex_up_left = glm::vec2(vertex_up_left_x, vertex_up_left_y);
glm::vec2 vertex_up_right = glm::vec2(vertex_up_right_x, vertex_up_right_y);
glm::vec2 vertex_down_left = glm::vec2(vertex_down_left_x, vertex_down_left_y);
glm::vec2 vertex_down_right = glm::vec2(vertex_down_right_x, vertex_down_right_y);
vertices.push_back(vertex_up_left);
vertices.push_back(vertex_down_left);
vertices.push_back(vertex_up_right);
vertices.push_back(vertex_down_right);
vertices.push_back(vertex_up_right);
vertices.push_back(vertex_down_left);
float uv_x = (character % font_size) / (GLfloat) font_size;
float uv_y;
if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0))
{
uv_y = (character / font_size) / (GLfloat) font_size;
}
else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0))
{
// BMP is stored in the file beginning from the bottom line.
uv_y = 1 - (character / font_size) / (GLfloat) font_size;
}
glm::vec2 uv_up_left = glm::vec2(uv_x , uv_y);
glm::vec2 uv_up_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), uv_y);
glm::vec2 uv_down_right;
glm::vec2 uv_down_left;
if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0))
{
uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y + 1.0f / (GLfloat) font_size));
uv_down_left = glm::vec2(uv_x , (uv_y + 1.0f / (GLfloat) font_size));
}
else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0))
{
// BMP is stored in the file beginning from the bottom line.
uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y - 1.0f / (GLfloat) font_size));
uv_down_left = glm::vec2(uv_x , (uv_y - 1.0f / (GLfloat) font_size));
}
UVs.push_back(uv_up_left);
UVs.push_back(uv_down_left);
UVs.push_back(uv_up_right);
UVs.push_back(uv_down_right);
UVs.push_back(uv_up_right);
UVs.push_back(uv_down_left);
}
glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID);
glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW);
// Bind shader
glUseProgram(Text2DShaderID);
// Bind texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Text2DTextureID);
// Set our "myTextureSampler" sampler to user Material Unit 0
glUniform1i(Text2DUniformID, 0);
// Set screen width.
glUniform1i(screen_width_uniform_ID, screen_width);
// Set screen height.
glUniform1i(screen_height_uniform_ID, screen_height);
// 1st attribute buffer : vertices
glEnableVertexAttribArray(vertexPosition_screenspaceID);
glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID);
glVertexAttribPointer(vertexPosition_screenspaceID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(vertexUVID);
glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID);
glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Draw call
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
glDisable(GL_BLEND);
glDisableVertexAttribArray(vertexPosition_screenspaceID);
glDisableVertexAttribArray(vertexUVID);
}
void printText2D(PrintingStruct printing_struct)
{
printText2D(
printing_struct.screen_width,
printing_struct.screen_height,
printing_struct.x,
printing_struct.y,
printing_struct.text_size,
printing_struct.font_size,
printing_struct.text,
printing_struct.char_font_texture_file_format,
printing_struct.horizontal_alignment,
printing_struct.vertical_alignment);
}
void printText2D(
GLuint screen_width,
GLuint screen_height,
GLuint x,
GLuint y,
GLuint text_size,
GLuint font_size,
const char* text,
const char* char_font_texture_file_format)
{
printText2D(screen_width, screen_height, x, y, text_size, font_size, text, char_font_texture_file_format, "left", "bottom");
}
void cleanupText2D()
{
// Delete buffers
glDeleteBuffers(1, &Text2DVertexBufferID);
glDeleteBuffers(1, &Text2DUVBufferID);
// Delete texture
glDeleteTextures(1, &Text2DTextureID);
// Delete shader
glDeleteProgram(Text2DShaderID);
}
}
<commit_msg>`void printText2D`: Refaktorointia.<commit_after>#include "text2D.hpp"
#include "shader_loader.hpp"
#include "texture_loader.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#include <glm/gtc/matrix_transform.hpp>
#endif
// Include standard headers
#include <vector> // std::vector
#include <cstring>
#include <stdint.h> // uint32_t etc.
GLuint Text2DTextureID; // Material containing the font
GLuint Text2DVertexBufferID; // Buffer containing the vertices
GLuint Text2DUVBufferID; // Buffer containing the UVs
GLuint Text2DShaderID; // Shader program used to display the text
GLuint vertexPosition_screenspaceID; // Location of the program's "vertexPosition_screenspace" attribute
GLuint vertexUVID; // Location of the program's "vertexUV" attribute
GLuint Text2DUniformID; // Location of the program's texture attribute
GLuint screen_width_uniform_ID; // Location of the program's window width uniform.
GLuint screen_height_uniform_ID; // Location of the program's window height uniform.
namespace text2D
{
void initText2D(
GLuint screen_width,
GLuint screen_height,
const char* texturePath,
const char* char_font_texture_file_format)
{
// Initialize texture
if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0))
{
Text2DTextureID = texture::load_BMP_texture(texturePath);
}
else if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0))
{
Text2DTextureID = texture::load_DDS_texture(texturePath);
}
// Initialize VBO
glGenBuffers(1, &Text2DVertexBufferID);
glGenBuffers(1, &Text2DUVBufferID);
// Initialize Shader
Text2DShaderID = LoadShaders("TextVertexShader.vertexshader", "TextVertexShader.fragmentshader");
// Get a handle for our buffers
vertexPosition_screenspaceID = glGetAttribLocation(Text2DShaderID, "vertexPosition_screenspace");
vertexUVID = glGetAttribLocation(Text2DShaderID, "vertexUV");
// Initialize uniforms' IDs
Text2DUniformID = glGetUniformLocation(Text2DShaderID, "myTextureSampler");
// Initialize uniform window width.
screen_width_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_width");
glUniform1i(screen_width_uniform_ID, screen_width);
// Initialize uniform window height.
screen_height_uniform_ID = glGetUniformLocation(Text2DShaderID, "screen_height");
glUniform1i(screen_height_uniform_ID, screen_height);
}
void printText2D(
GLuint screen_width,
GLuint screen_height,
GLuint x,
GLuint y,
GLuint text_size,
GLuint font_size,
const char* text,
const char* char_font_texture_file_format,
const char* horizontal_alignment,
const char* vertical_alignment)
{
// If horizontal alignment is `"left"`, each line begins from the same x coordinate.
// If horizontal alignment is `"left"` and vertical alignment is `"top"`,
// then there is no need to check the text beforehand for newlines.
// Otherwise newlines need to be checked beforehand.
//
// If horizontal alignment is right, each line ends in the same x coordinate.
// Newlines need to be checked beforehand.
uint32_t length = strlen(text);
// Count the number of lines.
uint32_t number_of_lines = 1;
uint32_t i = 0;
while(i < length)
{
char character = text[i++];
if (character == (char) '\\')
{
// OK, this character was backslash, so read the next character.
character = text[i++];
if (character == 'n')
{
number_of_lines++;
}
}
}
GLuint current_left_x;
GLuint current_top_y;
if (strcmp(horizontal_alignment, "left") == 0)
{
current_left_x = x;
}
else if (strcmp(horizontal_alignment, "center") == 0)
{
current_left_x = x - 0.5f * length * text_size;
}
else if (strcmp(horizontal_alignment, "right") == 0)
{
current_left_x = x - length * text_size;
}
if (strcmp(vertical_alignment, "top") == 0)
{
current_top_y = y;
}
else if (strcmp(vertical_alignment, "center") == 0)
{
current_top_y = y + 0.5f * number_of_lines * text_size;
}
else if (strcmp(vertical_alignment, "bottom") == 0)
{
current_top_y = y + number_of_lines * text_size;
}
// Fill buffers
std::vector<glm::vec2> vertices;
std::vector<glm::vec2> UVs;
i = 0;
while(i < length)
{
// Print to the right side of X (so far there is no check for input length).
// Print up of Y.
GLfloat vertex_up_left_x;
GLfloat vertex_up_left_y;
GLfloat vertex_up_right_x;
GLfloat vertex_up_right_y;
GLfloat vertex_down_left_x;
GLfloat vertex_down_left_y;
GLfloat vertex_down_right_x;
GLfloat vertex_down_right_y;
char character = text[i++];
if (character == (char) '\\')
{
// OK, this character was backslash, so read the next character.
character = text[i++];
if (character == 'n')
{
// jump to the beginning of the next line.
// `"left"` horizontal alignment and `"top"` vertical alignment are assumed.
// TODO: implement newline for other horizontal and vertical alignments too!
current_left_x = x;
current_top_y -= text_size;
continue;
}
}
vertex_up_left_x = vertex_down_left_x = current_left_x;
vertex_up_right_x = vertex_down_right_x = current_left_x + text_size;
current_left_x += text_size;
vertex_down_left_y = vertex_down_right_y = current_top_y - text_size;
vertex_up_left_y = vertex_up_right_y = current_top_y;
glm::vec2 vertex_up_left = glm::vec2(vertex_up_left_x, vertex_up_left_y);
glm::vec2 vertex_up_right = glm::vec2(vertex_up_right_x, vertex_up_right_y);
glm::vec2 vertex_down_left = glm::vec2(vertex_down_left_x, vertex_down_left_y);
glm::vec2 vertex_down_right = glm::vec2(vertex_down_right_x, vertex_down_right_y);
vertices.push_back(vertex_up_left);
vertices.push_back(vertex_down_left);
vertices.push_back(vertex_up_right);
vertices.push_back(vertex_down_right);
vertices.push_back(vertex_up_right);
vertices.push_back(vertex_down_left);
float uv_x = (character % font_size) / (GLfloat) font_size;
float uv_y;
if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0))
{
uv_y = (character / font_size) / (GLfloat) font_size;
}
else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0))
{
// BMP is stored in the file beginning from the bottom line.
uv_y = 1 - (character / font_size) / (GLfloat) font_size;
}
glm::vec2 uv_up_left = glm::vec2(uv_x , uv_y);
glm::vec2 uv_up_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), uv_y);
glm::vec2 uv_down_right;
glm::vec2 uv_down_left;
if ((strcmp(char_font_texture_file_format, "dds") == 0) || (strcmp(char_font_texture_file_format, "DDS") == 0))
{
uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y + 1.0f / (GLfloat) font_size));
uv_down_left = glm::vec2(uv_x , (uv_y + 1.0f / (GLfloat) font_size));
}
else if ((strcmp(char_font_texture_file_format, "bmp") == 0) || (strcmp(char_font_texture_file_format, "BMP") == 0))
{
// BMP is stored in the file beginning from the bottom line.
uv_down_right = glm::vec2(uv_x + (1.0f / (GLfloat) font_size), (uv_y - 1.0f / (GLfloat) font_size));
uv_down_left = glm::vec2(uv_x , (uv_y - 1.0f / (GLfloat) font_size));
}
UVs.push_back(uv_up_left);
UVs.push_back(uv_down_left);
UVs.push_back(uv_up_right);
UVs.push_back(uv_down_right);
UVs.push_back(uv_up_right);
UVs.push_back(uv_down_left);
}
glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID);
glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW);
// Bind shader
glUseProgram(Text2DShaderID);
// Bind texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Text2DTextureID);
// Set our "myTextureSampler" sampler to user Material Unit 0
glUniform1i(Text2DUniformID, 0);
// Set screen width.
glUniform1i(screen_width_uniform_ID, screen_width);
// Set screen height.
glUniform1i(screen_height_uniform_ID, screen_height);
// 1st attribute buffer : vertices
glEnableVertexAttribArray(vertexPosition_screenspaceID);
glBindBuffer(GL_ARRAY_BUFFER, Text2DVertexBufferID);
glVertexAttribPointer(vertexPosition_screenspaceID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(vertexUVID);
glBindBuffer(GL_ARRAY_BUFFER, Text2DUVBufferID);
glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Draw call
glDrawArrays(GL_TRIANGLES, 0, vertices.size());
glDisable(GL_BLEND);
glDisableVertexAttribArray(vertexPosition_screenspaceID);
glDisableVertexAttribArray(vertexUVID);
}
void printText2D(PrintingStruct printing_struct)
{
printText2D(
printing_struct.screen_width,
printing_struct.screen_height,
printing_struct.x,
printing_struct.y,
printing_struct.text_size,
printing_struct.font_size,
printing_struct.text,
printing_struct.char_font_texture_file_format,
printing_struct.horizontal_alignment,
printing_struct.vertical_alignment);
}
void printText2D(
GLuint screen_width,
GLuint screen_height,
GLuint x,
GLuint y,
GLuint text_size,
GLuint font_size,
const char* text,
const char* char_font_texture_file_format)
{
printText2D(screen_width, screen_height, x, y, text_size, font_size, text, char_font_texture_file_format, "left", "bottom");
}
void cleanupText2D()
{
// Delete buffers
glDeleteBuffers(1, &Text2DVertexBufferID);
glDeleteBuffers(1, &Text2DUVBufferID);
// Delete texture
glDeleteTextures(1, &Text2DTextureID);
// Delete shader
glDeleteProgram(Text2DShaderID);
}
}
<|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.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// 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 materials provided with the distribution.
//
// * The name of Intel Corporation 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 "test_precomp.hpp"
using namespace cv;
using namespace std;
template <typename T, typename compute>
class ShapeBaseTest : public cvtest::BaseTest
{
public:
typedef Point_<T> PointType;
ShapeBaseTest(int _NSN, int _NP, float _CURRENT_MAX_ACCUR)
: NSN(_NSN), NP(_NP), CURRENT_MAX_ACCUR(_CURRENT_MAX_ACCUR)
{
// generate file list
vector<string> shapeNames;
shapeNames.push_back("apple"); //ok
shapeNames.push_back("children"); // ok
shapeNames.push_back("device7"); // ok
shapeNames.push_back("Heart"); // ok
shapeNames.push_back("teddy"); // ok
for (vector<string>::const_iterator i = shapeNames.begin(); i != shapeNames.end(); ++i)
{
for (int j = 0; j < NSN; ++j)
{
stringstream filename;
filename << cvtest::TS::ptr()->get_data_path()
<< "shape/mpeg_test/" << *i << "-" << j + 1 << ".png";
filenames.push_back(filename.str());
}
}
// distance matrix
const int totalCount = (int)filenames.size();
distanceMat = Mat::zeros(totalCount, totalCount, CV_32F);
}
protected:
void run(int)
{
mpegTest();
displayMPEGResults();
}
vector<PointType> convertContourType(const Mat& currentQuery) const
{
vector<vector<Point> > _contoursQuery;
findContours(currentQuery, _contoursQuery, RETR_LIST, CHAIN_APPROX_NONE);
vector <PointType> contoursQuery;
for (size_t border=0; border<_contoursQuery.size(); border++)
{
for (size_t p=0; p<_contoursQuery[border].size(); p++)
{
contoursQuery.push_back(PointType((T)_contoursQuery[border][p].x,
(T)_contoursQuery[border][p].y));
}
}
// In case actual number of points is less than n
for (int add=(int)contoursQuery.size()-1; add<NP; add++)
{
contoursQuery.push_back(contoursQuery[contoursQuery.size()-add+1]); //adding dummy values
}
// Uniformly sampling
random_shuffle(contoursQuery.begin(), contoursQuery.end());
int nStart=NP;
vector<PointType> cont;
for (int i=0; i<nStart; i++)
{
cont.push_back(contoursQuery[i]);
}
return cont;
}
void mpegTest()
{
// query contours (normal v flipped, h flipped) and testing contour
vector<PointType> contoursQuery1, contoursQuery2, contoursQuery3, contoursTesting;
// reading query and computing its properties
for (vector<string>::const_iterator a = filenames.begin(); a != filenames.end(); ++a)
{
// read current image
int aIndex = a - filenames.begin();
Mat currentQuery = imread(*a, IMREAD_GRAYSCALE);
Mat flippedHQuery, flippedVQuery;
flip(currentQuery, flippedHQuery, 0);
flip(currentQuery, flippedVQuery, 1);
// compute border of the query and its flipped versions
contoursQuery1=convertContourType(currentQuery);
contoursQuery2=convertContourType(flippedHQuery);
contoursQuery3=convertContourType(flippedVQuery);
// compare with all the rest of the images: testing
for (vector<string>::const_iterator b = filenames.begin(); b != filenames.end(); ++b)
{
int bIndex = b - filenames.begin();
float distance = 0;
// skip self-comparisson
if (a != b)
{
// read testing image
Mat currentTest = imread(*b, IMREAD_GRAYSCALE);
// compute border of the testing
contoursTesting=convertContourType(currentTest);
// compute shape distance
distance = cmp(contoursQuery1, contoursQuery2,
contoursQuery3, contoursTesting);
}
distanceMat.at<float>(aIndex, bIndex) = distance;
}
}
}
void displayMPEGResults()
{
const int FIRST_MANY=2*NSN;
int corrects=0;
int divi=0;
for (int row=0; row<distanceMat.rows; row++)
{
if (row%NSN==0) //another group
{
divi+=NSN;
}
for (int col=divi-NSN; col<divi; col++)
{
int nsmall=0;
for (int i=0; i<distanceMat.cols; i++)
{
if (distanceMat.at<float>(row,col) > distanceMat.at<float>(row,i))
{
nsmall++;
}
}
if (nsmall<=FIRST_MANY)
{
corrects++;
}
}
}
float porc = 100*float(corrects)/(NSN*distanceMat.rows);
std::cout << "Test result: " << porc << "%" << std::endl;
if (porc >= CURRENT_MAX_ACCUR)
ts->set_failed_test_info(cvtest::TS::OK);
else
ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
}
protected:
int NSN;
int NP;
float CURRENT_MAX_ACCUR;
vector<string> filenames;
Mat distanceMat;
compute cmp;
};
//------------------------------------------------------------------------
// Test Shape_SCD.regression
//------------------------------------------------------------------------
class computeShapeDistance_Chi
{
Ptr <ShapeContextDistanceExtractor> mysc;
public:
computeShapeDistance_Chi()
{
const int angularBins=12;
const int radialBins=4;
const float minRad=0.2f;
const float maxRad=2;
mysc = createShapeContextDistanceExtractor(angularBins, radialBins, minRad, maxRad);
mysc->setIterations(1);
mysc->setCostExtractor(createChiHistogramCostExtractor(30,0.15f));
mysc->setTransformAlgorithm( createThinPlateSplineShapeTransformer() );
}
float operator()(vector <Point2f>& query1, vector <Point2f>& query2,
vector <Point2f>& query3, vector <Point2f>& testq)
{
return std::min(mysc->computeDistance(query1, testq),
std::min(mysc->computeDistance(query2, testq),
mysc->computeDistance(query3, testq)));
}
};
TEST(Shape_SCD, regression)
{
const int NSN_val=5;//10;//20; //number of shapes per class
const int NP_val=120; //number of points simplifying the contour
const float CURRENT_MAX_ACCUR_val=95; //99% and 100% reached in several tests, 95 is fixed as minimum boundary
ShapeBaseTest<float, computeShapeDistance_Chi> test(NSN_val, NP_val, CURRENT_MAX_ACCUR_val);
test.safe_run();
}
//------------------------------------------------------------------------
// Test ShapeEMD_SCD.regression
//------------------------------------------------------------------------
class computeShapeDistance_EMD
{
Ptr <ShapeContextDistanceExtractor> mysc;
public:
computeShapeDistance_EMD()
{
const int angularBins=12;
const int radialBins=4;
const float minRad=0.2f;
const float maxRad=2;
mysc = createShapeContextDistanceExtractor(angularBins, radialBins, minRad, maxRad);
mysc->setIterations(1);
mysc->setCostExtractor( createEMDL1HistogramCostExtractor() );
mysc->setTransformAlgorithm( createThinPlateSplineShapeTransformer() );
}
float operator()(vector <Point2f>& query1, vector <Point2f>& query2,
vector <Point2f>& query3, vector <Point2f>& testq)
{
return std::min(mysc->computeDistance(query1, testq),
std::min(mysc->computeDistance(query2, testq),
mysc->computeDistance(query3, testq)));
}
};
TEST(ShapeEMD_SCD, regression)
{
const int NSN_val=5;//10;//20; //number of shapes per class
const int NP_val=100; //number of points simplifying the contour
const float CURRENT_MAX_ACCUR_val=95; //98% and 99% reached in several tests, 95 is fixed as minimum boundary
ShapeBaseTest<float, computeShapeDistance_EMD> test(NSN_val, NP_val, CURRENT_MAX_ACCUR_val);
test.safe_run();
}
//------------------------------------------------------------------------
// Test Hauss.regression
//------------------------------------------------------------------------
class computeShapeDistance_Haussdorf
{
Ptr <HausdorffDistanceExtractor> haus;
public:
computeShapeDistance_Haussdorf()
{
haus = createHausdorffDistanceExtractor();
}
float operator()(vector<Point> &query1, vector<Point> &query2,
vector<Point> &query3, vector<Point> &testq)
{
return std::min(haus->computeDistance(query1,testq),
std::min(haus->computeDistance(query2,testq),
haus->computeDistance(query3,testq)));
}
};
TEST(Hauss, regression)
{
const int NSN_val=5;//10;//20; //number of shapes per class
const int NP_val = 180; //number of points simplifying the contour
const float CURRENT_MAX_ACCUR_val=85; //90% and 91% reached in several tests, 85 is fixed as minimum boundary
ShapeBaseTest<int, computeShapeDistance_Haussdorf> test(NSN_val, NP_val, CURRENT_MAX_ACCUR_val);
test.safe_run();
}
<commit_msg>Fixed win64 compile warning<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.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// 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 materials provided with the distribution.
//
// * The name of Intel Corporation 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 "test_precomp.hpp"
using namespace cv;
using namespace std;
template <typename T, typename compute>
class ShapeBaseTest : public cvtest::BaseTest
{
public:
typedef Point_<T> PointType;
ShapeBaseTest(int _NSN, int _NP, float _CURRENT_MAX_ACCUR)
: NSN(_NSN), NP(_NP), CURRENT_MAX_ACCUR(_CURRENT_MAX_ACCUR)
{
// generate file list
vector<string> shapeNames;
shapeNames.push_back("apple"); //ok
shapeNames.push_back("children"); // ok
shapeNames.push_back("device7"); // ok
shapeNames.push_back("Heart"); // ok
shapeNames.push_back("teddy"); // ok
for (vector<string>::const_iterator i = shapeNames.begin(); i != shapeNames.end(); ++i)
{
for (int j = 0; j < NSN; ++j)
{
stringstream filename;
filename << cvtest::TS::ptr()->get_data_path()
<< "shape/mpeg_test/" << *i << "-" << j + 1 << ".png";
filenames.push_back(filename.str());
}
}
// distance matrix
const int totalCount = (int)filenames.size();
distanceMat = Mat::zeros(totalCount, totalCount, CV_32F);
}
protected:
void run(int)
{
mpegTest();
displayMPEGResults();
}
vector<PointType> convertContourType(const Mat& currentQuery) const
{
vector<vector<Point> > _contoursQuery;
findContours(currentQuery, _contoursQuery, RETR_LIST, CHAIN_APPROX_NONE);
vector <PointType> contoursQuery;
for (size_t border=0; border<_contoursQuery.size(); border++)
{
for (size_t p=0; p<_contoursQuery[border].size(); p++)
{
contoursQuery.push_back(PointType((T)_contoursQuery[border][p].x,
(T)_contoursQuery[border][p].y));
}
}
// In case actual number of points is less than n
for (int add=(int)contoursQuery.size()-1; add<NP; add++)
{
contoursQuery.push_back(contoursQuery[contoursQuery.size()-add+1]); //adding dummy values
}
// Uniformly sampling
random_shuffle(contoursQuery.begin(), contoursQuery.end());
int nStart=NP;
vector<PointType> cont;
for (int i=0; i<nStart; i++)
{
cont.push_back(contoursQuery[i]);
}
return cont;
}
void mpegTest()
{
// query contours (normal v flipped, h flipped) and testing contour
vector<PointType> contoursQuery1, contoursQuery2, contoursQuery3, contoursTesting;
// reading query and computing its properties
for (vector<string>::const_iterator a = filenames.begin(); a != filenames.end(); ++a)
{
// read current image
int aIndex = (int)(a - filenames.begin());
Mat currentQuery = imread(*a, IMREAD_GRAYSCALE);
Mat flippedHQuery, flippedVQuery;
flip(currentQuery, flippedHQuery, 0);
flip(currentQuery, flippedVQuery, 1);
// compute border of the query and its flipped versions
contoursQuery1=convertContourType(currentQuery);
contoursQuery2=convertContourType(flippedHQuery);
contoursQuery3=convertContourType(flippedVQuery);
// compare with all the rest of the images: testing
for (vector<string>::const_iterator b = filenames.begin(); b != filenames.end(); ++b)
{
int bIndex = (int)(b - filenames.begin());
float distance = 0;
// skip self-comparisson
if (a != b)
{
// read testing image
Mat currentTest = imread(*b, IMREAD_GRAYSCALE);
// compute border of the testing
contoursTesting=convertContourType(currentTest);
// compute shape distance
distance = cmp(contoursQuery1, contoursQuery2,
contoursQuery3, contoursTesting);
}
distanceMat.at<float>(aIndex, bIndex) = distance;
}
}
}
void displayMPEGResults()
{
const int FIRST_MANY=2*NSN;
int corrects=0;
int divi=0;
for (int row=0; row<distanceMat.rows; row++)
{
if (row%NSN==0) //another group
{
divi+=NSN;
}
for (int col=divi-NSN; col<divi; col++)
{
int nsmall=0;
for (int i=0; i<distanceMat.cols; i++)
{
if (distanceMat.at<float>(row,col) > distanceMat.at<float>(row,i))
{
nsmall++;
}
}
if (nsmall<=FIRST_MANY)
{
corrects++;
}
}
}
float porc = 100*float(corrects)/(NSN*distanceMat.rows);
std::cout << "Test result: " << porc << "%" << std::endl;
if (porc >= CURRENT_MAX_ACCUR)
ts->set_failed_test_info(cvtest::TS::OK);
else
ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
}
protected:
int NSN;
int NP;
float CURRENT_MAX_ACCUR;
vector<string> filenames;
Mat distanceMat;
compute cmp;
};
//------------------------------------------------------------------------
// Test Shape_SCD.regression
//------------------------------------------------------------------------
class computeShapeDistance_Chi
{
Ptr <ShapeContextDistanceExtractor> mysc;
public:
computeShapeDistance_Chi()
{
const int angularBins=12;
const int radialBins=4;
const float minRad=0.2f;
const float maxRad=2;
mysc = createShapeContextDistanceExtractor(angularBins, radialBins, minRad, maxRad);
mysc->setIterations(1);
mysc->setCostExtractor(createChiHistogramCostExtractor(30,0.15f));
mysc->setTransformAlgorithm( createThinPlateSplineShapeTransformer() );
}
float operator()(vector <Point2f>& query1, vector <Point2f>& query2,
vector <Point2f>& query3, vector <Point2f>& testq)
{
return std::min(mysc->computeDistance(query1, testq),
std::min(mysc->computeDistance(query2, testq),
mysc->computeDistance(query3, testq)));
}
};
TEST(Shape_SCD, regression)
{
const int NSN_val=5;//10;//20; //number of shapes per class
const int NP_val=120; //number of points simplifying the contour
const float CURRENT_MAX_ACCUR_val=95; //99% and 100% reached in several tests, 95 is fixed as minimum boundary
ShapeBaseTest<float, computeShapeDistance_Chi> test(NSN_val, NP_val, CURRENT_MAX_ACCUR_val);
test.safe_run();
}
//------------------------------------------------------------------------
// Test ShapeEMD_SCD.regression
//------------------------------------------------------------------------
class computeShapeDistance_EMD
{
Ptr <ShapeContextDistanceExtractor> mysc;
public:
computeShapeDistance_EMD()
{
const int angularBins=12;
const int radialBins=4;
const float minRad=0.2f;
const float maxRad=2;
mysc = createShapeContextDistanceExtractor(angularBins, radialBins, minRad, maxRad);
mysc->setIterations(1);
mysc->setCostExtractor( createEMDL1HistogramCostExtractor() );
mysc->setTransformAlgorithm( createThinPlateSplineShapeTransformer() );
}
float operator()(vector <Point2f>& query1, vector <Point2f>& query2,
vector <Point2f>& query3, vector <Point2f>& testq)
{
return std::min(mysc->computeDistance(query1, testq),
std::min(mysc->computeDistance(query2, testq),
mysc->computeDistance(query3, testq)));
}
};
TEST(ShapeEMD_SCD, regression)
{
const int NSN_val=5;//10;//20; //number of shapes per class
const int NP_val=100; //number of points simplifying the contour
const float CURRENT_MAX_ACCUR_val=95; //98% and 99% reached in several tests, 95 is fixed as minimum boundary
ShapeBaseTest<float, computeShapeDistance_EMD> test(NSN_val, NP_val, CURRENT_MAX_ACCUR_val);
test.safe_run();
}
//------------------------------------------------------------------------
// Test Hauss.regression
//------------------------------------------------------------------------
class computeShapeDistance_Haussdorf
{
Ptr <HausdorffDistanceExtractor> haus;
public:
computeShapeDistance_Haussdorf()
{
haus = createHausdorffDistanceExtractor();
}
float operator()(vector<Point> &query1, vector<Point> &query2,
vector<Point> &query3, vector<Point> &testq)
{
return std::min(haus->computeDistance(query1,testq),
std::min(haus->computeDistance(query2,testq),
haus->computeDistance(query3,testq)));
}
};
TEST(Hauss, regression)
{
const int NSN_val=5;//10;//20; //number of shapes per class
const int NP_val = 180; //number of points simplifying the contour
const float CURRENT_MAX_ACCUR_val=85; //90% and 91% reached in several tests, 85 is fixed as minimum boundary
ShapeBaseTest<int, computeShapeDistance_Haussdorf> test(NSN_val, NP_val, CURRENT_MAX_ACCUR_val);
test.safe_run();
}
<|endoftext|>
|
<commit_before>//
// PROJECT: Aspia
// FILE: client/client_user_authorizer.cc
// LICENSE: GNU General Public License 3
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "client/client_user_authorizer.h"
#include <QCryptographicHash>
#include <QDebug>
#include "base/message_serialization.h"
#include "client/ui/authorization_dialog.h"
#include "crypto/secure_memory.h"
namespace aspia {
namespace {
const quint32 kKeyHashingRounds = 100000;
const quint32 kPasswordHashingRounds = 100000;
enum MessageId { LogonRequest, ClientChallenge };
QByteArray createPasswordHash(const QString& password)
{
QByteArray data = password.toUtf8();
for (int i = 0; i < kPasswordHashingRounds; ++i)
{
data = QCryptographicHash::hash(data, QCryptographicHash::Sha512);
}
return data;
}
QByteArray createSessionKey(const QByteArray& password_hash, const QByteArray& nonce)
{
QByteArray data = password_hash;
for (quint32 i = 0; i < kKeyHashingRounds; ++i)
{
QCryptographicHash hash(QCryptographicHash::Sha512);
hash.addData(data);
hash.addData(nonce);
data = hash.result();
}
return data;
}
} // namespace
ClientUserAuthorizer::ClientUserAuthorizer(QWidget* parent)
: QObject(parent)
{
// Nothing
}
ClientUserAuthorizer::~ClientUserAuthorizer()
{
secureMemZero(&username_);
secureMemZero(&password_);
cancel();
}
void ClientUserAuthorizer::setSessionType(proto::auth::SessionType session_type)
{
session_type_ = session_type;
}
void ClientUserAuthorizer::setUserName(const QString& username)
{
username_ = username;
}
void ClientUserAuthorizer::setPassword(const QString& password)
{
password_ = password;
}
void ClientUserAuthorizer::start()
{
if (state_ != NotStarted)
{
qWarning("Authorizer already started");
return;
}
proto::auth::ClientToHost message;
// We do not support other authorization methods yet.
message.mutable_logon_request()->set_method(proto::auth::METHOD_BASIC);
state_ = Started;
emit writeMessage(LogonRequest, serializeMessage(message));
}
void ClientUserAuthorizer::cancel()
{
if (state_ == Finished)
return;
state_ = Finished;
emit finished(proto::auth::STATUS_CANCELED);
}
void ClientUserAuthorizer::messageWritten(int message_id)
{
if (state_ == Finished)
return;
emit readMessage();
}
void ClientUserAuthorizer::messageReceived(const QByteArray& buffer)
{
if (state_ == Finished)
return;
proto::auth::HostToClient message;
if (parseMessage(buffer, message))
{
if (message.has_server_challenge())
{
readServerChallenge(message.server_challenge());
return;
}
else if (message.has_logon_result())
{
readLogonResult(message.logon_result());
return;
}
}
emit errorOccurred(tr("Protocol error: Unknown message message from host."));
cancel();
}
void ClientUserAuthorizer::readServerChallenge(
const proto::auth::ServerChallenge& server_challenge)
{
QByteArray nonce = QByteArray(server_challenge.nonce().c_str(),
server_challenge.nonce().size());
if (nonce.isEmpty())
{
emit errorOccurred(tr("Authorization error: Empty nonce is not allowed."));
cancel();
return;
}
if (username_.isEmpty() || password_.isEmpty())
{
AuthorizationDialog dialog;
dialog.setUserName(username_);
dialog.setPassword(password_);
if (dialog.exec() == AuthorizationDialog::Rejected)
{
emit errorOccurred(tr("Authorization is canceled by the user."));
cancel();
return;
}
username_ = dialog.userName();
password_ = dialog.password();
}
QByteArray session_key = createSessionKey(createPasswordHash(password_), nonce);
proto::auth::ClientToHost message;
proto::auth::ClientChallenge* client_challenge = message.mutable_client_challenge();
client_challenge->set_session_type(session_type_);
client_challenge->set_username(username_.toStdString());
client_challenge->set_session_key(session_key.constData(), session_key.size());
secureMemZero(&session_key);
QByteArray serialized_message = serializeMessage(message);
secureMemZero(client_challenge->mutable_username());
secureMemZero(client_challenge->mutable_session_key());
emit writeMessage(ClientChallenge, serialized_message);
secureMemZero(&serialized_message);
}
void ClientUserAuthorizer::readLogonResult(const proto::auth::LogonResult& logon_result)
{
state_ = Finished;
emit finished(logon_result.status());
}
} // namespace aspia
<commit_msg>- Set parent for authorization dialog.<commit_after>//
// PROJECT: Aspia
// FILE: client/client_user_authorizer.cc
// LICENSE: GNU General Public License 3
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "client/client_user_authorizer.h"
#include <QCryptographicHash>
#include <QDebug>
#include "base/message_serialization.h"
#include "client/ui/authorization_dialog.h"
#include "crypto/secure_memory.h"
namespace aspia {
namespace {
const quint32 kKeyHashingRounds = 100000;
const quint32 kPasswordHashingRounds = 100000;
enum MessageId { LogonRequest, ClientChallenge };
QByteArray createPasswordHash(const QString& password)
{
QByteArray data = password.toUtf8();
for (int i = 0; i < kPasswordHashingRounds; ++i)
{
data = QCryptographicHash::hash(data, QCryptographicHash::Sha512);
}
return data;
}
QByteArray createSessionKey(const QByteArray& password_hash, const QByteArray& nonce)
{
QByteArray data = password_hash;
for (quint32 i = 0; i < kKeyHashingRounds; ++i)
{
QCryptographicHash hash(QCryptographicHash::Sha512);
hash.addData(data);
hash.addData(nonce);
data = hash.result();
}
return data;
}
} // namespace
ClientUserAuthorizer::ClientUserAuthorizer(QWidget* parent)
: QObject(parent)
{
// Nothing
}
ClientUserAuthorizer::~ClientUserAuthorizer()
{
secureMemZero(&username_);
secureMemZero(&password_);
cancel();
}
void ClientUserAuthorizer::setSessionType(proto::auth::SessionType session_type)
{
session_type_ = session_type;
}
void ClientUserAuthorizer::setUserName(const QString& username)
{
username_ = username;
}
void ClientUserAuthorizer::setPassword(const QString& password)
{
password_ = password;
}
void ClientUserAuthorizer::start()
{
if (state_ != NotStarted)
{
qWarning("Authorizer already started");
return;
}
proto::auth::ClientToHost message;
// We do not support other authorization methods yet.
message.mutable_logon_request()->set_method(proto::auth::METHOD_BASIC);
state_ = Started;
emit writeMessage(LogonRequest, serializeMessage(message));
}
void ClientUserAuthorizer::cancel()
{
if (state_ == Finished)
return;
state_ = Finished;
emit finished(proto::auth::STATUS_CANCELED);
}
void ClientUserAuthorizer::messageWritten(int message_id)
{
if (state_ == Finished)
return;
emit readMessage();
}
void ClientUserAuthorizer::messageReceived(const QByteArray& buffer)
{
if (state_ == Finished)
return;
proto::auth::HostToClient message;
if (parseMessage(buffer, message))
{
if (message.has_server_challenge())
{
readServerChallenge(message.server_challenge());
return;
}
else if (message.has_logon_result())
{
readLogonResult(message.logon_result());
return;
}
}
emit errorOccurred(tr("Protocol error: Unknown message message from host."));
cancel();
}
void ClientUserAuthorizer::readServerChallenge(
const proto::auth::ServerChallenge& server_challenge)
{
QByteArray nonce = QByteArray(server_challenge.nonce().c_str(),
server_challenge.nonce().size());
if (nonce.isEmpty())
{
emit errorOccurred(tr("Authorization error: Empty nonce is not allowed."));
cancel();
return;
}
if (username_.isEmpty() || password_.isEmpty())
{
AuthorizationDialog dialog(dynamic_cast<QWidget*>(parent()));
dialog.setUserName(username_);
dialog.setPassword(password_);
if (dialog.exec() == AuthorizationDialog::Rejected)
{
emit errorOccurred(tr("Authorization is canceled by the user."));
cancel();
return;
}
username_ = dialog.userName();
password_ = dialog.password();
}
QByteArray session_key = createSessionKey(createPasswordHash(password_), nonce);
proto::auth::ClientToHost message;
proto::auth::ClientChallenge* client_challenge = message.mutable_client_challenge();
client_challenge->set_session_type(session_type_);
client_challenge->set_username(username_.toStdString());
client_challenge->set_session_key(session_key.constData(), session_key.size());
secureMemZero(&session_key);
QByteArray serialized_message = serializeMessage(message);
secureMemZero(client_challenge->mutable_username());
secureMemZero(client_challenge->mutable_session_key());
emit writeMessage(ClientChallenge, serialized_message);
secureMemZero(&serialized_message);
}
void ClientUserAuthorizer::readLogonResult(const proto::auth::LogonResult& logon_result)
{
state_ = Finished;
emit finished(logon_result.status());
}
} // namespace aspia
<|endoftext|>
|
<commit_before>#include "items/inventory.h"
#include "entity_system.h"
#include "dataconsts.h"
#include "random.h"
#include "components/basic_info.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/lua.h"
#include "components/position.h"
#include "components/owner.h"
#include "itemdb.h"
#include "srv_equip_item.h"
#include "srv_set_item.h"
#include "srv_set_money.h"
#include <limits>
using namespace RoseCommon;
using namespace Items;
namespace {
// only for items, not cart/castle gear
inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) {
const auto& item = entitySystem.get_component<ItemDef>(entity);
if (spot >= EquippedPosition::MAX_EQUIP_ITEMS) {
return false;
}
if (spot == 7 && (item.type == 8 || item.type == 9)) {
return true;
}
return item.type == spot;
}
inline bool is_spot_equipped(size_t spot) {
return spot < EquippedPosition::MAX_EQUIP_ITEMS;
}
}
size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
size_t res = decltype(inv.getInventory())::offset();
bool stackable = false;
uint8_t type = 0;
uint16_t id = 0;
if (item != entt::null) {
const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
stackable = i.is_stackable;
type = i.type;
id = i.id;
}
for (const auto item : inv.getInventory()) {
if (item == entt::null) {
return res;
} else if (stackable) {
const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
const auto& it = entitySystem.get_component<Component::Item>(item);
if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) {
return res;
}
}
++res;
}
return 0;
}
ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
const size_t pos = get_first_available_spot(entitySystem, entity, item);
if (pos == 0) {
return ReturnValue::NO_SPACE;
}
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (inv.items[pos] == entt::null) {
inv.items[pos] = item;
} else {
// add the stack
auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]);
auto& it = entitySystem.get_component<Component::Item>(item);
if (i.count + it.count < RoseCommon::MAX_STACK) {
// below max stack
i.count += it.count;
} else {
// split the stack in two or more
const uint32_t stack_tmp1 = i.count;
const uint32_t stack_tmp2 = it.count;
it.count -= RoseCommon::MAX_STACK - i.count;
i.count = RoseCommon::MAX_STACK;
if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) {
it.count = stack_tmp2;
i.count = stack_tmp1;
return ReturnValue::NO_SPACE;
}
}
}
RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
entitySystem.send_to(entity, packet);
return ReturnValue::OK;
}
RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) {
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
RoseCommon::Entity item = inv.items[pos];
auto& i = entitySystem.get_component<Component::Item>(item);
const auto& it = entitySystem.get_component<ItemDef>(item);
if (i.count < quantity) {
return entt::null;
}
if (i.count > quantity) {
const auto type = it.type;
const auto id = it.id;
i.count -= quantity;
RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity);
RoseCommon::Packet::SrvSetItem::IndexAndItem index;
index.set_index(pos);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
entitySystem.send_to(entity, packet);
return newItem;
}
if (is_spot_equipped(pos)) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(item);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_unequip(item)) {
return entt::null;
}
}
}
inv.items[pos] = entt::null;
RoseCommon::Packet::SrvSetItem::IndexAndItem index;
index.set_index(pos);
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
entitySystem.send_to(entity, packet);
return item;
}
void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) {
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
std::swap(inv.items[pos1], inv.items[pos2]);
}
ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) {
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) {
return ReturnValue::WRONG_INDEX;
}
if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) {
return ReturnValue::WRONG_INDEX;
}
const RoseCommon::Entity equipped = inv.items[to];
const RoseCommon::Entity to_equip = inv.items[from];
if (!is_spot_correct(entitySystem, to_equip, to)) {
return ReturnValue::REQUIREMENTS_NOT_MET;
}
if (equipped != entt::null) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_unequip(entity)) {
//return ReturnValue::REQUIREMENTS_NOT_MET;
}
}
}
if (from != entt::null) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_equip(entity)) {
//return ReturnValue::REQUIREMENTS_NOT_MET;
}
}
}
swap_item(entitySystem, entity, from, to);
const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
{
const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to,
entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to]));
entitySystem.send_nearby(entity, packet);
}
RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
index.set_index(from);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
packet.add_items(index);
entitySystem.send_to(entity, packet);
return ReturnValue::OK;
}
ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) {
const size_t to = get_first_available_spot(entitySystem, entity);
if (to == 0) {
return ReturnValue::NO_SPACE;
}
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) {
return ReturnValue::WRONG_INDEX;
}
const RoseCommon::Entity equipped = inv.items[from];
if (equipped != entt::null) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_unequip(entity)) {
//return ReturnValue::REQUIREMENTS_NOT_MET;
}
}
}
swap_item(entitySystem, entity, from, to);
const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
{
const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {});
entitySystem.send_nearby(entity, packet);
}
RoseCommon::Packet::SrvSetItem::IndexAndItem index;
index.set_index(to);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
index.set_index(from);
index.set_item({});
packet.add_items(index);
entitySystem.send_to(entity, packet);
return ReturnValue::OK;
}
void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) {
Component::BasicInfo bi;
bi.id = entitySystem.get_free_id();
if (owner != entt::null) {
const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner);
bi.teamId = basicInfo.teamId;
auto& Cowner = entitySystem.add_component<Component::Owner>(item);
Cowner.owner = owner;
} else {
bi.teamId = bi.id;
}
entitySystem.add_component(item, std::move(bi));
entitySystem.update_position(item, x, y);
entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) {
entitySystem.delete_entity(item);
});
}
bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) {
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (zuly < 0 && inv.zuly + zuly < 0) {
return false;
} else if (zuly < 0) {
inv.zuly += zuly;
} else {
inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly),
static_cast<uint64_t>(std::numeric_limits<int64_t>::max())));
}
entitySystem.send_to(entity,
RoseCommon::Packet::SrvSetMoney::create(inv.zuly));
return true;
}
void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) {
auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
logger->trace("equip_item_packet()");
logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo());
const auto from = packet.get_slotFrom();
const auto to = packet.get_slotTo();
const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag
unequip_item(entitySystem, entity, to):
equip_item(entitySystem, entity, from, to);
(void) res;
}
void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) {
auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
logger->trace("equip_item_packet()");
logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity());
const auto index = packet.get_index();
const auto quantity = packet.get_quantity();
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (index > inv.items.size()) {
logger->warn("wrong index {} for item drop, client {}", index, entity);
return;
}
RoseCommon::Entity item = entt::null;
if (index == 0) { // we drop zulies
if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) {
item = entitySystem.create_zuly(packet.get_quantity());
} else {
return; // we don't have enough zuly to remove
}
} else {
item = remove_item(entitySystem, entity, index, quantity);
}
const auto& pos = entitySystem.get_component<Component::Position>(entity);
const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE);
drop_item(entitySystem, item, x, y, entity);
}
<commit_msg>Update inventory.cpp<commit_after>#include "items/inventory.h"
#include "entity_system.h"
#include "dataconsts.h"
#include "random.h"
#include "components/basic_info.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/lua.h"
#include "components/position.h"
#include "components/owner.h"
#include "itemdb.h"
#include "srv_equip_item.h"
#include "srv_set_item.h"
#include "srv_set_money.h"
#include <limits>
using namespace RoseCommon;
using namespace Items;
namespace {
// only for items, not cart/castle gear
inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) {
const auto& item = entitySystem.get_component<ItemDef>(entity);
const EquippedPosition pos = static_cast<EquippedPosition>(spot);
if (pos >= EquippedPosition::MAX_EQUIP_ITEMS) {
return true; // we don't care of the spot if we are not equipping anything
}
const EquippedPosition
switch (item.type) {
case ItemType::GOGGLES:
return pos == EquippedPosition::GOGGLES;
case ItemType::HELMET:
return pos == EquippedPosition::HELMET;
case ItemType::ARMOR:
return pos == EquippedPosition::ARMOR;
case ItemType::GAUNTLET:
return pos == EquippedPosition::GAUNTLET;
case ItemType::BOOTS:
return pos == EquippedPosition::BOOTS;
case ItemType::BACKPACK:
return pos == EquippedPosition::BACKPACK;
case ItemType::RING:
return pos == EquippedPosition::RING;
case ItemType::WEAPON_R:
return pos == EquippedPosition::WEAPON_R;
case ItemType::WEAPON_L:
return pos == EquippedPosition::WEAPON_L;
default:
return false;
}
}
inline bool is_spot_equipped(size_t spot) {
return spot < EquippedPosition::MAX_EQUIP_ITEMS;
}
}
size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
size_t res = decltype(inv.getInventory())::offset();
bool stackable = false;
uint8_t type = 0;
uint16_t id = 0;
if (item != entt::null) {
const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
stackable = i.is_stackable;
type = i.type;
id = i.id;
}
for (const auto item : inv.getInventory()) {
if (item == entt::null) {
return res;
} else if (stackable) {
const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
const auto& it = entitySystem.get_component<Component::Item>(item);
if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) {
return res;
}
}
++res;
}
return 0;
}
ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
const size_t pos = get_first_available_spot(entitySystem, entity, item);
if (pos == 0) {
return ReturnValue::NO_SPACE;
}
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (inv.items[pos] == entt::null) {
inv.items[pos] = item;
} else {
// add the stack
auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]);
auto& it = entitySystem.get_component<Component::Item>(item);
if (i.count + it.count < RoseCommon::MAX_STACK) {
// below max stack
i.count += it.count;
} else {
// split the stack in two or more
const uint32_t stack_tmp1 = i.count;
const uint32_t stack_tmp2 = it.count;
it.count -= RoseCommon::MAX_STACK - i.count;
i.count = RoseCommon::MAX_STACK;
if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) {
it.count = stack_tmp2;
i.count = stack_tmp1;
return ReturnValue::NO_SPACE;
}
}
}
RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
entitySystem.send_to(entity, packet);
return ReturnValue::OK;
}
RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) {
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
RoseCommon::Entity item = inv.items[pos];
auto& i = entitySystem.get_component<Component::Item>(item);
const auto& it = entitySystem.get_component<ItemDef>(item);
if (i.count < quantity) {
return entt::null;
}
if (i.count > quantity) {
const auto type = it.type;
const auto id = it.id;
i.count -= quantity;
RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity);
RoseCommon::Packet::SrvSetItem::IndexAndItem index;
index.set_index(pos);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
entitySystem.send_to(entity, packet);
return newItem;
}
if (is_spot_equipped(pos)) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(item);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_unequip(item)) {
return entt::null;
}
}
}
inv.items[pos] = entt::null;
RoseCommon::Packet::SrvSetItem::IndexAndItem index;
index.set_index(pos);
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
entitySystem.send_to(entity, packet);
return item;
}
void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) {
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
std::swap(inv.items[pos1], inv.items[pos2]);
}
ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) {
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) {
return ReturnValue::WRONG_INDEX;
}
if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) {
return ReturnValue::WRONG_INDEX;
}
const RoseCommon::Entity equipped = inv.items[to];
const RoseCommon::Entity to_equip = inv.items[from];
if (!is_spot_correct(entitySystem, to_equip, to)) {
return ReturnValue::REQUIREMENTS_NOT_MET;
}
if (equipped != entt::null) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_unequip(entity)) {
//return ReturnValue::REQUIREMENTS_NOT_MET;
}
}
}
if (from != entt::null) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_equip(entity)) {
//return ReturnValue::REQUIREMENTS_NOT_MET;
}
}
}
swap_item(entitySystem, entity, from, to);
const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
{
const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to,
entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to]));
entitySystem.send_nearby(entity, packet);
}
RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
index.set_index(from);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
packet.add_items(index);
entitySystem.send_to(entity, packet);
return ReturnValue::OK;
}
ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) {
const size_t to = get_first_available_spot(entitySystem, entity);
if (to == 0) {
return ReturnValue::NO_SPACE;
}
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) {
return ReturnValue::WRONG_INDEX;
}
const RoseCommon::Entity equipped = inv.items[from];
if (equipped != entt::null) {
const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
if (const auto tmp = lua.api.lock(); tmp) {
if (!tmp->on_unequip(entity)) {
//return ReturnValue::REQUIREMENTS_NOT_MET;
}
}
}
swap_item(entitySystem, entity, from, to);
const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
{
const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {});
entitySystem.send_nearby(entity, packet);
}
RoseCommon::Packet::SrvSetItem::IndexAndItem index;
index.set_index(to);
index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
auto packet = RoseCommon::Packet::SrvSetItem::create();
packet.add_items(index);
index.set_index(from);
index.set_item({});
packet.add_items(index);
entitySystem.send_to(entity, packet);
return ReturnValue::OK;
}
void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) {
Component::BasicInfo bi;
bi.id = entitySystem.get_free_id();
if (owner != entt::null) {
const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner);
bi.teamId = basicInfo.teamId;
auto& Cowner = entitySystem.add_component<Component::Owner>(item);
Cowner.owner = owner;
} else {
bi.teamId = bi.id;
}
entitySystem.add_component(item, std::move(bi));
entitySystem.update_position(item, x, y);
entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) {
entitySystem.delete_entity(item);
});
}
bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) {
auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (zuly < 0 && inv.zuly + zuly < 0) {
return false;
} else if (zuly < 0) {
inv.zuly += zuly;
} else {
inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly),
static_cast<uint64_t>(std::numeric_limits<int64_t>::max())));
}
entitySystem.send_to(entity,
RoseCommon::Packet::SrvSetMoney::create(inv.zuly));
return true;
}
void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) {
auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
logger->trace("equip_item_packet()");
logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo());
const auto from = packet.get_slotFrom();
const auto to = packet.get_slotTo();
const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag
unequip_item(entitySystem, entity, to):
equip_item(entitySystem, entity, from, to);
(void) res;
}
void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) {
auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
logger->trace("equip_item_packet()");
logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity());
const auto index = packet.get_index();
const auto quantity = packet.get_quantity();
const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
if (index > inv.items.size()) {
logger->warn("wrong index {} for item drop, client {}", index, entity);
return;
}
RoseCommon::Entity item = entt::null;
if (index == 0) { // we drop zulies
if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) {
item = entitySystem.create_zuly(packet.get_quantity());
} else {
return; // we don't have enough zuly to remove
}
} else {
item = remove_item(entitySystem, entity, index, quantity);
}
const auto& pos = entitySystem.get_component<Component::Position>(entity);
const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE);
drop_item(entitySystem, item, x, y, entity);
}
<|endoftext|>
|
<commit_before>#include <Plugins/RenderPlugin.h>
#include <dlfcn.h>
IMPGEARS_BEGIN
std::map<RenderPlugin::Ptr,void*> PluginManager::_handlers;
//--------------------------------------------------------------
RenderPlugin::Ptr PluginManager::open(const std::string& name)
{
RenderPlugin::Ptr result;
void* handler = dlopen(name.c_str(),RTLD_LAZY);
if(handler == nullptr)
{
std::cout << "error dlopen : " << dlerror() << std::endl;
return result;
}
LoadFunc func = (LoadFunc)dlsym(handler, "loadRenderPlugin");
if (func == NULL)
{
std::cout << "error dlsym : " << dlerror() << std::endl;
dlclose(handler);
return result;
}
result = func();
_handlers[result] = handler;
return result;
}
//--------------------------------------------------------------
void PluginManager::close(RenderPlugin::Ptr& plugin)
{
void* handler = _handlers[plugin];
dlclose(handler);
_handlers.erase(plugin);
}
IMPGEARS_END
<commit_msg>fix plugin loading error<commit_after>#include <Plugins/RenderPlugin.h>
#include <dlfcn.h>
IMPGEARS_BEGIN
std::map<RenderPlugin::Ptr,void*> PluginManager::_handlers;
//--------------------------------------------------------------
RenderPlugin::Ptr PluginManager::open(const std::string& name)
{
RenderPlugin::Ptr result;
// void* handler = dlopen(name.c_str(),RTLD_LAZY);
void* handler = dlopen(name.c_str(),RTLD_NOW);
if(handler == nullptr)
{
std::cout << "error dlopen : " << dlerror() << std::endl;
return result;
}
LoadFunc func = (LoadFunc)dlsym(handler, "loadRenderPlugin");
if (func == NULL)
{
std::cout << "error dlsym : " << dlerror() << std::endl;
dlclose(handler);
return result;
}
result = func();
_handlers[result] = handler;
return result;
}
//--------------------------------------------------------------
void PluginManager::close(RenderPlugin::Ptr& plugin)
{
void* handler = _handlers[plugin];
dlclose(handler);
_handlers.erase(plugin);
}
IMPGEARS_END
<|endoftext|>
|
<commit_before>//
// PROJECT: Aspia Remote Desktop
// FILE: host/console_session_launcher.cc
// LICENSE: Mozilla Public License Version 2.0
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "host/console_session_launcher.h"
#include <userenv.h>
#include <string>
#include "base/process/process_helpers.h"
#include "base/service_manager.h"
#include "base/scoped_object.h"
#include "base/scoped_impersonator.h"
#include "base/files/base_paths.h"
#include "base/logging.h"
namespace aspia {
static const WCHAR kServiceShortName[] = L"aspia-desktop-session-launcher";
static const WCHAR kServiceFullName[] = L"Aspia Desktop Session Launcher";
// Name of the default session desktop.
static WCHAR kDefaultDesktopName[] = L"winsta0\\default";
ConsoleSessionLauncher::ConsoleSessionLauncher(const std::wstring& service_id)
: Service(ServiceManager::CreateUniqueServiceName(
kServiceShortName, service_id))
{
// Nothing
}
static bool CopyProcessToken(DWORD desired_access, ScopedHandle& token_out)
{
ScopedHandle process_token;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_DUPLICATE | desired_access,
process_token.Recieve()))
{
LOG(ERROR) << "OpenProcessToken() failed: "
<< GetLastSystemErrorString();
return false;
}
if (!DuplicateTokenEx(process_token,
desired_access,
nullptr,
SecurityImpersonation,
TokenPrimary,
token_out.Recieve()))
{
LOG(ERROR) << "DuplicateTokenEx() failed: "
<< GetLastSystemErrorString();
return false;
}
return true;
}
// Creates a copy of the current process with SE_TCB_NAME privilege enabled.
static bool CreatePrivilegedToken(ScopedHandle& token_out)
{
ScopedHandle privileged_token;
DWORD desired_access = TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE |
TOKEN_DUPLICATE | TOKEN_QUERY;
if (!CopyProcessToken(desired_access, privileged_token))
return false;
// Get the LUID for the SE_TCB_NAME privilege.
TOKEN_PRIVILEGES state;
state.PrivilegeCount = 1;
state.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!LookupPrivilegeValueW(nullptr, SE_TCB_NAME,
&state.Privileges[0].Luid))
{
LOG(ERROR) << "LookupPrivilegeValueW() failed: "
<< GetLastSystemErrorString();
return false;
}
// Enable the SE_TCB_NAME privilege.
if (!AdjustTokenPrivileges(privileged_token, FALSE, &state, 0,
nullptr, nullptr))
{
LOG(ERROR) << "AdjustTokenPrivileges() failed: "
<< GetLastSystemErrorString();
return false;
}
token_out.Reset(privileged_token.Release());
return true;
}
// Creates a copy of the current process token for the given |session_id| so
// it can be used to launch a process in that session.
static bool CreateSessionToken(uint32_t session_id, ScopedHandle& token_out)
{
ScopedHandle session_token;
DWORD desired_access = TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID |
TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY;
if (!CopyProcessToken(desired_access, session_token))
return false;
ScopedHandle privileged_token;
if (!CreatePrivilegedToken(privileged_token))
return false;
{
ScopedImpersonator impersonator;
if (!impersonator.ImpersonateLoggedOnUser(privileged_token))
return false;
// Change the session ID of the token.
DWORD new_session_id = session_id;
if (!SetTokenInformation(session_token,
TokenSessionId,
&new_session_id,
sizeof(new_session_id)))
{
LOG(ERROR) << "SetTokenInformation() failed: "
<< GetLastSystemErrorString();
return false;
}
}
token_out.Reset(session_token.Release());
return true;
}
static bool CreateProcessWithToken(HANDLE user_token,
const std::wstring& command_line)
{
PROCESS_INFORMATION process_info = { 0 };
STARTUPINFOW startup_info = { 0 };
startup_info.cb = sizeof(startup_info);
startup_info.lpDesktop = kDefaultDesktopName;
if (!CreateProcessAsUserW(user_token,
nullptr,
const_cast<LPWSTR>(command_line.c_str()),
nullptr,
nullptr,
FALSE,
0,
nullptr,
nullptr,
&startup_info,
&process_info))
{
LOG(ERROR) << "CreateProcessAsUserW() failed: "
<< GetLastSystemErrorString();
return false;
}
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
return true;
}
static bool CreateCommandLine(const std::wstring& run_mode,
const std::wstring& channel_id,
std::wstring& command_line)
{
FilePath path;
if (!GetBasePath(BasePathKey::FILE_EXE, path))
return false;
command_line.assign(path);
command_line.append(L" --run_mode=");
command_line.append(run_mode);
command_line.append(L" --channel_id=");
command_line.append(channel_id);
return true;
}
static bool LaunchProcessInSession(const std::wstring& run_mode,
uint32_t session_id,
const std::wstring& channel_id)
{
std::wstring command_line;
if (!CreateCommandLine(run_mode, channel_id, command_line))
return false;
ScopedHandle session_token;
if (!CreateSessionToken(session_id, session_token))
return false;
return CreateProcessWithToken(session_token, command_line);
}
static bool LaunchProcessWithCurrentRights(const std::wstring& run_mode,
const std::wstring& channel_id)
{
std::wstring command_line;
if (!CreateCommandLine(run_mode, channel_id, command_line))
return false;
ScopedHandle token;
if (!CopyProcessToken(TOKEN_ALL_ACCESS, token))
return false;
return CreateProcessWithToken(token, command_line);
}
static bool LaunchProcessOverService(uint32_t session_id,
const std::wstring& channel_id)
{
std::wstring service_id =
ServiceManager::GenerateUniqueServiceId();
std::wstring unique_short_name =
ServiceManager::CreateUniqueServiceName(kServiceShortName, service_id);
std::wstring unique_full_name =
ServiceManager::CreateUniqueServiceName(kServiceFullName, service_id);
FilePath path;
if (!GetBasePath(BasePathKey::FILE_EXE, path))
return false;
std::wstring command_line;
command_line.assign(path);
command_line.append(L" --channel_id=");
command_line.append(channel_id);
command_line.append(L" --run_mode=");
command_line.append(kDesktopSessionLauncherSwitch);
command_line.append(L" --session_id=");
command_line.append(std::to_wstring(session_id));
command_line.append(L" --service_id=");
command_line.append(service_id);
// Install the service in the system.
std::unique_ptr<ServiceManager> manager =
ServiceManager::Create(command_line,
unique_full_name,
unique_short_name);
// If the service was not installed.
if (!manager)
return false;
return manager->Start();
}
void ConsoleSessionLauncher::Worker()
{
LaunchProcessInSession(kDesktopSessionSwitch,
session_id_,
channel_id_);
}
void ConsoleSessionLauncher::OnStop()
{
// Nothing
}
void ConsoleSessionLauncher::ExecuteService(uint32_t session_id,
const std::wstring& channel_id)
{
session_id_ = session_id;
channel_id_ = channel_id;
Run();
ServiceManager(ServiceName()).Remove();
}
bool LaunchDesktopSession(uint32_t session_id, const std::wstring& channel_id)
{
if (!IsCallerHasAdminRights())
{
return LaunchProcessWithCurrentRights(kDesktopSessionSwitch,
channel_id);
}
if (!IsRunningAsService())
{
return LaunchProcessOverService(session_id, channel_id);
}
// The code is executed from the service.
// Start the process directly.
return LaunchProcessInSession(kDesktopSessionSwitch,
session_id,
channel_id);
}
bool LaunchFileTransferSession(uint32_t session_id,
const std::wstring& channel_id)
{
if (IsRunningAsService())
{
return LaunchProcessInSession(kFileTransferSessionSwitch,
session_id,
channel_id);
}
return LaunchProcessWithCurrentRights(kFileTransferSessionSwitch,
channel_id);
}
} // namespace aspia
<commit_msg>- Launch file transfer host process with the rights of the current console user - Create environment block for host process<commit_after>//
// PROJECT: Aspia Remote Desktop
// FILE: host/console_session_launcher.cc
// LICENSE: Mozilla Public License Version 2.0
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "host/console_session_launcher.h"
#include <userenv.h>
#include <string>
#include "base/process/process_helpers.h"
#include "base/service_manager.h"
#include "base/scoped_native_library.h"
#include "base/scoped_object.h"
#include "base/scoped_impersonator.h"
#include "base/files/base_paths.h"
#include "base/logging.h"
namespace aspia {
static const WCHAR kServiceShortName[] = L"aspia-desktop-session-launcher";
static const WCHAR kServiceFullName[] = L"Aspia Desktop Session Launcher";
// Name of the default session desktop.
static WCHAR kDefaultDesktopName[] = L"winsta0\\default";
ConsoleSessionLauncher::ConsoleSessionLauncher(const std::wstring& service_id)
: Service(ServiceManager::CreateUniqueServiceName(
kServiceShortName, service_id))
{
// Nothing
}
static bool CopyProcessToken(DWORD desired_access, ScopedHandle& token_out)
{
ScopedHandle process_token;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_DUPLICATE | desired_access,
process_token.Recieve()))
{
LOG(ERROR) << "OpenProcessToken() failed: "
<< GetLastSystemErrorString();
return false;
}
if (!DuplicateTokenEx(process_token,
desired_access,
nullptr,
SecurityImpersonation,
TokenPrimary,
token_out.Recieve()))
{
LOG(ERROR) << "DuplicateTokenEx() failed: "
<< GetLastSystemErrorString();
return false;
}
return true;
}
// Creates a copy of the current process with SE_TCB_NAME privilege enabled.
static bool CreatePrivilegedToken(ScopedHandle& token_out)
{
ScopedHandle privileged_token;
DWORD desired_access = TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE |
TOKEN_DUPLICATE | TOKEN_QUERY;
if (!CopyProcessToken(desired_access, privileged_token))
return false;
// Get the LUID for the SE_TCB_NAME privilege.
TOKEN_PRIVILEGES state;
state.PrivilegeCount = 1;
state.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!LookupPrivilegeValueW(nullptr, SE_TCB_NAME,
&state.Privileges[0].Luid))
{
LOG(ERROR) << "LookupPrivilegeValueW() failed: "
<< GetLastSystemErrorString();
return false;
}
// Enable the SE_TCB_NAME privilege.
if (!AdjustTokenPrivileges(privileged_token, FALSE, &state, 0,
nullptr, nullptr))
{
LOG(ERROR) << "AdjustTokenPrivileges() failed: "
<< GetLastSystemErrorString();
return false;
}
token_out.Reset(privileged_token.Release());
return true;
}
// Creates a copy of the current process token for the given |session_id| so
// it can be used to launch a process in that session.
static bool CreateSessionToken(uint32_t session_id, ScopedHandle& token_out)
{
ScopedHandle session_token;
DWORD desired_access = TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID |
TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY;
if (!CopyProcessToken(desired_access, session_token))
return false;
ScopedHandle privileged_token;
if (!CreatePrivilegedToken(privileged_token))
return false;
{
ScopedImpersonator impersonator;
if (!impersonator.ImpersonateLoggedOnUser(privileged_token))
return false;
// Change the session ID of the token.
DWORD new_session_id = session_id;
if (!SetTokenInformation(session_token,
TokenSessionId,
&new_session_id,
sizeof(new_session_id)))
{
LOG(ERROR) << "SetTokenInformation() failed: "
<< GetLastSystemErrorString();
return false;
}
}
token_out.Reset(session_token.Release());
return true;
}
static bool CreateProcessWithToken(HANDLE user_token,
const std::wstring& command_line)
{
PROCESS_INFORMATION process_info = { 0 };
STARTUPINFOW startup_info = { 0 };
startup_info.cb = sizeof(startup_info);
startup_info.lpDesktop = kDefaultDesktopName;
PVOID environment;
if (!CreateEnvironmentBlock(&environment, user_token, FALSE))
{
LOG(ERROR) << "CreateEnvironmentBlock() failed: "
<< GetLastSystemErrorString();
return false;
}
if (!CreateProcessAsUserW(user_token,
nullptr,
const_cast<LPWSTR>(command_line.c_str()),
nullptr,
nullptr,
FALSE,
CREATE_UNICODE_ENVIRONMENT,
environment,
nullptr,
&startup_info,
&process_info))
{
LOG(ERROR) << "CreateProcessAsUserW() failed: "
<< GetLastSystemErrorString();
DestroyEnvironmentBlock(environment);
return false;
}
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
DestroyEnvironmentBlock(environment);
return true;
}
static bool CreateCommandLine(const std::wstring& run_mode,
const std::wstring& channel_id,
std::wstring& command_line)
{
FilePath path;
if (!GetBasePath(BasePathKey::FILE_EXE, path))
return false;
command_line.assign(path);
command_line.append(L" --run_mode=");
command_line.append(run_mode);
command_line.append(L" --channel_id=");
command_line.append(channel_id);
return true;
}
static bool LaunchProcessInSession(const std::wstring& run_mode,
uint32_t session_id,
const std::wstring& channel_id)
{
std::wstring command_line;
if (!CreateCommandLine(run_mode, channel_id, command_line))
return false;
ScopedHandle session_token;
if (!CreateSessionToken(session_id, session_token))
return false;
return CreateProcessWithToken(session_token, command_line);
}
static bool LaunchProcessWithCurrentRights(const std::wstring& run_mode,
const std::wstring& channel_id)
{
std::wstring command_line;
if (!CreateCommandLine(run_mode, channel_id, command_line))
return false;
ScopedHandle token;
if (!CopyProcessToken(TOKEN_ALL_ACCESS, token))
return false;
return CreateProcessWithToken(token, command_line);
}
static bool LaunchProcessOverService(uint32_t session_id,
const std::wstring& channel_id)
{
std::wstring service_id =
ServiceManager::GenerateUniqueServiceId();
std::wstring unique_short_name =
ServiceManager::CreateUniqueServiceName(kServiceShortName, service_id);
std::wstring unique_full_name =
ServiceManager::CreateUniqueServiceName(kServiceFullName, service_id);
FilePath path;
if (!GetBasePath(BasePathKey::FILE_EXE, path))
return false;
std::wstring command_line;
command_line.assign(path);
command_line.append(L" --channel_id=");
command_line.append(channel_id);
command_line.append(L" --run_mode=");
command_line.append(kDesktopSessionLauncherSwitch);
command_line.append(L" --session_id=");
command_line.append(std::to_wstring(session_id));
command_line.append(L" --service_id=");
command_line.append(service_id);
// Install the service in the system.
std::unique_ptr<ServiceManager> manager =
ServiceManager::Create(command_line,
unique_full_name,
unique_short_name);
// If the service was not installed.
if (!manager)
return false;
return manager->Start();
}
void ConsoleSessionLauncher::Worker()
{
LaunchProcessInSession(kDesktopSessionSwitch,
session_id_,
channel_id_);
}
void ConsoleSessionLauncher::OnStop()
{
// Nothing
}
void ConsoleSessionLauncher::ExecuteService(uint32_t session_id,
const std::wstring& channel_id)
{
session_id_ = session_id;
channel_id_ = channel_id;
Run();
ServiceManager(ServiceName()).Remove();
}
bool LaunchDesktopSession(uint32_t session_id, const std::wstring& channel_id)
{
if (!IsCallerHasAdminRights())
{
return LaunchProcessWithCurrentRights(kDesktopSessionSwitch,
channel_id);
}
if (!IsRunningAsService())
{
return LaunchProcessOverService(session_id, channel_id);
}
// The code is executed from the service.
// Start the process directly.
return LaunchProcessInSession(kDesktopSessionSwitch,
session_id,
channel_id);
}
bool LaunchFileTransferSession(uint32_t session_id,
const std::wstring& channel_id)
{
if (IsRunningAsService())
{
ScopedHandle privileged_token;
if (!CreatePrivilegedToken(privileged_token))
return false;
ScopedNativeLibrary wtsapi32_library(L"wtsapi32.dll");
typedef BOOL(WINAPI * WTSQueryUserTokenFunc)(ULONG, PHANDLE);
WTSQueryUserTokenFunc query_user_token_func =
reinterpret_cast<WTSQueryUserTokenFunc>(
wtsapi32_library.GetFunctionPointer("WTSQueryUserToken"));
if (!query_user_token_func)
{
LOG(ERROR) << "WTSQueryUserToken function not found in wtsapi32.dll";
return false;
}
ScopedHandle session_token;
{
ScopedImpersonator impersonator;
if (!impersonator.ImpersonateLoggedOnUser(privileged_token))
return false;
if (!query_user_token_func(session_id,
session_token.Recieve()))
{
LOG(ERROR) << "WTSQueryUserToken() failed: "
<< GetLastSystemErrorString();
return false;
}
}
std::wstring command_line;
if (!CreateCommandLine(kFileTransferSessionSwitch,
channel_id, command_line))
return false;
return CreateProcessWithToken(session_token, command_line);
}
return LaunchProcessWithCurrentRights(kFileTransferSessionSwitch,
channel_id);
}
} // namespace aspia
<|endoftext|>
|
<commit_before>/*
*/
#include"ioprocesses.hpp"
#include<stdexcept>
#include<ev++.h>
#include<unistd.h>
#include<fcntl.h>
#include<string>
class PortData {
public:
int fd;
PortData(int nfd) : fd(nfd) {}
};
class EvCentralIO : public CentralIO {
private:
void getall(CentralIOToDo todo) {
while(!todo.empty()) {
IOAction io = todo.get();
switch(io.action) {
case ioaction_stdin:
io.port.reset(new PortData(STDIN_FILENO));
todo.respond(io);
break;
case ioaction_stdout:
io.port.reset(new PortData(STDOUT_FILENO));
todo.respond(io);
break;
case ioaction_stderr:
io.port.reset(new PortData(STDERR_FILENO));
todo.respond(io);
break;
case ioaction_read:
case ioaction_write:
default:
todo.error(io, std::string("not implemented"));
}
}
}
public:
void poll(CentralIOToDo todo) {
getall(todo);
ev_loop(ev_default_loop(0), EVLOOP_NONBLOCK);
}
void wait(CentralIOToDo todo) {
getall(todo);
ev_loop(ev_default_loop(0), EVLOOP_ONESHOT);
}
virtual ~EvCentralIO(){}
};
CentralIO* NewCentralIO(void) {
struct ev_loop* evloop = ev_default_loop(EVFLAG_AUTO);
if(!evloop) {
throw std::runtime_error("Unable to initialize libev");
}
return new EvCentralIO();
}
<commit_msg>centralio/ev: added reading handling functions, changed stdi/o/err handlers<commit_after>/*
*/
#include"ioprocesses.hpp"
#include<stdexcept>
#include<ev++.h>
#include<unistd.h>
#include<fcntl.h>
#include<string>
#include<boost/scoped_ptr.hpp>
#include<vector>
const size_t READ_SIZE;
class PortData {
public:
int fd;
boost::scoped_ptr<ev::io> iop;
IOAction ioa;
CentralIOToDo todo;
PortData(int nfd, int events) : fd(nfd), iop(new ev::io), ioap() {
iop->set(nfd, events);
}
bool check_select(int typ) {
/*TODO*/
}
void do_read(ev::io& w, int revents) {
/*now attempt the read*/
/*first use a select() to check: the event loop
might falsely trigger
*/
if((revents & ev::READ) && check_select(ev::READ)) {
/*now attempt a read*/
ioa.data.reset(
new std::vector<unsigned char>(READ_SIZE));
ssize_t rv = read(fd, io.data->begin(), READ_SIZE);
if(rv < 0) {
/*potential errors*/
switch(errno) {
/*ignore these*/
case EAGAIN:
case EINTR:
return;
break;
case EBADF:
todo.err(ioa, "not valid, or not "
"open for reading");
break;
case EFAULT:
todo.err(ioa, "internal error, buffer "
"misallocated");
break;
case EINVAL:
todo.err(ioa, "unsuitable for "
"reading");
break;
case EIO:
todo.err(ioa, "low-level i/o error");
break;
default:
todo.err(ioa, "unknown error type");
break;
}
} else if(rv == 0) {
todo.eof(ioa);
} else {
ioa.data->resize(rv);
todo.respond(ioa);
}
w.stop();
}
}
void do_write(ev::io& w, int revents) {
}
};
boost::shared_ptr<PortData> pd_stdin;
boost::shared_ptr<PortData> pd_stdout;
boost::shared_ptr<PortData> pd_stderr;
class EvCentralIO : public CentralIO {
private:
void getall(CentralIOToDo todo) {
while(!todo.empty()) {
IOAction io = todo.get();
switch(io.action) {
case ioaction_stdin:
if(!pd_stdin) {
pd_stdin.reset(
new PortData(STDIN_FILENO,
ev::READ));
}
io.port = pd_stdin;
todo.respond(io);
break;
case ioaction_stdout:
if(!pd_stdout) {
pd_stdout.reset(
new PortData(STDOUT_FILENO,
ev::WRITE));
}
io.port = pd_stdout;
todo.respond(io);
break;
case ioaction_stderr:
if(!pd_stderr) {
pd_stderr.reset(
new PortData(STDERR_FILENO,
ev::WRITE));
}
io.port = pd_stderr;
todo.respond(io);
break;
case ioaction_read:
PortData& port = *io.port;
port.ioa = io;
port.todo = todo;
port.iop->set<PortData, &PortData::do_read>(
&port);
port.iop->start();
break;
case ioaction_write:
default:
todo.error(io, std::string("not implemented"));
}
}
}
public:
void poll(CentralIOToDo todo) {
getall(todo);
ev_loop(ev_default_loop(0), EVLOOP_NONBLOCK);
}
void wait(CentralIOToDo todo) {
getall(todo);
ev_loop(ev_default_loop(0), EVLOOP_ONESHOT);
}
bool empty(void) const {
/*TODO*/
return 0;
}
virtual ~EvCentralIO(){}
};
CentralIO* NewCentralIO(void) {
struct ev_loop* evloop = ev_default_loop(EVFLAG_AUTO);
if(!evloop) {
throw std::runtime_error("Unable to initialize libev");
}
return new EvCentralIO();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZipPackageFolderEnumeration.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:18:30 $
*
* 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 _ZIP_PACKAGE_FOLDER_ENUMERATION_HXX
#include <ZipPackageFolderEnumeration.hxx>
#endif
#ifndef _CONTENT_INFO_HXX_
#include <ContentInfo.hxx>
#endif
using namespace com::sun::star;
using rtl::OUString;
ZipPackageFolderEnumeration::ZipPackageFolderEnumeration ( ContentHash &rInput)
: rContents (rInput)
, aIterator (rContents.begin())
{
}
ZipPackageFolderEnumeration::~ZipPackageFolderEnumeration( void )
{
}
sal_Bool SAL_CALL ZipPackageFolderEnumeration::hasMoreElements( )
throw(uno::RuntimeException)
{
return (aIterator != rContents.end() );
}
uno::Any SAL_CALL ZipPackageFolderEnumeration::nextElement( )
throw(container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
uno::Any aAny;
if (aIterator == rContents.end() )
throw container::NoSuchElementException();
aAny <<= (*aIterator).second->xTunnel;
aIterator++;
return aAny;
}
OUString ZipPackageFolderEnumeration::getImplementationName()
throw (uno::RuntimeException)
{
return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "ZipPackageFolderEnumeration" ) );
}
uno::Sequence< OUString > ZipPackageFolderEnumeration::getSupportedServiceNames()
throw (uno::RuntimeException)
{
uno::Sequence< OUString > aNames(1);
aNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.packages.PackageFolderEnumeration" ) );
return aNames;
}
sal_Bool SAL_CALL ZipPackageFolderEnumeration::supportsService( OUString const & rServiceName )
throw (uno::RuntimeException)
{
return rServiceName == getSupportedServiceNames()[0];
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.44); FILE MERGED 2006/09/01 17:32:43 kaib 1.11.44.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZipPackageFolderEnumeration.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-17 17:29:38 $
*
* 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_package.hxx"
#ifndef _ZIP_PACKAGE_FOLDER_ENUMERATION_HXX
#include <ZipPackageFolderEnumeration.hxx>
#endif
#ifndef _CONTENT_INFO_HXX_
#include <ContentInfo.hxx>
#endif
using namespace com::sun::star;
using rtl::OUString;
ZipPackageFolderEnumeration::ZipPackageFolderEnumeration ( ContentHash &rInput)
: rContents (rInput)
, aIterator (rContents.begin())
{
}
ZipPackageFolderEnumeration::~ZipPackageFolderEnumeration( void )
{
}
sal_Bool SAL_CALL ZipPackageFolderEnumeration::hasMoreElements( )
throw(uno::RuntimeException)
{
return (aIterator != rContents.end() );
}
uno::Any SAL_CALL ZipPackageFolderEnumeration::nextElement( )
throw(container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
uno::Any aAny;
if (aIterator == rContents.end() )
throw container::NoSuchElementException();
aAny <<= (*aIterator).second->xTunnel;
aIterator++;
return aAny;
}
OUString ZipPackageFolderEnumeration::getImplementationName()
throw (uno::RuntimeException)
{
return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "ZipPackageFolderEnumeration" ) );
}
uno::Sequence< OUString > ZipPackageFolderEnumeration::getSupportedServiceNames()
throw (uno::RuntimeException)
{
uno::Sequence< OUString > aNames(1);
aNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.packages.PackageFolderEnumeration" ) );
return aNames;
}
sal_Bool SAL_CALL ZipPackageFolderEnumeration::supportsService( OUString const & rServiceName )
throw (uno::RuntimeException)
{
return rServiceName == getSupportedServiceNames()[0];
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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 WEBSOCKET_BINARY_MESSAGE_HPP
#define WEBSOCKET_BINARY_MESSAGE_HPP
namespace websocketpp {
namespace message {
class binary_message : public basic_message {
public:
binary_message() {
m_payload.reserve(SIZE_INIT);
}
uint64_t process_payload(std::istream& input,uint64_t size) {
char c;
const uint64_t new_size = m_payload.size() + size;
if (new_size > SIZE_MAX) {
// TODO: real exception
throw "message too big exception";
}
if (new_size > m_payload.capacity()) {
m_payload.reserve(max(new_size,2*m_payload.capacity()));
}
for (uint64_t i = 0; i < size; ++i) {
if (input.good()) {
c = input.get();
} else if (input.eof()) {
break;
} else {
// istream read error? throw?
throw "TODO: fix";
}
if (input.good()) {
// process c
if (m_masking_key) {
c = c ^ m_masking_key[m_masking_index++%4];
}
// add c to payload
m_payload.push_back(c);
} else if (input.eof()) {
break;
} else {
// istream read error? throw?
throw "TODO: fix";
}
}
// successfully read all bytes
return i;
}
void reset(opcode::value opcode, uint32_t masking_key) {
m_opcode = opcode;
m_masking_key = masking_key;
m_masking_index = 0;
m_payload.resize(0);
}
private:
static const uint64_t SIZE_INIT = 1000000; // 1MB
static const uint64_t SIZE_MAX = 100000000;// 100MB
uint32_t m_masking_key;
int m_masking_index;
std::vector<unsigned char> m_payload;
};
} // namespace message
} // namespace websocketpp
#endif // WEBSOCKET_BINARY_MESSAGE_HPP<commit_msg>removes old files<commit_after><|endoftext|>
|
<commit_before>#ifndef NEK_ANY_ANY_HPP
#define NEK_ANY_ANY_HPP
#include <nek/any/any_fwd.hpp>
#include <nek/any/exception.hpp>
#include <nek/type_traits/is_reference.hpp>
#include <nek/type_traits/remove_reference.hpp>
#include <nek/utility/swap.hpp>
namespace nek
{
class any
{
public:
any()
: held_(nullptr)
{
}
template <class T>
any(const T& value)
: held_(new holder<T>(value))
{
}
any(const any& right)
: held_(right.held_ ? right.held_->clone() : nullptr)
{
}
~any()
{
delete held_;
held_ = nullptr;
}
any& operator=(const any& right)
{
any(right).swap(*this);
return *this;
}
template <class T>
any& operator=(const T& value)
{
any(value).swap(*this);
return *this;
}
any& swap(any& right)
{
using nek::swap;
swap(held_, right.held_);
return *this;
}
bool is_empty() const
{
return !held_;
}
bool empty() const
{
return is_empty();
}
const type_info& type() const
{
return held_ ? held_->type() : typeid(void);
}
private:
class holder_base
{
public:
virtual ~holder_base()
{
}
virtual holder_base* clone() const = 0;
virtual const std::type_info& type() const = 0;
};
template <class T>
class holder
: public holder_base
{
public:
holder(const T& value)
: value_(value)
{
}
holder_base* clone() const override
{
return new holder(value_);
}
const std::type_info& type() const override
{
return typeid(value_);
}
T value_;
private:
holder& operator=(const holder&);
};
holder_base* held_;
private:
template <class T>
friend T* any_cast(any* pointer);
};
inline void swap(any& left, any& right)
{
left.swap(right);
}
template <class T>
T* any_cast(any* pointer)
{
return pointer && pointer->type() == typeid(T) ?
&(static_cast<any::holder<T>*>(pointer->held_)->value_) : nullptr;
}
template <class T>
inline const T* any_cast(const any* pointer)
{
return any_cast<T>(const_cast<any*>(pointer));
}
template <class T>
T any_cast(any& value)
{
typedef typename remove_reference<T>::type nonref_type;
static_assert(!is_reference<nonref_type>::value, "nek::any_cast : !is_reference<nonref_type>::value");
nonref_type* result = any_cast<nonref_type>(&value);
if (!result)
{
throw bad_any_cast_exception();
}
return *result;
}
template <class T>
inline T any_cast(const any& value)
{
typedef typename remove_reference<T>::type nonref_type;
static_assert(!is_reference<nonref_type>::value, "nek::any_cast : !is_reference<nonref_type>::value");
return any_cast<const nonref_type&>(const_cast<any&>(value));
}
}
#endif<commit_msg>support C++11/14 of VC12<commit_after>#ifndef NEK_ANY_ANY_HPP
#define NEK_ANY_ANY_HPP
#include <nek/any/any_fwd.hpp>
#include <nek/any/exception.hpp>
#include <nek/type_traits/is_reference.hpp>
#include <nek/type_traits/remove_reference.hpp>
#include <nek/utility/swap.hpp>
namespace nek
{
class any
{
public:
any() = default;
template <class T>
any(const T& value)
: held_(new holder<T>(value))
{
}
any(const any& right)
: held_(right.held_ ? right.held_->clone() : nullptr)
{
}
~any()
{
delete held_;
held_ = nullptr;
}
any& operator=(const any& right)
{
any(right).swap(*this);
return *this;
}
template <class T>
any& operator=(const T& value)
{
any(value).swap(*this);
return *this;
}
any& swap(any& right)
{
using nek::swap;
swap(held_, right.held_);
return *this;
}
bool is_empty() const
{
return !held_;
}
bool empty() const
{
return is_empty();
}
const type_info& type() const
{
return held_ ? held_->type() : typeid(void);
}
private:
class holder_base
{
public:
virtual ~holder_base()
{
}
virtual holder_base* clone() const = 0;
virtual const std::type_info& type() const = 0;
};
template <class T>
class holder
: public holder_base
{
public:
holder(const T& value)
: value_(value)
{
}
holder_base* clone() const override
{
return new holder(value_);
}
const std::type_info& type() const override
{
return typeid(value_);
}
T value_;
private:
holder& operator=(const holder&);
};
holder_base* held_ = nullptr;
private:
template <class T>
friend T* any_cast(any* pointer);
};
inline void swap(any& left, any& right)
{
left.swap(right);
}
template <class T>
T* any_cast(any* pointer)
{
return pointer && pointer->type() == typeid(T) ?
&(static_cast<any::holder<T>*>(pointer->held_)->value_) : nullptr;
}
template <class T>
inline const T* any_cast(const any* pointer)
{
return any_cast<T>(const_cast<any*>(pointer));
}
template <class T>
T any_cast(any& value)
{
typedef typename remove_reference<T>::type nonref_type;
static_assert(!is_reference<nonref_type>::value, "nek::any_cast : !is_reference<nonref_type>::value");
nonref_type* result = any_cast<nonref_type>(&value);
if (!result)
{
throw bad_any_cast_exception();
}
return *result;
}
template <class T>
inline T any_cast(const any& value)
{
typedef typename remove_reference<T>::type nonref_type;
static_assert(!is_reference<nonref_type>::value, "nek::any_cast : !is_reference<nonref_type>::value");
return any_cast<const nonref_type&>(const_cast<any&>(value));
}
}
#endif<|endoftext|>
|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
// - required
parpars.registerParameter("i_dcd", "input dcd-file", INFILE, true);
parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output dcd-file name for first solution ", STRING, true, "", true);
parpars.registerParameter("o_id", "output id ", STRING, true, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution ", STRING, true, "", true);
parpars.registerParameter("o_dcd", "output directory for the reduced cluster set (one structure per final cluster) ", STRING, false, "", true);
// register String parameter for supplying minimal rmsd between clusters
parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);
// choice of atom rmsd scope
parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
list<String> rmsd_levels;
rmsd_levels.push_back("C_ALPHA");
//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
rmsd_levels.push_back("BACKBONE");
rmsd_levels.push_back("ALL_ATOMS");
parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);
// the manual
String man = "This tool computes clusters of docking poses given as conformation set using a complete linkage algorithm.\n\nParameters are the input ConformationSet (-i_dcd), one corresponding pdb file (-i_pdb) and a naming schema for the results (-o). Optional parameters are the minimal rmsd between the final clusters (-rmsd_cutoff) and the scope/level of detail of the rmsd computation (-rmsd_scope). The optional parameter (-o_dcd)\n\nOutput of this tool is a number of dcd files each containing one ConformationSet.";
parpars.setToolManual(man);
// here we set the types of I/O files
parpars.setSupportedFormats("i_dcd","dcd");
parpars.setSupportedFormats("i_pdb","pdb");
parpars.setSupportedFormats("o","dcd");
parpars.setSupportedFormats("o_dcd","dcd");
parpars.parse(argc, argv);
//////////////////////////////////////////////////
// read the input
PDBFile pdb;
pdb.open(parpars.get("i_pdb"));
System sys;
pdb.read(sys);
ConformationSet cs;
cs.setup(sys);
cs.readDCDFile(parpars.get("i_dcd"));
cs.resetScoring();
PoseClustering pc;
if (parpars.has("rmsd_cutoff"))
{
float rmsd = parpars.get("rmsd_cutoff").toInt();
pc.options.setReal(PoseClustering::Option::RMSD_THRESHOLD, rmsd);
}
if (parpars.has("rmsd_scope"))
{
String scope = parpars.get("rmsd_scope");
if (scope == "C_ALPHA")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA);
else if (scope == "BACKBONE")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE);
else if (scope == "ALL_ATOMS")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS);
}
pc.setConformationSet(&cs);
pc.compute();
Size num_clusters = pc.getNumberOfClusters();
for (Size i = 0; i < num_clusters; i++)
{
Log << " Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;
boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_cluster" + String(i)
+ "_visible_dcd";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
new_cs->writeDCDFile(outfile_name);
}
if (parpars.has("o_dcd"))
{
String outfile_name = String(parpars.get("o_dcd"));
boost::shared_ptr<ConformationSet> cs = pc.getReducedConformationSet();
cs->writeDCDFile(outfile_name);
}
Log << "done." << endl;
return 0;
}
<commit_msg>Updated the DockPoseClustering tool<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
// - required
parpars.registerParameter("i_dcd", "input dcd-file", INFILE, true);
parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output dcd-file name for first solution ", STRING, true, "", true);
parpars.registerParameter("o_id", "output id ", STRING, true, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution ", STRING, true, "", true);
parpars.registerParameter("o_dcd", "output directory for the reduced cluster set (one structure per final cluster) ", STRING, false, "", true);
// register String parameter for supplying minimal rmsd between clusters
parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);
// choice of atom rmsd scope
parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
list<String> rmsd_levels;
rmsd_levels.push_back("C_ALPHA");
//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
rmsd_levels.push_back("BACKBONE");
rmsd_levels.push_back("ALL_ATOMS");
parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);
// choice of cluster algorithm
parpars.registerParameter("alg", "algorithm used for clustering (CLINK_DEFAYS, SLINK_SIBSON) ", STRING, false, "CLINK_DEFAYS");
list<String> cluster_algs;
cluster_algs.push_back("CLINK_DEFAYS");
cluster_algs.push_back("SLINK_SIBSON");
parpars.setParameterRestrictions("alg", cluster_algs);
// the manual
String man = "This tool computes clusters of docking poses given as conformation set using the SLINK or CLINK algorithm.\n\nParameters are the input ConformationSet (-i_dcd), one corresponding pdb file (-i_pdb), the algorithm (-alg) and a naming schema for the results (-o). Optional parameters are the minimal rmsd between the final clusters (-rmsd_cutoff) and the scope/level of detail of the rmsd computation (-rmsd_scope). The optional parameter (-o_dcd)\n\nOutput of this tool is a number of dcd files each containing one ConformationSet.";
parpars.setToolManual(man);
// here we set the types of I/O files
parpars.setSupportedFormats("i_dcd","dcd");
parpars.setSupportedFormats("i_pdb","pdb");
parpars.setSupportedFormats("o","dcd");
parpars.setSupportedFormats("o_dcd","dcd");
parpars.parse(argc, argv);
//////////////////////////////////////////////////
// read the input
PDBFile pdb;
pdb.open(parpars.get("i_pdb"));
System sys;
pdb.read(sys);
ConformationSet cs;
cs.setup(sys);
cs.readDCDFile(parpars.get("i_dcd"));
cs.resetScoring();
PoseClustering pc;
if (parpars.has("rmsd_cutoff"))
{
float rmsd = parpars.get("rmsd_cutoff").toInt();
pc.options.setReal(PoseClustering::Option::RMSD_THRESHOLD, rmsd);
}
if (parpars.has("rmsd_scope"))
{
String scope = parpars.get("rmsd_scope");
if (scope == "C_ALPHA")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA);
else if (scope == "BACKBONE")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE);
else if (scope == "ALL_ATOMS")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS);
}
if (parpars.has("alg"))
{
String alg = parpars.get("alg");
if (alg == "CLINK_DEFAYS")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::CLINK_DEFAYS);
else if (alg == "SLINK_SIBSON")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::SLINK_SIBSON);
}
pc.setConformationSet(&cs);
pc.compute();
Size num_clusters = pc.getNumberOfClusters();
for (Size i = 0; i < num_clusters; i++)
{
Log << " Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;
boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_cluster" + String(i)
+ "_visible_dcd";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
new_cs->writeDCDFile(outfile_name);
}
if (parpars.has("o_dcd"))
{
String outfile_name = String(parpars.get("o_dcd"));
boost::shared_ptr<ConformationSet> cs = pc.getReducedConformationSet();
cs->writeDCDFile(outfile_name);
}
Log << "done." << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef NEK_ANY_ANY_HPP
#define NEK_ANY_ANY_HPP
#include <utility>
#include <nek/any/any_fwd.hpp>
#include <nek/any/exception.hpp>
#include <nek/mpl/if.hpp>
#include <nek/type_traits/add_lvalue_reference.hpp>
#include <nek/type_traits/is_reference.hpp>
#include <nek/type_traits/remove_reference.hpp>
namespace nek
{
class any
{
private:
class holder_base
{
public:
holder_base() = default;
holder_base(holder_base const&) = default;
virtual ~holder_base()
{
}
virtual holder_base* clone() const = 0;
virtual std::type_info const& type() const noexcept = 0;
};
template <class T>
class holder
: public holder_base
{
public:
T value_;
holder(const T& value)
: value_(value)
{
}
holder& operator=(holder const&) = delete;
holder_base* clone() const override
{
return new holder(value_);
}
std::type_info const& type() const noexcept override
{
return typeid(value_);
}
};
holder_base* held_ = nullptr;
public:
any() noexcept = default;
template <class T>
any(T const& value)
: held_(new holder<T>(value))
{
}
any(any const& right)
: held_(right.held_ ? right.held_->clone() : nullptr)
{
}
~any() noexcept
{
delete held_;
held_ = nullptr;
}
any& operator=(any const& right)
{
any(right).swap(*this);
return *this;
}
template <class T>
any& operator=(T const& value)
{
any(value).swap(*this);
return *this;
}
any& swap(any& right) noexcept
{
using std::swap;
swap(held_, right.held_);
return *this;
}
bool is_empty() const noexcept
{
return !held_;
}
type_info const& type() const noexcept
{
return held_ ? held_->type() : typeid(void);
}
private:
template <class T>
friend T* any_cast(any* pointer) noexcept;
};
inline void swap(any& left, any& right) noexcept
{
left.swap(right);
}
inline void clear(any& value) noexcept
{
any{}.swap(value);
}
template <class T>
T* any_cast(any* pointer) noexcept
{
return pointer && pointer->type() == typeid(T) ?
&(static_cast<any::holder<T>*>(pointer->held_)->value_) : nullptr;
}
template <class T>
inline T const* any_cast(any const* pointer) noexcept
{
return any_cast<T>(const_cast<any*>(pointer));
}
template <class T>
T any_cast(any& value)
{
using nonref_type = remove_reference_t<T>;
using ref_type = nek::mpl::if_t<nek::is_reference<T>,
T, typename add_lvalue_reference_t<T>>;
nonref_type* result = any_cast<nonref_type>(&value);
if (!result) {
throw bad_any_cast_exception();
}
return static_cast<ref_type>(*result);
}
template <class T>
inline T any_cast(any const& value)
{
using nonref_type = remove_reference_t<T>
return any_cast<nonref_type const&>(const_cast<any&>(value));
}
}
#endif<commit_msg>fix include path<commit_after>#ifndef NEK_ANY_ANY_HPP
#define NEK_ANY_ANY_HPP
#include <typeinfo>
#include <utility>
#include <nek/any/any_fwd.hpp>
#include <nek/any/exception.hpp>
#include <nek/mpl/if.hpp>
#include <nek/type_traits/add_lvalue_reference.hpp>
#include <nek/type_traits/is_reference.hpp>
#include <nek/type_traits/remove_reference.hpp>
namespace nek
{
class any
{
private:
class holder_base
{
public:
holder_base() = default;
holder_base(holder_base const&) = default;
virtual ~holder_base()
{
}
virtual holder_base* clone() const = 0;
virtual std::type_info const& type() const noexcept = 0;
};
template <class T>
class holder
: public holder_base
{
public:
T value_;
holder(const T& value)
: value_(value)
{
}
holder& operator=(holder const&) = delete;
holder_base* clone() const override
{
return new holder(value_);
}
std::type_info const& type() const noexcept override
{
return typeid(value_);
}
};
holder_base* held_ = nullptr;
public:
any() noexcept = default;
template <class T>
any(T const& value)
: held_(new holder<T>(value))
{
}
any(any const& right)
: held_(right.held_ ? right.held_->clone() : nullptr)
{
}
~any() noexcept
{
delete held_;
held_ = nullptr;
}
any& operator=(any const& right)
{
any(right).swap(*this);
return *this;
}
template <class T>
any& operator=(T const& value)
{
any(value).swap(*this);
return *this;
}
any& swap(any& right) noexcept
{
using std::swap;
swap(held_, right.held_);
return *this;
}
bool is_empty() const noexcept
{
return !held_;
}
std::type_info const& type() const noexcept
{
return held_ ? held_->type() : typeid(void);
}
private:
template <class T>
friend T* any_cast(any* pointer) noexcept;
};
inline void swap(any& left, any& right) noexcept
{
left.swap(right);
}
inline void clear(any& value) noexcept
{
any{}.swap(value);
}
template <class T>
T* any_cast(any* pointer) noexcept
{
return pointer && pointer->type() == typeid(T) ?
&(static_cast<any::holder<T>*>(pointer->held_)->value_) : nullptr;
}
template <class T>
inline T const* any_cast(any const* pointer) noexcept
{
return any_cast<T>(const_cast<any*>(pointer));
}
template <class T>
T any_cast(any& value)
{
using nonref_type = remove_reference_t<T>;
using ref_type = nek::mpl::if_t<nek::is_reference<T>,
T, add_lvalue_reference_t<T>>;
nonref_type* result = any_cast<nonref_type>(&value);
if (!result) {
throw bad_any_cast_exception();
}
return static_cast<ref_type>(*result);
}
template <class T>
inline T any_cast(any const& value)
{
using nonref_type = remove_reference_t<T>;
return any_cast<nonref_type const&>(const_cast<any&>(value));
}
}
#endif<|endoftext|>
|
<commit_before>#include "perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"
#ifdef HAVE_OPENCL
namespace cvtest {
namespace ocl {
CV_ENUM(MethodType, TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED)
typedef std::tr1::tuple<Size, Size, MethodType> ImgSize_TmplSize_Method_t;
typedef TestBaseWithParam<ImgSize_TmplSize_Method_t> ImgSize_TmplSize_Method;
OCL_PERF_TEST_P(ImgSize_TmplSize_Method, MatchTemplate,
::testing::Combine(
testing::Values(szSmall128, cv::Size(320, 240),
cv::Size(640, 480), cv::Size(800, 600),
cv::Size(1024, 768), cv::Size(1280, 1024)),
testing::Values(cv::Size(12, 12), cv::Size(28, 9),
cv::Size(8, 30), cv::Size(16, 16)),
MethodType::all()
)
)
{
const ImgSize_TmplSize_Method_t params = GetParam();
const Size imgSz = get<0>(params), tmplSz = get<1>(params);
const int method = get<2>(params);
UMat img(imgSz, CV_8UC1), tmpl(tmplSz, CV_8UC1);
UMat result(imgSz - tmplSz + Size(1, 1), CV_32F);
declare.in(img, tmpl, WARMUP_RNG).out(result);
OCL_TEST_CYCLE() matchTemplate(img, tmpl, result, method);
bool isNormed =
method == TM_CCORR_NORMED ||
method == TM_SQDIFF_NORMED ||
method == TM_CCOEFF_NORMED;
double eps = isNormed ? 3e-2
: 255 * 255 * tmpl.total() * 1e-4;
if (isNormed)
SANITY_CHECK(result, eps, ERROR_RELATIVE);
else
SANITY_CHECK(result, eps);
}
/////////// matchTemplate (performance tests from 2.4) ////////////////////////
typedef Size_MatType CV_TM_CCORRFixture;
OCL_PERF_TEST_P(CV_TM_CCORRFixture, matchTemplate,
::testing::Combine(::testing::Values(Size(1000, 1000), Size(2000, 2000)),
OCL_PERF_ENUM(CV_32FC1, CV_32FC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params), templSize(5, 5);
const int type = get<1>(params);
UMat src(srcSize, type), templ(templSize, type);
const Size dstSize(src.cols - templ.cols + 1, src.rows - templ.rows + 1);
UMat dst(dstSize, CV_32F);
declare.in(src, templ, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, CV_TM_CCORR);
SANITY_CHECK(dst, 1e-4);
}
typedef TestBaseWithParam<Size> CV_TM_CCORR_NORMEDFixture;
OCL_PERF_TEST_P(CV_TM_CCORR_NORMEDFixture, matchTemplate,
::testing::Values(Size(1000, 1000), Size(2000, 2000), Size(4000, 4000)))
{
const Size srcSize = GetParam(), templSize(5, 5);
UMat src(srcSize, CV_8UC1), templ(templSize, CV_8UC1);
const Size dstSize(src.cols - templ.cols + 1, src.rows - templ.rows + 1);
UMat dst(dstSize, CV_8UC1);
declare.in(src, templ, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, CV_TM_CCORR_NORMED);
SANITY_CHECK(dst, 3e-2);
}
} }
#endif // HAVE_OPENCL
<commit_msg>OCL: matchTemplate: changed perf test<commit_after>#include "perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"
#ifdef HAVE_OPENCL
namespace cvtest {
namespace ocl {
CV_ENUM(MethodType, TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED)
typedef std::tr1::tuple<Size, Size, MethodType, MatType> ImgSize_TmplSize_Method_MatType_t;
typedef TestBaseWithParam<ImgSize_TmplSize_Method_MatType_t> ImgSize_TmplSize_Method_MatType;
OCL_PERF_TEST_P(ImgSize_TmplSize_Method_MatType, MatchTemplate,
::testing::Combine(
testing::Values(cv::Size(640, 480), cv::Size(1280, 1024)),
testing::Values(cv::Size(11, 11), cv::Size(16, 16), cv::Size(41, 41)),
MethodType::all(),
testing::Values(CV_8UC1, CV_8UC3, CV_32FC1, CV_32FC3)
)
)
{
const ImgSize_TmplSize_Method_MatType_t params = GetParam();
const Size imgSz = get<0>(params), tmplSz = get<1>(params);
const int method = get<2>(params);
int type = get<3>(GetParam());
UMat img(imgSz, type), tmpl(tmplSz, type);
UMat result(imgSz - tmplSz + Size(1, 1), CV_32F);
declare.in(img, tmpl, WARMUP_RNG).out(result);
OCL_TEST_CYCLE() matchTemplate(img, tmpl, result, method);
bool isNormed =
method == TM_CCORR_NORMED ||
method == TM_SQDIFF_NORMED ||
method == TM_CCOEFF_NORMED;
double eps = isNormed ? 3e-2
: 255 * 255 * tmpl.total() * 1e-4;
SANITY_CHECK(result, eps, ERROR_RELATIVE);
}
/////////// matchTemplate (performance tests from 2.4) ////////////////////////
typedef Size_MatType CV_TM_CCORRFixture;
OCL_PERF_TEST_P(CV_TM_CCORRFixture, matchTemplate,
::testing::Combine(::testing::Values(Size(1000, 1000), Size(2000, 2000)),
OCL_PERF_ENUM(CV_32FC1, CV_32FC4)))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params), templSize(5, 5);
const int type = get<1>(params);
UMat src(srcSize, type), templ(templSize, type);
const Size dstSize(src.cols - templ.cols + 1, src.rows - templ.rows + 1);
UMat dst(dstSize, CV_32F);
declare.in(src, templ, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, CV_TM_CCORR);
SANITY_CHECK(dst, 1e-4);
}
typedef TestBaseWithParam<Size> CV_TM_CCORR_NORMEDFixture;
OCL_PERF_TEST_P(CV_TM_CCORR_NORMEDFixture, matchTemplate,
::testing::Values(Size(1000, 1000), Size(2000, 2000), Size(4000, 4000)))
{
const Size srcSize = GetParam(), templSize(5, 5);
UMat src(srcSize, CV_8UC1), templ(templSize, CV_8UC1);
const Size dstSize(src.cols - templ.cols + 1, src.rows - templ.rows + 1);
UMat dst(dstSize, CV_8UC1);
declare.in(src, templ, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, CV_TM_CCORR_NORMED);
SANITY_CHECK(dst, 3e-2);
}
} }
#endif // HAVE_OPENCL<|endoftext|>
|
<commit_before>// Copyright 2019 Google LLC
//
// 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 <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include <tuple>
#include <vector>
#include "absl/base/optimization.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "google/protobuf/text_format.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/object.h"
#include "riegeli/bytes/chain_backward_writer.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/message_parse.h"
#include "riegeli/bytes/message_serialize.h"
#include "riegeli/bytes/null_backward_writer.h"
#include "riegeli/bytes/reader_utils.h"
#include "riegeli/bytes/std_io.h"
#include "riegeli/bytes/varint_reading.h"
#include "riegeli/bytes/writer.h"
#include "riegeli/chunk_encoding/chunk.h"
#include "riegeli/chunk_encoding/constants.h"
#include "riegeli/chunk_encoding/decompressor.h"
#include "riegeli/chunk_encoding/field_projection.h"
#include "riegeli/chunk_encoding/transpose_decoder.h"
#include "riegeli/records/chunk_reader.h"
#include "riegeli/records/records_metadata.pb.h"
#include "riegeli/records/skipped_region.h"
#include "riegeli/records/tools/riegeli_summary.pb.h"
ABSL_FLAG(bool, show_records_metadata, true,
"If true, show parsed file metadata.");
ABSL_FLAG(bool, show_record_sizes, false,
"If true, show the list of record sizes in each chunk.");
namespace riegeli {
namespace tools {
namespace {
absl::Status DescribeFileMetadataChunk(const Chunk& chunk,
RecordsMetadata& records_metadata) {
// Based on `RecordReaderBase::ParseMetadata()`.
if (ABSL_PREDICT_FALSE(chunk.header.num_records() != 0)) {
return absl::DataLossError(absl::StrCat(
"Invalid file metadata chunk: number of records is not zero: ",
chunk.header.num_records()));
}
ChainReader<> data_reader(&chunk.data);
TransposeDecoder transpose_decoder;
ChainBackwardWriter<Chain> serialized_metadata_writer(
std::forward_as_tuple(), ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
std::vector<size_t> limits;
const bool ok = transpose_decoder.Decode(1, chunk.header.decoded_data_size(),
FieldProjection::All(), data_reader,
serialized_metadata_writer, limits);
if (ABSL_PREDICT_FALSE(!serialized_metadata_writer.Close())) {
return serialized_metadata_writer.status();
}
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!data_reader.VerifyEndAndClose())) {
return data_reader.status();
}
const Chain& serialized_metadata = serialized_metadata_writer.dest();
RIEGELI_ASSERT_EQ(limits.size(), 1u)
<< "Metadata chunk has unexpected record limits";
RIEGELI_ASSERT_EQ(limits.back(), serialized_metadata.size())
<< "Metadata chunk has unexpected record limits";
return ParseFromChain(serialized_metadata, records_metadata);
}
absl::Status DescribeSimpleChunk(const Chunk& chunk,
summary::SimpleChunk& simple_chunk) {
// Based on `SimpleDecoder::Decode()`.
ChainReader<> chunk_reader(&chunk.data);
const absl::optional<uint8_t> compression_type_byte = ReadByte(chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
const CompressionType compression_type =
static_cast<CompressionType>(*compression_type_byte);
simple_chunk.set_compression_type(
static_cast<summary::CompressionType>(compression_type));
if (absl::GetFlag(FLAGS_show_record_sizes)) {
const absl::optional<uint64_t> sizes_size = ReadVarint64(chunk_reader);
if (ABSL_PREDICT_FALSE(sizes_size == absl::nullopt)) {
return absl::DataLossError("Reading size of sizes failed");
}
if (ABSL_PREDICT_FALSE(*sizes_size > std::numeric_limits<Position>::max() -
chunk_reader.pos())) {
return absl::ResourceExhaustedError("Size of sizes too large");
}
internal::Decompressor<LimitingReader<>> sizes_decompressor(
std::forward_as_tuple(&chunk_reader, chunk_reader.pos() + *sizes_size),
compression_type);
if (ABSL_PREDICT_FALSE(!sizes_decompressor.healthy())) {
return sizes_decompressor.status();
}
while (IntCast<size_t>(simple_chunk.record_sizes_size()) <
chunk.header.num_records()) {
const absl::optional<uint64_t> size =
ReadVarint64(sizes_decompressor.reader());
if (ABSL_PREDICT_FALSE(size == absl::nullopt)) {
sizes_decompressor.reader().Fail(
absl::DataLossError("Reading record size failed"));
return sizes_decompressor.reader().status();
}
simple_chunk.add_record_sizes(*size);
}
if (ABSL_PREDICT_FALSE(!sizes_decompressor.VerifyEndAndClose())) {
return sizes_decompressor.status();
}
}
return absl::OkStatus();
}
absl::Status DescribeTransposedChunk(
const Chunk& chunk, summary::TransposedChunk& transposed_chunk) {
ChainReader<> chunk_reader(&chunk.data);
if (absl::GetFlag(FLAGS_show_record_sizes)) {
// Based on `ChunkDecoder::Parse()`.
TransposeDecoder transpose_decoder;
NullBackwardWriter dest_writer(NullBackwardWriter::kInitiallyOpen);
std::vector<size_t> limits;
const bool ok = transpose_decoder.Decode(
chunk.header.num_records(), chunk.header.decoded_data_size(),
FieldProjection::All(), chunk_reader, dest_writer, limits);
if (ABSL_PREDICT_FALSE(!dest_writer.Close())) return dest_writer.status();
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!chunk_reader.VerifyEndAndClose())) {
return chunk_reader.status();
}
size_t prev_limit = 0;
for (const size_t next_limit : limits) {
RIEGELI_ASSERT_LE(prev_limit, next_limit)
<< "Failed postcondition of TransposeDecoder: "
"record end positions not sorted";
transposed_chunk.add_record_sizes(next_limit - prev_limit);
prev_limit = next_limit;
}
} else {
// Based on `TransposeDecoder::Decode()`.
const absl::optional<uint8_t> compression_type_byte =
ReadByte(chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
transposed_chunk.set_compression_type(
static_cast<summary::CompressionType>(*compression_type_byte));
}
return absl::OkStatus();
}
void DescribeFile(absl::string_view filename, Writer* report) {
absl::Format(report,
"file {\n"
" filename: \"%s\"\n",
absl::Utf8SafeCEscape(filename));
DefaultChunkReader<FdReader<>> chunk_reader(
std::forward_as_tuple(filename, O_RDONLY));
const absl::optional<Position> size = chunk_reader.Size();
if (size != absl::nullopt) {
absl::Format(report, " file_size: %u\n", *size);
}
google::protobuf::TextFormat::Printer printer;
printer.SetInitialIndentLevel(2);
printer.SetUseShortRepeatedPrimitives(true);
printer.SetUseUtf8StringEscaping(true);
for (;;) {
report->Flush(FlushType::kFromProcess);
const Position chunk_begin = chunk_reader.pos();
Chunk chunk;
if (ABSL_PREDICT_FALSE(!chunk_reader.ReadChunk(chunk))) {
SkippedRegion skipped_region;
if (chunk_reader.Recover(&skipped_region)) {
absl::Format(StdErr(), "%s\n", skipped_region.message());
continue;
}
break;
}
summary::Chunk chunk_summary;
chunk_summary.set_chunk_begin(chunk_begin);
chunk_summary.set_chunk_type(
static_cast<summary::ChunkType>(chunk.header.chunk_type()));
chunk_summary.set_data_size(chunk.header.data_size());
chunk_summary.set_num_records(chunk.header.num_records());
chunk_summary.set_decoded_data_size(chunk.header.decoded_data_size());
{
absl::Status status;
switch (chunk.header.chunk_type()) {
case ChunkType::kFileMetadata:
if (absl::GetFlag(FLAGS_show_records_metadata)) {
status = DescribeFileMetadataChunk(
chunk, *chunk_summary.mutable_file_metadata_chunk());
}
break;
case ChunkType::kSimple:
status =
DescribeSimpleChunk(chunk, *chunk_summary.mutable_simple_chunk());
break;
case ChunkType::kTransposed:
status = DescribeTransposedChunk(
chunk, *chunk_summary.mutable_transposed_chunk());
break;
default:
break;
}
if (ABSL_PREDICT_FALSE(!status.ok())) {
absl::Format(StdErr(), "%s\n", status.message());
}
}
absl::Format(report, " chunk {\n");
WriterOutputStream proto_out(report);
printer.Print(chunk_summary, &proto_out);
absl::Format(report, " }\n");
}
absl::Format(report, "}\n");
if (!chunk_reader.Close()) {
absl::Format(StdErr(), "%s\n", chunk_reader.status().message());
}
}
const char kUsage[] =
"Usage: describe_riegeli_file (OPTION|FILE)...\n"
"\n"
"Shows summary of Riegeli/records file contents.\n";
} // namespace
} // namespace tools
} // namespace riegeli
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(riegeli::tools::kUsage);
const std::vector<char*> args = absl::ParseCommandLine(argc, argv);
for (size_t i = 1; i < args.size(); ++i) {
riegeli::tools::DescribeFile(args[i], riegeli::StdOut());
}
}
<commit_msg>Include `compression_type` in `transposed_chunk` also if `--show_record_sizes` is used.<commit_after>// Copyright 2019 Google LLC
//
// 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 <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include <tuple>
#include <vector>
#include "absl/base/optimization.h"
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "google/protobuf/text_format.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/object.h"
#include "riegeli/bytes/chain_backward_writer.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/message_parse.h"
#include "riegeli/bytes/message_serialize.h"
#include "riegeli/bytes/null_backward_writer.h"
#include "riegeli/bytes/reader_utils.h"
#include "riegeli/bytes/std_io.h"
#include "riegeli/bytes/varint_reading.h"
#include "riegeli/bytes/writer.h"
#include "riegeli/chunk_encoding/chunk.h"
#include "riegeli/chunk_encoding/constants.h"
#include "riegeli/chunk_encoding/decompressor.h"
#include "riegeli/chunk_encoding/field_projection.h"
#include "riegeli/chunk_encoding/transpose_decoder.h"
#include "riegeli/records/chunk_reader.h"
#include "riegeli/records/records_metadata.pb.h"
#include "riegeli/records/skipped_region.h"
#include "riegeli/records/tools/riegeli_summary.pb.h"
ABSL_FLAG(bool, show_records_metadata, true,
"If true, show parsed file metadata.");
ABSL_FLAG(bool, show_record_sizes, false,
"If true, show the list of record sizes in each chunk.");
namespace riegeli {
namespace tools {
namespace {
absl::Status DescribeFileMetadataChunk(const Chunk& chunk,
RecordsMetadata& records_metadata) {
// Based on `RecordReaderBase::ParseMetadata()`.
if (ABSL_PREDICT_FALSE(chunk.header.num_records() != 0)) {
return absl::DataLossError(absl::StrCat(
"Invalid file metadata chunk: number of records is not zero: ",
chunk.header.num_records()));
}
ChainReader<> data_reader(&chunk.data);
TransposeDecoder transpose_decoder;
ChainBackwardWriter<Chain> serialized_metadata_writer(
std::forward_as_tuple(), ChainBackwardWriterBase::Options().set_size_hint(
chunk.header.decoded_data_size()));
std::vector<size_t> limits;
const bool ok = transpose_decoder.Decode(1, chunk.header.decoded_data_size(),
FieldProjection::All(), data_reader,
serialized_metadata_writer, limits);
if (ABSL_PREDICT_FALSE(!serialized_metadata_writer.Close())) {
return serialized_metadata_writer.status();
}
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!data_reader.VerifyEndAndClose())) {
return data_reader.status();
}
const Chain& serialized_metadata = serialized_metadata_writer.dest();
RIEGELI_ASSERT_EQ(limits.size(), 1u)
<< "Metadata chunk has unexpected record limits";
RIEGELI_ASSERT_EQ(limits.back(), serialized_metadata.size())
<< "Metadata chunk has unexpected record limits";
return ParseFromChain(serialized_metadata, records_metadata);
}
absl::Status DescribeSimpleChunk(const Chunk& chunk,
summary::SimpleChunk& simple_chunk) {
// Based on `SimpleDecoder::Decode()`.
ChainReader<> chunk_reader(&chunk.data);
const absl::optional<uint8_t> compression_type_byte = ReadByte(chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
const CompressionType compression_type =
static_cast<CompressionType>(*compression_type_byte);
simple_chunk.set_compression_type(
static_cast<summary::CompressionType>(compression_type));
if (absl::GetFlag(FLAGS_show_record_sizes)) {
const absl::optional<uint64_t> sizes_size = ReadVarint64(chunk_reader);
if (ABSL_PREDICT_FALSE(sizes_size == absl::nullopt)) {
return absl::DataLossError("Reading size of sizes failed");
}
if (ABSL_PREDICT_FALSE(*sizes_size > std::numeric_limits<Position>::max() -
chunk_reader.pos())) {
return absl::ResourceExhaustedError("Size of sizes too large");
}
internal::Decompressor<LimitingReader<>> sizes_decompressor(
std::forward_as_tuple(&chunk_reader, chunk_reader.pos() + *sizes_size),
compression_type);
if (ABSL_PREDICT_FALSE(!sizes_decompressor.healthy())) {
return sizes_decompressor.status();
}
while (IntCast<size_t>(simple_chunk.record_sizes_size()) <
chunk.header.num_records()) {
const absl::optional<uint64_t> size =
ReadVarint64(sizes_decompressor.reader());
if (ABSL_PREDICT_FALSE(size == absl::nullopt)) {
sizes_decompressor.reader().Fail(
absl::DataLossError("Reading record size failed"));
return sizes_decompressor.reader().status();
}
simple_chunk.add_record_sizes(*size);
}
if (ABSL_PREDICT_FALSE(!sizes_decompressor.VerifyEndAndClose())) {
return sizes_decompressor.status();
}
}
return absl::OkStatus();
}
absl::Status DescribeTransposedChunk(
const Chunk& chunk, summary::TransposedChunk& transposed_chunk) {
// Based on `TransposeDecoder::Decode()`.
ChainReader<> chunk_reader(&chunk.data);
const absl::optional<uint8_t> compression_type_byte = ReadByte(chunk_reader);
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
return absl::DataLossError("Reading compression type failed");
}
transposed_chunk.set_compression_type(
static_cast<summary::CompressionType>(*compression_type_byte));
if (absl::GetFlag(FLAGS_show_record_sizes)) {
// Based on `ChunkDecoder::Parse()`.
chunk_reader.Seek(0);
TransposeDecoder transpose_decoder;
NullBackwardWriter dest_writer(NullBackwardWriter::kInitiallyOpen);
std::vector<size_t> limits;
const bool ok = transpose_decoder.Decode(
chunk.header.num_records(), chunk.header.decoded_data_size(),
FieldProjection::All(), chunk_reader, dest_writer, limits);
if (ABSL_PREDICT_FALSE(!dest_writer.Close())) return dest_writer.status();
if (ABSL_PREDICT_FALSE(!ok)) return transpose_decoder.status();
if (ABSL_PREDICT_FALSE(!chunk_reader.VerifyEndAndClose())) {
return chunk_reader.status();
}
size_t prev_limit = 0;
for (const size_t next_limit : limits) {
RIEGELI_ASSERT_LE(prev_limit, next_limit)
<< "Failed postcondition of TransposeDecoder: "
"record end positions not sorted";
transposed_chunk.add_record_sizes(next_limit - prev_limit);
prev_limit = next_limit;
}
}
return absl::OkStatus();
}
void DescribeFile(absl::string_view filename, Writer* report) {
absl::Format(report,
"file {\n"
" filename: \"%s\"\n",
absl::Utf8SafeCEscape(filename));
DefaultChunkReader<FdReader<>> chunk_reader(
std::forward_as_tuple(filename, O_RDONLY));
const absl::optional<Position> size = chunk_reader.Size();
if (size != absl::nullopt) {
absl::Format(report, " file_size: %u\n", *size);
}
google::protobuf::TextFormat::Printer printer;
printer.SetInitialIndentLevel(2);
printer.SetUseShortRepeatedPrimitives(true);
printer.SetUseUtf8StringEscaping(true);
for (;;) {
report->Flush(FlushType::kFromProcess);
const Position chunk_begin = chunk_reader.pos();
Chunk chunk;
if (ABSL_PREDICT_FALSE(!chunk_reader.ReadChunk(chunk))) {
SkippedRegion skipped_region;
if (chunk_reader.Recover(&skipped_region)) {
absl::Format(StdErr(), "%s\n", skipped_region.message());
continue;
}
break;
}
summary::Chunk chunk_summary;
chunk_summary.set_chunk_begin(chunk_begin);
chunk_summary.set_chunk_type(
static_cast<summary::ChunkType>(chunk.header.chunk_type()));
chunk_summary.set_data_size(chunk.header.data_size());
chunk_summary.set_num_records(chunk.header.num_records());
chunk_summary.set_decoded_data_size(chunk.header.decoded_data_size());
{
absl::Status status;
switch (chunk.header.chunk_type()) {
case ChunkType::kFileMetadata:
if (absl::GetFlag(FLAGS_show_records_metadata)) {
status = DescribeFileMetadataChunk(
chunk, *chunk_summary.mutable_file_metadata_chunk());
}
break;
case ChunkType::kSimple:
status =
DescribeSimpleChunk(chunk, *chunk_summary.mutable_simple_chunk());
break;
case ChunkType::kTransposed:
status = DescribeTransposedChunk(
chunk, *chunk_summary.mutable_transposed_chunk());
break;
default:
break;
}
if (ABSL_PREDICT_FALSE(!status.ok())) {
absl::Format(StdErr(), "%s\n", status.message());
}
}
absl::Format(report, " chunk {\n");
WriterOutputStream proto_out(report);
printer.Print(chunk_summary, &proto_out);
absl::Format(report, " }\n");
}
absl::Format(report, "}\n");
if (!chunk_reader.Close()) {
absl::Format(StdErr(), "%s\n", chunk_reader.status().message());
}
}
const char kUsage[] =
"Usage: describe_riegeli_file (OPTION|FILE)...\n"
"\n"
"Shows summary of Riegeli/records file contents.\n";
} // namespace
} // namespace tools
} // namespace riegeli
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(riegeli::tools::kUsage);
const std::vector<char*> args = absl::ParseCommandLine(argc, argv);
for (size_t i = 1; i < args.size(); ++i) {
riegeli::tools::DescribeFile(args[i], riegeli::StdOut());
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "BrightnessController.h"
#include "../Monitor.h"
#include "../Logger.h"
BrightnessController::BrightnessController(HMONITOR monitor) {
BOOL result;
DWORD numPhysicalMonitors = 0;
result = GetNumberOfPhysicalMonitorsFromHMONITOR(
monitor, &numPhysicalMonitors);
if (result == FALSE || numPhysicalMonitors <= 0) {
CLOG(L"Could not get physical monitors");
return;
}
CLOG(L"Number of physical monitors detected: %d", numPhysicalMonitors);
PHYSICAL_MONITOR *monitors = new PHYSICAL_MONITOR[numPhysicalMonitors];
result = GetPhysicalMonitorsFromHMONITOR(
monitor, numPhysicalMonitors, monitors);
for (unsigned int i = 0; i < numPhysicalMonitors; ++i) {
CLOG(L"Monitor: %s", monitors[i].szPhysicalMonitorDescription);
bool supportsAPI = SupportsBrightnessAPI(monitors[i]);
QCLOG(L"Supports *MonitorBrightness APIs: %s",
supportsAPI ? L"YES" : L"NO");
if (supportsAPI) {
/* For now, we use the first compatible monitor found. */
_monitorHandle = monitors[i].hPhysicalMonitor;
break;
}
}
delete[] monitors;
DWORD min, cur, max;
result = GetMonitorBrightness(_monitorHandle, &min, &cur, &max);
if (result == 0) {
Logger::LogLastError();
}
_minBrightness = min;
_maxBrightness = max;
CLOG(L"Got brightness: %d, %d, %d %f", min, cur, max, Brightness());
}
BrightnessController::BrightnessController(Monitor &monitor) :
BrightnessController(monitor.Handle()) {
}
float BrightnessController::Brightness() {
DWORD cur;
GetMonitorBrightness(_monitorHandle, NULL, &cur, NULL);
return (float) (cur - _minBrightness) / (_maxBrightness - _minBrightness);
}
void BrightnessController::Brightness(float level) {
}
bool BrightnessController::SupportsBrightnessAPI(PHYSICAL_MONITOR &pm) {
DWORD caps, color;
GetMonitorCapabilities(pm.hPhysicalMonitor, &caps, &color);
return ((caps & MC_CAPS_BRIGHTNESS) == MC_CAPS_BRIGHTNESS);
}
<commit_msg>Add diagnostic info if DDC unsupported<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "BrightnessController.h"
#include "../Monitor.h"
#include "../Logger.h"
BrightnessController::BrightnessController(HMONITOR monitor) {
BOOL result;
DWORD numPhysicalMonitors = 0;
result = GetNumberOfPhysicalMonitorsFromHMONITOR(
monitor, &numPhysicalMonitors);
if (result == FALSE || numPhysicalMonitors <= 0) {
CLOG(L"Could not get physical monitors");
return;
}
CLOG(L"Number of physical monitors detected: %d", numPhysicalMonitors);
PHYSICAL_MONITOR *monitors = new PHYSICAL_MONITOR[numPhysicalMonitors];
result = GetPhysicalMonitorsFromHMONITOR(
monitor, numPhysicalMonitors, monitors);
for (unsigned int i = 0; i < numPhysicalMonitors; ++i) {
CLOG(L"Monitor: %s", monitors[i].szPhysicalMonitorDescription);
bool supportsAPI = SupportsBrightnessAPI(monitors[i]);
QCLOG(L"Supports *MonitorBrightness APIs: %s",
supportsAPI ? L"YES" : L"NO");
if (supportsAPI) {
/* For now, we use the first compatible monitor found. */
_monitorHandle = monitors[i].hPhysicalMonitor;
break;
}
}
delete[] monitors;
DWORD min, cur, max;
result = GetMonitorBrightness(_monitorHandle, &min, &cur, &max);
if (result == 0) {
Logger::LogLastError();
}
_minBrightness = min;
_maxBrightness = max;
CLOG(L"Got brightness: %d, %d, %d %f", min, cur, max, Brightness());
}
BrightnessController::BrightnessController(Monitor &monitor) :
BrightnessController(monitor.Handle()) {
}
float BrightnessController::Brightness() {
DWORD cur;
GetMonitorBrightness(_monitorHandle, NULL, &cur, NULL);
return (float) (cur - _minBrightness) / (_maxBrightness - _minBrightness);
}
void BrightnessController::Brightness(float level) {
}
bool BrightnessController::SupportsBrightnessAPI(PHYSICAL_MONITOR &pm) {
DWORD caps, color;
BOOL result = GetMonitorCapabilities(pm.hPhysicalMonitor, &caps, &color);
if (result == FALSE) {
QCLOG(L"Monitor does not support DDC/CI");
return false;
}
return ((caps & MC_CAPS_BRIGHTNESS) == MC_CAPS_BRIGHTNESS);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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 "test.h"
#include "main.h"
#include "io.h"
#include "miniposix.h"
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#ifndef _WIN32
#include <sys/mman.h>
#endif
namespace kj {
namespace {
TestCase* testCasesHead = nullptr;
TestCase** testCasesTail = &testCasesHead;
} // namespace
TestCase::TestCase(const char* file, uint line, const char* description)
: file(file), line(line), description(description), next(nullptr), prev(testCasesTail),
matchedFilter(false) {
*prev = this;
testCasesTail = &next;
}
TestCase::~TestCase() {
*prev = next;
if (next == nullptr) {
testCasesTail = prev;
} else {
next->prev = prev;
}
}
// =======================================================================================
namespace _ { // private
bool hasSubstring(kj::StringPtr haystack, kj::StringPtr needle) {
// TODO(perf): This is not the best algorithm for substring matching.
if (needle.size() <= haystack.size()) {
for (size_t i = 0; i <= haystack.size() - needle.size(); i++) {
if (haystack.slice(i).startsWith(needle)) {
return true;
}
}
}
return false;
}
LogExpectation::LogExpectation(LogSeverity severity, StringPtr substring)
: severity(severity), substring(substring), seen(false) {}
LogExpectation::~LogExpectation() {
if (!unwindDetector.isUnwinding()) {
KJ_ASSERT(seen, "expected log message not seen", severity, substring);
}
}
void LogExpectation::logMessage(
LogSeverity severity, const char* file, int line, int contextDepth,
String&& text) {
if (!seen && severity == this->severity) {
if (hasSubstring(text, substring)) {
// Match. Ignore it.
seen = true;
return;
}
}
// Pass up the chain.
ExceptionCallback::logMessage(severity, file, line, contextDepth, kj::mv(text));
}
// =======================================================================================
GlobFilter::GlobFilter(const char* pattern): pattern(heapString(pattern)) {}
GlobFilter::GlobFilter(ArrayPtr<const char> pattern): pattern(heapString(pattern)) {}
bool GlobFilter::matches(StringPtr name) {
// Get out your computer science books. We're implementing a non-deterministic finite automaton.
//
// Our NDFA has one "state" corresponding to each character in the pattern.
//
// As you may recall, an NDFA can be transformed into a DFA where every state in the DFA
// represents some combination of states in the NDFA. Therefore, we actually have to store a
// list of states here. (Actually, what we really want is a set of states, but because our
// patterns are mostly non-cyclic a list of states should work fine and be a bit more efficient.)
// Our state list starts out pointing only at the start of the pattern.
states.resize(0);
states.add(0);
Vector<uint> scratch;
// Iterate through each character in the name.
for (char c: name) {
// Pull the current set of states off to the side, so that we can populate `states` with the
// new set of states.
Vector<uint> oldStates = kj::mv(states);
states = kj::mv(scratch);
states.resize(0);
// The pattern can omit a leading path. So if we're at a '/' then enter the state machine at
// the beginning on the next char.
if (c == '/' || c == '\\') {
states.add(0);
}
// Process each state.
for (uint state: oldStates) {
applyState(c, state);
}
// Store the previous state vector for reuse.
scratch = kj::mv(oldStates);
}
// If any one state is at the end of the pattern (or at a wildcard just before the end of the
// pattern), we have a match.
for (uint state: states) {
while (state < pattern.size() && pattern[state] == '*') {
++state;
}
if (state == pattern.size()) {
return true;
}
}
return false;
}
void GlobFilter::applyState(char c, int state) {
if (state < pattern.size()) {
switch (pattern[state]) {
case '*':
// At a '*', we both re-add the current state and attempt to match the *next* state.
if (c != '/' && c != '\\') { // '*' doesn't match '/'.
states.add(state);
}
applyState(c, state + 1);
break;
case '?':
// A '?' matches one character (never a '/').
if (c != '/' && c != '\\') {
states.add(state + 1);
}
break;
default:
// Any other character matches only itself.
if (c == pattern[state]) {
states.add(state + 1);
}
break;
}
}
}
} // namespace _ (private)
// =======================================================================================
namespace {
class TestExceptionCallback: public ExceptionCallback {
public:
TestExceptionCallback(ProcessContext& context): context(context) {}
bool failed() { return sawError; }
void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
String&& text) override {
void* traceSpace[32];
auto trace = getStackTrace(traceSpace, 2);
if (text.size() == 0) {
text = kj::heapString("expectation failed");
}
text = kj::str(kj::repeat('_', contextDepth), file, ':', line, ": ", kj::mv(text));
if (severity == LogSeverity::ERROR || severity == LogSeverity::FATAL) {
sawError = true;
context.error(kj::str(text, "\nstack: ", strArray(trace, " "), stringifyStackTrace(trace)));
} else {
context.warning(text);
}
}
private:
ProcessContext& context;
bool sawError = false;
};
} // namespace
class TestRunner {
public:
explicit TestRunner(ProcessContext& context)
: context(context), useColor(isatty(STDOUT_FILENO)) {}
MainFunc getMain() {
return MainBuilder(context, "KJ Test Runner (version not applicable)",
"Run all tests that have been linked into the binary with this test runner.")
.addOptionWithArg({'f', "filter"}, KJ_BIND_METHOD(*this, setFilter), "<file>[:<line>]",
"Run only the specified test case(s). You may use a '*' wildcard in <file>. You may "
"also omit any prefix of <file>'s path; test from all matching files will run. "
"You may specify multiple filters; any test matching at least one filter will run. "
"<line> may be a range, e.g. \"100-500\".")
.addOption({'l', "list"}, KJ_BIND_METHOD(*this, setList),
"List all test cases that would run, but don't run them. If --filter is specified "
"then only the match tests will be listed.")
.callAfterParsing(KJ_BIND_METHOD(*this, run))
.build();
}
MainBuilder::Validity setFilter(StringPtr pattern) {
hasFilter = true;
ArrayPtr<const char> filePattern = pattern;
uint minLine = kj::minValue;
uint maxLine = kj::maxValue;
KJ_IF_MAYBE(colonPos, pattern.findLast(':')) {
char* end;
StringPtr lineStr = pattern.slice(*colonPos + 1);
bool parsedRange = false;
minLine = strtoul(lineStr.cStr(), &end, 0);
if (end != lineStr.begin()) {
if (*end == '-') {
// A range.
const char* part2 = end + 1;
maxLine = strtoul(part2, &end, 0);
if (end > part2 && *end == '\0') {
parsedRange = true;
}
} else if (*end == '\0') {
parsedRange = true;
maxLine = minLine;
}
}
if (parsedRange) {
// We have an exact line number.
filePattern = pattern.slice(0, *colonPos);
} else {
// Can't parse as a number. Maybe the colon is part of a Windows path name or something.
// Let's just keep it as part of the file pattern.
minLine = kj::minValue;
maxLine = kj::maxValue;
}
}
_::GlobFilter filter(filePattern);
for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) {
if (!testCase->matchedFilter && filter.matches(testCase->file) &&
testCase->line >= minLine && testCase->line <= maxLine) {
testCase->matchedFilter = true;
}
}
return true;
}
MainBuilder::Validity setList() {
listOnly = true;
return true;
}
MainBuilder::Validity run() {
if (testCasesHead == nullptr) {
return "no tests were declared";
}
// Find the common path prefix of all filenames, so we can strip it off.
ArrayPtr<const char> commonPrefix = StringPtr(testCasesHead->file);
for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) {
for (size_t i: kj::indices(commonPrefix)) {
if (testCase->file[i] != commonPrefix[i]) {
commonPrefix = commonPrefix.slice(0, i);
break;
}
}
}
// Back off the prefix to the last '/'.
while (commonPrefix.size() > 0 && commonPrefix.back() != '/' && commonPrefix.back() != '\\') {
commonPrefix = commonPrefix.slice(0, commonPrefix.size() - 1);
}
// Run the testts.
uint passCount = 0;
uint failCount = 0;
for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) {
if (!hasFilter || testCase->matchedFilter) {
auto name = kj::str(testCase->file + commonPrefix.size(), ':', testCase->line,
": ", testCase->description);
write(BLUE, "[ TEST ]", name);
if (!listOnly) {
bool currentFailed = true;
KJ_IF_MAYBE(exception, runCatchingExceptions([&]() {
TestExceptionCallback exceptionCallback(context);
testCase->run();
currentFailed = exceptionCallback.failed();
})) {
context.error(kj::str(*exception));
}
if (currentFailed) {
write(RED, "[ FAIL ]", name);
++failCount;
} else {
write(GREEN, "[ PASS ]", name);
++passCount;
}
}
}
}
if (passCount > 0) write(GREEN, kj::str(passCount, " test(s) passed"), "");
if (failCount > 0) write(RED, kj::str(failCount, " test(s) failed"), "");
context.exit();
}
private:
ProcessContext& context;
bool useColor;
bool hasFilter = false;
bool listOnly = false;
enum Color {
RED,
GREEN,
BLUE
};
void write(StringPtr text) {
FdOutputStream(STDOUT_FILENO).write(text.begin(), text.size());
}
void write(Color color, StringPtr prefix, StringPtr message) {
StringPtr startColor, endColor;
if (useColor) {
switch (color) {
case RED: startColor = "\033[0;1;31m"; break;
case GREEN: startColor = "\033[0;1;32m"; break;
case BLUE: startColor = "\033[0;1;34m"; break;
}
endColor = "\033[0m";
}
String text = kj::str(startColor, prefix, endColor, ' ', message, '\n');
write(text);
}
};
} // namespace kj
KJ_MAIN(kj::TestRunner);
<commit_msg>kj/test: fix missing return TestRunner::run<commit_after>// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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 "test.h"
#include "main.h"
#include "io.h"
#include "miniposix.h"
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#ifndef _WIN32
#include <sys/mman.h>
#endif
namespace kj {
namespace {
TestCase* testCasesHead = nullptr;
TestCase** testCasesTail = &testCasesHead;
} // namespace
TestCase::TestCase(const char* file, uint line, const char* description)
: file(file), line(line), description(description), next(nullptr), prev(testCasesTail),
matchedFilter(false) {
*prev = this;
testCasesTail = &next;
}
TestCase::~TestCase() {
*prev = next;
if (next == nullptr) {
testCasesTail = prev;
} else {
next->prev = prev;
}
}
// =======================================================================================
namespace _ { // private
bool hasSubstring(kj::StringPtr haystack, kj::StringPtr needle) {
// TODO(perf): This is not the best algorithm for substring matching.
if (needle.size() <= haystack.size()) {
for (size_t i = 0; i <= haystack.size() - needle.size(); i++) {
if (haystack.slice(i).startsWith(needle)) {
return true;
}
}
}
return false;
}
LogExpectation::LogExpectation(LogSeverity severity, StringPtr substring)
: severity(severity), substring(substring), seen(false) {}
LogExpectation::~LogExpectation() {
if (!unwindDetector.isUnwinding()) {
KJ_ASSERT(seen, "expected log message not seen", severity, substring);
}
}
void LogExpectation::logMessage(
LogSeverity severity, const char* file, int line, int contextDepth,
String&& text) {
if (!seen && severity == this->severity) {
if (hasSubstring(text, substring)) {
// Match. Ignore it.
seen = true;
return;
}
}
// Pass up the chain.
ExceptionCallback::logMessage(severity, file, line, contextDepth, kj::mv(text));
}
// =======================================================================================
GlobFilter::GlobFilter(const char* pattern): pattern(heapString(pattern)) {}
GlobFilter::GlobFilter(ArrayPtr<const char> pattern): pattern(heapString(pattern)) {}
bool GlobFilter::matches(StringPtr name) {
// Get out your computer science books. We're implementing a non-deterministic finite automaton.
//
// Our NDFA has one "state" corresponding to each character in the pattern.
//
// As you may recall, an NDFA can be transformed into a DFA where every state in the DFA
// represents some combination of states in the NDFA. Therefore, we actually have to store a
// list of states here. (Actually, what we really want is a set of states, but because our
// patterns are mostly non-cyclic a list of states should work fine and be a bit more efficient.)
// Our state list starts out pointing only at the start of the pattern.
states.resize(0);
states.add(0);
Vector<uint> scratch;
// Iterate through each character in the name.
for (char c: name) {
// Pull the current set of states off to the side, so that we can populate `states` with the
// new set of states.
Vector<uint> oldStates = kj::mv(states);
states = kj::mv(scratch);
states.resize(0);
// The pattern can omit a leading path. So if we're at a '/' then enter the state machine at
// the beginning on the next char.
if (c == '/' || c == '\\') {
states.add(0);
}
// Process each state.
for (uint state: oldStates) {
applyState(c, state);
}
// Store the previous state vector for reuse.
scratch = kj::mv(oldStates);
}
// If any one state is at the end of the pattern (or at a wildcard just before the end of the
// pattern), we have a match.
for (uint state: states) {
while (state < pattern.size() && pattern[state] == '*') {
++state;
}
if (state == pattern.size()) {
return true;
}
}
return false;
}
void GlobFilter::applyState(char c, int state) {
if (state < pattern.size()) {
switch (pattern[state]) {
case '*':
// At a '*', we both re-add the current state and attempt to match the *next* state.
if (c != '/' && c != '\\') { // '*' doesn't match '/'.
states.add(state);
}
applyState(c, state + 1);
break;
case '?':
// A '?' matches one character (never a '/').
if (c != '/' && c != '\\') {
states.add(state + 1);
}
break;
default:
// Any other character matches only itself.
if (c == pattern[state]) {
states.add(state + 1);
}
break;
}
}
}
} // namespace _ (private)
// =======================================================================================
namespace {
class TestExceptionCallback: public ExceptionCallback {
public:
TestExceptionCallback(ProcessContext& context): context(context) {}
bool failed() { return sawError; }
void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
String&& text) override {
void* traceSpace[32];
auto trace = getStackTrace(traceSpace, 2);
if (text.size() == 0) {
text = kj::heapString("expectation failed");
}
text = kj::str(kj::repeat('_', contextDepth), file, ':', line, ": ", kj::mv(text));
if (severity == LogSeverity::ERROR || severity == LogSeverity::FATAL) {
sawError = true;
context.error(kj::str(text, "\nstack: ", strArray(trace, " "), stringifyStackTrace(trace)));
} else {
context.warning(text);
}
}
private:
ProcessContext& context;
bool sawError = false;
};
} // namespace
class TestRunner {
public:
explicit TestRunner(ProcessContext& context)
: context(context), useColor(isatty(STDOUT_FILENO)) {}
MainFunc getMain() {
return MainBuilder(context, "KJ Test Runner (version not applicable)",
"Run all tests that have been linked into the binary with this test runner.")
.addOptionWithArg({'f', "filter"}, KJ_BIND_METHOD(*this, setFilter), "<file>[:<line>]",
"Run only the specified test case(s). You may use a '*' wildcard in <file>. You may "
"also omit any prefix of <file>'s path; test from all matching files will run. "
"You may specify multiple filters; any test matching at least one filter will run. "
"<line> may be a range, e.g. \"100-500\".")
.addOption({'l', "list"}, KJ_BIND_METHOD(*this, setList),
"List all test cases that would run, but don't run them. If --filter is specified "
"then only the match tests will be listed.")
.callAfterParsing(KJ_BIND_METHOD(*this, run))
.build();
}
MainBuilder::Validity setFilter(StringPtr pattern) {
hasFilter = true;
ArrayPtr<const char> filePattern = pattern;
uint minLine = kj::minValue;
uint maxLine = kj::maxValue;
KJ_IF_MAYBE(colonPos, pattern.findLast(':')) {
char* end;
StringPtr lineStr = pattern.slice(*colonPos + 1);
bool parsedRange = false;
minLine = strtoul(lineStr.cStr(), &end, 0);
if (end != lineStr.begin()) {
if (*end == '-') {
// A range.
const char* part2 = end + 1;
maxLine = strtoul(part2, &end, 0);
if (end > part2 && *end == '\0') {
parsedRange = true;
}
} else if (*end == '\0') {
parsedRange = true;
maxLine = minLine;
}
}
if (parsedRange) {
// We have an exact line number.
filePattern = pattern.slice(0, *colonPos);
} else {
// Can't parse as a number. Maybe the colon is part of a Windows path name or something.
// Let's just keep it as part of the file pattern.
minLine = kj::minValue;
maxLine = kj::maxValue;
}
}
_::GlobFilter filter(filePattern);
for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) {
if (!testCase->matchedFilter && filter.matches(testCase->file) &&
testCase->line >= minLine && testCase->line <= maxLine) {
testCase->matchedFilter = true;
}
}
return true;
}
MainBuilder::Validity setList() {
listOnly = true;
return true;
}
MainBuilder::Validity run() {
if (testCasesHead == nullptr) {
return "no tests were declared";
}
// Find the common path prefix of all filenames, so we can strip it off.
ArrayPtr<const char> commonPrefix = StringPtr(testCasesHead->file);
for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) {
for (size_t i: kj::indices(commonPrefix)) {
if (testCase->file[i] != commonPrefix[i]) {
commonPrefix = commonPrefix.slice(0, i);
break;
}
}
}
// Back off the prefix to the last '/'.
while (commonPrefix.size() > 0 && commonPrefix.back() != '/' && commonPrefix.back() != '\\') {
commonPrefix = commonPrefix.slice(0, commonPrefix.size() - 1);
}
// Run the testts.
uint passCount = 0;
uint failCount = 0;
for (TestCase* testCase = testCasesHead; testCase != nullptr; testCase = testCase->next) {
if (!hasFilter || testCase->matchedFilter) {
auto name = kj::str(testCase->file + commonPrefix.size(), ':', testCase->line,
": ", testCase->description);
write(BLUE, "[ TEST ]", name);
if (!listOnly) {
bool currentFailed = true;
KJ_IF_MAYBE(exception, runCatchingExceptions([&]() {
TestExceptionCallback exceptionCallback(context);
testCase->run();
currentFailed = exceptionCallback.failed();
})) {
context.error(kj::str(*exception));
}
if (currentFailed) {
write(RED, "[ FAIL ]", name);
++failCount;
} else {
write(GREEN, "[ PASS ]", name);
++passCount;
}
}
}
}
if (passCount > 0) write(GREEN, kj::str(passCount, " test(s) passed"), "");
if (failCount > 0) write(RED, kj::str(failCount, " test(s) failed"), "");
context.exit();
return true;
}
private:
ProcessContext& context;
bool useColor;
bool hasFilter = false;
bool listOnly = false;
enum Color {
RED,
GREEN,
BLUE
};
void write(StringPtr text) {
FdOutputStream(STDOUT_FILENO).write(text.begin(), text.size());
}
void write(Color color, StringPtr prefix, StringPtr message) {
StringPtr startColor, endColor;
if (useColor) {
switch (color) {
case RED: startColor = "\033[0;1;31m"; break;
case GREEN: startColor = "\033[0;1;32m"; break;
case BLUE: startColor = "\033[0;1;34m"; break;
}
endColor = "\033[0m";
}
String text = kj::str(startColor, prefix, endColor, ' ', message, '\n');
write(text);
}
};
} // namespace kj
KJ_MAIN(kj::TestRunner);
<|endoftext|>
|
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* DataManReader.cpp
*
* Created on: Feb 21, 2017
* Author: Jason Wang
*/
#include "DataManReader.tcc"
#include "adios2/helper/adiosString.h"
namespace adios2
{
namespace core
{
namespace engine
{
DataManReader::DataManReader(IO &io, const std::string &name,
const Mode openMode, helper::Comm comm)
: Engine("DataManReader", io, name, openMode, std::move(comm)),
m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)),
m_RequesterThreadActive(true), m_SubscriberThreadActive(true),
m_FinalStep(std::numeric_limits<size_t>::max())
{
m_MpiRank = m_Comm.Rank();
m_MpiSize = m_Comm.Size();
helper::GetParameter(m_IO.m_Parameters, "IPAddress", m_IPAddress);
helper::GetParameter(m_IO.m_Parameters, "Port", m_Port);
helper::GetParameter(m_IO.m_Parameters, "Timeout", m_Timeout);
helper::GetParameter(m_IO.m_Parameters, "Verbose", m_Verbosity);
helper::GetParameter(m_IO.m_Parameters, "Threading", m_Threading);
helper::GetParameter(m_IO.m_Parameters, "Monitor", m_MonitorActive);
if (m_IPAddress.empty())
{
throw(std::invalid_argument(
"IP address not specified in wide area staging"));
}
std::string requesterAddress =
"tcp://" + m_IPAddress + ":" + std::to_string(m_Port);
std::string subscriberAddress =
"tcp://" + m_IPAddress + ":" + std::to_string(m_Port + 1);
m_Requester.OpenRequester(requesterAddress, m_Timeout,
m_ReceiverBufferSize);
auto timeBeforeRequest = std::chrono::system_clock::now();
auto reply = m_Requester.Request("Handshake", 9);
auto timeAfterRequest = std::chrono::system_clock::now();
auto roundLatency = std::chrono::duration_cast<std::chrono::milliseconds>(
timeAfterRequest - timeBeforeRequest)
.count();
auto startTime = std::chrono::system_clock::now();
while (reply == nullptr or reply->empty())
{
reply = m_Requester.Request("Handshake", 9);
auto nowTime = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(
nowTime - startTime);
roundLatency = duration.count() * 1000;
if (duration.count() > m_Timeout)
{
m_InitFailed = true;
return;
}
}
nlohmann::json message = nlohmann::json::parse(reply->data());
m_TransportMode = message["Transport"];
if (m_MonitorActive)
{
m_Monitor.SetClockError(roundLatency, message["TimeStamp"]);
m_Monitor.AddTransport(m_TransportMode);
if (m_Threading)
{
m_Monitor.SetReaderThreading();
}
}
if (m_TransportMode == "fast")
{
m_Subscriber.OpenSubscriber(subscriberAddress, m_ReceiverBufferSize);
m_SubscriberThread = std::thread(&DataManReader::SubscribeThread, this);
}
else if (m_TransportMode == "reliable")
{
}
else
{
throw(std::invalid_argument("unknown transport mode"));
}
m_Requester.Request("Ready", 5);
if (m_TransportMode == "reliable")
{
m_RequesterThread = std::thread(&DataManReader::RequestThread, this);
}
}
DataManReader::~DataManReader()
{
if (not m_IsClosed)
{
DoClose();
}
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::~DataManReader() Rank " << m_MpiRank
<< ", Step " << m_CurrentStep << std::endl;
}
}
StepStatus DataManReader::BeginStep(StepMode stepMode,
const float timeoutSeconds)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() begin, Rank " << m_MpiRank
<< ", Step " << m_CurrentStep << std::endl;
}
float timeout = timeoutSeconds;
if (timeout <= 0)
{
timeout = m_Timeout;
}
if (m_InitFailed)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep(), Rank " << m_MpiRank
<< " returned EndOfStream due "
"to initialization failure"
<< std::endl;
}
return StepStatus::EndOfStream;
}
if (m_CurrentStep >= m_FinalStep and m_CurrentStep >= 0)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
<< " returned EndOfStream, "
"final step is "
<< m_FinalStep << std::endl;
}
return StepStatus::EndOfStream;
}
m_CurrentStepMetadata =
m_Serializer.GetEarliestLatestStep(m_CurrentStep, 1, timeout, false);
if (m_CurrentStepMetadata == nullptr)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
<< " returned EndOfStream due "
"to timeout"
<< std::endl;
}
return StepStatus::EndOfStream;
}
m_Serializer.GetAttributes(m_IO);
for (const auto &i : *m_CurrentStepMetadata)
{
if (i.step == m_CurrentStep)
{
if (i.type == DataType::None)
{
throw("unknown data type");
}
#define declare_type(T) \
else if (i.type == helper::GetDataType<T>()) \
{ \
CheckIOVariable<T>(i.name, i.shape, i.start, i.count); \
}
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
else { throw("unknown data type"); }
}
}
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() end, Rank " << m_MpiRank
<< ", Step " << m_CurrentStep << std::endl;
}
if (m_MonitorActive)
{
m_Monitor.BeginStep(m_CurrentStep);
}
return StepStatus::OK;
}
size_t DataManReader::CurrentStep() const { return m_CurrentStep; }
void DataManReader::PerformGets() {}
void DataManReader::EndStep()
{
m_Serializer.Erase(m_CurrentStep, true);
m_CurrentStepMetadata = nullptr;
if (m_MonitorActive)
{
auto comMap = m_Serializer.GetOperatorMap();
for (const auto &i : comMap)
{
std::string method, accuracy;
auto it = i.second.find("accuracy");
if (it != i.second.end())
{
accuracy = it->second;
}
it = i.second.find("method");
if (it != i.second.end())
{
method = it->second;
}
m_Monitor.AddCompression(method, std::stof(accuracy));
}
m_Monitor.EndStep(m_CurrentStep);
}
}
void DataManReader::Flush(const int transportIndex) {}
// PRIVATE
void DataManReader::RequestThread()
{
while (m_RequesterThreadActive)
{
auto buffer = m_Requester.Request("Step", 4);
if (buffer != nullptr && buffer->size() > 0)
{
if (buffer->size() < 64)
{
try
{
auto jmsg = nlohmann::json::parse(buffer->data());
m_FinalStep = jmsg["FinalStep"].get<size_t>();
return;
}
catch (...)
{
}
}
m_Serializer.PutPack(buffer, m_Threading);
if (m_MonitorActive)
{
size_t combiningSteps = m_Serializer.GetCombiningSteps();
if (combiningSteps < 20)
{
m_Monitor.SetAverageSteps(40);
}
else
{
m_Monitor.SetAverageSteps(combiningSteps * 2);
}
auto timeStamps = m_Serializer.GetTimeStamps();
for (const auto &timeStamp : timeStamps)
{
m_Monitor.AddLatencyMilliseconds(timeStamp);
}
}
}
}
}
void DataManReader::SubscribeThread()
{
while (m_SubscriberThreadActive)
{
auto buffer = m_Subscriber.Receive();
if (buffer != nullptr && buffer->size() > 0)
{
if (buffer->size() < 64)
{
try
{
auto jmsg = nlohmann::json::parse(buffer->data());
m_FinalStep = jmsg["FinalStep"].get<size_t>();
continue;
}
catch (...)
{
}
}
m_Serializer.PutPack(buffer, m_Threading);
if (m_MonitorActive)
{
size_t combiningSteps = m_Serializer.GetCombiningSteps();
if (combiningSteps < 20)
{
m_Monitor.SetAverageSteps(40);
}
else
{
m_Monitor.SetAverageSteps(combiningSteps * 2);
}
auto timeStamps = m_Serializer.GetTimeStamps();
for (const auto &timeStamp : timeStamps)
{
m_Monitor.AddLatencyMilliseconds(timeStamp);
}
}
}
}
}
#define declare_type(T) \
void DataManReader::DoGetSync(Variable<T> &variable, T *data) \
{ \
GetSyncCommon(variable, data); \
} \
void DataManReader::DoGetDeferred(Variable<T> &variable, T *data) \
{ \
GetDeferredCommon(variable, data); \
} \
std::map<size_t, std::vector<typename Variable<T>::Info>> \
DataManReader::DoAllStepsBlocksInfo(const Variable<T> &variable) const \
{ \
return AllStepsBlocksInfoCommon(variable); \
} \
std::vector<typename Variable<T>::Info> DataManReader::DoBlocksInfo( \
const Variable<T> &variable, const size_t step) const \
{ \
return BlocksInfoCommon(variable, step); \
}
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
void DataManReader::DoClose(const int transportIndex)
{
m_SubscriberThreadActive = false;
m_RequesterThreadActive = false;
if (m_SubscriberThread.joinable())
{
m_SubscriberThread.join();
}
if (m_RequesterThread.joinable())
{
m_RequesterThread.join();
}
m_IsClosed = true;
if (m_MonitorActive)
{
m_Monitor.OutputJson(m_Name);
}
}
} // end namespace engine
} // end namespace core
} // end namespace adios2
<commit_msg>pass writer threading to reader for monitoring<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* DataManReader.cpp
*
* Created on: Feb 21, 2017
* Author: Jason Wang
*/
#include "DataManReader.tcc"
#include "adios2/helper/adiosString.h"
namespace adios2
{
namespace core
{
namespace engine
{
DataManReader::DataManReader(IO &io, const std::string &name,
const Mode openMode, helper::Comm comm)
: Engine("DataManReader", io, name, openMode, std::move(comm)),
m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)),
m_RequesterThreadActive(true), m_SubscriberThreadActive(true),
m_FinalStep(std::numeric_limits<size_t>::max())
{
m_MpiRank = m_Comm.Rank();
m_MpiSize = m_Comm.Size();
helper::GetParameter(m_IO.m_Parameters, "IPAddress", m_IPAddress);
helper::GetParameter(m_IO.m_Parameters, "Port", m_Port);
helper::GetParameter(m_IO.m_Parameters, "Timeout", m_Timeout);
helper::GetParameter(m_IO.m_Parameters, "Verbose", m_Verbosity);
helper::GetParameter(m_IO.m_Parameters, "Threading", m_Threading);
helper::GetParameter(m_IO.m_Parameters, "Monitor", m_MonitorActive);
if (m_IPAddress.empty())
{
throw(std::invalid_argument(
"IP address not specified in wide area staging"));
}
std::string requesterAddress =
"tcp://" + m_IPAddress + ":" + std::to_string(m_Port);
std::string subscriberAddress =
"tcp://" + m_IPAddress + ":" + std::to_string(m_Port + 1);
m_Requester.OpenRequester(requesterAddress, m_Timeout,
m_ReceiverBufferSize);
auto timeBeforeRequest = std::chrono::system_clock::now();
auto reply = m_Requester.Request("Handshake", 9);
auto timeAfterRequest = std::chrono::system_clock::now();
auto roundLatency = std::chrono::duration_cast<std::chrono::milliseconds>(
timeAfterRequest - timeBeforeRequest)
.count();
auto startTime = std::chrono::system_clock::now();
while (reply == nullptr or reply->empty())
{
reply = m_Requester.Request("Handshake", 9);
auto nowTime = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(
nowTime - startTime);
roundLatency = duration.count() * 1000;
if (duration.count() > m_Timeout)
{
m_InitFailed = true;
return;
}
}
nlohmann::json message = nlohmann::json::parse(reply->data());
m_TransportMode = message["Transport"];
if (m_MonitorActive)
{
m_Monitor.SetClockError(roundLatency, message["TimeStamp"]);
m_Monitor.AddTransport(m_TransportMode);
if (m_Threading)
{
m_Monitor.SetReaderThreading();
}
bool writerThreading = message["Threading"];
if (writerThreading)
{
m_Monitor.SetWriterThreading();
}
}
if (m_TransportMode == "fast")
{
m_Subscriber.OpenSubscriber(subscriberAddress, m_ReceiverBufferSize);
m_SubscriberThread = std::thread(&DataManReader::SubscribeThread, this);
}
else if (m_TransportMode == "reliable")
{
}
else
{
throw(std::invalid_argument("unknown transport mode"));
}
m_Requester.Request("Ready", 5);
if (m_TransportMode == "reliable")
{
m_RequesterThread = std::thread(&DataManReader::RequestThread, this);
}
}
DataManReader::~DataManReader()
{
if (not m_IsClosed)
{
DoClose();
}
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::~DataManReader() Rank " << m_MpiRank
<< ", Step " << m_CurrentStep << std::endl;
}
}
StepStatus DataManReader::BeginStep(StepMode stepMode,
const float timeoutSeconds)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() begin, Rank " << m_MpiRank
<< ", Step " << m_CurrentStep << std::endl;
}
float timeout = timeoutSeconds;
if (timeout <= 0)
{
timeout = m_Timeout;
}
if (m_InitFailed)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep(), Rank " << m_MpiRank
<< " returned EndOfStream due "
"to initialization failure"
<< std::endl;
}
return StepStatus::EndOfStream;
}
if (m_CurrentStep >= m_FinalStep and m_CurrentStep >= 0)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
<< " returned EndOfStream, "
"final step is "
<< m_FinalStep << std::endl;
}
return StepStatus::EndOfStream;
}
m_CurrentStepMetadata =
m_Serializer.GetEarliestLatestStep(m_CurrentStep, 1, timeout, false);
if (m_CurrentStepMetadata == nullptr)
{
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
<< " returned EndOfStream due "
"to timeout"
<< std::endl;
}
return StepStatus::EndOfStream;
}
m_Serializer.GetAttributes(m_IO);
for (const auto &i : *m_CurrentStepMetadata)
{
if (i.step == m_CurrentStep)
{
if (i.type == DataType::None)
{
throw("unknown data type");
}
#define declare_type(T) \
else if (i.type == helper::GetDataType<T>()) \
{ \
CheckIOVariable<T>(i.name, i.shape, i.start, i.count); \
}
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
else { throw("unknown data type"); }
}
}
if (m_Verbosity >= 5)
{
std::cout << "DataManReader::BeginStep() end, Rank " << m_MpiRank
<< ", Step " << m_CurrentStep << std::endl;
}
if (m_MonitorActive)
{
m_Monitor.BeginStep(m_CurrentStep);
}
return StepStatus::OK;
}
size_t DataManReader::CurrentStep() const { return m_CurrentStep; }
void DataManReader::PerformGets() {}
void DataManReader::EndStep()
{
m_Serializer.Erase(m_CurrentStep, true);
m_CurrentStepMetadata = nullptr;
if (m_MonitorActive)
{
auto comMap = m_Serializer.GetOperatorMap();
for (const auto &i : comMap)
{
std::string method, accuracy;
auto it = i.second.find("accuracy");
if (it != i.second.end())
{
accuracy = it->second;
}
it = i.second.find("method");
if (it != i.second.end())
{
method = it->second;
}
m_Monitor.AddCompression(method, std::stof(accuracy));
}
m_Monitor.EndStep(m_CurrentStep);
}
}
void DataManReader::Flush(const int transportIndex) {}
// PRIVATE
void DataManReader::RequestThread()
{
while (m_RequesterThreadActive)
{
auto buffer = m_Requester.Request("Step", 4);
if (buffer != nullptr && buffer->size() > 0)
{
if (buffer->size() < 64)
{
try
{
auto jmsg = nlohmann::json::parse(buffer->data());
m_FinalStep = jmsg["FinalStep"].get<size_t>();
return;
}
catch (...)
{
}
}
m_Serializer.PutPack(buffer, m_Threading);
if (m_MonitorActive)
{
size_t combiningSteps = m_Serializer.GetCombiningSteps();
if (combiningSteps < 20)
{
m_Monitor.SetAverageSteps(40);
}
else
{
m_Monitor.SetAverageSteps(combiningSteps * 2);
}
auto timeStamps = m_Serializer.GetTimeStamps();
for (const auto &timeStamp : timeStamps)
{
m_Monitor.AddLatencyMilliseconds(timeStamp);
}
}
}
}
}
void DataManReader::SubscribeThread()
{
while (m_SubscriberThreadActive)
{
auto buffer = m_Subscriber.Receive();
if (buffer != nullptr && buffer->size() > 0)
{
if (buffer->size() < 64)
{
try
{
auto jmsg = nlohmann::json::parse(buffer->data());
m_FinalStep = jmsg["FinalStep"].get<size_t>();
continue;
}
catch (...)
{
}
}
m_Serializer.PutPack(buffer, m_Threading);
if (m_MonitorActive)
{
size_t combiningSteps = m_Serializer.GetCombiningSteps();
if (combiningSteps < 20)
{
m_Monitor.SetAverageSteps(40);
}
else
{
m_Monitor.SetAverageSteps(combiningSteps * 2);
}
auto timeStamps = m_Serializer.GetTimeStamps();
for (const auto &timeStamp : timeStamps)
{
m_Monitor.AddLatencyMilliseconds(timeStamp);
}
}
}
}
}
#define declare_type(T) \
void DataManReader::DoGetSync(Variable<T> &variable, T *data) \
{ \
GetSyncCommon(variable, data); \
} \
void DataManReader::DoGetDeferred(Variable<T> &variable, T *data) \
{ \
GetDeferredCommon(variable, data); \
} \
std::map<size_t, std::vector<typename Variable<T>::Info>> \
DataManReader::DoAllStepsBlocksInfo(const Variable<T> &variable) const \
{ \
return AllStepsBlocksInfoCommon(variable); \
} \
std::vector<typename Variable<T>::Info> DataManReader::DoBlocksInfo( \
const Variable<T> &variable, const size_t step) const \
{ \
return BlocksInfoCommon(variable, step); \
}
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
void DataManReader::DoClose(const int transportIndex)
{
m_SubscriberThreadActive = false;
m_RequesterThreadActive = false;
if (m_SubscriberThread.joinable())
{
m_SubscriberThread.join();
}
if (m_RequesterThread.joinable())
{
m_RequesterThread.join();
}
m_IsClosed = true;
if (m_MonitorActive)
{
m_Monitor.OutputJson(m_Name);
}
}
} // end namespace engine
} // end namespace core
} // end namespace adios2
<|endoftext|>
|
<commit_before>/*****************************************************************************
multiBamCov.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "lineFileUtilities.h"
#include "multiBamCov.h"
#include "api/BamMultiReader.h"
/*
Constructor
*/
MultiCovBam::MultiCovBam(const vector<string> &bam_files, const string bed_file,
int minQual, bool properOnly,
bool keepDuplicates, bool keepFailedQC,
bool obeySplits, bool sameStrand,
bool diffStrand, float overlapFraction,
bool reciprocal)
:
_bam_files(bam_files),
_bed_file(bed_file),
_minQual(minQual),
_properOnly(properOnly),
_keepDuplicates(keepDuplicates),
_keepFailedQC(keepFailedQC),
_obeySplits(obeySplits),
_sameStrand(sameStrand),
_diffStrand(diffStrand),
_overlapFraction(overlapFraction),
_reciprocal(reciprocal)
{
_bed = new BedFile(_bed_file);
LoadBamFileMap();
}
/*
Destructor
*/
MultiCovBam::~MultiCovBam(void)
{}
bool MultiCovBam::FindBlockedOverlaps(const BED &a, const vector<BED> &a_blocks,
const BED &hit) {
int a_footprint = GetTotalBlockLength(a_blocks);
// 1. Break the raw hit into it's blocks
// and see of one of the hit blocks (inner loop)
// overlaps one of a's blocks (inner, inner loop)
// 2. If so, mark the hit as valid and add it to the valid_set.
// Otherwise, the hit only overlapped the span of a and not
// the individual blocks. Thus, it doesn't count.
// break the hit into blocks
bedVector hitBlocks;
GetBedBlocks(hit, hitBlocks);
int b_footprint = GetTotalBlockLength(hitBlocks);
// test to see if there is a valid hit with one of the blocks
bool valid_hit = false;
int tot_overlap = 0;
bedVector::const_iterator hbItr = hitBlocks.begin();
bedVector::const_iterator hbEnd = hitBlocks.end();
for (; hbItr != hbEnd; ++hbItr) {
// look for overlaps between this hit/block and each block in a
bedVector::const_iterator a_blockItr = a_blocks.begin();
bedVector::const_iterator a_blockEnd = a_blocks.end();
for (; a_blockItr != a_blockEnd; ++a_blockItr) {
int hs = max(a_blockItr->start, hbItr->start);
int he = min(a_blockItr->end, hbItr->end);
int overlap = he - hs;
if (overlap > 0) {
valid_hit = true;
tot_overlap += overlap;
}
}
}
if (valid_hit)
{
// require sufficient overlap fraction (reciprocal or otherwise)
// w.r.t to the "footprint" (i.e., the total length of each block)
if ( ((float) tot_overlap / (float) a_footprint) > _overlapFraction) {
if (_reciprocal &&
((float) tot_overlap / (float) b_footprint) > _overlapFraction)
{
return true;
}
else if (!_reciprocal) {
return true;
}
}
}
return false;
}
void MultiCovBam::CollectCoverage()
{
BamMultiReader reader;
if ( !reader.Open(_bam_files) )
{
cerr << "Could not open input BAM files." << endl;
exit(1);
}
else
{
// attempt to find index files
reader.LocateIndexes();
// if index data available for all BAM files, we can use SetRegion
if ( reader.HasIndexes() ) {
BED bed;
_bed->Open();
// loop through each BED entry, jump to it,
// and collect coverage from each BAM
while (_bed->GetNextBed(bed))
{
if (_bed->_status == BED_VALID)
{
// initialize counts for each file to 0
vector<int> counts(_bam_files.size(), 0);
// get the BAM refId for this chrom.
int refId = reader.GetReferenceID(bed.chrom);
// set up a BamRegion to which to attempt to jump
BamRegion region(refId, (int)bed.start, refId, (int)bed.end);
// everything checks out, just iterate through
// specified region, counting alignments
if ( (refId != -1) && (reader.SetRegion(region)) ) {
BamAlignment al;
while ( reader.GetNextAlignment(al) )
{
string strand = "+";
if (al.IsReverseStrand() == true) strand = "-";
bool strands_are_same = (bed.strand == strand);
bool duplicate = al.IsDuplicate();
bool failedQC = al.IsFailedQC();
if (_keepDuplicates) duplicate = false;
if (_keepFailedQC) failedQC = false;
// filters
if (
(_properOnly && !al.IsProperPair()) ||
(_sameStrand && !strands_are_same) ||
(_diffStrand && strands_are_same) ||
(al.MapQuality < _minQual) ||
(duplicate) ||
(failedQC)
)
{
continue;
}
if (_obeySplits == false) {
// enforce fractional overlap
int al_end = al.GetEndPosition(false, false);
CHRPOS s = max(al.Position, (int) bed.start);
CHRPOS e = min(al_end, (int) bed.end);
CHRPOS aLength = (bed.end - bed.start);
CHRPOS bLength = (al_end - al.Position);
int overlapBases = (e - s);
float aOverlap =
( (float) overlapBases / (float) aLength );
float bOverlap =
( (float) overlapBases / (float) bLength );
if ( aOverlap >= _overlapFraction)
{
if (!_reciprocal)
counts[bamFileMap[al.Filename]]++;
else if (bOverlap >= _overlapFraction)
counts[bamFileMap[al.Filename]]++;
}
}
else {
// break alignment into discrete blocks,
bedVector bed_blocks, hits;
GetBamBlocks(al, bed.chrom,
bed_blocks, false, true);
// find the overlaps b/w the block in A & B
bool overlapsFound = FindBlockedOverlaps(bed,
bed_blocks,
bed);
if (overlapsFound == true)
counts[bamFileMap[al.Filename]]++;
}
}
}
// report the cov at this interval for each file and reset
_bed->reportBedTab(bed);
ReportCounts(counts);
}
}
_bed->Close();
}
else {
cerr << "Could not find indexes." << endl;
reader.Close();
exit(1);
}
}
}
void MultiCovBam::LoadBamFileMap(void)
{
for (size_t i = 0; i < _bam_files.size(); ++i)
{
bamFileMap[_bam_files[i]] = i;
}
}
void MultiCovBam::ReportCounts(const vector<int> &counts)
{
for (size_t i = 0; i < counts.size(); ++i)
{
if (i < counts.size() - 1)
cout << counts[i] << "\t";
else
cout << counts[i];
}
cout << endl;
}
<commit_msg>multicov: Propagate error messages from BamMultiReaderPrivate::Open to users.<commit_after>/*****************************************************************************
multiBamCov.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "lineFileUtilities.h"
#include "multiBamCov.h"
#include "api/BamMultiReader.h"
/*
Constructor
*/
MultiCovBam::MultiCovBam(const vector<string> &bam_files, const string bed_file,
int minQual, bool properOnly,
bool keepDuplicates, bool keepFailedQC,
bool obeySplits, bool sameStrand,
bool diffStrand, float overlapFraction,
bool reciprocal)
:
_bam_files(bam_files),
_bed_file(bed_file),
_minQual(minQual),
_properOnly(properOnly),
_keepDuplicates(keepDuplicates),
_keepFailedQC(keepFailedQC),
_obeySplits(obeySplits),
_sameStrand(sameStrand),
_diffStrand(diffStrand),
_overlapFraction(overlapFraction),
_reciprocal(reciprocal)
{
_bed = new BedFile(_bed_file);
LoadBamFileMap();
}
/*
Destructor
*/
MultiCovBam::~MultiCovBam(void)
{}
bool MultiCovBam::FindBlockedOverlaps(const BED &a, const vector<BED> &a_blocks,
const BED &hit) {
int a_footprint = GetTotalBlockLength(a_blocks);
// 1. Break the raw hit into it's blocks
// and see of one of the hit blocks (inner loop)
// overlaps one of a's blocks (inner, inner loop)
// 2. If so, mark the hit as valid and add it to the valid_set.
// Otherwise, the hit only overlapped the span of a and not
// the individual blocks. Thus, it doesn't count.
// break the hit into blocks
bedVector hitBlocks;
GetBedBlocks(hit, hitBlocks);
int b_footprint = GetTotalBlockLength(hitBlocks);
// test to see if there is a valid hit with one of the blocks
bool valid_hit = false;
int tot_overlap = 0;
bedVector::const_iterator hbItr = hitBlocks.begin();
bedVector::const_iterator hbEnd = hitBlocks.end();
for (; hbItr != hbEnd; ++hbItr) {
// look for overlaps between this hit/block and each block in a
bedVector::const_iterator a_blockItr = a_blocks.begin();
bedVector::const_iterator a_blockEnd = a_blocks.end();
for (; a_blockItr != a_blockEnd; ++a_blockItr) {
int hs = max(a_blockItr->start, hbItr->start);
int he = min(a_blockItr->end, hbItr->end);
int overlap = he - hs;
if (overlap > 0) {
valid_hit = true;
tot_overlap += overlap;
}
}
}
if (valid_hit)
{
// require sufficient overlap fraction (reciprocal or otherwise)
// w.r.t to the "footprint" (i.e., the total length of each block)
if ( ((float) tot_overlap / (float) a_footprint) > _overlapFraction) {
if (_reciprocal &&
((float) tot_overlap / (float) b_footprint) > _overlapFraction)
{
return true;
}
else if (!_reciprocal) {
return true;
}
}
}
return false;
}
void MultiCovBam::CollectCoverage()
{
BamMultiReader reader;
if ( !reader.Open(_bam_files) )
{
cerr << "Could not open input BAM files." << endl;
cerr << reader.GetErrorString() << endl;
exit(1);
}
else
{
// attempt to find index files
reader.LocateIndexes();
// if index data available for all BAM files, we can use SetRegion
if ( reader.HasIndexes() ) {
BED bed;
_bed->Open();
// loop through each BED entry, jump to it,
// and collect coverage from each BAM
while (_bed->GetNextBed(bed))
{
if (_bed->_status == BED_VALID)
{
// initialize counts for each file to 0
vector<int> counts(_bam_files.size(), 0);
// get the BAM refId for this chrom.
int refId = reader.GetReferenceID(bed.chrom);
// set up a BamRegion to which to attempt to jump
BamRegion region(refId, (int)bed.start, refId, (int)bed.end);
// everything checks out, just iterate through
// specified region, counting alignments
if ( (refId != -1) && (reader.SetRegion(region)) ) {
BamAlignment al;
while ( reader.GetNextAlignment(al) )
{
string strand = "+";
if (al.IsReverseStrand() == true) strand = "-";
bool strands_are_same = (bed.strand == strand);
bool duplicate = al.IsDuplicate();
bool failedQC = al.IsFailedQC();
if (_keepDuplicates) duplicate = false;
if (_keepFailedQC) failedQC = false;
// filters
if (
(_properOnly && !al.IsProperPair()) ||
(_sameStrand && !strands_are_same) ||
(_diffStrand && strands_are_same) ||
(al.MapQuality < _minQual) ||
(duplicate) ||
(failedQC)
)
{
continue;
}
if (_obeySplits == false) {
// enforce fractional overlap
int al_end = al.GetEndPosition(false, false);
CHRPOS s = max(al.Position, (int) bed.start);
CHRPOS e = min(al_end, (int) bed.end);
CHRPOS aLength = (bed.end - bed.start);
CHRPOS bLength = (al_end - al.Position);
int overlapBases = (e - s);
float aOverlap =
( (float) overlapBases / (float) aLength );
float bOverlap =
( (float) overlapBases / (float) bLength );
if ( aOverlap >= _overlapFraction)
{
if (!_reciprocal)
counts[bamFileMap[al.Filename]]++;
else if (bOverlap >= _overlapFraction)
counts[bamFileMap[al.Filename]]++;
}
}
else {
// break alignment into discrete blocks,
bedVector bed_blocks, hits;
GetBamBlocks(al, bed.chrom,
bed_blocks, false, true);
// find the overlaps b/w the block in A & B
bool overlapsFound = FindBlockedOverlaps(bed,
bed_blocks,
bed);
if (overlapsFound == true)
counts[bamFileMap[al.Filename]]++;
}
}
}
// report the cov at this interval for each file and reset
_bed->reportBedTab(bed);
ReportCounts(counts);
}
}
_bed->Close();
}
else {
cerr << "Could not find/load indexes." << endl;
cerr << reader.GetErrorString() << endl;
reader.Close();
exit(1);
}
}
}
void MultiCovBam::LoadBamFileMap(void)
{
for (size_t i = 0; i < _bam_files.size(); ++i)
{
bamFileMap[_bam_files[i]] = i;
}
}
void MultiCovBam::ReportCounts(const vector<int> &counts)
{
for (size_t i = 0; i < counts.size(); ++i)
{
if (i < counts.size() - 1)
cout << counts[i] << "\t";
else
cout << counts[i];
}
cout << endl;
}
<|endoftext|>
|
<commit_before>// MS WARNINGS MACRO
#define _SCL_SECURE_NO_WARNINGS
#include <iostream>
#include <array>
#include <deque>
#include <boost/noncopyable.hpp>
#include "data_type.hpp"
#include "pixel_sorter.hpp"
#include "ppm_reader.hpp"
#include "splitter.hpp"
#include "algorithm.hpp"
#include "algorithm_2.hpp"
#include "gui.hpp"
#include "network.hpp"
#include <sort_algorithm/yrange2.hpp>
#include <sort_algorithm/yrange5.hpp>
#include <sort_algorithm/genetic.hpp>
#include <sort_algorithm/Murakami.hpp>
class position_manager
{
public:
typedef question_data position_type;
position_manager() = default;
virtual ~position_manager() = default;
template<class T>
void add(T && pos)
{
std::lock_guard<std::mutex> lock(mutex_);
items_.push_back(std::forward<T>(pos));
}
position_type get()
{
std::lock_guard<std::mutex> lock(mutex_);
auto res = items_.front();
items_.pop_front();
return res;
}
bool empty()
{
return items_.empty();
}
private:
std::mutex mutex_;
std::deque<position_type> items_;
};
class analyzer : boost::noncopyable
{
public:
explicit analyzer(int const problem_id, std::string const& player_id)
: client_(), problem_id_(problem_id), player_id_(player_id)
{
}
virtual ~analyzer() = default;
void operator() (position_manager& manager)
{
// 問題文の入手
raw_data_ = get_raw_question();
data_ = get_skelton_question(raw_data_);
// 2次元画像に分割
split_image_ = splitter().split_image(raw_data_);
// 原画像推測部
// TODO: yrangeなどの実行
auto sorter_resolve = sorter_(raw_data_, split_image_);
//data_.block = std::move(sorter_resolve);
data_.block = sorter_resolve;
manager.add(convert_block(data_)); // 解答
// TODO: yrange5の実行(並列化)
// 画面表示をいくつか(yrange/Murakmi/yrange5/algo2 etc.)
std::vector<boost::shared_ptr<gui::impl::MoveWindow>> windows;
windows.push_back(
gui::make_mansort_window(split_image_, sorter_resolve, "Murakami")
);
windows.push_back(
gui::make_mansort_window(split_image_, sorter_resolve, "Murakami")
);
boost::thread th(
[&]()
{
// futureリストでvalidを巡回し,閉じられたWindowから解とする
while(!windows.empty())
{
for(auto it = windows.begin(); it != windows.end();)
{
auto res = gui::get_result(*it);
if(res)
{
data_.block = res.get();
manager.add(convert_block(data_)); // 解答
it = windows.erase(it);
}
else ++it;
}
}
});
gui::wait_all_window();
th.join();
}
std::string submit(answer_type const& ans) const
{
auto submit_result = client_.submit(problem_id_, player_id_, ans);
return submit_result.get();
}
private:
question_raw_data get_raw_question() const
{
#if 1
// ファイルから
std::string const path("prob01.ppm");
return ppm_reader().from_file(path);
#else
// ネットワーク通信から
std::string const data = client_.get_problem(01).get();
return ppm_reader().from_data(data);
#endif
}
question_data get_skelton_question(question_raw_data const& raw) const
{
question_data formed = {
problem_id_,
player_id_,
raw.split_num,
raw.selectable_num,
raw.cost.first,
raw.cost.second,
std::vector<std::vector<point_type>>()
};
return formed;
}
question_data convert_block(question_data const& data) const
{
auto res = data.clone();
for(int i = 0; i < data.size.second; ++i)
{
for(int j = 0; j < data.size.first; ++j)
{
auto const& target = data.block[i][j];
res.block[target.y][target.x] = point_type{j, i};
}
}
return res;
}
int const problem_id_;
std::string const player_id_;
question_raw_data raw_data_;
question_data data_;
split_image_type split_image_;
mutable network::client client_;
pixel_sorter<Murakami> sorter_;
};
question_data convert_block(question_data const& data)
{
auto res = data.clone();
for(int i = 0; i < data.size.second; ++i)
{
for(int j = 0; j < data.size.first; ++j)
{
auto const& target = data.block[i][j];
res.block[target.y][target.x] = point_type{j, i};
}
}
return res;
}
int main()
{
auto const ploblemid = 1;
auto const token = "3935105806";
analyzer analyze(ploblemid, token);
algorithm_2 algo;
position_manager manager;
boost::thread thread(boost::bind(&analyzer::operator(), &analyze, std::ref(manager)));
while(true)
{
if(!manager.empty())
{
// 手順探索部
algo.reset(manager.get());
auto const answer = algo.get();
if(answer)
{
// 解が見つかった
// TODO: 前より良くなったら提出など
// auto result = analyze.submit(answer.get());
// std::cout << "Submit Result: " << result << std::endl;
std::cout << "Test";
}
}
}
thread.join();
return 0;
}
<commit_msg>サーバ通信で問題を取ってくるか,ローカルの問題を使うかの選択をマクロに<commit_after>// MS WARNINGS MACRO
#define _SCL_SECURE_NO_WARNINGS
// Macro: Program Settings
#define ENABLE_NETWORK_IO 0
#include <iostream>
#include <deque>
#include <boost/noncopyable.hpp>
#include "data_type.hpp"
#include "pixel_sorter.hpp"
#include "ppm_reader.hpp"
#include "splitter.hpp"
#include "algorithm.hpp"
#include "algorithm_2.hpp"
#include "gui.hpp"
#include "network.hpp"
#include <sort_algorithm/yrange2.hpp>
#include <sort_algorithm/yrange5.hpp>
#include <sort_algorithm/genetic.hpp>
#include <sort_algorithm/Murakami.hpp>
class position_manager : boost::noncopyable
{
public:
typedef question_data position_type;
position_manager() = default;
virtual ~position_manager() = default;
template<class T>
void add(T && pos)
{
std::lock_guard<std::mutex> lock(mutex_);
items_.push_back(std::forward<T>(pos));
}
position_type get()
{
std::lock_guard<std::mutex> lock(mutex_);
auto res = items_.front();
items_.pop_front();
return res;
}
bool empty()
{
return items_.empty();
}
private:
std::mutex mutex_;
std::deque<position_type> items_;
};
class analyzer : boost::noncopyable
{
public:
explicit analyzer(int const problem_id, std::string const& player_id)
: client_(), problem_id_(problem_id), player_id_(player_id)
{
}
virtual ~analyzer() = default;
void operator() (position_manager& manager)
{
// 問題文の入手
raw_data_ = get_raw_question();
data_ = get_skelton_question(raw_data_);
// 2次元画像に分割
split_image_ = splitter().split_image(raw_data_);
// 原画像推測部
// TODO: yrangeなどの実行
auto sorter_resolve = sorter_(raw_data_, split_image_);
//data_.block = std::move(sorter_resolve);
data_.block = sorter_resolve;
manager.add(convert_block(data_)); // 解答
// TODO: yrange5の実行(並列化)
// 画面表示をいくつか(yrange/Murakmi/yrange5/algo2 etc.)
std::vector<boost::shared_ptr<gui::impl::MoveWindow>> windows;
windows.push_back(
gui::make_mansort_window(split_image_, sorter_resolve, "Murakami")
);
windows.push_back(
gui::make_mansort_window(split_image_, sorter_resolve, "Murakami")
);
boost::thread th(
[&]()
{
// futureリストでvalidを巡回し,閉じられたWindowから解とする
while(!windows.empty())
{
for(auto it = windows.begin(); it != windows.end();)
{
auto res = gui::get_result(*it);
if(res)
{
data_.block = res.get();
manager.add(convert_block(data_)); // 解答
it = windows.erase(it);
}
else ++it;
}
}
});
gui::wait_all_window();
th.join();
}
std::string submit(answer_type const& ans) const
{
auto submit_result = client_.submit(problem_id_, player_id_, ans);
return submit_result.get();
}
private:
question_raw_data get_raw_question() const
{
#if ENABLE_NETWORK_IO
// ネットワーク通信から
std::string const data = client_.get_problem(01).get();
return ppm_reader().from_data(data);
#else
// ファイルから
std::string const path("prob01.ppm");
return ppm_reader().from_file(path);
#endif
}
question_data get_skelton_question(question_raw_data const& raw) const
{
question_data formed = {
problem_id_,
player_id_,
raw.split_num,
raw.selectable_num,
raw.cost.first,
raw.cost.second,
std::vector<std::vector<point_type>>()
};
return formed;
}
question_data convert_block(question_data const& data) const
{
auto res = data.clone();
for(int i = 0; i < data.size.second; ++i)
{
for(int j = 0; j < data.size.first; ++j)
{
auto const& target = data.block[i][j];
res.block[target.y][target.x] = point_type{j, i};
}
}
return res;
}
int const problem_id_;
std::string const player_id_;
question_raw_data raw_data_;
question_data data_;
split_image_type split_image_;
mutable network::client client_;
pixel_sorter<Murakami> sorter_;
};
question_data convert_block(question_data const& data)
{
auto res = data.clone();
for(int i = 0; i < data.size.second; ++i)
{
for(int j = 0; j < data.size.first; ++j)
{
auto const& target = data.block[i][j];
res.block[target.y][target.x] = point_type{j, i};
}
}
return res;
}
int main()
{
auto const ploblemid = 1;
auto const token = "3935105806";
analyzer analyze(ploblemid, token);
algorithm_2 algo;
position_manager manager;
boost::thread thread(boost::bind(&analyzer::operator(), &analyze, std::ref(manager)));
while(true)
{
if(!manager.empty())
{
// 手順探索部
algo.reset(manager.get());
auto const answer = algo.get();
if(answer)
{
// 解が見つかった
// TODO: 前より良くなったら提出など
// auto result = analyze.submit(answer.get());
// std::cout << "Submit Result: " << result << std::endl;
std::cout << "Test";
}
}
}
thread.join();
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <AL/al.h>
namespace Audio {
/// Interface for sound files of various formats.
/**
* Used to get raw audio data to a SoundBuffer.
*/
class SoundFile {
public:
/// Destructor.
virtual ~SoundFile() { }
/// Get raw audio data.
/**
* @return Raw audio data.
*/
virtual const char* GetData() const = 0;
/// Get data size.
/**
* @return The length of the raw audio data.
*/
virtual ALsizei GetSize() const = 0;
/// Get AL format.
/**
* 32-bit sound is not supported in OpenAL.
* @return One of AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 or AL_FORMAT_STEREO16.
*/
virtual ALenum GetFormat() const = 0;
/// Get sample rate.
/**
* @return The sound file's sample rate (Hz).
*/
virtual ALsizei GetSampleRate() const = 0;
};
}
<commit_msg>Fix indentation<commit_after>#pragma once
#include <AL/al.h>
namespace Audio {
/// Interface for sound files of various formats.
/**
* Used to get raw audio data to a SoundBuffer.
*/
class SoundFile {
public:
/// Destructor.
virtual ~SoundFile() { }
/// Get raw audio data.
/**
* @return Raw audio data.
*/
virtual const char* GetData() const = 0;
/// Get data size.
/**
* @return The length of the raw audio data.
*/
virtual ALsizei GetSize() const = 0;
/// Get AL format.
/**
* 32-bit sound is not supported in OpenAL.
* @return One of AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 or AL_FORMAT_STEREO16.
*/
virtual ALenum GetFormat() const = 0;
/// Get sample rate.
/**
* @return The sound file's sample rate (Hz).
*/
virtual ALsizei GetSampleRate() const = 0;
};
}
<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright (c) 2012-2019 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_DetailsTreeVisualization.hpp>
#include <DTK_LinearBVH.hpp>
#include <Kokkos_Core.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <algorithm>
#include <fstream>
#include <random>
#include <point_clouds.hpp>
template <typename View>
void printPointCloud( View points, std::ostream &os )
{
auto const n = points.extent_int( 0 );
for ( int i = 0; i < n; ++i )
os << "\\node[leaf] at (" << points( i )[0] << "," << points( i )[1]
<< ") {\\textbullet};\n";
}
template <typename TreeType>
void viz()
{
using DeviceType = typename TreeType::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
Kokkos::View<DataTransferKit::Point *, DeviceType> points( "points" );
loadPointCloud( "/scratch/source/trilinos/release/DataTransferKit/packages/"
"Search/examples/point_clouds/leaf_cloud.txt",
points );
TreeType bvh( points );
std::fstream fout;
std::string const prefix = "trash_";
// Print the point cloud
fout.open( prefix + "points.tex", std::fstream::out );
printPointCloud( points, fout );
fout.close();
// Print the entire tree
fout.open( prefix + "tree_all_nodes_and_edges.dot.m4", std::fstream::out );
using TreeVisualization =
typename DataTransferKit::Details::TreeVisualization<DeviceType>;
using GraphvizVisitor = typename TreeVisualization::GraphvizVisitor;
TreeVisualization::visitAllIterative( bvh, GraphvizVisitor{fout} );
fout.close();
int const n_neighbors = 10;
int const n_queries = bvh.size();
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType>
queries( "queries", n_queries );
Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::nearest(
points( i ), n_neighbors );
} );
Kokkos::fence();
for ( int i = 0; i < n_queries; ++i )
{
fout.open( prefix + "untouched_" + std::to_string( i ) +
"_nearest_traversal.dot.m4",
std::fstream::out );
TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} );
fout.close();
}
// Shuffle the queries
std::random_device rd;
std::mt19937 g( rd() );
std::shuffle( queries.data(), queries.data() + queries.size(), g );
for ( int i = 0; i < n_queries; ++i )
{
fout.open( prefix + "shuffled_" + std::to_string( i ) +
"_nearest_traversal.dot.m4",
std::fstream::out );
TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} );
fout.close();
}
// Sort them
auto permute = DataTransferKit::Details::BatchedQueries<
DeviceType>::sortQueriesAlongZOrderCurve( bvh.bounds(), queries );
queries =
DataTransferKit::Details::BatchedQueries<DeviceType>::applyPermutation(
permute, queries );
for ( int i = 0; i < n_queries; ++i )
{
fout.open( prefix + "sorted_" + std::to_string( i ) +
"_nearest_traversal.dot.m4",
std::fstream::out );
TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} );
fout.close();
}
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
using Serial = Kokkos::Compat::KokkosSerialWrapperNode::device_type;
using Tree = DataTransferKit::BVH<Serial>;
viz<Tree>();
Kokkos::finalize();
return 0;
}
<commit_msg>Traverse the entire tree and print all bounding volumes<commit_after>/****************************************************************************
* Copyright (c) 2012-2019 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_DetailsTreeVisualization.hpp>
#include <DTK_LinearBVH.hpp>
#include <Kokkos_Core.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <algorithm>
#include <fstream>
#include <random>
#include <point_clouds.hpp>
template <typename View>
void printPointCloud( View points, std::ostream &os )
{
auto const n = points.extent_int( 0 );
for ( int i = 0; i < n; ++i )
os << "\\node[leaf] at (" << points( i )[0] << "," << points( i )[1]
<< ") {\\textbullet};\n";
}
template <typename TreeType>
void viz()
{
using DeviceType = typename TreeType::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
Kokkos::View<DataTransferKit::Point *, DeviceType> points( "points" );
loadPointCloud( "/scratch/source/trilinos/release/DataTransferKit/packages/"
"Search/examples/point_clouds/leaf_cloud.txt",
points );
TreeType bvh( points );
std::fstream fout;
std::string const prefix = "trash_";
// Print the point cloud
fout.open( prefix + "points.tex", std::fstream::out );
printPointCloud( points, fout );
fout.close();
using TreeVisualization =
typename DataTransferKit::Details::TreeVisualization<DeviceType>;
using TikZVisitor = typename TreeVisualization::TikZVisitor;
using GraphvizVisitor = typename TreeVisualization::GraphvizVisitor;
// Print the bounding volume hierarchy
fout.open( prefix + "bounding_volumes.tex", std::fstream::out );
TreeVisualization::visitAllIterative( bvh, TikZVisitor{fout} );
fout.close();
// Print the entire tree
fout.open( prefix + "tree_all_nodes_and_edges.dot.m4", std::fstream::out );
TreeVisualization::visitAllIterative( bvh, GraphvizVisitor{fout} );
fout.close();
int const n_neighbors = 10;
int const n_queries = bvh.size();
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType>
queries( "queries", n_queries );
Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::nearest(
points( i ), n_neighbors );
} );
Kokkos::fence();
for ( int i = 0; i < n_queries; ++i )
{
fout.open( prefix + "untouched_" + std::to_string( i ) +
"_nearest_traversal.dot.m4",
std::fstream::out );
TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} );
fout.close();
}
// Shuffle the queries
std::random_device rd;
std::mt19937 g( rd() );
std::shuffle( queries.data(), queries.data() + queries.size(), g );
for ( int i = 0; i < n_queries; ++i )
{
fout.open( prefix + "shuffled_" + std::to_string( i ) +
"_nearest_traversal.dot.m4",
std::fstream::out );
TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} );
fout.close();
}
// Sort them
auto permute = DataTransferKit::Details::BatchedQueries<
DeviceType>::sortQueriesAlongZOrderCurve( bvh.bounds(), queries );
queries =
DataTransferKit::Details::BatchedQueries<DeviceType>::applyPermutation(
permute, queries );
for ( int i = 0; i < n_queries; ++i )
{
fout.open( prefix + "sorted_" + std::to_string( i ) +
"_nearest_traversal.dot.m4",
std::fstream::out );
TreeVisualization::visit( bvh, queries( i ), GraphvizVisitor{fout} );
fout.close();
}
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
using Serial = Kokkos::Compat::KokkosSerialWrapperNode::device_type;
using Tree = DataTransferKit::BVH<Serial>;
viz<Tree>();
Kokkos::finalize();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2014 Martin Klapetek <mklapetek@kde.org>
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
*/
#include "kaccounts-ktp-plugin.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/Profile>
#include <TelepathyQt/ConnectionManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingAccount>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/PendingVariant>
#include <TelepathyQt/AccountSet>
#include <TelepathyQt/AccountInterfaceStorageInterface>
#include <TelepathyQt/Utils>
#include <TelepathyQt/PendingVariantMap>
#include <KSharedConfig>
#include <KConfigGroup>
#include <QTimer>
#include <QStandardPaths>
#include <QDir>
#include <KTp/Logger/log-manager.h>
#include <Accounts/Service>
#include <Accounts/Manager>
#include <Accounts/Account>
#include <Accounts/AccountService>
#include <KAccounts/getcredentialsjob.h>
#include <KAccounts/core.h>
static QStringList s_knownProviders{QStringLiteral("haze-icq"),
QStringLiteral("jabber"),
QStringLiteral("kde-talk"),
QStringLiteral("haze-sametime"),
QStringLiteral("haze-yahoo"),
QStringLiteral("haze-gadugadu")};
class KAccountsKTpPlugin::Private {
public:
Private(KAccountsKTpPlugin *qq) { q = qq; };
Tp::AccountPtr tpAccountForAccountId(const Accounts::AccountId accountId);
void migrateTelepathyAccounts();
void migrateLogs(const QString &tpAccountId, const Accounts::AccountId accountId);
Tp::AccountManagerPtr accountManager;
Tp::ConnectionManagerPtr connectionManager;
Tp::ProfilePtr profile;
KSharedConfigPtr kaccountsConfig;
QString logsBasePath;
KAccountsKTpPlugin *q;
};
Tp::AccountPtr KAccountsKTpPlugin::Private::tpAccountForAccountId(const Accounts::AccountId accountId)
{
kaccountsConfig->reparseConfiguration();
KConfigGroup ktpKaccountsGroup = kaccountsConfig->group(QStringLiteral("kaccounts-ktp"));
QString accountUid = ktpKaccountsGroup.readEntry(QString::number(accountId));
return accountManager->accountForObjectPath(accountUid);
}
void KAccountsKTpPlugin::Private::migrateTelepathyAccounts()
{
Q_FOREACH (const Tp::AccountPtr &account, accountManager->validAccounts()->accounts()) {
KConfigGroup kaccountsKtpGroup = kaccountsConfig->group(QStringLiteral("ktp-kaccounts"));
const Accounts::AccountId kaccountsId = kaccountsKtpGroup.readEntry(account->objectPath(), 0);
qDebug() << "Looking at" << account->objectPath();
qDebug() << " KAccounts id" << kaccountsId;
if (kaccountsId != 0) {
migrateLogs(account->objectPath(), kaccountsId);
Accounts::Account *kaccount = KAccounts::accountsManager()->account(kaccountsId);
auto services = kaccount->services(QStringLiteral("IM"));
if (services.size() > 0) {
qDebug() << "Writing service data:" << account->cmName() << account->protocolName() << account->serviceName();
Accounts::Service imService = services.at(0);
Accounts::AccountService accountService(kaccount, imService);
accountService.setValue("telepathy/manager", account->cmName());
accountService.setValue("telepathy/protocol", account->protocolName());
kaccount->sync();
}
// Remove the mapping from the config file
kaccountsKtpGroup.deleteEntry(account->objectPath());
KConfigGroup ktpKaccountsGroup = kaccountsConfig->group(QStringLiteral("kaccounts-ktp"));
ktpKaccountsGroup.deleteEntry(QString::number(kaccountsId));
kaccount->deleteLater();
// Remove the old Tp Account; the new one will be served by the MC plugin directly
account->remove();
} else {
// Get account storage interface for checking if this account is not already handled
// by Accounts SSO MC plugin
Tp::Client::AccountInterfaceStorageInterface storageInterface(account.data());
Tp::PendingVariant *data = storageInterface.requestPropertyStorageProvider();
data->setProperty("accountObjectPath", account->objectPath());
QObject::connect(data, &Tp::PendingOperation::finished, q, &KAccountsKTpPlugin::onStorageProviderRetrieved);
}
}
}
void KAccountsKTpPlugin::onStorageProviderRetrieved(Tp::PendingOperation *op)
{
const QString storageProvider = qobject_cast<Tp::PendingVariant*>(op)->result().toString();
if (storageProvider == QLatin1String("im.telepathy.Account.Storage.AccountsSSO")) {
qDebug() << "Found Tp Account with AccountsSSO provider, skipping...";
return;
}
qDebug() << "No KAccounts id, creating new account";
Accounts::Account *kaccount;
Tp::AccountPtr account = d->accountManager->accountForObjectPath(op->property("accountObjectPath").toString());
if (account.isNull() || !account->isValid()) {
qDebug() << "An invalid Tp Account retrieved, aborting...";
return;
}
QString providerName = QStringLiteral("ktp-");
if (s_knownProviders.contains(account->serviceName())) {
providerName.append(account->serviceName());
} else {
providerName.append(QStringLiteral("generic"));
}
qDebug() << "Creating account with providerName" << providerName;
kaccount = KAccounts::accountsManager()->createAccount(providerName);
kaccount->setDisplayName(account->displayName());
kaccount->setValue(QStringLiteral("uid"), account->objectPath());
kaccount->setValue(QStringLiteral("username"), account->nickname());
kaccount->setValue(QStringLiteral("auth/mechanism"), QStringLiteral("password"));
kaccount->setValue(QStringLiteral("auth/method"), QStringLiteral("password"));
kaccount->setEnabled(true);
Accounts::ServiceList services = kaccount->services();
Q_FOREACH(const Accounts::Service &service, services) {
kaccount->selectService(service);
kaccount->setEnabled(account->isEnabled());
if (service.serviceType() == QLatin1String("IM")) {
// Set the telepathy/ settings on the service so that
// the MC plugin can use this service
Accounts::AccountService accountService(kaccount, service);
accountService.setValue("telepathy/manager", account->cmName());
accountService.setValue("telepathy/protocol", account->protocolName());
}
}
kaccount->sync();
QObject::connect(kaccount, &Accounts::Account::synced, this, &KAccountsKTpPlugin::onAccountSynced);
}
void KAccountsKTpPlugin::onAccountSynced()
{
Accounts::Account *account = qobject_cast<Accounts::Account*>(sender());
if (!account) {
return;
}
const QString tpAccountId = account->value(QStringLiteral("uid")).toString();
d->migrateLogs(tpAccountId, account->id());
Tp::AccountPtr tpAccount = d->accountManager->accountForObjectPath(tpAccountId);
// Remove the old Tp Account; the new one will be served by the MC plugin directly
tpAccount->remove();
}
void KAccountsKTpPlugin::Private::migrateLogs(const QString &tpAccountId, const Accounts::AccountId accountId)
{
if (tpAccountId.isEmpty() || accountId == 0) {
qWarning() << "Cannot finish migration because of empty data received: TP account id:" << tpAccountId << "KAccounts ID:" << accountId;
return;
}
if (logsBasePath.isEmpty()) {
logsBasePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/TpLogger/logs");
}
Tp::AccountPtr tpAccount = accountManager->accountForObjectPath(tpAccountId);
if (tpAccount.isNull() || !tpAccount->isValid()) {
return;
}
// Construct the new dir which is in form "$cmName_$protocol_ktp_2d$service_name_$KAccountsID"
// eg. haze_icq_ktp_2d_haze_2dicq_2dim_24
QString newLogsDir = tpAccount->cmName() + QLatin1Char('_') + tpAccount->protocolName() + QLatin1Char('_');
if (tpAccount->serviceName() == QLatin1String("google-talk")) {
newLogsDir += QStringLiteral("google_2dim");
} else {
newLogsDir += Tp::escapeAsIdentifier(QStringLiteral("ktp-") + tpAccount->serviceName());
}
newLogsDir += QLatin1Char('_') + QString::number(accountId);
QString accountLogsDir = tpAccount->uniqueIdentifier();
/* Escape '/' in tpAccountId as '_' */
if (accountLogsDir.contains(QLatin1Char('/'))) {
accountLogsDir.replace(QLatin1Char('/'), QLatin1String("_"));
}
QDir logsDir(logsBasePath);
qDebug() << "Migrating logs for" << accountLogsDir << "into" << newLogsDir;
bool renamed = false;
if (logsDir.exists()) {
renamed = logsDir.rename(accountLogsDir, newLogsDir);
}
if (!renamed) {
qWarning() << "Could not rename the directory!";
}
}
//---------------------------------------------------------------------------------------
KAccountsKTpPlugin::KAccountsKTpPlugin(QObject *parent)
: KAccountsDPlugin(parent),
d(new Private(this))
{
d->kaccountsConfig = KSharedConfig::openConfig(QStringLiteral("kaccounts-ktprc"));
Tp::registerTypes();
// Start setting up the Telepathy AccountManager.
Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Account::FeatureCore);
d->accountManager = Tp::AccountManager::create(accountFactory);
// There should be well enough time between AM finishes getting ready and before it's needed,
// so there's no slot watching "finished"
connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
KAccountsKTpPlugin::~KAccountsKTpPlugin()
{
}
void KAccountsKTpPlugin::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qWarning() << "Failed initializing AccountManager";
return;
}
d->migrateTelepathyAccounts();
}
void KAccountsKTpPlugin::onAccountCreated(const Accounts::AccountId accountId, const Accounts::ServiceList &serviceList)
{
//TODO: should we connect the new account here?
}
void KAccountsKTpPlugin::onAccountRemoved(const Accounts::AccountId accountId)
{
}
void KAccountsKTpPlugin::onServiceEnabled(const Accounts::AccountId accountId, const Accounts::Service &service)
{
}
void KAccountsKTpPlugin::onServiceDisabled(const Accounts::AccountId accountId, const Accounts::Service &service)
{
}
<commit_msg>[kaccounts] Make the debug output more useful<commit_after>/*
Copyright (C) 2014 Martin Klapetek <mklapetek@kde.org>
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
*/
#include "kaccounts-ktp-plugin.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/Profile>
#include <TelepathyQt/ConnectionManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingAccount>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/PendingVariant>
#include <TelepathyQt/AccountSet>
#include <TelepathyQt/AccountInterfaceStorageInterface>
#include <TelepathyQt/Utils>
#include <TelepathyQt/PendingVariantMap>
#include <KSharedConfig>
#include <KConfigGroup>
#include <QTimer>
#include <QStandardPaths>
#include <QDir>
#include <KTp/Logger/log-manager.h>
#include <Accounts/Service>
#include <Accounts/Manager>
#include <Accounts/Account>
#include <Accounts/AccountService>
#include <KAccounts/getcredentialsjob.h>
#include <KAccounts/core.h>
static QStringList s_knownProviders{QStringLiteral("haze-icq"),
QStringLiteral("jabber"),
QStringLiteral("kde-talk"),
QStringLiteral("haze-sametime"),
QStringLiteral("haze-yahoo"),
QStringLiteral("haze-gadugadu")};
class KAccountsKTpPlugin::Private {
public:
Private(KAccountsKTpPlugin *qq) { q = qq; };
Tp::AccountPtr tpAccountForAccountId(const Accounts::AccountId accountId);
void migrateTelepathyAccounts();
void migrateLogs(const QString &tpAccountId, const Accounts::AccountId accountId);
Tp::AccountManagerPtr accountManager;
Tp::ConnectionManagerPtr connectionManager;
Tp::ProfilePtr profile;
KSharedConfigPtr kaccountsConfig;
QString logsBasePath;
KAccountsKTpPlugin *q;
};
Tp::AccountPtr KAccountsKTpPlugin::Private::tpAccountForAccountId(const Accounts::AccountId accountId)
{
kaccountsConfig->reparseConfiguration();
KConfigGroup ktpKaccountsGroup = kaccountsConfig->group(QStringLiteral("kaccounts-ktp"));
QString accountUid = ktpKaccountsGroup.readEntry(QString::number(accountId));
return accountManager->accountForObjectPath(accountUid);
}
void KAccountsKTpPlugin::Private::migrateTelepathyAccounts()
{
Q_FOREACH (const Tp::AccountPtr &account, accountManager->validAccounts()->accounts()) {
KConfigGroup kaccountsKtpGroup = kaccountsConfig->group(QStringLiteral("ktp-kaccounts"));
const Accounts::AccountId kaccountsId = kaccountsKtpGroup.readEntry(account->objectPath(), 0);
qDebug() << "Looking at" << account->objectPath();
qDebug() << " KAccounts id" << kaccountsId;
if (kaccountsId != 0) {
migrateLogs(account->objectPath(), kaccountsId);
Accounts::Account *kaccount = KAccounts::accountsManager()->account(kaccountsId);
auto services = kaccount->services(QStringLiteral("IM"));
if (services.size() > 0) {
qDebug() << "Writing service data:" << account->cmName() << account->protocolName() << account->serviceName();
Accounts::Service imService = services.at(0);
Accounts::AccountService accountService(kaccount, imService);
accountService.setValue("telepathy/manager", account->cmName());
accountService.setValue("telepathy/protocol", account->protocolName());
kaccount->sync();
}
// Remove the mapping from the config file
kaccountsKtpGroup.deleteEntry(account->objectPath());
KConfigGroup ktpKaccountsGroup = kaccountsConfig->group(QStringLiteral("kaccounts-ktp"));
ktpKaccountsGroup.deleteEntry(QString::number(kaccountsId));
kaccount->deleteLater();
// Remove the old Tp Account; the new one will be served by the MC plugin directly
account->remove();
} else {
// Get account storage interface for checking if this account is not already handled
// by Accounts SSO MC plugin
Tp::Client::AccountInterfaceStorageInterface storageInterface(account.data());
Tp::PendingVariant *data = storageInterface.requestPropertyStorageProvider();
data->setProperty("accountObjectPath", account->objectPath());
QObject::connect(data, &Tp::PendingOperation::finished, q, &KAccountsKTpPlugin::onStorageProviderRetrieved);
}
}
}
void KAccountsKTpPlugin::onStorageProviderRetrieved(Tp::PendingOperation *op)
{
const QString storageProvider = qobject_cast<Tp::PendingVariant*>(op)->result().toString();
const QString accountObjectPath = op->property("accountObjectPath").toString();
if (storageProvider == QLatin1String("im.telepathy.Account.Storage.AccountsSSO")) {
qDebug() << "Found Tp Account" << accountObjectPath << "with AccountsSSO provider, skipping...";
return;
}
qDebug() << "Creating new KAccounts account for" << accountObjectPath;
Accounts::Account *kaccount;
Tp::AccountPtr account = d->accountManager->accountForObjectPath(accountObjectPath);
if (account.isNull() || !account->isValid()) {
qDebug() << "An invalid Tp Account retrieved, aborting...";
return;
}
QString providerName = QStringLiteral("ktp-");
if (s_knownProviders.contains(account->serviceName())) {
providerName.append(account->serviceName());
} else {
providerName.append(QStringLiteral("generic"));
}
qDebug() << "Creating account with providerName" << providerName;
kaccount = KAccounts::accountsManager()->createAccount(providerName);
kaccount->setDisplayName(account->displayName());
kaccount->setValue(QStringLiteral("uid"), account->objectPath());
kaccount->setValue(QStringLiteral("username"), account->nickname());
kaccount->setValue(QStringLiteral("auth/mechanism"), QStringLiteral("password"));
kaccount->setValue(QStringLiteral("auth/method"), QStringLiteral("password"));
kaccount->setEnabled(true);
Accounts::ServiceList services = kaccount->services();
Q_FOREACH(const Accounts::Service &service, services) {
kaccount->selectService(service);
kaccount->setEnabled(account->isEnabled());
if (service.serviceType() == QLatin1String("IM")) {
// Set the telepathy/ settings on the service so that
// the MC plugin can use this service
Accounts::AccountService accountService(kaccount, service);
accountService.setValue("telepathy/manager", account->cmName());
accountService.setValue("telepathy/protocol", account->protocolName());
}
}
kaccount->sync();
QObject::connect(kaccount, &Accounts::Account::synced, this, &KAccountsKTpPlugin::onAccountSynced);
}
void KAccountsKTpPlugin::onAccountSynced()
{
Accounts::Account *account = qobject_cast<Accounts::Account*>(sender());
if (!account) {
return;
}
const QString tpAccountId = account->value(QStringLiteral("uid")).toString();
d->migrateLogs(tpAccountId, account->id());
Tp::AccountPtr tpAccount = d->accountManager->accountForObjectPath(tpAccountId);
// Remove the old Tp Account; the new one will be served by the MC plugin directly
tpAccount->remove();
}
void KAccountsKTpPlugin::Private::migrateLogs(const QString &tpAccountId, const Accounts::AccountId accountId)
{
if (tpAccountId.isEmpty() || accountId == 0) {
qWarning() << "Cannot finish migration because of empty data received: TP account id:" << tpAccountId << "KAccounts ID:" << accountId;
return;
}
if (logsBasePath.isEmpty()) {
logsBasePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/TpLogger/logs");
}
Tp::AccountPtr tpAccount = accountManager->accountForObjectPath(tpAccountId);
if (tpAccount.isNull() || !tpAccount->isValid()) {
qDebug() << "Invalid account for" << tpAccountId << "aborting...";
return;
}
// Construct the new dir which is in form "$cmName_$protocol_ktp_2d$service_name_$KAccountsID"
// eg. haze_icq_ktp_2d_haze_2dicq_2dim_24
QString newLogsDir = tpAccount->cmName() + QLatin1Char('_') + tpAccount->protocolName() + QLatin1Char('_');
if (tpAccount->serviceName() == QLatin1String("google-talk")) {
newLogsDir += QStringLiteral("google_2dim");
} else {
newLogsDir += Tp::escapeAsIdentifier(QStringLiteral("ktp-") + tpAccount->serviceName());
}
newLogsDir += QLatin1Char('_') + QString::number(accountId);
QString accountLogsDir = tpAccount->uniqueIdentifier();
/* Escape '/' in tpAccountId as '_' */
if (accountLogsDir.contains(QLatin1Char('/'))) {
accountLogsDir.replace(QLatin1Char('/'), QLatin1String("_"));
}
QDir logsDir(logsBasePath);
qDebug() << "Migrating logs for" << accountLogsDir << "into" << newLogsDir;
bool renamed = false;
if (logsDir.exists()) {
renamed = logsDir.rename(accountLogsDir, newLogsDir);
}
if (!renamed) {
qWarning() << "Could not rename the directory!";
}
}
//---------------------------------------------------------------------------------------
KAccountsKTpPlugin::KAccountsKTpPlugin(QObject *parent)
: KAccountsDPlugin(parent),
d(new Private(this))
{
d->kaccountsConfig = KSharedConfig::openConfig(QStringLiteral("kaccounts-ktprc"));
Tp::registerTypes();
// Start setting up the Telepathy AccountManager.
Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
Tp::Features() << Tp::Account::FeatureCore);
d->accountManager = Tp::AccountManager::create(accountFactory);
// There should be well enough time between AM finishes getting ready and before it's needed,
// so there's no slot watching "finished"
connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
KAccountsKTpPlugin::~KAccountsKTpPlugin()
{
}
void KAccountsKTpPlugin::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qWarning() << "Failed initializing AccountManager";
return;
}
d->migrateTelepathyAccounts();
}
void KAccountsKTpPlugin::onAccountCreated(const Accounts::AccountId accountId, const Accounts::ServiceList &serviceList)
{
//TODO: should we connect the new account here?
}
void KAccountsKTpPlugin::onAccountRemoved(const Accounts::AccountId accountId)
{
}
void KAccountsKTpPlugin::onServiceEnabled(const Accounts::AccountId accountId, const Accounts::Service &service)
{
}
void KAccountsKTpPlugin::onServiceDisabled(const Accounts::AccountId accountId, const Accounts::Service &service)
{
}
<|endoftext|>
|
<commit_before>/** \file add_superior_flag.cc
* \author Oliver Obenland
*
* A tool for marking superior records that have associated inferior records in our data sets.
*/
/*
Copyright (C) 2016, Library of the University of Tübingen
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 <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "File.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
#include "XmlWriter.h"
static unsigned modified_count(0);
static std::set<std::string> superior_ppns;
static std::string superior_subfield_data;
void Usage() {
std::cerr << "Usage: " << progname << " marc_input marc_output superior_ppns\n";
std::exit(EXIT_FAILURE);
}
void ProcessRecord(XmlWriter * const xml_writer, MarcUtil::Record * const record) {
record->setRecordWillBeWrittenAsXml(true);
// Don't add the flag twice
if (record->getFieldIndex("SPR") != -1) {
record->write(xml_writer);
return;
}
const std::vector<std::string> &field_data(record->getFields());
const auto iter(superior_ppns.find(field_data.at(0)));
if (iter != superior_ppns.end()) {
if (not record->insertField("UBR", superior_subfield_data)) {
Warning("Not enough room to add a SPR field! (Control number: " + field_data[0] + ")");
}
++modified_count;
}
record->write(xml_writer);
}
void AddSuperiorFlag(File * const input, File * const output) {
XmlWriter xml_writer(output);
xml_writer.openTag("marc:collection",
{ std::make_pair("xmlns:marc", "http://www.loc.gov/MARC21/slim"),
std::make_pair("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"),
std::make_pair("xsi:schemaLocation", "http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd")});
while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input))
ProcessRecord(&xml_writer, &record);
xml_writer.closeTag();
std::cerr << "Modified " << modified_count << " record(s).\n";
}
void LoadSuperiorPPNs(const std::string &child_refs_filename) {
std::ifstream child_refs(child_refs_filename.c_str());
if (not child_refs.is_open())
Error("Failed to open \"" + child_refs_filename + "\" for reading!");
std::string line;
unsigned line_no(0);
while (std::getline(child_refs, line)) {
++line_no;
superior_ppns.emplace(line);
}
if (unlikely(superior_ppns.empty()))
Error("Found no data in \"" + child_refs_filename + "\"!");
std::cerr << "Read " << line_no << " superior PPNs.\n";
}
int main(int argc, char **argv) {
progname = argv[0];
if (argc != 4)
Usage();
const std::string marc_input_filename(argv[1]);
File marc_input(marc_input_filename, "rm");
if (not marc_input)
Error("can't open \"" + marc_input_filename + "\" for reading!");
const std::string marc_output_filename(argv[2]);
File marc_output(marc_output_filename, "w");
if (not marc_output)
Error("can't open \"" + marc_output_filename + "\" for writing!");
try {
LoadSuperiorPPNs(argv[3]);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
Subfields superior_subfield(/* indicator1 = */' ', /* indicator2 = */' ');
superior_subfield.addSubfield('a', "1");
superior_subfield_data = superior_subfield.toString();
AddSuperiorFlag(&marc_input, &marc_output);
}
<commit_msg>Update add_superior_flag.cc<commit_after>/** \file add_superior_flag.cc
* \author Oliver Obenland
*
* A tool for marking superior records that have associated inferior records in our data sets.
*/
/*
Copyright (C) 2016, Library of the University of Tübingen
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 <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "File.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
#include "XmlWriter.h"
static unsigned modified_count(0);
static std::set<std::string> superior_ppns;
static std::string superior_subfield_data;
void Usage() {
std::cerr << "Usage: " << progname << " marc_input marc_output superior_ppns\n";
std::exit(EXIT_FAILURE);
}
void ProcessRecord(XmlWriter * const xml_writer, MarcUtil::Record * const record) {
record->setRecordWillBeWrittenAsXml(true);
// Don't add the flag twice
if (record->getFieldIndex("SPR") != -1) {
record->write(xml_writer);
return;
}
const std::vector<std::string> &field_data(record->getFields());
const auto iter(superior_ppns.find(field_data.at(0)));
if (iter != superior_ppns.end()) {
if (not record->insertField("SPR", superior_subfield_data))
Warning("Not enough room to add a SPR field! (Control number: " + field_data[0] + ")");
++modified_count;
}
record->write(xml_writer);
}
void AddSuperiorFlag(File * const input, File * const output) {
XmlWriter xml_writer(output);
xml_writer.openTag("marc:collection",
{ std::make_pair("xmlns:marc", "http://www.loc.gov/MARC21/slim"),
std::make_pair("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"),
std::make_pair("xsi:schemaLocation", "http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd")});
while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input))
ProcessRecord(&xml_writer, &record);
xml_writer.closeTag();
std::cerr << "Modified " << modified_count << " record(s).\n";
}
void LoadSuperiorPPNs(const std::string &child_refs_filename) {
std::ifstream child_refs(child_refs_filename.c_str());
if (not child_refs.is_open())
Error("Failed to open \"" + child_refs_filename + "\" for reading!");
std::string line;
unsigned line_no(0);
while (std::getline(child_refs, line)) {
++line_no;
superior_ppns.emplace(line);
}
if (unlikely(superior_ppns.empty()))
Error("Found no data in \"" + child_refs_filename + "\"!");
std::cerr << "Read " << line_no << " superior PPNs.\n";
}
int main(int argc, char **argv) {
progname = argv[0];
if (argc != 4)
Usage();
const std::string marc_input_filename(argv[1]);
File marc_input(marc_input_filename, "rm");
if (not marc_input)
Error("can't open \"" + marc_input_filename + "\" for reading!");
const std::string marc_output_filename(argv[2]);
File marc_output(marc_output_filename, "w");
if (not marc_output)
Error("can't open \"" + marc_output_filename + "\" for writing!");
try {
LoadSuperiorPPNs(argv[3]);
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
Subfields superior_subfield(/* indicator1 = */' ', /* indicator2 = */' ');
superior_subfield.addSubfield('a', "1");
superior_subfield_data = superior_subfield.toString();
AddSuperiorFlag(&marc_input, &marc_output);
}
<|endoftext|>
|
<commit_before>
#include "AttrTokenizeWrapper.h"
#include <knlp/attr_tokenize.h>
#include <knlp/dictionary.h>
#include <exception>
#include <glog/logging.h>
#include <util/singleton.h>
#include <boost/filesystem.hpp>
using namespace sf1r;
namespace bfs = boost::filesystem;
AttrTokenizeWrapper::AttrTokenizeWrapper()
: isDictLoaded_(false)
{
}
AttrTokenizeWrapper::~AttrTokenizeWrapper()
{
}
AttrTokenizeWrapper* AttrTokenizeWrapper::get()
{
return izenelib::util::Singleton<AttrTokenizeWrapper>::get();
}
bool AttrTokenizeWrapper::loadDictFiles(const std::string& dictDir)
{
if (isDictLoaded_)
return true;
dictDir_ = dictDir;
LOG(INFO) << "Start loading attr_tokenize dictionaries in " << dictDir_;
const bfs::path dirPath(dictDir_);
try
{
attr_tokenizer_.reset(new ilplib::knlp::AttributeTokenize( dirPath.string() ));
LOG(INFO) << "load /single_term2cate.mapping" ;
std::string queryCate = "/single_term2cate.mapping";
queryMultiCatesDict_.reset(new ilplib::knlp::VectorDictionary(dictDir_ + queryCate));
}
catch (const std::exception& e)
{
LOG(ERROR) << "exception: " << e.what()
<< ", dictDir: " << dictDir_;
return false;
}
isDictLoaded_ = true;
LOG(INFO) << "Finished loading attr_tokenize dictionaries.";
return true;
}
void AttrTokenizeWrapper::attr_tokenize_index(
const std::string& title,
const std::string& attr,
const std::string& cate,
const std::string& ocate,
const std::string& source,
std::vector<std::pair<std::string, double> >& tokenScoreList)
{
attr_tokenizer_->tokenize(title, attr, cate, ocate, source, tokenScoreList);
}
void AttrTokenizeWrapper::attr_tokenize(
const std::string& Q,
std::vector<std::pair<std::string, int> >& tokenList)
{
attr_tokenizer_->tokenize(Q, tokenList);
}
bool AttrTokenizeWrapper::attr_subtokenize(
const std::vector<std::pair<std::string, int> >& tks,
std::vector<std::pair<std::string, int> >& tokenList)
{
attr_tokenizer_->subtokenize(tks, tokenList);
return tokenList != tks;
}
double AttrTokenizeWrapper::att_name_weight(
const std::string& attr_name,
const std::string& cate)
{
return attr_tokenizer_->att_weight(attr_name, cate);
}
double AttrTokenizeWrapper::att_value_weight(
const std::string& attr_name,
const std::string& attr_value,
const std::string& cate)
{
return attr_tokenizer_->att_weight(attr_name, attr_value, cate);
}
std::vector<char*>** AttrTokenizeWrapper::get_TermCategory(const std::string& query)
{
return queryMultiCatesDict_->value(KString(query), true);
}
<commit_msg>Category score is only used in attr_token index<commit_after>
#include "AttrTokenizeWrapper.h"
#include <knlp/attr_tokenize.h>
#include <knlp/dictionary.h>
#include <exception>
#include <glog/logging.h>
#include <util/singleton.h>
#include <boost/filesystem.hpp>
using namespace sf1r;
namespace bfs = boost::filesystem;
AttrTokenizeWrapper::AttrTokenizeWrapper()
: isDictLoaded_(false)
{
}
AttrTokenizeWrapper::~AttrTokenizeWrapper()
{
}
AttrTokenizeWrapper* AttrTokenizeWrapper::get()
{
return izenelib::util::Singleton<AttrTokenizeWrapper>::get();
}
bool AttrTokenizeWrapper::loadDictFiles(const std::string& dictDir)
{
if (isDictLoaded_)
return true;
dictDir_ = dictDir;
LOG(INFO) << "Start loading attr_tokenize dictionaries in " << dictDir_;
const bfs::path dirPath(dictDir_);
try
{
attr_tokenizer_.reset(new ilplib::knlp::AttributeTokenize( dirPath.string() ));
LOG(INFO) << "load /single_term2cate.mapping" ;
std::string queryCate = "/single_term2cate.mapping";
queryMultiCatesDict_.reset(new ilplib::knlp::VectorDictionary(dictDir_ + queryCate));
}
catch (const std::exception& e)
{
LOG(ERROR) << "exception: " << e.what()
<< ", dictDir: " << dictDir_;
return false;
}
isDictLoaded_ = true;
LOG(INFO) << "Finished loading attr_tokenize dictionaries.";
return true;
}
void AttrTokenizeWrapper::attr_tokenize_index(
const std::string& title,
const std::string& attr,
const std::string& cate,
const std::string& ocate,
const std::string& source,
std::vector<std::pair<std::string, double> >& tokenScoreList)
{
attr_tokenizer_->tokenize(title, attr, cate, ocate, source, tokenScoreList);
}
void AttrTokenizeWrapper::attr_tokenize(
const std::string& Q,
std::vector<std::pair<std::string, int> >& tokenList)
{
attr_tokenizer_->tokenize(Q, tokenList);
}
bool AttrTokenizeWrapper::attr_subtokenize(
const std::vector<std::pair<std::string, int> >& tks,
std::vector<std::pair<std::string, int> >& tokenList)
{
attr_tokenizer_->subtokenize(tks, tokenList);
return tokenList != tks;
}
double AttrTokenizeWrapper::att_name_weight(
const std::string& attr_name,
const std::string& cate)
{
return attr_tokenizer_->att_weight(attr_name, cate);
}
double AttrTokenizeWrapper::att_value_weight(
const std::string& attr_name,
const std::string& attr_value,
const std::string& cate)
{
return attr_tokenizer_->att_weight(attr_name, attr_value, cate);
}
std::vector<char*>** AttrTokenizeWrapper::get_TermCategory(const std::string& query)
{
if (!queryMultiCatesDict_)
return NULL;
return queryMultiCatesDict_->value(KString(query), true);
}
<|endoftext|>
|
<commit_before>///
/// @file LicenseManager.cpp
/// @brief A source file of license manager.
/// @author Dohyun Yun ( dualistmage@gmail.com )
/// @date 2010-05-18
///
#include "LicenseManager.h"
#include "LicenseRequestFileGenerator.h"
#include "LicenseTool.h"
#include <common/SFLogger.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <sstream>
using namespace sf1r;
using namespace license_module;
boost::mutex LicenseManager::mutex_;
license_module::license_max_doc_t LicenseManager::maxIndexSize_(0);
license_module::license_max_index_data_size_t LicenseManager::maxIndexFileSize_(0);
bool LicenseManager::continueIndex_(true);
const std::string LicenseManager::LICENSE_REQUEST_FILENAME = "sf1-license-request.dat";
const std::string LicenseManager::LICENSE_KEY_FILENAME = "sf1-license-key.dat";
const std::string LicenseManager::TOKEN_FILENAME = "token.dat";
const std::string LicenseManager::STOP_SERVICE_TOKEN = "@@ALL@@";
const std::string LicenseManager::START_SERVICE_TOKEN = "@@NONE@@";
LicenseManager::LicenseManager(const std::string& sf1Version, const std::string& licenseFilePath, bool systemInfoType):
systemInfoType_(systemInfoType)
{
std::string productCodeStr("SF1");
productCodeStr += sf1Version;
memcpy(&productCode_, productCodeStr.c_str(), sizeof(uint64_t));
licenseFilePath_ = licenseFilePath;
licenseClient_.reset(
new LicenseClient(
productCode_,
"127.0.0.1", // TODO
"23456", // TODO
licenseFilePath_,
systemInfoType)
);
} // end - LicenseManager()
bool LicenseManager::validateLicense()
{
#ifdef COBRA_RESTRICT
if ( licenseClient_ )
return licenseClient_->validateLicenseCertificate();
return false;
#else
return true;
#endif // COBRA_RESTICT
} // end - validateLicense()
bool LicenseManager::validateLicenseFile()
{
#ifdef COBRA_RESTRICT
if ( licenseClient_ )
return licenseClient_->validateLicenseFile(licenseFilePath_);
return false;
#else
return true;
#endif // COBRA_RESTICT
}
bool LicenseManager::createLicenseRequestFile(const std::string& licenseRequestFile)
{
return LicenseRequestFileGenerator::createLicenseRequestFile( productCode_, licenseRequestFile, systemInfoType_ );
} // end - createLicenseRequestFile()
void LicenseManager::startBGWork(std::vector<std::string> indexPathList)
{
boost::thread_group bgWork;
bgWork.create_thread(boost::bind(&LicenseManager::bgCheckIndexFileSize, this, indexPathList, 600)); // disk size check every 10 mins
bgWork.join_all();
} // end - isIndexFileSizeValid()
license_module::license_max_doc_t LicenseManager::getMaxIndexSize()
{
boost::mutex::scoped_lock lock(mutex_);
return maxIndexSize_;
} // end - getMaxIndexSize()
license_module::license_max_index_data_size_t LicenseManager::getMaxIndexFileSize()
{
boost::mutex::scoped_lock lock(mutex_);
return maxIndexFileSize_;
} // end - getMaxIndexFileSize()
void LicenseManager::bgCheckIndexFileSize(const std::vector<std::string>& indexPathList, size_t intervalSec)
{
#ifdef COBRA_RESTRICT
license_module::license_max_index_data_size_t totalSize;
while(1) {
// std::stringstream ss;
totalSize = 0;
std::vector<std::string>::const_iterator indexPathIter = indexPathList.begin();
for(; indexPathIter != indexPathList.end(); indexPathIter++)
{
totalSize += license_tool::dirSize(*indexPathIter, true);
// ss << "-----[ " << *indexPathIter << " : " << license_tool::dirSize(*indexPathIter, true) << std::endl;
}
// ss << "----------[ " << "TOTAL SIZE : " << totalSize << std::endl;
// std::cerr << ss.str() << std::endl;
if ( totalSize > LICENSE_MAX_SIZE * GB )
{
sflog->error(SFL_INIT, 150001, totalSize, getMaxIndexFileSize());
continueIndex_ = false;
//kill(getpid(), SIGTERM);
}
sleep(intervalSec);
}
#else
std::cerr << "-----[ Background Process of License checking is disabled" << std::endl;
#endif // COBRA_RESTRICT
} // end - bgCheckIndexFileSize()
void LicenseManager::getLicenseLimitation(LicenseGrade grade, license_module::license_max_doc_t& maxDocSize, license_module::license_max_index_data_size_t& maxSize)
{
switch(grade) {
case COBRA_LICENSE:
maxDocSize = 10 * K;
maxSize = 1 * GB;
break;
case SILVER_LICENSE:
maxDocSize = 100 * K;
maxSize = 10 * GB;
break;
case GOLD_LICENSE:
maxDocSize = 1 * M;
maxSize = 100 * GB;
break;
case PLATINUM_LICENSE:
maxDocSize = 500 * M;
maxSize = 50000 * GB;
break;
case MAX_SIZE_TEST_LICENSE:
maxDocSize = 500 * M;
maxSize = 1024 * 1024; // 1M
break;
case MAX_DOC_SIZE_TEST_LICENSE:
maxDocSize = 1 * K;
maxSize = 5000 * GB;
break;
case DEV_LICENCE:
maxDocSize = 500 * M;
maxSize = 50000 * GB;
break;
default:
maxDocSize = 0;
maxSize = 0;
}
}
bool LicenseManager::extract_token_from(const std::string& filePath, std::string& token)
{
int len;
LICENSE_DATA_T tmpData;
ifstream fpin( filePath.c_str() , ios::binary );
// Get length of file
fpin.seekg ( 0 , ios::end );
len = fpin.tellg();
if ( len == -1 )
{
fpin.close();
return false;
}
fpin.seekg ( 0, ios::beg );
// Read binary data of given file.
tmpData.reset(new unsigned char [len]);
fpin.read((char*)tmpData.get(), len);
fpin.close();
size_t decSize;
LICENSE_DATA_T decData;
LicenseEncryptor licenseEncryptor;
licenseEncryptor.decryptData(len, tmpData, decSize, decData);
// Extract token
license_tool::arrToStr(decSize, decData, token);
return true;
}
void LicenseManager::write_token_to(const std::string filePath, const std::string& token)
{
size_t tokenSize;
LICENSE_DATA_T tokenData;
license_tool::strToArr(token, tokenSize, tokenData);
/// Encrypt token data
size_t encSize;
LICENSE_DATA_T encData;
LicenseEncryptor licenseEncryptor;
licenseEncryptor.encryptData(tokenSize, tokenData, encSize, encData);
/// Write data into file
ofstream fpout(filePath.c_str());
fpout.write( (char*)(encData.get()), encSize );
fpout.close();
}
<commit_msg>modify extract_token_from and write_token_to functions in LicenseManager<commit_after>///
/// @file LicenseManager.cpp
/// @brief A source file of license manager.
/// @author Dohyun Yun ( dualistmage@gmail.com )
/// @date 2010-05-18
///
#include "LicenseManager.h"
#include "LicenseRequestFileGenerator.h"
#include "LicenseTool.h"
#include <common/SFLogger.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <sstream>
using namespace sf1r;
using namespace license_module;
boost::mutex LicenseManager::mutex_;
license_module::license_max_doc_t LicenseManager::maxIndexSize_(0);
license_module::license_max_index_data_size_t LicenseManager::maxIndexFileSize_(0);
bool LicenseManager::continueIndex_(true);
const std::string LicenseManager::LICENSE_REQUEST_FILENAME = "sf1-license-request.dat";
const std::string LicenseManager::LICENSE_KEY_FILENAME = "sf1-license-key.dat";
const std::string LicenseManager::TOKEN_FILENAME = "token.dat";
const std::string LicenseManager::STOP_SERVICE_TOKEN = "@@ALL@@";
const std::string LicenseManager::START_SERVICE_TOKEN = "@@NONEdfetfhhhrrer@@";
LicenseManager::LicenseManager(const std::string& sf1Version, const std::string& licenseFilePath, bool systemInfoType):
systemInfoType_(systemInfoType)
{
std::string productCodeStr("SF1");
productCodeStr += sf1Version;
memcpy(&productCode_, productCodeStr.c_str(), sizeof(uint64_t));
licenseFilePath_ = licenseFilePath;
licenseClient_.reset(
new LicenseClient(
productCode_,
"127.0.0.1", // TODO
"23456", // TODO
licenseFilePath_,
systemInfoType)
);
} // end - LicenseManager()
bool LicenseManager::validateLicense()
{
#ifdef COBRA_RESTRICT
if ( licenseClient_ )
return licenseClient_->validateLicenseCertificate();
return false;
#else
return true;
#endif // COBRA_RESTICT
} // end - validateLicense()
bool LicenseManager::validateLicenseFile()
{
#ifdef COBRA_RESTRICT
if ( licenseClient_ )
return licenseClient_->validateLicenseFile(licenseFilePath_);
return false;
#else
return true;
#endif // COBRA_RESTICT
}
bool LicenseManager::createLicenseRequestFile(const std::string& licenseRequestFile)
{
return LicenseRequestFileGenerator::createLicenseRequestFile( productCode_, licenseRequestFile, systemInfoType_ );
} // end - createLicenseRequestFile()
void LicenseManager::startBGWork(std::vector<std::string> indexPathList)
{
boost::thread_group bgWork;
bgWork.create_thread(boost::bind(&LicenseManager::bgCheckIndexFileSize, this, indexPathList, 600)); // disk size check every 10 mins
bgWork.join_all();
} // end - isIndexFileSizeValid()
license_module::license_max_doc_t LicenseManager::getMaxIndexSize()
{
boost::mutex::scoped_lock lock(mutex_);
return maxIndexSize_;
} // end - getMaxIndexSize()
license_module::license_max_index_data_size_t LicenseManager::getMaxIndexFileSize()
{
boost::mutex::scoped_lock lock(mutex_);
return maxIndexFileSize_;
} // end - getMaxIndexFileSize()
void LicenseManager::bgCheckIndexFileSize(const std::vector<std::string>& indexPathList, size_t intervalSec)
{
#ifdef COBRA_RESTRICT
license_module::license_max_index_data_size_t totalSize;
while(1) {
// std::stringstream ss;
totalSize = 0;
std::vector<std::string>::const_iterator indexPathIter = indexPathList.begin();
for(; indexPathIter != indexPathList.end(); indexPathIter++)
{
totalSize += license_tool::dirSize(*indexPathIter, true);
// ss << "-----[ " << *indexPathIter << " : " << license_tool::dirSize(*indexPathIter, true) << std::endl;
}
// ss << "----------[ " << "TOTAL SIZE : " << totalSize << std::endl;
// std::cerr << ss.str() << std::endl;
if ( totalSize > LICENSE_MAX_SIZE * GB )
{
sflog->error(SFL_INIT, 150001, totalSize, getMaxIndexFileSize());
continueIndex_ = false;
//kill(getpid(), SIGTERM);
}
sleep(intervalSec);
}
#else
std::cerr << "-----[ Background Process of License checking is disabled" << std::endl;
#endif // COBRA_RESTRICT
} // end - bgCheckIndexFileSize()
void LicenseManager::getLicenseLimitation(LicenseGrade grade, license_module::license_max_doc_t& maxDocSize, license_module::license_max_index_data_size_t& maxSize)
{
switch(grade) {
case COBRA_LICENSE:
maxDocSize = 10 * K;
maxSize = 1 * GB;
break;
case SILVER_LICENSE:
maxDocSize = 100 * K;
maxSize = 10 * GB;
break;
case GOLD_LICENSE:
maxDocSize = 1 * M;
maxSize = 100 * GB;
break;
case PLATINUM_LICENSE:
maxDocSize = 500 * M;
maxSize = 50000 * GB;
break;
case MAX_SIZE_TEST_LICENSE:
maxDocSize = 500 * M;
maxSize = 1024 * 1024; // 1M
break;
case MAX_DOC_SIZE_TEST_LICENSE:
maxDocSize = 1 * K;
maxSize = 5000 * GB;
break;
case DEV_LICENCE:
maxDocSize = 500 * M;
maxSize = 50000 * GB;
break;
default:
maxDocSize = 0;
maxSize = 0;
}
}
bool LicenseManager::extract_token_from(const std::string& filePath, std::string& token)
{
int len;
LICENSE_DATA_T tmpData;
ifstream fpin( filePath.c_str() , ios::binary );
// Get length of file
fpin.seekg ( 0 , ios::end );
len = fpin.tellg();
if ( len == -1 )
{
fpin.close();
return false;
}
fpin.seekg ( 0, ios::beg );
// Read binary data of given file.
tmpData.reset(new unsigned char [len]);
fpin.read((char*)tmpData.get(), len);
fpin.close();
size_t decSize;
LICENSE_DATA_T decData;
LicenseEncryptor licenseEncryptor;
licenseEncryptor.decryptData(len, tmpData, decSize, decData);
// Extract token
char tmp[decSize];
memcpy(tmp, decData.get(), decSize);
token.assign(tmp, decSize);
return true;
}
void LicenseManager::write_token_to(const std::string filePath, const std::string& token)
{
size_t tokenSize = token.size();
LICENSE_DATA_T tokenData(new unsigned char[tokenSize]);
memcpy(tokenData.get(), token.c_str(), tokenSize);
/// Encrypt token data
size_t encSize;
LICENSE_DATA_T encData;
LicenseEncryptor licenseEncryptor;
licenseEncryptor.encryptData(tokenSize, tokenData, encSize, encData);
/// Write data into file
ofstream fpout(filePath.c_str());
fpout.write( (char*)(encData.get()), encSize );
fpout.close();
}
<|endoftext|>
|
<commit_before>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015-2020 Vladimir Menshakov
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License,
or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <usb/Device.h>
#include <usb/Context.h>
#include <usb/Interface.h>
#include <usb/call.h>
#include <mtp/ByteArray.h>
#include <mtp/log.h>
namespace mtp { namespace usb
{
Device::Device(ContextPtr context, IOUSBDeviceType ** dev): _context(context), _dev(dev)
{ }
Device::~Device()
{
(*_dev)->USBDeviceClose(_dev);
}
void Device::Reset()
{ }
int Device::GetConfiguration() const
{ return 0; }
void Device::SetConfiguration(int idx)
{ USB_CALL((*_dev)->SetConfiguration(_dev, idx)); }
void Device::ClearHalt(const EndpointPtr & ep)
{
IOUSBInterfaceInterface ** interface = ep->GetInterfaceHandle();
USB_CALL((*interface)->ClearPipeStallBothEnds(interface, ep->GetRefIndex()));
}
void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)
{
IOUSBInterfaceInterface ** interface = ep->GetInterfaceHandle();
size_t transferSize = ep->GetMaxPacketSize();
ByteArray buffer(transferSize);
size_t r;
do
{
r = inputStream->Read(buffer.data(), buffer.size());
USB_CALL((*interface)->WritePipe(interface, ep->GetRefIndex(), buffer.data(), r));
}
while(r == transferSize);
}
void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)
{
IOUSBInterfaceInterface ** interface = ep->GetInterfaceHandle();
size_t transferSize = ep->GetMaxPacketSize();
ByteArray buffer(transferSize);
size_t r;
do
{
UInt32 readBytes = buffer.size();
USB_CALL((*interface)->ReadPipe(interface, ep->GetRefIndex(), buffer.data(), &readBytes));
r = outputStream->Write(buffer.data(), readBytes);
}
while(r == transferSize);
}
void Device::ReadControl(IOUSBDeviceType **dev, u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)
{
IOUSBDevRequest request = {};
request.bmRequestType = type;
request.bRequest = req;
request.wValue = value;
request.wIndex = index;
request.pData = data.data();
request.wLength = data.size();
USB_CALL((*dev)->DeviceRequest(dev, &request));
data.resize(request.wLenDone);
}
void Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)
{ ReadControl(_dev, type, req, value, index, data, timeout); }
void Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, int timeout)
{ error("WriteControl stub"); }
InterfaceTokenPtr Device::ClaimInterface(const InterfacePtr &interface)
{ return interface->Claim(); }
}}
<commit_msg>Revert "use ClearPipeStallBothEnds instead of ClearPipeStall"<commit_after>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015-2020 Vladimir Menshakov
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License,
or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <usb/Device.h>
#include <usb/Context.h>
#include <usb/Interface.h>
#include <usb/call.h>
#include <mtp/ByteArray.h>
#include <mtp/log.h>
namespace mtp { namespace usb
{
Device::Device(ContextPtr context, IOUSBDeviceType ** dev): _context(context), _dev(dev)
{ }
Device::~Device()
{
(*_dev)->USBDeviceClose(_dev);
}
void Device::Reset()
{ }
int Device::GetConfiguration() const
{ return 0; }
void Device::SetConfiguration(int idx)
{ USB_CALL((*_dev)->SetConfiguration(_dev, idx)); }
void Device::ClearHalt(const EndpointPtr & ep)
{
IOUSBInterfaceInterface ** interface = ep->GetInterfaceHandle();
USB_CALL((*interface)->ClearPipeStall(interface, ep->GetRefIndex()));
}
void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)
{
IOUSBInterfaceInterface ** interface = ep->GetInterfaceHandle();
size_t transferSize = ep->GetMaxPacketSize();
ByteArray buffer(transferSize);
size_t r;
do
{
r = inputStream->Read(buffer.data(), buffer.size());
USB_CALL((*interface)->WritePipe(interface, ep->GetRefIndex(), buffer.data(), r));
}
while(r == transferSize);
}
void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)
{
IOUSBInterfaceInterface ** interface = ep->GetInterfaceHandle();
size_t transferSize = ep->GetMaxPacketSize();
ByteArray buffer(transferSize);
size_t r;
do
{
UInt32 readBytes = buffer.size();
USB_CALL((*interface)->ReadPipe(interface, ep->GetRefIndex(), buffer.data(), &readBytes));
r = outputStream->Write(buffer.data(), readBytes);
}
while(r == transferSize);
}
void Device::ReadControl(IOUSBDeviceType **dev, u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)
{
IOUSBDevRequest request = {};
request.bmRequestType = type;
request.bRequest = req;
request.wValue = value;
request.wIndex = index;
request.pData = data.data();
request.wLength = data.size();
USB_CALL((*dev)->DeviceRequest(dev, &request));
data.resize(request.wLenDone);
}
void Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)
{ ReadControl(_dev, type, req, value, index, data, timeout); }
void Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, int timeout)
{ error("WriteControl stub"); }
InterfaceTokenPtr Device::ClaimInterface(const InterfacePtr &interface)
{ return interface->Claim(); }
}}
<|endoftext|>
|
<commit_before>#include <android_native_app_glue.h>
#include <errno.h>
#include <jni.h>
#include <sys/time.h>
#include <time.h>
#include <android/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <queue>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#define LOG_TAG "OCV:libnative_activity"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
struct Engine
{
android_app* app;
cv::Ptr<cv::VideoCapture> capture;
};
static cv::Size calc_optimal_camera_resolution(const char* supported, int width, int height)
{
int frame_width = 0;
int frame_height = 0;
size_t prev_idx = 0;
size_t idx = 0;
float min_diff = FLT_MAX;
do
{
int tmp_width;
int tmp_height;
prev_idx = idx;
while ((supported[idx] != '\0') && (supported[idx] != ','))
idx++;
sscanf(&supported[prev_idx], "%dx%d", &tmp_width, &tmp_height);
int w_diff = width - tmp_width;
int h_diff = height - tmp_height;
if ((h_diff >= 0) && (w_diff >= 0))
{
if ((h_diff <= min_diff) && (tmp_height <= 720))
{
frame_width = tmp_width;
frame_height = tmp_height;
min_diff = h_diff;
}
}
idx++; // to skip comma symbol
} while(supported[idx-1] != '\0');
return cv::Size(frame_width, frame_height);
}
static void engine_draw_frame(Engine* engine, const cv::Mat& frame)
{
if (engine->app->window == NULL)
return; // No window.
ANativeWindow_Buffer buffer;
if (ANativeWindow_lock(engine->app->window, &buffer, NULL) < 0)
{
LOGW("Unable to lock window buffer");
return;
}
int32_t* pixels = (int32_t*)buffer.bits;
int left_indent = (buffer.width-frame.cols)/2;
int top_indent = (buffer.height-frame.rows)/2;
if (top_indent > 0)
{
memset(pixels, 0, top_indent*buffer.stride*sizeof(int32_t));
pixels += top_indent*buffer.stride;
}
for (int yy = 0; yy < frame.rows; yy++)
{
if (left_indent > 0)
{
memset(pixels, 0, left_indent*sizeof(int32_t));
memset(pixels+left_indent+frame.cols, 0, (buffer.stride-frame.cols-left_indent)*sizeof(int32_t));
}
int32_t* line = pixels + left_indent;
size_t line_size = frame.cols*4*sizeof(unsigned char);
memcpy(line, frame.ptr<unsigned char>(yy), line_size);
// go to next line
pixels += buffer.stride;
}
ANativeWindow_unlockAndPost(engine->app->window);
}
static void engine_handle_cmd(android_app* app, int32_t cmd)
{
Engine* engine = (Engine*)app->userData;
switch (cmd)
{
case APP_CMD_INIT_WINDOW:
if (app->window != NULL)
{
LOGI("APP_CMD_INIT_WINDOW");
engine->capture = new cv::VideoCapture(0);
union {double prop; const char* name;} u;
u.prop = engine->capture->get(CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING);
int view_width = ANativeWindow_getWidth(app->window);
int view_height = ANativeWindow_getHeight(app->window);
cv::Size camera_resolution;
if (u.name)
camera_resolution = calc_optimal_camera_resolution(u.name, 640, 480);
else
{
LOGE("Cannot get supported camera camera_resolutions");
camera_resolution = cv::Size(ANativeWindow_getWidth(app->window),
ANativeWindow_getHeight(app->window));
}
if ((camera_resolution.width != 0) && (camera_resolution.height != 0))
{
engine->capture->set(CV_CAP_PROP_FRAME_WIDTH, camera_resolution.width);
engine->capture->set(CV_CAP_PROP_FRAME_HEIGHT, camera_resolution.height);
}
float scale = std::min((float)view_width/camera_resolution.width,
(float)view_height/camera_resolution.height);
if (ANativeWindow_setBuffersGeometry(app->window, (int)(view_width/scale),
int(view_height/scale), WINDOW_FORMAT_RGBA_8888) < 0)
{
LOGE("Cannot set pixel format!");
return;
}
LOGI("Camera initialized at resolution %dx%d", camera_resolution.width, camera_resolution.height);
}
break;
case APP_CMD_TERM_WINDOW:
LOGI("APP_CMD_TERM_WINDOW");
engine->capture->release();
break;
}
}
void android_main(android_app* app)
{
Engine engine;
// Make sure glue isn't stripped.
app_dummy();
size_t engine_size = sizeof(engine); // for Eclipse CDT parser
memset((void*)&engine, 0, engine_size);
app->userData = &engine;
app->onAppCmd = engine_handle_cmd;
engine.app = app;
float fps = 0;
cv::Mat drawing_frame;
std::queue<int64> time_queue;
// loop waiting for stuff to do.
while (1)
{
// Read all pending events.
int ident;
int events;
android_poll_source* source;
// Process system events
while ((ident=ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0)
{
// Process this event.
if (source != NULL)
{
source->process(app, source);
}
// Check if we are exiting.
if (app->destroyRequested != 0)
{
LOGI("Engine thread destroy requested!");
return;
}
}
int64 then;
int64 now = cv::getTickCount();
time_queue.push(now);
// Capture frame from camera and draw it
if (!engine.capture.empty())
{
if (engine.capture->grab())
engine.capture->retrieve(drawing_frame, CV_CAP_ANDROID_COLOR_FRAME_RGBA);
char buffer[256];
sprintf(buffer, "Display performance: %dx%d @ %.3f", drawing_frame.cols, drawing_frame.rows, fps);
cv::putText(drawing_frame, std::string(buffer), cv::Point(8,64),
cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(0,255,0,255));
engine_draw_frame(&engine, drawing_frame);
}
if (time_queue.size() >= 2)
then = time_queue.front();
else
then = 0;
if (time_queue.size() >= 25)
time_queue.pop();
fps = time_queue.size() * (float)cv::getTickFrequency() / (now-then);
}
}
<commit_msg>Updated the native activity sample to master's API.<commit_after>#include <android_native_app_glue.h>
#include <errno.h>
#include <jni.h>
#include <sys/time.h>
#include <time.h>
#include <android/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <queue>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#define LOG_TAG "OCV:libnative_activity"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
struct Engine
{
android_app* app;
cv::Ptr<cv::VideoCapture> capture;
};
static cv::Size calc_optimal_camera_resolution(const char* supported, int width, int height)
{
int frame_width = 0;
int frame_height = 0;
size_t prev_idx = 0;
size_t idx = 0;
float min_diff = FLT_MAX;
do
{
int tmp_width;
int tmp_height;
prev_idx = idx;
while ((supported[idx] != '\0') && (supported[idx] != ','))
idx++;
sscanf(&supported[prev_idx], "%dx%d", &tmp_width, &tmp_height);
int w_diff = width - tmp_width;
int h_diff = height - tmp_height;
if ((h_diff >= 0) && (w_diff >= 0))
{
if ((h_diff <= min_diff) && (tmp_height <= 720))
{
frame_width = tmp_width;
frame_height = tmp_height;
min_diff = h_diff;
}
}
idx++; // to skip comma symbol
} while(supported[idx-1] != '\0');
return cv::Size(frame_width, frame_height);
}
static void engine_draw_frame(Engine* engine, const cv::Mat& frame)
{
if (engine->app->window == NULL)
return; // No window.
ANativeWindow_Buffer buffer;
if (ANativeWindow_lock(engine->app->window, &buffer, NULL) < 0)
{
LOGW("Unable to lock window buffer");
return;
}
int32_t* pixels = (int32_t*)buffer.bits;
int left_indent = (buffer.width-frame.cols)/2;
int top_indent = (buffer.height-frame.rows)/2;
if (top_indent > 0)
{
memset(pixels, 0, top_indent*buffer.stride*sizeof(int32_t));
pixels += top_indent*buffer.stride;
}
for (int yy = 0; yy < frame.rows; yy++)
{
if (left_indent > 0)
{
memset(pixels, 0, left_indent*sizeof(int32_t));
memset(pixels+left_indent+frame.cols, 0, (buffer.stride-frame.cols-left_indent)*sizeof(int32_t));
}
int32_t* line = pixels + left_indent;
size_t line_size = frame.cols*4*sizeof(unsigned char);
memcpy(line, frame.ptr<unsigned char>(yy), line_size);
// go to next line
pixels += buffer.stride;
}
ANativeWindow_unlockAndPost(engine->app->window);
}
static void engine_handle_cmd(android_app* app, int32_t cmd)
{
Engine* engine = (Engine*)app->userData;
switch (cmd)
{
case APP_CMD_INIT_WINDOW:
if (app->window != NULL)
{
LOGI("APP_CMD_INIT_WINDOW");
engine->capture = cv::makePtr<cv::VideoCapture>(0);
union {double prop; const char* name;} u;
u.prop = engine->capture->get(cv::CAP_PROP_ANDROID_PREVIEW_SIZES_STRING);
int view_width = ANativeWindow_getWidth(app->window);
int view_height = ANativeWindow_getHeight(app->window);
cv::Size camera_resolution;
if (u.name)
camera_resolution = calc_optimal_camera_resolution(u.name, 640, 480);
else
{
LOGE("Cannot get supported camera camera_resolutions");
camera_resolution = cv::Size(ANativeWindow_getWidth(app->window),
ANativeWindow_getHeight(app->window));
}
if ((camera_resolution.width != 0) && (camera_resolution.height != 0))
{
engine->capture->set(cv::CAP_PROP_FRAME_WIDTH, camera_resolution.width);
engine->capture->set(cv::CAP_PROP_FRAME_HEIGHT, camera_resolution.height);
}
float scale = std::min((float)view_width/camera_resolution.width,
(float)view_height/camera_resolution.height);
if (ANativeWindow_setBuffersGeometry(app->window, (int)(view_width/scale),
int(view_height/scale), WINDOW_FORMAT_RGBA_8888) < 0)
{
LOGE("Cannot set pixel format!");
return;
}
LOGI("Camera initialized at resolution %dx%d", camera_resolution.width, camera_resolution.height);
}
break;
case APP_CMD_TERM_WINDOW:
LOGI("APP_CMD_TERM_WINDOW");
engine->capture->release();
break;
}
}
void android_main(android_app* app)
{
Engine engine;
// Make sure glue isn't stripped.
app_dummy();
size_t engine_size = sizeof(engine); // for Eclipse CDT parser
memset((void*)&engine, 0, engine_size);
app->userData = &engine;
app->onAppCmd = engine_handle_cmd;
engine.app = app;
float fps = 0;
cv::Mat drawing_frame;
std::queue<int64> time_queue;
// loop waiting for stuff to do.
while (1)
{
// Read all pending events.
int ident;
int events;
android_poll_source* source;
// Process system events
while ((ident=ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0)
{
// Process this event.
if (source != NULL)
{
source->process(app, source);
}
// Check if we are exiting.
if (app->destroyRequested != 0)
{
LOGI("Engine thread destroy requested!");
return;
}
}
int64 then;
int64 now = cv::getTickCount();
time_queue.push(now);
// Capture frame from camera and draw it
if (!engine.capture.empty())
{
if (engine.capture->grab())
engine.capture->retrieve(drawing_frame, cv::CAP_ANDROID_COLOR_FRAME_RGBA);
char buffer[256];
sprintf(buffer, "Display performance: %dx%d @ %.3f", drawing_frame.cols, drawing_frame.rows, fps);
cv::putText(drawing_frame, std::string(buffer), cv::Point(8,64),
cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(0,255,0,255));
engine_draw_frame(&engine, drawing_frame);
}
if (time_queue.size() >= 2)
then = time_queue.front();
else
then = 0;
if (time_queue.size() >= 25)
time_queue.pop();
fps = time_queue.size() * (float)cv::getTickFrequency() / (now-then);
}
}
<|endoftext|>
|
<commit_before>/**
Runtime library for Harlan.
*/
#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include <assert.h>
#include <string.h>
#include "gc.h"
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
#include "gpu_common.h"
enum error {
HARLAN_ERR_OUT_OF_BOUNDS,
HARLAN_ERR_MISPLACED_VECTOR
};
#include "cl++.h"
cl_device_type get_device_type();
#ifndef NO_GLOBALS
cl::device_list g_devices(get_device_type());
cl::context g_ctx(g_devices);
cl::command_queue g_queue(g_ctx.createCommandQueue(g_devices[0]));
#else
extern cl::device_list g_devices;
extern cl::context g_ctx;
extern cl::command_queue g_queue;
#endif
template<typename T>
void print(T n) {
std::cout << n << std::endl;
}
region *create_region(unsigned int size);
void map_region(region *ptr);
void unmap_region(region *ptr);
region_ptr alloc_in_region(region *r, unsigned int size);
cl_mem get_cl_buffer(region *r);
#define __global
<commit_msg>Changing the definition of print in the runtime so it does not include a newline automatically<commit_after>/**
Runtime library for Harlan.
*/
#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include <assert.h>
#include <string.h>
#include "gc.h"
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
#include "gpu_common.h"
enum error {
HARLAN_ERR_OUT_OF_BOUNDS,
HARLAN_ERR_MISPLACED_VECTOR
};
#include "cl++.h"
cl_device_type get_device_type();
#ifndef NO_GLOBALS
cl::device_list g_devices(get_device_type());
cl::context g_ctx(g_devices);
cl::command_queue g_queue(g_ctx.createCommandQueue(g_devices[0]));
#else
extern cl::device_list g_devices;
extern cl::context g_ctx;
extern cl::command_queue g_queue;
#endif
template<typename T>
void print(T n) {
std::cout << n;
}
region *create_region(unsigned int size);
void map_region(region *ptr);
void unmap_region(region *ptr);
region_ptr alloc_in_region(region *r, unsigned int size);
cl_mem get_cl_buffer(region *r);
#define __global
<|endoftext|>
|
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.51
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "ParallelTemperingPreprocessor.h"
#if GOMC_LIB_MPI
ParallelTemperingPreprocessor::ParallelTemperingPreprocessor( int argc,
char *argv[])
{
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[1];
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
// placeholder
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
}
//OPEN FILE
inputFileReaderMPI.open(inputFileStringMPI.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReaderMPI.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileStringMPI <<
" in the directory provided!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReaderMPI.close();
if(checkIfParallelTempering(inputFileStringMPI.c_str())) {
checkIfValid(inputFileStringMPI.c_str());
if(worldRank >= getNumberOfReplicas(inputFileStringMPI.c_str())) {
std::cout << "You may not request more processes (" << worldSize
<< ") than there are replicas(" << getNumberOfReplicas(inputFileStringMPI.c_str())
<< ")! Exiting this process[" << worldRank << "]!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
} else {
#if ENSEMBLE == GCMC
pathToReplicaDirectory = setupReplicaDirectoriesAndRedirectSTDOUTToFile ( getMultiSimFolderName(inputFileStringMPI.c_str()),
getTemperature(inputFileStringMPI.c_str(), worldRank),
getChemicalPotential(inputFileStringMPI.c_str(), worldRank));
#else
pathToReplicaDirectory = setupReplicaDirectoriesAndRedirectSTDOUTToFile ( getMultiSimFolderName(inputFileStringMPI.c_str()),
getTemperature(inputFileStringMPI.c_str(), worldRank));
#endif
restart = checkIfRestart(inputFileStringMPI.c_str());
restartFromCheckpoint = checkIfRestartFromCheckpoint(inputFileStringMPI.c_str());
}
}
}
}
bool ParallelTemperingPreprocessor::checkIfValidRank()
{
if (worldRank >= getNumberOfReplicas(inputFileStringMPI.c_str())) {
return false;
} else {
return true;
}
}
bool ParallelTemperingPreprocessor::checkIfParallelTempering(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
bool isParallelTemperingInTemperature = false;
bool isParallelTemperingInChemicalPotential = false;
bool isParallelTemperingInFreeEnergyCoulomb = false;
bool isParallelTemperingInFreeEnergyVDW = false;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Temperature")) {
if (line.size() > 2)
isParallelTemperingInTemperature = true;
} else if (checkString(line[0], "ChemPot")) {
if (line.size() > 3)
isParallelTemperingInChemicalPotential = true;
} else if (checkString(line[0], "LambdaCoulomb")) {
if (line.size() > 2)
isParallelTemperingInFreeEnergyCoulomb = true;
} else if (checkString(line[0], "LambdaVDW")) {
if (line.size() > 2)
isParallelTemperingInFreeEnergyVDW = true;
}
// Clear and get ready for the next line
line.clear();
}
return isParallelTemperingInTemperature || isParallelTemperingInChemicalPotential ||
isParallelTemperingInFreeEnergyCoulomb || isParallelTemperingInFreeEnergyVDW;
}
void ParallelTemperingPreprocessor::checkIfValid(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
int numberOfTemperatures = 0;
vector < int > numberOfChemPots;
int numberOfLambdaCoulombs = 0;
int numberOfLambdaVDWs = 0;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Temperature")) {
numberOfTemperatures = line.size() - 1;
} else if (checkString(line[0], "ChemPot")) {
numberOfChemPots.push_back(line.size() - 2);
} else if (checkString(line[0], "LambdaCoulomb")) {
numberOfLambdaCoulombs = line.size() - 1;
} else if (checkString(line[0], "LambdaVDW")) {
numberOfLambdaVDWs = line.size() - 1;
}
// Clear and get ready for the next line
line.clear();
}
for( vector < int >::iterator it = numberOfChemPots.begin(); it != numberOfChemPots.end(); ++it ) {
if (*it > 1 && numberOfTemperatures > 1 && *it != numberOfTemperatures) {
std::cout << "Error: Unequal number of temperatures and chemical potentials in Multicanonical!\n";
std::cout << "If you only want to only sample mu-space or temperature-space\n";
std::cout << "provide only one temperature or only one chemical potential.\n";
std::cout << "Number of temperatures provided: " << numberOfTemperatures << "\n";
std::cout << "Number of chemical potentials provided: " << *it << "\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
}
if ( numberOfLambdaCoulombs != numberOfLambdaVDWs) {
std::cout << "Error: Unequal number of LambdaCoulombs and LambdaVDWs in Free Energy calculation!\n";
std::cout << "Number of temperatures provided: " << numberOfLambdaCoulombs << "\n";
std::cout << "Number of temperatures provided: " << numberOfLambdaVDWs << "\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
}
int ParallelTemperingPreprocessor::getNumberOfReplicas(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
int numberOfTemperatures = 0;
vector < int > numberOfChemPots;
int numberOfLambdaCoulombs = 0;
int numberOfLambdaVDWs = 0;
int numberOfReplicas = 0;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Temperature")) {
numberOfTemperatures = line.size() - 1;
} else if (checkString(line[0], "ChemPot")) {
numberOfChemPots.push_back(line.size() - 2);
} else if (checkString(line[0], "LambdaCoulomb")) {
numberOfLambdaCoulombs = line.size() - 1;
} else if (checkString(line[0], "LambdaVDW")) {
numberOfLambdaVDWs = line.size() - 1;
}
// Clear and get ready for the next line
line.clear();
}
for( vector < int >::iterator it = numberOfChemPots.begin(); it != numberOfChemPots.end(); ++it ) {
numberOfReplicas = std::max(numberOfReplicas, *it);
}
numberOfReplicas = std::max(numberOfReplicas, numberOfTemperatures);
numberOfReplicas = std::max(numberOfReplicas, numberOfLambdaCoulombs);
numberOfReplicas = std::max(numberOfReplicas, numberOfLambdaVDWs);
return numberOfReplicas;
}
std::string ParallelTemperingPreprocessor::getMultiSimFolderName(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
string folderName;
while(reader.readNextLine(line)) {
if(line.size() == 0) {
continue;
} else if(line[0] == "MultiSimFolderName") {
std::stringstream ss;
for (int i = 1; i < line.size(); i++) {
if (line[i] == " ") {
ss << '_';
} else {
ss << line[i];
if (i + 1 != line.size())
ss << "_";
}
}
folderName = ss.str();
}
// Clear and get ready for the next line
line.clear();
}
if (folderName.empty()) {
folderName = "MultiSimFolderName";
}
return folderName;
}
std::string ParallelTemperingPreprocessor::getTemperature(const char *fileName, int worldRank)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
string temperature;
while(reader.readNextLine(line)) {
if(line.size() == 0) {
continue;
} else if(line[0] == "Temperature") {
if (line.size() > 2) {
temperature = line[worldRank + 1];
} else {
temperature = line[1];
}
}
// Clear and get ready for the next line
line.clear();
}
return temperature;
}
std::string ParallelTemperingPreprocessor::getChemicalPotential(const char *fileName, int worldRank)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
std::stringstream chemPotStream;
std::string resName;
std::string val;
while(reader.readNextLine(line)) {
if(line.size() == 0) {
continue;
} else if(checkString(line[0], "ChemPot")) {
if (line.size() > 3) {
resName = line[1];
val = line[2 + worldRank];
chemPotStream << "_" << resName << "_" << val;
} else if(line.size() != 3) {
std::cout << "Error: Chemical potential parameters are not specified!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
} else {
resName = line[1];
val = line[2];
chemPotStream << "_" << resName << "_" << val;
}
}
// Clear and get ready for the next line
line.clear();
}
return chemPotStream.str();
}
bool ParallelTemperingPreprocessor::checkIfRestart(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
bool restart = false;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Restart")) {
restart = checkBool(line[1]);
return restart;
}
// Clear and get ready for the next line
line.clear();
}
return restart;
}
bool ParallelTemperingPreprocessor::checkIfRestartFromCheckpoint(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
bool restartFromCheckpoint = false;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "RestartCheckpoint")) {
restartFromCheckpoint = checkBool(line[1]);
return restartFromCheckpoint;
}
// Clear and get ready for the next line
line.clear();
}
return restartFromCheckpoint;
}
std::string ParallelTemperingPreprocessor::setupReplicaDirectoriesAndRedirectSTDOUTToFile(std::string multiSimTitle, std::string temperature)
{
std::stringstream replicaTemp;
replicaTemp << "temp_" << temperature;
std::string replicaDirectory = replicaTemp.str();
return mkdirWrapper(multiSimTitle, replicaDirectory);
}
std::string ParallelTemperingPreprocessor::setupReplicaDirectoriesAndRedirectSTDOUTToFile(std::string multiSimTitle, std::string temperature, std::string chemPot)
{
std::stringstream replicaTemp;
replicaTemp << "temp_" << temperature << chemPot;
std::string replicaDirectory = replicaTemp.str();
return mkdirWrapper(multiSimTitle, replicaDirectory);
}
std::string ParallelTemperingPreprocessor::mkdirWrapper(std::string multisimDirectoryName, string replicaDirectoryName)
{
std::stringstream replicaStream;
std::stringstream replicaStreamErr;
replicaStream << multisimDirectoryName << OS_SEP
<< replicaDirectoryName << OS_SEP;
replicaStreamErr << multisimDirectoryName << OS_SEP
<< replicaDirectoryName << OS_SEP;
std::string replicaDirectoryPathString = replicaStream.str();
system(("mkdir -p " + multisimDirectoryName + OS_SEP + replicaDirectoryPathString).c_str()); // note the slash after accounts!
std::string pathToReplicaDirectory = replicaStream.str();
replicaStream << "ConsoleOut.dat";
replicaStreamErr << "ErrorsMessages.dat";
std::string pathToReplicaLogFile = replicaStream.str();
std::string pathToReplicaErrorLogFile = replicaStreamErr.str();
if(worldRank == 0) {
std::cout << "Monitor progress of your simulation by navigating to a replica output directory and issuing:\n"
<< "\t$ tail -f \"YourUniqueFileName\".console" << std::endl;
}
freopen(pathToReplicaLogFile.c_str(), "w", stdout);
freopen(pathToReplicaErrorLogFile.c_str(), "w", stderr);
return pathToReplicaDirectory;
}
bool ParallelTemperingPreprocessor::checkString(string str1, string str2)
{
for(int k = 0; k < str1.length(); k++) {
str1[k] = toupper(str1[k]);
}
for(int j = 0; j < str2.length(); j++) {
str2[j] = toupper(str2[j]);
}
return (str1 == str2);
}
bool ParallelTemperingPreprocessor::checkBool(string str)
{
int k;
// capitalize string
for(k = 0; k < str.length(); k++) {
str[k] = toupper(str[k]);
}
if(str == "ON" || str == "TRUE" || str == "YES")
return true;
else if(str == "OFF" || str == "FALSE" || str == "NO")
return false;
std::cout << "Error: " << str << "couldn't be recognized!" << std::endl;
exit(EXIT_FAILURE);
}
MultiSim::MultiSim(ParallelTemperingPreprocessor & pt) :
worldSize(pt.worldSize), worldRank(pt.worldRank), pathToReplicaDirectory(pt.pathToReplicaDirectory),
restart(pt.restart), restartFromCheckpoint(pt.restartFromCheckpoint)
{}
#endif<commit_msg>wateR<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.51
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "ParallelTemperingPreprocessor.h"
#if GOMC_LIB_MPI
ParallelTemperingPreprocessor::ParallelTemperingPreprocessor( int argc,
char *argv[])
{
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[1];
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
// placeholder
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
}
//OPEN FILE
inputFileReaderMPI.open(inputFileStringMPI.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReaderMPI.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileStringMPI <<
" in the directory provided!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReaderMPI.close();
if(checkIfParallelTempering(inputFileStringMPI.c_str())) {
checkIfValid(inputFileStringMPI.c_str());
if(worldRank >= getNumberOfReplicas(inputFileStringMPI.c_str())) {
std::cout << "You may not request more processes (" << worldSize
<< ") than there are replicas(" << getNumberOfReplicas(inputFileStringMPI.c_str())
<< ")! Exiting this process[" << worldRank << "]!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
} else {
#if ENSEMBLE == GCMC
pathToReplicaDirectory = setupReplicaDirectoriesAndRedirectSTDOUTToFile ( getMultiSimFolderName(inputFileStringMPI.c_str()),
getTemperature(inputFileStringMPI.c_str(), worldRank),
getChemicalPotential(inputFileStringMPI.c_str(), worldRank));
#else
pathToReplicaDirectory = setupReplicaDirectoriesAndRedirectSTDOUTToFile ( getMultiSimFolderName(inputFileStringMPI.c_str()),
getTemperature(inputFileStringMPI.c_str(), worldRank));
#endif
restart = checkIfRestart(inputFileStringMPI.c_str());
restartFromCheckpoint = checkIfRestartFromCheckpoint(inputFileStringMPI.c_str());
}
}
}
}
bool ParallelTemperingPreprocessor::checkIfValidRank()
{
if (worldRank >= getNumberOfReplicas(inputFileStringMPI.c_str())) {
return false;
} else {
return true;
}
}
bool ParallelTemperingPreprocessor::checkIfParallelTempering(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
bool isParallelTemperingInTemperature = false;
bool isParallelTemperingInChemicalPotential = false;
bool isParallelTemperingInFreeEnergyCoulomb = false;
bool isParallelTemperingInFreeEnergyVDW = false;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Temperature")) {
if (line.size() > 2)
isParallelTemperingInTemperature = true;
} else if (checkString(line[0], "ChemPot")) {
if (line.size() > 3)
isParallelTemperingInChemicalPotential = true;
} else if (checkString(line[0], "LambdaCoulomb")) {
if (line.size() > 2)
isParallelTemperingInFreeEnergyCoulomb = true;
} else if (checkString(line[0], "LambdaVDW")) {
if (line.size() > 2)
isParallelTemperingInFreeEnergyVDW = true;
}
// Clear and get ready for the next line
line.clear();
}
return isParallelTemperingInTemperature || isParallelTemperingInChemicalPotential ||
isParallelTemperingInFreeEnergyCoulomb || isParallelTemperingInFreeEnergyVDW;
}
void ParallelTemperingPreprocessor::checkIfValid(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
int numberOfTemperatures = 0;
vector < int > numberOfChemPots;
int numberOfLambdaCoulombs = 0;
int numberOfLambdaVDWs = 0;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Temperature")) {
numberOfTemperatures = line.size() - 1;
} else if (checkString(line[0], "ChemPot")) {
numberOfChemPots.push_back(line.size() - 2);
} else if (checkString(line[0], "LambdaCoulomb")) {
numberOfLambdaCoulombs = line.size() - 1;
} else if (checkString(line[0], "LambdaVDW")) {
numberOfLambdaVDWs = line.size() - 1;
}
// Clear and get ready for the next line
line.clear();
}
for( vector < int >::iterator it = numberOfChemPots.begin(); it != numberOfChemPots.end(); ++it ) {
if (*it > 1 && numberOfTemperatures > 1 && *it != numberOfTemperatures) {
std::cout << "Error: Unequal number of temperatures and chemical potentials in Multicanonical!\n";
std::cout << "If you only want to only sample mu-space or temperature-space\n";
std::cout << "provide only one temperature or only one chemical potential.\n";
std::cout << "Number of temperatures provided: " << numberOfTemperatures << "\n";
std::cout << "Number of chemical potentials provided: " << *it << "\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
}
if ( numberOfLambdaCoulombs != numberOfLambdaVDWs) {
std::cout << "Error: Unequal number of LambdaCoulombs and LambdaVDWs in Free Energy calculation!\n";
std::cout << "Number of temperatures provided: " << numberOfLambdaCoulombs << "\n";
std::cout << "Number of temperatures provided: " << numberOfLambdaVDWs << "\n";
MPI_Finalize();
exit(EXIT_FAILURE);
}
}
int ParallelTemperingPreprocessor::getNumberOfReplicas(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
int numberOfTemperatures = 0;
vector < int > numberOfChemPots;
int numberOfLambdaCoulombs = 0;
int numberOfLambdaVDWs = 0;
int numberOfReplicas = 0;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Temperature")) {
numberOfTemperatures = line.size() - 1;
} else if (checkString(line[0], "ChemPot")) {
numberOfChemPots.push_back(line.size() - 2);
} else if (checkString(line[0], "LambdaCoulomb")) {
numberOfLambdaCoulombs = line.size() - 1;
} else if (checkString(line[0], "LambdaVDW")) {
numberOfLambdaVDWs = line.size() - 1;
}
// Clear and get ready for the next line
line.clear();
}
for( vector < int >::iterator it = numberOfChemPots.begin(); it != numberOfChemPots.end(); ++it ) {
numberOfReplicas = std::max(numberOfReplicas, *it);
}
numberOfReplicas = std::max(numberOfReplicas, numberOfTemperatures);
numberOfReplicas = std::max(numberOfReplicas, numberOfLambdaCoulombs);
numberOfReplicas = std::max(numberOfReplicas, numberOfLambdaVDWs);
return numberOfReplicas;
}
std::string ParallelTemperingPreprocessor::getMultiSimFolderName(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
string folderName;
while(reader.readNextLine(line)) {
if(line.size() == 0) {
continue;
} else if(line[0] == "MultiSimFolderName") {
std::stringstream ss;
for (int i = 1; i < line.size(); i++) {
if (line[i] == " ") {
ss << '_';
} else {
ss << line[i];
if (i + 1 != line.size())
ss << "_";
}
}
folderName = ss.str();
}
// Clear and get ready for the next line
line.clear();
}
if (folderName.empty()) {
folderName = "MultiSimFolderName";
}
return folderName;
}
std::string ParallelTemperingPreprocessor::getTemperature(const char *fileName, int worldRank)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
string temperature;
while(reader.readNextLine(line)) {
if(line.size() == 0) {
continue;
} else if(line[0] == "Temperature") {
if (line.size() > 2) {
temperature = line[worldRank + 1];
} else {
temperature = line[1];
}
}
// Clear and get ready for the next line
line.clear();
}
return temperature;
}
std::string ParallelTemperingPreprocessor::getChemicalPotential(const char *fileName, int worldRank)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
std::stringstream chemPotStream;
std::string resName;
std::string val;
while(reader.readNextLine(line)) {
if(line.size() == 0) {
continue;
} else if(checkString(line[0], "ChemPot")) {
if (line.size() > 3) {
resName = line[1];
val = line[2 + worldRank];
chemPotStream << "_" << resName << "_" << val;
} else if(line.size() != 3) {
std::cout << "Error: Chemical potential parameters are not specified!\n";
MPI_Finalize();
exit(EXIT_FAILURE);
} else {
resName = line[1];
val = line[2];
chemPotStream << "_" << resName << "_" << val;
}
}
// Clear and get ready for the next line
line.clear();
}
return chemPotStream.str();
}
bool ParallelTemperingPreprocessor::checkIfRestart(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
bool restart = false;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "Restart")) {
restart = checkBool(line[1]);
return restart;
}
// Clear and get ready for the next line
line.clear();
}
return restart;
}
bool ParallelTemperingPreprocessor::checkIfRestartFromCheckpoint(const char *fileName)
{
InputFileReader reader;
std::vector<std::string> line;
reader.Open(fileName);
bool restartFromCheckpoint = false;
while(reader.readNextLine(line)) {
if(line.size() == 0)
continue;
if(checkString(line[0], "RestartCheckpoint")) {
restartFromCheckpoint = checkBool(line[1]);
return restartFromCheckpoint;
}
// Clear and get ready for the next line
line.clear();
}
return restartFromCheckpoint;
}
std::string ParallelTemperingPreprocessor::setupReplicaDirectoriesAndRedirectSTDOUTToFile(std::string multiSimTitle, std::string temperature)
{
std::stringstream replicaTemp;
replicaTemp << "temp_" << temperature;
std::string replicaDirectory = replicaTemp.str();
return mkdirWrapper(multiSimTitle, replicaDirectory);
}
std::string ParallelTemperingPreprocessor::setupReplicaDirectoriesAndRedirectSTDOUTToFile(std::string multiSimTitle, std::string temperature, std::string chemPot)
{
std::stringstream replicaTemp;
replicaTemp << "temp_" << temperature << chemPot;
std::string replicaDirectory = replicaTemp.str();
return mkdirWrapper(multiSimTitle, replicaDirectory);
}
std::string ParallelTemperingPreprocessor::mkdirWrapper(std::string multisimDirectoryName, string replicaDirectoryName)
{
std::stringstream replicaStream;
std::stringstream replicaStreamErr;
replicaStream << multisimDirectoryName << OS_SEP
<< replicaDirectoryName << OS_SEP;
replicaStreamErr << multisimDirectoryName << OS_SEP
<< replicaDirectoryName << OS_SEP;
std::string replicaDirectoryPathString = replicaStream.str();
system(("mkdir -p " + multisimDirectoryName + OS_SEP + replicaDirectoryPathString + OS_SEP).c_str()); // note the slash after accounts!
std::string pathToReplicaDirectory = replicaStream.str();
replicaStream << "ConsoleOut.dat";
replicaStreamErr << "ErrorsMessages.dat";
std::string pathToReplicaLogFile = replicaStream.str();
std::string pathToReplicaErrorLogFile = replicaStreamErr.str();
if(worldRank == 0) {
std::cout << "Monitor progress of your simulation by navigating to a replica output directory and issuing:\n"
<< "\t$ tail -f \"YourUniqueFileName\".console" << std::endl;
}
freopen(pathToReplicaLogFile.c_str(), "w", stdout);
freopen(pathToReplicaErrorLogFile.c_str(), "w", stderr);
return pathToReplicaDirectory;
}
bool ParallelTemperingPreprocessor::checkString(string str1, string str2)
{
for(int k = 0; k < str1.length(); k++) {
str1[k] = toupper(str1[k]);
}
for(int j = 0; j < str2.length(); j++) {
str2[j] = toupper(str2[j]);
}
return (str1 == str2);
}
bool ParallelTemperingPreprocessor::checkBool(string str)
{
int k;
// capitalize string
for(k = 0; k < str.length(); k++) {
str[k] = toupper(str[k]);
}
if(str == "ON" || str == "TRUE" || str == "YES")
return true;
else if(str == "OFF" || str == "FALSE" || str == "NO")
return false;
std::cout << "Error: " << str << "couldn't be recognized!" << std::endl;
exit(EXIT_FAILURE);
}
MultiSim::MultiSim(ParallelTemperingPreprocessor & pt) :
worldSize(pt.worldSize), worldRank(pt.worldRank), pathToReplicaDirectory(pt.pathToReplicaDirectory),
restart(pt.restart), restartFromCheckpoint(pt.restartFromCheckpoint)
{}
#endif<|endoftext|>
|
<commit_before>//===--- MemLocationPrinter.cpp - Dump all memory locations in program ---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This pass dumps all the memory locations accessed in the function, as well
// as their expansions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-memlocation-dumper"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/MemLocation.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILAnalysis/Analysis.h"
#include "swift/SILPasses/Transforms.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
namespace {
enum class MLKind : unsigned {
OnlyExpansion = 0,
OnlyReduction = 1,
OnlyTypeExpansion = 2,
All = 3,
};
} // end anonymous namespace
static llvm::cl::opt<MLKind> MemLocationKinds(
"ml", llvm::cl::desc("MemLocation Kinds:"), llvm::cl::init(MLKind::All),
llvm::cl::values(
clEnumValN(MLKind::OnlyExpansion, "only-expansion", "only-expansion"),
clEnumValN(MLKind::OnlyReduction, "only-reduction", "only-reduction"),
clEnumValN(MLKind::OnlyTypeExpansion, "only-type-expansion",
"only-type-expansion"),
clEnumValN(MLKind::All, "all", "all"), clEnumValEnd));
namespace {
class MemLocationPrinter : public SILFunctionTransform {
/// Dumps the expansions of memory locations accessed in the function.
/// This tests the expand function in MemLocation class.
///
/// We test it to catch any suspicious things when memory location is
/// expanded, i.e. base is traced back and aggregate is expanded
/// properly.
void printMemExpansion(SILFunction &Fn) {
MemLocation L;
MemLocationList Locs;
unsigned Counter = 0;
for (auto &BB : Fn) {
for (auto &II : BB) {
if (auto *LI = dyn_cast<LoadInst>(&II)) {
L.initialize(LI->getOperand());
if (!L.isValid())
continue;
MemLocation::expand(L, &Fn.getModule(), Locs);
} else if (auto *SI = dyn_cast<StoreInst>(&II)) {
L.initialize(SI->getDest());
if (!L.isValid())
continue;
MemLocation::expand(L, &Fn.getModule(), Locs);
} else {
// Not interested in these instructions yet.
continue;
}
llvm::outs() << "#" << Counter++ << II;
for (auto &Loc : Locs) {
llvm::outs() << Loc;
}
L.reset();
Locs.clear();
}
}
llvm::outs() << "\n";
}
/// Dumps the expansions of SILType accessed in the function.
/// This tests the BreadthFirstEnumTypeProjection function, which is
/// a function used extensively in expand and reduce functions.
///
/// We test it to catch any suspicious things in the earliest point.
///
void printTypeExpansion(SILFunction &Fn) {
SILModule *M = &Fn.getModule();
ProjectionPathList PPList;
unsigned Counter = 0;
for (auto &BB : Fn) {
for (auto &II : BB) {
if (auto *LI = dyn_cast<LoadInst>(&II)) {
SILValue V = LI->getOperand();
// This is an address type, take it object type.
SILType Ty = V.getType().getObjectType();
ProjectionPath::BreadthFirstEnumTypeProjection(Ty, M, PPList, true);
} else if (auto *SI = dyn_cast<StoreInst>(&II)) {
SILValue V = SI->getDest();
// This is an address type, take it object type.
SILType Ty = V.getType().getObjectType();
ProjectionPath::BreadthFirstEnumTypeProjection(Ty, M, PPList, true);
} else {
// Not interested in these instructions yet.
continue;
}
llvm::outs() << "#" << Counter++ << II;
for (auto &T : PPList) {
llvm::outs() << T.getValue();
}
PPList.clear();
}
}
llvm::outs() << "\n";
}
void run() override {
SILFunction &Fn = *getFunction();
llvm::outs() << "@" << Fn.getName() << "\n";
switch (MemLocationKinds) {
case MLKind::OnlyExpansion:
printMemExpansion(Fn);
break;
case MLKind::OnlyTypeExpansion:
printTypeExpansion(Fn);
break;
default:
break;
}
}
StringRef getName() override { return "Mem Location Dumper"; }
};
} // end anonymous namespace
SILTransform *swift::createMemLocationPrinter() {
return new MemLocationPrinter();
}
<commit_msg>Update comments and reorder functions in MemLocationPrinter. NFC<commit_after>///===--- MemLocationPrinter.cpp - Dump all memory locations in program ---===//
///
/// This source file is part of the Swift.org open source project
///
/// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
/// Licensed under Apache License v2.0 with Runtime Library Exception
///
/// See http://swift.org/LICENSE.txt for license information
/// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
///
///===---------------------------------------------------------------------===//
///
/// This pass tests type expansion, memlocation expansion and memlocation
/// reduction.
///
///===---------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-memlocation-dumper"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/MemLocation.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILAnalysis/Analysis.h"
#include "swift/SILPasses/Transforms.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
namespace {
enum class MLKind : unsigned {
OnlyExpansion = 0,
OnlyReduction = 1,
OnlyTypeExpansion = 2,
All = 3,
};
} // end anonymous namespace
static llvm::cl::opt<MLKind> MemLocationKinds(
"ml", llvm::cl::desc("MemLocation Kinds:"), llvm::cl::init(MLKind::All),
llvm::cl::values(
clEnumValN(MLKind::OnlyExpansion, "only-expansion", "only-expansion"),
clEnumValN(MLKind::OnlyReduction, "only-reduction", "only-reduction"),
clEnumValN(MLKind::OnlyTypeExpansion, "only-type-expansion",
"only-type-expansion"),
clEnumValN(MLKind::All, "all", "all"), clEnumValEnd));
namespace {
class MemLocationPrinter : public SILFunctionTransform {
/// Dumps the expansions of SILType accessed in the function.
/// This tests the BreadthFirstEnumTypeProjection function, which is
/// a function used extensively in expand and reduce functions.
///
/// We test it to catch any suspicious things in the earliest point.
///
void printTypeExpansion(SILFunction &Fn) {
SILModule *M = &Fn.getModule();
ProjectionPathList PPList;
unsigned Counter = 0;
for (auto &BB : Fn) {
for (auto &II : BB) {
if (auto *LI = dyn_cast<LoadInst>(&II)) {
SILValue V = LI->getOperand();
// This is an address type, take it object type.
SILType Ty = V.getType().getObjectType();
ProjectionPath::BreadthFirstEnumTypeProjection(Ty, M, PPList, true);
} else if (auto *SI = dyn_cast<StoreInst>(&II)) {
SILValue V = SI->getDest();
// This is an address type, take it object type.
SILType Ty = V.getType().getObjectType();
ProjectionPath::BreadthFirstEnumTypeProjection(Ty, M, PPList, true);
} else {
// Not interested in these instructions yet.
continue;
}
llvm::outs() << "#" << Counter++ << II;
for (auto &T : PPList) {
llvm::outs() << T.getValue();
}
PPList.clear();
}
}
llvm::outs() << "\n";
}
/// Dumps the expansions of memory locations accessed in the function.
/// This tests the expand function in MemLocation class.
///
/// We test it to catch any suspicious things when memory location is
/// expanded, i.e. base is traced back and aggregate is expanded
/// properly.
void printMemExpansion(SILFunction &Fn) {
MemLocation L;
MemLocationList Locs;
unsigned Counter = 0;
for (auto &BB : Fn) {
for (auto &II : BB) {
if (auto *LI = dyn_cast<LoadInst>(&II)) {
L.initialize(LI->getOperand());
if (!L.isValid())
continue;
MemLocation::expand(L, &Fn.getModule(), Locs);
} else if (auto *SI = dyn_cast<StoreInst>(&II)) {
L.initialize(SI->getDest());
if (!L.isValid())
continue;
MemLocation::expand(L, &Fn.getModule(), Locs);
} else {
// Not interested in these instructions yet.
continue;
}
llvm::outs() << "#" << Counter++ << II;
for (auto &Loc : Locs) {
llvm::outs() << Loc;
}
L.reset();
Locs.clear();
}
}
llvm::outs() << "\n";
}
void run() override {
SILFunction &Fn = *getFunction();
llvm::outs() << "@" << Fn.getName() << "\n";
switch (MemLocationKinds) {
case MLKind::OnlyExpansion:
printMemExpansion(Fn);
break;
case MLKind::OnlyTypeExpansion:
printTypeExpansion(Fn);
break;
default:
break;
}
}
StringRef getName() override { return "Mem Location Dumper"; }
};
} // end anonymous namespace
SILTransform *swift::createMemLocationPrinter() {
return new MemLocationPrinter();
}
<|endoftext|>
|
<commit_before>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Keith Kyzivat <kkyzivat AT SIPez DOT com>
// SYSTEM INCLUDES
#include <Windows.h>
// APPLICATION INCLUDES
#include "mp/MpInputDeviceDriverWnt.h"
#include "mp/MpInputDeviceManager.h"
// EXTERNAL FUNCTIONS
extern void showWaveError(char *syscall, int e, int N, int line) ; // dmaTaskWnt.cpp
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Default constructor
MpInputDeviceDriverWnt::MpInputDeviceDriverWnt(const UtlString& name,
MpInputDeviceManager& deviceManager,
unsigned nInputBuffers)
: MpInputDeviceDriver(name, deviceManager)
, mWntDeviceId(-1)
, mDevHandle(NULL)
, mNumInBuffers(nInputBuffers)
, mWaveBufSize(0) // Unknown until enableDevice()
, mIsOpen(FALSE)
{
WAVEINCAPS devCaps;
// Grab the number of input devices that are available.
UINT nInputDevs = waveInGetNumDevs();
// Search through the input devices looking for the input device specified.
MMRESULT wavResult = MMSYSERR_NOERROR;
unsigned i;
for (i = 0; i < nInputDevs; i++)
{
MMRESULT res = waveInGetDevCaps(i, &devCaps, sizeof(devCaps));
if (res != MMSYSERR_NOERROR)
{
wavResult = res;
}
else if (strncmp(name, devCaps.szPname, MAXPNAMELEN) == 0)
{
mWntDeviceId = i;
break;
}
}
// Allocate the wave headers and buffer pointers for use with
// windows audio routines.
//(This does *not* include allocation of the buffers themselves -
// that is handled in enableDevice, as we don't know the
// buffer size (#samplesPerFrame) until then.
mpWaveHeaders = new WAVEHDR[mNumInBuffers];
mpWaveBuffers = new LPSTR[mNumInBuffers];
}
// Destructor
MpInputDeviceDriverWnt::~MpInputDeviceDriverWnt()
{
// If we happen to still be enabled at this point, disable the device.
assert(!isEnabled());
if (isEnabled())
{
disableDevice();
}
// Delete the sample headers and sample buffer pointers..
unsigned i;
for (i = 0; i < mNumInBuffers; i++)
{
assert(mpWaveBuffers[i] == NULL);
if (mpWaveBuffers[i] != NULL)
{
delete[] mpWaveBuffers[i];
mpWaveBuffers[i] = NULL;
}
}
delete[] mpWaveBuffers;
delete[] mpWaveHeaders;
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpInputDeviceDriverWnt::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime)
{
OsStatus status = OS_SUCCESS;
// If the device is not valid, let the user know it's bad.
if (!isDeviceValid())
{
return OS_INVALID_STATE; // perhaps new OsState of OS_RESOURCE_INVALID?
}
if (isEnabled())
{
return OS_FAILED;
}
// Set some wave header stat information.
mSamplesPerFrame = samplesPerFrame;
mSamplesPerSec = samplesPerSec;
mCurrentFrameTime = currentFrameTime;
// Do stuff to enable device.
int nChannels = 1;
WAVEFORMATEX wavFormat;
wavFormat.wFormatTag = WAVE_FORMAT_PCM;
wavFormat.nChannels = nChannels;
wavFormat.nSamplesPerSec = mSamplesPerSec;
wavFormat.nAvgBytesPerSec =
nChannels * mSamplesPerSec * sizeof(MpAudioSample);
wavFormat.nBlockAlign = nChannels * sizeof(MpAudioSample);
wavFormat.wBitsPerSample = sizeof(MpAudioSample) * 8;
wavFormat.cbSize = 0;
// Tell windows to open the input audio device. This doesn't
// tell it to send the data to our callback yet, just to get it ready
// to do so..
MMRESULT res = waveInOpen(&mDevHandle, mWntDeviceId,
&wavFormat, (DWORD_PTR)waveInCallbackStatic,
(DWORD_PTR)this, CALLBACK_FUNCTION);
if (res != MMSYSERR_NOERROR)
{
// If waveInOpen failed, print out the error info,
// invalidate the handle, and the device driver itself,
status = OS_FAILED;
showWaveError("MpInputDeviceDriverWnt::enableDevice", res, -1, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL; // Open didn't work, reset device handle to NULL
mWntDeviceId = -1; // Make device invalid.
// and return OS_FAILED.
return status;
}
// Allocate the buffers we are going to use to receive audio data from
// the windows audio input callback.
// Calculate the buffer length we're going to use.
// number of samples per frame * sample size in bytes
mWaveBufSize = mSamplesPerFrame * sizeof(MpAudioSample);
unsigned i;
for (i = 0; i < mNumInBuffers; i++)
{
mpWaveBuffers[i] = new char[mWaveBufSize];
}
// Setup the buffers so windows can stuff them full of audio
// when it becomes available from this audio input device.
WAVEHDR* pWaveHdr = NULL;
for (i=0; i < mNumInBuffers; i++)
{
pWaveHdr = initWaveHeader(i);
res = waveInPrepareHeader(mDevHandle, pWaveHdr, sizeof(WAVEHDR));
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInPrepareHeader", res, i, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL;
mWntDeviceId = -1;
// and return OS_FAILED.
return status;
}
res = waveInAddBuffer(mDevHandle, pWaveHdr, sizeof(WAVEHDR));
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInAddBuffer", res, i, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL;
mWntDeviceId = -1;
// and return OS_FAILED.
return status;
}
}
// Tell windows to start sending audio data to the callback.
res = waveInStart(mDevHandle);
if (res != MMSYSERR_NOERROR)
{
// If waveInStart failed, print out the error info,
// invalidate the handle and the device driver itself,
status = OS_FAILED;
showWaveError("waveInStart", res, -1, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL;
mWntDeviceId = -1;
// and return OS_FAILED.
return status;
}
// If enableDevice failed, return indicating failure.
if (status == OS_SUCCESS)
{
mIsEnabled = TRUE;
}
return status;
}
OsStatus MpInputDeviceDriverWnt::disableDevice()
{
OsStatus status = OS_SUCCESS;
MMRESULT res;
if (!isDeviceValid() || !isEnabled())
{
return OS_FAILED;
}
// Indicate we are no longer enabled -- Do this first,
// since we'll be partially disabled from here on out.
mIsEnabled = FALSE;
// Cleanup
if (mDevHandle == NULL)
{
return OS_INVALID_STATE;
}
// Reset performs a stop, resets the buffers, and marks them
// for being sent to the callback.
// The remaining data in the windows buffers *IS* sent to the callback,
// So be sure to watch for it and drop it on the floor.
res = waveInReset(mDevHandle);
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInReset", res, -1, __LINE__);
}
// Must unprepare the headers after a reset, but before the device is closed
// (if this is done after waveInClose, mDevHandle will be invalid and
// MMSYSERR_INVALHANDLE will be returned.
unsigned i;
for (i=0; i < mNumInBuffers; i++)
{
res = waveInUnprepareHeader(mDevHandle, &mpWaveHeaders[i], sizeof(WAVEHDR));
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInUnprepareHeader", res, i, __LINE__);
}
}
res = waveInClose(mDevHandle);
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInClose", res, -1, __LINE__);
}
// Delete the buffers that were allocated in enableDevice()
for (i = 0; i < mNumInBuffers; i++)
{
delete[] mpWaveBuffers[i];
mpWaveBuffers[i] = NULL;
}
// set the device handle to NULL, since it no longer is valid.
mDevHandle = NULL;
// Clear out all the wave header information.
mSamplesPerFrame = 0;
mSamplesPerSec = 0;
mCurrentFrameTime = 0;
return status;
}
/* ============================ ACCESSORS ================================= */
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
void MpInputDeviceDriverWnt::processAudioInput(HWAVEIN hwi,
UINT uMsg,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2)
{
if (!mIsOpen)
{
assert(uMsg == WIM_OPEN);
if (uMsg == WIM_OPEN)
{
printf("received WIM_OPEN\n");
mIsOpen = TRUE;
}
}
if (uMsg == WIM_DATA)
{
//printf("received WIM_DATA\n");
assert(mIsOpen);
WAVEHDR* pWaveHdr = (WAVEHDR*)dwParam1;
assert(pWaveHdr->dwBufferLength
== (mSamplesPerFrame*sizeof(MpAudioSample)));
assert(pWaveHdr->lpData != NULL);
mpInputDeviceManager->pushFrame(mDeviceId,
mSamplesPerFrame,
(MpAudioSample*)pWaveHdr->lpData,
mCurrentFrameTime);
// Ok, we have received and pushed a frame to the manager,
// Now we advance the frame time.
mCurrentFrameTime += (mSamplesPerFrame*1000)/mSamplesPerSec;
}
else if (uMsg == WIM_CLOSE)
{
printf("received WIM_CLOSE\n");
mIsOpen = FALSE;
}
}
void CALLBACK
MpInputDeviceDriverWnt::waveInCallbackStatic(HWAVEIN hwi,
UINT uMsg,
DWORD_PTR dwInstance,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2)
{
assert(dwInstance != NULL);
MpInputDeviceDriverWnt* iddWntPtr = (MpInputDeviceDriverWnt*)dwInstance;
iddWntPtr->processAudioInput(hwi, uMsg, dwParam1, dwParam2);
}
/* //////////////////////////// PRIVATE /////////////////////////////////// */
WAVEHDR* MpInputDeviceDriverWnt::initWaveHeader(int n)
{
assert((n >= 0) && (n < (int)mNumInBuffers));
assert(mpWaveHeaders != NULL);
assert((mpWaveBuffers != NULL) && (mpWaveBuffers[n] != NULL));
WAVEHDR& wave_hdr(mpWaveHeaders[n]);
LPSTR wave_data(mpWaveBuffers[n]);
// zero out the wave buffer.
memset(wave_data, 0, mWaveBufSize);
// Set wave header data to initial values.
wave_hdr.lpData = wave_data;
wave_hdr.dwBufferLength = mWaveBufSize;
wave_hdr.dwBytesRecorded = 0; // Filled in by wave functions
wave_hdr.dwUser = n;
wave_hdr.dwFlags = 0;
wave_hdr.dwLoops = 0;
wave_hdr.lpNext = NULL;
wave_hdr.reserved = 0;
return &wave_hdr;
}
// Copy constructor (not implemented for this class)
//MpWntInputDeviceDriver::MpWntInputDeviceDriver(const MpInputDeviceDriver& rMpInputDeviceDriver) {}
// Copy constructor (not implemented for this class)
//MpWntInputDeviceDriver& MpWntInputDeviceDriver::operator =(const MpInputDeviceDriver &rhs) {}<commit_msg>All wave buffers pointers should be set to NULL in MpInputDeviceDriverWnt constructor to be clean prevent assert in its destructor if device was never enabled.<commit_after>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Keith Kyzivat <kkyzivat AT SIPez DOT com>
// SYSTEM INCLUDES
#include <Windows.h>
// APPLICATION INCLUDES
#include "mp/MpInputDeviceDriverWnt.h"
#include "mp/MpInputDeviceManager.h"
// EXTERNAL FUNCTIONS
extern void showWaveError(char *syscall, int e, int N, int line) ; // dmaTaskWnt.cpp
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Default constructor
MpInputDeviceDriverWnt::MpInputDeviceDriverWnt(const UtlString& name,
MpInputDeviceManager& deviceManager,
unsigned nInputBuffers)
: MpInputDeviceDriver(name, deviceManager)
, mWntDeviceId(-1)
, mDevHandle(NULL)
, mNumInBuffers(nInputBuffers)
, mWaveBufSize(0) // Unknown until enableDevice()
, mIsOpen(FALSE)
{
WAVEINCAPS devCaps;
// Grab the number of input devices that are available.
UINT nInputDevs = waveInGetNumDevs();
// Search through the input devices looking for the input device specified.
MMRESULT wavResult = MMSYSERR_NOERROR;
unsigned i;
for (i = 0; i < nInputDevs; i++)
{
MMRESULT res = waveInGetDevCaps(i, &devCaps, sizeof(devCaps));
if (res != MMSYSERR_NOERROR)
{
wavResult = res;
}
else if (strncmp(name, devCaps.szPname, MAXPNAMELEN) == 0)
{
mWntDeviceId = i;
break;
}
}
// Allocate the wave headers and buffer pointers for use with
// windows audio routines.
//(This does *not* include allocation of the buffers themselves -
// that is handled in enableDevice, as we don't know the
// buffer size (#samplesPerFrame) until then.
mpWaveHeaders = new WAVEHDR[mNumInBuffers];
mpWaveBuffers = new LPSTR[mNumInBuffers];
for (i = 0; i < mNumInBuffers; i++)
{
mpWaveBuffers[i] = NULL;
}
}
// Destructor
MpInputDeviceDriverWnt::~MpInputDeviceDriverWnt()
{
// If we happen to still be enabled at this point, disable the device.
assert(!isEnabled());
if (isEnabled())
{
disableDevice();
}
// Delete the sample headers and sample buffer pointers..
unsigned i;
for (i = 0; i < mNumInBuffers; i++)
{
assert(mpWaveBuffers[i] == NULL);
if (mpWaveBuffers[i] != NULL)
{
delete[] mpWaveBuffers[i];
mpWaveBuffers[i] = NULL;
}
}
delete[] mpWaveBuffers;
delete[] mpWaveHeaders;
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpInputDeviceDriverWnt::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime)
{
OsStatus status = OS_SUCCESS;
// If the device is not valid, let the user know it's bad.
if (!isDeviceValid())
{
return OS_INVALID_STATE; // perhaps new OsState of OS_RESOURCE_INVALID?
}
if (isEnabled())
{
return OS_FAILED;
}
// Set some wave header stat information.
mSamplesPerFrame = samplesPerFrame;
mSamplesPerSec = samplesPerSec;
mCurrentFrameTime = currentFrameTime;
// Do stuff to enable device.
int nChannels = 1;
WAVEFORMATEX wavFormat;
wavFormat.wFormatTag = WAVE_FORMAT_PCM;
wavFormat.nChannels = nChannels;
wavFormat.nSamplesPerSec = mSamplesPerSec;
wavFormat.nAvgBytesPerSec =
nChannels * mSamplesPerSec * sizeof(MpAudioSample);
wavFormat.nBlockAlign = nChannels * sizeof(MpAudioSample);
wavFormat.wBitsPerSample = sizeof(MpAudioSample) * 8;
wavFormat.cbSize = 0;
// Tell windows to open the input audio device. This doesn't
// tell it to send the data to our callback yet, just to get it ready
// to do so..
MMRESULT res = waveInOpen(&mDevHandle, mWntDeviceId,
&wavFormat, (DWORD_PTR)waveInCallbackStatic,
(DWORD_PTR)this, CALLBACK_FUNCTION);
if (res != MMSYSERR_NOERROR)
{
// If waveInOpen failed, print out the error info,
// invalidate the handle, and the device driver itself,
status = OS_FAILED;
showWaveError("MpInputDeviceDriverWnt::enableDevice", res, -1, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL; // Open didn't work, reset device handle to NULL
mWntDeviceId = -1; // Make device invalid.
// and return OS_FAILED.
return status;
}
// Allocate the buffers we are going to use to receive audio data from
// the windows audio input callback.
// Calculate the buffer length we're going to use.
// number of samples per frame * sample size in bytes
mWaveBufSize = mSamplesPerFrame * sizeof(MpAudioSample);
unsigned i;
for (i = 0; i < mNumInBuffers; i++)
{
mpWaveBuffers[i] = new char[mWaveBufSize];
}
// Setup the buffers so windows can stuff them full of audio
// when it becomes available from this audio input device.
WAVEHDR* pWaveHdr = NULL;
for (i=0; i < mNumInBuffers; i++)
{
pWaveHdr = initWaveHeader(i);
res = waveInPrepareHeader(mDevHandle, pWaveHdr, sizeof(WAVEHDR));
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInPrepareHeader", res, i, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL;
mWntDeviceId = -1;
// and return OS_FAILED.
return status;
}
res = waveInAddBuffer(mDevHandle, pWaveHdr, sizeof(WAVEHDR));
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInAddBuffer", res, i, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL;
mWntDeviceId = -1;
// and return OS_FAILED.
return status;
}
}
// Tell windows to start sending audio data to the callback.
res = waveInStart(mDevHandle);
if (res != MMSYSERR_NOERROR)
{
// If waveInStart failed, print out the error info,
// invalidate the handle and the device driver itself,
status = OS_FAILED;
showWaveError("waveInStart", res, -1, __LINE__);
waveInClose(mDevHandle);
mDevHandle = NULL;
mWntDeviceId = -1;
// and return OS_FAILED.
return status;
}
// If enableDevice failed, return indicating failure.
if (status == OS_SUCCESS)
{
mIsEnabled = TRUE;
}
return status;
}
OsStatus MpInputDeviceDriverWnt::disableDevice()
{
OsStatus status = OS_SUCCESS;
MMRESULT res;
if (!isDeviceValid() || !isEnabled())
{
return OS_FAILED;
}
// Indicate we are no longer enabled -- Do this first,
// since we'll be partially disabled from here on out.
mIsEnabled = FALSE;
// Cleanup
if (mDevHandle == NULL)
{
return OS_INVALID_STATE;
}
// Reset performs a stop, resets the buffers, and marks them
// for being sent to the callback.
// The remaining data in the windows buffers *IS* sent to the callback,
// So be sure to watch for it and drop it on the floor.
res = waveInReset(mDevHandle);
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInReset", res, -1, __LINE__);
}
// Must unprepare the headers after a reset, but before the device is closed
// (if this is done after waveInClose, mDevHandle will be invalid and
// MMSYSERR_INVALHANDLE will be returned.
unsigned i;
for (i=0; i < mNumInBuffers; i++)
{
res = waveInUnprepareHeader(mDevHandle, &mpWaveHeaders[i], sizeof(WAVEHDR));
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInUnprepareHeader", res, i, __LINE__);
}
}
res = waveInClose(mDevHandle);
if (res != MMSYSERR_NOERROR)
{
showWaveError("waveInClose", res, -1, __LINE__);
}
// Delete the buffers that were allocated in enableDevice()
for (i = 0; i < mNumInBuffers; i++)
{
delete[] mpWaveBuffers[i];
mpWaveBuffers[i] = NULL;
}
// set the device handle to NULL, since it no longer is valid.
mDevHandle = NULL;
// Clear out all the wave header information.
mSamplesPerFrame = 0;
mSamplesPerSec = 0;
mCurrentFrameTime = 0;
return status;
}
/* ============================ ACCESSORS ================================= */
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
void MpInputDeviceDriverWnt::processAudioInput(HWAVEIN hwi,
UINT uMsg,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2)
{
if (!mIsOpen)
{
assert(uMsg == WIM_OPEN);
if (uMsg == WIM_OPEN)
{
printf("received WIM_OPEN\n");
mIsOpen = TRUE;
}
}
if (uMsg == WIM_DATA)
{
//printf("received WIM_DATA\n");
assert(mIsOpen);
WAVEHDR* pWaveHdr = (WAVEHDR*)dwParam1;
assert(pWaveHdr->dwBufferLength
== (mSamplesPerFrame*sizeof(MpAudioSample)));
assert(pWaveHdr->lpData != NULL);
mpInputDeviceManager->pushFrame(mDeviceId,
mSamplesPerFrame,
(MpAudioSample*)pWaveHdr->lpData,
mCurrentFrameTime);
// Ok, we have received and pushed a frame to the manager,
// Now we advance the frame time.
mCurrentFrameTime += (mSamplesPerFrame*1000)/mSamplesPerSec;
}
else if (uMsg == WIM_CLOSE)
{
printf("received WIM_CLOSE\n");
mIsOpen = FALSE;
}
}
void CALLBACK
MpInputDeviceDriverWnt::waveInCallbackStatic(HWAVEIN hwi,
UINT uMsg,
DWORD_PTR dwInstance,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2)
{
assert(dwInstance != NULL);
MpInputDeviceDriverWnt* iddWntPtr = (MpInputDeviceDriverWnt*)dwInstance;
iddWntPtr->processAudioInput(hwi, uMsg, dwParam1, dwParam2);
}
/* //////////////////////////// PRIVATE /////////////////////////////////// */
WAVEHDR* MpInputDeviceDriverWnt::initWaveHeader(int n)
{
assert((n >= 0) && (n < (int)mNumInBuffers));
assert(mpWaveHeaders != NULL);
assert((mpWaveBuffers != NULL) && (mpWaveBuffers[n] != NULL));
WAVEHDR& wave_hdr(mpWaveHeaders[n]);
LPSTR wave_data(mpWaveBuffers[n]);
// zero out the wave buffer.
memset(wave_data, 0, mWaveBufSize);
// Set wave header data to initial values.
wave_hdr.lpData = wave_data;
wave_hdr.dwBufferLength = mWaveBufSize;
wave_hdr.dwBytesRecorded = 0; // Filled in by wave functions
wave_hdr.dwUser = n;
wave_hdr.dwFlags = 0;
wave_hdr.dwLoops = 0;
wave_hdr.lpNext = NULL;
wave_hdr.reserved = 0;
return &wave_hdr;
}
// Copy constructor (not implemented for this class)
//MpWntInputDeviceDriver::MpWntInputDeviceDriver(const MpInputDeviceDriver& rMpInputDeviceDriver) {}
// Copy constructor (not implemented for this class)
//MpWntInputDeviceDriver& MpWntInputDeviceDriver::operator =(const MpInputDeviceDriver &rhs) {}<|endoftext|>
|
<commit_before>//
// main.cpp
// curveDrawing
//
// Created by Ian Watterson on 1/28/16.
// Copyright © 2016 IanWattersonPersonal. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
<commit_msg>Open a glfw window. Essentially following the LearnOpenGL Tutorial. It was frustrating to get the linking of packages to work in Xcode, but I got it done.<commit_after>//
// main.cpp
// curveDrawing
//
// Created by Ian Watterson on 1/28/16.
// Copyright © 2016 IanWattersonPersonal. All rights reserved.
//
#include <iostream>
// GLEW
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
int main(int argc, const char * argv[]) {
std::cout << "Hello, World!\n";
std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
// Define the viewport dimensions
glViewport(0, 0, WIDTH, HEIGHT);
// Game loop
while (!glfwWindowShouldClose(window))
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Swap the screen buffers
glfwSwapBuffers(window);
}
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
std::cout << key << std::endl;
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
<|endoftext|>
|
<commit_before>#include <psp2/ctrl.h>
#include <psp2/touch.h>
#include <psp2/moduleinfo.h>
#include <psp2/kernel/processmgr.h>
#include <string>
#include <cstdio>
#include <vita2d.h>
#include "../vitamenulib/libvitamenu/menu_manager.h"
#include "../vitamenulib/libvitamenu/menu.h"
#include "../vitamenulib/libvitamenu/menu_item.h"
#include "../vitamenulib/libvitamenu/utils.h"
#include "libUVL/libUVL.h"
PSP2_MODULE_INFO(0, 0, "kmenu");
void log(std::string s)
{
printf("%s%s", s.c_str(), "\n");
}
void load_helloworld()
{
char test_homebrew_file[] = "cache0:/VitaDefilerClient/Documents/helloworld.elf";
if(uvl_load(&test_homebrew_file[0]) < 0)
{
log("Hello world failed to load!");
}
else
{
log("Hello world loaded!");
}
}
int main() {
log("Starting");
vita2d_init();
char menu_name[] = "kMenu";
char test_menuitem_name[] = "Run a test";
char background_file[] = "cache0:/VitaDefilerClient/Documents/splash.png";
MenuManager * manager = new MenuManager();
Menu * menu = new Menu(manager, 100, 50);
menu->setName(&menu_name[0]);
menu->setBackground(&background_file[0]);
menu->addMenuItem(new MenuItem(&test_menuitem_name[0], 100, 100, &load_helloworld));
//input for both touch and joysticks
SceCtrlData pad;
SceTouchData touch;
while(1) {
//read input
sceCtrlPeekBufferPositive(0, &pad, 1);
sceTouchPeek(0, &touch, 1);
//quit when you press triangle
if (pad.buttons & PSP2_CTRL_TRIANGLE)
{
break;
}
manager->handleDpad(&pad);
manager->handleTouch(&touch);
vita2d_start_drawing();
vita2d_clear_screen();
manager->draw();
vita2d_end_drawing();
vita2d_swap_buffers();
}
log("Stopped.\n");
vita2d_fini();
sceKernelExitProcess(0);
delete manager;
return 0;
}<commit_msg>Use lowercase since git ignores string case in file names<commit_after>#include <psp2/ctrl.h>
#include <psp2/touch.h>
#include <psp2/moduleinfo.h>
#include <psp2/kernel/processmgr.h>
#include <string>
#include <cstdio>
#include <vita2d.h>
#include "../vitamenulib/libvitamenu/menu_manager.h"
#include "../vitamenulib/libvitamenu/menu.h"
#include "../vitamenulib/libvitamenu/menu_item.h"
#include "../vitamenulib/libvitamenu/utils.h"
#include "libUVL/libuvl.h"
PSP2_MODULE_INFO(0, 0, "kmenu");
void log(std::string s)
{
printf("%s%s", s.c_str(), "\n");
}
void load_helloworld()
{
char test_homebrew_file[] = "cache0:/VitaDefilerClient/Documents/helloworld.elf";
if(uvl_load(&test_homebrew_file[0]) < 0)
{
log("Hello world failed to load!");
}
else
{
log("Hello world loaded!");
}
}
int main() {
log("Starting");
vita2d_init();
char menu_name[] = "kMenu";
char test_menuitem_name[] = "Run a test";
char background_file[] = "cache0:/VitaDefilerClient/Documents/splash.png";
MenuManager * manager = new MenuManager();
Menu * menu = new Menu(manager, 100, 50);
menu->setName(&menu_name[0]);
menu->setBackground(&background_file[0]);
menu->addMenuItem(new MenuItem(&test_menuitem_name[0], 100, 100, &load_helloworld));
//input for both touch and joysticks
SceCtrlData pad;
SceTouchData touch;
while(1) {
//read input
sceCtrlPeekBufferPositive(0, &pad, 1);
sceTouchPeek(0, &touch, 1);
//quit when you press triangle
if (pad.buttons & PSP2_CTRL_TRIANGLE)
{
break;
}
manager->handleDpad(&pad);
manager->handleTouch(&touch);
vita2d_start_drawing();
vita2d_clear_screen();
manager->draw();
vita2d_end_drawing();
vita2d_swap_buffers();
}
log("Stopped.\n");
vita2d_fini();
sceKernelExitProcess(0);
delete manager;
return 0;
}<|endoftext|>
|
<commit_before>/*
* Raging MIDI (https://github.com/waddlesplash/ragingmidi).
*
* Copyright (c) 2012-2013 WaddleSplash & contributors (see AUTHORS.txt).
*
* 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 "TracksEdit.h"
#include "ui_TracksEdit.h"
#include <QColor>
#include <QMessageBox>
#include <QMidi.h>
#include "../Selectors/SelectInstrument.h"
void TrackSlider::setValue(int v)
{
valToRevertTo = v;
QSlider::setValue(v);
}
void TrackSlider::revert()
{
blockSignals(true);
setValue(valToRevertTo);
blockSignals(false);
}
TrackItem::TrackItem(QTreeWidget *tree, int track)
: QTreeWidgetItem(tree)
{
this->setText(TrackNumber,QString::number(track));
volSL = new TrackSlider(this->treeWidget());
volSL->setTracking(false);
volSL->setMinimum(0);
volSL->setValue(100);
volSL->setMaximum(100);
this->treeWidget()->setItemWidget(this,Vol,volSL);
balSL = new TrackSlider(this->treeWidget());
balSL->setTracking(false);
balSL->setMinimum(-50);
balSL->setMaximum(50);
this->treeWidget()->setItemWidget(this,Bal,balSL);
}
TracksEdit::TracksEdit(QWidget *parent) :
QTreeWidget(parent),
ui(new Ui::TracksEdit)
{
ui->setupUi(this);
this->hideColumn(TrackItem::TrackNumber);
colorNames = QColor::colorNames();
colorNames.removeOne("black");
colorNames.removeOne("white");
colorNames.removeOne("azure");
colorNames.removeOne("aliceblue");
connect(this,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemDoubleClicked(QTreeWidgetItem*,int)));
connect(this,SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemClicked(QTreeWidgetItem*,int)));
connect(this,SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemChanged(QTreeWidgetItem*,int)));
resizeColsToContents();
}
TracksEdit::~TracksEdit()
{
delete ui;
}
void TracksEdit::resizeColsToContents()
{
for(int i = 0;i<this->columnCount();i++)
{ this->resizeColumnToContents(i); }
}
TrackItem* TracksEdit::createTrack(int trackNum)
{
TrackItem* ret = new TrackItem(this,trackNum);
ret->setBackgroundColor(TrackItem::Name,QColor(colorNames.at(trackNum)));
myTrackColors.insert(trackNum,QColor(colorNames.at(trackNum)));
ret->setType(tr("Instrument"));
ret->setOn(tr("on"));
ret->setDevice("<automatic>");
ret->volSlider()->setTrack(trackNum);
ret->balSlider()->setTrack(trackNum);
connect(ret->volSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_volChanged(int)));
connect(ret->balSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_balChanged(int)));
return ret;
}
void TracksEdit::trackItem_volChanged(int v)
{
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
int trk = sl->track();
int vel = 127.0*(v/100.0);
int oldVel = -1;
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if(e->type() != QMidiEvent::NoteOn) { continue; }
if(oldVel == -1) { oldVel = e->velocity(); continue; }
if(oldVel != e->velocity()) {
int ret = QMessageBox::warning(this->parentWidget(),tr("Different volumes!"),
tr("<b>Some of the notes in this track have different volumes than others.</b><br/>"
"Are you sure you want to modify the volume?"),
QMessageBox::Ok,QMessageBox::Cancel);
if(ret == QMessageBox::Ok) { break; }
else { sl->revert(); return; }
}
}
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if(e->type() != QMidiEvent::NoteOn) { continue; }
e->setVelocity(vel);
}
emit somethingChanged();
}
void TracksEdit::trackItem_balChanged(int b)
{
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
int trk = sl->track();
int val = 0x40 + (b * 0x3f)/50;
int oldVal = -1;
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if((e->type() != QMidiEvent::ControlChange) ||
(e->number() != /*Coarse pan */10)) { continue; }
if(oldVal == -1) { oldVal = e->value(); continue; }
if(oldVal != e->value()) {
int ret = QMessageBox::warning(this->parentWidget(),tr("Different Balance!"),
tr("<b>This track already has Balance event.</b><br/>"
"Are you sure you want to modify the balance?"),
QMessageBox::Ok,QMessageBox::Cancel);
if(ret == QMessageBox::Ok) { break; }
else { sl->revert(); return; }
}
}
bool bChanged = false;
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if((e->type() != QMidiEvent::ControlChange) ||
(e->number() != /*Coarse pan */10)) { continue; }
e->setValue(val);
bChanged = true;
}
if (!bChanged) {
midiFile->createControlChangeEvent(trk, 0, this->tracks().at(trk)->voice(), /* Coarse Pan */10, val);
}
QMidi::outSendMsg((0xb0 + this->tracks().at(trk)->voice())|(10<<8)|(val<<16));
emit somethingChanged();
}
QList<TrackItem*> TracksEdit::tracks()
{
QList<TrackItem*> ret;
QTreeWidgetItem *c;
for(int i = 0;i<this->topLevelItemCount();i++) {
c = this->topLevelItem(i);
ret.append(static_cast<TrackItem*>(c));
}
return ret;
}
void TracksEdit::init(VirtualPiano* p)
{
piano = p;
}
void TracksEdit::setupTracks(QMidiFile *f)
{
ignoreEvents = true;
midiFile = f;
this->clear();
foreach(int curTrack,midiFile->tracks())
{
TrackItem* i = this->createTrack(curTrack);
bool didInstr = false, didVoice = false, didName = false, didVol = false;
foreach(QMidiEvent* e, midiFile->eventsForTrack(curTrack))
{
if(!didVoice && e->type() == QMidiEvent::NoteOn)
{
i->setVoice(e->voice());
if(e->voice() == 9) { i->setInst(tr("Drums")); didInstr = true; }
didVoice = true;
}
if(!didVol && e->type() == QMidiEvent::NoteOn)
{
i->setVol((e->velocity()/127.0)*100);
didVol = true;
}
else if(!didInstr && e->type() == QMidiEvent::ProgramChange)
{
int instr = e->number();
SelectInstrument sel(this);
sel.setInsNum(instr);
i->setInst(sel.insName());
QMidi::outSetInstr(e->voice(),e->number());
didInstr = true;
}
else if(!didName && (e->type() == QMidiEvent::Meta) &&
(e->number() == 0x03))
{ i->setName(e->data()); didName = true; } // Name
if(didInstr && didVoice && didName) { break; }
}
if(!didInstr)
{ i->setInst(tr("(no instrument)")); }
if(!didName)
{ i->setName(tr("Track %1","track number").arg(curTrack)); }
}
ignoreEvents = false;
resizeColsToContents();
myTrackStatus.clear();
updateTrackOn();
}
void TracksEdit::deleteCurTrack()
{
TrackItem* i = static_cast<TrackItem*>(this->selectedItems().at(0));
if(!i) { return; }
int trackNum = i->track();
i->~QTreeWidgetItem();
foreach(QMidiEvent*e,midiFile->eventsForTrack(trackNum))
{
midiFile->removeEvent(e);
delete e;
}
midiFile->removeTrack(trackNum);
}
void TracksEdit::updateTrackOn()
{
QList<int> soloTracks;
foreach(TrackItem* itm,tracks()) {
if(itm->on() == tr("solo")) {
soloTracks.append(itm->track());
piano->clearTrackColors(itm->track());
}
bool on = (itm->on() == tr("on"));
myTrackStatus.insert(itm->track(),on);
if(!on) { QMidi::outStopAll(itm->voice()); }
}
if(soloTracks.size() < 1) { return; }
foreach(int i,myTrackStatus.keys()) {
if(soloTracks.contains(i)) {
myTrackStatus.insert(i,true);
continue;
}
myTrackStatus.insert(i,false);
}
QMidi::outStopAll();
piano->clearTrackColors();
}
void TracksEdit::tracksEdit_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::Name) {
Qt::ItemFlags oldFlags = itm->flags();
itm->setFlags(oldFlags | Qt::ItemIsEditable);
this->editItem(itm,column);
itm->setFlags(oldFlags);
} else if(column == TrackItem::Inst) {
if(itm->voice() == 9) { return; } // drums, don't change
SelectInstrument* ins = new SelectInstrument(this);
ins->setModal(true);
ins->setInsName(itm->inst());
if(ins->exec() == QDialog::Accepted) {
itm->setInst(ins->insName());
int insNum = ins->insNum();
bool didChange = false;
foreach(QMidiEvent*e,midiFile->eventsForTrack(itm->track())) {
if (e->type() == QMidiEvent::ProgramChange) {
didChange = (e->number() != insNum) || didChange;
e->setNumber(insNum);
}
}
QMidi::outSetInstr(itm->voice(),ins->insNum());
if(didChange) { emit somethingChanged(); }
}
}
}
void TracksEdit::tracksEdit_itemClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::On) {
if(itm->on() == tr("on")) {
itm->setOn(tr("mute"));
itm->setBackgroundColor(TrackItem::On,QColor("#a52a2a"));
itm->setForeground(TrackItem::On,QColor(Qt::white));
updateTrackOn();
} else if(itm->on() == tr("mute")) {
itm->setOn(tr("solo"));
item->setBackgroundColor(TrackItem::On,QColor(Qt::darkBlue));
updateTrackOn();
} else {
itm->setOn(tr("on"));
itm->setBackgroundColor(TrackItem::On,QColor(Qt::white));
itm->setForeground(TrackItem::On,QColor(Qt::black));
updateTrackOn();
}
this->resizeColumnToContents(TrackItem::On);
}
VirtualPiano::voiceToUse = itm->voice();
}
void TracksEdit::tracksEdit_itemChanged(QTreeWidgetItem* item, int column)
{
if(ignoreEvents) { return; }
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::Name)
{
foreach(QMidiEvent* e, midiFile->eventsForTrack(itm->track()))
{
if((e->type() == QMidiEvent::Meta) &&
(e->number() == 0x03) &&
(e->data() != itm->name().toUtf8()))
{
e->setData(itm->name().toUtf8());
emit somethingChanged();
return;
}
}
}
}
<commit_msg>Fix indentation<commit_after>/*
* Raging MIDI (https://github.com/waddlesplash/ragingmidi).
*
* Copyright (c) 2012-2013 WaddleSplash & contributors (see AUTHORS.txt).
*
* 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 "TracksEdit.h"
#include "ui_TracksEdit.h"
#include <QColor>
#include <QMessageBox>
#include <QMidi.h>
#include "../Selectors/SelectInstrument.h"
void TrackSlider::setValue(int v)
{
valToRevertTo = v;
QSlider::setValue(v);
}
void TrackSlider::revert()
{
blockSignals(true);
setValue(valToRevertTo);
blockSignals(false);
}
TrackItem::TrackItem(QTreeWidget *tree, int track)
: QTreeWidgetItem(tree)
{
this->setText(TrackNumber,QString::number(track));
volSL = new TrackSlider(this->treeWidget());
volSL->setTracking(false);
volSL->setMinimum(0);
volSL->setValue(100);
volSL->setMaximum(100);
this->treeWidget()->setItemWidget(this,Vol,volSL);
balSL = new TrackSlider(this->treeWidget());
balSL->setTracking(false);
balSL->setMinimum(-50);
balSL->setMaximum(50);
this->treeWidget()->setItemWidget(this,Bal,balSL);
}
TracksEdit::TracksEdit(QWidget *parent) :
QTreeWidget(parent),
ui(new Ui::TracksEdit)
{
ui->setupUi(this);
this->hideColumn(TrackItem::TrackNumber);
colorNames = QColor::colorNames();
colorNames.removeOne("black");
colorNames.removeOne("white");
colorNames.removeOne("azure");
colorNames.removeOne("aliceblue");
connect(this,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemDoubleClicked(QTreeWidgetItem*,int)));
connect(this,SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemClicked(QTreeWidgetItem*,int)));
connect(this,SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemChanged(QTreeWidgetItem*,int)));
resizeColsToContents();
}
TracksEdit::~TracksEdit()
{
delete ui;
}
void TracksEdit::resizeColsToContents()
{
for(int i = 0;i<this->columnCount();i++)
{ this->resizeColumnToContents(i); }
}
TrackItem* TracksEdit::createTrack(int trackNum)
{
TrackItem* ret = new TrackItem(this,trackNum);
ret->setBackgroundColor(TrackItem::Name,QColor(colorNames.at(trackNum)));
myTrackColors.insert(trackNum,QColor(colorNames.at(trackNum)));
ret->setType(tr("Instrument"));
ret->setOn(tr("on"));
ret->setDevice("<automatic>");
ret->volSlider()->setTrack(trackNum);
ret->balSlider()->setTrack(trackNum);
connect(ret->volSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_volChanged(int)));
connect(ret->balSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_balChanged(int)));
return ret;
}
void TracksEdit::trackItem_volChanged(int v)
{
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
int trk = sl->track();
int vel = 127.0*(v/100.0);
int oldVel = -1;
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if(e->type() != QMidiEvent::NoteOn) { continue; }
if(oldVel == -1) { oldVel = e->velocity(); continue; }
if(oldVel != e->velocity()) {
int ret = QMessageBox::warning(this->parentWidget(),tr("Different volumes!"),
tr("<b>Some of the notes in this track have different volumes than others.</b><br/>"
"Are you sure you want to modify the volume?"),
QMessageBox::Ok,QMessageBox::Cancel);
if(ret == QMessageBox::Ok) { break; }
else { sl->revert(); return; }
}
}
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if(e->type() != QMidiEvent::NoteOn) { continue; }
e->setVelocity(vel);
}
emit somethingChanged();
}
void TracksEdit::trackItem_balChanged(int b)
{
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
int trk = sl->track();
int val = 0x40 + (b * 0x3f)/50;
int oldVal = -1;
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if((e->type() != QMidiEvent::ControlChange) ||
(e->number() != /*Coarse pan */10)) { continue; }
if(oldVal == -1) { oldVal = e->value(); continue; }
if(oldVal != e->value()) {
int ret = QMessageBox::warning(this->parentWidget(),tr("Different Balance!"),
tr("<b>This track already has Balance event.</b><br/>"
"Are you sure you want to modify the balance?"),
QMessageBox::Ok,QMessageBox::Cancel);
if(ret == QMessageBox::Ok) { break; }
else { sl->revert(); return; }
}
}
bool bChanged = false;
foreach(QMidiEvent* e, midiFile->eventsForTrack(trk))
{
if((e->type() != QMidiEvent::ControlChange) ||
(e->number() != /*Coarse pan */10)) { continue; }
e->setValue(val);
bChanged = true;
}
if (!bChanged) {
midiFile->createControlChangeEvent(trk, 0, this->tracks().at(trk)->voice(), /* Coarse Pan */10, val);
}
QMidi::outSendMsg((0xb0 + this->tracks().at(trk)->voice())|(10<<8)|(val<<16));
emit somethingChanged();
}
QList<TrackItem*> TracksEdit::tracks()
{
QList<TrackItem*> ret;
QTreeWidgetItem *c;
for(int i = 0;i<this->topLevelItemCount();i++) {
c = this->topLevelItem(i);
ret.append(static_cast<TrackItem*>(c));
}
return ret;
}
void TracksEdit::init(VirtualPiano* p)
{
piano = p;
}
void TracksEdit::setupTracks(QMidiFile *f)
{
ignoreEvents = true;
midiFile = f;
this->clear();
foreach(int curTrack,midiFile->tracks())
{
TrackItem* i = this->createTrack(curTrack);
bool didInstr = false, didVoice = false, didName = false, didVol = false;
foreach(QMidiEvent* e, midiFile->eventsForTrack(curTrack))
{
if(!didVoice && e->type() == QMidiEvent::NoteOn)
{
i->setVoice(e->voice());
if(e->voice() == 9) { i->setInst(tr("Drums")); didInstr = true; }
didVoice = true;
}
if(!didVol && e->type() == QMidiEvent::NoteOn)
{
i->setVol((e->velocity()/127.0)*100);
didVol = true;
}
else if(!didInstr && e->type() == QMidiEvent::ProgramChange)
{
int instr = e->number();
SelectInstrument sel(this);
sel.setInsNum(instr);
i->setInst(sel.insName());
QMidi::outSetInstr(e->voice(),e->number());
didInstr = true;
}
else if(!didName && (e->type() == QMidiEvent::Meta) &&
(e->number() == 0x03))
{ i->setName(e->data()); didName = true; } // Name
if(didInstr && didVoice && didName) { break; }
}
if(!didInstr)
{ i->setInst(tr("(no instrument)")); }
if(!didName)
{ i->setName(tr("Track %1","track number").arg(curTrack)); }
}
ignoreEvents = false;
resizeColsToContents();
myTrackStatus.clear();
updateTrackOn();
}
void TracksEdit::deleteCurTrack()
{
TrackItem* i = static_cast<TrackItem*>(this->selectedItems().at(0));
if(!i) { return; }
int trackNum = i->track();
i->~QTreeWidgetItem();
foreach(QMidiEvent*e,midiFile->eventsForTrack(trackNum))
{
midiFile->removeEvent(e);
delete e;
}
midiFile->removeTrack(trackNum);
}
void TracksEdit::updateTrackOn()
{
QList<int> soloTracks;
foreach(TrackItem* itm,tracks()) {
if(itm->on() == tr("solo")) {
soloTracks.append(itm->track());
piano->clearTrackColors(itm->track());
}
bool on = (itm->on() == tr("on"));
myTrackStatus.insert(itm->track(),on);
if(!on) { QMidi::outStopAll(itm->voice()); }
}
if(soloTracks.size() < 1) { return; }
foreach(int i,myTrackStatus.keys()) {
if(soloTracks.contains(i)) {
myTrackStatus.insert(i,true);
continue;
}
myTrackStatus.insert(i,false);
}
QMidi::outStopAll();
piano->clearTrackColors();
}
void TracksEdit::tracksEdit_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::Name) {
Qt::ItemFlags oldFlags = itm->flags();
itm->setFlags(oldFlags | Qt::ItemIsEditable);
this->editItem(itm,column);
itm->setFlags(oldFlags);
} else if(column == TrackItem::Inst) {
if(itm->voice() == 9) { return; } // drums, don't change
SelectInstrument* ins = new SelectInstrument(this);
ins->setModal(true);
ins->setInsName(itm->inst());
if(ins->exec() == QDialog::Accepted) {
itm->setInst(ins->insName());
int insNum = ins->insNum();
bool didChange = false;
foreach(QMidiEvent*e,midiFile->eventsForTrack(itm->track())) {
if (e->type() == QMidiEvent::ProgramChange) {
didChange = (e->number() != insNum) || didChange;
e->setNumber(insNum);
}
}
QMidi::outSetInstr(itm->voice(),ins->insNum());
if(didChange) { emit somethingChanged(); }
}
}
}
void TracksEdit::tracksEdit_itemClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::On) {
if(itm->on() == tr("on")) {
itm->setOn(tr("mute"));
itm->setBackgroundColor(TrackItem::On,QColor("#a52a2a"));
itm->setForeground(TrackItem::On,QColor(Qt::white));
updateTrackOn();
} else if(itm->on() == tr("mute")) {
itm->setOn(tr("solo"));
item->setBackgroundColor(TrackItem::On,QColor(Qt::darkBlue));
updateTrackOn();
} else {
itm->setOn(tr("on"));
itm->setBackgroundColor(TrackItem::On,QColor(Qt::white));
itm->setForeground(TrackItem::On,QColor(Qt::black));
updateTrackOn();
}
this->resizeColumnToContents(TrackItem::On);
}
VirtualPiano::voiceToUse = itm->voice();
}
void TracksEdit::tracksEdit_itemChanged(QTreeWidgetItem* item, int column)
{
if(ignoreEvents) { return; }
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::Name)
{
foreach(QMidiEvent* e, midiFile->eventsForTrack(itm->track()))
{
if((e->type() == QMidiEvent::Meta) &&
(e->number() == 0x03) &&
(e->data() != itm->name().toUtf8()))
{
e->setData(itm->name().toUtf8());
emit somethingChanged();
return;
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/page_info_bubble_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/toolbar_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/controls/separator.h"
#include "views/grid_layout.h"
#include "views/widget/widget.h"
#include "views/window/window.h"
namespace {
// Layout constants.
const int kHGapToBorder = 11;
const int kVGapToImage = 10;
const int kVGapToHeadline = 7;
const int kHGapImageToDescription = 6;
const int kTextPaddingRight = 10;
const int kPaddingBelowSeparator = 4;
const int kPaddingAboveSeparator = 13;
const int kIconOffset = 28;
// A section contains an image that shows a status (good or bad), a title, an
// optional head-line (in bold) and a description.
class Section : public views::View,
public views::LinkController {
public:
Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info);
virtual ~Section();
// views::View methods:
virtual int GetHeightForWidth(int w);
virtual void Layout();
// views::LinkController methods:
virtual void LinkActivated(views::Link* source, int event_flags);
private:
// Calculate the layout if |compute_bounds_only|, otherwise does Layout also.
gfx::Size LayoutItems(bool compute_bounds_only, int width);
// The view that owns this Section object.
PageInfoBubbleView* owner_;
// The information this view represents.
PageInfoModel::SectionInfo info_;
static SkBitmap* good_state_icon_;
static SkBitmap* bad_state_icon_;
views::ImageView* status_image_;
views::Label* headline_label_;
views::Label* description_label_;
views::Link* link_;
DISALLOW_COPY_AND_ASSIGN(Section);
};
// static
SkBitmap* Section::good_state_icon_ = NULL;
SkBitmap* Section::bad_state_icon_ = NULL;
} // namespace
////////////////////////////////////////////////////////////////////////////////
// PageInfoBubbleView
PageInfoBubbleView::PageInfoBubbleView(gfx::NativeWindow parent_window,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
parent_window_(parent_window),
cert_id_(ssl.cert_id()),
info_bubble_(NULL) {
LayoutSections();
}
PageInfoBubbleView::~PageInfoBubbleView() {
}
void PageInfoBubbleView::ShowCertDialog() {
ShowCertificateViewerByID(parent_window_, cert_id_);
}
void PageInfoBubbleView::LayoutSections() {
// Remove all the existing sections.
RemoveAllChildViews(true);
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
views::ColumnSet* columns = layout->AddColumnSet(0);
columns->AddColumn(views::GridLayout::FILL, // Horizontal resize.
views::GridLayout::FILL, // Vertical resize.
1, // Resize weight.
views::GridLayout::USE_PREF, // Size type.
0, // Ignored for USE_PREF.
0); // Minimum size.
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
layout->StartRow(0, 0);
// TODO(finnur): Remove title from the info struct, since it is
// not used anymore.
layout->AddView(new Section(this, info));
// Add separator after all sections except the last.
if (i < count - 1) {
layout->AddPaddingRow(0, kPaddingAboveSeparator);
layout->StartRow(0, 0);
layout->AddView(new views::Separator());
layout->AddPaddingRow(0, kPaddingBelowSeparator);
}
}
}
gfx::Size PageInfoBubbleView::GetPreferredSize() {
gfx::Size size(views::Window::GetLocalizedContentsSize(
IDS_PAGEINFOBUBBLE_WIDTH_CHARS, IDS_PAGEINFOBUBBLE_HEIGHT_LINES));
size.set_height(0);
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
Section section(this, info);
size.Enlarge(0, section.GetHeightForWidth(size.width()));
}
// Account for the separators and padding.
views::Separator separator;
gfx::Size separator_size = separator.GetPreferredSize();
size.Enlarge(0, (count - 1) * (separator_size.height() +
kPaddingAboveSeparator +
kPaddingBelowSeparator));
return size;
}
void PageInfoBubbleView::ModelChanged() {
LayoutSections();
info_bubble_->SizeToContents();
}
////////////////////////////////////////////////////////////////////////////////
// Section
Section::Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info)
: owner_(owner),
info_(section_info) {
if (!good_state_icon_) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
good_state_icon_ = rb.GetBitmapNamed(IDR_PAGEINFO_GOOD);
bad_state_icon_ = rb.GetBitmapNamed(IDR_PAGEINFO_BAD);
}
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY ||
info_.type == PageInfoModel::SECTION_INFO_CONNECTION) {
status_image_ = new views::ImageView();
status_image_->SetImage(info_.state ? good_state_icon_ : bad_state_icon_);
AddChildView(status_image_);
}
headline_label_ = new views::Label(UTF16ToWideHack(info_.headline));
headline_label_->SetFont(
headline_label_->font().DeriveFont(0, gfx::Font::BOLD));
headline_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(headline_label_);
description_label_ = new views::Label(UTF16ToWideHack(info_.description));
description_label_->SetMultiLine(true);
description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
description_label_->SetAllowCharacterBreak(true);
AddChildView(description_label_);
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY) {
link_ = new views::Link(
l10n_util::GetStringUTF16(IDS_PAGEINFO_CERT_INFO_BUTTON));
link_->SetController(this);
AddChildView(link_);
}
}
Section::~Section() {
}
int Section::GetHeightForWidth(int width) {
return LayoutItems(true, width).height();
}
void Section::Layout() {
LayoutItems(false, width());
}
void Section::LinkActivated(views::Link* source, int event_flags) {
owner_->ShowCertDialog();
}
gfx::Size Section::LayoutItems(bool compute_bounds_only, int width) {
int x = kHGapToBorder;
int y = kVGapToImage;
// Layout the image, head-line and description.
gfx::Size size;
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY ||
info_.type == PageInfoModel::SECTION_INFO_CONNECTION) {
size = status_image_->GetPreferredSize();
if (!compute_bounds_only)
status_image_->SetBounds(x, y, size.width(), size.height());
}
int image_height = y + size.height();
x += size.width() + kHGapImageToDescription;
int w = width - x - kTextPaddingRight;
y = kVGapToHeadline;
if (!headline_label_->GetText().empty()) {
size = headline_label_->GetPreferredSize();
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, w > 0 ? w : 0, size.height());
y += size.height();
} else {
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, 0, 0);
}
if (w > 0) {
int height = description_label_->GetHeightForWidth(w);
if (!compute_bounds_only)
description_label_->SetBounds(x, y, w, height);
y += height;
} else {
if (!compute_bounds_only)
description_label_->SetBounds(x, y, 0, 0);
}
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY) {
size = link_->GetPreferredSize();
link_->SetBounds(x, y, size.width(), size.height());
y += size.height();
}
// Make sure the image is not truncated if the text doesn't contain much.
y = std::max(y, image_height);
return gfx::Size(width, y);
}
namespace browser {
void ShowPageInfoBubble(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
// Find where to point the bubble at.
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(parent);
gfx::Rect bounds = browser_view->toolbar()->location_bar()->bounds();
gfx::Point point;
views::View::ConvertPointToScreen(browser_view->toolbar()->location_bar(),
&point);
bounds.set_origin(point);
bounds.set_width(kIconOffset);
// Show the bubble.
PageInfoBubbleView* page_info_bubble =
new PageInfoBubbleView(parent, profile, url, ssl, show_history);
InfoBubble* info_bubble =
InfoBubble::Show(browser_view->GetWidget(), bounds,
BubbleBorder::TOP_LEFT,
page_info_bubble, page_info_bubble);
page_info_bubble->set_info_bubble(info_bubble);
}
}
<commit_msg>Build fix for ChromeOS. (Didn't see this error below the first)<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/page_info_bubble_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/toolbar_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/controls/separator.h"
#include "views/grid_layout.h"
#include "views/widget/widget.h"
#include "views/window/window.h"
namespace {
// Layout constants.
const int kHGapToBorder = 11;
const int kVGapToImage = 10;
const int kVGapToHeadline = 7;
const int kHGapImageToDescription = 6;
const int kTextPaddingRight = 10;
const int kPaddingBelowSeparator = 4;
const int kPaddingAboveSeparator = 13;
const int kIconOffset = 28;
// A section contains an image that shows a status (good or bad), a title, an
// optional head-line (in bold) and a description.
class Section : public views::View,
public views::LinkController {
public:
Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info);
virtual ~Section();
// views::View methods:
virtual int GetHeightForWidth(int w);
virtual void Layout();
// views::LinkController methods:
virtual void LinkActivated(views::Link* source, int event_flags);
private:
// Calculate the layout if |compute_bounds_only|, otherwise does Layout also.
gfx::Size LayoutItems(bool compute_bounds_only, int width);
// The view that owns this Section object.
PageInfoBubbleView* owner_;
// The information this view represents.
PageInfoModel::SectionInfo info_;
static SkBitmap* good_state_icon_;
static SkBitmap* bad_state_icon_;
views::ImageView* status_image_;
views::Label* headline_label_;
views::Label* description_label_;
views::Link* link_;
DISALLOW_COPY_AND_ASSIGN(Section);
};
// static
SkBitmap* Section::good_state_icon_ = NULL;
SkBitmap* Section::bad_state_icon_ = NULL;
} // namespace
////////////////////////////////////////////////////////////////////////////////
// PageInfoBubbleView
PageInfoBubbleView::PageInfoBubbleView(gfx::NativeWindow parent_window,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
parent_window_(parent_window),
cert_id_(ssl.cert_id()),
info_bubble_(NULL) {
LayoutSections();
}
PageInfoBubbleView::~PageInfoBubbleView() {
}
void PageInfoBubbleView::ShowCertDialog() {
ShowCertificateViewerByID(parent_window_, cert_id_);
}
void PageInfoBubbleView::LayoutSections() {
// Remove all the existing sections.
RemoveAllChildViews(true);
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
views::ColumnSet* columns = layout->AddColumnSet(0);
columns->AddColumn(views::GridLayout::FILL, // Horizontal resize.
views::GridLayout::FILL, // Vertical resize.
1, // Resize weight.
views::GridLayout::USE_PREF, // Size type.
0, // Ignored for USE_PREF.
0); // Minimum size.
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
layout->StartRow(0, 0);
// TODO(finnur): Remove title from the info struct, since it is
// not used anymore.
layout->AddView(new Section(this, info));
// Add separator after all sections except the last.
if (i < count - 1) {
layout->AddPaddingRow(0, kPaddingAboveSeparator);
layout->StartRow(0, 0);
layout->AddView(new views::Separator());
layout->AddPaddingRow(0, kPaddingBelowSeparator);
}
}
}
gfx::Size PageInfoBubbleView::GetPreferredSize() {
gfx::Size size(views::Window::GetLocalizedContentsSize(
IDS_PAGEINFOBUBBLE_WIDTH_CHARS, IDS_PAGEINFOBUBBLE_HEIGHT_LINES));
size.set_height(0);
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
Section section(this, info);
size.Enlarge(0, section.GetHeightForWidth(size.width()));
}
// Account for the separators and padding.
views::Separator separator;
gfx::Size separator_size = separator.GetPreferredSize();
size.Enlarge(0, (count - 1) * (separator_size.height() +
kPaddingAboveSeparator +
kPaddingBelowSeparator));
return size;
}
void PageInfoBubbleView::ModelChanged() {
LayoutSections();
info_bubble_->SizeToContents();
}
////////////////////////////////////////////////////////////////////////////////
// Section
Section::Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info)
: owner_(owner),
info_(section_info) {
if (!good_state_icon_) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
good_state_icon_ = rb.GetBitmapNamed(IDR_PAGEINFO_GOOD);
bad_state_icon_ = rb.GetBitmapNamed(IDR_PAGEINFO_BAD);
}
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY ||
info_.type == PageInfoModel::SECTION_INFO_CONNECTION) {
status_image_ = new views::ImageView();
status_image_->SetImage(info_.state ? good_state_icon_ : bad_state_icon_);
AddChildView(status_image_);
}
headline_label_ = new views::Label(UTF16ToWideHack(info_.headline));
headline_label_->SetFont(
headline_label_->font().DeriveFont(0, gfx::Font::BOLD));
headline_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(headline_label_);
description_label_ = new views::Label(UTF16ToWideHack(info_.description));
description_label_->SetMultiLine(true);
description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
description_label_->SetAllowCharacterBreak(true);
AddChildView(description_label_);
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY) {
link_ = new views::Link(
l10n_util::GetString(IDS_PAGEINFO_CERT_INFO_BUTTON));
link_->SetController(this);
AddChildView(link_);
}
}
Section::~Section() {
}
int Section::GetHeightForWidth(int width) {
return LayoutItems(true, width).height();
}
void Section::Layout() {
LayoutItems(false, width());
}
void Section::LinkActivated(views::Link* source, int event_flags) {
owner_->ShowCertDialog();
}
gfx::Size Section::LayoutItems(bool compute_bounds_only, int width) {
int x = kHGapToBorder;
int y = kVGapToImage;
// Layout the image, head-line and description.
gfx::Size size;
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY ||
info_.type == PageInfoModel::SECTION_INFO_CONNECTION) {
size = status_image_->GetPreferredSize();
if (!compute_bounds_only)
status_image_->SetBounds(x, y, size.width(), size.height());
}
int image_height = y + size.height();
x += size.width() + kHGapImageToDescription;
int w = width - x - kTextPaddingRight;
y = kVGapToHeadline;
if (!headline_label_->GetText().empty()) {
size = headline_label_->GetPreferredSize();
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, w > 0 ? w : 0, size.height());
y += size.height();
} else {
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, 0, 0);
}
if (w > 0) {
int height = description_label_->GetHeightForWidth(w);
if (!compute_bounds_only)
description_label_->SetBounds(x, y, w, height);
y += height;
} else {
if (!compute_bounds_only)
description_label_->SetBounds(x, y, 0, 0);
}
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY) {
size = link_->GetPreferredSize();
link_->SetBounds(x, y, size.width(), size.height());
y += size.height();
}
// Make sure the image is not truncated if the text doesn't contain much.
y = std::max(y, image_height);
return gfx::Size(width, y);
}
namespace browser {
void ShowPageInfoBubble(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
// Find where to point the bubble at.
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(parent);
gfx::Rect bounds = browser_view->toolbar()->location_bar()->bounds();
gfx::Point point;
views::View::ConvertPointToScreen(browser_view->toolbar()->location_bar(),
&point);
bounds.set_origin(point);
bounds.set_width(kIconOffset);
// Show the bubble.
PageInfoBubbleView* page_info_bubble =
new PageInfoBubbleView(parent, profile, url, ssl, show_history);
InfoBubble* info_bubble =
InfoBubble::Show(browser_view->GetWidget(), bounds,
BubbleBorder::TOP_LEFT,
page_info_bubble, page_info_bubble);
page_info_bubble->set_info_bubble(info_bubble);
}
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>
// stl
#include <cmath>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(raster_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans)
{
raster_ptr const& raster=feature.get_raster();
if (raster)
{
// If there's a colorizer defined, use it to color the raster in-place
raster_colorizer_ptr colorizer = sym.get_colorizer();
if (colorizer)
colorizer->colorize(raster);
box2d<double> ext=t_.forward(raster->ext_);
int start_x = (int)ext.minx();
int start_y = (int)ext.miny();
int end_x = (int)ceil(ext.maxx());
int end_y = (int)ceil(ext.maxy());
int raster_width = end_x - start_x;
int raster_height = end_y - start_y;
double err_offs_x = ext.minx() - start_x;
double err_offs_y = ext.miny() - start_y;
if ( raster_width > 0 && raster_height > 0)
{
double scale_factor = ext.width() / raster->data_.width();
image_data_32 target(raster_width,raster_height);
if (sym.get_scaling() == "bilinear8"){
scale_image_bilinear8<image_data_32>(target,raster->data_, err_offs_x, err_offs_y);
} else {
scaling_method_e scaling_method = get_scaling_method_by_name(sym.get_scaling());
std::clog << "scaling: " << scaling_method << "\n";
scale_image_agg<image_data_32>(target,raster->data_, (scaling_method_e)scaling_method, scale_factor, err_offs_x, err_offs_y, sym.calculate_filter_factor());
}
if (sym.get_mode() == "normal"){
if (sym.get_opacity() == 1.0) {
pixmap_.set_rectangle_alpha(start_x,start_y,target);
} else {
pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
}
} else if (sym.get_mode() == "grain_merge"){
pixmap_.template merge_rectangle<MergeGrain> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "grain_merge2"){
pixmap_.template merge_rectangle<MergeGrain2> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "multiply"){
pixmap_.template merge_rectangle<Multiply> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "multiply2"){
pixmap_.template merge_rectangle<Multiply2> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "divide"){
pixmap_.template merge_rectangle<Divide> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "divide2"){
pixmap_.template merge_rectangle<Divide2> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "screen"){
pixmap_.template merge_rectangle<Screen> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "hard_light"){
pixmap_.template merge_rectangle<HardLight> (target,start_x,start_y, sym.get_opacity());
} else {
if (sym.get_opacity() == 1.0){
pixmap_.set_rectangle(start_x,start_y,target);
} else {
pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
}
}
// TODO: other modes? (add,diff,sub,...)
}
}
}
template void agg_renderer<image_32>::process(raster_symbolizer const&,
Feature const&,
proj_transform const&);
}
<commit_msg>+ remove debug printout<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>
// stl
#include <cmath>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(raster_symbolizer const& sym,
Feature const& feature,
proj_transform const& prj_trans)
{
raster_ptr const& raster=feature.get_raster();
if (raster)
{
// If there's a colorizer defined, use it to color the raster in-place
raster_colorizer_ptr colorizer = sym.get_colorizer();
if (colorizer)
colorizer->colorize(raster);
box2d<double> ext=t_.forward(raster->ext_);
int start_x = (int)ext.minx();
int start_y = (int)ext.miny();
int end_x = (int)ceil(ext.maxx());
int end_y = (int)ceil(ext.maxy());
int raster_width = end_x - start_x;
int raster_height = end_y - start_y;
double err_offs_x = ext.minx() - start_x;
double err_offs_y = ext.miny() - start_y;
if ( raster_width > 0 && raster_height > 0)
{
double scale_factor = ext.width() / raster->data_.width();
image_data_32 target(raster_width,raster_height);
if (sym.get_scaling() == "bilinear8"){
scale_image_bilinear8<image_data_32>(target,raster->data_, err_offs_x, err_offs_y);
} else {
scaling_method_e scaling_method = get_scaling_method_by_name(sym.get_scaling());
scale_image_agg<image_data_32>(target,raster->data_, (scaling_method_e)scaling_method, scale_factor, err_offs_x, err_offs_y, sym.calculate_filter_factor());
}
if (sym.get_mode() == "normal"){
if (sym.get_opacity() == 1.0) {
pixmap_.set_rectangle_alpha(start_x,start_y,target);
} else {
pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
}
} else if (sym.get_mode() == "grain_merge"){
pixmap_.template merge_rectangle<MergeGrain> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "grain_merge2"){
pixmap_.template merge_rectangle<MergeGrain2> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "multiply"){
pixmap_.template merge_rectangle<Multiply> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "multiply2"){
pixmap_.template merge_rectangle<Multiply2> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "divide"){
pixmap_.template merge_rectangle<Divide> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "divide2"){
pixmap_.template merge_rectangle<Divide2> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "screen"){
pixmap_.template merge_rectangle<Screen> (target,start_x,start_y, sym.get_opacity());
} else if (sym.get_mode() == "hard_light"){
pixmap_.template merge_rectangle<HardLight> (target,start_x,start_y, sym.get_opacity());
} else {
if (sym.get_opacity() == 1.0){
pixmap_.set_rectangle(start_x,start_y,target);
} else {
pixmap_.set_rectangle_alpha2(target,start_x,start_y, sym.get_opacity());
}
}
// TODO: other modes? (add,diff,sub,...)
}
}
}
template void agg_renderer<image_32>::process(raster_symbolizer const&,
Feature const&,
proj_transform const&);
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(AIXDEFINITIONS_HEADER_GUARD_1357924680)
#define AIXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_LSTRSUPPORT
#define XALAN_USE_WCHAR_CAST_HACK
#define XALAN_POSIX2_AVAILABLE
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#if __IBMCPP__ > 366
#define XALAN_EXPLICIT_SCOPE_IN_TEMPLATE_BUG
#define XALAN_NEW_STD_ALLOCATOR
#else
#define XALAN_OLD_STYLE_CASTS
#define XALAN_OLD_STREAMS
#define XALAN_NO_NAMESPACES
#define XALAN_NO_MUTABLE
#define XALAN_SGI_BASED_STL
#define XALAN_NO_MEMBER_TEMPLATES
#define XALAN_AMBIGUOUS_EVEN_IF_NOT_CALLED
#define XALAN_CANNOT_DELETE_CONST
#define XALAN_BOOL_AS_INT
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION
#define XALAN_NO_ALGORITHMS_WITH_BUILTINS
#define XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS
#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_AUTO_PTR_REQUIRES_DEFINITION
#define XALAN_NEEDS_EXPLICIT_TEMPLATE_INSTANTIATION
#define XALAN_STLPORT_STL
#define XALAN_TEMPLATE_FUNCTION_NO_DEFAULT_PARAMETERS
#define XALAN_NO_STD_NUMERIC_LIMITS
// STL Port Definitions
#define _REENTRANT
#define __STL_NO_SGI_IOSTREAMS
#include <stl/_config.h>
#endif
#define XALAN_UNALIGNED
#endif // AIXDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Added missing #define.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(AIXDEFINITIONS_HEADER_GUARD_1357924680)
#define AIXDEFINITIONS_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_LSTRSUPPORT
#define XALAN_USE_WCHAR_CAST_HACK
#define XALAN_POSIX2_AVAILABLE
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#if __IBMCPP__ > 366
#define XALAN_EXPLICIT_SCOPE_IN_TEMPLATE_BUG
#define XALAN_NEW_STD_ALLOCATOR
#else
#define XALAN_OLD_STYLE_CASTS
#define XALAN_OLD_STREAM_HEADERS
#define XALAN_OLD_STREAMS
#define XALAN_NO_NAMESPACES
#define XALAN_NO_MUTABLE
#define XALAN_SGI_BASED_STL
#define XALAN_NO_MEMBER_TEMPLATES
#define XALAN_AMBIGUOUS_EVEN_IF_NOT_CALLED
#define XALAN_CANNOT_DELETE_CONST
#define XALAN_BOOL_AS_INT
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION
#define XALAN_NO_ALGORITHMS_WITH_BUILTINS
#define XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS
#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_AUTO_PTR_REQUIRES_DEFINITION
#define XALAN_NEEDS_EXPLICIT_TEMPLATE_INSTANTIATION
#define XALAN_STLPORT_STL
#define XALAN_TEMPLATE_FUNCTION_NO_DEFAULT_PARAMETERS
#define XALAN_NO_STD_NUMERIC_LIMITS
// STL Port Definitions
#define _REENTRANT
#define __STL_NO_SGI_IOSTREAMS
#include <stl/_config.h>
#endif
#define XALAN_UNALIGNED
#endif // AIXDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef TEST_SEED_HPP_
#define TEST_SEED_HPP_
static constexpr int random_seeds_count = 10;
static constexpr unsigned int seeds [] = {0, 2, 10, 1000};
static constexpr size_t seed_size = sizeof(seeds) / sizeof(seeds[0]);
#endif // TEST_SEED_HPP_<commit_msg>Reduce random test count<commit_after>// Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef TEST_SEED_HPP_
#define TEST_SEED_HPP_
static constexpr int random_seeds_count = 1;
static constexpr unsigned int seeds [] = {0, 1000};
static constexpr size_t seed_size = sizeof(seeds) / sizeof(seeds[0]);
#endif // TEST_SEED_HPP_<|endoftext|>
|
<commit_before>#include "../src/alloc.hpp"
#include "../src/bytecode.hpp"
#include "../src/function.hpp"
#include "../src/interpret.hpp"
#include "../src/thread.hpp"
#include <catch.hpp>
using namespace slakken;
using namespace slakken::bytecode;
#define SLAKKEN_PUSH_OP_0(function_id, opcode) \
do { \
instruction inst; \
inst.what = (opcode); \
functions.functions.at(function_id).instructions.push_back(inst); \
} while (false)
#define SLAKKEN_PUSH_OP_1(function_id, opcode, op0_t, op0_v) \
do { \
instruction inst; \
inst.what = (opcode); \
inst.op0.op0_t = (op0_v); \
functions.functions.at(function_id).instructions.push_back(inst); \
} while (false)
TEST_CASE("resume", "[resume]") {
alloc alloc;
function_set functions;
thread thread;
auto main = functions.alloc("");
SECTION("nop") {
SLAKKEN_PUSH_OP_0(main, opcode::nop);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
SECTION("brk") {
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
SECTION("ck.param.eq") {
SECTION("succeed") {
SECTION("0") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 0);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
SECTION("1") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 1);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(1);
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
}
SECTION("fail") {
SECTION("1 != 0") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 1);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
REQUIRE_THROWS(
resume(alloc, functions, thread)
);
}
SECTION("2 != 3") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 2);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(3);
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
REQUIRE_THROWS(
resume(alloc, functions, thread)
);
}
}
}
}
#undef SLAKKEN_PUSH_OP_1
#undef SLAKKEN_PUSH_OP_0
<commit_msg>Test neg.int interpretation<commit_after>#include "../src/alloc.hpp"
#include "../src/bytecode.hpp"
#include "../src/function.hpp"
#include "../src/interpret.hpp"
#include "../src/thread.hpp"
#include <catch.hpp>
#include <cmath>
using namespace slakken;
using namespace slakken::bytecode;
#define SLAKKEN_PUSH_OP_0(function_id, opcode) \
do { \
instruction inst; \
inst.what = (opcode); \
functions.functions.at(function_id).instructions.push_back(inst); \
} while (false)
#define SLAKKEN_PUSH_OP_1(function_id, opcode, op0_t, op0_v) \
do { \
instruction inst; \
inst.what = (opcode); \
inst.op0.op0_t = (op0_v); \
functions.functions.at(function_id).instructions.push_back(inst); \
} while (false)
TEST_CASE("resume", "[resume]") {
alloc alloc;
function_set functions;
thread thread;
auto main = functions.alloc("");
SECTION("nop") {
SLAKKEN_PUSH_OP_0(main, opcode::nop);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
SECTION("brk") {
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
SECTION("ck.param.eq") {
SECTION("succeed") {
SECTION("0") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 0);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
SECTION("1") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 1);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(1);
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
}
}
SECTION("fail") {
SECTION("1 != 0") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 1);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
REQUIRE_THROWS(
resume(alloc, functions, thread)
);
}
SECTION("2 != 3") {
SLAKKEN_PUSH_OP_1(main, opcode::ck_param_eq, imm, 2);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(3);
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
thread.params.push_back(&alloc.alloc_array(nullptr, 0));
REQUIRE_THROWS(
resume(alloc, functions, thread)
);
}
}
}
SECTION("neg.int") {
auto test_neg_int = [&] (double in, double out) {
SLAKKEN_PUSH_OP_0(main, opcode::neg_int);
SLAKKEN_PUSH_OP_0(main, opcode::brk);
thread.program_counters.emplace_back(main, 0);
thread.param_counts.push_back(0);
thread.operands.push_back(&alloc.alloc_float(in));
auto status = resume(alloc, functions, thread);
REQUIRE(status == resume_status::breakpoint);
auto& result = *thread.operands.at(0);
REQUIRE(dynamic_cast<float_value const&>(result).get() == out);
if (in == 0.0) {
REQUIRE(!std::signbit(dynamic_cast<float_value const&>(result).get()));
}
};
SECTION("42") { test_neg_int(42.0, -42.0); }
SECTION("-42") { test_neg_int(-42.0, 42.0); }
SECTION("0") { test_neg_int(0.0, 0.0); }
SECTION("2147483647") { test_neg_int(2147483647.0, -2147483647.0); }
SECTION("-2147483647") { test_neg_int(-2147483647.0, 2147483647.0); }
SECTION("-2147483648") { test_neg_int(-2147483648.0, -2147483648.0); }
}
}
#undef SLAKKEN_PUSH_OP_1
#undef SLAKKEN_PUSH_OP_0
<|endoftext|>
|
<commit_before>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkPluginFrameworkContext_p.h"
#include "ctkPluginFrameworkUtil_p.h"
#include "ctkPluginFramework_p.h"
#include "ctkPluginArchive_p.h"
#include "ctkPluginStorageSQL_p.h"
#include "ctkPluginConstants.h"
#include "ctkServices_p.h"
#include "ctkUtils.h"
//----------------------------------------------------------------------------
QMutex ctkPluginFrameworkContext::globalFwLock;
int ctkPluginFrameworkContext::globalId = 1;
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::ctkPluginFrameworkContext(
const ctkProperties& initProps)
: plugins(0), listeners(this), services(0), systemPlugin(new ctkPluginFramework()),
storage(0), firstInit(true), props(initProps), debug(props),
initialized(false)
{
{
QMutexLocker lock(&globalFwLock);
id = globalId++;
systemPlugin->ctkPlugin::init(new ctkPluginFrameworkPrivate(systemPlugin, this));
}
initProperties();
log() << "created";
}
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::~ctkPluginFrameworkContext()
{
if (initialized)
{
this->uninit();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::initProperties()
{
props[ctkPluginConstants::FRAMEWORK_VERSION] = "0.9";
props[ctkPluginConstants::FRAMEWORK_VENDOR] = "CommonTK";
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::init()
{
log() << "initializing";
if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT
== props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN])
{
deleteFWDir();
firstInit = false;
}
// Pre-load libraries
// This may speed up installing new plug-ins if they have dependencies on
// one of these libraries. It prevents repeated loading and unloading of the
// pre-loaded libraries during caching of the plug-in meta-data.
if (props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].isValid())
{
QStringList preloadLibs = props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].toStringList();
QLibrary::LoadHints loadHints;
QVariant loadHintsVariant = props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
if (loadHintsVariant.isValid())
{
loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
}
foreach(QString preloadLib, preloadLibs)
{
QLibrary lib;
QStringList nameAndVersion = preloadLib.split(":");
QString libraryName;
if (nameAndVersion.count() == 1)
{
libraryName = nameAndVersion.front();
lib.setFileName(nameAndVersion.front());
}
else if (nameAndVersion.count() == 2)
{
libraryName = nameAndVersion.front() + "." + nameAndVersion.back();
lib.setFileNameAndVersion(nameAndVersion.front(), nameAndVersion.back());
}
else
{
qWarning() << "Wrong syntax in" << preloadLib << ". Use <lib-name>[:version]. Skipping.";
continue;
}
lib.setLoadHints(loadHints);
log() << "Pre-loading library" << lib.fileName() << "with hints [" << static_cast<int>(loadHints) << "]";
if (!lib.load())
{
qWarning() << "Pre-loading library" << lib.fileName() << "failed:" << lib.errorString() << "\nCheck your library search paths.";
}
}
}
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->initSystemPlugin();
storage = new ctkPluginStorageSQL(this);
dataStorage = ctkPluginFrameworkUtil::getFileStorage(this, "data");
services = new ctkServices(this);
plugins = new ctkPlugins(this);
plugins->load();
log() << "inited";
initialized = true;
log() << "Installed plugins:";
// Use the ordering in the plugin storage to get a sorted list of plugins.
QList<QSharedPointer<ctkPluginArchive> > allPAs = storage->getAllPluginArchives();
foreach (QSharedPointer<ctkPluginArchive> pa, allPAs)
{
QSharedPointer<ctkPlugin> plugin = plugins->getPlugin(pa->getPluginLocation().toString());
log() << " #" << plugin->getPluginId() << " " << plugin->getSymbolicName() << ":"
<< plugin->getVersion() << " location:" << plugin->getLocation();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::uninit()
{
if (!initialized) return;
log() << "uninit";
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->uninitSystemPlugin();
plugins->clear();
delete plugins;
plugins = 0;
delete storage; // calls storage->close()
storage = 0;
delete services;
services = 0;
initialized = false;
}
//----------------------------------------------------------------------------
int ctkPluginFrameworkContext::getId() const
{
return id;
}
//----------------------------------------------------------------------------
QFileInfo ctkPluginFrameworkContext::getDataStorage(long id)
{
return QFileInfo(dataStorage.absolutePath() + '/' + QString::number(id) + '/');
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkOurPlugin(ctkPlugin* plugin) const
{
ctkPluginPrivate* pp = plugin->d_func();
if (this != pp->fwCtx)
{
throw ctkInvalidArgumentException("ctkPlugin does not belong to this framework: " + plugin->getSymbolicName());
}
}
//----------------------------------------------------------------------------
QDebug ctkPluginFrameworkContext::log() const
{
static QString nirvana;
nirvana.clear();
if (debug.framework)
return qDebug() << "Framework instance " << getId() << ": ";
else
return QDebug(&nirvana);
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::resolvePlugin(ctkPluginPrivate* plugin)
{
if (debug.resolve)
{
qDebug() << "resolve:" << plugin->symbolicName << "[" << plugin->id << "]";
}
// If we enter with tempResolved set, it means that we already have
// resolved plugins. Check that it is true!
if (tempResolved.size() > 0 && !tempResolved.contains(plugin))
{
ctkPluginException pe("resolve: InternalError1!", ctkPluginException::RESOLVE_ERROR);
listeners.frameworkError(plugin->q_func(), pe);
throw pe;
}
tempResolved.clear();
tempResolved.insert(plugin);
checkRequirePlugin(plugin);
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "resolve: Done for" << plugin->symbolicName << "[" << plugin->id << "]";
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkRequirePlugin(ctkPluginPrivate *plugin)
{
if (!plugin->require.isEmpty())
{
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: check requiring plugin" << plugin->id;
}
QListIterator<ctkRequirePlugin*> i(plugin->require);
while (i.hasNext())
{
ctkRequirePlugin* pr = i.next();
QList<ctkPlugin*> pl = plugins->getPlugins(pr->name, pr->pluginRange);
ctkPluginPrivate* ok = 0;
for (QListIterator<ctkPlugin*> pci(pl); pci.hasNext() && ok == 0; )
{
ctkPluginPrivate* p2 = pci.next()->d_func();
if (tempResolved.contains(p2))
{
ok = p2;
}
else if (ctkPluginPrivate::RESOLVED_FLAGS & p2->state)
{
ok = p2;
}
else if (p2->state == ctkPlugin::INSTALLED) {
QSet<ctkPluginPrivate*> oldTempResolved = tempResolved;
tempResolved.insert(p2);
// TODO check if operation locking is correct in case of
// multi-threaded plug-in start up. Maybe refactor out the dependency
// checking (use the "package" lock)
ctkPluginPrivate::Locker sync(&p2->operationLock);
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::RESOLVING);
checkRequirePlugin(p2);
tempResolved = oldTempResolved;
p2->state = ctkPlugin::RESOLVED;
listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, p2->q_func()));
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::IDLE);
ok = p2;
}
}
if (!ok && pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
{
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: failed to satisfy:" << pr->name;
}
throw ctkPluginException(QString("Failed to resolve required plugin: %1").arg(pr->name));
}
}
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::deleteFWDir()
{
QString d = ctkPluginFrameworkUtil::getFrameworkDir(this);
QFileInfo fwDirInfo(d);
if (fwDirInfo.exists())
{
if(fwDirInfo.isDir())
{
log() << "deleting old framework directory.";
bool bOK = ctk::removeDirRecursively(fwDirInfo.absoluteFilePath());
if(!bOK)
{
qDebug() << "Failed to remove existing fwdir" << fwDirInfo.absoluteFilePath();
}
}
}
}
<commit_msg>Using : as separator might conflict with absolute paths on Windows.<commit_after>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkPluginFrameworkContext_p.h"
#include "ctkPluginFrameworkUtil_p.h"
#include "ctkPluginFramework_p.h"
#include "ctkPluginArchive_p.h"
#include "ctkPluginStorageSQL_p.h"
#include "ctkPluginConstants.h"
#include "ctkServices_p.h"
#include "ctkUtils.h"
//----------------------------------------------------------------------------
QMutex ctkPluginFrameworkContext::globalFwLock;
int ctkPluginFrameworkContext::globalId = 1;
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::ctkPluginFrameworkContext(
const ctkProperties& initProps)
: plugins(0), listeners(this), services(0), systemPlugin(new ctkPluginFramework()),
storage(0), firstInit(true), props(initProps), debug(props),
initialized(false)
{
{
QMutexLocker lock(&globalFwLock);
id = globalId++;
systemPlugin->ctkPlugin::init(new ctkPluginFrameworkPrivate(systemPlugin, this));
}
initProperties();
log() << "created";
}
//----------------------------------------------------------------------------
ctkPluginFrameworkContext::~ctkPluginFrameworkContext()
{
if (initialized)
{
this->uninit();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::initProperties()
{
props[ctkPluginConstants::FRAMEWORK_VERSION] = "0.9";
props[ctkPluginConstants::FRAMEWORK_VENDOR] = "CommonTK";
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::init()
{
log() << "initializing";
if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT
== props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN])
{
deleteFWDir();
firstInit = false;
}
// Pre-load libraries
// This may speed up installing new plug-ins if they have dependencies on
// one of these libraries. It prevents repeated loading and unloading of the
// pre-loaded libraries during caching of the plug-in meta-data.
if (props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].isValid())
{
QStringList preloadLibs = props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].toStringList();
QLibrary::LoadHints loadHints;
QVariant loadHintsVariant = props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
if (loadHintsVariant.isValid())
{
loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
}
foreach(QString preloadLib, preloadLibs)
{
QLibrary lib;
QStringList nameAndVersion = preloadLib.split("$");
QString libraryName;
if (nameAndVersion.count() == 1)
{
libraryName = nameAndVersion.front();
lib.setFileName(nameAndVersion.front());
}
else if (nameAndVersion.count() == 2)
{
libraryName = nameAndVersion.front() + "." + nameAndVersion.back();
lib.setFileNameAndVersion(nameAndVersion.front(), nameAndVersion.back());
}
else
{
qWarning() << "Wrong syntax in" << preloadLib << ". Use <lib-name>[$version]. Skipping.";
continue;
}
lib.setLoadHints(loadHints);
log() << "Pre-loading library" << lib.fileName() << "with hints [" << static_cast<int>(loadHints) << "]";
if (!lib.load())
{
qWarning() << "Pre-loading library" << lib.fileName() << "failed:" << lib.errorString() << "\nCheck your library search paths.";
}
}
}
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->initSystemPlugin();
storage = new ctkPluginStorageSQL(this);
dataStorage = ctkPluginFrameworkUtil::getFileStorage(this, "data");
services = new ctkServices(this);
plugins = new ctkPlugins(this);
plugins->load();
log() << "inited";
initialized = true;
log() << "Installed plugins:";
// Use the ordering in the plugin storage to get a sorted list of plugins.
QList<QSharedPointer<ctkPluginArchive> > allPAs = storage->getAllPluginArchives();
foreach (QSharedPointer<ctkPluginArchive> pa, allPAs)
{
QSharedPointer<ctkPlugin> plugin = plugins->getPlugin(pa->getPluginLocation().toString());
log() << " #" << plugin->getPluginId() << " " << plugin->getSymbolicName() << ":"
<< plugin->getVersion() << " location:" << plugin->getLocation();
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::uninit()
{
if (!initialized) return;
log() << "uninit";
ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func();
systemPluginPrivate->uninitSystemPlugin();
plugins->clear();
delete plugins;
plugins = 0;
delete storage; // calls storage->close()
storage = 0;
delete services;
services = 0;
initialized = false;
}
//----------------------------------------------------------------------------
int ctkPluginFrameworkContext::getId() const
{
return id;
}
//----------------------------------------------------------------------------
QFileInfo ctkPluginFrameworkContext::getDataStorage(long id)
{
return QFileInfo(dataStorage.absolutePath() + '/' + QString::number(id) + '/');
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkOurPlugin(ctkPlugin* plugin) const
{
ctkPluginPrivate* pp = plugin->d_func();
if (this != pp->fwCtx)
{
throw ctkInvalidArgumentException("ctkPlugin does not belong to this framework: " + plugin->getSymbolicName());
}
}
//----------------------------------------------------------------------------
QDebug ctkPluginFrameworkContext::log() const
{
static QString nirvana;
nirvana.clear();
if (debug.framework)
return qDebug() << "Framework instance " << getId() << ": ";
else
return QDebug(&nirvana);
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::resolvePlugin(ctkPluginPrivate* plugin)
{
if (debug.resolve)
{
qDebug() << "resolve:" << plugin->symbolicName << "[" << plugin->id << "]";
}
// If we enter with tempResolved set, it means that we already have
// resolved plugins. Check that it is true!
if (tempResolved.size() > 0 && !tempResolved.contains(plugin))
{
ctkPluginException pe("resolve: InternalError1!", ctkPluginException::RESOLVE_ERROR);
listeners.frameworkError(plugin->q_func(), pe);
throw pe;
}
tempResolved.clear();
tempResolved.insert(plugin);
checkRequirePlugin(plugin);
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "resolve: Done for" << plugin->symbolicName << "[" << plugin->id << "]";
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::checkRequirePlugin(ctkPluginPrivate *plugin)
{
if (!plugin->require.isEmpty())
{
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: check requiring plugin" << plugin->id;
}
QListIterator<ctkRequirePlugin*> i(plugin->require);
while (i.hasNext())
{
ctkRequirePlugin* pr = i.next();
QList<ctkPlugin*> pl = plugins->getPlugins(pr->name, pr->pluginRange);
ctkPluginPrivate* ok = 0;
for (QListIterator<ctkPlugin*> pci(pl); pci.hasNext() && ok == 0; )
{
ctkPluginPrivate* p2 = pci.next()->d_func();
if (tempResolved.contains(p2))
{
ok = p2;
}
else if (ctkPluginPrivate::RESOLVED_FLAGS & p2->state)
{
ok = p2;
}
else if (p2->state == ctkPlugin::INSTALLED) {
QSet<ctkPluginPrivate*> oldTempResolved = tempResolved;
tempResolved.insert(p2);
// TODO check if operation locking is correct in case of
// multi-threaded plug-in start up. Maybe refactor out the dependency
// checking (use the "package" lock)
ctkPluginPrivate::Locker sync(&p2->operationLock);
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::RESOLVING);
checkRequirePlugin(p2);
tempResolved = oldTempResolved;
p2->state = ctkPlugin::RESOLVED;
listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, p2->q_func()));
p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::IDLE);
ok = p2;
}
}
if (!ok && pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
{
tempResolved.clear();
if (debug.resolve)
{
qDebug() << "checkRequirePlugin: failed to satisfy:" << pr->name;
}
throw ctkPluginException(QString("Failed to resolve required plugin: %1").arg(pr->name));
}
}
}
}
//----------------------------------------------------------------------------
void ctkPluginFrameworkContext::deleteFWDir()
{
QString d = ctkPluginFrameworkUtil::getFrameworkDir(this);
QFileInfo fwDirInfo(d);
if (fwDirInfo.exists())
{
if(fwDirInfo.isDir())
{
log() << "deleting old framework directory.";
bool bOK = ctk::removeDirRecursively(fwDirInfo.absoluteFilePath());
if(!bOK)
{
qDebug() << "Failed to remove existing fwdir" << fwDirInfo.absoluteFilePath();
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger
*
* the lineedit data code is largely inspired from the gtk redmond engine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenlineeditdata.h"
#include "oxygenanimations.h"
#include "../oxygengtkutils.h"
#include <gtk/gtk.h>
#include <iostream>
namespace Oxygen
{
//________________________________________________________________________________
void LineEditData::connect( GtkWidget* widget )
{
_motionId = g_signal_connect( G_OBJECT(widget), "motion-notify-event", (GCallback)motionNotifyEvent, 0L);
_leaveId = g_signal_connect( G_OBJECT(widget), "leave-notify-event", (GCallback)leaveNotifyEvent, 0L );
}
//________________________________________________________________________________
void LineEditData::disconnect( GtkWidget* widget )
{
// disconnect signal
g_signal_handler_disconnect(G_OBJECT(widget), _motionId );
g_signal_handler_disconnect(G_OBJECT(widget), _leaveId );
}
//________________________________________________________________________________
gboolean LineEditData::motionNotifyEvent(GtkWidget *widget, GdkEventMotion *event, gpointer )
{
if( Animations::instance().lineEditEngine().setHovered( widget, true ) )
{ gtk_widget_queue_draw( widget ); }
return FALSE;
}
//________________________________________________________________________________
gboolean LineEditData::leaveNotifyEvent( GtkWidget *widget, GdkEventCrossing *event, gpointer )
{
if( Animations::instance().lineEditEngine().setHovered( widget, false ) )
{ gtk_widget_queue_draw( widget ); }
return FALSE;
}
}
<commit_msg>nothing.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger
*
* the lineedit data code is largely inspired from the gtk redmond engine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "oxygenlineeditdata.h"
#include "oxygenanimations.h"
#include "../oxygengtkutils.h"
#include <gtk/gtk.h>
#include <iostream>
namespace Oxygen
{
//________________________________________________________________________________
void LineEditData::connect( GtkWidget* widget )
{
_motionId = g_signal_connect( G_OBJECT(widget), "motion-notify-event", (GCallback)motionNotifyEvent, 0L );
_leaveId = g_signal_connect( G_OBJECT(widget), "leave-notify-event", (GCallback)leaveNotifyEvent, 0L );
}
//________________________________________________________________________________
void LineEditData::disconnect( GtkWidget* widget )
{
// disconnect signal
g_signal_handler_disconnect(G_OBJECT(widget), _motionId );
g_signal_handler_disconnect(G_OBJECT(widget), _leaveId );
}
//________________________________________________________________________________
gboolean LineEditData::motionNotifyEvent(GtkWidget *widget, GdkEventMotion *event, gpointer )
{
if( Animations::instance().lineEditEngine().setHovered( widget, true ) )
{ gtk_widget_queue_draw( widget ); }
return FALSE;
}
//________________________________________________________________________________
gboolean LineEditData::leaveNotifyEvent( GtkWidget *widget, GdkEventCrossing *event, gpointer )
{
if( Animations::instance().lineEditEngine().setHovered( widget, false ) )
{ gtk_widget_queue_draw( widget ); }
return FALSE;
}
}
<|endoftext|>
|
<commit_before>#include "../base/SRC_FIRST.hpp"
#include "hex.hpp"
namespace impl {
static const char kToHexTable[] = "0123456789ABCDEF";
void ToHexRaw(void const * src, size_t size, void * dst)
{
uint8_t const * ptr = static_cast<uint8_t const *>(src);
uint8_t const * end = ptr + size;
uint8_t * out = static_cast<uint8_t*>(dst);
while (ptr != end)
{
*out++ = kToHexTable[(*ptr) >> 4];
*out++ = kToHexTable[(*ptr) & 0xF];
++ptr;
}
}
// static const char kFromHexTable[] = "0123456789ABCDEF";
void FromHexRaw(void const * src, size_t size, void * dst)
{
uint8_t const * ptr = static_cast<uint8_t const *>(src);
uint8_t const * end = ptr + size;
uint8_t * out = static_cast<uint8_t*>(dst);
while (ptr < end) {
*out = 0;
if (*ptr >= '0' && *ptr <= '9') {
*out |= ((*ptr - '0') << 4);
} else if (*ptr >= 'A' && *ptr <= 'F') {
*out |= ((*ptr - 'A' + 10) << 4);
}
++ptr;
if (*ptr >= '0' && *ptr <= '9') {
*out |= ((*ptr - '0') & 0xF);
} else if (*ptr >= 'A' && *ptr <= 'F') {
*out |= ((*ptr - 'A' + 10) & 0xF);
}
++ptr;
++out;
}
}
}
<commit_msg>Refactor and remove useless code in FromHex().<commit_after>#include "../base/SRC_FIRST.hpp"
#include "hex.hpp"
namespace impl {
static const char kToHexTable[] = "0123456789ABCDEF";
void ToHexRaw(void const * src, size_t size, void * dst)
{
uint8_t const * ptr = static_cast<uint8_t const *>(src);
uint8_t const * end = ptr + size;
uint8_t * out = static_cast<uint8_t*>(dst);
while (ptr != end)
{
*out++ = kToHexTable[(*ptr) >> 4];
*out++ = kToHexTable[(*ptr) & 0xF];
++ptr;
}
}
// static const char kFromHexTable[] = "0123456789ABCDEF";
uint8_t HexDigitToRaw(uint8_t const digit)
{
if (digit >= '0' && digit <= '9')
return (digit - '0');
else if (digit >= 'A' && digit <= 'F')
return (digit - 'A' + 10);
ASSERT(false, (digit));
return 0;
}
void FromHexRaw(void const * src, size_t size, void * dst)
{
uint8_t const * ptr = static_cast<uint8_t const *>(src);
uint8_t const * end = ptr + size;
uint8_t * out = static_cast<uint8_t*>(dst);
while (ptr < end)
{
*out = HexDigitToRaw(*ptr++) << 4;
*out |= HexDigitToRaw(*ptr++);
++out;
}
}
}
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/ConsoleApplication/ConsoleCommands.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Core/Application/Application.h>
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Network/Module.h>
#include <Core/Logging/ConsoleLogger.h>
#include <Core/Python/PythonInterpreter.h>
using namespace SCIRun::Core;
using namespace Commands;
using namespace Console;
using namespace SCIRun::Dataflow::Networks;
using namespace Algorithms;
LoadFileCommandConsole::LoadFileCommandConsole()
{
addParameter(Name("FileNum"), 0);
addParameter(Variables::Filename, std::string());
}
bool LoadFileCommandConsole::execute()
{
auto inputFiles = Application::Instance().parameters()->inputFiles();
std::string filename;
if (!inputFiles.empty())
filename = inputFiles[0];
else
{
filename = get(Variables::Filename).toFilename().string();
}
{
/// @todo: real logger
std::cout << "Attempting load of " << filename << std::endl;
if (!boost::filesystem::exists(filename))
{
std::cout << "File does not exist: " << filename << std::endl;
return false;
}
try
{
auto openedFile = XMLSerializer::load_xml<NetworkFile>(filename);
if (openedFile)
{
Application::Instance().controller()->clear();
Application::Instance().controller()->loadNetwork(openedFile);
/// @todo: real logger
std::cout << "File load done: " << filename << std::endl;
return true;
}
/// @todo: real logger
std::cout << "File load failed: " << filename << std::endl;
}
catch (...)
{
/// @todo: real logger
std::cout << "File load failed: " << filename << std::endl;
}
return false;
}
return true;
}
bool SaveFileCommandConsole::execute()
{
throw "todo";
}
bool ExecuteCurrentNetworkCommandConsole::execute()
{
Application::Instance().controller()->executeAll(nullptr);
return true;
}
QuitAfterExecuteCommandConsole::QuitAfterExecuteCommandConsole()
{
addParameter(Name("RunningPython"), false);
}
bool QuitAfterExecuteCommandConsole::execute()
{
std::cout << "Goodbye!" << std::endl;
Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ exit(code); });
//SCIRunMainWindow::Instance()->setupQuitAfterExecute();
return true;
}
QuitCommandConsole::QuitCommandConsole()
{
addParameter(Name("RunningPython"), false);
}
bool QuitCommandConsole::execute()
{
std::cout << "Exiting!" << std::endl;
exit(0);
return true;
}
bool PrintHelpCommand::execute()
{
std::cout << Application::Instance().commandHelpString() << std::endl;
return true;
}
bool PrintVersionCommand::execute()
{
std::cout << Application::Instance().version() << std::endl;
return true;
}
bool PrintModulesCommand::execute()
{
std::cout << "MODULE LIST as of " << Application::Instance().version() << "\n" << Application::Instance().moduleList() << std::endl;
return true;
}
bool InteractiveModeCommandConsole::execute()
{
SCIRun::Dataflow::Networks::Module::defaultLogger_.reset(new SCIRun::Core::Logging::NullLogger);
PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *");
std::string line;
while (true)
{
std::cout << "scirun5> " << std::flush;
std::getline(std::cin, line);
if (line.find("quit") != std::string::npos) // TODO: need fix for ^D entry || (!x.empty() && x[0] == '\004'))
break;
PythonInterpreter::Instance().run_string(line);
}
exit(0);
return true;
}
bool RunPythonScriptCommandConsole::execute()
{
auto script = Application::Instance().parameters()->pythonScriptFile();
if (script)
{
#ifdef BUILD_WITH_PYTHON
std::cout << "RUNNING PYTHON SCRIPT: " << *script << std::endl;;
Application::Instance().controller()->clear();
PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *");
PythonInterpreter::Instance().run_file(script->string());
//TODO: not sure what else to do here. Probably wait on a condition variable, or just loop forever
if (!Application::Instance().parameters()->interactiveMode())
{
while (true)
{
std::cout << "Running Python script." << std::endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
}
std::cout << "Done running Python script." << std::endl;
return true;
#else
std::cout << "Python disabled, cannot run script " << *script << std::endl;
return false;
#endif
}
return false;
}
<commit_msg>Closes #1410<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/ConsoleApplication/ConsoleCommands.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Core/Application/Application.h>
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Network/Module.h>
#include <Core/Logging/ConsoleLogger.h>
#include <Core/Python/PythonInterpreter.h>
using namespace SCIRun::Core;
using namespace Commands;
using namespace Console;
using namespace SCIRun::Dataflow::Networks;
using namespace Algorithms;
LoadFileCommandConsole::LoadFileCommandConsole()
{
addParameter(Name("FileNum"), 0);
addParameter(Variables::Filename, std::string());
}
//TODO: find a better place for this function
namespace
{
void quietModulesIfNotVerbose()
{
if (!Application::Instance().parameters()->verboseMode())
SCIRun::Dataflow::Networks::Module::defaultLogger_.reset(new SCIRun::Core::Logging::NullLogger);
}
}
bool LoadFileCommandConsole::execute()
{
quietModulesIfNotVerbose();
auto inputFiles = Application::Instance().parameters()->inputFiles();
std::string filename;
if (!inputFiles.empty())
filename = inputFiles[0];
else
{
filename = get(Variables::Filename).toFilename().string();
}
{
/// @todo: real logger
std::cout << "Attempting load of " << filename << std::endl;
if (!boost::filesystem::exists(filename))
{
std::cout << "File does not exist: " << filename << std::endl;
return false;
}
try
{
auto openedFile = XMLSerializer::load_xml<NetworkFile>(filename);
if (openedFile)
{
Application::Instance().controller()->clear();
Application::Instance().controller()->loadNetwork(openedFile);
/// @todo: real logger
std::cout << "File load done: " << filename << std::endl;
return true;
}
/// @todo: real logger
std::cout << "File load failed: " << filename << std::endl;
}
catch (...)
{
/// @todo: real logger
std::cout << "File load failed: " << filename << std::endl;
}
return false;
}
return true;
}
bool SaveFileCommandConsole::execute()
{
throw "todo";
}
bool ExecuteCurrentNetworkCommandConsole::execute()
{
Application::Instance().controller()->executeAll(nullptr);
return true;
}
QuitAfterExecuteCommandConsole::QuitAfterExecuteCommandConsole()
{
addParameter(Name("RunningPython"), false);
}
bool QuitAfterExecuteCommandConsole::execute()
{
std::cout << "Goodbye!" << std::endl;
Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ exit(code); });
//SCIRunMainWindow::Instance()->setupQuitAfterExecute();
return true;
}
QuitCommandConsole::QuitCommandConsole()
{
addParameter(Name("RunningPython"), false);
}
bool QuitCommandConsole::execute()
{
std::cout << "Exiting!" << std::endl;
exit(0);
return true;
}
bool PrintHelpCommand::execute()
{
std::cout << Application::Instance().commandHelpString() << std::endl;
return true;
}
bool PrintVersionCommand::execute()
{
std::cout << Application::Instance().version() << std::endl;
return true;
}
bool PrintModulesCommand::execute()
{
std::cout << "MODULE LIST as of " << Application::Instance().version() << "\n" << Application::Instance().moduleList() << std::endl;
return true;
}
bool InteractiveModeCommandConsole::execute()
{
quietModulesIfNotVerbose();
PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *");
std::string line;
while (true)
{
std::cout << "scirun5> " << std::flush;
std::getline(std::cin, line);
if (line.find("quit") != std::string::npos) // TODO: need fix for ^D entry || (!x.empty() && x[0] == '\004'))
break;
PythonInterpreter::Instance().run_string(line);
}
exit(0);
return true;
}
bool RunPythonScriptCommandConsole::execute()
{
quietModulesIfNotVerbose();
auto script = Application::Instance().parameters()->pythonScriptFile();
if (script)
{
#ifdef BUILD_WITH_PYTHON
std::cout << "RUNNING PYTHON SCRIPT: " << *script << std::endl;;
Application::Instance().controller()->clear();
PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *");
PythonInterpreter::Instance().run_file(script->string());
//TODO: not sure what else to do here. Probably wait on a condition variable, or just loop forever
if (!Application::Instance().parameters()->interactiveMode())
{
while (true)
{
std::cout << "Running Python script." << std::endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
}
std::cout << "Done running Python script." << std::endl;
return true;
#else
std::cout << "Python disabled, cannot run script " << *script << std::endl;
return false;
#endif
}
return false;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "BuildingCard.h"
using namespace std;
BuildingCard::~BuildingCard()
{
}
void BuildingCard::Run()
{
}
<commit_msg>small comment<commit_after>#include "stdafx.h"
#include "BuildingCard.h"
using namespace std;
BuildingCard::~BuildingCard()
{
}
void BuildingCard::Run()
{
//This should remain empty because this is for the basic building cards which don't really do anything but exist
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015, 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.
*
*/
#include <string.h>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/byte_buffer_reader.h"
#include "grpc/support/slice.h"
#include "byte_buffer.h"
namespace grpc {
namespace node {
using v8::Context;
using v8::Function;
using v8::Local;
using v8::Object;
using v8::Number;
using v8::Value;
grpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {
Nan::HandleScope scope;
int length = ::node::Buffer::Length(buffer);
char *data = ::node::Buffer::Data(buffer);
gpr_slice slice = gpr_slice_malloc(length);
memcpy(GPR_SLICE_START_PTR(slice), data, length);
grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));
gpr_slice_unref(slice);
return byte_buffer;
}
Local<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {
Nan::EscapableHandleScope scope;
if (buffer == NULL) {
return scope.Escape(Nan::Null());
}
size_t length = grpc_byte_buffer_length(buffer);
char *result = reinterpret_cast<char *>(calloc(length, sizeof(char)));
size_t offset = 0;
grpc_byte_buffer_reader reader;
grpc_byte_buffer_reader_init(&reader, buffer);
gpr_slice next;
while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {
memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next));
offset += GPR_SLICE_LENGTH(next);
}
return scope.Escape(MakeFastBuffer(
Nan::NewBuffer(result, length).ToLocalChecked()));
}
Local<Value> MakeFastBuffer(Local<Value> slowBuffer) {
Nan::EscapableHandleScope scope;
Local<Object> globalObj = Nan::GetCurrentContext()->Global();
Local<Function> bufferConstructor = Local<Function>::Cast(
globalObj->Get(Nan::New("Buffer").ToLocalChecked()));
Local<Value> consArgs[3] = {
slowBuffer,
Nan::New<Number>(::node::Buffer::Length(slowBuffer)),
Nan::New<Number>(0)
};
Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);
return scope.Escape(fastBuffer);
}
} // namespace node
} // namespace grpc
<commit_msg>Fixes memory leak when receiving data<commit_after>/*
*
* Copyright 2015, 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.
*
*/
#include <string.h>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/byte_buffer_reader.h"
#include "grpc/support/slice.h"
#include "byte_buffer.h"
namespace grpc {
namespace node {
using v8::Context;
using v8::Function;
using v8::Local;
using v8::Object;
using v8::Number;
using v8::Value;
grpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {
Nan::HandleScope scope;
int length = ::node::Buffer::Length(buffer);
char *data = ::node::Buffer::Data(buffer);
gpr_slice slice = gpr_slice_malloc(length);
memcpy(GPR_SLICE_START_PTR(slice), data, length);
grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));
gpr_slice_unref(slice);
return byte_buffer;
}
Local<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {
Nan::EscapableHandleScope scope;
if (buffer == NULL) {
return scope.Escape(Nan::Null());
}
size_t length = grpc_byte_buffer_length(buffer);
char *result = reinterpret_cast<char *>(calloc(length, sizeof(char)));
size_t offset = 0;
grpc_byte_buffer_reader reader;
grpc_byte_buffer_reader_init(&reader, buffer);
gpr_slice next;
while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {
memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next));
offset += GPR_SLICE_LENGTH(next);
gpr_slice_unref(next);
}
return scope.Escape(MakeFastBuffer(
Nan::NewBuffer(result, length).ToLocalChecked()));
}
Local<Value> MakeFastBuffer(Local<Value> slowBuffer) {
Nan::EscapableHandleScope scope;
Local<Object> globalObj = Nan::GetCurrentContext()->Global();
Local<Function> bufferConstructor = Local<Function>::Cast(
globalObj->Get(Nan::New("Buffer").ToLocalChecked()));
Local<Value> consArgs[3] = {
slowBuffer,
Nan::New<Number>(::node::Buffer::Length(slowBuffer)),
Nan::New<Number>(0)
};
Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);
return scope.Escape(fastBuffer);
}
} // namespace node
} // namespace grpc
<|endoftext|>
|
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "regression.hpp"
#include <map>
#include <string>
#include <utility>
#include "../fv_converter/datum.hpp"
#include "../fv_converter/datum_to_fv_converter.hpp"
#include "../fv_converter/converter_config.hpp"
#include "../storage/storage_factory.hpp"
using std::string;
using std::pair;
using jubatus::util::lang::shared_ptr;
using jubatus::core::fv_converter::weight_manager;
namespace jubatus {
namespace core {
namespace driver {
regression::regression(
shared_ptr<storage::storage_base> model_storage,
shared_ptr<core::regression::regression_base> regression_method,
shared_ptr<fv_converter::datum_to_fv_converter> converter)
: converter_(converter)
, regression_(regression_method)
, mixable_regression_model_(regression_method->get_storage())
, wm_(core::fv_converter::mixable_weight_manager::model_ptr(new weight_manager)) {
// TODO: register mixable holder (regresion_, wm_)
converter_->set_weight_manager(wm_.get_model());
}
regression::~regression() {
}
void regression::train(const pair<float, fv_converter::datum>& data) {
common::sfv_t v;
converter_->convert_and_update_weight(data.second, v);
regression_->train(v, data.first);
}
float regression::estimate(
const fv_converter::datum& data) const {
common::sfv_t v;
converter_->convert(data, v);
float value = regression_->estimate(v);
return value;
}
void regression::get_status(std::map<string, string>& status) const {
regression_->get_status(status);
}
void regression::clear() {
regression_->clear();
converter_->clear_weights();
}
void regression::pack(msgpack::packer<msgpack::sbuffer>& pk) const {
pk.pack_array(2);
regression_->get_storage()->pack(pk);
wm_.get_model()->pack(pk);
}
void regression::unpack(msgpack::object o) {
if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {
throw msgpack::type_error();
}
// clear before load
regression_->clear();
converter_->clear_weights();
regression_->get_storage()->unpack(o.via.array.ptr[0]);
wm_.get_model()->unpack(o.via.array.ptr[1]);
}
} // namespace driver
} // namespace core
} // namespace jubatus
<commit_msg>Fix regression server to adapt new mixable<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "regression.hpp"
#include <map>
#include <string>
#include <utility>
#include "../fv_converter/datum.hpp"
#include "../fv_converter/datum_to_fv_converter.hpp"
#include "../fv_converter/converter_config.hpp"
#include "../storage/storage_factory.hpp"
using std::string;
using std::pair;
using jubatus::util::lang::shared_ptr;
using jubatus::core::fv_converter::weight_manager;
namespace jubatus {
namespace core {
namespace driver {
regression::regression(
shared_ptr<storage::storage_base> model_storage,
shared_ptr<core::regression::regression_base> regression_method,
shared_ptr<fv_converter::datum_to_fv_converter> converter)
: converter_(converter)
, regression_(regression_method)
, mixable_regression_model_(regression_method->get_storage())
, wm_(core::fv_converter::mixable_weight_manager::model_ptr(new weight_manager)) {
register_mixable(&mixable_regression_model_);
register_mixable(&wm_);
converter_->set_weight_manager(wm_.get_model());
}
regression::~regression() {
}
void regression::train(const pair<float, fv_converter::datum>& data) {
common::sfv_t v;
converter_->convert_and_update_weight(data.second, v);
regression_->train(v, data.first);
}
float regression::estimate(
const fv_converter::datum& data) const {
common::sfv_t v;
converter_->convert(data, v);
float value = regression_->estimate(v);
return value;
}
void regression::get_status(std::map<string, string>& status) const {
regression_->get_status(status);
}
void regression::clear() {
regression_->clear();
converter_->clear_weights();
}
void regression::pack(msgpack::packer<msgpack::sbuffer>& pk) const {
pk.pack_array(2);
regression_->get_storage()->pack(pk);
wm_.get_model()->pack(pk);
}
void regression::unpack(msgpack::object o) {
if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {
throw msgpack::type_error();
}
// clear before load
regression_->clear();
converter_->clear_weights();
regression_->get_storage()->unpack(o.via.array.ptr[0]);
wm_.get_model()->unpack(o.via.array.ptr[1]);
}
} // namespace driver
} // namespace core
} // namespace jubatus
<|endoftext|>
|
<commit_before>//
// kern_cpu.cpp
// Lilu
//
// Copyright © 2018 vit9696. All rights reserved.
//
#include <Headers/kern_cpu.hpp>
#include <Headers/kern_devinfo.hpp>
#include <PrivateHeaders/kern_config.hpp>
#include <i386/proc_reg.h>
extern "C" {
#include <i386/pmCPU.h>
}
/**
* Shared R/W BaseDeviceInfo instance.
*/
extern BaseDeviceInfo globalBaseDeviceInfo;
void CPUInfo::init() {
auto &bdi = globalBaseDeviceInfo;
// Start with detecting CPU vendor
uint32_t b = 0, c = 0, d = 0;
getCpuid(0, 0, &bdi.cpuMaxLevel, &b, &c, &d);
if (b == signature_INTEL_ebx && c == signature_INTEL_ecx && d == signature_INTEL_edx)
bdi.cpuVendor = CpuVendor::Intel;
else if (b == signature_AMD_ebx && c == signature_AMD_ecx && d == signature_AMD_edx)
bdi.cpuVendor = CpuVendor::AMD;
getCpuid(0x80000000, 0, &bdi.cpuMaxLevelExt);
// Only do extended model checking on Intel or when unsupported.
if (bdi.cpuVendor != CpuVendor::Intel || bdi.cpuMaxLevel < 1)
return;
// Detect CPU family and model
union {
CpuVersion fmt;
uint32_t raw;
} ver {};
getCpuid(1, 0, &ver.raw);
bdi.cpuFamily = ver.fmt.family;
if (bdi.cpuFamily == 15) bdi.cpuFamily += ver.fmt.extendedFamily;
bdi.cpuModel = ver.fmt.model;
if (bdi.cpuFamily == 15 || bdi.cpuFamily == 6)
bdi.cpuModel |= ver.fmt.extendedModel << 4;
bdi.cpuStepping = ver.fmt.stepping;
bdi.cpuHasAvx2 = getCpuid(7, 0, nullptr, &b) && (b & CPUInfo::bit_AVX2) != 0;
// Last but not least detect CPU generation
uint32_t generation = 0;
if (PE_parse_boot_argn(Configuration::bootargCpu, &generation, sizeof(generation))) {
DBGLOG("cpu", "found CPU generation override %u", generation);
if (generation < static_cast<uint32_t>(CPUInfo::CpuGeneration::MaxGeneration)) {
bdi.cpuGeneration = static_cast<CPUInfo::CpuGeneration>(generation);
return;
} else {
SYSLOG("cpu", "found invalid CPU generation override %u, falling back...", generation);
}
}
// Keep this mostly in sync to cpuid_set_cpufamily from osfmk/i386/cpuid.c
if (ver.fmt.family == 6) {
switch (bdi.cpuModel) {
case CPU_MODEL_PENRYN:
bdi.cpuGeneration = CpuGeneration::Penryn;
break;
case CPU_MODEL_NEHALEM:
case CPU_MODEL_FIELDS:
case CPU_MODEL_DALES:
case CPU_MODEL_NEHALEM_EX:
bdi.cpuGeneration = CpuGeneration::Nehalem;
break;
case CPU_MODEL_DALES_32NM:
case CPU_MODEL_WESTMERE:
case CPU_MODEL_WESTMERE_EX:
bdi.cpuGeneration = CpuGeneration::Westmere;
break;
case CPU_MODEL_SANDYBRIDGE:
case CPU_MODEL_JAKETOWN:
bdi.cpuGeneration = CpuGeneration::SandyBridge;
break;
case CPU_MODEL_IVYBRIDGE:
case CPU_MODEL_IVYBRIDGE_EP:
bdi.cpuGeneration = CpuGeneration::IvyBridge;
break;
case CPU_MODEL_HASWELL:
case CPU_MODEL_HASWELL_EP:
case CPU_MODEL_HASWELL_ULT:
case CPU_MODEL_CRYSTALWELL:
bdi.cpuGeneration = CpuGeneration::Haswell;
break;
case CPU_MODEL_BROADWELL:
case CPU_MODEL_BRYSTALWELL:
bdi.cpuGeneration = CpuGeneration::Broadwell;
break;
case CPU_MODEL_SKYLAKE:
case CPU_MODEL_SKYLAKE_DT:
case CPU_MODEL_SKYLAKE_W:
bdi.cpuGeneration = CpuGeneration::Skylake;
break;
case CPU_MODEL_KABYLAKE:
case CPU_MODEL_KABYLAKE_DT:
// Kaby has 0x9 stepping, and Coffee use 0xA / 0xB stepping.
if (ver.fmt.stepping == 9)
bdi.cpuGeneration = CpuGeneration::KabyLake;
else
bdi.cpuGeneration = CpuGeneration::CoffeeLake;
break;
case CPU_MODEL_CANNONLAKE:
bdi.cpuGeneration = CpuGeneration::CannonLake;
break;
case CPU_MODEL_ICELAKE_Y:
case CPU_MODEL_ICELAKE_U:
case CPU_MODEL_ICELAKE_SP:
bdi.cpuGeneration = CpuGeneration::IceLake;
break;
case CPU_MODEL_COMETLAKE_Y:
case CPU_MODEL_COMETLAKE_U:
bdi.cpuGeneration = CpuGeneration::CometLake;
break;
case CPU_MODEL_ROCKETLAKE_S:
bdi.cpuGeneration = CpuGeneration::RocketLake;
break;
case CPU_MODEL_TIGERLAKE_U:
bdi.cpuGeneration = CpuGeneration::TigerLake;
break;
default:
bdi.cpuGeneration = CpuGeneration::Unknown;
break;
}
}
}
CPUInfo::CpuGeneration CPUInfo::getGeneration(uint32_t *ofamily, uint32_t *omodel, uint32_t *ostepping) {
auto &bdi = BaseDeviceInfo::get();
if (ofamily) *ofamily = bdi.cpuFamily;
if (omodel) *omodel = bdi.cpuModel;
if (ostepping) *ostepping = bdi.cpuStepping;
return bdi.cpuGeneration;
}
bool CPUInfo::getCpuTopology(CpuTopology &topology) {
// Obtain power management callbacks
if (getKernelVersion() < KernelVersion::Lion) {
SYSLOG("cpu", "cannot use pmKextRegister before 10.7");
return false;
}
pmCallBacks_t callbacks {};
pmKextRegister(PM_DISPATCH_VERSION, nullptr, &callbacks);
if (!callbacks.GetPkgRoot) {
SYSLOG("cpu", "failed to obtain package root callback");
return false;
}
auto pkg = callbacks.GetPkgRoot();
if (!pkg) {
SYSLOG("cpu", "failed to obtain valid package root");
return false;
}
while (pkg) {
auto core = pkg->cores;
// Set physcal core mapping based on first virtual core
while (core) {
// I think lcpus could be null when the core is disabled and the topology is partially constructed
auto lcpu = core->lcpus;
if (lcpu) {
topology.numberToPackage[lcpu->cpu_num] = topology.packageCount;
topology.numberToPhysical[lcpu->cpu_num] = topology.physicalCount[topology.packageCount];
topology.numberToLogical[lcpu->cpu_num] = topology.logicalCount[topology.packageCount];
topology.physicalCount[topology.packageCount]++;
topology.logicalCount[topology.packageCount]++;
}
core = core->next_in_pkg;
}
// Set the rest of virtual core mapping
core = pkg->cores;
while (core) {
auto first_lcpu = core->lcpus;
auto lcpu = first_lcpu ? first_lcpu->next_in_core : nullptr;
while (lcpu) {
topology.numberToPackage[lcpu->cpu_num] = topology.packageCount;
topology.numberToPhysical[lcpu->cpu_num] = topology.numberToPhysical[first_lcpu->cpu_num];
topology.numberToLogical[lcpu->cpu_num] = topology.logicalCount[topology.packageCount];
topology.logicalCount[topology.packageCount]++;
lcpu = lcpu->next_in_core;
}
core = core->next_in_pkg;
}
topology.packageCount++;
pkg = pkg->next;
}
return true;
}
bool CPUInfo::getCpuid(uint32_t no, uint32_t count, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d) {
auto &bdi = BaseDeviceInfo::get();
uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;
bool supported = (no & 0x80000000) ? bdi.cpuMaxLevelExt >= no : bdi.cpuMaxLevel >= no;
// At least pass zeroes on failure
if (supported) {
asm ("xchgq %%rbx, %q1\n"
"cpuid\n"
"xchgq %%rbx, %q1"
: "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx)
: "0" (no), "2" (count));
}
if (a) *a = eax;
if (b) *b = ebx;
if (c) *c = ecx;
if (d) *d = edx;
return supported;
}
<commit_msg>Allow AVX 2.0 detection on AMD<commit_after>//
// kern_cpu.cpp
// Lilu
//
// Copyright © 2018 vit9696. All rights reserved.
//
#include <Headers/kern_cpu.hpp>
#include <Headers/kern_devinfo.hpp>
#include <PrivateHeaders/kern_config.hpp>
#include <i386/proc_reg.h>
extern "C" {
#include <i386/pmCPU.h>
}
/**
* Shared R/W BaseDeviceInfo instance.
*/
extern BaseDeviceInfo globalBaseDeviceInfo;
void CPUInfo::init() {
auto &bdi = globalBaseDeviceInfo;
// Start with detecting CPU vendor
uint32_t b = 0, c = 0, d = 0;
getCpuid(0, 0, &bdi.cpuMaxLevel, &b, &c, &d);
if (b == signature_INTEL_ebx && c == signature_INTEL_ecx && d == signature_INTEL_edx)
bdi.cpuVendor = CpuVendor::Intel;
else if (b == signature_AMD_ebx && c == signature_AMD_ecx && d == signature_AMD_edx)
bdi.cpuVendor = CpuVendor::AMD;
getCpuid(0x80000000, 0, &bdi.cpuMaxLevelExt);
bdi.cpuHasAvx2 = getCpuid(7, 0, nullptr, &b) && (b & CPUInfo::bit_AVX2) != 0;
// Only do extended model checking on Intel or when unsupported.
if (bdi.cpuVendor != CpuVendor::Intel || bdi.cpuMaxLevel < 1)
return;
// Detect CPU family and model
union {
CpuVersion fmt;
uint32_t raw;
} ver {};
getCpuid(1, 0, &ver.raw);
bdi.cpuFamily = ver.fmt.family;
if (bdi.cpuFamily == 15) bdi.cpuFamily += ver.fmt.extendedFamily;
bdi.cpuModel = ver.fmt.model;
if (bdi.cpuFamily == 15 || bdi.cpuFamily == 6)
bdi.cpuModel |= ver.fmt.extendedModel << 4;
bdi.cpuStepping = ver.fmt.stepping;
// Last but not least detect CPU generation
uint32_t generation = 0;
if (PE_parse_boot_argn(Configuration::bootargCpu, &generation, sizeof(generation))) {
DBGLOG("cpu", "found CPU generation override %u", generation);
if (generation < static_cast<uint32_t>(CPUInfo::CpuGeneration::MaxGeneration)) {
bdi.cpuGeneration = static_cast<CPUInfo::CpuGeneration>(generation);
return;
} else {
SYSLOG("cpu", "found invalid CPU generation override %u, falling back...", generation);
}
}
// Keep this mostly in sync to cpuid_set_cpufamily from osfmk/i386/cpuid.c
if (ver.fmt.family == 6) {
switch (bdi.cpuModel) {
case CPU_MODEL_PENRYN:
bdi.cpuGeneration = CpuGeneration::Penryn;
break;
case CPU_MODEL_NEHALEM:
case CPU_MODEL_FIELDS:
case CPU_MODEL_DALES:
case CPU_MODEL_NEHALEM_EX:
bdi.cpuGeneration = CpuGeneration::Nehalem;
break;
case CPU_MODEL_DALES_32NM:
case CPU_MODEL_WESTMERE:
case CPU_MODEL_WESTMERE_EX:
bdi.cpuGeneration = CpuGeneration::Westmere;
break;
case CPU_MODEL_SANDYBRIDGE:
case CPU_MODEL_JAKETOWN:
bdi.cpuGeneration = CpuGeneration::SandyBridge;
break;
case CPU_MODEL_IVYBRIDGE:
case CPU_MODEL_IVYBRIDGE_EP:
bdi.cpuGeneration = CpuGeneration::IvyBridge;
break;
case CPU_MODEL_HASWELL:
case CPU_MODEL_HASWELL_EP:
case CPU_MODEL_HASWELL_ULT:
case CPU_MODEL_CRYSTALWELL:
bdi.cpuGeneration = CpuGeneration::Haswell;
break;
case CPU_MODEL_BROADWELL:
case CPU_MODEL_BRYSTALWELL:
bdi.cpuGeneration = CpuGeneration::Broadwell;
break;
case CPU_MODEL_SKYLAKE:
case CPU_MODEL_SKYLAKE_DT:
case CPU_MODEL_SKYLAKE_W:
bdi.cpuGeneration = CpuGeneration::Skylake;
break;
case CPU_MODEL_KABYLAKE:
case CPU_MODEL_KABYLAKE_DT:
// Kaby has 0x9 stepping, and Coffee use 0xA / 0xB stepping.
if (ver.fmt.stepping == 9)
bdi.cpuGeneration = CpuGeneration::KabyLake;
else
bdi.cpuGeneration = CpuGeneration::CoffeeLake;
break;
case CPU_MODEL_CANNONLAKE:
bdi.cpuGeneration = CpuGeneration::CannonLake;
break;
case CPU_MODEL_ICELAKE_Y:
case CPU_MODEL_ICELAKE_U:
case CPU_MODEL_ICELAKE_SP:
bdi.cpuGeneration = CpuGeneration::IceLake;
break;
case CPU_MODEL_COMETLAKE_Y:
case CPU_MODEL_COMETLAKE_U:
bdi.cpuGeneration = CpuGeneration::CometLake;
break;
case CPU_MODEL_ROCKETLAKE_S:
bdi.cpuGeneration = CpuGeneration::RocketLake;
break;
case CPU_MODEL_TIGERLAKE_U:
bdi.cpuGeneration = CpuGeneration::TigerLake;
break;
default:
bdi.cpuGeneration = CpuGeneration::Unknown;
break;
}
}
}
CPUInfo::CpuGeneration CPUInfo::getGeneration(uint32_t *ofamily, uint32_t *omodel, uint32_t *ostepping) {
auto &bdi = BaseDeviceInfo::get();
if (ofamily) *ofamily = bdi.cpuFamily;
if (omodel) *omodel = bdi.cpuModel;
if (ostepping) *ostepping = bdi.cpuStepping;
return bdi.cpuGeneration;
}
bool CPUInfo::getCpuTopology(CpuTopology &topology) {
// Obtain power management callbacks
if (getKernelVersion() < KernelVersion::Lion) {
SYSLOG("cpu", "cannot use pmKextRegister before 10.7");
return false;
}
pmCallBacks_t callbacks {};
pmKextRegister(PM_DISPATCH_VERSION, nullptr, &callbacks);
if (!callbacks.GetPkgRoot) {
SYSLOG("cpu", "failed to obtain package root callback");
return false;
}
auto pkg = callbacks.GetPkgRoot();
if (!pkg) {
SYSLOG("cpu", "failed to obtain valid package root");
return false;
}
while (pkg) {
auto core = pkg->cores;
// Set physcal core mapping based on first virtual core
while (core) {
// I think lcpus could be null when the core is disabled and the topology is partially constructed
auto lcpu = core->lcpus;
if (lcpu) {
topology.numberToPackage[lcpu->cpu_num] = topology.packageCount;
topology.numberToPhysical[lcpu->cpu_num] = topology.physicalCount[topology.packageCount];
topology.numberToLogical[lcpu->cpu_num] = topology.logicalCount[topology.packageCount];
topology.physicalCount[topology.packageCount]++;
topology.logicalCount[topology.packageCount]++;
}
core = core->next_in_pkg;
}
// Set the rest of virtual core mapping
core = pkg->cores;
while (core) {
auto first_lcpu = core->lcpus;
auto lcpu = first_lcpu ? first_lcpu->next_in_core : nullptr;
while (lcpu) {
topology.numberToPackage[lcpu->cpu_num] = topology.packageCount;
topology.numberToPhysical[lcpu->cpu_num] = topology.numberToPhysical[first_lcpu->cpu_num];
topology.numberToLogical[lcpu->cpu_num] = topology.logicalCount[topology.packageCount];
topology.logicalCount[topology.packageCount]++;
lcpu = lcpu->next_in_core;
}
core = core->next_in_pkg;
}
topology.packageCount++;
pkg = pkg->next;
}
return true;
}
bool CPUInfo::getCpuid(uint32_t no, uint32_t count, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d) {
auto &bdi = BaseDeviceInfo::get();
uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;
bool supported = (no & 0x80000000) ? bdi.cpuMaxLevelExt >= no : bdi.cpuMaxLevel >= no;
// At least pass zeroes on failure
if (supported) {
asm ("xchgq %%rbx, %q1\n"
"cpuid\n"
"xchgq %%rbx, %q1"
: "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx)
: "0" (no), "2" (count));
}
if (a) *a = eax;
if (b) *b = ebx;
if (c) *c = ecx;
if (d) *d = edx;
return supported;
}
<|endoftext|>
|
<commit_before>/*
This file is part of:
NoahFrame
https://github.com/ketoo/NoahGameFrame
Copyright 2009 - 2020 NoahFrame(NoahGameFrame)
File creator: lvsheng.huang
NoahFrame is open-source software and you can redistribute it and/or modify
it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.
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 "NFInventoryModule.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"
#include "NFComm/NFMessageDefine/NFDefine.pb.h"
#include "NFComm/NFMessageDefine/NFMsgShare.pb.h"
bool NFInventoryModule::Init()
{
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
return true;
}
bool NFInventoryModule::Shut()
{
return true;
}
bool NFInventoryModule::Execute()
{
return true;
}
bool NFInventoryModule::AfterInit()
{
return true;
}
NFGUID NFInventoryModule::CreateEquip(const NFGUID& self, const std::string& strConfigName )
{
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return NULL_OBJECT;
}
bool bExist = m_pElementModule->ExistElement( strConfigName );
if ( !bExist )
{
m_pLogModule->LogError(self, "has no this element:" + strConfigName);
return NULL_OBJECT;
}
int nItemType = m_pElementModule->GetPropertyInt32(strConfigName, NFrame::Item::ItemType());
if ( NFMsg::EItemType::EIT_EQUIP != nItemType )
{
m_pLogModule->LogError(self, strConfigName + " has no this item type:" + std::to_string(nItemType));
return NULL_OBJECT;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::InventoryEquipment::ThisName() );
if (!pRecord)
{
return NULL_OBJECT;
}
NFGUID ident = m_pKernelModule->CreateGUID();
NF_SHARE_PTR<NFDataList> var = pRecord->GetInitData();
var->SetObject(NFrame::Player::InventoryEquipment::GUID, ident);
var->SetString(NFrame::Player::InventoryEquipment::ConfigID, strConfigName.c_str());
var->SetInt(NFrame::Player::InventoryEquipment::Date, pPluginManager->GetNowTime());
int nAddRow = pRecord->AddRow(-1, *var);
if (nAddRow > 0)
{
return pRecord->GetObject(nAddRow, NFrame::Player::InventoryEquipment::GUID);
}
return NULL_OBJECT;
}
bool NFInventoryModule::CreateItem(const NFGUID& self, const std::string& strConfigName, const int nCount)
{
if (nCount <= 0)
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return false;
}
bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strConfigName );
if ( !bExist )
{
m_pLogModule->LogError(self, "has no this element:" + strConfigName);
return false;
}
int nItemType = m_pElementModule->GetPropertyInt32(strConfigName, NFrame::Item::ItemType());
if ( NFMsg::EItemType::EIT_EQUIP == nItemType )
{
CreateEquip(self, strConfigName);
return false;
}
const int nSceneID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::SceneID());
NFMsg::ESceneType eSceneType = (NFMsg::ESceneType)m_pElementModule->GetPropertyInt32(std::to_string(nSceneID), NFrame::Scene::Type());
return CreateItemInNormalBag(self, strConfigName, nCount);
}
bool NFInventoryModule::DeleteEquip(const NFGUID& self, const NFGUID& id )
{
if (id.IsNull())
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if (nullptr == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::InventoryEquipment::ThisName() );
if (nullptr == pRecord)
{
return false;
}
NFDataList varFindResult;
int nFindRowCount = pRecord->FindObject(NFrame::Player::InventoryEquipment::GUID, id, varFindResult);
if (nFindRowCount > 0)
{
//int nTotalCount = 0;
for (int i = 0; i < varFindResult.GetCount(); ++i)
{
int nFindRow = varFindResult.Int32(i);
pRecord->Remove(nFindRow);
}
}
return true;
}
bool NFInventoryModule::DeleteItem(const NFGUID& self, const std::string& strItemConfigID, const int nCount )
{
if(nCount <= 0)
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return false;
}
if (!m_pElementModule->ExistElement(NFrame::Item::ThisName(), strItemConfigID))
{
m_pLogModule->LogError(self, "has no this element:" + strItemConfigID);
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::Inventory::ThisName() );
if (!pRecord)
{
return false;
}
int nFindRow = pRecord->FindString(NFrame::Player::Inventory::ConfigID, strItemConfigID);
if (nFindRow > 0)
{
int nOldCount = pRecord->GetInt32(nFindRow, NFrame::Player::Inventory::ItemCount);
if (nOldCount > nCount)
{
int nNewCount = nOldCount - nCount;
pRecord->SetInt(nFindRow, NFrame::Player::Inventory::ItemCount, nNewCount);
m_pLogModule->LogInfo(self, " DeleteItem:" + strItemConfigID + ", from " + std::to_string(nOldCount) + " to " + std::to_string(nNewCount));
}
else if (nOldCount == nCount)
{
pRecord->Remove(nFindRow);
m_pLogModule->LogInfo(self, " DeleteItem:" + strItemConfigID + ", from " + std::to_string(nOldCount) + " to 0");
}
}
return false;
}
bool NFInventoryModule::EnoughItem(const NFGUID& self, const std::string& strItemConfigID, const int nCount )
{
if(nCount <= 0)
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return false;
}
bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strItemConfigID );
if ( !bExist )
{
m_pLogModule->LogError(self, "has no this element:" + strItemConfigID);
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::Inventory::ThisName() );
if (!pRecord)
{
return false;
}
int row = pRecord->FindString(NFrame::Player::Inventory::ConfigID, strItemConfigID);
if (row >= 0)
{
int count = pRecord->GetInt32(row, NFrame::Player::Inventory::ItemCount);
if (count >= nCount)
{
return true;
}
}
return false;
}
bool NFInventoryModule::CreateItemInNormalBag(const NFGUID & self, const std::string & strConfigName, const int nCount)
{
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, NFrame::Player::Inventory::ThisName());
if (nullptr == pRecord)
{
return false;
}
int row = pRecord->FindString(NFrame::Player::Inventory::ConfigID, strConfigName);
if (row < 0)
{
NF_SHARE_PTR<NFDataList> xRowData = pRecord->GetInitData();
xRowData->SetString(NFrame::Player::Inventory::ConfigID, strConfigName);
xRowData->SetInt(NFrame::Player::Inventory::ItemCount, nCount);
int row = pRecord->AddRow(-1, *xRowData);
if (row < 0)
{
m_pLogModule->LogError(self, " cant add item to bag " + strConfigName);
return false;
}
}
else
{
int count = pRecord->GetInt32(row, NFrame::Player::Inventory::ItemCount) + nCount;
pRecord->SetInt(row, NFrame::Player::Inventory::ItemCount, count);
}
m_pLogModule->LogInfo(self, "add item to bag:" + strConfigName + ", count:" + std::to_string(nCount));
return true;
}<commit_msg>fix bug<commit_after>/*
This file is part of:
NoahFrame
https://github.com/ketoo/NoahGameFrame
Copyright 2009 - 2020 NoahFrame(NoahGameFrame)
File creator: lvsheng.huang
NoahFrame is open-source software and you can redistribute it and/or modify
it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.
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 "NFInventoryModule.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"
#include "NFComm/NFMessageDefine/NFDefine.pb.h"
#include "NFComm/NFMessageDefine/NFMsgShare.pb.h"
bool NFInventoryModule::Init()
{
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
return true;
}
bool NFInventoryModule::Shut()
{
return true;
}
bool NFInventoryModule::Execute()
{
return true;
}
bool NFInventoryModule::AfterInit()
{
return true;
}
NFGUID NFInventoryModule::CreateEquip(const NFGUID& self, const std::string& strConfigName )
{
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return NULL_OBJECT;
}
bool bExist = m_pElementModule->ExistElement( strConfigName );
if ( !bExist )
{
m_pLogModule->LogError(self, "has no this element:" + strConfigName);
return NULL_OBJECT;
}
int nItemType = m_pElementModule->GetPropertyInt32(strConfigName, NFrame::Item::ItemType());
if ( NFMsg::EItemType::EIT_EQUIP != nItemType )
{
m_pLogModule->LogError(self, strConfigName + " has no this item type:" + std::to_string(nItemType));
return NULL_OBJECT;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::InventoryEquipment::ThisName() );
if (!pRecord)
{
return NULL_OBJECT;
}
NFGUID ident = m_pKernelModule->CreateGUID();
NF_SHARE_PTR<NFDataList> var = pRecord->GetInitData();
var->SetObject(NFrame::Player::InventoryEquipment::GUID, ident);
var->SetString(NFrame::Player::InventoryEquipment::ConfigID, strConfigName.c_str());
var->SetInt(NFrame::Player::InventoryEquipment::Date, pPluginManager->GetNowTime());
int nAddRow = pRecord->AddRow(-1, *var);
if (nAddRow > 0)
{
return pRecord->GetObject(nAddRow, NFrame::Player::InventoryEquipment::GUID);
}
return NULL_OBJECT;
}
bool NFInventoryModule::CreateItem(const NFGUID& self, const std::string& strConfigName, const int nCount)
{
if (nCount <= 0)
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return false;
}
bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strConfigName );
if ( !bExist )
{
m_pLogModule->LogError(self, "has no this element:" + strConfigName);
return false;
}
int nItemType = m_pElementModule->GetPropertyInt32(strConfigName, NFrame::Item::ItemType());
if ( NFMsg::EItemType::EIT_EQUIP == nItemType )
{
CreateEquip(self, strConfigName);
return false;
}
const int nSceneID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::SceneID());
NFMsg::ESceneType eSceneType = (NFMsg::ESceneType)m_pElementModule->GetPropertyInt32(std::to_string(nSceneID), NFrame::Scene::Type());
return CreateItemInNormalBag(self, strConfigName, nCount);
}
bool NFInventoryModule::DeleteEquip(const NFGUID& self, const NFGUID& id )
{
if (id.IsNull())
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if (nullptr == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::InventoryEquipment::ThisName() );
if (nullptr == pRecord)
{
return false;
}
NFDataList varFindResult;
int nFindRowCount = pRecord->FindObject(NFrame::Player::InventoryEquipment::GUID, id, varFindResult);
if (nFindRowCount > 0)
{
//int nTotalCount = 0;
for (int i = 0; i < varFindResult.GetCount(); ++i)
{
int nFindRow = varFindResult.Int32(i);
pRecord->Remove(nFindRow);
}
}
return true;
}
bool NFInventoryModule::DeleteItem(const NFGUID& self, const std::string& strItemConfigID, const int nCount )
{
if(nCount <= 0)
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return false;
}
if (!m_pElementModule->ExistElement(NFrame::Item::ThisName(), strItemConfigID))
{
m_pLogModule->LogError(self, "has no this element:" + strItemConfigID);
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::Inventory::ThisName() );
if (!pRecord)
{
return false;
}
int nFindRow = pRecord->FindString(NFrame::Player::Inventory::ConfigID, strItemConfigID);
if (nFindRow > 0)
{
int nOldCount = pRecord->GetInt32(nFindRow, NFrame::Player::Inventory::ItemCount);
if (nOldCount > nCount)
{
int nNewCount = nOldCount - nCount;
pRecord->SetInt(nFindRow, NFrame::Player::Inventory::ItemCount, nNewCount);
m_pLogModule->LogInfo(self, " DeleteItem:" + strItemConfigID + ", from " + std::to_string(nOldCount) + " to " + std::to_string(nNewCount));
return true;
}
else if (nOldCount == nCount)
{
pRecord->Remove(nFindRow);
m_pLogModule->LogInfo(self, " DeleteItem:" + strItemConfigID + ", from " + std::to_string(nOldCount) + " to 0");
return true;
}
}
return false;
}
bool NFInventoryModule::EnoughItem(const NFGUID& self, const std::string& strItemConfigID, const int nCount )
{
if(nCount <= 0)
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject( self );
if ( NULL == pObject )
{
return false;
}
bool bExist = m_pElementModule->ExistElement(NFrame::Item::ThisName(), strItemConfigID );
if ( !bExist )
{
m_pLogModule->LogError(self, "has no this element:" + strItemConfigID);
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement( NFrame::Player::Inventory::ThisName() );
if (!pRecord)
{
return false;
}
int row = pRecord->FindString(NFrame::Player::Inventory::ConfigID, strItemConfigID);
if (row >= 0)
{
int count = pRecord->GetInt32(row, NFrame::Player::Inventory::ItemCount);
if (count >= nCount)
{
return true;
}
}
return false;
}
bool NFInventoryModule::CreateItemInNormalBag(const NFGUID & self, const std::string & strConfigName, const int nCount)
{
NF_SHARE_PTR<NFIRecord> pRecord = m_pKernelModule->FindRecord(self, NFrame::Player::Inventory::ThisName());
if (nullptr == pRecord)
{
return false;
}
int row = pRecord->FindString(NFrame::Player::Inventory::ConfigID, strConfigName);
if (row < 0)
{
NF_SHARE_PTR<NFDataList> xRowData = pRecord->GetInitData();
xRowData->SetString(NFrame::Player::Inventory::ConfigID, strConfigName);
xRowData->SetInt(NFrame::Player::Inventory::ItemCount, nCount);
int row = pRecord->AddRow(-1, *xRowData);
if (row < 0)
{
m_pLogModule->LogError(self, " cant add item to bag " + strConfigName);
return false;
}
}
else
{
int count = pRecord->GetInt32(row, NFrame::Player::Inventory::ItemCount) + nCount;
pRecord->SetInt(row, NFrame::Player::Inventory::ItemCount, count);
}
m_pLogModule->LogInfo(self, "add item to bag:" + strConfigName + ", count:" + std::to_string(nCount));
return true;
}<|endoftext|>
|
<commit_before>/*
This file is part of KAddressbook.
Copyright (c) 2000 Cornelius Schumacher <schumacher@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) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlayout.h>
#include <kaboutdata.h>
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <klocale.h>
#include <kparts/genericfactory.h>
#include "actionmanager.h"
#include "kaddressbook.h"
#include "kaddressbookiface.h"
#include "kaddressbooktableview.h"
#include "viewmanager.h"
#include "kaddressbook_part.h"
typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory;
K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory );
KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName,
QObject *parent, const char *name,
const QStringList & )
: KParts::ReadOnlyPart( parent, name ), DCOPObject( "KAddressBookIface" )
{
kdDebug(5720) << "KAddressbookPart()" << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
setInstance( KAddressbookFactory::instance() );
kdDebug(5720) << "KAddressbookPart()..." << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
// create a canvas to insert our widget
QWidget *canvas = new QWidget( parentWidget, widgetName );
canvas->setFocusPolicy( QWidget::ClickFocus );
setWidget( canvas );
mExtension = new KAddressbookBrowserExtension( this );
QVBoxLayout *topLayout = new QVBoxLayout( canvas );
KGlobal::iconLoader()->addAppDir( "kaddressbook" );
mWidget = new KAddressBook( canvas );
mWidget->readConfig();
topLayout->addWidget( mWidget );
mWidget->viewManager()->setActiveExtension( 0 );
mWidget->show();
mActionManager = new ActionManager( this, mWidget, false, this );
setXMLFile( "kaddressbook_part.rc" );
}
KAddressbookPart::~KAddressbookPart()
{
closeURL();
}
KAboutData *KAddressbookPart::createAboutData()
{
KAboutData *about = new KAboutData( "kaddressbook", I18N_NOOP( "KAddressBook" ),
"3.1", I18N_NOOP( "The KDE Address Book" ),
KAboutData::License_BSD,
I18N_NOOP( "(c) 1997-2002, The KDE PIM Team" ) );
about->addAuthor( "Tobias Koenig", I18N_NOOP( "Current maintainer" ), "tokoe@kde.org" );
about->addAuthor( "Don Sanders", I18N_NOOP( "Original author" ) );
about->addAuthor( "Cornelius Schumacher",
I18N_NOOP( "Co-maintainer, libkabc port, csv import/export" ),
"schumacher@kde.org" );
about->addAuthor( "Mike Pilone", I18N_NOOP( "GUI and framework redesign" ),
"mpilone@slac.com" );
about->addAuthor( "Greg Stern", I18N_NOOP( "DCOP interface" ) );
about->addAuthor( "Mark Westcott", I18N_NOOP( "Contact pinning" ) );
about->addAuthor( "Mischel Boyer de la Giroday", I18N_NOOP( "LDAP Lookup" ),
"michel@klaralvdalens-datakonsult.se" );
about->addAuthor( "Steffen Hansen", I18N_NOOP( "LDAP Lookup" ),
"hansen@kde.org" );
return about;
}
void KAddressbookPart::addEmail( QString addr )
{
mWidget->addEmail( addr );
}
ASYNC KAddressbookPart::showContactEditor( QString uid )
{
mWidget->showContactEditor( uid );
}
void KAddressbookPart::newContact()
{
mWidget->newContact();
}
QString KAddressbookPart::getNameByPhone( QString phone )
{
return mWidget->getNameByPhone( phone );
}
void KAddressbookPart::save()
{
mWidget->save();
}
void KAddressbookPart::exit()
{
delete this;
}
void KAddressbookPart::updateEditMenu()
{
}
bool KAddressbookPart::openFile()
{
kdDebug(5720) << "KAddressbookPart:openFile()" << endl;
mWidget->show();
return true;
}
void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e )
{
kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl;
KParts::ReadOnlyPart::guiActivateEvent( e );
mActionManager->initActionViewList();
}
KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent )
: KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" )
{
}
KAddressbookBrowserExtension::~KAddressbookBrowserExtension()
{
}
using namespace KParts;
#include "kaddressbook_part.moc"
<commit_msg>Fix incorrect CSV acronym<commit_after>/*
This file is part of KAddressbook.
Copyright (c) 2000 Cornelius Schumacher <schumacher@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) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlayout.h>
#include <kaboutdata.h>
#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <klocale.h>
#include <kparts/genericfactory.h>
#include "actionmanager.h"
#include "kaddressbook.h"
#include "kaddressbookiface.h"
#include "kaddressbooktableview.h"
#include "viewmanager.h"
#include "kaddressbook_part.h"
typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory;
K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory );
KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName,
QObject *parent, const char *name,
const QStringList & )
: KParts::ReadOnlyPart( parent, name ), DCOPObject( "KAddressBookIface" )
{
kdDebug(5720) << "KAddressbookPart()" << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
setInstance( KAddressbookFactory::instance() );
kdDebug(5720) << "KAddressbookPart()..." << endl;
kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl;
// create a canvas to insert our widget
QWidget *canvas = new QWidget( parentWidget, widgetName );
canvas->setFocusPolicy( QWidget::ClickFocus );
setWidget( canvas );
mExtension = new KAddressbookBrowserExtension( this );
QVBoxLayout *topLayout = new QVBoxLayout( canvas );
KGlobal::iconLoader()->addAppDir( "kaddressbook" );
mWidget = new KAddressBook( canvas );
mWidget->readConfig();
topLayout->addWidget( mWidget );
mWidget->viewManager()->setActiveExtension( 0 );
mWidget->show();
mActionManager = new ActionManager( this, mWidget, false, this );
setXMLFile( "kaddressbook_part.rc" );
}
KAddressbookPart::~KAddressbookPart()
{
closeURL();
}
KAboutData *KAddressbookPart::createAboutData()
{
KAboutData *about = new KAboutData( "kaddressbook", I18N_NOOP( "KAddressBook" ),
"3.1", I18N_NOOP( "The KDE Address Book" ),
KAboutData::License_BSD,
I18N_NOOP( "(c) 1997-2002, The KDE PIM Team" ) );
about->addAuthor( "Tobias Koenig", I18N_NOOP( "Current maintainer" ), "tokoe@kde.org" );
about->addAuthor( "Don Sanders", I18N_NOOP( "Original author" ) );
about->addAuthor( "Cornelius Schumacher",
I18N_NOOP( "Co-maintainer, libkabc port, CSV import/export" ),
"schumacher@kde.org" );
about->addAuthor( "Mike Pilone", I18N_NOOP( "GUI and framework redesign" ),
"mpilone@slac.com" );
about->addAuthor( "Greg Stern", I18N_NOOP( "DCOP interface" ) );
about->addAuthor( "Mark Westcott", I18N_NOOP( "Contact pinning" ) );
about->addAuthor( "Mischel Boyer de la Giroday", I18N_NOOP( "LDAP Lookup" ),
"michel@klaralvdalens-datakonsult.se" );
about->addAuthor( "Steffen Hansen", I18N_NOOP( "LDAP Lookup" ),
"hansen@kde.org" );
return about;
}
void KAddressbookPart::addEmail( QString addr )
{
mWidget->addEmail( addr );
}
ASYNC KAddressbookPart::showContactEditor( QString uid )
{
mWidget->showContactEditor( uid );
}
void KAddressbookPart::newContact()
{
mWidget->newContact();
}
QString KAddressbookPart::getNameByPhone( QString phone )
{
return mWidget->getNameByPhone( phone );
}
void KAddressbookPart::save()
{
mWidget->save();
}
void KAddressbookPart::exit()
{
delete this;
}
void KAddressbookPart::updateEditMenu()
{
}
bool KAddressbookPart::openFile()
{
kdDebug(5720) << "KAddressbookPart:openFile()" << endl;
mWidget->show();
return true;
}
void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e )
{
kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl;
KParts::ReadOnlyPart::guiActivateEvent( e );
mActionManager->initActionViewList();
}
KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent )
: KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" )
{
}
KAddressbookBrowserExtension::~KAddressbookBrowserExtension()
{
}
using namespace KParts;
#include "kaddressbook_part.moc"
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkImageDataItem.h"
#include <vtkImageData.h>
#include <vtkPointData.h>
#include <vtkBitArray.h>
#include <vtkCharArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkIntArray.h>
#include <vtkLongArray.h>
#include <vtkShortArray.h>
#include <vtkUnsignedCharArray.h>
#include <vtkUnsignedIntArray.h>
#include <vtkUnsignedLongArray.h>
#include <vtkUnsignedShortArray.h>
#include "ipFunc/ipFunc.h"
mitk::ImageDataItem::ImageDataItem(const ImageDataItem& aParent, unsigned int dimension, void *data, bool manageMemory, size_t offset) :
m_Data(NULL), m_ManageMemory(false), m_PicDescriptor(NULL), m_VtkImageData(NULL), m_Offset(offset), m_IsComplete(false),
m_Parent(&aParent)
{
m_PixelType = aParent.GetPixelType();
m_PicDescriptor=ipPicNew();
m_PicDescriptor->bpe=m_PixelType.GetBpe();
m_PicDescriptor->type=m_PixelType.GetType();
m_PicDescriptor->dim=dimension;
memcpy(m_PicDescriptor->n, aParent.GetPicDescriptor()->n, sizeof(unsigned int)*(dimension<=8?dimension:8));
m_PicDescriptor->data=m_Data=static_cast<unsigned char*>(aParent.GetData())+offset;
ipFuncCopyTags(m_PicDescriptor, aParent.GetPicDescriptor());
if(data != NULL)
{
memcpy(m_Data, data, _ipPicSize(m_PicDescriptor));
if(manageMemory)
{
delete data;
}
}
m_ReferenceCountLock.Lock();
m_ReferenceCount = 0;
m_ReferenceCountLock.Unlock();
}
mitk::ImageDataItem::~ImageDataItem()
{
if(m_VtkImageData!=NULL)
m_VtkImageData->Delete();
if(m_PicDescriptor!=NULL)
{
m_PicDescriptor->data=NULL;
ipPicFree(m_PicDescriptor);
}
if(m_Parent.IsNull())
{
if(m_ManageMemory)
delete m_Data;
}
}
mitk::ImageDataItem::ImageDataItem(const mitk::PixelType& type, unsigned int dimension, unsigned int *dimensions, void *data, bool manageMemory) :
m_Data((unsigned char*)data), m_ManageMemory(manageMemory), m_PicDescriptor(NULL), m_VtkImageData(NULL), m_Offset(0), m_IsComplete(false),
m_Parent(NULL)
{
//const std::type_info & typeId=*type.GetTypeId();
m_PixelType = type;
m_PicDescriptor=ipPicNew();
m_PicDescriptor->bpe=m_PixelType.GetBpe();
m_PicDescriptor->type=m_PixelType.GetType();
m_PicDescriptor->dim=dimension;
memcpy(m_PicDescriptor->n, dimensions, sizeof(unsigned int)*(dimension<=8?dimension:8));
if(m_Data == NULL)
{
m_Data=new unsigned char[_ipPicSize(m_PicDescriptor)];
m_ManageMemory = true;
}
m_PicDescriptor->data=m_Data;
m_ReferenceCountLock.Lock();
m_ReferenceCount = 0;
m_ReferenceCountLock.Unlock();
}
void mitk::ImageDataItem::ConstructVtkImageData() const
{
vtkImageData *inData = vtkImageData::New();
vtkDataArray *scalars = NULL;
inData->SetNumberOfScalarComponents(m_PixelType.GetNumberOfComponents());
unsigned long size = 0;
if ( m_PicDescriptor->dim == 1 )
{
inData->SetDimensions( m_PicDescriptor->n[0] -1, 1, 1);
size = m_PicDescriptor->n[0];
inData->SetOrigin( ((float) m_PicDescriptor->n[0]) / 2.0f, 0, 0 );
}
else
if ( m_PicDescriptor->dim == 2 )
{
inData->SetDimensions( m_PicDescriptor->n[0] , m_PicDescriptor->n[1] , 1 );
size = m_PicDescriptor->n[0] * m_PicDescriptor->n[1];
inData->SetOrigin( ((float) m_PicDescriptor->n[0]) / 2.0f, ((float) m_PicDescriptor->n[1]) / 2.0f, 0 );
}
else
if ( m_PicDescriptor->dim >= 3 )
{
inData->SetDimensions( m_PicDescriptor->n[0], m_PicDescriptor->n[1], m_PicDescriptor->n[2] );
size = m_PicDescriptor->n[0] * m_PicDescriptor->n[1] * m_PicDescriptor->n[2];
// Test
//inData->SetOrigin( (float) m_PicDescriptor->n[0] / 2.0f, (float) m_PicDescriptor->n[1] / 2.0f, (float) m_PicDescriptor->n[2] / 2.0f );
inData->SetOrigin( 0, 0, 0 );
}
else
{
inData->Delete () ;
return;
}
if ( ( m_PixelType.GetType() == ipPicInt || m_PixelType.GetType() == ipPicUInt ) && m_PixelType.GetBitsPerComponent() == 1 )
{
inData->SetScalarType( VTK_BIT );
scalars = vtkBitArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 8 )
{
inData->SetScalarType( VTK_CHAR );
scalars = vtkCharArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 8 )
{
inData->SetScalarType( VTK_UNSIGNED_CHAR );
scalars = vtkUnsignedCharArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 16 )
{
inData->SetScalarType( VTK_SHORT );
scalars = vtkShortArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 16 )
{
inData->SetScalarType( VTK_UNSIGNED_SHORT );
scalars = vtkUnsignedShortArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 32 )
{
inData->SetScalarType( VTK_INT );
scalars = vtkIntArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 32 )
{
inData->SetScalarType( VTK_UNSIGNED_INT );
scalars = vtkUnsignedIntArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 64 )
{
inData->SetScalarType( VTK_LONG );
scalars = vtkLongArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 64 )
{
inData->SetScalarType( VTK_UNSIGNED_LONG );
scalars = vtkUnsignedLongArray::New();
}
else if ( m_PixelType.GetType() == ipPicFloat && m_PixelType.GetBitsPerComponent() == 32 )
{
inData->SetScalarType( VTK_FLOAT );
scalars = vtkFloatArray::New();
}
else if ( m_PixelType.GetType() == ipPicFloat && m_PixelType.GetBitsPerComponent() == 64 )
{
inData->SetScalarType( VTK_DOUBLE );
scalars = vtkDoubleArray::New();
}
else
{
inData->Delete();
return;
}
m_VtkImageData = inData;
// allocate the new scalars
scalars->SetNumberOfComponents(m_VtkImageData->GetNumberOfScalarComponents());
scalars->SetVoidArray(m_PicDescriptor->data, _ipPicElements(m_PicDescriptor), 1);
m_VtkImageData->GetPointData()->SetScalars(scalars);
scalars->Delete();
}
void mitk::ImageDataItem::Modified() const
{
if(m_VtkImageData)
m_VtkImageData->Modified();
}
<commit_msg>FIX: warnings; delete issue<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkImageDataItem.h"
#include <vtkImageData.h>
#include <vtkPointData.h>
#include <vtkBitArray.h>
#include <vtkCharArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkIntArray.h>
#include <vtkLongArray.h>
#include <vtkShortArray.h>
#include <vtkUnsignedCharArray.h>
#include <vtkUnsignedIntArray.h>
#include <vtkUnsignedLongArray.h>
#include <vtkUnsignedShortArray.h>
#include "ipFunc/ipFunc.h"
mitk::ImageDataItem::ImageDataItem(const ImageDataItem& aParent, unsigned int dimension, void *data, bool manageMemory, size_t offset) :
m_Data(NULL), m_ManageMemory(false), m_PicDescriptor(NULL), m_VtkImageData(NULL), m_Offset(offset), m_IsComplete(false),
m_Parent(&aParent)
{
m_PixelType = aParent.GetPixelType();
m_PicDescriptor=ipPicNew();
m_PicDescriptor->bpe=m_PixelType.GetBpe();
m_PicDescriptor->type=m_PixelType.GetType();
m_PicDescriptor->dim=dimension;
memcpy(m_PicDescriptor->n, aParent.GetPicDescriptor()->n, sizeof(unsigned int)*(dimension<=8?dimension:8));
m_PicDescriptor->data=m_Data=static_cast<unsigned char*>(aParent.GetData())+offset;
ipFuncCopyTags(m_PicDescriptor, aParent.GetPicDescriptor());
if(data != NULL)
{
memcpy(m_Data, data, _ipPicSize(m_PicDescriptor));
if(manageMemory)
{
delete [] (unsigned char*) data;
}
}
m_ReferenceCountLock.Lock();
m_ReferenceCount = 0;
m_ReferenceCountLock.Unlock();
}
mitk::ImageDataItem::~ImageDataItem()
{
if(m_VtkImageData!=NULL)
m_VtkImageData->Delete();
if(m_PicDescriptor!=NULL)
{
m_PicDescriptor->data=NULL;
ipPicFree(m_PicDescriptor);
}
if(m_Parent.IsNull())
{
if(m_ManageMemory)
delete [] m_Data;
}
}
mitk::ImageDataItem::ImageDataItem(const mitk::PixelType& type, unsigned int dimension, unsigned int *dimensions, void *data, bool manageMemory) :
m_Data((unsigned char*)data), m_ManageMemory(manageMemory), m_PicDescriptor(NULL), m_VtkImageData(NULL), m_Offset(0), m_IsComplete(false),
m_Parent(NULL)
{
//const std::type_info & typeId=*type.GetTypeId();
m_PixelType = type;
m_PicDescriptor=ipPicNew();
m_PicDescriptor->bpe=m_PixelType.GetBpe();
m_PicDescriptor->type=m_PixelType.GetType();
m_PicDescriptor->dim=dimension;
memcpy(m_PicDescriptor->n, dimensions, sizeof(unsigned int)*(dimension<=8?dimension:8));
if(m_Data == NULL)
{
m_Data=new unsigned char[_ipPicSize(m_PicDescriptor)];
m_ManageMemory = true;
}
m_PicDescriptor->data=m_Data;
m_ReferenceCountLock.Lock();
m_ReferenceCount = 0;
m_ReferenceCountLock.Unlock();
}
void mitk::ImageDataItem::ConstructVtkImageData() const
{
vtkImageData *inData = vtkImageData::New();
vtkDataArray *scalars = NULL;
inData->SetNumberOfScalarComponents(m_PixelType.GetNumberOfComponents());
unsigned long size = 0;
if ( m_PicDescriptor->dim == 1 )
{
inData->SetDimensions( m_PicDescriptor->n[0] -1, 1, 1);
size = m_PicDescriptor->n[0];
inData->SetOrigin( ((float) m_PicDescriptor->n[0]) / 2.0f, 0, 0 );
}
else
if ( m_PicDescriptor->dim == 2 )
{
inData->SetDimensions( m_PicDescriptor->n[0] , m_PicDescriptor->n[1] , 1 );
size = m_PicDescriptor->n[0] * m_PicDescriptor->n[1];
inData->SetOrigin( ((float) m_PicDescriptor->n[0]) / 2.0f, ((float) m_PicDescriptor->n[1]) / 2.0f, 0 );
}
else
if ( m_PicDescriptor->dim >= 3 )
{
inData->SetDimensions( m_PicDescriptor->n[0], m_PicDescriptor->n[1], m_PicDescriptor->n[2] );
size = m_PicDescriptor->n[0] * m_PicDescriptor->n[1] * m_PicDescriptor->n[2];
// Test
//inData->SetOrigin( (float) m_PicDescriptor->n[0] / 2.0f, (float) m_PicDescriptor->n[1] / 2.0f, (float) m_PicDescriptor->n[2] / 2.0f );
inData->SetOrigin( 0, 0, 0 );
}
else
{
inData->Delete () ;
return;
}
if ( ( m_PixelType.GetType() == ipPicInt || m_PixelType.GetType() == ipPicUInt ) && m_PixelType.GetBitsPerComponent() == 1 )
{
inData->SetScalarType( VTK_BIT );
scalars = vtkBitArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 8 )
{
inData->SetScalarType( VTK_CHAR );
scalars = vtkCharArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 8 )
{
inData->SetScalarType( VTK_UNSIGNED_CHAR );
scalars = vtkUnsignedCharArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 16 )
{
inData->SetScalarType( VTK_SHORT );
scalars = vtkShortArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 16 )
{
inData->SetScalarType( VTK_UNSIGNED_SHORT );
scalars = vtkUnsignedShortArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 32 )
{
inData->SetScalarType( VTK_INT );
scalars = vtkIntArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 32 )
{
inData->SetScalarType( VTK_UNSIGNED_INT );
scalars = vtkUnsignedIntArray::New();
}
else if ( m_PixelType.GetType() == ipPicInt && m_PixelType.GetBitsPerComponent() == 64 )
{
inData->SetScalarType( VTK_LONG );
scalars = vtkLongArray::New();
}
else if ( m_PixelType.GetType() == ipPicUInt && m_PixelType.GetBitsPerComponent() == 64 )
{
inData->SetScalarType( VTK_UNSIGNED_LONG );
scalars = vtkUnsignedLongArray::New();
}
else if ( m_PixelType.GetType() == ipPicFloat && m_PixelType.GetBitsPerComponent() == 32 )
{
inData->SetScalarType( VTK_FLOAT );
scalars = vtkFloatArray::New();
}
else if ( m_PixelType.GetType() == ipPicFloat && m_PixelType.GetBitsPerComponent() == 64 )
{
inData->SetScalarType( VTK_DOUBLE );
scalars = vtkDoubleArray::New();
}
else
{
inData->Delete();
return;
}
m_VtkImageData = inData;
// allocate the new scalars
scalars->SetNumberOfComponents(m_VtkImageData->GetNumberOfScalarComponents());
scalars->SetVoidArray(m_PicDescriptor->data, _ipPicElements(m_PicDescriptor), 1);
m_VtkImageData->GetPointData()->SetScalars(scalars);
scalars->Delete();
}
void mitk::ImageDataItem::Modified() const
{
if(m_VtkImageData)
m_VtkImageData->Modified();
}
<|endoftext|>
|
<commit_before><commit_msg>PWGGA/GammaConv: Fixed event cut for some pPb8TeV configs<commit_after><|endoftext|>
|
<commit_before>#include "PlaneGeometry.h"
//##ModelId=3E395F22035A
mitk::PlaneGeometry::PlaneGeometry() : Geometry2D(10.0, 10.0), m_ScaleFactorMMPerUnitX(1.0), m_ScaleFactorMMPerUnitY(1.0)
{
}
//##ModelId=3E395F220382
mitk::PlaneGeometry::~PlaneGeometry()
{
}
//##ModelId=3E395E3E0077
const mitk::PlaneView& mitk::PlaneGeometry::GetPlaneView() const
{
return m_PlaneView;
}
//##ModelId=3E396ABE0385
void mitk::PlaneGeometry::SetPlaneView(const mitk::PlaneView& aPlaneView)
{
m_PlaneView=aPlaneView;
m_ScaleFactorMMPerUnitX=m_PlaneView.getOrientation1().length()/m_WidthInUnits;
m_ScaleFactorMMPerUnitY=m_PlaneView.getOrientation2().length()/m_HeightInUnits;
Modified();
}
//##ModelId=3E3AEB7C001C
itk::Transform<float,3,2>::Pointer mitk::PlaneGeometry::GetTransfrom() const
{
itkExceptionMacro("Transform not yet supported.");
return NULL;
}
//##ModelId=3E3B9C6E02B5
void mitk::PlaneGeometry::Map(const mitk::Point3D &pt3d_mm, mitk::Point2D &pt2d_mm) const
{
m_PlaneView.map(pt3d_mm, pt2d_mm);
}
//##ModelId=3E3B9C7101BF
void mitk::PlaneGeometry::Map(const mitk::Point2D &pt2d_mm, mitk::Point3D &pt3d_mm) const
{
m_PlaneView.map(pt2d_mm, pt3d_mm);
}
//##ModelId=3E3B9C730262
void mitk::PlaneGeometry::UnitsToMM(const mitk::Point2D &pt_units, mitk::Point2D &pt_mm) const
{
pt_mm.x=m_ScaleFactorMMPerUnitX*pt_units.x;
pt_mm.y=m_ScaleFactorMMPerUnitY*pt_units.y;
}
//##ModelId=3E3B9C760112
void mitk::PlaneGeometry::MMToUnits(const mitk::Point2D &pt_mm, mitk::Point2D &pt_units) const
{
pt_units.x=pt_mm.x*(1.0/m_ScaleFactorMMPerUnitX);
pt_units.y=pt_mm.y*(1.0/m_ScaleFactorMMPerUnitY);
}
//##ModelId=3E3B9C8C0145
void mitk::PlaneGeometry::UnitsToMM(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const
{
vec_mm.x=m_ScaleFactorMMPerUnitX*vec_units.x;
vec_mm.y=m_ScaleFactorMMPerUnitY*vec_units.y;
}
//##ModelId=3E3B9C8E0152
void mitk::PlaneGeometry::MMToUnits(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const
{
vec_units.x=vec_mm.x*(1.0/m_ScaleFactorMMPerUnitX);
vec_units.y=vec_mm.y*(1.0/m_ScaleFactorMMPerUnitY);
}
<commit_msg>fixed size initialization in SetPlaneView()<commit_after>#include "PlaneGeometry.h"
//##ModelId=3E395F22035A
mitk::PlaneGeometry::PlaneGeometry() : Geometry2D(10.0, 10.0), m_ScaleFactorMMPerUnitX(1.0), m_ScaleFactorMMPerUnitY(1.0)
{
}
//##ModelId=3E395F220382
mitk::PlaneGeometry::~PlaneGeometry()
{
}
//##ModelId=3E395E3E0077
const mitk::PlaneView& mitk::PlaneGeometry::GetPlaneView() const
{
return m_PlaneView;
}
//##ModelId=3E396ABE0385
void mitk::PlaneGeometry::SetPlaneView(const mitk::PlaneView& aPlaneView)
{
m_PlaneView=aPlaneView;
m_WidthInUnits = m_PlaneView.getOrientation1().length();
m_HeightInUnits = m_PlaneView.getOrientation2().length();
m_ScaleFactorMMPerUnitX=m_PlaneView.getOrientation1().length()/m_WidthInUnits;
m_ScaleFactorMMPerUnitY=m_PlaneView.getOrientation2().length()/m_HeightInUnits;
Modified();
}
//##ModelId=3E3AEB7C001C
itk::Transform<float,3,2>::Pointer mitk::PlaneGeometry::GetTransfrom() const
{
itkExceptionMacro("Transform not yet supported.");
return NULL;
}
//##ModelId=3E3B9C6E02B5
void mitk::PlaneGeometry::Map(const mitk::Point3D &pt3d_mm, mitk::Point2D &pt2d_mm) const
{
m_PlaneView.map(pt3d_mm, pt2d_mm);
}
//##ModelId=3E3B9C7101BF
void mitk::PlaneGeometry::Map(const mitk::Point2D &pt2d_mm, mitk::Point3D &pt3d_mm) const
{
m_PlaneView.map(pt2d_mm, pt3d_mm);
}
//##ModelId=3E3B9C730262
void mitk::PlaneGeometry::UnitsToMM(const mitk::Point2D &pt_units, mitk::Point2D &pt_mm) const
{
pt_mm.x=m_ScaleFactorMMPerUnitX*pt_units.x;
pt_mm.y=m_ScaleFactorMMPerUnitY*pt_units.y;
}
//##ModelId=3E3B9C760112
void mitk::PlaneGeometry::MMToUnits(const mitk::Point2D &pt_mm, mitk::Point2D &pt_units) const
{
pt_units.x=pt_mm.x*(1.0/m_ScaleFactorMMPerUnitX);
pt_units.y=pt_mm.y*(1.0/m_ScaleFactorMMPerUnitY);
}
//##ModelId=3E3B9C8C0145
void mitk::PlaneGeometry::UnitsToMM(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const
{
vec_mm.x=m_ScaleFactorMMPerUnitX*vec_units.x;
vec_mm.y=m_ScaleFactorMMPerUnitY*vec_units.y;
}
//##ModelId=3E3B9C8E0152
void mitk::PlaneGeometry::MMToUnits(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const
{
vec_units.x=vec_mm.x*(1.0/m_ScaleFactorMMPerUnitX);
vec_units.y=vec_mm.y*(1.0/m_ScaleFactorMMPerUnitY);
}
<|endoftext|>
|
<commit_before>void AddTask_MaterialHistos_pp( Int_t trainConfig = 1, // change different set of cuts
TString V0ReaderEventCutNumber = "00000003",
TString V0ReaderPhotonCutNumber = "060000084001001500000000",
Bool_t isMC = kFALSE,
Int_t IsHeavyIon = 0,
TString cutnumberAODBranch = "0000000060084001001500000",
Bool_t doEtaShiftV0Reader = kFALSE,
Bool_t enableV0findingEffi = kFALSE // enables V0finding efficiency histograms
){
// ================= Load Librariers =================================
gSystem->Load("libCore");
gSystem->Load("libTree");
gSystem->Load("libGeom");
gSystem->Load("libVMC");
gSystem->Load("libPhysics");
gSystem->Load("libMinuit");
gSystem->Load("libSTEERBase");
gSystem->Load("libESD");
gSystem->Load("libAOD");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libCDB");
gSystem->Load("libSTEER");
gSystem->Load("libSTEERBase");
gSystem->Load("libTender");
gSystem->Load("libTenderSupplies");
gSystem->Load("libPWGflowBase");
gSystem->Load("libPWGflowTasks");
gSystem->Load("libPWGGAGammaConv");
// ================== GetAnalysisManager ===============================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
return ;
}
// ================== GetInputEventHandler =============================
AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
//========= Add PID Reponse to ANALYSIS manager ====
if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
AddTaskPIDResponse(isMC);
}
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
if( !(AliV0ReaderV1*)mgr->GetTask("V0ReaderV1") ){
AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1("V0ReaderV1");
fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);
fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi);
if (!mgr) {
Error("AddTask_V0ReaderV1", "No analysis manager found.");
return;
}
AliConvEventCuts *fEventCuts=NULL;
if(V0ReaderEventCutNumber!=""){
fEventCuts= new AliConvEventCuts(V0ReaderEventCutNumber.Data(),V0ReaderEventCutNumber.Data());
fEventCuts->SetPreSelectionCutFlag(kTRUE);
if(fEventCuts->InitializeCutsFromCutString(V0ReaderEventCutNumber.Data())){
fV0ReaderV1->SetEventCuts(fEventCuts);
fEventCuts->SetFillCutHistograms("",kTRUE);
if (IsHeavyIon==2){
fEventCuts->SelectCollisionCandidates(AliVEvent::kINT7);
fEventCuts->DoEtaShift(doEtaShiftV0Reader);
}
}
}
// Set AnalysisCut Number
AliConversionPhotonCuts *fCuts=NULL;
if(V0ReaderPhotonCutNumber!=""){
fCuts= new AliConversionPhotonCuts(V0ReaderPhotonCutNumber.Data(),V0ReaderPhotonCutNumber.Data());
fCuts->SetPreSelectionCutFlag(kTRUE);
fCuts->SetIsHeavyIon(IsHeavyIon);
if(fCuts->InitializeCutsFromCutString(V0ReaderPhotonCutNumber.Data())){
fV0ReaderV1->SetConversionCuts(fCuts);
fCuts->SetFillCutHistograms("",kTRUE);
}
}
if(inputHandler->IsA()==AliAODInputHandler::Class()){
// AOD mode
fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
}
fV0ReaderV1->Init();
AliLog::SetGlobalLogLevel(AliLog::kInfo);
//connect input V0Reader
mgr->AddTask(fV0ReaderV1);
mgr->ConnectInput(fV0ReaderV1,0,cinput);
} else {
Error("AddTask_V0ReaderV1", "Cannot execute AddTask, V0ReaderV1 already exists.");
}
TString TaskEventCutnumber = "00000003";
TString TaskPhotonCutnumber = "06000009266374308800004000";
if(trainConfig == 1){
TaskEventCutnumber = "00000003";
TaskPhotonCutnumber = "06000009266374308800404000";
} else if (trainConfig == 2) {
TaskEventCutnumber = "00000003";
TaskPhotonCutnumber = "06000009266372008800404000";
}
AliConvEventCuts *analysisEventCuts = new AliConvEventCuts();
analysisEventCuts->InitializeCutsFromCutString(TaskEventCutnumber.Data());
analysisEventCuts->SetFillCutHistograms("",kFALSE);
AliConversionPhotonCuts *analysisCuts = new AliConversionPhotonCuts();
analysisCuts->InitializeCutsFromCutString(TaskPhotonCutnumber.Data());
analysisCuts->SetFillCutHistograms("",kFALSE);
AliAnalysisTaskMaterialHistos *fMaterial= new AliAnalysisTaskMaterialHistos(Form("%s_%s_Material",(analysisEventCuts->GetCutNumber()).Data(),(analysisCuts->GetCutNumber()).Data()));
fMaterial->SetEventCuts(analysisEventCuts,IsHeavyIon);
fMaterial->SetConversionCuts(analysisCuts,IsHeavyIon);
fMaterial->SetIsMC(isMC);
mgr->AddTask(fMaterial);
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer(Form("GammaConvMaterial_%s_%s",TaskEventCutnumber.Data(),TaskPhotonCutnumber.Data()), TList::Class(), AliAnalysisManager::kOutputContainer,Form("GammaConv_Material_%s_%s.root",TaskEventCutnumber.Data(),TaskPhotonCutnumber.Data()));
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
mgr->ConnectInput(fMaterial, 0, cinput1 );
mgr->ConnectOutput (fMaterial, 1, coutput1);
//connect containers
return;
}
<commit_msg>modifying AddTask_MaterialHistos_pp<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Friederike Bock, Lucia Leardini , A. Marin *
* Version 1.0 *
* *
* *
* 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. *
**************************************************************************/
//***************************************************************************************
//This AddTask is supposed to set up the main task
//($ALIPHYSICS/PWGGA/GammaConv/AliAnalysisTaskMaterialHistos.cxx) for
//pp together with all supporting classes
//***************************************************************************************
//***************************************************************************************
//CutHandler contains all cuts for a certain analysis and trainconfig,
//it automatically checks length of cutStrings and takes care of the number of added cuts,
//no specification of the variable 'numberOfCuts' needed anymore.
//***************************************************************************************
class CutHandlerConv{
public:
CutHandlerConv(Int_t nMax=10){
nCuts=0; nMaxCuts=nMax; validCuts = true;
eventCutArray = new TString[nMaxCuts]; photonCutArray = new TString[nMaxCuts]; mesonCutArray = new TString[nMaxCuts]; clusterCutArray = new TString[nMaxCuts];
for(Int_t i=0; i<nMaxCuts; i++) {eventCutArray[i] = ""; photonCutArray[i] = ""; mesonCutArray[i] = ""; clusterCutArray[i] = "";}
}
void AddCut(TString eventCut, TString photonCut){
if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
if( eventCut.Length()!=8 || photonCut.Length()!=26 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=""; clusterCutArray[nCuts]="";
nCuts++;
return;
}
void AddCut(TString eventCut, TString photonCut, TString mesonCut){
if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]="";
nCuts++;
return;
}
void AddCut(TString eventCut, TString photonCut, TString mesonCut, TString clusterCut){
if(nCuts>=nMaxCuts) {cout << "ERROR in CutHandlerConv: Exceeded maximum number of cuts!" << endl; validCuts = false; return;}
if( eventCut.Length()!=8 || photonCut.Length()!=26 || mesonCut.Length()!=16 || clusterCut.Length()!=19 ) {cout << "ERROR in CutHandlerConv: Incorrect length of cut string!" << endl; validCuts = false; return;}
eventCutArray[nCuts]=eventCut; photonCutArray[nCuts]=photonCut; mesonCutArray[nCuts]=mesonCut; clusterCutArray[nCuts]=clusterCut;
nCuts++;
return;
}
Bool_t AreValid(){return validCuts;}
Int_t GetNCuts(){if(validCuts) return nCuts; else return 0;}
TString GetEventCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return eventCutArray[i]; else{cout << "ERROR in CutHandlerConv: GetEventCut wrong index i" << endl;return "";}}
TString GetPhotonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return photonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetPhotonCut wrong index i" << endl;return "";}}
TString GetMesonCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return mesonCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetMesonCut wrong index i" << endl;return "";}}
TString GetClusterCut(Int_t i){if(validCuts&&i<nMaxCuts&&i>=0) return clusterCutArray[i]; else {cout << "ERROR in CutHandlerConv: GetClusterCut wrong index i" << endl;return "";}}
private:
Bool_t validCuts;
Int_t nCuts; Int_t nMaxCuts;
TString* eventCutArray;
TString* photonCutArray;
TString* mesonCutArray;
TString* clusterCutArray;
};
void AddTask_MaterialHistos_pp( Int_t trainConfig = 1, // change different set of cuts
Int_t isMC = kFALSE,
TString periodname = "LHC10b", // period name
TString periodNameV0Reader = "",
TString periodNameAnchor = "",
Bool_t enableV0findingEffi = kFALSE // enables V0finding efficiency histograms
){
// ================= Load Librariers =================================
gSystem->Load("libCore");
gSystem->Load("libTree");
gSystem->Load("libGeom");
gSystem->Load("libVMC");
gSystem->Load("libPhysics");
gSystem->Load("libMinuit");
gSystem->Load("libSTEERBase");
gSystem->Load("libESD");
gSystem->Load("libAOD");
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libCDB");
gSystem->Load("libSTEER");
gSystem->Load("libSTEERBase");
gSystem->Load("libTender");
gSystem->Load("libTenderSupplies");
gSystem->Load("libPWGflowBase");
gSystem->Load("libPWGflowTasks");
gSystem->Load("libPWGGAGammaConv");
Int_t IsHeavyIon = 0;
// ================== GetAnalysisManager ===============================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error(Form("AddTask_GammaConvV1_%i",trainConfig), "No analysis manager found.");
return ;
}
// ================== GetInputEventHandler =============================
AliVEventHandler *inputHandler=mgr->GetInputEventHandler();
Bool_t isMCForOtherSettings = 0;
if (isMC > 0) isMCForOtherSettings = 1;
//========= Add PID Reponse to ANALYSIS manager ====
if(!(AliPIDResponse*)mgr->GetTask("PIDResponseTask")){
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
AddTaskPIDResponse(isMCForOtherSettings);
}
//========= Set Cutnumber for V0Reader ================================
TString cutnumberPhoton = "00000000000000000500000000";
//"00200008400000002200000000";
TString cutnumberEvent = "00000103";
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
//========= Add V0 Reader to ANALYSIS manager if not yet existent =====
if( !(AliV0ReaderV1*)mgr->GetTask("V0ReaderV1") ){
AliV0ReaderV1 *fV0ReaderV1 = new AliV0ReaderV1("V0ReaderV1");
if (periodNameV0Reader.CompareTo("") != 0) fV0ReaderV1->SetPeriodName(periodNameV0Reader);
fV0ReaderV1->SetUseOwnXYZCalculation(kTRUE);
fV0ReaderV1->SetCreateAODs(kFALSE);// AOD Output
fV0ReaderV1->SetUseAODConversionPhoton(kTRUE);
fV0ReaderV1->SetProduceV0FindingEfficiency(enableV0findingEffi);
if (!mgr) {
Error("AddTask_V0ReaderV1", "No analysis manager found.");
return;
}
// AliConvEventCuts *fEventCuts=NULL;
// if(V0ReaderEventCutNumber!=""){
// fEventCuts= new AliConvEventCuts(V0ReaderEventCutNumber.Data(),V0ReaderEventCutNumber.Data());
// fEventCuts->SetPreSelectionCutFlag(kTRUE);
// if(fEventCuts->InitializeCutsFromCutString(V0ReaderEventCutNumber.Data())){
// fV0ReaderV1->SetEventCuts(fEventCuts);
// fEventCuts->SetFillCutHistograms("",kTRUE);
// if (IsHeavyIon==2){
// fEventCuts->SelectCollisionCandidates(AliVEvent::kINT7);
// fEventCuts->DoEtaShift(doEtaShiftV0Reader);
// }
// }
// }
// // Set AnalysisCut Number
// AliConversionPhotonCuts *fCuts=NULL;
// if(V0ReaderPhotonCutNumber!=""){
// fCuts= new AliConversionPhotonCuts(V0ReaderPhotonCutNumber.Data(),V0ReaderPhotonCutNumber.Data());
// fCuts->SetPreSelectionCutFlag(kTRUE);
// fCuts->SetIsHeavyIon(IsHeavyIon);
// if(fCuts->InitializeCutsFromCutString(V0ReaderPhotonCutNumber.Data())){
// fV0ReaderV1->SetConversionCuts(fCuts);
// fCuts->SetFillCutHistograms("",kTRUE);
// }
// }
AliConvEventCuts *fEventCuts=NULL;
if(cutnumberEvent!=""){
fEventCuts= new AliConvEventCuts(cutnumberEvent.Data(),cutnumberEvent.Data());
fEventCuts->SetPreSelectionCutFlag(kTRUE);
if(fEventCuts->InitializeCutsFromCutString(cutnumberEvent.Data())){
fV0ReaderV1->SetEventCuts(fEventCuts);
fEventCuts->SetFillCutHistograms("",kTRUE);
}
}
// Set AnalysisCut Number
AliConversionPhotonCuts *fCuts=NULL;
if(cutnumberPhoton!=""){
fCuts= new AliConversionPhotonCuts(cutnumberPhoton.Data(),cutnumberPhoton.Data());
fCuts->SetPreSelectionCutFlag(kTRUE);
fCuts->SetIsHeavyIon(IsHeavyIon);
if(fCuts->InitializeCutsFromCutString(cutnumberPhoton.Data())){
fV0ReaderV1->SetConversionCuts(fCuts);
fCuts->SetFillCutHistograms("",kTRUE);
}
}
if(inputHandler->IsA()==AliAODInputHandler::Class()){
// AOD mode
fV0ReaderV1->SetDeltaAODBranchName(Form("GammaConv_%s_gamma",cutnumberAODBranch.Data()));
}
fV0ReaderV1->Init();
AliLog::SetGlobalLogLevel(AliLog::kInfo);
//connect input V0Reader
mgr->AddTask(fV0ReaderV1);
mgr->ConnectInput(fV0ReaderV1,0,cinput);
} else {
Error("AddTask_V0ReaderV1", "Cannot execute AddTask, V0ReaderV1 already exists.");
}
//================================================
//========= Add task to the ANALYSIS manager =====
// find input container
AliAnalysisTaskMaterialHistos *fMaterialHistos=NULL;
fMaterialHistos= new AliAnalysisTaskMaterialHistos(Form("MaterialHistos_%i",trainConfig));
fMaterialHistos->SetIsMC(isMC);
fMaterialHistos->SetIsHeavyIon(IsHeavyIon);
CutHandlerConv cuts;
if(trainConfig == 1){
cuts.AddCut("00000103", "00000009266302004204400000");
// cuts.AddCut("00000103", "00000009266302004254400000");
// cuts.AddCut("00000103", "00000009266372004204400000");
// cuts.AddCut("00000103", "00000009286372004204400000");
} else if (trainConfig == 2) {
cuts.AddCut("00000103", "00000009286342004204400000");
cuts.AddCut("00000103", "00000009286342001204400000");
cuts.AddCut("00000103", "00000009286342007204400000");
cuts.AddCut("00000103", "00000009286342004254400000");
}else {
Error(Form("GammaConvV1_%i",trainConfig), "wrong trainConfig variable no cuts have been specified for the configuration");
return;
}
if(!cuts.AreValid()){
cout << "\n\n****************************************************" << endl;
cout << "ERROR: No valid cuts stored in CutHandlerConv! Returning..." << endl;
cout << "****************************************************\n\n" << endl;
return;
}
Int_t numberOfCuts = cuts.GetNCuts();
TList *EventCutList = new TList();
TList *ConvCutList = new TList();
EventCutList->SetOwner(kTRUE);
AliConvEventCuts **analysisEventCuts = new AliConvEventCuts*[numberOfCuts];
ConvCutList->SetOwner(kTRUE);
AliConversionPhotonCuts **analysisCuts = new AliConversionPhotonCuts*[numberOfCuts];
for(Int_t i = 0; i<numberOfCuts; i++){
analysisEventCuts[i] = new AliConvEventCuts();
analysisEventCuts[i]->InitializeCutsFromCutString((cuts.GetEventCut(i)).Data());
EventCutList->Add(analysisEventCuts[i]);
analysisEventCuts[i]->SetFillCutHistograms("",kTRUE);
analysisCuts[i] = new AliConversionPhotonCuts();
analysisCuts[i]->InitializeCutsFromCutString((cuts.GetPhotonCut(i)).Data());
analysisCuts[i]->SetFillCutHistograms("",kTRUE);
ConvCutList->Add(analysisCuts[i]);
EventCutList->Add(analysisEventCuts[i]);
}
fMaterialHistos->SetEventCutList(numberOfCuts,EventCutList);
fMaterialHistos->SetConversionCutList(numberOfCuts,ConvCutList);
mgr->AddTask(fMaterialHistos);
AliAnalysisDataContainer *coutput =
mgr->CreateContainer(Form("GammaConvMaterial_%i",trainConfig), TList::Class(),
AliAnalysisManager::kOutputContainer,Form("GammaConv_Material_%i.root",trainConfig ));
mgr->ConnectInput(fMaterialHistos, 0, cinput );
mgr->ConnectOutput(fMaterialHistos, 1, coutput);
//connect containers
return;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Declarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgparticlepainter_p.h"
#include <QDebug>
QT_BEGIN_NAMESPACE
/*!
\qmlclass ParticlePainter QSGParticlePainter
\inqmlmodule QtQuick.Particles 2
\inherits ParticlePainter
\brief ParticlePainter elements allow you to specify how to paint particles.
The default implementation paints nothing. See the subclasses if you want to
paint something visible.
*/
/*!
\qmlproperty ParticleSystem QtQuick.Particles2::ParticlePainter::system
This is the system whose particles can be painted by the element.
If the ParticlePainter is a direct child of a ParticleSystem, it will automatically be associated with it.
*/
/*!
\qmlproperty list<string> QtQuick.Particles2::ParticlePainter::groups
Which logical particle groups will be painted.
If empty, it will paint the default particle group ("").
*/
QSGParticlePainter::QSGParticlePainter(QSGItem *parent) :
QSGItem(parent),
m_system(0), m_count(0), m_sentinel(new QSGParticleData(0))
{
connect(this, SIGNAL(parentChanged(QSGItem*)),
this, SLOT(calcSystemOffset()));
connect(this, SIGNAL(xChanged()),
this, SLOT(calcSystemOffset()));
connect(this, SIGNAL(yChanged()),
this, SLOT(calcSystemOffset()));
}
void QSGParticlePainter::componentComplete()
{
if (!m_system && qobject_cast<QSGParticleSystem*>(parentItem()))
setSystem(qobject_cast<QSGParticleSystem*>(parentItem()));
if (!m_system)
qWarning() << "ParticlePainter created without a particle system specified";//TODO: useful QML warnings, like line number?
QSGItem::componentComplete();
}
void QSGParticlePainter::setSystem(QSGParticleSystem *arg)
{
if (m_system != arg) {
m_system = arg;
if (m_system){
m_system->registerParticlePainter(this);
connect(m_system, SIGNAL(xChanged()),
this, SLOT(calcSystemOffset()));
connect(m_system, SIGNAL(yChanged()),
this, SLOT(calcSystemOffset()));
calcSystemOffset();
}
emit systemChanged(arg);
}
}
void QSGParticlePainter::load(QSGParticleData* d)
{
if (m_pleaseReset)
return;
initialize(d->group, d->index);
m_pendingCommits << qMakePair<int, int>(d->group, d->index);
}
void QSGParticlePainter::reload(QSGParticleData* d)
{
if (m_pleaseReset)
return;
m_pendingCommits << qMakePair<int, int>(d->group, d->index);
}
void QSGParticlePainter::reset()
{
calcSystemOffset(true);//In case an ancestor changed in some way
}
void QSGParticlePainter::setCount(int c)//### TODO: some resizeing so that particles can reallocate on size change instead of recreate
{
Q_ASSERT(c >= 0); //XXX
if (c == m_count)
return;
m_count = c;
emit countChanged();
reset();
}
int QSGParticlePainter::count()
{
return m_count;
}
void QSGParticlePainter::calcSystemOffset(bool resetPending)
{
if (!m_system || !parentItem())
return;
QPointF lastOffset = m_systemOffset;
m_systemOffset = -1 * this->mapFromItem(m_system, QPointF(0.0, 0.0));
if (lastOffset != m_systemOffset && !resetPending){
//Reload all particles//TODO: Necessary?
foreach (const QString &g, m_groups){
int gId = m_system->m_groupIds[g];
foreach (QSGParticleData* d, m_system->m_groupData[gId]->data)
reload(d);
}
}
}
typedef QPair<int,int> intPair;
void QSGParticlePainter::performPendingCommits()
{
foreach (intPair p, m_pendingCommits)
commit(p.first, p.second);
m_pendingCommits.clear();
}
QT_END_NAMESPACE
<commit_msg>Reset on system change<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Declarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgparticlepainter_p.h"
#include <QDebug>
QT_BEGIN_NAMESPACE
/*!
\qmlclass ParticlePainter QSGParticlePainter
\inqmlmodule QtQuick.Particles 2
\inherits ParticlePainter
\brief ParticlePainter elements allow you to specify how to paint particles.
The default implementation paints nothing. See the subclasses if you want to
paint something visible.
*/
/*!
\qmlproperty ParticleSystem QtQuick.Particles2::ParticlePainter::system
This is the system whose particles can be painted by the element.
If the ParticlePainter is a direct child of a ParticleSystem, it will automatically be associated with it.
*/
/*!
\qmlproperty list<string> QtQuick.Particles2::ParticlePainter::groups
Which logical particle groups will be painted.
If empty, it will paint the default particle group ("").
*/
QSGParticlePainter::QSGParticlePainter(QSGItem *parent) :
QSGItem(parent),
m_system(0), m_count(0), m_sentinel(new QSGParticleData(0))
{
connect(this, SIGNAL(parentChanged(QSGItem*)),
this, SLOT(calcSystemOffset()));
connect(this, SIGNAL(xChanged()),
this, SLOT(calcSystemOffset()));
connect(this, SIGNAL(yChanged()),
this, SLOT(calcSystemOffset()));
}
void QSGParticlePainter::componentComplete()
{
if (!m_system && qobject_cast<QSGParticleSystem*>(parentItem()))
setSystem(qobject_cast<QSGParticleSystem*>(parentItem()));
if (!m_system)
qWarning() << "ParticlePainter created without a particle system specified";//TODO: useful QML warnings, like line number?
QSGItem::componentComplete();
}
void QSGParticlePainter::setSystem(QSGParticleSystem *arg)
{
if (m_system != arg) {
m_system = arg;
if (m_system){
m_system->registerParticlePainter(this);
connect(m_system, SIGNAL(xChanged()),
this, SLOT(calcSystemOffset()));
connect(m_system, SIGNAL(yChanged()),
this, SLOT(calcSystemOffset()));
reset();
}
emit systemChanged(arg);
}
}
void QSGParticlePainter::load(QSGParticleData* d)
{
if (m_pleaseReset)
return;
initialize(d->group, d->index);
m_pendingCommits << qMakePair<int, int>(d->group, d->index);
}
void QSGParticlePainter::reload(QSGParticleData* d)
{
if (m_pleaseReset)
return;
m_pendingCommits << qMakePair<int, int>(d->group, d->index);
}
void QSGParticlePainter::reset()
{
calcSystemOffset(true);//In case an ancestor changed in some way
}
void QSGParticlePainter::setCount(int c)//### TODO: some resizeing so that particles can reallocate on size change instead of recreate
{
Q_ASSERT(c >= 0); //XXX
if (c == m_count)
return;
m_count = c;
emit countChanged();
reset();
}
int QSGParticlePainter::count()
{
return m_count;
}
void QSGParticlePainter::calcSystemOffset(bool resetPending)
{
if (!m_system || !parentItem())
return;
QPointF lastOffset = m_systemOffset;
m_systemOffset = -1 * this->mapFromItem(m_system, QPointF(0.0, 0.0));
if (lastOffset != m_systemOffset && !resetPending){
//Reload all particles//TODO: Necessary?
foreach (const QString &g, m_groups){
int gId = m_system->m_groupIds[g];
foreach (QSGParticleData* d, m_system->m_groupData[gId]->data)
reload(d);
}
}
}
typedef QPair<int,int> intPair;
void QSGParticlePainter::performPendingCommits()
{
foreach (intPair p, m_pendingCommits)
commit(p.first, p.second);
m_pendingCommits.clear();
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before><commit_msg>Fix of the addtask name<commit_after><|endoftext|>
|
<commit_before>#include "player.h"
#include "alien.h"
#include "global.h"
using namespace wsp;
Player players[NUM_PLAYERS];
Alien *aliens[NUM_ALIENS];
wsp::Sprite bgs[NUM_SPACE_BGS];
void initBackgrounds()
{
if(imgBgs[0].LoadImage("/apps/Spaaace/images/space1.png") != IMG_LOAD_ERROR_NONE) exit(1);
bgs[0].SetImage(&imgBgs[0]);
bgs[0].SetPosition(0, 0);
manager.Append(&bgs[0]);
}
void initBoundaries() {
bounds.left.SetPosition(-1, 0);
bounds.left.SetWidth(1);
bounds.left.SetHeight(480);
bounds.right.SetPosition(640, 0);
bounds.right.SetWidth(1);
bounds.right.SetHeight(480);
bounds.top.SetPosition(0, -1);
bounds.top.SetWidth(640);
bounds.top.SetHeight(1);
bounds.bottom.SetPosition(0, 480);
bounds.bottom.SetWidth(640);
bounds.bottom.SetHeight(1);
}
void loadPlayerSprites() {
const char *imgPaths[2] = { "/apps/Spaaace/images/ship.png", "/apps/Spaaace/images/ship2.png" };
int i;
for(i=0;i<NUM_PLAYERS;i++) {
if(imgPlayers[i].LoadImage(imgPaths[i]) != IMG_LOAD_ERROR_NONE) exit(1);
players[i].SetImage(&imgPlayers[i]);
players[i].SetPosition(100, 100);
manager.Append(&players[i]);
}
}
void initAliens(unsigned int maxAliens) {
if(imgAliens[0].LoadImage("/apps/Spaaace/images/alien3.png") != IMG_LOAD_ERROR_NONE) exit(1);
int i;
for(i=0;i<maxAliens;i++) {
aliens[i] = new Alien(&imgAliens[0]);
manager.Append(aliens[i]);
}
}
int main(int argc, char **argv) {
gwd.InitVideo();
gwd.SetBackground((GXColor){ 0, 0, 0, 255 });
fatInitDefault();
WPAD_Init();
loadPlayerSprites();
initBoundaries();
initAliens(NUM_ALIENS);
initBackgrounds();
while(true) {
WPAD_ScanPads();
if(WPAD_ButtonsDown(WPAD_CHAN_0) & WPAD_BUTTON_HOME) break;
int i;
for(i=0;i<NUM_ALIENS;i++) {
aliens[i]->update();
}
for(i=0;i<NUM_PLAYERS;i++) {
u32 pressed = WPAD_ButtonsHeld(i);
players[i].update(pressed, (wsp::Sprite **)aliens);
}
manager.Draw(0,0);
gwd.Flush();
}
return 0;
}
<commit_msg>Moving space and prep for shooting<commit_after>#include "player.h"
#include "alien.h"
#include "shot.h"
#include "global.h"
using namespace wsp;
Player players[NUM_PLAYERS];
Alien *aliens[NUM_ALIENS];
Shot *shots[NUM_SHOTS];
wsp::Sprite bgs[NUM_SPACE_BGS];
void initBackgrounds()
{
int i=0;
for(int i=0;i<NUM_SPACE_BGS;i++) {
char path[256];
sprintf(path, "/apps/Spaaace/images/space-%i.png", i%2);
if(imgBgs[i].LoadImage((const char *)path) != IMG_LOAD_ERROR_NONE) exit(1);
bgs[i].SetImage(&imgBgs[i], 640, 480);
bgs[i].SetPosition(i*640, 0);
manager.Append(&bgs[i]);
}
}
void initBoundaries() {
bounds.left.SetPosition(-1, 0);
bounds.left.SetWidth(1);
bounds.left.SetHeight(480);
bounds.right.SetPosition(640, 0);
bounds.right.SetWidth(1);
bounds.right.SetHeight(480);
bounds.top.SetPosition(0, -1);
bounds.top.SetWidth(640);
bounds.top.SetHeight(1);
bounds.bottom.SetPosition(0, 480);
bounds.bottom.SetWidth(640);
bounds.bottom.SetHeight(1);
}
void loadPlayerSprites() {
const char *imgPaths[2] = { "/apps/Spaaace/images/ship.png", "/apps/Spaaace/images/ship2.png" };
int i;
for(i=0;i<NUM_PLAYERS;i++) {
if(imgPlayers[i].LoadImage(imgPaths[i]) != IMG_LOAD_ERROR_NONE) exit(1);
players[i].SetImage(&imgPlayers[i]);
players[i].SetPosition(100, 100);
players[i].setShots((Shot **)&shots);
manager.Append(&players[i]);
}
}
void initAliens(unsigned int maxAliens) {
if(imgAliens[0].LoadImage("/apps/Spaaace/images/alien3.png") != IMG_LOAD_ERROR_NONE) exit(1);
int i;
for(i=0;i<maxAliens;i++) {
aliens[i] = new Alien(&imgAliens[0]);
manager.Append(aliens[i]);
}
}
void initShots() {
if(bullet.LoadImage("/apps/Spaaace/images/bullet.png") != IMG_LOAD_ERROR_NONE) exit(1);
int i;
for(i=0;i<NUM_SHOTS;i++) {
shots[i] = new Shot(&bullet, -100, -100);
manager.Append(shots[i]);
}
}
int main(int argc, char **argv) {
gwd.InitVideo();
gwd.SetBackground((GXColor){ 0, 0, 0, 255 });
fatInitDefault();
WPAD_Init();
initShots();
loadPlayerSprites();
initBoundaries();
initAliens(NUM_ALIENS);
initBackgrounds();
while(true) {
WPAD_ScanPads();
if(WPAD_ButtonsDown(WPAD_CHAN_0) & WPAD_BUTTON_HOME) break;
int i;
for(i=0;i<NUM_ALIENS;i++) {
aliens[i]->update();
}
for(i=0;i<NUM_PLAYERS;i++) {
u32 held = WPAD_ButtonsHeld(i);
u32 pressed = WPAD_ButtonsDown(i);
players[i].update(held, pressed, (wsp::Sprite **)aliens);
}
for(i=0;i<NUM_SHOTS;i++) {
//if(shots[i]->isFired() == false) continue;
shots[i]->update();
}
for(i=0;i<NUM_SPACE_BGS;i++) {
bgs[i].Move(-1, 0);
if(bgs[i].GetX() < -640) {
bgs[i].SetPosition(1920, 0);
}
}
manager.Draw(0,0);
gwd.Flush();
}
return 0;
}
<|endoftext|>
|
<commit_before>
blink-an-led.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//Device ID
//48ff70065067555028111587
//Access Token
//4348526a1c0932c678d6e971ce456b9d2ea4a1f5
// Define the pins we're going to call pinMode on
int led = D0; // You'll need to wire an LED to this one to see it blink.
int led2 = D7; // This one is the built-in tiny one to the right of the USB jack
volatile int flag = 0;
int flagvalue = 0;
class elapsedMillis
{
private:
unsigned long ms;
public:
elapsedMillis(void) { ms = millis(); }
elapsedMillis(unsigned long val) { ms = millis() - val; }
elapsedMillis(const elapsedMillis &orig) { ms = orig.ms; }
operator unsigned long () const { return millis() - ms; }
elapsedMillis & operator = (const elapsedMillis &rhs) { ms = rhs.ms; return *this; }
elapsedMillis & operator = (unsigned long val) { ms = millis() - val; return *this; }
elapsedMillis & operator -= (unsigned long val) { ms += val ; return *this; }
elapsedMillis & operator += (unsigned long val) { ms -= val ; return *this; }
elapsedMillis operator - (int val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator - (unsigned int val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator - (long val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator - (unsigned long val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator + (int val) const { elapsedMillis r(*this); r.ms -= val; return r; }
elapsedMillis operator + (unsigned int val) const { elapsedMillis r(*this); r.ms -= val; return r; }
elapsedMillis operator + (long val) const { elapsedMillis r(*this); r.ms -= val; return r; }
elapsedMillis operator + (unsigned long val) const { elapsedMillis r(*this); r.ms -= val; return r; }
};
class elapsedMicros
{
private:
unsigned long us;
public:
elapsedMicros(void) { us = micros(); }
elapsedMicros(unsigned long val) { us = micros() - val; }
elapsedMicros(const elapsedMicros &orig) { us = orig.us; }
operator unsigned long () const { return micros() - us; }
elapsedMicros & operator = (const elapsedMicros &rhs) { us = rhs.us; return *this; }
elapsedMicros & operator = (unsigned long val) { us = micros() - val; return *this; }
elapsedMicros & operator -= (unsigned long val) { us += val ; return *this; }
elapsedMicros & operator += (unsigned long val) { us -= val ; return *this; }
elapsedMicros operator - (int val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator - (unsigned int val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator - (long val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator - (unsigned long val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator + (int val) const { elapsedMicros r(*this); r.us -= val; return r; }
elapsedMicros operator + (unsigned int val) const { elapsedMicros r(*this); r.us -= val; return r; }
elapsedMicros operator + (long val) const { elapsedMicros r(*this); r.us -= val; return r; }
elapsedMicros operator + (unsigned long val) const { elapsedMicros r(*this); r.us -= val; return r; }
};
Ready.<commit_msg>updated the spark core code to latest version<commit_after>//Device ID
//48ff70065067555028111587
//Access Token
//4348526a1c0932c678d6e971ce456b9d2ea4a1f5
#define DURATION 50000
#define NOTE_BF4 1073
#define NOTE_AF4 1205
#define NOTE_F4 1433
#define NOTE_EF5 804
#define NOTE_D5 852
#define PAUSE 50000
#define MAX_NOTES 11
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int funkyTown[12] = {NOTE_BF4, NOTE_BF4, NOTE_AF4, NOTE_BF4,
PAUSE, NOTE_F4, PAUSE, NOTE_F4,
NOTE_BF4, NOTE_EF5, NOTE_D5, NOTE_BF4};
int16_t audioPin = D6;
int16_t x,y = 0;
// Define the pins we're going to call pinMode on
int led = D0; // You'll need to wire an LED to this one to see it blink.
int led2 = D7; // This one is the built-in tiny one to the right of the USB jack
volatile int flag = 0;
int flagvalue = 0;
int motorpin = A0;
volatile int open_door_flag = 0;
class elapsedMillis
{
private:
unsigned long ms;
public:
elapsedMillis(void) { ms = millis(); }
elapsedMillis(unsigned long val) { ms = millis() - val; }
elapsedMillis(const elapsedMillis &orig) { ms = orig.ms; }
operator unsigned long () const { return millis() - ms; }
elapsedMillis & operator = (const elapsedMillis &rhs) { ms = rhs.ms; return *this; }
elapsedMillis & operator = (unsigned long val) { ms = millis() - val; return *this; }
elapsedMillis & operator -= (unsigned long val) { ms += val ; return *this; }
elapsedMillis & operator += (unsigned long val) { ms -= val ; return *this; }
elapsedMillis operator - (int val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator - (unsigned int val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator - (long val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator - (unsigned long val) const { elapsedMillis r(*this); r.ms += val; return r; }
elapsedMillis operator + (int val) const { elapsedMillis r(*this); r.ms -= val; return r; }
elapsedMillis operator + (unsigned int val) const { elapsedMillis r(*this); r.ms -= val; return r; }
elapsedMillis operator + (long val) const { elapsedMillis r(*this); r.ms -= val; return r; }
elapsedMillis operator + (unsigned long val) const { elapsedMillis r(*this); r.ms -= val; return r; }
};
class elapsedMicros
{
private:
unsigned long us;
public:
elapsedMicros(void) { us = micros(); }
elapsedMicros(unsigned long val) { us = micros() - val; }
elapsedMicros(const elapsedMicros &orig) { us = orig.us; }
operator unsigned long () const { return micros() - us; }
elapsedMicros & operator = (const elapsedMicros &rhs) { us = rhs.us; return *this; }
elapsedMicros & operator = (unsigned long val) { us = micros() - val; return *this; }
elapsedMicros & operator -= (unsigned long val) { us += val ; return *this; }
elapsedMicros & operator += (unsigned long val) { us -= val ; return *this; }
elapsedMicros operator - (int val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator - (unsigned int val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator - (long val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator - (unsigned long val) const { elapsedMicros r(*this); r.us += val; return r; }
elapsedMicros operator + (int val) const { elapsedMicros r(*this); r.us -= val; return r; }
elapsedMicros operator + (unsigned int val) const { elapsedMicros r(*this); r.us -= val; return r; }
elapsedMicros operator + (long val) const { elapsedMicros r(*this); r.us -= val; return r; }
elapsedMicros operator + (unsigned long val) const { elapsedMicros r(*this); r.us -= val; return r; }
};
int cook(String args)
{
int value_time = atoi(args.c_str());
flag = 1;
flagvalue = value_time*1000;
return value_time;
}
int stopcook(String args)
{
flag = 0;
flagvalue = 0;
return 1;
}
int opendoor(String args)
{
open_door_flag = 1;
return 1;
}
void takeMeTo(int pin, int note){
for(x = 0; x < (DURATION/(note*2)); x++) {
PIN_MAP[pin].gpio_peripheral->BSRR = PIN_MAP[pin].gpio_pin; // HIGH
delayMicroseconds(note);
PIN_MAP[pin].gpio_peripheral->BRR = PIN_MAP[pin].gpio_pin; // LOW
delayMicroseconds(note);
}
y++;
if(y >= MAX_NOTES) y = 0;
delay(250);
}
void outputmusic()
{
int i = 0;
for (i = 0; i < 12; i++) {
takeMeTo(audioPin, funkyTown[i]);
}
}
void openDoor()
{
myservo.write(90);
delay(1000);
myservo.write(180);
delay(1000);
myservo.write(220);
delay(1000);
myservo.write(90);
}
// This routine runs only once upon reset
void setup() {
// Initialize D0 + D7 pin as output
// It's important you do this here, inside the setup() function rather than outside it or in the loop function.
myservo.attach(motorpin);
pinMode(audioPin, OUTPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
Spark.function("cook",cook);
Spark.function("stopcook",stopcook);
Spark.function("opendoor",opendoor);
}
// This routine gets called repeatedly, like once every 5-15 milliseconds.
// Spark firmware interleaves background CPU activity associated with WiFi + Cloud activity with your code.
// Make sure none of your code delays or blocks for too long (like more than 5 seconds), or weird things can happen.
void loop() {
if (flag)
{
elapsedMillis timeElapsed;
int interval = flagvalue;
while (timeElapsed < interval && flag)
{
digitalWrite(led, HIGH); // Turn ON the LED pins
digitalWrite(led2, HIGH);
delay(10); // Wait for 1000mS = 1 second
}
digitalWrite(led, LOW); // Turn OFF the LED pins
digitalWrite(led2, LOW);
openDoor();
outputmusic();
flag = 0;
flagvalue = 0;
}
else
{
if(open_door_flag)
{
openDoor();
open_door_flag = 0;
}
}
}
<|endoftext|>
|
<commit_before>/*!
* Copyright (c) 2016 by Contributors
* \file q_fully_connected.cc
* \brief Quantized CONV operator
* \author HPI-DeepLearning
*/
#include "./q_convolution-inl.h"
#include <mshadow/base.h>
#include <mshadow/tensor.h>
#include <memory>
#include "./binary_layer.h"
#include "./xnor_cpu.h"
#if MXNET_USE_MKL2017 == 1
#include <mkl_memory.h>
#include "../../src/operator/mkl/mkl_memory-inl.h"
#include "../../src/operator/mkl/mkl_convolution-inl.h"
#endif // MXNET_USE_MKL2017
#if MXNET_USE_NNPACK == 1
#include "../../src/operator/nnpack/nnpack_convolution-inl.h"
#endif // MXNET_USE_NNPACK
# include <chrono>
using ns = std::chrono::nanoseconds;
using get_time = std::chrono::steady_clock ;
namespace mshadow {
inline BINARY_WORD concatenate(float* array)
{
BINARY_WORD rvalue=0;
BINARY_WORD sign;
#pragma omp parallel for
for (int i = 0; i < BITS_PER_BINARY_WORD; i++)
{
sign = (array[i]>=0);
rvalue = rvalue | (sign<< (i));
}
return rvalue;
}
inline void get_binary_row(float* row, BINARY_WORD * b_row, int size){
for (int i = 0; i < size; i+=BITS_PER_BINARY_WORD) {
float * array = new float[BITS_PER_BINARY_WORD];
#pragma omp parallel for
for (int j = 0;j < BITS_PER_BINARY_WORD; ++j) {
array[j] = row[i+j];
}
b_row[i/BITS_PER_BINARY_WORD] = concatenate(array);
delete[] array;
}
}
inline void get_binary_col(float* col, BINARY_WORD * b_col, int n, int k){
for(int x=0; x < k; ++x){
for(int y=0; y<(n/BITS_PER_BINARY_WORD); y++){
float * array = new float[BITS_PER_BINARY_WORD];
#pragma omp parallel for
for(int b=0; b<BITS_PER_BINARY_WORD; ++b){
array[b] = col[(y*BITS_PER_BINARY_WORD+b)*k + x];
}
b_col[y*k + x]=concatenate(array);
delete[] array;
}
}
}
inline void xnor_gemm(int M, int K, int N,
BINARY_WORD *A, int lda,
BINARY_WORD *B, int ldb,
float *C, int ldc){
int i,n,k;
#pragma omp parallel for
for(i = 0; i < M; ++i){
#pragma omp parallel for
for(n = 0; n < N; ++n){
BINARY_WORD A_PART = A[i*lda+n];
#pragma omp parallel for
for(k = 0; k < K; ++k){
C[i*ldc+k] += (float)__builtin_popcount(~(A_PART ^ B[n*ldb+k]));
}
}
}
}
inline void baseline_gemm(int M, int K, int N,
float *A, int lda,
float *B, int ldb,
float *C, int ldc){
int i,n,k;
for(i = 0; i < M; ++i){
for(n = 0; n < N; ++n){
float A_PART = A[i*lda+n];
for(k = 0; k < K; ++k){
C[i*ldc+k] += A_PART * B[n*ldb+k];
}
}
}
}
inline void QConvolutionForward(const Tensor<cpu, 4, float> &data,
const Tensor<cpu, 2, float> &wmat,
const Tensor<cpu, 2, float> &in_col,
const Tensor<cpu, 2, float> &temp_dst,
const Tensor<cpu, 4, float> &out,
const mxnet::op::QConvolutionParam ¶m) {
CHECK_EQ(param.stride[0], 1) << "binary convolution currently only supported with stride==1";
CHECK_EQ(param.stride[1], 1) << "binary convolution currently only supported with stride==1";
///*
int m = wmat.size(0);
int n = wmat.size(1);
int k = in_col.size(1);
BINARY_WORD* binary_row = (BINARY_WORD*) malloc(m * n/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD));
BINARY_WORD* binary_col = (BINARY_WORD*) malloc(n * k/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD));
get_binary_row(wmat.dptr_, binary_row, m*n);
get_binary_col(in_col.dptr_, binary_col, n, k);
auto start = std::chrono::high_resolution_clock::now();
///*
xnor_gemm(m, k, n/BITS_PER_BINARY_WORD,
binary_row, n/BITS_PER_BINARY_WORD,
binary_col, k,
temp_dst.dptr_, k);
//*/
/*
//test using baseline gemm kernel
baseline_gemm(m, k, n,
wmat.dptr_, n,
in_col.dptr_, k,
temp_dst.dptr_, k);
*/
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "xnor Elapsed time: " << elapsed.count() << " s\n";
free(binary_row);
free(binary_col);
}
template<typename DType>
inline void QConvolutionForward(const Tensor<cpu, 4, DType> &data,
const Tensor<cpu, 2, DType> &wmat,
const Tensor<cpu, 2, DType> &in_col,
const Tensor<cpu, 2, DType> &temp_dst,
const Tensor<cpu, 4, DType> &out,
const mxnet::op::QConvolutionParam ¶m) {
CHECK(false) << "only float supported";
}
}
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(QConvolutionParam);
template<>
Operator* CreateOp<cpu>(QConvolutionParam param, int dtype,
std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape,
Context ctx) {
Operator *op = NULL;
#if MXNET_USE_MKL2017 == 1
if ((param.dilate[0] == 1 && param.dilate[1] == 1)
&& param.kernel.ndim() == 2) {
LOG(FATAL) << "QConvolution not supported with MKL";
switch (dtype) {
case mshadow::kFloat32:
return new MKLConvolutionOp<cpu, float>(param);
case mshadow::kFloat64:
return new MKLConvolutionOp<cpu, double>(param);
default:
break;
}
}
LOG(INFO) << MKLConvolutionOp<cpu, float>::getName() << " Skip MKL optimization";
#endif
#if MXNET_USE_NNPACK == 1
const size_t batch_size = (*in_shape)[0][0];
if ((param.dilate[0] == 1 && param.dilate[1] == 1)
&& param.kernel.ndim() == 2 && (!param.no_bias)
&& param.num_group == 1 && (batch_size == 1 ||
((batch_size > 1) && (param.stride[0] == 1) &&
(param.stride[1] == 1)))) {
LOG(FATAL) << "QConvolution not supported with NNPACK";
switch (dtype) {
case mshadow::kFloat32:
return new NNPACKConvolutionOp<cpu, float>(param);
default:
break;
}
}
#endif
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
op = new QConvolutionOp<cpu, DType>(param);
})
return op;
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *QConvolutionProp::CreateOperatorEx(Context ctx,
std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0], in_shape, &out_shape, ctx);
}
MXNET_REGISTER_OP_PROPERTY(QConvolution, QConvolutionProp)
.add_argument("data", "Symbol", "Input data to the ConvolutionOp.")
.add_argument("weight", "Symbol", "Weight matrix.")
.add_argument("bias", "Symbol", "Bias parameter.")
.add_arguments(QConvolutionParam::__FIELDS__())
.describe("Apply convolution to input then add a bias.");
} // namespace op
} // namespace mxnet
<commit_msg>add calculation of alpha and beta values (not applied to result yet)<commit_after>/*!
* Copyright (c) 2016 by Contributors
* \file q_fully_connected.cc
* \brief Quantized CONV operator
* \author HPI-DeepLearning
*/
#include "./q_convolution-inl.h"
#include <mshadow/base.h>
#include <mshadow/tensor.h>
#include <memory>
#include "./binary_layer.h"
#include "./xnor_cpu.h"
#if MXNET_USE_MKL2017 == 1
#include <mkl_memory.h>
#include "../../src/operator/mkl/mkl_memory-inl.h"
#include "../../src/operator/mkl/mkl_convolution-inl.h"
#endif // MXNET_USE_MKL2017
#if MXNET_USE_NNPACK == 1
#include "../../src/operator/nnpack/nnpack_convolution-inl.h"
#endif // MXNET_USE_NNPACK
# include <chrono>
using ns = std::chrono::nanoseconds;
using get_time = std::chrono::steady_clock ;
namespace mshadow {
inline float get_alpha(float* weight, int width, int height, int depth) {
float accum = 0.0f;
for (int z = 0; z < depth; ++z) {
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
accum += weight[z * (width * height) + x * height + y]; //@todo: abs?
}
}
}
return accum / (float) (width * height * depth);
}
inline void get_alpha_plane(float* alpha_plane_out, float* weights,
int num_weights,
int kernel_width, int kernel_height,
int input_depth) {
for (int i = 0; i < num_weights; i++) {
alpha_plane_out[i] = get_alpha(&weights[i * kernel_height * kernel_width * input_depth], kernel_height, kernel_width, input_depth);
}
}
inline void get_A_planes(float* A_planes_out, float* input,
int input_depth, int input_width, int input_height,
int batch_size) {
for (int i = 0; i < batch_size; i++) {
for (int x = 0; x < input_width; ++x) {
for (int y = 0; y < input_height; ++y) {
float accum = 0.0f;
for (int z = 0; z < input_depth; ++z) {
accum += input[i * (input_depth * input_width * input_height) +
z * (input_width * input_height) +
x * input_height +
y]; //@todo: abs?
}
A_planes_out[i * input_width * input_height +
x * input_height +
y] = accum / (float) input_depth;
}
}
}
}
inline void get_K_planes(float* K_planes_out, float* A_planes,
int input_width, int input_height,
int kernel_width, int kernel_height,
int batch_size) {
int K_width = (input_width - kernel_width + 2 * 0/*padding*/) / 1/*stride*/ + 1;
int K_height = (input_height - kernel_height + 2 * 0/*padding*/) / 1/*stride*/ + 1;
//@todo: super naive conv
for (int i = 0; i < batch_size; i ++) {
// for every batch
for (int kx = 0; kx < K_width; kx++) {
for (int ky = 0; ky < K_height; ky++) {
// for every kx, ky in our output plane
int accum = 0;
// we do collect the sum of all values covered by the kernel
for (int ix = kx; ix < kx + kernel_width; ix++) {
for (int iy = ky; iy < ky + kernel_height; iy++) {
accum += A_planes[i * input_width * input_height +
ix * input_height +
iy];
}
}
// and multiply them with 1/(w * h)
K_planes_out[i * K_width * K_height +
kx * K_height +
ky] = accum / ((float) kernel_height * kernel_width);
}
}
}
}
inline void pointwise_mul_mm(float *output, const float *input, int size){
for (int i = 0; i < size; i++) {
output[i] *= input[i];
}
}
inline void pointwise_mul_scalar(float *output, const float scalar, int size){
for (int i = 0; i < size; i++) {
output[i] *= scalar;
}
}
inline BINARY_WORD concatenate(float* array)
{
BINARY_WORD rvalue=0;
BINARY_WORD sign;
#pragma omp parallel for
for (int i = 0; i < BITS_PER_BINARY_WORD; i++)
{
sign = (array[i]>=0);
rvalue = rvalue | (sign<< (i));
}
return rvalue;
}
inline void get_binary_row(float* row, BINARY_WORD * b_row, int size){
for (int i = 0; i < size; i+=BITS_PER_BINARY_WORD) {
float * array = new float[BITS_PER_BINARY_WORD];
#pragma omp parallel for
for (int j = 0;j < BITS_PER_BINARY_WORD; ++j) {
array[j] = row[i+j];
}
b_row[i/BITS_PER_BINARY_WORD] = concatenate(array);
delete[] array;
}
}
inline void get_binary_col(float* col, BINARY_WORD * b_col, int n, int k){
for(int x=0; x < k; ++x){
for(int y=0; y<(n/BITS_PER_BINARY_WORD); y++){
float * array = new float[BITS_PER_BINARY_WORD];
#pragma omp parallel for
for(int b=0; b<BITS_PER_BINARY_WORD; ++b){
array[b] = col[(y*BITS_PER_BINARY_WORD+b)*k + x];
}
b_col[y*k + x]=concatenate(array);
delete[] array;
}
}
}
inline void xnor_gemm(int M, int K, int N,
BINARY_WORD *A, int lda,
BINARY_WORD *B, int ldb,
float *C, int ldc){
int i,n,k;
#pragma omp parallel for
for(i = 0; i < M; ++i){
#pragma omp parallel for
for(n = 0; n < N; ++n){
BINARY_WORD A_PART = A[i*lda+n];
#pragma omp parallel for
for(k = 0; k < K; ++k){
C[i*ldc+k] += (float)__builtin_popcount(~(A_PART ^ B[n*ldb+k]));
}
}
}
}
inline void baseline_gemm(int M, int K, int N,
float *A, int lda,
float *B, int ldb,
float *C, int ldc){
int i,n,k;
for(i = 0; i < M; ++i){
for(n = 0; n < N; ++n){
float A_PART = A[i*lda+n];
for(k = 0; k < K; ++k){
C[i*ldc+k] += A_PART * B[n*ldb+k];
}
}
}
}
inline void QConvolutionForward(const Tensor<cpu, 4, float> &data,
const Tensor<cpu, 2, float> &wmat,
const Tensor<cpu, 2, float> &in_col,
const Tensor<cpu, 2, float> &temp_dst,
const Tensor<cpu, 4, float> &out,
const mxnet::op::QConvolutionParam ¶m) {
CHECK_EQ(param.stride[0], 1) << "binary convolution currently only supported with stride==1";
CHECK_EQ(param.stride[1], 1) << "binary convolution currently only supported with stride==1";
CHECK_EQ(param.pad[0], 0) << "cant create beta scaling factor with padded input yet";
CHECK_EQ(param.pad[1], 0) << "cant create beta scaling factor with padded input yet";
///*
int m = wmat.size(0);
int n = wmat.size(1);
int k = in_col.size(1);
int batch_size = data.size(0);
int input_width = data.size(2);
int input_height = data.size(3);
int input_depth = data.size(1);
int output_width = (input_width - param.kernel[0] + 2 * 0/*padding*/) / 1/*stride*/ + 1;
int output_height = (input_height - param.kernel[1] + 2 * 0/*padding*/) / 1/*stride*/ + 1;
BINARY_WORD* binary_row = (BINARY_WORD*) malloc(m * n/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD));
BINARY_WORD* binary_col = (BINARY_WORD*) malloc(n * k/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD));
float* alpha_plane = (float *) malloc (param.num_filter * sizeof(float));
float* A_planes = (float *) malloc (input_width * input_height * batch_size * sizeof(float));
float* K_planes = (float *) malloc (output_width * output_height * batch_size * sizeof(float));
get_binary_row(wmat.dptr_, binary_row, m*n);
get_binary_col(in_col.dptr_, binary_col, n, k);
// alpha
get_alpha_plane(alpha_plane, wmat.dptr_, param.num_filter, param.kernel[0], param.kernel[1], input_depth);
// beta
get_A_planes(A_planes, data.dptr_, input_depth, input_width, input_height, batch_size);
get_K_planes(K_planes, A_planes, input_width, input_height, param.kernel[0], param.kernel[1], batch_size);
auto start = std::chrono::high_resolution_clock::now();
///*
xnor_gemm(m, k, n/BITS_PER_BINARY_WORD,
binary_row, n/BITS_PER_BINARY_WORD,
binary_col, k,
temp_dst.dptr_, k);
//*/
/*
//test using baseline gemm kernel
baseline_gemm(m, k, n,
wmat.dptr_, n,
in_col.dptr_, k,
temp_dst.dptr_, k);
*/
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "xnor Elapsed time: " << elapsed.count() << " s\n";
free(binary_row);
free(binary_col);
free(alpha_plane);
free(A_planes);
free(K_planes);
}
template<typename DType>
inline void QConvolutionForward(const Tensor<cpu, 4, DType> &data,
const Tensor<cpu, 2, DType> &wmat,
const Tensor<cpu, 2, DType> &in_col,
const Tensor<cpu, 2, DType> &temp_dst,
const Tensor<cpu, 4, DType> &out,
const mxnet::op::QConvolutionParam ¶m) {
CHECK(false) << "only float supported";
}
}
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(QConvolutionParam);
template<>
Operator* CreateOp<cpu>(QConvolutionParam param, int dtype,
std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape,
Context ctx) {
Operator *op = NULL;
#if MXNET_USE_MKL2017 == 1
if ((param.dilate[0] == 1 && param.dilate[1] == 1)
&& param.kernel.ndim() == 2) {
LOG(FATAL) << "QConvolution not supported with MKL";
switch (dtype) {
case mshadow::kFloat32:
return new MKLConvolutionOp<cpu, float>(param);
case mshadow::kFloat64:
return new MKLConvolutionOp<cpu, double>(param);
default:
break;
}
}
LOG(INFO) << MKLConvolutionOp<cpu, float>::getName() << " Skip MKL optimization";
#endif
#if MXNET_USE_NNPACK == 1
const size_t batch_size = (*in_shape)[0][0];
if ((param.dilate[0] == 1 && param.dilate[1] == 1)
&& param.kernel.ndim() == 2 && (!param.no_bias)
&& param.num_group == 1 && (batch_size == 1 ||
((batch_size > 1) && (param.stride[0] == 1) &&
(param.stride[1] == 1)))) {
LOG(FATAL) << "QConvolution not supported with NNPACK";
switch (dtype) {
case mshadow::kFloat32:
return new NNPACKConvolutionOp<cpu, float>(param);
default:
break;
}
}
#endif
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
op = new QConvolutionOp<cpu, DType>(param);
})
return op;
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *QConvolutionProp::CreateOperatorEx(Context ctx,
std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0], in_shape, &out_shape, ctx);
}
MXNET_REGISTER_OP_PROPERTY(QConvolution, QConvolutionProp)
.add_argument("data", "Symbol", "Input data to the ConvolutionOp.")
.add_argument("weight", "Symbol", "Weight matrix.")
.add_argument("bias", "Symbol", "Bias parameter.")
.add_arguments(QConvolutionParam::__FIELDS__())
.describe("Apply convolution to input then add a bias.");
} // namespace op
} // namespace mxnet
<|endoftext|>
|
<commit_before>
#include <stdint.h>
#include <atomic>
#include <mutex>
#include <vector>
#include <string>
#include <random>
#include <iostream>
#include <sstream>
#include <thread>
#include "ConcurrentMap.hpp"
//#include <SIM/SIM_GeneralTemplateUtil.hpp>
#ifndef PAUSE
#define PAUSE std::cout << "Paused at line " << __LINE__ << std::endl; int VAR##__LINE__; std::cin >> VAR##__LINE__;
#endif
#ifndef TO
#define TO(to, var) for(std::remove_const<decltype(to)>::type var = 0; var < to; ++var)
#endif
ui32 intHash(ui32 h)
{
//h += 1;
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
ui32 nextPowerOf2(ui32 v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
template <typename T> struct RngInt
{
std::mt19937 m_gen;
std::uniform_int_distribution<T> m_dis;
RngInt(T lo = 0, T hi = 1, int seed = 16807)
: m_gen(seed), m_dis(lo, hi)
{ }
inline T operator()()
{ return m_dis(m_gen); }
inline T operator()(T lo, T hi)
{
std::uniform_int_distribution<T> dis(lo, hi);
return dis(m_gen);
}
};
template<class STR>
STR keepAlphaNumeric(STR const& s)
{
using namespace std;
regex alphaNumeric("[a-zA-Z\\d]+");
sregex_iterator iter( ALL(s), alphaNumeric );
sregex_iterator iter_end;
STR out;
while( iter != iter_end )
out += iter++->str(); // ...
return out;
}
template<class STR1, class STR2>
STR1 subNonFilename(STR1 const& s, STR2 const& substr)
{
using namespace std;
//string patStr("[#%&\\{\\}\\\\<>\\*\\?/\\w\\$!'\":@\\+`\\|=\\.]+");
//string patStr("#|%|&|\\{|\\}|\\\\|<|>|\\*|\\?|/|\\w|\\$|!|'|\"|:|@|\\+|`|\\||=|\\.");
STR1 patStr(":|\\*|\\.|\\?|\\\\|/|\\||>|<");
regex pattern(patStr);
return regex_replace(s, pattern, substr);
}
template<class T> inline auto
Concat(const T& a) -> T
{ return a; }
template<class T1, class... T> inline auto
Concat(const T1& a, const T&... args) -> T1
{
//T1 ret;
//ret.append( ALL(a) );
//ret.append( ALL(Concat(args...)) );
return a + Concat(args...);
}
inline std::string
toString(std::vector<std::string> const& v)
{
using namespace std;
ostringstream convert;
TO(v.size(),i) convert << v[i] << " ";
convert << endl;
return convert.str();
}
template<class T> inline std::string
toString(T const& x)
{
std::ostringstream convert;
convert << x;
return convert.str();
}
template<class T1, class... T> inline std::string
toString(const T1& a, const T&... args)
{
return toString(a) + toString(args...) ;
}
template< template<class...> class L, class... T, int IDX = 0> std::string
toString(const std::tuple<T...>& tpl)
{
using namespace std;
const auto len = mp_len<T...>::value;
string ret;
ret += toString(get<IDX>(tpl), " ");
if(IDX < len-1) ret += toString(get<IDX+1>(tpl));
return ret;
}
inline std::ostream& Print(std::ostream& o) { return o; }
template<class... T> inline std::ostream&
Print(std::ostream& o, const T&... args)
{
o << toString(args ...);
o.flush();
return o;
}
template<class... T> inline std::ostream&
Println(std::ostream& o, const T&... args)
{
//o << toString(args...) << std::endl;
Print(o, args..., "\n");
return o;
}
template<class... T> inline void
Print(const T&... args)
{
Print(std::cout, args...);
//std::cout << toString(args...);
}
template<class... T> inline void
Println(const T&... args)
{
Println(std::cout, args...);
//std::cout << toString(args...) << std::endl;
}
template<class T> inline void
PrintSpaceln(const T& a)
{
Print(std::cout, a);
}
template<class T1, class... T> inline void
PrintSpaceln(const T1& a, const T&... args)
{
Print(std::cout, a, " ");
PrintSpaceln(args...);
Println();
}
template<class T, class _Alloc=std::allocator<T> >
using vec = std::vector<T, _Alloc>;
using std::thread;
int main()
{
using namespace std;
//ui32 sz = 18921703;
//ui32 sz = 400;
//ConcurrentMap cm(sz);
//ScopeTime t;
//t.start();
//cm.init(sz);
//t.stop("Init");
//Println( (i64)t.stop() );
//t.start();
//
//Println("sz: ", cm.size());
//
//TO(100,i) {
// Println("i: ",i," ", intHash(i) );
//}
//
//TO(100,i) {
// Println("i: ",i," ", nextPowerOf2(i));
//}
//ui32 loopSz = (ui32)( double(cm.size()) / 1.5);
RngInt<int> rng(1, 2);
//vec<thread> thrds;
//TO(5,tid)
//{
// thrds.push_back( thread([&cm, &rng, loopSz, tid]()
// {
// ScopeTime t;
//
// t.start();
// TO(loopSz, i) {
// auto val = i*10 + tid;
// ui32 pidx = cm.put(i, val);
// SleepMs( rng() );
//
// //SleepMs( (int)pow(4-tid,2) );
// //cout << pidx << " ";
// //Println("Put Idx: ", (i64)pidx);
// }
// t.stop("Put");
// //Println( t.getSeconds() );
//
// //t.start();
// //TO(loopSz, i) {
// // ui32 gidx = cm.get(i);
// // cout << gidx << " ";
// // //Println("Get Idx: ", (i64)gidx);
// //}
// //t.stop("Get");
// //Println( t.getSeconds() );
// })); // .detach();
// //thrds.back().detach();
//}
////for(auto& th : thrds) th.detach();
//for(auto& th : thrds) th.join();
// test getting back from the map
//t.start();
//TO(loopSz, i) {
// ui32 gidx = cm.get(i);
// cout << gidx << " ";
// //Println("Get Idx: ", (i64)gidx);
//}
//Println();
//t.stop("Get");
//RngInt<int> rngb(0,1);
//RngInt<int> rngl(0,loopSz-1);
//ConcurrentList cl(loopSz);
//// serial test of ConcurrentList
////t.start();
////TO(loopSz, i){
//// Print(cl.idx(),":", cl.alloc(), " ");
////}
////TO(loopSz, i){
//// Print(cl.idx(),":", cl.free(i), " ");
////}
////Println();
////auto lv = cl.list();
////TO(lv->size(), i){
//// Print( i,":",(*lv)[i], " ");
////}
////Println();
////t.stop("List");
//Println("\nLinks: ", cl.lnkCnt(), " ");
//vec<thread> thrds;
//TO(12,tid)
//{
// thrds.push_back( thread([&cl, &rngb, &rngl, loopSz, tid]()
// {
// ScopeTime t;
// t.start();
// TO(loopSz/5, i){
// //if(rngb())
// Print(tid,":",cl.nxt()," ");
// //else Print(tid,":",cl.free(rngl()), " ");
// SleepMs( rngb() );
// }
// t.stop("alloc/free");
// }));
//}
//for(auto& th : thrds) th.join();
//Println();
//auto lv = cl.list();
//TO(lv->size(), i){
// Print( i,":",(*lv)[i], " ");
//}
//Println();
//Println("\nLinks: ", cl.lnkCnt(), " ");
//i32 blkSz = 5;
//i32 blocks = 2;
//vec<ui8> mem(blocks*blkSz, 0);
//ConcurrentStore cs(mem.data(), blkSz, (ui32)(blocks) );
//
//Println("\n");
//
//TO(cs.m_cl.list()->size(), i){
// Println( (*cs.m_cl.list())[i] );
//}
//Println("\n\n");
//
//TO(2,i){
// i32 blks = 0;
// auto s = "w";
// i32 slen = (i32)strlen(s)+1;
// //i32 slen = 1;
// auto idx = cs.alloc(slen, &blks); // must allocate the exact number of bytes and no more, since that number will be used to read and write
// cs.put(idx, (void*)s, slen);
//
// vec<char> gs(slen,0);
// cs.get(idx, gs.data(), slen);
// Println(gs.data());
// cs.free(idx);
//
// TO(cs.m_blockCount, b){
// Println(cs.nxtBlock(b));
// }
// Println("\n\n");
// TO(cs.m_cl.list()->size(), i){
// Println( (*cs.m_cl.list())[i] );
// }
// Println("\n\n");
//
//}
//ConcurrentHash ch(64);
//vec<thread> thrds;
//TO(24,tid)
//{
// thrds.push_back( thread([&ch, &rng, tid]()
// {
// TO(64,h)
// {
// ch.put(h, h*h);
// //Print(h,": ", ch.put(h, h*h) );
// Print(h,":", ch.get(h)==h*h, " ");
// }
// } ));
// thrds.back().detach();
//}
SimDB db(16, 4);
str wat = "wat";
str skidoosh = "skidoosh";
str kablam = "kablam";
Println("put: ", db.put( (void*)wat.data(), (ui32)wat.length(), (void*)skidoosh.data(), (ui32)skidoosh.length()) );
Println("put: ", db.put( (void*)wat.data(), (ui32)wat.length(), (void*)kablam.data(), (ui32)kablam.length()) );
auto idx = db.get((void*)wat.data(), (ui32)wat.length());
Println("get: ", idx);
str clear = " ";
db.get(idx, (void*)clear.data() );
Println("get: ", clear);
PAUSE
return 0;
}
//struct keyval
//{
// uint64_t readers : 4;
// uint64_t key : 28;
// uint64_t val : 28;
//};
//Println("kv size: ", sizeof(ConcurrentHash::kv) );
//Println("kv size: ", sizeof(keyval) );
//Println("ui64 size: ", sizeof(ui64) );
//Aui32* key_addr = (Aui32*)(&m_keys.get()[i]);
//ui32 probedKey = atomic_load( key_addr );
//atomic_store( (Aui32*)(&m_vals.get()[i]), val);
//ui32 i = 0;
//for(; i < m_sz; ++i)
//copy( m_keys.get(), m_keys.get()+sz, EMPTY_KEY );
//copy( m_keys.get(), m_keys.get()+sz, EMPTY_KEY );
//m_keys.get()[i] = EMPTY_KEY;
//m_vals.get()[i] = EMPTY_KEY;
//~ConcurrentMap()
//{
// //m_mut.unlock(); // if this is already unlocked, will this crash?
//}
//using Keys = std::vector<ui32>;
//using Values = std::vector<ui32>;
//ui32 put(ui32 key, ui32 val) const
//{
// using namespace std;
//
// ui32 empty_ref = EMPTY_KEY;
//
// for(ui32 i=0; true; ++i)
// {
// ui32 prevKey = m_keys[i].compare_exchange_strong(empty_ref,key); // mint_compare_exchange_strong_32_relaxed(&m_entries[idx].key, 0, key);
// if( (prevKey==0) || (prevKey==key))
// {
// m_vals[i].store(val);
// return i;
// }
// }
//}
<commit_msg>more key value tests<commit_after>
#include <stdint.h>
#include <atomic>
#include <mutex>
#include <vector>
#include <string>
#include <random>
#include <iostream>
#include <sstream>
#include <thread>
#include "ConcurrentMap.hpp"
//#include <SIM/SIM_GeneralTemplateUtil.hpp>
#ifndef PAUSE
#define PAUSE std::cout << "Paused at line " << __LINE__ << std::endl; int VAR##__LINE__; std::cin >> VAR##__LINE__;
#endif
#ifndef TO
#define TO(to, var) for(std::remove_const<decltype(to)>::type var = 0; var < to; ++var)
#endif
ui32 intHash(ui32 h)
{
//h += 1;
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
ui32 nextPowerOf2(ui32 v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
template <typename T> struct RngInt
{
std::mt19937 m_gen;
std::uniform_int_distribution<T> m_dis;
RngInt(T lo = 0, T hi = 1, int seed = 16807)
: m_gen(seed), m_dis(lo, hi)
{ }
inline T operator()()
{ return m_dis(m_gen); }
inline T operator()(T lo, T hi)
{
std::uniform_int_distribution<T> dis(lo, hi);
return dis(m_gen);
}
};
template<class STR>
STR keepAlphaNumeric(STR const& s)
{
using namespace std;
regex alphaNumeric("[a-zA-Z\\d]+");
sregex_iterator iter( ALL(s), alphaNumeric );
sregex_iterator iter_end;
STR out;
while( iter != iter_end )
out += iter++->str(); // ...
return out;
}
template<class STR1, class STR2>
STR1 subNonFilename(STR1 const& s, STR2 const& substr)
{
using namespace std;
//string patStr("[#%&\\{\\}\\\\<>\\*\\?/\\w\\$!'\":@\\+`\\|=\\.]+");
//string patStr("#|%|&|\\{|\\}|\\\\|<|>|\\*|\\?|/|\\w|\\$|!|'|\"|:|@|\\+|`|\\||=|\\.");
STR1 patStr(":|\\*|\\.|\\?|\\\\|/|\\||>|<");
regex pattern(patStr);
return regex_replace(s, pattern, substr);
}
template<class T> inline auto
Concat(const T& a) -> T
{ return a; }
template<class T1, class... T> inline auto
Concat(const T1& a, const T&... args) -> T1
{
//T1 ret;
//ret.append( ALL(a) );
//ret.append( ALL(Concat(args...)) );
return a + Concat(args...);
}
inline std::string
toString(std::vector<std::string> const& v)
{
using namespace std;
ostringstream convert;
TO(v.size(),i) convert << v[i] << " ";
convert << endl;
return convert.str();
}
template<class T> inline std::string
toString(T const& x)
{
std::ostringstream convert;
convert << x;
return convert.str();
}
template<class T1, class... T> inline std::string
toString(const T1& a, const T&... args)
{
return toString(a) + toString(args...) ;
}
template< template<class...> class L, class... T, int IDX = 0> std::string
toString(const std::tuple<T...>& tpl)
{
using namespace std;
const auto len = mp_len<T...>::value;
string ret;
ret += toString(get<IDX>(tpl), " ");
if(IDX < len-1) ret += toString(get<IDX+1>(tpl));
return ret;
}
inline std::ostream& Print(std::ostream& o) { return o; }
template<class... T> inline std::ostream&
Print(std::ostream& o, const T&... args)
{
o << toString(args ...);
o.flush();
return o;
}
template<class... T> inline std::ostream&
Println(std::ostream& o, const T&... args)
{
//o << toString(args...) << std::endl;
Print(o, args..., "\n");
return o;
}
template<class... T> inline void
Print(const T&... args)
{
Print(std::cout, args...);
//std::cout << toString(args...);
}
template<class... T> inline void
Println(const T&... args)
{
Println(std::cout, args...);
//std::cout << toString(args...) << std::endl;
}
template<class T> inline void
PrintSpaceln(const T& a)
{
Print(std::cout, a);
}
template<class T1, class... T> inline void
PrintSpaceln(const T1& a, const T&... args)
{
Print(std::cout, a, " ");
PrintSpaceln(args...);
Println();
}
template<class T, class _Alloc=std::allocator<T> >
using vec = std::vector<T, _Alloc>;
using std::thread;
int main()
{
using namespace std;
//ui32 sz = 18921703;
//ui32 sz = 400;
//ConcurrentMap cm(sz);
//ScopeTime t;
//t.start();
//cm.init(sz);
//t.stop("Init");
//Println( (i64)t.stop() );
//t.start();
//
//Println("sz: ", cm.size());
//
//TO(100,i) {
// Println("i: ",i," ", intHash(i) );
//}
//
//TO(100,i) {
// Println("i: ",i," ", nextPowerOf2(i));
//}
//ui32 loopSz = (ui32)( double(cm.size()) / 1.5);
RngInt<int> rng(1, 2);
//vec<thread> thrds;
//TO(5,tid)
//{
// thrds.push_back( thread([&cm, &rng, loopSz, tid]()
// {
// ScopeTime t;
//
// t.start();
// TO(loopSz, i) {
// auto val = i*10 + tid;
// ui32 pidx = cm.put(i, val);
// SleepMs( rng() );
//
// //SleepMs( (int)pow(4-tid,2) );
// //cout << pidx << " ";
// //Println("Put Idx: ", (i64)pidx);
// }
// t.stop("Put");
// //Println( t.getSeconds() );
//
// //t.start();
// //TO(loopSz, i) {
// // ui32 gidx = cm.get(i);
// // cout << gidx << " ";
// // //Println("Get Idx: ", (i64)gidx);
// //}
// //t.stop("Get");
// //Println( t.getSeconds() );
// })); // .detach();
// //thrds.back().detach();
//}
////for(auto& th : thrds) th.detach();
//for(auto& th : thrds) th.join();
// test getting back from the map
//t.start();
//TO(loopSz, i) {
// ui32 gidx = cm.get(i);
// cout << gidx << " ";
// //Println("Get Idx: ", (i64)gidx);
//}
//Println();
//t.stop("Get");
//RngInt<int> rngb(0,1);
//RngInt<int> rngl(0,loopSz-1);
//ConcurrentList cl(loopSz);
//// serial test of ConcurrentList
////t.start();
////TO(loopSz, i){
//// Print(cl.idx(),":", cl.alloc(), " ");
////}
////TO(loopSz, i){
//// Print(cl.idx(),":", cl.free(i), " ");
////}
////Println();
////auto lv = cl.list();
////TO(lv->size(), i){
//// Print( i,":",(*lv)[i], " ");
////}
////Println();
////t.stop("List");
//Println("\nLinks: ", cl.lnkCnt(), " ");
//vec<thread> thrds;
//TO(12,tid)
//{
// thrds.push_back( thread([&cl, &rngb, &rngl, loopSz, tid]()
// {
// ScopeTime t;
// t.start();
// TO(loopSz/5, i){
// //if(rngb())
// Print(tid,":",cl.nxt()," ");
// //else Print(tid,":",cl.free(rngl()), " ");
// SleepMs( rngb() );
// }
// t.stop("alloc/free");
// }));
//}
//for(auto& th : thrds) th.join();
//Println();
//auto lv = cl.list();
//TO(lv->size(), i){
// Print( i,":",(*lv)[i], " ");
//}
//Println();
//Println("\nLinks: ", cl.lnkCnt(), " ");
//i32 blkSz = 5;
//i32 blocks = 2;
//vec<ui8> mem(blocks*blkSz, 0);
//ConcurrentStore cs(mem.data(), blkSz, (ui32)(blocks) );
//
//Println("\n");
//
//TO(cs.m_cl.list()->size(), i){
// Println( (*cs.m_cl.list())[i] );
//}
//Println("\n\n");
//
//TO(2,i){
// i32 blks = 0;
// auto s = "w";
// i32 slen = (i32)strlen(s)+1;
// //i32 slen = 1;
// auto idx = cs.alloc(slen, &blks); // must allocate the exact number of bytes and no more, since that number will be used to read and write
// cs.put(idx, (void*)s, slen);
//
// vec<char> gs(slen,0);
// cs.get(idx, gs.data(), slen);
// Println(gs.data());
// cs.free(idx);
//
// TO(cs.m_blockCount, b){
// Println(cs.nxtBlock(b));
// }
// Println("\n\n");
// TO(cs.m_cl.list()->size(), i){
// Println( (*cs.m_cl.list())[i] );
// }
// Println("\n\n");
//
//}
//ConcurrentHash ch(64);
//vec<thread> thrds;
//TO(24,tid)
//{
// thrds.push_back( thread([&ch, &rng, tid]()
// {
// TO(64,h)
// {
// ch.put(h, h*h);
// //Print(h,": ", ch.put(h, h*h) );
// Print(h,":", ch.get(h)==h*h, " ");
// }
// } ));
// thrds.back().detach();
//}
SimDB db(16, 8);
str wat = "wat";
str skidoosh = "skidoosh";
str kablam = "kablam";
Println("put: ", db.put( (void*)wat.data(), (ui32)wat.length(), (void*)skidoosh.data(), (ui32)skidoosh.length()) );
Println("put: ", db.put( (void*)wat.data(), (ui32)wat.length(), (void*)kablam.data(), (ui32)kablam.length()) );
Println("put: ", db.put( (void*)kablam.data(), (ui32)kablam.length(), (void*)skidoosh.data(), (ui32)skidoosh.length()) );
auto idx = db.get((void*)wat.data(), (ui32)wat.length());
Println("get: ", idx);
str clear = " ";
db.get(idx, (void*)clear.data() );
Println("get: ", clear);
auto idx2 = db.get((void*)kablam.data(), (ui32)kablam.length());
Println("get: ", idx2);
db.get(idx2, (void*)clear.data() );
Println("get: ", clear);
PAUSE
return 0;
}
//struct keyval
//{
// uint64_t readers : 4;
// uint64_t key : 28;
// uint64_t val : 28;
//};
//Println("kv size: ", sizeof(ConcurrentHash::kv) );
//Println("kv size: ", sizeof(keyval) );
//Println("ui64 size: ", sizeof(ui64) );
//Aui32* key_addr = (Aui32*)(&m_keys.get()[i]);
//ui32 probedKey = atomic_load( key_addr );
//atomic_store( (Aui32*)(&m_vals.get()[i]), val);
//ui32 i = 0;
//for(; i < m_sz; ++i)
//copy( m_keys.get(), m_keys.get()+sz, EMPTY_KEY );
//copy( m_keys.get(), m_keys.get()+sz, EMPTY_KEY );
//m_keys.get()[i] = EMPTY_KEY;
//m_vals.get()[i] = EMPTY_KEY;
//~ConcurrentMap()
//{
// //m_mut.unlock(); // if this is already unlocked, will this crash?
//}
//using Keys = std::vector<ui32>;
//using Values = std::vector<ui32>;
//ui32 put(ui32 key, ui32 val) const
//{
// using namespace std;
//
// ui32 empty_ref = EMPTY_KEY;
//
// for(ui32 i=0; true; ++i)
// {
// ui32 prevKey = m_keys[i].compare_exchange_strong(empty_ref,key); // mint_compare_exchange_strong_32_relaxed(&m_entries[idx].key, 0, key);
// if( (prevKey==0) || (prevKey==key))
// {
// m_vals[i].store(val);
// return i;
// }
// }
//}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.