text stringlengths 54 60.6k |
|---|
<commit_before>#include <graphics/buffer/buffer.h>
#include <core/video/context.h>
#include <core/log/log.h>
namespace fd {
namespace graphics {
namespace buffer {
using namespace core;
using namespace video;
using namespace log;
Buffer::Buffer(VkBufferUsageFlags usage, const void* const data, uint64 size, bool dynamic) : size(size), dynamic(dynamic) {
VkBufferCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
info.pNext = nullptr;
info.flags = 0;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.usage = dynamic ? usage : VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
info.size = size;
info.queueFamilyIndexCount = 0;
info.pQueueFamilyIndices = nullptr;
VkBuffer tmpBuf;
VkDeviceMemory tmpMemory;
VK(vkCreateBuffer(Context::GetDevice(), &info, nullptr, &tmpBuf));
VkMemoryRequirements req;
vkGetBufferMemoryRequirements(Context::GetDevice(), tmpBuf, &req);
const VkPhysicalDeviceMemoryProperties mem = Context::GetAdapter()->GetMemoryProperties();
uint32 memIndex = FindMemoryType(mem, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VkMemoryAllocateInfo ainfo;
ainfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
ainfo.pNext = nullptr;
ainfo.memoryTypeIndex = memIndex;
ainfo.allocationSize = req.size;
VK(vkAllocateMemory(Context::GetDevice(), &ainfo, nullptr, &tmpMemory));
VK(vkBindBufferMemory(Context::GetDevice(), tmpBuf, tmpMemory, 0));
void* dank = nullptr;
VK(vkMapMemory(Context::GetDevice(), tmpMemory, 0, size, 0, &dank));
if (data) memcpy(dank, data, size);
vkUnmapMemory(Context::GetDevice(), tmpMemory);
if (dynamic) {
buf = tmpBuf;
deviceMemory = tmpMemory;
}else {
info.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VK(vkCreateBuffer(Context::GetDevice(), &info, nullptr, &buf));
vkGetBufferMemoryRequirements(Context::GetDevice(), buf, &req);
memIndex = FindMemoryType(mem, req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
ainfo.memoryTypeIndex = memIndex;
ainfo.allocationSize = req.size;
VK(vkAllocateMemory(Context::GetDevice(), &ainfo, nullptr, &deviceMemory));
VK(vkBindBufferMemory(Context::GetDevice(), buf, deviceMemory, 0));
Context::CopyBuffers(&buf, &tmpBuf, &size, 1);
vkDestroyBuffer(Context::GetDevice(), tmpBuf, nullptr);
vkFreeMemory(Context::GetDevice(), tmpMemory, nullptr);
}
}
Buffer::~Buffer() {
vkDestroyBuffer(Context::GetDevice(), buf, nullptr);
vkFreeMemory(Context::GetDevice(), deviceMemory, nullptr);
}
void* Buffer::Map(uint64 offset, uint64 size) {
#ifdef FD_DEBUG
if (!dynamic) {
FD_FATAL("[Buffer] Buffer not mappable!");
return nullptr;
}
if (offset + size > this->size) {
FD_FATAL("[Buffer] Buffer mapping out of bounds! Offset(%u) + size(%u) > buffer size(%u)", offset, size, this->size);
return nullptr;
}
#endif
void* mappedData = nullptr;
VK(vkMapMemory(Context::GetDevice(), deviceMemory, offset, size, 0, &mappedData));
return mappedData;
}
void Buffer::Unmap() {
vkUnmapMemory(Context::GetDevice(), deviceMemory);
}
uint32 FindMemoryType(const VkPhysicalDeviceMemoryProperties mem, uint32 type, uint32 prop) {
for (uint32 i = 0; i < mem.memoryTypeCount; i++) {
if ((type & (1 << i)) && ((mem.memoryTypes[i].propertyFlags & prop) == prop)) return i;
}
return ~0;
}
uint8 GetFormatSize(VkFormat format) {
if (format >= VK_FORMAT_R8_UNORM && format <= VK_FORMAT_R8_SRGB) {
return 1;
} else if (format >= VK_FORMAT_R8G8_UNORM && format <= VK_FORMAT_R8G8_SRGB) {
return 2;
} else if (format >= VK_FORMAT_R8G8B8_UNORM && format <= VK_FORMAT_B8G8R8_SRGB) {
return 3;
} else if (format >= VK_FORMAT_R8G8B8A8_UNORM && format <= VK_FORMAT_B8G8R8A8_SRGB) {
return 4;
} else if (format >= VK_FORMAT_R16_UNORM && format <= VK_FORMAT_R16_SFLOAT) {
return 2;
} else if (format >= VK_FORMAT_R16G16_UNORM && format <= VK_FORMAT_R16G16_SFLOAT) {
return 4;
} else if (format >= VK_FORMAT_R16G16B16_UNORM && format <= VK_FORMAT_R16G16B16_SFLOAT) {
return 6;
} else if (format >= VK_FORMAT_R16G16B16A16_UNORM && format <= VK_FORMAT_R16G16B16A16_SFLOAT) {
return 8;
} else if (format >= VK_FORMAT_R32_UINT && format <= VK_FORMAT_R32_SFLOAT) {
return 4;
} else if (format >= VK_FORMAT_R32G32_UINT && format <= VK_FORMAT_R32G32_SFLOAT) {
return 8;
} else if (format >= VK_FORMAT_R32G32B32_UINT && format <= VK_FORMAT_R32G32B32_SFLOAT) {
return 12;
} else if (format >= VK_FORMAT_R32G32B32A32_UINT && format <= VK_FORMAT_R32G32B32A32_SFLOAT) {
return 16;
} else if (format >= VK_FORMAT_R64_UINT && format <= VK_FORMAT_R64_SFLOAT) {
return 8;
} else if (format >= VK_FORMAT_R64G64_UINT && format <= VK_FORMAT_R64G64_SFLOAT) {
return 16;
} else if (format >= VK_FORMAT_R64G64B64_UINT && format <= VK_FORMAT_R64G64B64_SFLOAT) {
return 24;
} else if (format >= VK_FORMAT_R64G64B64A64_UINT && format <= VK_FORMAT_R64G64B64A64_SFLOAT) {
return 32;
}
return 0;
}
}
}
}<commit_msg>Fixed usage error<commit_after>#include <graphics/buffer/buffer.h>
#include <core/video/context.h>
#include <core/log/log.h>
namespace fd {
namespace graphics {
namespace buffer {
using namespace core;
using namespace video;
using namespace log;
Buffer::Buffer(VkBufferUsageFlags usage, const void* const data, uint64 size, bool dynamic) : size(size), dynamic(dynamic) {
VkBufferCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
info.pNext = nullptr;
info.flags = 0;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.usage = dynamic ? usage : VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
info.size = size;
info.queueFamilyIndexCount = 0;
info.pQueueFamilyIndices = nullptr;
VkBuffer tmpBuf;
VkDeviceMemory tmpMemory;
VK(vkCreateBuffer(Context::GetDevice(), &info, nullptr, &tmpBuf));
VkMemoryRequirements req;
vkGetBufferMemoryRequirements(Context::GetDevice(), tmpBuf, &req);
const VkPhysicalDeviceMemoryProperties mem = Context::GetAdapter()->GetMemoryProperties();
uint32 memIndex = FindMemoryType(mem, req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VkMemoryAllocateInfo ainfo;
ainfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
ainfo.pNext = nullptr;
ainfo.memoryTypeIndex = memIndex;
ainfo.allocationSize = req.size;
VK(vkAllocateMemory(Context::GetDevice(), &ainfo, nullptr, &tmpMemory));
VK(vkBindBufferMemory(Context::GetDevice(), tmpBuf, tmpMemory, 0));
void* dank = nullptr;
VK(vkMapMemory(Context::GetDevice(), tmpMemory, 0, size, 0, &dank));
if (data) memcpy(dank, data, size);
vkUnmapMemory(Context::GetDevice(), tmpMemory);
if (dynamic) {
buf = tmpBuf;
deviceMemory = tmpMemory;
}else {
info.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT | usage;
VK(vkCreateBuffer(Context::GetDevice(), &info, nullptr, &buf));
vkGetBufferMemoryRequirements(Context::GetDevice(), buf, &req);
memIndex = FindMemoryType(mem, req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
ainfo.memoryTypeIndex = memIndex;
ainfo.allocationSize = req.size;
VK(vkAllocateMemory(Context::GetDevice(), &ainfo, nullptr, &deviceMemory));
VK(vkBindBufferMemory(Context::GetDevice(), buf, deviceMemory, 0));
Context::CopyBuffers(&buf, &tmpBuf, &size, 1);
vkDestroyBuffer(Context::GetDevice(), tmpBuf, nullptr);
vkFreeMemory(Context::GetDevice(), tmpMemory, nullptr);
}
}
Buffer::~Buffer() {
vkDestroyBuffer(Context::GetDevice(), buf, nullptr);
vkFreeMemory(Context::GetDevice(), deviceMemory, nullptr);
}
void* Buffer::Map(uint64 offset, uint64 size) {
#ifdef FD_DEBUG
if (!dynamic) {
FD_FATAL("[Buffer] Buffer not mappable!");
return nullptr;
}
if (offset + size > this->size) {
FD_FATAL("[Buffer] Buffer mapping out of bounds! Offset(%u) + size(%u) > buffer size(%u)", offset, size, this->size);
return nullptr;
}
#endif
void* mappedData = nullptr;
VK(vkMapMemory(Context::GetDevice(), deviceMemory, offset, size, 0, &mappedData));
return mappedData;
}
void Buffer::Unmap() {
vkUnmapMemory(Context::GetDevice(), deviceMemory);
}
uint32 FindMemoryType(const VkPhysicalDeviceMemoryProperties mem, uint32 type, uint32 prop) {
for (uint32 i = 0; i < mem.memoryTypeCount; i++) {
if ((type & (1 << i)) && ((mem.memoryTypes[i].propertyFlags & prop) == prop)) return i;
}
return ~0;
}
uint8 GetFormatSize(VkFormat format) {
if (format >= VK_FORMAT_R8_UNORM && format <= VK_FORMAT_R8_SRGB) {
return 1;
} else if (format >= VK_FORMAT_R8G8_UNORM && format <= VK_FORMAT_R8G8_SRGB) {
return 2;
} else if (format >= VK_FORMAT_R8G8B8_UNORM && format <= VK_FORMAT_B8G8R8_SRGB) {
return 3;
} else if (format >= VK_FORMAT_R8G8B8A8_UNORM && format <= VK_FORMAT_B8G8R8A8_SRGB) {
return 4;
} else if (format >= VK_FORMAT_R16_UNORM && format <= VK_FORMAT_R16_SFLOAT) {
return 2;
} else if (format >= VK_FORMAT_R16G16_UNORM && format <= VK_FORMAT_R16G16_SFLOAT) {
return 4;
} else if (format >= VK_FORMAT_R16G16B16_UNORM && format <= VK_FORMAT_R16G16B16_SFLOAT) {
return 6;
} else if (format >= VK_FORMAT_R16G16B16A16_UNORM && format <= VK_FORMAT_R16G16B16A16_SFLOAT) {
return 8;
} else if (format >= VK_FORMAT_R32_UINT && format <= VK_FORMAT_R32_SFLOAT) {
return 4;
} else if (format >= VK_FORMAT_R32G32_UINT && format <= VK_FORMAT_R32G32_SFLOAT) {
return 8;
} else if (format >= VK_FORMAT_R32G32B32_UINT && format <= VK_FORMAT_R32G32B32_SFLOAT) {
return 12;
} else if (format >= VK_FORMAT_R32G32B32A32_UINT && format <= VK_FORMAT_R32G32B32A32_SFLOAT) {
return 16;
} else if (format >= VK_FORMAT_R64_UINT && format <= VK_FORMAT_R64_SFLOAT) {
return 8;
} else if (format >= VK_FORMAT_R64G64_UINT && format <= VK_FORMAT_R64G64_SFLOAT) {
return 16;
} else if (format >= VK_FORMAT_R64G64B64_UINT && format <= VK_FORMAT_R64G64B64_SFLOAT) {
return 24;
} else if (format >= VK_FORMAT_R64G64B64A64_UINT && format <= VK_FORMAT_R64G64B64A64_SFLOAT) {
return 32;
}
return 0;
}
}
}
}<|endoftext|> |
<commit_before>// Created on: 2002-04-12
// Created by: Alexander GRIGORIEV
// Copyright (c) 2002-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef NCollection_IncAllocator_HeaderFile
#define NCollection_IncAllocator_HeaderFile
#include <NCollection_BaseAllocator.hxx>
/**
* Class NCollection_IncAllocator - incremental memory allocator. This class
* allocates memory on request returning the pointer to an allocated
* block. This memory is never returned to the system until the allocator is
* destroyed.
*
* By comparison with the standard new() and malloc() calls, this method is
* faster and consumes very small additional memory to maintain the heap.
*
* All pointers returned by Allocate() are aligned to the size of the data
* type "aligned_t". To modify the size of memory blocks requested from the
* OS, use the parameter of the constructor (measured in bytes); if this
* parameter is smaller than 25 bytes on 32bit or 49 bytes on 64bit, the
* block size will be the default 24 kbytes
*/
class NCollection_IncAllocator : public NCollection_BaseAllocator
{
public:
// The type defining the alignement of allocated objects
typedef void * aligned_t;
// ---------- PUBLIC METHODS ----------
//! Constructor
Standard_EXPORT NCollection_IncAllocator (const size_t theBlockSize = DefaultBlockSize);
//! Allocate memory with given size. Returns NULL on failure
Standard_EXPORT virtual void* Allocate (const size_t size);
//! Free a previously allocated memory. Does nothing
Standard_EXPORT virtual void Free (void *anAddress);
//! Diagnostic method, returns the total allocated size
Standard_EXPORT size_t GetMemSize () const;
//! Destructor (calls Clean() internally)
Standard_EXPORT ~NCollection_IncAllocator ();
//! Reallocation: it is always allowed but is only efficient with the
//! last allocated item
Standard_EXPORT void * Reallocate (void * anAddress,
const size_t oldSize,
const size_t newSize);
//! Re-initialize the allocator so that the next Allocate call should
//! start allocating in the very begining as though the allocator is just
//! constructed. Warning: make sure that all previously allocated data are
//! no more used in your code!
//! @param doReleaseMem
//! True - release all previously allocated memory, False - preserve it
//! for future allocations.
Standard_EXPORT void Reset (const Standard_Boolean
doReleaseMem=Standard_True);
static const size_t DefaultBlockSize = 24600;
protected:
struct IBlock;
//! Flush all previously allocated data. All pointers returned by
//! Allocate() become invalid -- be very careful with this
Standard_EXPORT void Clean ();
//! Allocate a new block and return a pointer to it
//! ** only for internal usage **
void * allocateNewBlock (const size_t cSize);
private:
// Prohibited methods
NCollection_IncAllocator (const NCollection_IncAllocator&);
NCollection_IncAllocator& operator = (const NCollection_IncAllocator&);
protected:
// ----- PROTECTED CLASS IBlock -------
struct IBlock {
aligned_t * allocateInBlock (const size_t cSize)
{
aligned_t * aResult = p_free_space;
p_free_space += cSize;
return aResult;
}
aligned_t * p_free_space;
aligned_t * p_end_block;
struct IBlock * p_next;
};
protected:
// --------- PROTECTED FIELDS ---------
IBlock * myFirstBlock;
size_t mySize;
size_t myMemSize;
public:
// Declaration of CASCADE RTTI
DEFINE_STANDARD_RTTI (NCollection_IncAllocator)
};
// Definition of HANDLE object using Standard_DefineHandle.hxx
DEFINE_STANDARD_HANDLE (NCollection_IncAllocator, NCollection_BaseAllocator)
#endif
<commit_msg>ports/force-8byte-alignment<commit_after>// Created on: 2002-04-12
// Created by: Alexander GRIGORIEV
// Copyright (c) 2002-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef NCollection_IncAllocator_HeaderFile
#define NCollection_IncAllocator_HeaderFile
#include <NCollection_BaseAllocator.hxx>
#if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef unsigned __int64 uint64_t;
#elif defined(__hpux) && !defined(__GNUC__)
# include <inttypes.h>
#else
# include <stdint.h>
#endif
/**
* Class NCollection_IncAllocator - incremental memory allocator. This class
* allocates memory on request returning the pointer to an allocated
* block. This memory is never returned to the system until the allocator is
* destroyed.
*
* By comparison with the standard new() and malloc() calls, this method is
* faster and consumes very small additional memory to maintain the heap.
*
* All pointers returned by Allocate() are aligned to the size of the data
* type "aligned_t". To modify the size of memory blocks requested from the
* OS, use the parameter of the constructor (measured in bytes); if this
* parameter is smaller than 25 bytes on 32bit or 49 bytes on 64bit, the
* block size will be the default 24 kbytes
*/
class NCollection_IncAllocator : public NCollection_BaseAllocator
{
public:
// The type defining the alignement of allocated objects
typedef uint64_t aligned_t;
// ---------- PUBLIC METHODS ----------
//! Constructor
Standard_EXPORT NCollection_IncAllocator (const size_t theBlockSize = DefaultBlockSize);
//! Allocate memory with given size. Returns NULL on failure
Standard_EXPORT virtual void* Allocate (const size_t size);
//! Free a previously allocated memory. Does nothing
Standard_EXPORT virtual void Free (void *anAddress);
//! Diagnostic method, returns the total allocated size
Standard_EXPORT size_t GetMemSize () const;
//! Destructor (calls Clean() internally)
Standard_EXPORT ~NCollection_IncAllocator ();
//! Reallocation: it is always allowed but is only efficient with the
//! last allocated item
Standard_EXPORT void * Reallocate (void * anAddress,
const size_t oldSize,
const size_t newSize);
//! Re-initialize the allocator so that the next Allocate call should
//! start allocating in the very begining as though the allocator is just
//! constructed. Warning: make sure that all previously allocated data are
//! no more used in your code!
//! @param doReleaseMem
//! True - release all previously allocated memory, False - preserve it
//! for future allocations.
Standard_EXPORT void Reset (const Standard_Boolean
doReleaseMem=Standard_True);
static const size_t DefaultBlockSize = 24600;
protected:
struct IBlock;
//! Flush all previously allocated data. All pointers returned by
//! Allocate() become invalid -- be very careful with this
Standard_EXPORT void Clean ();
//! Allocate a new block and return a pointer to it
//! ** only for internal usage **
void * allocateNewBlock (const size_t cSize);
private:
// Prohibited methods
NCollection_IncAllocator (const NCollection_IncAllocator&);
NCollection_IncAllocator& operator = (const NCollection_IncAllocator&);
protected:
// ----- PROTECTED CLASS IBlock -------
struct IBlock {
aligned_t * allocateInBlock (const size_t cSize)
{
aligned_t * aResult = p_free_space;
p_free_space += cSize;
return aResult;
}
aligned_t * p_free_space;
aligned_t * p_end_block;
struct IBlock * p_next;
};
protected:
// --------- PROTECTED FIELDS ---------
IBlock * myFirstBlock;
size_t mySize;
size_t myMemSize;
public:
// Declaration of CASCADE RTTI
DEFINE_STANDARD_RTTI (NCollection_IncAllocator)
};
// Definition of HANDLE object using Standard_DefineHandle.hxx
DEFINE_STANDARD_HANDLE (NCollection_IncAllocator, NCollection_BaseAllocator)
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <unordered_map>
#include <math.h>
#include <utility>
#include <thread>
#include <stdexcept>
#include <ostream>
#include "random.hpp"
using Random = effolkronium::random_thread_local;
#include "neuron.hpp"
#include "network.hpp"
Neuron::Neuron(Network& network)
{
this->network = &network;
this->network->neurons.push_back(this);
}
void Neuron::partially_subscribe()
{
if (this->subscriptions.size() == 0) {
unsigned seed = std::chrono::system_clock::now()
.time_since_epoch().count();
std::default_random_engine generator (seed);
std::normal_distribution<double> distribution(
this->network->connectivity,
this->network->connectivity_sqrt
);
unsigned int sample_length = distribution(generator);
if (sample_length > this->network->nonmotor_neurons.size())
sample_length = this->network->nonmotor_neurons.size();
if (sample_length <= 0)
sample_length = 0;
std::vector<Neuron*> elected = random_sample(
this->network->nonmotor_neurons,
sample_length
);
for (auto const& target_neuron: elected) {
if (target_neuron != this) {
this->subscriptions.insert(
std::pair<Neuron*, double>(
target_neuron,
Random::get(-1.0, 1.0)
)
);
target_neuron->publications.insert(
std::pair<Neuron*, double>(this, 0.0)
);
}
}
this->network->increase_initiated_neurons();
}
}
double Neuron::calculate_potential() const
{
double total = 0;
for (auto const& it: this->subscriptions) {
total += it.first->potential * it.second;
}
return this->activation_function(total);
}
double Neuron::activation_function(double x) const
{
return 1 / (1 + exp(-x));
}
double Neuron::derivative(double x) const
{
return x * (1 - x);
}
double Neuron::calculate_loss() const
{
try {
return this->potential - this->desired_potential;
} catch (const std::exception& e) {
return 0;
}
}
bool Neuron::fire()
{
if (this->type != SENSORY_NEURON) {
this->potential = this->calculate_potential();
this->network->fire_counter++;
this->fire_counter++;
if (this->desired_potential) {
this->loss = this->calculate_loss();
int alteration_sign;
if (this->loss > 0) {
alteration_sign = -1;
} else if (this->loss < 0) {
alteration_sign = 1;
} else {
this->desired_potential = NULL;
return true;
}
double alteration_value = pow(fabs(this->loss), 2);
alteration_value = alteration_value * pow(
this->network->decay_factor,
(this->network->fire_counter/1000)
);
for (auto& it: this->subscriptions) {
it.first->desired_potential = it.first->potential
+ alteration_sign
* this->derivative(it.first->potential);
this->subscriptions[it.first] = it.second
+ (alteration_value * alteration_sign)
* this->derivative(it.first->potential);
}
}
}
}
Network::Network(
int size,
int input_dim = 0,
int output_dim = 0,
double connectivity = 0.01,
int precision = 2,
bool randomly_fire = false,
bool dynamic_output = false,
bool visualization = false,
double decay_factor = 1.0
)
{
this->precision = precision;
std::cout << "\nPrecision of the network will be "
<< 1.0 / pow(10, precision) << '\n';
this->connectivity = static_cast<int>(size * connectivity);
this->connectivity_sqrt = static_cast<int>(sqrt(this->connectivity));
std::cout << "Each individual non-sensory neuron will subscribe to "
<< this->connectivity << " different neurons" << '\n';
this->neurons.reserve(size);
for (int i = 0; i < size; i++) {
new Neuron(*this);
}
std::cout << size << " neurons created" << '\n';
this->input_dim = input_dim;
this->sensory_neurons.reserve(this->input_dim);
this->pick_neurons_by_type(this->input_dim, SENSORY_NEURON);
this->output_dim = output_dim;
this->motor_neurons.reserve(this->output_dim);
this->pick_neurons_by_type(this->output_dim, MOTOR_NEURON);
this->get_neurons_by_type(NON_SENSORY_NEURON);
this->get_neurons_by_type(NON_MOTOR_NEURON);
this->get_neurons_by_type(INTER_NEURON);
this->randomly_fire = randomly_fire;
this->motor_randomly_fire_rate = sqrt(
this->nonsensory_neurons.size() / this->motor_neurons.size()
);
this->dynamic_output = dynamic_output;
this->decay_factor = decay_factor;
this->initiated_neurons = 0;
this->initiate_subscriptions();
this->fire_counter = 0;
this->output.reserve(this->output_dim);
this->wave_counter = 0;
this->freezer = false;
this->thread_kill_signal = false;
this->ignite();
}
void Network::initiate_subscriptions()
{
for (auto& neuron: this->neurons) {
if (neuron->type != SENSORY_NEURON) {
neuron->partially_subscribe();
std::cout << "Initiated: " << this->initiated_neurons
<< " neuron(s)\r" << std::flush;
}
}
}
void Network::_ignite(Network* network)
{
unsigned int motor_fire_counter = 0;
std::vector<Neuron*> ban_list;
while (network->freezer == false) {
if (network->randomly_fire) {
Neuron* neuron = random_sample(
network->nonsensory_neurons,
1
)[0];
if (neuron->type == MOTOR_NEURON) {
if (1 != Random::get(1, network->motor_randomly_fire_rate))
continue;
else
motor_fire_counter++;
}
neuron->fire();
if (motor_fire_counter >= network->motor_neurons.size()) {
if (network->dynamic_output) {
network->print_output();
}
network->output = network->get_output();
network->wave_counter++;
motor_fire_counter = 0;
}
} else {
if (network->next_queue.empty()) {
for (auto& neuron: network->motor_neurons) {
neuron->fire();
}
for (auto& neuron: ban_list) {
neuron->ban_counter = 0;
}
ban_list.clear();
if (network->dynamic_output) {
network->print_output();
}
network->output = network->get_output();
network->wave_counter++;
if (network->first_queue.empty()) {
for (auto const& neuron: network->sensory_neurons) {
network->first_queue.insert(
neuron->publications.begin(),
neuron->publications.end()
);
}
}
network->next_queue = network->first_queue;
}
std::unordered_map<Neuron*, double> current_queue
= network->next_queue;
network->next_queue.clear();
for (auto const& neuron: ban_list) {
if (neuron->ban_counter > network->connectivity_sqrt)
current_queue.erase(neuron);
}
while (current_queue.size() > 0) {
auto it = current_queue.begin();
std::advance(it, rand() % current_queue.size());
Neuron* neuron = it->first;
current_queue.erase(neuron);
if (neuron->ban_counter <= network->connectivity_sqrt) {
if (neuron->type == MOTOR_NEURON) {
continue;
}
neuron->fire();
ban_list.push_back(neuron);
neuron->ban_counter++;
network->next_queue.insert(
neuron->publications.begin(),
neuron->publications.end()
);
}
}
}
//break;
}
}
void Network::ignite()
{
this->freezer = false;
this->thread1 = std::thread{Network::_ignite, this};
//this->thread1.detach();
//this->thread1.join();
std::cout << "Network has been ignited" << '\n';
}
void Network::freeze()
{
this->freezer = true;
this->thread_kill_signal = true;
std::cout << "Network is now frozen" << '\n';
}
void Network::breakit() const
{
for (auto& neuron: this->neurons) {
neuron->subscriptions.clear();
}
std::cout << "All the subscriptions are now broken" << '\n';
}
void Network::pick_neurons_by_type(int input_dim, NeuronType neuron_type)
{
std::vector<Neuron*> available_neurons;
for (auto const& neuron: this->neurons) {
if (neuron->type == INTER_NEURON) {
available_neurons.push_back(neuron);
}
}
for (int j = 0; j < input_dim; j++) {
switch (neuron_type) {
case SENSORY_NEURON:
available_neurons[j]->type = SENSORY_NEURON;
this->sensory_neurons.push_back(available_neurons[j]);
break;
case MOTOR_NEURON:
available_neurons[j]->type = MOTOR_NEURON;
this->motor_neurons.push_back(available_neurons[j]);
break;
default:
throw std::invalid_argument(
"Network::pick_neurons_by_type(int input_dim, "
"NeuronType neuron_type) function only accepts "
"SENSORY_NEURON or MOTOR_NEURON as the neuron type!"
);
break;
}
}
switch (neuron_type) {
case SENSORY_NEURON:
std::cout << input_dim
<< " neuron picked as sensory neuron" << '\n';
break;
case MOTOR_NEURON:
std::cout << input_dim
<< " neuron picked as motor neuron" << '\n';
break;
default:
throw std::invalid_argument(
"Network::pick_neurons_by_type(int input_dim, "
"NeuronType neuron_type) function only accepts "
"SENSORY_NEURON or MOTOR_NEURON as the neuron type!"
);
break;
}
}
void Network::get_neurons_by_type(NeuronType neuron_type)
{
std::vector<Neuron*> available_neurons;
unsigned int i = 0;
for (auto const& neuron: this->neurons) {
switch (neuron_type) {
case NON_SENSORY_NEURON:
if (neuron->type != SENSORY_NEURON) {
this->nonsensory_neurons.push_back(neuron);
}
break;
case NON_MOTOR_NEURON:
if (neuron->type != MOTOR_NEURON) {
this->nonmotor_neurons.push_back(neuron);
}
break;
case INTER_NEURON:
if (neuron->type == INTER_NEURON) {
this->interneurons.push_back(neuron);
}
break;
default:
throw std::invalid_argument(
"Network::pick_neurons_by_type(int input_dim, "
"NeuronType neuron_type) function only accepts "
"NON_SENSORY_NEURON, NON_MOTOR_NEURON or "
"INTER_NEURON as the neuron type!"
);
break;
}
}
}
void Network::increase_initiated_neurons()
{
this->initiated_neurons += 1;
}
std::vector<double> Network::get_output() const
{
std::vector<double> output;
for (auto& neuron: this->motor_neurons) {
int decimals = pow(10, this->precision);
output.push_back(roundf(neuron->potential * decimals) / decimals);
}
return output;
}
void Network::print_output() const
{
std::vector<double> output = this->get_output();
std::cout << "\r";
std::cout << "Output: ";
for (const auto& i: output)
std::cout << i << ' ';
}
void Network::load(
std::vector<double> input_arr,
std::vector<double> output_arr
)
{
if (this->sensory_neurons.size() != input_arr.size()) {
std::cout << "Size of the input array: " << input_arr.size() << '\n';
std::cout << "Number of the sensory neurons: "
<< this->sensory_neurons.size() << '\n';
std::cout << "Size of the input array and number of the sensory "
"neurons are not matching! Please try again" << '\n';
} else {
int step = 0;
for (auto& neuron: this->sensory_neurons) {
neuron->potential = input_arr[step];
step++;
}
}
if (output_arr.empty()) {
this->freezer = true;
for (auto& neuron: this->nonsensory_neurons) {
neuron->desired_potential = NULL;
}
this->freezer = false;
} else {
if (this->motor_neurons.size() != output_arr.size()) {
std::cout << "Size of the output/target array: "
<< output_arr.size() << '\n';
std::cout << "Number of the motor neurons: "
<< this->motor_neurons.size() << '\n';
std::cout << "Size of the output/target array and number "
"of the motor neurons are not matching! "
"Please try again" << '\n';
} else {
int step = 0;
for (auto& neuron: this->motor_neurons) {
neuron->desired_potential = output_arr[step];
step++;
}
}
}
}
<commit_msg>Instead of assigning NULL to desired_potential, assign std::nan (NaN)<commit_after>#include <iostream>
#include <cstdlib>
#include <unordered_map>
#include <math.h>
#include <cmath>
#include <utility>
#include <thread>
#include <stdexcept>
#include <ostream>
#include "random.hpp"
using Random = effolkronium::random_thread_local;
#include "neuron.hpp"
#include "network.hpp"
Neuron::Neuron(Network& network)
{
this->network = &network;
this->network->neurons.push_back(this);
}
void Neuron::partially_subscribe()
{
if (this->subscriptions.size() == 0) {
unsigned seed = std::chrono::system_clock::now()
.time_since_epoch().count();
std::default_random_engine generator (seed);
std::normal_distribution<double> distribution(
this->network->connectivity,
this->network->connectivity_sqrt
);
unsigned int sample_length = distribution(generator);
if (sample_length > this->network->nonmotor_neurons.size())
sample_length = this->network->nonmotor_neurons.size();
if (sample_length <= 0)
sample_length = 0;
std::vector<Neuron*> elected = random_sample(
this->network->nonmotor_neurons,
sample_length
);
for (auto const& target_neuron: elected) {
if (target_neuron != this) {
this->subscriptions.insert(
std::pair<Neuron*, double>(
target_neuron,
Random::get(-1.0, 1.0)
)
);
target_neuron->publications.insert(
std::pair<Neuron*, double>(this, 0.0)
);
}
}
this->network->increase_initiated_neurons();
}
}
double Neuron::calculate_potential() const
{
double total = 0;
for (auto const& it: this->subscriptions) {
total += it.first->potential * it.second;
}
return this->activation_function(total);
}
double Neuron::activation_function(double x) const
{
return 1 / (1 + exp(-x));
}
double Neuron::derivative(double x) const
{
return x * (1 - x);
}
double Neuron::calculate_loss() const
{
try {
return this->potential - this->desired_potential;
} catch (const std::exception& e) {
return 0;
}
}
bool Neuron::fire()
{
if (this->type != SENSORY_NEURON) {
this->potential = this->calculate_potential();
this->network->fire_counter++;
this->fire_counter++;
if (! std::isnan(this->desired_potential)) {
this->loss = this->calculate_loss();
int alteration_sign;
if (this->loss > 0) {
alteration_sign = -1;
} else if (this->loss < 0) {
alteration_sign = 1;
} else {
this->desired_potential = std::nan("None");
return true;
}
double alteration_value = pow(fabs(this->loss), 2);
alteration_value = alteration_value * pow(
this->network->decay_factor,
(this->network->fire_counter/1000)
);
for (auto& it: this->subscriptions) {
it.first->desired_potential = it.first->potential
+ alteration_sign
* this->derivative(it.first->potential);
this->subscriptions[it.first] = it.second
+ (alteration_value * alteration_sign)
* this->derivative(it.first->potential);
}
}
}
}
Network::Network(
int size,
int input_dim = 0,
int output_dim = 0,
double connectivity = 0.01,
int precision = 2,
bool randomly_fire = false,
bool dynamic_output = false,
bool visualization = false,
double decay_factor = 1.0
)
{
this->precision = precision;
std::cout << "\nPrecision of the network will be "
<< 1.0 / pow(10, precision) << '\n';
this->connectivity = static_cast<int>(size * connectivity);
this->connectivity_sqrt = static_cast<int>(sqrt(this->connectivity));
std::cout << "Each individual non-sensory neuron will subscribe to "
<< this->connectivity << " different neurons" << '\n';
this->neurons.reserve(size);
for (int i = 0; i < size; i++) {
new Neuron(*this);
}
std::cout << size << " neurons created" << '\n';
this->input_dim = input_dim;
this->sensory_neurons.reserve(this->input_dim);
this->pick_neurons_by_type(this->input_dim, SENSORY_NEURON);
this->output_dim = output_dim;
this->motor_neurons.reserve(this->output_dim);
this->pick_neurons_by_type(this->output_dim, MOTOR_NEURON);
this->get_neurons_by_type(NON_SENSORY_NEURON);
this->get_neurons_by_type(NON_MOTOR_NEURON);
this->get_neurons_by_type(INTER_NEURON);
this->randomly_fire = randomly_fire;
this->motor_randomly_fire_rate = sqrt(
this->nonsensory_neurons.size() / this->motor_neurons.size()
);
this->dynamic_output = dynamic_output;
this->decay_factor = decay_factor;
this->initiated_neurons = 0;
this->initiate_subscriptions();
this->fire_counter = 0;
this->output.reserve(this->output_dim);
this->wave_counter = 0;
this->freezer = false;
this->thread_kill_signal = false;
this->ignite();
}
void Network::initiate_subscriptions()
{
for (auto& neuron: this->neurons) {
if (neuron->type != SENSORY_NEURON) {
neuron->partially_subscribe();
std::cout << "Initiated: " << this->initiated_neurons
<< " neuron(s)\r" << std::flush;
}
}
}
void Network::_ignite(Network* network)
{
unsigned int motor_fire_counter = 0;
std::vector<Neuron*> ban_list;
while (network->freezer == false) {
if (network->randomly_fire) {
Neuron* neuron = random_sample(
network->nonsensory_neurons,
1
)[0];
if (neuron->type == MOTOR_NEURON) {
if (1 != Random::get(1, network->motor_randomly_fire_rate))
continue;
else
motor_fire_counter++;
}
neuron->fire();
if (motor_fire_counter >= network->motor_neurons.size()) {
if (network->dynamic_output) {
network->print_output();
}
network->output = network->get_output();
network->wave_counter++;
motor_fire_counter = 0;
}
} else {
if (network->next_queue.empty()) {
for (auto& neuron: network->motor_neurons) {
neuron->fire();
}
for (auto& neuron: ban_list) {
neuron->ban_counter = 0;
}
ban_list.clear();
if (network->dynamic_output) {
network->print_output();
}
network->output = network->get_output();
network->wave_counter++;
if (network->first_queue.empty()) {
for (auto const& neuron: network->sensory_neurons) {
network->first_queue.insert(
neuron->publications.begin(),
neuron->publications.end()
);
}
}
network->next_queue = network->first_queue;
}
std::unordered_map<Neuron*, double> current_queue
= network->next_queue;
network->next_queue.clear();
for (auto const& neuron: ban_list) {
if (neuron->ban_counter > network->connectivity_sqrt)
current_queue.erase(neuron);
}
while (current_queue.size() > 0) {
auto it = current_queue.begin();
std::advance(it, rand() % current_queue.size());
Neuron* neuron = it->first;
current_queue.erase(neuron);
if (neuron->ban_counter <= network->connectivity_sqrt) {
if (neuron->type == MOTOR_NEURON) {
continue;
}
neuron->fire();
ban_list.push_back(neuron);
neuron->ban_counter++;
network->next_queue.insert(
neuron->publications.begin(),
neuron->publications.end()
);
}
}
}
//break;
}
}
void Network::ignite()
{
this->freezer = false;
this->thread1 = std::thread{Network::_ignite, this};
//this->thread1.detach();
//this->thread1.join();
std::cout << "Network has been ignited" << '\n';
}
void Network::freeze()
{
this->freezer = true;
this->thread_kill_signal = true;
std::cout << "Network is now frozen" << '\n';
}
void Network::breakit() const
{
for (auto& neuron: this->neurons) {
neuron->subscriptions.clear();
}
std::cout << "All the subscriptions are now broken" << '\n';
}
void Network::pick_neurons_by_type(int input_dim, NeuronType neuron_type)
{
std::vector<Neuron*> available_neurons;
for (auto const& neuron: this->neurons) {
if (neuron->type == INTER_NEURON) {
available_neurons.push_back(neuron);
}
}
for (int j = 0; j < input_dim; j++) {
switch (neuron_type) {
case SENSORY_NEURON:
available_neurons[j]->type = SENSORY_NEURON;
this->sensory_neurons.push_back(available_neurons[j]);
break;
case MOTOR_NEURON:
available_neurons[j]->type = MOTOR_NEURON;
this->motor_neurons.push_back(available_neurons[j]);
break;
default:
throw std::invalid_argument(
"Network::pick_neurons_by_type(int input_dim, "
"NeuronType neuron_type) function only accepts "
"SENSORY_NEURON or MOTOR_NEURON as the neuron type!"
);
break;
}
}
switch (neuron_type) {
case SENSORY_NEURON:
std::cout << input_dim
<< " neuron picked as sensory neuron" << '\n';
break;
case MOTOR_NEURON:
std::cout << input_dim
<< " neuron picked as motor neuron" << '\n';
break;
default:
throw std::invalid_argument(
"Network::pick_neurons_by_type(int input_dim, "
"NeuronType neuron_type) function only accepts "
"SENSORY_NEURON or MOTOR_NEURON as the neuron type!"
);
break;
}
}
void Network::get_neurons_by_type(NeuronType neuron_type)
{
std::vector<Neuron*> available_neurons;
unsigned int i = 0;
for (auto const& neuron: this->neurons) {
switch (neuron_type) {
case NON_SENSORY_NEURON:
if (neuron->type != SENSORY_NEURON) {
this->nonsensory_neurons.push_back(neuron);
}
break;
case NON_MOTOR_NEURON:
if (neuron->type != MOTOR_NEURON) {
this->nonmotor_neurons.push_back(neuron);
}
break;
case INTER_NEURON:
if (neuron->type == INTER_NEURON) {
this->interneurons.push_back(neuron);
}
break;
default:
throw std::invalid_argument(
"Network::pick_neurons_by_type(int input_dim, "
"NeuronType neuron_type) function only accepts "
"NON_SENSORY_NEURON, NON_MOTOR_NEURON or "
"INTER_NEURON as the neuron type!"
);
break;
}
}
}
void Network::increase_initiated_neurons()
{
this->initiated_neurons += 1;
}
std::vector<double> Network::get_output() const
{
std::vector<double> output;
for (auto& neuron: this->motor_neurons) {
int decimals = pow(10, this->precision);
output.push_back(roundf(neuron->potential * decimals) / decimals);
}
return output;
}
void Network::print_output() const
{
std::vector<double> output = this->get_output();
std::cout << "\r";
std::cout << "Output: ";
for (const auto& i: output)
std::cout << i << ' ';
}
void Network::load(
std::vector<double> input_arr,
std::vector<double> output_arr
)
{
if (this->sensory_neurons.size() != input_arr.size()) {
std::cout << "Size of the input array: " << input_arr.size() << '\n';
std::cout << "Number of the sensory neurons: "
<< this->sensory_neurons.size() << '\n';
std::cout << "Size of the input array and number of the sensory "
"neurons are not matching! Please try again" << '\n';
} else {
int step = 0;
for (auto& neuron: this->sensory_neurons) {
neuron->potential = input_arr[step];
step++;
}
}
if (output_arr.empty()) {
this->freezer = true;
for (auto& neuron: this->nonsensory_neurons) {
neuron->desired_potential = std::nan("None");
}
this->freezer = false;
} else {
if (this->motor_neurons.size() != output_arr.size()) {
std::cout << "Size of the output/target array: "
<< output_arr.size() << '\n';
std::cout << "Number of the motor neurons: "
<< this->motor_neurons.size() << '\n';
std::cout << "Size of the output/target array and number "
"of the motor neurons are not matching! "
"Please try again" << '\n';
} else {
int step = 0;
for (auto& neuron: this->motor_neurons) {
neuron->desired_potential = output_arr[step];
step++;
}
}
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <memory>
#include <string>
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/binary.h"
namespace paddle {
namespace operators {
using Tensor = phi::DenseTensor;
class PReluOp : public framework::OperatorWithKernel {
public:
PReluOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
auto input_data_type =
framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
return framework::OpKernelType(input_data_type, ctx.GetPlace());
}
framework::OpKernelType GetKernelTypeForVar(
const std::string &var_name,
const Tensor &tensor,
const framework::OpKernelType &expected_kernel_type) const override {
#ifdef PADDLE_WITH_MKLDNN
// All inputs (including alpha) need shape rotating
if ((expected_kernel_type.data_layout_ == phi::DataLayout::kMKLDNN) &&
(tensor.layout() != phi::DataLayout::kMKLDNN) &&
paddle::platform::MKLDNNDeviceContext::tls()
.get_cur_paddle_data_layout() == phi::DataLayout::kNHWC) {
return framework::OpKernelType(expected_kernel_type.data_type_,
tensor.place(),
phi::DataLayout::kNHWC);
}
#endif
return framework::OpKernelType(
expected_kernel_type.data_type_, tensor.place(), tensor.layout());
}
};
class PReluOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X", "The input tensor of prelu operator.");
AddInput("Alpha", "The alpha weight of prelu operator.");
AddOutput("Out", "The output tensor of prelu operator.");
AddComment(R"DOC(
PRelu Operator.
The equation is:
$$
f(x) =
\begin{cases}
\alpha * x, \quad \text{if} \ x < 0 \\
x, \qquad \text{if} \ x >= 0
\end{cases}
$$
The input `X` can carry the LoD (Level of Details) information,
or not. And the output shares the LoD information with input `X`.
There are modes:
all: all elements share same weight
channel: elements in a channel share same weight
element: each element has a weight
)DOC");
AddAttr<std::string>("mode", "The mode for inputs to share weights.")
.SetDefault("all");
AddAttr<std::string>("data_format",
"Data format that specifies the layout of input")
.SetDefault("NCHW");
}
};
// The operator to calculate gradients of a prelu operator.
class PReluGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "prelu");
OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
"Input",
"Out@GRAD",
"prelu");
auto x_grad_name = framework::GradVarName("X");
auto alpha_grad_name = framework::GradVarName("Alpha");
if (ctx->HasOutput(x_grad_name)) {
ctx->SetOutputDim(x_grad_name, ctx->GetInputDim("X"));
}
if (ctx->HasOutput(alpha_grad_name)) {
ctx->SetOutputDim(alpha_grad_name, ctx->GetInputDim("Alpha"));
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
auto input_data_type =
framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
return framework::OpKernelType(input_data_type, ctx.GetPlace());
}
framework::OpKernelType GetKernelTypeForVar(
const std::string &var_name,
const Tensor &tensor,
const framework::OpKernelType &expected_kernel_type) const override {
#ifdef PADDLE_WITH_MKLDNN
// All inputs (including alpha) need shape rotating
if ((expected_kernel_type.data_layout_ == phi::DataLayout::kMKLDNN) &&
(tensor.layout() != phi::DataLayout::kMKLDNN) &&
paddle::platform::MKLDNNDeviceContext::tls()
.get_cur_paddle_data_layout() == phi::DataLayout::kNHWC) {
return framework::OpKernelType(expected_kernel_type.data_type_,
tensor.place(),
phi::DataLayout::kNHWC);
}
#endif
return framework::OpKernelType(
expected_kernel_type.data_type_, tensor.place(), tensor.layout());
}
};
template <typename T>
class PReluGradOpMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("prelu_grad");
op->SetInput("X", this->Input("X"));
op->SetInput("Alpha", this->Input("Alpha"));
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetOutput(framework::GradVarName("Alpha"), this->InputGrad("Alpha"));
op->SetAttrMap(this->Attrs());
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
DECLARE_INFER_SHAPE_FUNCTOR(prelu,
PReluInferShapeFunctor,
PD_INFER_META(phi::PReluInferMeta));
REGISTER_OPERATOR(prelu,
ops::PReluOp,
ops::PReluOpMaker,
ops::PReluGradOpMaker<paddle::framework::OpDesc>,
ops::PReluGradOpMaker<paddle::imperative::OpBase>,
PReluInferShapeFunctor);
REGISTER_OPERATOR(prelu_grad, ops::PReluGradOp);
<commit_msg>delete GetKernelTypeForVar mkldnn hardcode (#47360)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <memory>
#include <string>
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/binary.h"
namespace paddle {
namespace operators {
using Tensor = phi::DenseTensor;
class PReluOp : public framework::OperatorWithKernel {
public:
PReluOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
auto input_data_type =
framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
return framework::OpKernelType(input_data_type, ctx.GetPlace());
}
};
class PReluOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X", "The input tensor of prelu operator.");
AddInput("Alpha", "The alpha weight of prelu operator.");
AddOutput("Out", "The output tensor of prelu operator.");
AddComment(R"DOC(
PRelu Operator.
The equation is:
$$
f(x) =
\begin{cases}
\alpha * x, \quad \text{if} \ x < 0 \\
x, \qquad \text{if} \ x >= 0
\end{cases}
$$
The input `X` can carry the LoD (Level of Details) information,
or not. And the output shares the LoD information with input `X`.
There are modes:
all: all elements share same weight
channel: elements in a channel share same weight
element: each element has a weight
)DOC");
AddAttr<std::string>("mode", "The mode for inputs to share weights.")
.SetDefault("all");
AddAttr<std::string>("data_format",
"Data format that specifies the layout of input")
.SetDefault("NCHW");
}
};
// The operator to calculate gradients of a prelu operator.
class PReluGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "prelu");
OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
"Input",
"Out@GRAD",
"prelu");
auto x_grad_name = framework::GradVarName("X");
auto alpha_grad_name = framework::GradVarName("Alpha");
if (ctx->HasOutput(x_grad_name)) {
ctx->SetOutputDim(x_grad_name, ctx->GetInputDim("X"));
}
if (ctx->HasOutput(alpha_grad_name)) {
ctx->SetOutputDim(alpha_grad_name, ctx->GetInputDim("Alpha"));
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
auto input_data_type =
framework::OperatorWithKernel::IndicateVarDataType(ctx, "X");
return framework::OpKernelType(input_data_type, ctx.GetPlace());
}
};
template <typename T>
class PReluGradOpMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("prelu_grad");
op->SetInput("X", this->Input("X"));
op->SetInput("Alpha", this->Input("Alpha"));
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetOutput(framework::GradVarName("Alpha"), this->InputGrad("Alpha"));
op->SetAttrMap(this->Attrs());
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
DECLARE_INFER_SHAPE_FUNCTOR(prelu,
PReluInferShapeFunctor,
PD_INFER_META(phi::PReluInferMeta));
REGISTER_OPERATOR(prelu,
ops::PReluOp,
ops::PReluOpMaker,
ops::PReluGradOpMaker<paddle::framework::OpDesc>,
ops::PReluGradOpMaker<paddle::imperative::OpBase>,
PReluInferShapeFunctor);
REGISTER_OPERATOR(prelu_grad, ops::PReluGradOp);
<|endoftext|> |
<commit_before>#include <LoggerProcess.hpp>
#include <Utility/Utilities/Include/String/StringHelper.hpp>
#include <Utility/Utilities/Include/IO/FileMap/FileMap.hpp>
#include <Utility/Utilities/Include/Constants/LoggerConstants.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
#include <Utility/Utilities/Include/Logging/HelpFunctions.hpp>
#include <time.h>
#include <Windows.h>
#include <iostream>
#include <thread>
using namespace Doremi::Utilities;
LoggerProcess::LoggerProcess() : m_fileMap(nullptr), m_ingoingBuffer(nullptr), m_mutex(nullptr) {}
LoggerProcess::~LoggerProcess()
{
if(m_fileMap != nullptr)
{
delete m_fileMap;
}
if(m_ingoingBuffer != nullptr)
{
delete m_ingoingBuffer;
}
if(m_mutex != nullptr)
{
delete m_mutex;
}
}
void LoggerProcess::Initialize(const int& p_uniqueId)
{
m_processIdOfGame = p_uniqueId;
SetupFolderStructure();
BuildLogFiles();
SetupCircleBuffer();
void* fileMapMemory = InitializeFileMap(Constants::IPC_FILEMAP_SIZE);
m_mutex = CreateFileMapMutex();
m_ingoingBuffer->Initialize(fileMapMemory, Constants::IPC_FILEMAP_SIZE, m_mutex);
}
void LoggerProcess::Run()
{
using namespace Doremi::Utilities;
// Create temporary data/header memory
Logging::LogTextData* data = new Logging::LogTextData();
Memory::CircleBufferHeader* header = new Memory::CircleBufferHeader();
bool messageExist = false;
bool gameIsRunning = true;
double elapsedTimeSinceLastEntry = 0;
double flushTimer = 0;
m_timer.Tick();
while(gameIsRunning || messageExist)
{
// Consume data from shared memory
messageExist = m_ingoingBuffer->Consume(header, data);
gameIsRunning = IsGameRunning();
// If any data existed
if(messageExist)
{
// Send data to logfile
m_logfiles[data->logTag].Write(*data);
// Print data to console
// std::cout << data->message << "\n";
// Reset elapsed time
elapsedTimeSinceLastEntry = 0;
}
else
{
using namespace std::literals;
// TODORT
// TODOXX is 10ms good?
std::this_thread::sleep_for(10ms);
}
// Compute delta time
m_timer.Tick();
const double deltaTime = m_timer.GetElapsedTimeInSeconds();
// Check if time for flush
flushTimer += deltaTime;
if(flushTimer > Constants::LOGFILE_FLUSH_INTERVAL)
{
for(auto& logfile : m_logfiles)
{
logfile.second.Flush();
}
}
// If elapsed time since last log is greater than a timeout
elapsedTimeSinceLastEntry += deltaTime;
if(elapsedTimeSinceLastEntry > Constants::IPC_FILEMAP_TIMEOUT)
{
// Shutdown
// break; //TODORT Not sure that the loggerprocess must have a hard timeout
}
}
// Release temporary memory
delete data;
delete header;
}
void* LoggerProcess::InitializeFileMap(const std::size_t& p_size)
{
m_fileMap = new IO::FileMap();
std::string fileMapName;
// If id is zero, default, otherwise build uniquename.
if(m_processIdOfGame == 0)
{
fileMapName = Constants::IPC_DEFAULT_FILEMAP_NAME;
}
else
{
fileMapName = Logging::BuildFileMapName(m_processIdOfGame);
}
void* memory = m_fileMap->Initialize(fileMapName, p_size);
if(memory != nullptr)
{
return memory;
}
else
{
throw std::runtime_error("Failed to initialize filemap.");
}
}
void LoggerProcess::SetupCircleBuffer() { m_ingoingBuffer = new Memory::CircleBuffer<Logging::LogTextData>(); }
IO::Mutex* LoggerProcess::CreateFileMapMutex()
{
IO::Mutex* mutex = new IO::FileMapMutex();
const bool success = mutex->Initialize(Constants::IPC_FILEMAP_MUTEX_NAME);
if(success)
{
return mutex;
}
else
{
delete mutex;
throw std::runtime_error("Failed to initialize filemap mutex.");
}
}
void LoggerProcess::SetupFolderStructure()
{
using namespace std;
// Build logfilename
string& folderName = Logging::BuildFolderNameBasedOnTime();
folderName.append("_" + std::to_string(GetCurrentProcessId()));
// Create the directory
CreateDirectory(L"logs", NULL);
CreateDirectory(String::StringToWideString(folderName).c_str(), NULL);
// Set working directory
SetCurrentDirectory(String::StringToWideString(folderName).c_str());
}
void LoggerProcess::BuildLogFiles()
{
for(auto& tag : Logging::ALL_LOG_TAGS)
{
m_logfiles[tag] = SpecificLogFile();
m_logfiles[tag].Initialize(tag);
}
}
bool LoggerProcess::IsGameRunning()
{
bool returnValue = false;
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, m_processIdOfGame);
if(processHandle != NULL)
{
returnValue = true;
}
CloseHandle(processHandle);
return returnValue;
}
<commit_msg>Improved the insertion in a map using emplace<commit_after>#include <LoggerProcess.hpp>
#include <Utility/Utilities/Include/String/StringHelper.hpp>
#include <Utility/Utilities/Include/IO/FileMap/FileMap.hpp>
#include <Utility/Utilities/Include/Constants/LoggerConstants.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
#include <Utility/Utilities/Include/Logging/HelpFunctions.hpp>
#include <time.h>
#include <Windows.h>
#include <iostream>
#include <thread>
using namespace Doremi::Utilities;
LoggerProcess::LoggerProcess() : m_fileMap(nullptr), m_ingoingBuffer(nullptr), m_mutex(nullptr) {}
LoggerProcess::~LoggerProcess()
{
if(m_fileMap != nullptr)
{
delete m_fileMap;
}
if(m_ingoingBuffer != nullptr)
{
delete m_ingoingBuffer;
}
if(m_mutex != nullptr)
{
delete m_mutex;
}
}
void LoggerProcess::Initialize(const int& p_uniqueId)
{
m_processIdOfGame = p_uniqueId;
SetupFolderStructure();
BuildLogFiles();
SetupCircleBuffer();
void* fileMapMemory = InitializeFileMap(Constants::IPC_FILEMAP_SIZE);
m_mutex = CreateFileMapMutex();
m_ingoingBuffer->Initialize(fileMapMemory, Constants::IPC_FILEMAP_SIZE, m_mutex);
}
void LoggerProcess::Run()
{
using namespace Doremi::Utilities;
// Create temporary data/header memory
Logging::LogTextData* data = new Logging::LogTextData();
Memory::CircleBufferHeader* header = new Memory::CircleBufferHeader();
bool messageExist = false;
bool gameIsRunning = true;
double elapsedTimeSinceLastEntry = 0;
double flushTimer = 0;
m_timer.Tick();
while(gameIsRunning || messageExist)
{
// Consume data from shared memory
messageExist = m_ingoingBuffer->Consume(header, data);
gameIsRunning = IsGameRunning();
// If any data existed
if(messageExist)
{
// Send data to logfile
m_logfiles[data->logTag].Write(*data);
// Print data to console
// std::cout << data->message << "\n";
// Reset elapsed time
elapsedTimeSinceLastEntry = 0;
}
else
{
using namespace std::literals;
// TODORT
// TODOXX is 10ms good?
std::this_thread::sleep_for(10ms);
}
// Compute delta time
m_timer.Tick();
const double deltaTime = m_timer.GetElapsedTimeInSeconds();
// Check if time for flush
flushTimer += deltaTime;
if(flushTimer > Constants::LOGFILE_FLUSH_INTERVAL)
{
for(auto& logfile : m_logfiles)
{
logfile.second.Flush();
}
}
// If elapsed time since last log is greater than a timeout
elapsedTimeSinceLastEntry += deltaTime;
if(elapsedTimeSinceLastEntry > Constants::IPC_FILEMAP_TIMEOUT)
{
// Shutdown
// break; //TODORT Not sure that the loggerprocess must have a hard timeout
}
}
// Release temporary memory
delete data;
delete header;
}
void* LoggerProcess::InitializeFileMap(const std::size_t& p_size)
{
m_fileMap = new IO::FileMap();
std::string fileMapName;
// If id is zero, default, otherwise build uniquename.
if(m_processIdOfGame == 0)
{
fileMapName = Constants::IPC_DEFAULT_FILEMAP_NAME;
}
else
{
fileMapName = Logging::BuildFileMapName(m_processIdOfGame);
}
void* memory = m_fileMap->Initialize(fileMapName, p_size);
if(memory != nullptr)
{
return memory;
}
else
{
throw std::runtime_error("Failed to initialize filemap.");
}
}
void LoggerProcess::SetupCircleBuffer() { m_ingoingBuffer = new Memory::CircleBuffer<Logging::LogTextData>(); }
IO::Mutex* LoggerProcess::CreateFileMapMutex()
{
IO::Mutex* mutex = new IO::FileMapMutex();
const bool success = mutex->Initialize(Constants::IPC_FILEMAP_MUTEX_NAME);
if(success)
{
return mutex;
}
else
{
delete mutex;
throw std::runtime_error("Failed to initialize filemap mutex.");
}
}
void LoggerProcess::SetupFolderStructure()
{
using namespace std;
// Build logfilename
string& folderName = Logging::BuildFolderNameBasedOnTime();
folderName.append("_" + std::to_string(GetCurrentProcessId()));
// Create the directory
CreateDirectory(L"logs", NULL);
CreateDirectory(String::StringToWideString(folderName).c_str(), NULL);
// Set working directory
SetCurrentDirectory(String::StringToWideString(folderName).c_str());
}
void LoggerProcess::BuildLogFiles()
{
for(auto& tag : Logging::ALL_LOG_TAGS)
{
m_logfiles.emplace(tag, SpecificLogFile());
m_logfiles[tag].Initialize(tag);
}
}
bool LoggerProcess::IsGameRunning()
{
bool returnValue = false;
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, m_processIdOfGame);
if(processHandle != NULL)
{
returnValue = true;
}
CloseHandle(processHandle);
return returnValue;
}
<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file ModProgMeshT.cc
*/
//=============================================================================
//
// CLASS ModProgMeshT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_DECIMATER_MODPROGMESH_CC
//== INCLUDES =================================================================
#include <vector>
#include <fstream>
// --------------------
#include <OpenMesh/Core/Utils/vector_cast.hh>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/Utils/Endian.hh>
// --------------------
#include <OpenMesh/Tools/Decimater/ModProgMeshT.hh>
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template <class MeshT>
bool
ModProgMeshT<MeshT>::
write( const std::string& _ofname )
{
// sort vertices
size_t i=0, N=Base::mesh().n_vertices(), n_base_vertices(0), n_base_faces(0);
std::vector<typename Mesh::VertexHandle> vhandles(N);
// base vertices
typename Mesh::VertexIter
v_it=Base::mesh().vertices_begin(),
v_end=Base::mesh().vertices_end();
for (; v_it != v_end; ++v_it)
if (!Base::mesh().status(*v_it).deleted())
{
vhandles[i] = *v_it;
Base::mesh().property( idx_, *v_it ) = i;
++i;
}
n_base_vertices = i;
// deleted vertices
typename InfoList::reverse_iterator
r_it=pmi_.rbegin(), r_end=pmi_.rend();
for (; r_it!=r_end; ++r_it)
{
vhandles[i] = r_it->v0;
Base::mesh().property( idx_, r_it->v0) = i;
++i;
}
// base faces
typename Mesh::ConstFaceIter f_it = Base::mesh().faces_begin(),
f_end = Base::mesh().faces_end();
for (; f_it != f_end; ++f_it)
if (!Base::mesh().status(*f_it).deleted())
++n_base_faces;
// ---------------------------------------- write progressive mesh
std::ofstream out( _ofname.c_str(), std::ios::binary );
if (!out)
return false;
// always use little endian byte ordering
bool swap = Endian::local() != Endian::LSB;
// write header
out << "ProgMesh";
IO::store( out, n_base_vertices, swap );
IO::store( out, n_base_faces , swap );
IO::store( out, pmi_.size() , swap );
Vec3f p;
// write base vertices
for (i=0; i<n_base_vertices; ++i)
{
assert (!Base::mesh().status(vhandles[i]).deleted());
p = vector_cast< Vec3f >( Base::mesh().point(vhandles[i]) );
IO::store( out, p, swap );
}
// write base faces
for (f_it=Base::mesh().faces_begin(); f_it != f_end; ++f_it)
{
if (!Base::mesh().status(*f_it).deleted())
{
typename Mesh::ConstFaceVertexIter fv_it(Base::mesh(), *f_it);
IO::store( out, Base::mesh().property( idx_, *fv_it ) );
IO::store( out, Base::mesh().property( idx_, *(++fv_it )) );
IO::store( out, Base::mesh().property( idx_, *(++fv_it )) );
}
}
// write detail info
for (r_it=pmi_.rbegin(); r_it!=r_end; ++r_it)
{
// store v0.pos, v1.idx, vl.idx, vr.idx
IO::store( out, vector_cast<Vec3f>(Base::mesh().point(r_it->v0)));
IO::store( out, Base::mesh().property( idx_, r_it->v1 ) );
IO::store( out,
r_it->vl.is_valid() ? Base::mesh().property(idx_, r_it->vl) : -1 );
IO::store( out,
r_it->vr.is_valid() ? Base::mesh().property(idx_, r_it->vr) : -1 );
}
return true;
}
//=============================================================================
} // END_NS_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<commit_msg>fix 32/64-bit bug on windows (analyzer and synthesizer reads with unsigned int -> 32bit, writer writes size_t -> possible 64-bit)<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file ModProgMeshT.cc
*/
//=============================================================================
//
// CLASS ModProgMeshT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_DECIMATER_MODPROGMESH_CC
//== INCLUDES =================================================================
#include <vector>
#include <fstream>
// --------------------
#include <OpenMesh/Core/Utils/vector_cast.hh>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/Utils/Endian.hh>
// --------------------
#include <OpenMesh/Tools/Decimater/ModProgMeshT.hh>
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template <class MeshT>
bool
ModProgMeshT<MeshT>::
write( const std::string& _ofname )
{
// sort vertices
size_t i=0, N=Base::mesh().n_vertices(), n_base_vertices(0), n_base_faces(0);
std::vector<typename Mesh::VertexHandle> vhandles(N);
// base vertices
typename Mesh::VertexIter
v_it=Base::mesh().vertices_begin(),
v_end=Base::mesh().vertices_end();
for (; v_it != v_end; ++v_it)
if (!Base::mesh().status(*v_it).deleted())
{
vhandles[i] = *v_it;
Base::mesh().property( idx_, *v_it ) = i;
++i;
}
n_base_vertices = i;
// deleted vertices
typename InfoList::reverse_iterator
r_it=pmi_.rbegin(), r_end=pmi_.rend();
for (; r_it!=r_end; ++r_it)
{
vhandles[i] = r_it->v0;
Base::mesh().property( idx_, r_it->v0) = i;
++i;
}
// base faces
typename Mesh::ConstFaceIter f_it = Base::mesh().faces_begin(),
f_end = Base::mesh().faces_end();
for (; f_it != f_end; ++f_it)
if (!Base::mesh().status(*f_it).deleted())
++n_base_faces;
// ---------------------------------------- write progressive mesh
std::ofstream out( _ofname.c_str(), std::ios::binary );
if (!out)
return false;
// always use little endian byte ordering
bool swap = Endian::local() != Endian::LSB;
// write header
out << "ProgMesh";
IO::store( out, static_cast<unsigned int>(n_base_vertices), swap );//store in 32-bit
IO::store( out, static_cast<unsigned int>(n_base_faces) , swap );
IO::store( out, static_cast<unsigned int>(pmi_.size()) , swap );
Vec3f p;
// write base vertices
for (i=0; i<n_base_vertices; ++i)
{
assert (!Base::mesh().status(vhandles[i]).deleted());
p = vector_cast< Vec3f >( Base::mesh().point(vhandles[i]) );
IO::store( out, p, swap );
}
// write base faces
for (f_it=Base::mesh().faces_begin(); f_it != f_end; ++f_it)
{
if (!Base::mesh().status(*f_it).deleted())
{
typename Mesh::ConstFaceVertexIter fv_it(Base::mesh(), *f_it);
IO::store( out, Base::mesh().property( idx_, *fv_it ) );
IO::store( out, Base::mesh().property( idx_, *(++fv_it )) );
IO::store( out, Base::mesh().property( idx_, *(++fv_it )) );
}
}
// write detail info
for (r_it=pmi_.rbegin(); r_it!=r_end; ++r_it)
{
// store v0.pos, v1.idx, vl.idx, vr.idx
IO::store( out, vector_cast<Vec3f>(Base::mesh().point(r_it->v0)));
IO::store( out, Base::mesh().property( idx_, r_it->v1 ) );
IO::store( out,
r_it->vl.is_valid() ? Base::mesh().property(idx_, r_it->vl) : -1 );
IO::store( out,
r_it->vr.is_valid() ? Base::mesh().property(idx_, r_it->vr) : -1 );
}
return true;
}
//=============================================================================
} // END_NS_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<|endoftext|> |
<commit_before>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// 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 "geo/bezier.hh"
#include "geo/geo-func.hh"
#include "geo/int-rect.hh"
#include "geo/measure.hh"
#include "geo/points.hh"
#include "objects/object.hh"
#include "objects/objpath.hh"
#include "rendering/faint-dc.hh"
#include "text/utf8-string.hh"
#include "util/object-util.hh"
#include "util/setting-id.hh"
#include "util/setting-util.hh"
#include "util/settings.hh"
namespace faint{
class ObjPath : public Object{
public:
ObjPath(const Points& points, const Settings& settings)
: Object(with_point_editing(settings, start_enabled(false))),
m_points(points),
m_tri(points.GetTri())
{}
bool CyclicPoints() const override{
return true;
}
Object* Clone() const override{
return new ObjPath(*this);
}
void Draw(FaintDC& dc, ExpressionContext&) override{
dc.Path(m_points.GetPoints(m_tri), m_settings);
}
void DrawMask(FaintDC& dc) override{
dc.Path(m_points.GetPoints(m_tri), mask_settings_fill(m_settings));
}
std::vector<Point> GetAttachPoints() const override{
std::vector<Point> attachPoints;
auto pts = m_points.GetPoints(m_tri);
if (pts.empty()){
return {};
}
const Point first = pts.front().p;
Point prev = first;
for (const auto& pt : pts){
pt.Visit(
[&](const ArcTo& arc){
// Fixme: Verify that p is end-point
prev = arc.p;
},
[&](const Close&){
attachPoints.push_back(mid_point(prev, first));
},
[&](const CubicBezier& bezier){
// Fixme: allow subdivisions too
attachPoints.push_back(bezier_point(0.5, prev, bezier));
attachPoints.push_back(bezier.p);
prev = bezier.p;
},
[&](const LineTo& to){
attachPoints.push_back(mid_point(prev, to.p));
attachPoints.push_back(to.p);
prev = to.p;
},
[&](const MoveTo& to){
attachPoints.push_back(to.p);
prev = to.p;
});
}
return attachPoints;
}
std::vector<ExtensionPoint> GetExtensionPoints() const override{
if (m_points.Empty()){
return {};
}
auto pathPts = m_points.GetPoints(m_tri);
Point current = pathPts.front().p;
std::vector<ExtensionPoint> extensionPoints;
int i = 0;
for (const auto& pt : pathPts){
pt.Visit(
[&](const ArcTo& ap){
current = ap.p;
i++;
},
[&](const Close&){
extensionPoints.push_back({mid_point(current, pathPts.front().p), i});
i++;
},
[&](const CubicBezier& bezier){
extensionPoints.push_back({bezier_point(0.5, current, bezier), i});
current = bezier.p;
i += 3;
},
[&](const LineTo& to){
extensionPoints.push_back({mid_point(current, to.p), i});
current = to.p;
i += 1;
},
[&](const MoveTo& to){
current = to.p;
i += 1;
});
}
return extensionPoints;
}
std::vector<Point> GetMovablePoints() const override{
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
std::vector<Point> movablePts;
movablePts.reserve(pathPts.size());
for (const PathPt& pt : pathPts){
if (pt.IsCubicBezier()){
movablePts.push_back(pt.p);
movablePts.push_back(pt.c);
movablePts.push_back(pt.d);
}
else if (pt.IsLine()){
movablePts.push_back(pt.p);
}
else if (pt.IsMove()){
movablePts.push_back(pt.p);
}
// Else?
}
return movablePts;
}
std::vector<PathPt> GetPath(const ExpressionContext&) const override{
return m_points.GetPoints(m_tri);
}
Point GetPoint(int index) const override{
return GetMovablePoints()[to_size_t(index)]; // Fixme: Slow
}
IntRect GetRefreshRect() const override{
return floored(bounding_rect(m_tri, m_settings));
}
Tri GetTri() const override{
return m_tri;
}
utf8_string GetType() const override{
return "Path";
}
void InsertPoint(const Point& pt, int index) override{
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
auto p0 = pathPts.at(index - 1); // Fixme: Check bounds
pathPts.at(index).Visit(
[](const ArcTo&){ assert(false);}, // Not implemented
[&](const Close&){
m_points.InsertPointRaw(LineTo(pt), index);
},
[&](const CubicBezier& b){
auto bs = in_twain(p0.p, b);
bs.first.p = pt;
m_points.RemovePointRaw(index);
m_points.InsertPointRaw(bs.second, index);
m_points.InsertPointRaw(bs.first, index);
},
[&](const LineTo&){
m_points.InsertPointRaw(LineTo(pt), index);
},
[](const MoveTo&){assert(false);}); // Not implemented
}
bool IsControlPoint(int index) const override{
assert(index >= 0);
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
int at = 0;
// Fixme: Duplicates SetPoint
for (size_t i = 0; i != pathPts.size(); i++){
const PathPt& pt = pathPts[i];
if (pt.IsCubicBezier()){
if (index <= at + 2){
if (index == at){
return false;
}
else if (index == at + 1){
return true;
}
else if (index == at + 2){
return true;
}
assert(false);
}
at += 3;
}
else if (pt.IsLine()){
if (index == at){
return false;
}
at += 1;
}
else if (pt.IsMove()){
if (index == at){
return false;
}
at += 1;
}
// Fixme: What of arc etc? :-x Use visit.
}
return false;
}
int NumPoints() const override{
return resigned(GetMovablePoints().size()); // Fixme: slow.
}
void RemovePoint(int index) override{
// Fixme: When used for undo, this will deform the path.
assert(index >= 0);
m_points.RemovePointRaw(index);
}
void SetPoint(const Point& pt, int index) override{
assert(index >= 0);
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
int at = 0;
for (size_t i = 0; i != pathPts.size(); i++){
const PathPt& oldPt = pathPts[i];
if (oldPt.IsCubicBezier()){
if (index <= at + 2){
PathPt copy(oldPt);
if (index == at){
copy.p = pt;
}
else if (index == at + 1){
copy.c = pt;
}
else if (index == at + 2){
copy.d = pt;
}
else{
assert(false);
}
m_points.SetPoint(m_tri, copy, resigned(i));
break;
}
at += 3;
}
else if (oldPt.IsLine()){
if (index == at){
m_points.SetPoint(m_tri, PathPt::LineTo(pt), resigned(i));
break;
}
at += 1;
}
else if (oldPt.IsMove()){
if (index == at){
m_points.SetPoint(m_tri, PathPt::MoveTo(pt), resigned(i));
break;
}
at += 1;
}
}
SetTri(m_points.GetTri()); // Fixme
}
void SetTri(const Tri& t) override{
m_tri = t;
}
private:
// For clone
ObjPath(const ObjPath& other) :
Object(other.m_settings),
m_points(other.m_points),
m_tri(other.GetTri())
{}
Points m_points;
Tri m_tri;
};
Object* create_path_object(const Points& points, const Settings& settings){
return new ObjPath(points, without(settings, ts_ClosedPath));
}
} // namespace
<commit_msg>Removed fixme comment.<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// 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 "geo/bezier.hh"
#include "geo/geo-func.hh"
#include "geo/int-rect.hh"
#include "geo/measure.hh"
#include "geo/points.hh"
#include "objects/object.hh"
#include "objects/objpath.hh"
#include "rendering/faint-dc.hh"
#include "text/utf8-string.hh"
#include "util/object-util.hh"
#include "util/setting-id.hh"
#include "util/setting-util.hh"
#include "util/settings.hh"
namespace faint{
class ObjPath : public Object{
public:
ObjPath(const Points& points, const Settings& settings)
: Object(with_point_editing(settings, start_enabled(false))),
m_points(points),
m_tri(points.GetTri())
{}
bool CyclicPoints() const override{
return true;
}
Object* Clone() const override{
return new ObjPath(*this);
}
void Draw(FaintDC& dc, ExpressionContext&) override{
dc.Path(m_points.GetPoints(m_tri), m_settings);
}
void DrawMask(FaintDC& dc) override{
dc.Path(m_points.GetPoints(m_tri), mask_settings_fill(m_settings));
}
std::vector<Point> GetAttachPoints() const override{
std::vector<Point> attachPoints;
auto pts = m_points.GetPoints(m_tri);
if (pts.empty()){
return {};
}
const Point first = pts.front().p;
Point prev = first;
for (const auto& pt : pts){
pt.Visit(
[&](const ArcTo& arc){
// Fixme: Verify that p is end-point
prev = arc.p;
},
[&](const Close&){
attachPoints.push_back(mid_point(prev, first));
},
[&](const CubicBezier& bezier){
attachPoints.push_back(bezier_point(0.5, prev, bezier));
attachPoints.push_back(bezier.p);
prev = bezier.p;
},
[&](const LineTo& to){
attachPoints.push_back(mid_point(prev, to.p));
attachPoints.push_back(to.p);
prev = to.p;
},
[&](const MoveTo& to){
attachPoints.push_back(to.p);
prev = to.p;
});
}
return attachPoints;
}
std::vector<ExtensionPoint> GetExtensionPoints() const override{
if (m_points.Empty()){
return {};
}
auto pathPts = m_points.GetPoints(m_tri);
Point current = pathPts.front().p;
std::vector<ExtensionPoint> extensionPoints;
int i = 0;
for (const auto& pt : pathPts){
pt.Visit(
[&](const ArcTo& ap){
current = ap.p;
i++;
},
[&](const Close&){
extensionPoints.push_back({mid_point(current, pathPts.front().p), i});
i++;
},
[&](const CubicBezier& bezier){
extensionPoints.push_back({bezier_point(0.5, current, bezier), i});
current = bezier.p;
i += 3;
},
[&](const LineTo& to){
extensionPoints.push_back({mid_point(current, to.p), i});
current = to.p;
i += 1;
},
[&](const MoveTo& to){
current = to.p;
i += 1;
});
}
return extensionPoints;
}
std::vector<Point> GetMovablePoints() const override{
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
std::vector<Point> movablePts;
movablePts.reserve(pathPts.size());
for (const PathPt& pt : pathPts){
if (pt.IsCubicBezier()){
movablePts.push_back(pt.p);
movablePts.push_back(pt.c);
movablePts.push_back(pt.d);
}
else if (pt.IsLine()){
movablePts.push_back(pt.p);
}
else if (pt.IsMove()){
movablePts.push_back(pt.p);
}
// Else?
}
return movablePts;
}
std::vector<PathPt> GetPath(const ExpressionContext&) const override{
return m_points.GetPoints(m_tri);
}
Point GetPoint(int index) const override{
return GetMovablePoints()[to_size_t(index)]; // Fixme: Slow
}
IntRect GetRefreshRect() const override{
return floored(bounding_rect(m_tri, m_settings));
}
Tri GetTri() const override{
return m_tri;
}
utf8_string GetType() const override{
return "Path";
}
void InsertPoint(const Point& pt, int index) override{
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
auto p0 = pathPts.at(index - 1); // Fixme: Check bounds
pathPts.at(index).Visit(
[](const ArcTo&){ assert(false);}, // Not implemented
[&](const Close&){
m_points.InsertPointRaw(LineTo(pt), index);
},
[&](const CubicBezier& b){
auto bs = in_twain(p0.p, b);
bs.first.p = pt;
m_points.RemovePointRaw(index);
m_points.InsertPointRaw(bs.second, index);
m_points.InsertPointRaw(bs.first, index);
},
[&](const LineTo&){
m_points.InsertPointRaw(LineTo(pt), index);
},
[](const MoveTo&){assert(false);}); // Not implemented
}
bool IsControlPoint(int index) const override{
assert(index >= 0);
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
int at = 0;
// Fixme: Duplicates SetPoint
for (size_t i = 0; i != pathPts.size(); i++){
const PathPt& pt = pathPts[i];
if (pt.IsCubicBezier()){
if (index <= at + 2){
if (index == at){
return false;
}
else if (index == at + 1){
return true;
}
else if (index == at + 2){
return true;
}
assert(false);
}
at += 3;
}
else if (pt.IsLine()){
if (index == at){
return false;
}
at += 1;
}
else if (pt.IsMove()){
if (index == at){
return false;
}
at += 1;
}
// Fixme: What of arc etc? :-x Use visit.
}
return false;
}
int NumPoints() const override{
return resigned(GetMovablePoints().size()); // Fixme: slow.
}
void RemovePoint(int index) override{
// Fixme: When used for undo, this will deform the path.
assert(index >= 0);
m_points.RemovePointRaw(index);
}
void SetPoint(const Point& pt, int index) override{
assert(index >= 0);
std::vector<PathPt> pathPts = m_points.GetPoints(m_tri);
int at = 0;
for (size_t i = 0; i != pathPts.size(); i++){
const PathPt& oldPt = pathPts[i];
if (oldPt.IsCubicBezier()){
if (index <= at + 2){
PathPt copy(oldPt);
if (index == at){
copy.p = pt;
}
else if (index == at + 1){
copy.c = pt;
}
else if (index == at + 2){
copy.d = pt;
}
else{
assert(false);
}
m_points.SetPoint(m_tri, copy, resigned(i));
break;
}
at += 3;
}
else if (oldPt.IsLine()){
if (index == at){
m_points.SetPoint(m_tri, PathPt::LineTo(pt), resigned(i));
break;
}
at += 1;
}
else if (oldPt.IsMove()){
if (index == at){
m_points.SetPoint(m_tri, PathPt::MoveTo(pt), resigned(i));
break;
}
at += 1;
}
}
SetTri(m_points.GetTri()); // Fixme
}
void SetTri(const Tri& t) override{
m_tri = t;
}
private:
// For clone
ObjPath(const ObjPath& other) :
Object(other.m_settings),
m_points(other.m_points),
m_tri(other.GetTri())
{}
Points m_points;
Tri m_tri;
};
Object* create_path_object(const Points& points, const Settings& settings){
return new ObjPath(points, without(settings, ts_ClosedPath));
}
} // namespace
<|endoftext|> |
<commit_before>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: cgogn@unistra.fr *
* *
*******************************************************************************/
#include <core/utils/thread_pool.h>
namespace cgogn
{
std::vector<std::thread::id> ThreadPool::get_threads_ids() const
{
std::vector<std::thread::id> res;
res.reserve(workers_.size());
for (const std::thread& w : workers_)
res.push_back(w.get_id());
return res;
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex_);
stop_ = true;
}
condition_.notify_all();
for(std::thread &worker: workers_)
worker.join();
}
ThreadPool::ThreadPool() : stop_(false)
{
for(unsigned int i = 0u; i< MAX_NB_THREADS ;++i)
workers_.emplace_back(
[this,i]
{
for(;;)
{
std::function<void(unsigned int)> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex_);
this->condition_.wait(lock,
[this]{ return this->stop_ || !this->tasks_.empty(); });
if(this->stop_ && this->tasks_.empty())
return;
task = std::move(this->tasks_.front());
this->tasks_.pop();
}
task(i);
}
}
);
}
} // namespace cgogn
<commit_msg>Added missing thread_start() and thread_stop()<commit_after>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: cgogn@unistra.fr *
* *
*******************************************************************************/
#include <core/utils/thread_pool.h>
namespace cgogn
{
std::vector<std::thread::id> ThreadPool::get_threads_ids() const
{
std::vector<std::thread::id> res;
res.reserve(workers_.size());
for (const std::thread& w : workers_)
res.push_back(w.get_id());
return res;
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex_);
stop_ = true;
}
condition_.notify_all();
for(std::thread &worker: workers_)
worker.join();
}
ThreadPool::ThreadPool() : stop_(false)
{
for(unsigned int i = 0u; i< MAX_NB_THREADS ;++i)
workers_.emplace_back(
[this,i]
{
cgogn::thread_start();
for(;;)
{
std::function<void(unsigned int)> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex_);
this->condition_.wait(lock,
[this]{ return this->stop_ || !this->tasks_.empty(); });
if(this->stop_ && this->tasks_.empty())
{
cgogn::thread_stop();
return;
}
task = std::move(this->tasks_.front());
this->tasks_.pop();
}
task(i);
}
}
);
}
} // namespace cgogn
<|endoftext|> |
<commit_before>
#include "ObjectStore.h"
#include "Configuration.h"
ObjectStore::ObjectStore()
{
memset(this->functions, '\0', 10);
this->first = NULL;
this->last = NULL;
this->basicObjectCount = 0;
}
void ObjectStore::addObject(BasicObject* bo)
{
ObjectStoreNode* node = new ObjectStoreNode();
node->prev = this->last;
node->next = NULL;
node->object = bo;
if (this->first == NULL) {
this->first = node;
} else {
this->last->next = node;
}
this->last = node;
this->basicObjectCount++;
}
void ObjectStore::updateObjects()
{
for (ObjectStoreNode* node = this->first; node != NULL; node = node->next)
{
node->object->update();
}
}
void ObjectStore::handleOrder(String objectName, byte orderVec[], long orderVecLen)
{
for (ObjectStoreNode* node = this->first; node != NULL; node = node->next)
{
if (node->object->hasName(objectName))
{
node->object->handleOrder(orderVec, orderVecLen);
}
}
}
void ObjectStore::loadSaved()
{
byte sd[200];
byte sdLength = Configuration::getSD(sd, 200);
byte currPos = 0;
int objNum = 0;
while (sdLength > currPos)
{
byte sdObjectLength = sd[currPos];
byte sdObjectType = sd[currPos + 1];
if (sdObjectType < 10) {
BasicObject* bo = this->functions[sdObjectType]();
bo->init(String("Points " + String(objNum + 1)), sd + (currPos + 2), sdObjectLength - 1);
ObjectStore::getInstance().addObject(bo);
}
currPos += sd[currPos] + 1;
objNum++;
}
}
void ObjectStore::registerType(int typeId, initObjectFunction fun)
{
this->functions[typeId] = fun;
}
<commit_msg>Fixed potential NULL pointer issue<commit_after>
#include "ObjectStore.h"
#include "Configuration.h"
ObjectStore::ObjectStore()
{
memset(this->functions, '\0', 10);
this->first = NULL;
this->last = NULL;
this->basicObjectCount = 0;
}
void ObjectStore::addObject(BasicObject* bo)
{
ObjectStoreNode* node = new ObjectStoreNode();
node->prev = this->last;
node->next = NULL;
node->object = bo;
if (this->first == NULL) {
this->first = node;
} else {
this->last->next = node;
}
this->last = node;
this->basicObjectCount++;
}
void ObjectStore::updateObjects()
{
for (ObjectStoreNode* node = this->first; node != NULL; node = node->next)
{
node->object->update();
}
}
void ObjectStore::handleOrder(String objectName, byte orderVec[], long orderVecLen)
{
for (ObjectStoreNode* node = this->first; node != NULL; node = node->next)
{
if (node->object->hasName(objectName))
{
node->object->handleOrder(orderVec, orderVecLen);
}
}
}
void ObjectStore::loadSaved()
{
byte sd[200];
byte sdLength = Configuration::getSD(sd, 200);
byte currPos = 0;
int objNum = 0;
while (sdLength > currPos)
{
byte sdObjectLength = sd[currPos];
byte sdObjectType = sd[currPos + 1];
if (sdObjectType < 10 && this.functions[sdObjectType] != NULL) {
BasicObject* bo = this->functions[sdObjectType]();
bo->init(String("Points " + String(objNum + 1)), sd + (currPos + 2), sdObjectLength - 1);
ObjectStore::getInstance().addObject(bo);
}
currPos += sd[currPos] + 1;
objNum++;
}
}
void ObjectStore::registerType(int typeId, initObjectFunction fun)
{
this->functions[typeId] = fun;
}
<|endoftext|> |
<commit_before>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/common.h>
#include <ode/odemath.h>
// this may be called for vectors `a' with extremely small magnitude, for
// example the result of a cross product on two nearly perpendicular vectors.
// we must be robust to these small vectors. to prevent numerical error,
// first find the component a[i] with the largest magnitude and then scale
// all the components by 1/a[i]. then we can compute the length of `a' and
// scale the components by 1/l. this has been verified to work with vectors
// containing the smallest representable numbers.
void dNormalize3 (dVector3 a)
{
dReal a0,a1,a2,aa0,aa1,aa2,l;
dAASSERT (a);
a0 = a[0];
a1 = a[1];
a2 = a[2];
aa0 = dFabs(a0);
aa1 = dFabs(a1);
aa2 = dFabs(a2);
if (aa1 > aa0) {
if (aa2 > aa1) {
goto aa2_largest;
}
else { // aa1 is largest
a0 /= aa1;
a2 /= aa1;
l = dRecipSqrt (a0*a0 + a2*a2 + 1);
a[0] = a0*l;
a[1] = dCopySign(l,a1);
a[2] = a2*l;
}
}
else {
if (aa2 > aa0) {
aa2_largest: // aa2 is largest
a0 /= aa2;
a1 /= aa2;
l = dRecipSqrt (a0*a0 + a1*a1 + 1);
a[0] = a0*l;
a[1] = a1*l;
a[2] = dCopySign(l,a2);
}
else { // aa0 is largest
if (aa0 <= 0) {
// dDEBUGMSG ("vector has zero size"); ... this messace is annoying
a[0] = 1; // if all a's are zero, this is where we'll end up.
a[1] = 0; // return a default unit length vector.
a[2] = 0;
return;
}
a1 /= aa0;
a2 /= aa0;
l = dRecipSqrt (a1*a1 + a2*a2 + 1);
a[0] = dCopySign(l,a0);
a[1] = a1*l;
a[2] = a2*l;
}
}
}
/* OLD VERSION */
/*
void dNormalize3 (dVector3 a)
{
dASSERT (a);
dReal l = dDOT(a,a);
if (l > 0) {
l = dRecipSqrt(l);
a[0] *= l;
a[1] *= l;
a[2] *= l;
}
else {
a[0] = 1;
a[1] = 0;
a[2] = 0;
}
}
*/
void dNormalize4 (dVector4 a)
{
dAASSERT (a);
dReal l = dDOT(a,a)+a[3]*a[3];
if (l > 0) {
l = dRecipSqrt(l);
a[0] *= l;
a[1] *= l;
a[2] *= l;
a[3] *= l;
}
else {
dDEBUGMSG ("vector has zero size");
a[0] = 1;
a[1] = 0;
a[2] = 0;
a[3] = 0;
}
}
void dPlaneSpace (const dVector3 n, dVector3 p, dVector3 q)
{
dAASSERT (n && p && q);
if (dFabs(n[2]) > M_SQRT1_2) {
// choose p in y-z plane
dReal a = n[1]*n[1] + n[2]*n[2];
dReal k = dRecipSqrt (a);
p[0] = 0;
p[1] = -n[2]*k;
p[2] = n[1]*k;
// set q = n x p
q[0] = a*k;
q[1] = -n[0]*p[2];
q[2] = n[0]*p[1];
}
else {
// choose p in x-y plane
dReal a = n[0]*n[0] + n[1]*n[1];
dReal k = dRecipSqrt (a);
p[0] = -n[1]*k;
p[1] = n[0]*k;
p[2] = 0;
// set q = n x p
q[0] = -n[2]*p[1];
q[1] = n[2]*p[0];
q[2] = a*k;
}
}
<commit_msg>Replaced WIN32/CYGWIN specific defines<commit_after>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/common.h>
#include <ode/odemath.h>
// get some math functions under windows
#ifdef WIN32
#include <float.h>
#ifndef CYGWIN // added by andy for cygwin
#define copysign(a,b) ((dReal)_copysign(a,b))
#endif // added by andy for cygwin
#endif
// this may be called for vectors `a' with extremely small magnitude, for
// example the result of a cross product on two nearly perpendicular vectors.
// we must be robust to these small vectors. to prevent numerical error,
// first find the component a[i] with the largest magnitude and then scale
// all the components by 1/a[i]. then we can compute the length of `a' and
// scale the components by 1/l. this has been verified to work with vectors
// containing the smallest representable numbers.
void dNormalize3 (dVector3 a)
{
dReal a0,a1,a2,aa0,aa1,aa2,l;
dAASSERT (a);
a0 = a[0];
a1 = a[1];
a2 = a[2];
aa0 = dFabs(a0);
aa1 = dFabs(a1);
aa2 = dFabs(a2);
if (aa1 > aa0) {
if (aa2 > aa1) {
goto aa2_largest;
}
else { // aa1 is largest
a0 /= aa1;
a2 /= aa1;
l = dRecipSqrt (a0*a0 + a2*a2 + 1);
a[0] = a0*l;
a[1] = dCopySign(l,a1);
a[2] = a2*l;
}
}
else {
if (aa2 > aa0) {
aa2_largest: // aa2 is largest
a0 /= aa2;
a1 /= aa2;
l = dRecipSqrt (a0*a0 + a1*a1 + 1);
a[0] = a0*l;
a[1] = a1*l;
a[2] = dCopySign(l,a2);
}
else { // aa0 is largest
if (aa0 <= 0) {
// dDEBUGMSG ("vector has zero size"); ... this messace is annoying
a[0] = 1; // if all a's are zero, this is where we'll end up.
a[1] = 0; // return a default unit length vector.
a[2] = 0;
return;
}
a1 /= aa0;
a2 /= aa0;
l = dRecipSqrt (a1*a1 + a2*a2 + 1);
a[0] = dCopySign(l,a0);
a[1] = a1*l;
a[2] = a2*l;
}
}
}
/* OLD VERSION */
/*
void dNormalize3 (dVector3 a)
{
dASSERT (a);
dReal l = dDOT(a,a);
if (l > 0) {
l = dRecipSqrt(l);
a[0] *= l;
a[1] *= l;
a[2] *= l;
}
else {
a[0] = 1;
a[1] = 0;
a[2] = 0;
}
}
*/
void dNormalize4 (dVector4 a)
{
dAASSERT (a);
dReal l = dDOT(a,a)+a[3]*a[3];
if (l > 0) {
l = dRecipSqrt(l);
a[0] *= l;
a[1] *= l;
a[2] *= l;
a[3] *= l;
}
else {
dDEBUGMSG ("vector has zero size");
a[0] = 1;
a[1] = 0;
a[2] = 0;
a[3] = 0;
}
}
void dPlaneSpace (const dVector3 n, dVector3 p, dVector3 q)
{
dAASSERT (n && p && q);
if (dFabs(n[2]) > M_SQRT1_2) {
// choose p in y-z plane
dReal a = n[1]*n[1] + n[2]*n[2];
dReal k = dRecipSqrt (a);
p[0] = 0;
p[1] = -n[2]*k;
p[2] = n[1]*k;
// set q = n x p
q[0] = a*k;
q[1] = -n[0]*p[2];
q[2] = n[0]*p[1];
}
else {
// choose p in x-y plane
dReal a = n[0]*n[0] + n[1]*n[1];
dReal k = dRecipSqrt (a);
p[0] = -n[1]*k;
p[1] = n[0]*k;
p[2] = 0;
// set q = n x p
q[0] = -n[2]*p[1];
q[1] = n[2]*p[0];
q[2] = a*k;
}
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "StateSpace3.h"
#include "PriorityQueue.h"
#include "State3.h"
#include "environment.h"
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature(unsigned long t);
//function to select next action
float selectAction(PriorityQueue<float, double>& a_queue, unsigned long int iterations);
//function to update a q value
void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
//learning factor
const double alpha = 0.5;
//discount factor
const double gamma = 0.5;
const double deltatime = 0.1;
const double mass = 0.5;
const double length = 0.08;
const int angle_bins = 100;
const int velocity_bins = 50;
const int torque_bins = 9;
const double maxangle = 4;
const double maxvelocity = 4;
const double maxtorque = 4;
/*for (int i = 0; i < torque_bins; ++i) {
const int t_i = -maxtorque + i;
}*/
environment* env = new environment(0, 0, 0, maxtorque, 0, deltatime, mass, length, gamma);
//seed rng
std::srand(static_cast<unsigned int>(std::time(NULL)));
//create pointers to the possible actions as well as a pointer to hold the chosen action
float chosen_action = 1.0f; // THE F MUST NOT BE DELETED UNDER ANY CIRCUMSTANCES
float actions[torque_bins];
for (int i = 0; i < (maxtorque*2)+1 ; ++i) {
actions[i] = static_cast<float>(-maxtorque+i);
}
//create a priority queue to copy to all the state space priority queues
PriorityQueue<float, double> initiator_queue(MAX);
for (int i = 0; i < torque_bins; ++i) {
initiator_queue.enqueueWithPriority(actions[i], 0);
}
//create the state space
StateSpace space(initiator_queue, angle_bins, velocity_bins, torque_bins, maxangle, maxvelocity, maxtorque);
//state objects
State current_state(0, 0, 0);
State old_state(0, 0, 0);
std::ofstream file("output.txt");
file.precision(16);
file << "Trialno" << " " << "Time" << " " << "Theta" << " " << "Thetadot" << " " << "Torque" << std::endl;
double trialno = 1;
unsigned long i=0UL;
while (true)
{
current_state.theta = env->getTheta();
current_state.theta_dot = env->getThetadot();
current_state.torque = env->getTorque();
std::cout << "State Read" << std::endl;
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
std::cout << "Q Updated" << std::endl;
if (current_state.theta>2 * 3.1415 && current_state.theta_dot>2 * 3.1415 && env->getTime() >= 10) {
env->resetPendulum();
std::domain_error("unsuccessful trial");
trialno++;
i = 0;
}
old_state = current_state;
chosen_action = selectAction(space[current_state],i);
std::cout << "Action Selected" << std::endl;
env->setTorque(chosen_action);
env->propagate();
std::cout << "Environment Propogated\n" << std::endl;
file << trialno << " " << env->getTime() << " " << current_state.theta << " " << current_state.theta_dot << " " << current_state.torque << std::endl;
++i;
}
file.close();
delete env;
return 1;
}
double temperature(unsigned long t) {
return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}
int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {
typedef std::vector<std::pair<int, double> > VecPair ;
//turn priority queue into a vector of pairs
VecPair vec = a_queue.saveOrderedQueueAsVector();
//sum for partition function
double sum = 0.0;
// calculate partition function by iterating over action-values
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature(iterations));
}
// compute Boltzmann factors for action-values and enqueue to vec
for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
iter->second = std::exp(iter->second / temperature(iterations)) / sum;
}
// calculate cumulative probability distribution
for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
//second member of pair becomes addition of its current value
//and that of the index before it
iter->second += (iter-1)->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma)
{
//std::cout << action << std::endl;
//std::cout << space[old_state].toString() << std::endl << "-----------";
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
std::cout << "Reward: " << R << std::endl;
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
//std::cout << "New Q-Value: " << newQ << std::endl;
space[old_state].changePriority(action, newQ);
}
<commit_msg>fixed selectAction defn<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "StateSpace3.h"
#include "PriorityQueue.h"
#include "State3.h"
#include "environment.h"
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature(unsigned long t);
//function to select next action
float selectAction(PriorityQueue<float, double>& a_queue, unsigned long int iterations);
//function to update a q value
void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
//learning factor
const double alpha = 0.5;
//discount factor
const double gamma = 0.5;
const double deltatime = 0.1;
const double mass = 0.5;
const double length = 0.08;
const int angle_bins = 100;
const int velocity_bins = 50;
const int torque_bins = 9;
const double maxangle = 4;
const double maxvelocity = 4;
const double maxtorque = 4;
/*for (int i = 0; i < torque_bins; ++i) {
const int t_i = -maxtorque + i;
}*/
environment* env = new environment(0, 0, 0, maxtorque, 0, deltatime, mass, length, gamma);
//seed rng
std::srand(static_cast<unsigned int>(std::time(NULL)));
//create pointers to the possible actions as well as a pointer to hold the chosen action
float chosen_action = 1.0f; // THE F MUST NOT BE DELETED UNDER ANY CIRCUMSTANCES
float actions[torque_bins];
for (int i = 0; i < (maxtorque*2)+1 ; ++i) {
actions[i] = static_cast<float>(-maxtorque+i);
}
//create a priority queue to copy to all the state space priority queues
PriorityQueue<float, double> initiator_queue(MAX);
for (int i = 0; i < torque_bins; ++i) {
initiator_queue.enqueueWithPriority(actions[i], 0);
}
//create the state space
StateSpace space(initiator_queue, angle_bins, velocity_bins, torque_bins, maxangle, maxvelocity, maxtorque);
//state objects
State current_state(0, 0, 0);
State old_state(0, 0, 0);
std::ofstream file("output.txt");
file.precision(16);
file << "Trialno" << " " << "Time" << " " << "Theta" << " " << "Thetadot" << " " << "Torque" << std::endl;
double trialno = 1;
unsigned long i=0UL;
while (true)
{
current_state.theta = env->getTheta();
current_state.theta_dot = env->getThetadot();
current_state.torque = env->getTorque();
std::cout << "State Read" << std::endl;
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
std::cout << "Q Updated" << std::endl;
if (current_state.theta>2 * 3.1415 && current_state.theta_dot>2 * 3.1415 && env->getTime() >= 10) {
env->resetPendulum();
std::domain_error("unsuccessful trial");
trialno++;
i = 0;
}
old_state = current_state;
chosen_action = selectAction(space[current_state],i);
std::cout << "Action Selected" << std::endl;
env->setTorque(chosen_action);
env->propagate();
std::cout << "Environment Propogated\n" << std::endl;
file << trialno << " " << env->getTime() << " " << current_state.theta << " " << current_state.theta_dot << " " << current_state.torque << std::endl;
++i;
}
file.close();
delete env;
return 1;
}
double temperature(unsigned long t) {
return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}
float selectAction(PriorityQueue<float, double>& a_queue, unsigned long iterations) {
typedef std::vector<std::pair<float, double> > VecPair ;
//turn priority queue into a vector of pairs
VecPair vec = a_queue.saveOrderedQueueAsVector();
//sum for partition function
double sum = 0.0;
// calculate partition function by iterating over action-values
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature(iterations));
}
// compute Boltzmann factors for action-values and enqueue to vec
for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
iter->second = std::exp(iter->second / temperature(iterations)) / sum;
}
// calculate cumulative probability distribution
for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
//second member of pair becomes addition of its current value
//and that of the index before it
iter->second += (iter-1)->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
void updateQ(StateSpace & space, float action, State & new_state, State & old_state, double alpha, double gamma)
{
//std::cout << action << std::endl;
//std::cout << space[old_state].toString() << std::endl << "-----------";
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
std::cout << "Reward: " << R << std::endl;
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
//std::cout << "New Q-Value: " << newQ << std::endl;
space[old_state].changePriority(action, newQ);
}
<|endoftext|> |
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file showClock.cpp
* @author Geoff Lawler <geoff.lawler@cobham.com>
* @date 2009-07-15
*/
/**
* @page showClock
*
* showClock is a test node command line program that "draws" a clock by arranging a set of nodes and edges into the shape of an
* analog clock. The "clock" is updated once a second to move "the hands" of the clock around. This program is mostly
* used to test the "TiVO" functionality built into the watcher system.
*
* Usage:
* @{
* <b>showClock -s server [optional args]</b>
* @}
* @{
* Args:
* @arg <b>-s, --server=address|name</b>, The address or name of the node running watcherd
* @}
* Optional args:
* @arg <b>-r, --radius</b>, The radius of the clock face in some unknown unit
* @arg <b>-S, --hideSecondRing</b> Don't send message to draw the outer, second hand ring.
* @arg <b>-H, --hideHourRing</b> Don't send message to draw the inner, hour hand ring.
* @arg <b>-p, --logProps=file</b>, log.properties file, which controls logging for this program
* @arg <b>-h, --help</b>, Show help message
*/
#include <getopt.h>
#include <string>
#include <math.h>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <libwatcher/client.h>
#include <libwatcher/gpsMessage.h>
#include <libwatcher/labelMessage.h>
#include <libwatcher/edgeMessage.h>
#include <libwatcher/watcherColors.h>
#include <libwatcher/colors.h>
#include "logger.h"
#include <libwatcher/sendMessageHandler.h>
DECLARE_GLOBAL_LOGGER("showClock");
using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;
#define PI (3.141592653589793) // Isn't this #DEFINEd somewhere?
void usage(const char *progName)
{
fprintf(stderr, "Usage: %s [args]\n", basename(progName));
fprintf(stderr, "Args:\n");
fprintf(stderr, " -s, --server=address The addres of the node running watcherd\n");
fprintf(stderr, "\n");
fprintf(stderr, "Optional args:\n");
fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n");
fprintf(stderr, " -r, --radius The radius of the circle in some unknown unit\n");
fprintf(stderr, " -S, --hideSecondRing Don't send message to draw the outer, second hand ring\n");
fprintf(stderr, " -H, --hideHourRing Don't send message to draw the inner, hour hand ring\n");
fprintf(stderr, " -t, --latitude Place the clock at this latitude (def==0).\n");
fprintf(stderr, " -g, --longitude Place the clock at this longitude (def==0).\n");
fprintf(stderr, " -x, --gpsScale Factor the GPS positions by this much (def==1)\n");
fprintf(stderr, "\n");
fprintf(stderr, " -h, --help Show this message\n");
exit(1);
}
int main(int argc, char **argv)
{
TRACE_ENTER();
int c;
string server;
string logProps(string(basename(argv[0]))+string(".log.properties"));
double radius=50.0;
bool showSecondRing=true, showHourRing=true;
double offsetLong=0, offsetLat=0;
double gpsScale=1;
while (true)
{
int option_index = 0;
static struct option long_options[] = {
{"server", required_argument, 0, 's'},
{"logProps", required_argument, 0, 'p'},
{"radius", no_argument, 0, 'r'},
{"hideSecondRing", no_argument, 0, 'S'},
{"hideHourRing", no_argument, 0, 'H'},
{"latitude", required_argument, 0, 't'},
{"longitude", required_argument, 0, 'g'},
{"gpsScale", required_argument, 0, 'x'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "r:s:p:t:g:x:eSHh?", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 's':
server=optarg;
break;
case 'p':
logProps=optarg;
break;
case 'r':
radius=lexical_cast<double>(optarg);
break;
case 'S':
showSecondRing=false;
break;
case 'H':
showHourRing=false;
break;
case 'g':
offsetLong=lexical_cast<double>(optarg);
break;
case 't':
offsetLat=lexical_cast<double>(optarg);
break;
case 'x':
gpsScale=lexical_cast<double>(optarg);
break;
case 'h':
case '?':
default:
usage(argv[0]);
break;
}
}
if (server=="")
{
usage(argv[0]);
exit(1);
}
//
// Now do some actual work.
//
LOAD_LOG_PROPS(logProps);
Client client(server);
LOG_INFO("Connecting to " << server << " and sending message.");
// Do not add empty handler - default Client handler does not close connection.
// client.addMessageHandler(SendMessageHandler::create());
unsigned int loopTime=1;
// Create hour, min, sec, and center nodes.
NodeIdentifier centerId=NodeIdentifier::from_string("192.168.1.100");
NodeIdentifier hourId=NodeIdentifier::from_string("192.168.1.101");
NodeIdentifier minId=NodeIdentifier::from_string("192.168.1.102");
NodeIdentifier secId=NodeIdentifier::from_string("192.168.1.103");
const GUILayer hourLayer("Hour");
const GUILayer minLayer("Min");
const GUILayer secLayer("Sec");
const GUILayer hourRingLayer("HourRing");
const GUILayer secRingLayer("SecondRing");
const double step=(2*PI)/60;
struct
{
double theta;
NodeIdentifier *id;
const char *label;
double length;
const GUILayer layer;
} nodeData[]=
{
{ 0, &hourId, "hour", radius*0.7, hourLayer },
{ 0, &minId, "min", radius, minLayer },
{ 0, &secId, "sec", radius, secLayer },
};
while (true) // draw everything all the time as we don't know when watcher will start
{
vector<MessagePtr> messages;
// Draw center node
GPSMessagePtr gpsMess(new GPSMessage(gpsScale*(offsetLong+radius), gpsScale*(offsetLat+radius), 0));
gpsMess->layer=hourLayer; // meh.
gpsMess->fromNodeID=centerId;
messages.push_back(gpsMess);
for (unsigned int i=0; i<sizeof(nodeData)/sizeof(nodeData[0]); i++)
{
// update location offsets by current time.
time_t nowInSecs=time(NULL);
struct tm *now=localtime(&nowInSecs);
if (*nodeData[i].id==hourId)
nodeData[i].theta=step*((now->tm_hour*(60/12))+(now->tm_min/12));
else if(*nodeData[i].id==minId)
nodeData[i].theta=step*now->tm_min;
else if(*nodeData[i].id==secId)
nodeData[i].theta=step*now->tm_sec;
// Move hour. min, and sec nodes to appropriate locations.
GPSMessagePtr gpsMess(new GPSMessage(
gpsScale*(offsetLong+(sin(nodeData[i].theta)*nodeData[i].length)+radius),
gpsScale*(offsetLat+(cos(nodeData[i].theta)*nodeData[i].length)+radius),
(double)i));
gpsMess->layer=nodeData[i].layer;
gpsMess->fromNodeID=*nodeData[i].id;
messages.push_back(gpsMess);
EdgeMessagePtr edge(new EdgeMessage(centerId, *nodeData[i].id, nodeData[i].layer,
colors::blue, 2.0, false, loopTime*1500, true));
LabelMessagePtr labMess(new LabelMessage(nodeData[i].label));
labMess->layer=nodeData[i].layer;
labMess->expiration=loopTime*1500;
edge->middleLabel=labMess;
LabelMessagePtr numLabMess(new LabelMessage);
if (*nodeData[i].id==hourId)
numLabMess->label=boost::lexical_cast<string>(now->tm_hour%12);
else if(*nodeData[i].id==minId)
numLabMess->label=boost::lexical_cast<string>(now->tm_min);
else if(*nodeData[i].id==secId)
numLabMess->label=boost::lexical_cast<string>(now->tm_sec);
numLabMess->layer=nodeData[i].layer;
numLabMess->expiration=loopTime*1500;
edge->node2Label=numLabMess;
messages.push_back(edge);
}
if (showHourRing)
{
// add nodes at clock face number locations.
double theta=(2*PI)/12;
for (unsigned int i=0; i<12; i++, theta+=(2*PI)/12)
{
NodeIdentifier thisId=NodeIdentifier::from_string("192.168.2." + lexical_cast<string>(i+1));
GPSMessagePtr gpsMess(new GPSMessage(
gpsScale*(offsetLong+((sin(theta)*radius)+radius)),
gpsScale*(offsetLat+((cos(theta)*radius)+radius)),
0.0));
gpsMess->layer=hourRingLayer;
gpsMess->fromNodeID=thisId;
messages.push_back(gpsMess);
}
}
if (showSecondRing)
{
// add nodes at clock face second locations.
double theta=(2*PI)/60;
for (unsigned int i=0; i<60; i++, theta+=(2*PI)/60)
{
NodeIdentifier thisId=NodeIdentifier::from_string("192.168.3." + lexical_cast<string>(i+1));
double faceRad=radius*1.15;
GPSMessagePtr gpsMess(new GPSMessage(
gpsScale*(offsetLong+((sin(theta)*faceRad)+radius)),
gpsScale*(offsetLat+((cos(theta)*faceRad)+radius)), 0.0));
gpsMess->layer=secRingLayer;
gpsMess->fromNodeID=thisId;
messages.push_back(gpsMess);
}
}
if (!messages.empty()) {
if(!client.sendMessages(messages)) {
LOG_ERROR("Error sending " << messages.size() << " messages.");
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
}
sleep(loopTime);
}
client.wait();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
}
<commit_msg>add DataPointMessages for the hour, minute, and second nodes for testing Data Watcher.<commit_after>/* Copyright 2009, 2010 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file showClock.cpp
* @author Geoff Lawler <geoff.lawler@cobham.com>
* @date 2009-07-15
*/
/**
* @page showClock
*
* showClock is a test node command line program that "draws" a clock by arranging a set of nodes and edges into the shape of an
* analog clock. The "clock" is updated once a second to move "the hands" of the clock around. This program is mostly
* used to test the "TiVO" functionality built into the watcher system.
*
* Usage:
* @{
* <b>showClock -s server [optional args]</b>
* @}
* @{
* Args:
* @arg <b>-s, --server=address|name</b>, The address or name of the node running watcherd
* @}
* Optional args:
* @arg <b>-r, --radius</b>, The radius of the clock face in some unknown unit
* @arg <b>-S, --hideSecondRing</b> Don't send message to draw the outer, second hand ring.
* @arg <b>-H, --hideHourRing</b> Don't send message to draw the inner, hour hand ring.
* @arg <b>-p, --logProps=file</b>, log.properties file, which controls logging for this program
* @arg <b>-h, --help</b>, Show help message
*/
#include <getopt.h>
#include <string>
#include <math.h>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <libwatcher/client.h>
#include <libwatcher/gpsMessage.h>
#include <libwatcher/labelMessage.h>
#include <libwatcher/edgeMessage.h>
#include <libwatcher/watcherColors.h>
#include <libwatcher/colors.h>
#include "logger.h"
#include <libwatcher/sendMessageHandler.h>
#include <libwatcher/dataPointMessage.h>
DECLARE_GLOBAL_LOGGER("showClock");
using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;
#define PI (3.141592653589793) // Isn't this #DEFINEd somewhere?
void usage(const char *progName)
{
fprintf(stderr, "Usage: %s [args]\n", basename(progName));
fprintf(stderr, "Args:\n");
fprintf(stderr, " -s, --server=address The addres of the node running watcherd\n");
fprintf(stderr, "\n");
fprintf(stderr, "Optional args:\n");
fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n");
fprintf(stderr, " -r, --radius The radius of the circle in some unknown unit\n");
fprintf(stderr, " -S, --hideSecondRing Don't send message to draw the outer, second hand ring\n");
fprintf(stderr, " -H, --hideHourRing Don't send message to draw the inner, hour hand ring\n");
fprintf(stderr, " -t, --latitude Place the clock at this latitude (def==0).\n");
fprintf(stderr, " -g, --longitude Place the clock at this longitude (def==0).\n");
fprintf(stderr, " -x, --gpsScale Factor the GPS positions by this much (def==1)\n");
fprintf(stderr, "\n");
fprintf(stderr, " -h, --help Show this message\n");
exit(1);
}
int main(int argc, char **argv)
{
TRACE_ENTER();
int c;
string server;
string logProps(string(basename(argv[0]))+string(".log.properties"));
double radius=50.0;
bool showSecondRing=true, showHourRing=true;
double offsetLong=0, offsetLat=0;
double gpsScale=1;
// dataPoint values for each node
int minuteDP[60] = {0,};
int secDP[60] = {0,};
while (true)
{
int option_index = 0;
static struct option long_options[] = {
{"server", required_argument, 0, 's'},
{"logProps", required_argument, 0, 'p'},
{"radius", no_argument, 0, 'r'},
{"hideSecondRing", no_argument, 0, 'S'},
{"hideHourRing", no_argument, 0, 'H'},
{"latitude", required_argument, 0, 't'},
{"longitude", required_argument, 0, 'g'},
{"gpsScale", required_argument, 0, 'x'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "r:s:p:t:g:x:eSHh?", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 's':
server=optarg;
break;
case 'p':
logProps=optarg;
break;
case 'r':
radius=lexical_cast<double>(optarg);
break;
case 'S':
showSecondRing=false;
break;
case 'H':
showHourRing=false;
break;
case 'g':
offsetLong=lexical_cast<double>(optarg);
break;
case 't':
offsetLat=lexical_cast<double>(optarg);
break;
case 'x':
gpsScale=lexical_cast<double>(optarg);
break;
case 'h':
case '?':
default:
usage(argv[0]);
break;
}
}
if (server=="")
{
usage(argv[0]);
exit(1);
}
//
// Now do some actual work.
//
LOAD_LOG_PROPS(logProps);
Client client(server);
LOG_INFO("Connecting to " << server << " and sending message.");
// Do not add empty handler - default Client handler does not close connection.
// client.addMessageHandler(SendMessageHandler::create());
unsigned int loopTime=1;
// Create hour, min, sec, and center nodes.
NodeIdentifier centerId=NodeIdentifier::from_string("192.168.1.100");
NodeIdentifier hourId=NodeIdentifier::from_string("192.168.1.101");
NodeIdentifier minId=NodeIdentifier::from_string("192.168.1.102");
NodeIdentifier secId=NodeIdentifier::from_string("192.168.1.103");
const GUILayer hourLayer("Hour");
const GUILayer minLayer("Min");
const GUILayer secLayer("Sec");
const GUILayer hourRingLayer("HourRing");
const GUILayer secRingLayer("SecondRing");
const double step=(2*PI)/60;
struct
{
double theta;
NodeIdentifier *id;
const char *label;
double length;
const GUILayer layer;
double dataPoint[2];
} nodeData[]=
{
{ 0, &hourId, "hour", radius*0.7, hourLayer, { 0, 0 } },
{ 0, &minId, "min", radius, minLayer, { 0, 0 } },
{ 0, &secId, "sec", radius, secLayer, { 0, 0 } },
};
while (true) // draw everything all the time as we don't know when watcher will start
{
vector<MessagePtr> messages;
// Draw center node
GPSMessagePtr gpsMess(new GPSMessage(gpsScale*(offsetLong+radius), gpsScale*(offsetLat+radius), 0));
gpsMess->layer=hourLayer; // meh.
gpsMess->fromNodeID=centerId;
messages.push_back(gpsMess);
for (unsigned int i=0; i<sizeof(nodeData)/sizeof(nodeData[0]); i++)
{
// update location offsets by current time.
time_t nowInSecs=time(NULL);
struct tm *now=localtime(&nowInSecs);
if (*nodeData[i].id==hourId)
nodeData[i].theta=step*((now->tm_hour*(60/12))+(now->tm_min/12));
else if(*nodeData[i].id==minId)
nodeData[i].theta=step*now->tm_min;
else if(*nodeData[i].id==secId)
nodeData[i].theta=step*now->tm_sec;
// Move hour. min, and sec nodes to appropriate locations.
GPSMessagePtr gpsMess(new GPSMessage(
gpsScale*(offsetLong+(sin(nodeData[i].theta)*nodeData[i].length)+radius),
gpsScale*(offsetLat+(cos(nodeData[i].theta)*nodeData[i].length)+radius),
(double)i));
gpsMess->layer=nodeData[i].layer;
gpsMess->fromNodeID=*nodeData[i].id;
messages.push_back(gpsMess);
EdgeMessagePtr edge(new EdgeMessage(centerId, *nodeData[i].id, nodeData[i].layer,
colors::blue, 2.0, false, loopTime*1500, true));
LabelMessagePtr labMess(new LabelMessage(nodeData[i].label));
labMess->layer=nodeData[i].layer;
labMess->expiration=loopTime*1500;
edge->middleLabel=labMess;
LabelMessagePtr numLabMess(new LabelMessage);
if (*nodeData[i].id==hourId)
numLabMess->label=boost::lexical_cast<string>(now->tm_hour%12);
else if(*nodeData[i].id==minId)
numLabMess->label=boost::lexical_cast<string>(now->tm_min);
else if(*nodeData[i].id==secId)
numLabMess->label=boost::lexical_cast<string>(now->tm_sec);
numLabMess->layer=nodeData[i].layer;
numLabMess->expiration=loopTime*1500;
edge->node2Label=numLabMess;
messages.push_back(edge);
int unit = (rand() <= RAND_MAX/2) ? -1 : +1;
DataPointMessagePtr dataMess0(new DataPointMessage);
nodeData[i].dataPoint[0] += unit;
dataMess0->fromNodeID = *nodeData[i].id;
dataMess0->dataPoints.push_back(nodeData[i].dataPoint[0]);
dataMess0->dataName = "data0";
messages.push_back(dataMess0);
unit = (rand() <= RAND_MAX/2) ? -1 : +1;
nodeData[i].dataPoint[1] += unit;
DataPointMessagePtr dataMess1(new DataPointMessage);
dataMess1->fromNodeID = *nodeData[i].id;
dataMess1->dataPoints.push_back(nodeData[i].dataPoint[1]);
dataMess1->dataName = "data1";
messages.push_back(dataMess1);
}
if (showHourRing)
{
// add nodes at clock face number locations.
double theta=(2*PI)/12;
for (unsigned int i=0; i<12; i++, theta+=(2*PI)/12)
{
NodeIdentifier thisId=NodeIdentifier::from_string("192.168.2." + lexical_cast<string>(i+1));
GPSMessagePtr gpsMess(new GPSMessage(
gpsScale*(offsetLong+((sin(theta)*radius)+radius)),
gpsScale*(offsetLat+((cos(theta)*radius)+radius)),
0.0));
gpsMess->layer=hourRingLayer;
gpsMess->fromNodeID=thisId;
messages.push_back(gpsMess);
}
}
if (showSecondRing)
{
// add nodes at clock face second locations.
double theta=(2*PI)/60;
for (unsigned int i=0; i<60; i++, theta+=(2*PI)/60)
{
NodeIdentifier thisId=NodeIdentifier::from_string("192.168.3." + lexical_cast<string>(i+1));
double faceRad=radius*1.15;
GPSMessagePtr gpsMess(new GPSMessage(
gpsScale*(offsetLong+((sin(theta)*faceRad)+radius)),
gpsScale*(offsetLat+((cos(theta)*faceRad)+radius)), 0.0));
gpsMess->layer=secRingLayer;
gpsMess->fromNodeID=thisId;
messages.push_back(gpsMess);
}
}
if (!messages.empty()) {
if(!client.sendMessages(messages)) {
LOG_ERROR("Error sending " << messages.size() << " messages.");
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
}
sleep(loopTime);
}
client.wait();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "clustering/administration/http/server.hpp"
#include "clustering/administration/http/directory_app.hpp"
#include "clustering/administration/http/issues_app.hpp"
#include "clustering/administration/http/last_seen_app.hpp"
#include "clustering/administration/http/log_app.hpp"
#include "clustering/administration/http/progress_app.hpp"
#include "clustering/administration/http/semilattice_app.hpp"
#include "clustering/administration/http/stat_app.hpp"
#include "http/file_app.hpp"
#include "http/http.hpp"
#include "http/routing_app.hpp"
#include "rpc/directory/watchable_copier.hpp"
std::map<peer_id_t, log_server_business_card_t> get_log_mailbox(const std::map<peer_id_t, cluster_directory_metadata_t> &md) {
std::map<peer_id_t, log_server_business_card_t> out;
for (std::map<peer_id_t, cluster_directory_metadata_t>::const_iterator it = md.begin(); it != md.end(); it++) {
out.insert(std::make_pair(it->first, it->second.log_mailbox));
}
return out;
}
std::map<peer_id_t, machine_id_t> get_machine_id(const std::map<peer_id_t, cluster_directory_metadata_t> &md) {
std::map<peer_id_t, machine_id_t> out;
for (std::map<peer_id_t, cluster_directory_metadata_t>::const_iterator it = md.begin(); it != md.end(); it++) {
out.insert(std::make_pair(it->first, it->second.machine_id));
}
return out;
}
administrative_http_server_manager_t::administrative_http_server_manager_t(
int port,
mailbox_manager_t *mbox_manager,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> > _semilattice_metadata,
clone_ptr_t<watchable_t<std::map<peer_id_t, cluster_directory_metadata_t> > > _directory_metadata,
global_issue_tracker_t *_issue_tracker,
last_seen_tracker_t *_last_seen_tracker,
boost::uuids::uuid _us,
std::string path)
{
std::set<std::string> white_list;
white_list.insert("/cluster.css");
white_list.insert("/cluster.html");
white_list.insert("/cluster-min.js");
white_list.insert("/favicon.ico");
white_list.insert("/js/backbone.js");
white_list.insert("/js/bootstrap/bootstrap-alert.js");
white_list.insert("/js/bootstrap/bootstrap-modal.js");
white_list.insert("/js/bootstrap/bootstrap-tab.js");
white_list.insert("/js/bootstrap/bootstrap-typeahead.js");
white_list.insert("/js/bootstrap/bootstrap-collapse.js");
white_list.insert("/js/d3.v2.min.js");
white_list.insert("/js/date-en-US.js");
white_list.insert("/js/flot/jquery.flot.js");
white_list.insert("/js/flot/jquery.flot.resize.js");
white_list.insert("/js/handlebars-1.0.0.beta.6.js");
white_list.insert("/js/jquery-1.7.1.min.js");
white_list.insert("/js/jquery.dataTables.min.js");
white_list.insert("/js/jquery.form.js");
white_list.insert("/js/jquery.hotkeys.js");
white_list.insert("/js/jquery.sparkline.min.js");
white_list.insert("/js/jquery.timeago.js");
white_list.insert("/js/jquery.validate.min.js");
white_list.insert("/js/underscore-min.js");
white_list.insert("/images/alert-icon_small.png");
white_list.insert("/images/critical-issue_small.png");
white_list.insert("/images/information-icon_small.png");
white_list.insert("/images/mini_right-arrow.png");
white_list.insert("/images/mini_down-arrow.png");
white_list.insert("/index.html");
file_app.reset(new file_http_app_t(white_list, path));
semilattice_app.reset(new semilattice_http_app_t(_semilattice_metadata, _directory_metadata, _us));
directory_app.reset(new directory_http_app_t(_directory_metadata));
issues_app.reset(new issues_http_app_t(_issue_tracker));
stat_app.reset(new stat_http_app_t(mbox_manager, _directory_metadata));
last_seen_app.reset(new last_seen_http_app_t(_last_seen_tracker));
log_app.reset(new log_http_app_t(mbox_manager,
_directory_metadata->subview(&get_log_mailbox),
_directory_metadata->subview(&get_machine_id)
));
progress_app.reset(new progress_app_t(_directory_metadata, mbox_manager));
std::map<std::string, http_app_t *> ajax_routes;
ajax_routes["directory"] = directory_app.get();
ajax_routes["issues"] = issues_app.get();
ajax_routes["stat"] = stat_app.get();
ajax_routes["last_seen"] = last_seen_app.get();
ajax_routes["log"] = log_app.get();
ajax_routes["progress"] = progress_app.get();
ajax_routing_app.reset(new routing_http_app_t(semilattice_app.get(), ajax_routes));
std::map<std::string, http_app_t *> root_routes;
root_routes["ajax"] = ajax_routing_app.get();
root_routing_app.reset(new routing_http_app_t(file_app.get(), root_routes));
server.reset(new http_server_t(port, root_routing_app.get()));
}
administrative_http_server_manager_t::~administrative_http_server_manager_t() {
/* This must be declared in the `.cc` file because the definitions of the
destructors for the things in `boost::scoped_ptr`s are not available from
the `.hpp` file. */
}
<commit_msg>Adding whitelist bootstrap button<commit_after>#include "clustering/administration/http/server.hpp"
#include "clustering/administration/http/directory_app.hpp"
#include "clustering/administration/http/issues_app.hpp"
#include "clustering/administration/http/last_seen_app.hpp"
#include "clustering/administration/http/log_app.hpp"
#include "clustering/administration/http/progress_app.hpp"
#include "clustering/administration/http/semilattice_app.hpp"
#include "clustering/administration/http/stat_app.hpp"
#include "http/file_app.hpp"
#include "http/http.hpp"
#include "http/routing_app.hpp"
#include "rpc/directory/watchable_copier.hpp"
std::map<peer_id_t, log_server_business_card_t> get_log_mailbox(const std::map<peer_id_t, cluster_directory_metadata_t> &md) {
std::map<peer_id_t, log_server_business_card_t> out;
for (std::map<peer_id_t, cluster_directory_metadata_t>::const_iterator it = md.begin(); it != md.end(); it++) {
out.insert(std::make_pair(it->first, it->second.log_mailbox));
}
return out;
}
std::map<peer_id_t, machine_id_t> get_machine_id(const std::map<peer_id_t, cluster_directory_metadata_t> &md) {
std::map<peer_id_t, machine_id_t> out;
for (std::map<peer_id_t, cluster_directory_metadata_t>::const_iterator it = md.begin(); it != md.end(); it++) {
out.insert(std::make_pair(it->first, it->second.machine_id));
}
return out;
}
administrative_http_server_manager_t::administrative_http_server_manager_t(
int port,
mailbox_manager_t *mbox_manager,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> > _semilattice_metadata,
clone_ptr_t<watchable_t<std::map<peer_id_t, cluster_directory_metadata_t> > > _directory_metadata,
global_issue_tracker_t *_issue_tracker,
last_seen_tracker_t *_last_seen_tracker,
boost::uuids::uuid _us,
std::string path)
{
std::set<std::string> white_list;
white_list.insert("/cluster.css");
white_list.insert("/cluster.html");
white_list.insert("/cluster-min.js");
white_list.insert("/favicon.ico");
white_list.insert("/js/backbone.js");
white_list.insert("/js/bootstrap/bootstrap-alert.js");
white_list.insert("/js/bootstrap/bootstrap-modal.js");
white_list.insert("/js/bootstrap/bootstrap-tab.js");
white_list.insert("/js/bootstrap/bootstrap-typeahead.js");
white_list.insert("/js/bootstrap/bootstrap-collapse.js");
white_list.insert("/js/bootstrap/bootstrap-button.js");
white_list.insert("/js/d3.v2.min.js");
white_list.insert("/js/date-en-US.js");
white_list.insert("/js/flot/jquery.flot.js");
white_list.insert("/js/flot/jquery.flot.resize.js");
white_list.insert("/js/handlebars-1.0.0.beta.6.js");
white_list.insert("/js/jquery-1.7.1.min.js");
white_list.insert("/js/jquery.dataTables.min.js");
white_list.insert("/js/jquery.form.js");
white_list.insert("/js/jquery.hotkeys.js");
white_list.insert("/js/jquery.sparkline.min.js");
white_list.insert("/js/jquery.timeago.js");
white_list.insert("/js/jquery.validate.min.js");
white_list.insert("/js/underscore-min.js");
white_list.insert("/images/alert-icon_small.png");
white_list.insert("/images/critical-issue_small.png");
white_list.insert("/images/information-icon_small.png");
white_list.insert("/images/mini_right-arrow.png");
white_list.insert("/images/mini_down-arrow.png");
white_list.insert("/index.html");
file_app.reset(new file_http_app_t(white_list, path));
semilattice_app.reset(new semilattice_http_app_t(_semilattice_metadata, _directory_metadata, _us));
directory_app.reset(new directory_http_app_t(_directory_metadata));
issues_app.reset(new issues_http_app_t(_issue_tracker));
stat_app.reset(new stat_http_app_t(mbox_manager, _directory_metadata));
last_seen_app.reset(new last_seen_http_app_t(_last_seen_tracker));
log_app.reset(new log_http_app_t(mbox_manager,
_directory_metadata->subview(&get_log_mailbox),
_directory_metadata->subview(&get_machine_id)
));
progress_app.reset(new progress_app_t(_directory_metadata, mbox_manager));
std::map<std::string, http_app_t *> ajax_routes;
ajax_routes["directory"] = directory_app.get();
ajax_routes["issues"] = issues_app.get();
ajax_routes["stat"] = stat_app.get();
ajax_routes["last_seen"] = last_seen_app.get();
ajax_routes["log"] = log_app.get();
ajax_routes["progress"] = progress_app.get();
ajax_routing_app.reset(new routing_http_app_t(semilattice_app.get(), ajax_routes));
std::map<std::string, http_app_t *> root_routes;
root_routes["ajax"] = ajax_routing_app.get();
root_routing_app.reset(new routing_http_app_t(file_app.get(), root_routes));
server.reset(new http_server_t(port, root_routing_app.get()));
}
administrative_http_server_manager_t::~administrative_http_server_manager_t() {
/* This must be declared in the `.cc` file because the definitions of the
destructors for the things in `boost::scoped_ptr`s are not available from
the `.hpp` file. */
}
<|endoftext|> |
<commit_before>/*
* Copyright 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 "multivalue.h"
#include "length.h"
#include <assert.h>
void
StringList::unserialise(const std::string & serialised)
{
const char * ptr = serialised.data();
const char * end = serialised.data() + serialised.size();
unserialise(&ptr, end);
}
void
StringList::unserialise(const char ** ptr, const char * end)
{
clear();
size_t length = decode_length(ptr, end, true);
if (length == -1 || length != end - *ptr) {
push_back(std::string(*ptr, end - *ptr));
} else {
size_t currlen;
while (*ptr != end) {
currlen = decode_length(ptr, end, true);
if (currlen == -1) {
// FIXME: throwing a NetworkError if the length is too long - should be a more appropriate error.
throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
push_back(std::string(*ptr, currlen));
*ptr += currlen;
}
}
}
std::string
StringList::serialise() const
{
std::string serialised, values;
StringList::const_iterator i(begin());
if (size() > 1) {
for (; i != end(); i++) {
values.append(encode_length((*i).size()));
values.append(*i);
}
serialised.append(encode_length(values.size()));
} else if (i != end()) {
values.assign(*i);
}
serialised.append(values);
return serialised;
}
void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double) {
assert(internal.get());
++(internal->total);
StringList list;
list.unserialise(doc.get_value(internal->slot));
StringList::const_iterator i(list.begin());
for (; i != list.end(); i++) {
std::string val(*i);
if (!val.empty()) ++(internal->values[val]);
}
}
Xapian::MatchSpy *
MultiValueCountMatchSpy::clone() const {
assert(internal.get());
return new MultiValueCountMatchSpy(internal->slot);
}
std::string
MultiValueCountMatchSpy::name() const {
return "Xapian::MultiValueCountMatchSpy";
}
std::string
MultiValueCountMatchSpy::serialise() const {
assert(internal.get());
std::string result;
result += encode_length(internal->slot);
return result;
}
Xapian::MatchSpy *
MultiValueCountMatchSpy::unserialise(const std::string & s,
const Xapian::Registry &) const{
const char * p = s.data();
const char * end = p + s.size();
Xapian::valueno new_slot = decode_length(&p, end, false);
if (new_slot == -1) {
throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
if (p != end) {
throw Xapian::NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
}
return new MultiValueCountMatchSpy(new_slot);
}
std::string
MultiValueCountMatchSpy::get_description() const {
char buffer[20];
std::string d = "MultiValueCountMatchSpy(";
if (internal.get()) {
snprintf(buffer, sizeof(buffer), "%u", internal->total);
d += buffer;
d += " docs seen, looking in ";
snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
d += buffer;
d += " slots)";
} else {
d += ")";
}
return d;
}<commit_msg>Cleanups<commit_after>/*
* Copyright 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 "multivalue.h"
#include "length.h"
#include <assert.h>
void
StringList::unserialise(const std::string & serialised)
{
const char * ptr = serialised.data();
const char * end = serialised.data() + serialised.size();
unserialise(&ptr, end);
}
void
StringList::unserialise(const char ** ptr, const char * end)
{
clear();
size_t length = decode_length(ptr, end, true);
if (length == -1 || length != end - *ptr) {
push_back(std::string(*ptr, end - *ptr));
} else {
size_t currlen;
while (*ptr != end) {
currlen = decode_length(ptr, end, true);
if (currlen == -1) {
// FIXME: throwing a NetworkError if the length is too long - should be a more appropriate error.
throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
push_back(std::string(*ptr, currlen));
*ptr += currlen;
}
}
}
std::string
StringList::serialise() const
{
std::string serialised, values;
StringList::const_iterator i(begin());
if (size() > 1) {
for (; i != end(); i++) {
values.append(encode_length((*i).size()));
values.append(*i);
}
serialised.append(encode_length(values.size()));
} else if (i != end()) {
values.assign(*i);
}
serialised.append(values);
return serialised;
}
void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double) {
assert(internal.get());
++(internal->total);
StringList list;
list.unserialise(doc.get_value(internal->slot));
StringList::const_iterator i(list.begin());
for (; i != list.end(); i++) {
std::string val(*i);
if (!val.empty()) ++(internal->values[val]);
}
}
Xapian::MatchSpy *
MultiValueCountMatchSpy::clone() const {
assert(internal.get());
return new MultiValueCountMatchSpy(internal->slot);
}
std::string
MultiValueCountMatchSpy::name() const {
return "Xapian::MultiValueCountMatchSpy";
}
std::string
MultiValueCountMatchSpy::serialise() const {
assert(internal.get());
std::string result;
result += encode_length(internal->slot);
return result;
}
Xapian::MatchSpy *
MultiValueCountMatchSpy::unserialise(const std::string & s,
const Xapian::Registry &) const{
const char * p = s.data();
const char * end = p + s.size();
Xapian::valueno new_slot = decode_length(&p, end, false);
if (new_slot == -1) {
throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
if (p != end) {
throw Xapian::NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
}
return new MultiValueCountMatchSpy(new_slot);
}
std::string
MultiValueCountMatchSpy::get_description() const {
char buffer[20];
std::string d = "MultiValueCountMatchSpy(";
if (internal.get()) {
snprintf(buffer, sizeof(buffer), "%u", internal->total);
d += buffer;
d += " docs seen, looking in ";
snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
d += buffer;
d += " slots)";
} else {
d += ")";
}
return d;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <set>
#include <vector>
#include <string>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <sys/stat.h>
#include <readline/readline.h>
#include <readline/history.h>
#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE
#include <natus/natus.hpp>
using namespace natus;
#define _str(s) # s
#define __str(s) _str(s)
#define PWSIZE 1024
#define PROMPT ">>> "
#define NPRMPT "... "
#define HISTORYFILE ".natus_history"
#define error(status, num, ...) { \
fprintf(stderr, __VA_ARGS__); \
return status; \
}
Value* glbl;
static Value alert(Value& ths, Value& fnc, Value& args) {
NATUS_CHECK_ARGUMENTS(fnc, "s");
fprintf(stderr, "%s\n", args[0].to<UTF8>().c_str());
return ths.newUndefined();
}
static Value dir(Value& ths, Value& fnc, Value& args) {
Value obj = ths.getGlobal();
if (args.get("length").to<long>() > 0)
obj = args[0];
Value names = obj.enumerate();
for (long i=0 ; i < names.get("length").to<long>() ; i++)
fprintf(stderr, "\t%s\n", names[i].to<UTF8>().c_str());
return ths.newUndefined();
}
static bool inblock(const char *str) {
char strstart = '\0';
int bracedepth = 0, parendepth = 0;
for (char prv='\0' ; *str ; prv=*str++) {
if (strstart) {
if (strstart == '"' && *str == '"' && prv != '\\')
strstart = '\0';
else if (strstart == '\'' && *str == '\'' && prv != '\\')
strstart = '\0';
continue;
}
// We are not inside a string literal
switch (*str) {
case '"':
// We're starting a double-quoted string
strstart = '"';
break;
case '\'':
// We're starting a single-quoted string
strstart = '\'';
break;
case '{':
// We're starting a new block
bracedepth++;
break;
case '}':
// We're ending an existing block
bracedepth--;
break;
case '(':
// We're starting a new block
parendepth++;
break;
case ')':
// We're ending an existing block
parendepth--;
break;
}
}
return bracedepth > 0 || parendepth > 0;
}
static vector<string> pathparser(string path) {
if (path.find(':') == string::npos) {
vector<string> tmp;
if (path != "")
tmp.push_back(path);
return tmp;
}
string segment = path.substr(path.find_last_of(':')+1);
vector<string> paths = pathparser(path.substr(0, path.find_last_of(':')));
if (segment != "") paths.push_back(segment);
return paths;
}
static char* completion_generator(const char* text, int state) {
static set<string> names;
static set<string>::iterator it;
char* last = (char*) strrchr(text, '.');
if (state == 0) {
Value obj = *glbl;
if (last) {
char* base = new char[last-text+1];
memset(base, 0, sizeof(char) * (last-text+1));
strncpy(base, text, last-text);
obj = obj.get(base);
delete[] base;
if (obj.isUndefined()) return NULL;
}
Value nm = obj.enumerate();
for (long i=0 ; i < nm.get("length").to<long>() ; i++)
names.insert(nm[i].to<UTF8>().c_str());
it = names.begin();
}
if (last) last++;
for ( ; it != names.end() ; it++) {
if ((last && it->find(last) == 0) || (!last && it->find(text) == 0)) {
string tmp = last ? (string(text) + (it->c_str()+strlen(last))) : *it;
char* ret = strdup(tmp.c_str());
it++;
return ret;
}
}
return NULL;
}
static char** completion(const char* text, int start, int end) {
return rl_completion_matches(text, completion_generator);
}
static Value set_path(Value& ctx, Require::HookStep step, char* name, void* misc) {
if (step == Require::HookStepProcess && !strcmp(name, "system")) {
Value args = ctx.get("args");
if (!args.isArray()) return NULL;
const char** argv = (const char **) misc;
for (int i=0 ; argv[i] ; i++)
arrayBuilder(args, argv[0]);
}
return NULL;
}
int main(int argc, char** argv) {
Engine engine;
Value global;
vector<string> configs;
const char *eng = NULL;
const char *eval = NULL;
int c=0, exitcode=0;
glbl = &global;
// The engine argument can be embedded in a symlink
if (strstr(argv[0], "natus-") == argv[0])
eng = strchr(argv[0], '-')+1;
// Get the path
string path;
if (getenv("NATUS_PATH"))
path = string(getenv("NATUS_PATH")) + ":";
path += __str(MODULEDIR);
opterr = 0;
while ((c = getopt (argc, argv, "+C:c:e:n")) != -1) {
switch (c) {
case 'C':
configs.push_back(optarg);
break;
case 'c':
eval = optarg;
break;
case 'e':
eng = optarg;
break;
case 'n':
path.clear();
break;
case '?':
if (optopt == 'e')
fprintf(stderr, "Option -%c requires an engine name.\n", optopt);
else {
fprintf(stderr, "Usage: %s [-C <config>=<jsonval>|-c <javascript>|-e <engine>|-n|<scriptfile>]\n\n", argv[0]);
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
}
return 1;
default:
abort();
}
}
// Initialize the engine
if (!engine.initialize(eng))
error(1, 0, "Unable to init engine!\n");
// Setup our global
global = engine.newGlobal();
if (global.isUndefined() || global.isException())
error(2, 0, "Unable to init global!\n");
// Setup our config
Value cfg = global.newObject();
if (!path.empty()) {
while (path.find(':') != string::npos)
path = path.substr(0, path.find(':')) + "\", \"" + path.substr(path.find(':')+1);
assert(!cfg.setRecursive("natus.require.path", fromJSON(global, "[\"" + path + "\"]"), Value::PropAttrNone, true).isException());
}
for (vector<string>::iterator it=configs.begin() ; it != configs.end() ; it++) {
if (access(it->c_str(), R_OK) == 0) {
ifstream file(it->c_str());
for (string line ; getline(file, line) ; ) {
if (line.find('=') == string::npos) continue;
string key = line.substr(0, line.find('='));
Value val = fromJSON(global, line.substr(line.find('=')+1).c_str());
if (val.isException()) {
fprintf(stderr, "An error occurred in file '%s'\n", it->c_str());
fprintf(stderr, "\tline: %s\n", line.c_str());
fprintf(stderr, "\t%s\n", val.to<UTF8>().c_str());
continue;
}
assert(!cfg.setRecursive(key, val, Value::PropAttrNone, true).isException());
}
file.close();
} else if (it->find("=") != string::npos) {
string key = it->substr(0, it->find('='));
Value val = fromJSON(global, it->substr(it->find('=')+1));
if (val.isException()) {
fprintf(stderr, "An error occurred on '%s'\n", it->c_str());
fprintf(stderr, "\t%s\n", val.to<UTF8>().c_str());
continue;
}
assert(!cfg.setRecursive(key, val, Value::PropAttrNone, true).isException());
}
}
// Bring up the Module Loader
Require req(global);
if (!req.initialize(cfg))
error(3, 0, "Unable to init module loader\n!");
// Export some basic functions
global.set("alert", global.newFunction(alert));
global.set("dir", global.newFunction(dir));
// Do the evaluation
if (eval) {
Value res = global.evaluate(eval);
// Print uncaught exceptions
if (res.isException())
error(8, 0, "Uncaught Exception: %s", res.to<UTF8>().c_str());
// Let the script return exitcodes
if (res.isNumber())
exitcode = (int) res.to<long>();
return exitcode;
}
// Start the shell
if (optind >= argc) {
fprintf(stderr, "Natus v" PACKAGE_VERSION " - Using: %s\n", engine.getName());
if (getenv("HOME"))
read_history((string(getenv("HOME")) + "/" + HISTORYFILE).c_str());
rl_readline_name = (char*) "natus";
rl_attempted_completion_function = completion;
read_history(HISTORYFILE);
char* line;
const char* prompt = PROMPT;
string prev = "";
long lcnt = 0;
for (line=readline(prompt) ; line ; line=readline(prompt)) {
// Strip the line
string l = line;
free(line);
string::size_type start = l.find_first_not_of(" \t");
l = start == string::npos ? string("") : l.substr(start, l.find_last_not_of(" \t")-start+1);
if (l == "") continue;
// Append the line to the buffer
prev.append(l);
// Continue to the next line
if (inblock(prev.c_str())) {
prompt = NPRMPT;
continue;
}
prompt = PROMPT;
add_history(prev.c_str());
Value res = global.evaluate(prev.c_str(), "", lcnt++);
string fmt;
if (res.isException()) {
fmt = "Uncaught Exception: %s\n";
if (prev == "exit" || prev == "quit") {
res = res.newUndefined();
fprintf(stderr, "Use Ctrl-D (i.e. EOF) to exit\n");
}
} else
fmt = "%s\n";
if (!res.isUndefined() && !res.isNull())
fprintf(stderr, fmt.c_str(), res.to<UTF8>().c_str());
prev = "";
}
printf("\n");
if (getenv("HOME"))
write_history((string(getenv("HOME")) + "/" + HISTORYFILE).c_str());
return 0;
}
// Get the script filename
char *filename = argv[optind];
// Stat our file
struct stat st;
if (stat(filename, &st))
error(3, 0, "Script file does not exist: %s\n", filename);
// Read in our script file
FILE *file = fopen(filename, "r");
if (!file)
error(4, 0, "Unable to open file: %s\n", filename);
char *jscript = new char[st.st_size + 1];
if (!jscript) {
fclose(file);
error(5, 0, "Out of memory!\n");
}
if ((size_t) fread(jscript, 1, st.st_size, file) != (size_t) st.st_size) {
delete[] jscript;
fclose(file);
error(6, 0, "Error reading file: %s\n", filename);
}
fclose(file);
jscript[st.st_size] = '\0';
// Evaluate it
req.addHook("system_args", set_path, argv+optind);
Value res = global.evaluate(jscript, filename ? filename : "");
delete[] jscript;
// Print uncaught exceptions
if (res.isException())
error(8, 0, "Uncaught Exception: %s\n", res.to<UTF8>().c_str());
// Let the script return exitcodes
if (res.isNumber())
exitcode = (int) res.to<long>();
return exitcode;
}
<commit_msg>[shell] fix recursive get in the tab completion logic<commit_after>/*
* Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <set>
#include <vector>
#include <string>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <sys/stat.h>
#include <readline/readline.h>
#include <readline/history.h>
#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE
#include <natus/natus.hpp>
using namespace natus;
#define _str(s) # s
#define __str(s) _str(s)
#define PWSIZE 1024
#define PROMPT ">>> "
#define NPRMPT "... "
#define HISTORYFILE ".natus_history"
#define error(status, num, ...) { \
fprintf(stderr, __VA_ARGS__); \
return status; \
}
Value* glbl;
static Value alert(Value& ths, Value& fnc, Value& args) {
NATUS_CHECK_ARGUMENTS(fnc, "s");
fprintf(stderr, "%s\n", args[0].to<UTF8>().c_str());
return ths.newUndefined();
}
static Value dir(Value& ths, Value& fnc, Value& args) {
Value obj = ths.getGlobal();
if (args.get("length").to<long>() > 0)
obj = args[0];
Value names = obj.enumerate();
for (long i=0 ; i < names.get("length").to<long>() ; i++)
fprintf(stderr, "\t%s\n", names[i].to<UTF8>().c_str());
return ths.newUndefined();
}
static bool inblock(const char *str) {
char strstart = '\0';
int bracedepth = 0, parendepth = 0;
for (char prv='\0' ; *str ; prv=*str++) {
if (strstart) {
if (strstart == '"' && *str == '"' && prv != '\\')
strstart = '\0';
else if (strstart == '\'' && *str == '\'' && prv != '\\')
strstart = '\0';
continue;
}
// We are not inside a string literal
switch (*str) {
case '"':
// We're starting a double-quoted string
strstart = '"';
break;
case '\'':
// We're starting a single-quoted string
strstart = '\'';
break;
case '{':
// We're starting a new block
bracedepth++;
break;
case '}':
// We're ending an existing block
bracedepth--;
break;
case '(':
// We're starting a new block
parendepth++;
break;
case ')':
// We're ending an existing block
parendepth--;
break;
}
}
return bracedepth > 0 || parendepth > 0;
}
static vector<string> pathparser(string path) {
if (path.find(':') == string::npos) {
vector<string> tmp;
if (path != "")
tmp.push_back(path);
return tmp;
}
string segment = path.substr(path.find_last_of(':')+1);
vector<string> paths = pathparser(path.substr(0, path.find_last_of(':')));
if (segment != "") paths.push_back(segment);
return paths;
}
static char* completion_generator(const char* text, int state) {
static set<string> names;
static set<string>::iterator it;
char* last = (char*) strrchr(text, '.');
if (state == 0) {
Value obj = *glbl;
if (last) {
char* base = new char[last-text+1];
memset(base, 0, sizeof(char) * (last-text+1));
strncpy(base, text, last-text);
obj = obj.getRecursive(base);
delete[] base;
if (obj.isUndefined()) return NULL;
}
Value nm = obj.enumerate();
for (long i=0 ; i < nm.get("length").to<long>() ; i++)
names.insert(nm[i].to<UTF8>().c_str());
it = names.begin();
}
if (last) last++;
for ( ; it != names.end() ; it++) {
if ((last && it->find(last) == 0) || (!last && it->find(text) == 0)) {
string tmp = last ? (string(text) + (it->c_str()+strlen(last))) : *it;
char* ret = strdup(tmp.c_str());
it++;
return ret;
}
}
return NULL;
}
static char** completion(const char* text, int start, int end) {
return rl_completion_matches(text, completion_generator);
}
static Value set_path(Value& ctx, Require::HookStep step, char* name, void* misc) {
if (step == Require::HookStepProcess && !strcmp(name, "system")) {
Value args = ctx.get("args");
if (!args.isArray()) return NULL;
const char** argv = (const char **) misc;
for (int i=0 ; argv[i] ; i++)
arrayBuilder(args, argv[0]);
}
return NULL;
}
int main(int argc, char** argv) {
Engine engine;
Value global;
vector<string> configs;
const char *eng = NULL;
const char *eval = NULL;
int c=0, exitcode=0;
glbl = &global;
// The engine argument can be embedded in a symlink
if (strstr(argv[0], "natus-") == argv[0])
eng = strchr(argv[0], '-')+1;
// Get the path
string path;
if (getenv("NATUS_PATH"))
path = string(getenv("NATUS_PATH")) + ":";
path += __str(MODULEDIR);
opterr = 0;
while ((c = getopt (argc, argv, "+C:c:e:n")) != -1) {
switch (c) {
case 'C':
configs.push_back(optarg);
break;
case 'c':
eval = optarg;
break;
case 'e':
eng = optarg;
break;
case 'n':
path.clear();
break;
case '?':
if (optopt == 'e')
fprintf(stderr, "Option -%c requires an engine name.\n", optopt);
else {
fprintf(stderr, "Usage: %s [-C <config>=<jsonval>|-c <javascript>|-e <engine>|-n|<scriptfile>]\n\n", argv[0]);
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
}
return 1;
default:
abort();
}
}
// Initialize the engine
if (!engine.initialize(eng))
error(1, 0, "Unable to init engine!\n");
// Setup our global
global = engine.newGlobal();
if (global.isUndefined() || global.isException())
error(2, 0, "Unable to init global!\n");
// Setup our config
Value cfg = global.newObject();
if (!path.empty()) {
while (path.find(':') != string::npos)
path = path.substr(0, path.find(':')) + "\", \"" + path.substr(path.find(':')+1);
assert(!cfg.setRecursive("natus.require.path", fromJSON(global, "[\"" + path + "\"]"), Value::PropAttrNone, true).isException());
}
for (vector<string>::iterator it=configs.begin() ; it != configs.end() ; it++) {
if (access(it->c_str(), R_OK) == 0) {
ifstream file(it->c_str());
for (string line ; getline(file, line) ; ) {
if (line.find('=') == string::npos) continue;
string key = line.substr(0, line.find('='));
Value val = fromJSON(global, line.substr(line.find('=')+1).c_str());
if (val.isException()) {
fprintf(stderr, "An error occurred in file '%s'\n", it->c_str());
fprintf(stderr, "\tline: %s\n", line.c_str());
fprintf(stderr, "\t%s\n", val.to<UTF8>().c_str());
continue;
}
assert(!cfg.setRecursive(key, val, Value::PropAttrNone, true).isException());
}
file.close();
} else if (it->find("=") != string::npos) {
string key = it->substr(0, it->find('='));
Value val = fromJSON(global, it->substr(it->find('=')+1));
if (val.isException()) {
fprintf(stderr, "An error occurred on '%s'\n", it->c_str());
fprintf(stderr, "\t%s\n", val.to<UTF8>().c_str());
continue;
}
assert(!cfg.setRecursive(key, val, Value::PropAttrNone, true).isException());
}
}
// Bring up the Module Loader
Require req(global);
if (!req.initialize(cfg))
error(3, 0, "Unable to init module loader\n!");
// Export some basic functions
global.set("alert", global.newFunction(alert));
global.set("dir", global.newFunction(dir));
// Do the evaluation
if (eval) {
Value res = global.evaluate(eval);
// Print uncaught exceptions
if (res.isException())
error(8, 0, "Uncaught Exception: %s", res.to<UTF8>().c_str());
// Let the script return exitcodes
if (res.isNumber())
exitcode = (int) res.to<long>();
return exitcode;
}
// Start the shell
if (optind >= argc) {
fprintf(stderr, "Natus v" PACKAGE_VERSION " - Using: %s\n", engine.getName());
if (getenv("HOME"))
read_history((string(getenv("HOME")) + "/" + HISTORYFILE).c_str());
rl_readline_name = (char*) "natus";
rl_attempted_completion_function = completion;
read_history(HISTORYFILE);
char* line;
const char* prompt = PROMPT;
string prev = "";
long lcnt = 0;
for (line=readline(prompt) ; line ; line=readline(prompt)) {
// Strip the line
string l = line;
free(line);
string::size_type start = l.find_first_not_of(" \t");
l = start == string::npos ? string("") : l.substr(start, l.find_last_not_of(" \t")-start+1);
if (l == "") continue;
// Append the line to the buffer
prev.append(l);
// Continue to the next line
if (inblock(prev.c_str())) {
prompt = NPRMPT;
continue;
}
prompt = PROMPT;
add_history(prev.c_str());
Value res = global.evaluate(prev.c_str(), "", lcnt++);
string fmt;
if (res.isException()) {
fmt = "Uncaught Exception: %s\n";
if (prev == "exit" || prev == "quit") {
res = res.newUndefined();
fprintf(stderr, "Use Ctrl-D (i.e. EOF) to exit\n");
}
} else
fmt = "%s\n";
if (!res.isUndefined() && !res.isNull())
fprintf(stderr, fmt.c_str(), res.to<UTF8>().c_str());
prev = "";
}
printf("\n");
if (getenv("HOME"))
write_history((string(getenv("HOME")) + "/" + HISTORYFILE).c_str());
return 0;
}
// Get the script filename
char *filename = argv[optind];
// Stat our file
struct stat st;
if (stat(filename, &st))
error(3, 0, "Script file does not exist: %s\n", filename);
// Read in our script file
FILE *file = fopen(filename, "r");
if (!file)
error(4, 0, "Unable to open file: %s\n", filename);
char *jscript = new char[st.st_size + 1];
if (!jscript) {
fclose(file);
error(5, 0, "Out of memory!\n");
}
if ((size_t) fread(jscript, 1, st.st_size, file) != (size_t) st.st_size) {
delete[] jscript;
fclose(file);
error(6, 0, "Error reading file: %s\n", filename);
}
fclose(file);
jscript[st.st_size] = '\0';
// Evaluate it
req.addHook("system_args", set_path, argv+optind);
Value res = global.evaluate(jscript, filename ? filename : "");
delete[] jscript;
// Print uncaught exceptions
if (res.isException())
error(8, 0, "Uncaught Exception: %s\n", res.to<UTF8>().c_str());
// Let the script return exitcodes
if (res.isNumber())
exitcode = (int) res.to<long>();
return exitcode;
}
<|endoftext|> |
<commit_before>#include "netdrawer.h"
using namespace NEAT;
using namespace std;
/*
//void setPosition(double &x, double &y, double Min, double Max){
void setPosition(double &x, double &y){
//randomly generate position for a node;
double Min = 0.0, Max = 1000.0;
double p = (double)rand() / RAND_MAX;
x = Min + p * (Max - Min);
x = (floor(x * 10))/10; //only keep one digit after the decimal point
double q = (double)rand() / RAND_MAX;
y = Min + q * (Max - Min);
y = (floor(y * 10))/10;
return;
}
*/
void setPositionX(double &x, int side){
//side can only be 0, 1, 2 (representing left, right, middle)
switch(side){
case 0:
x = 100.0;
break;
case 1:
x = 500.0;
break;
case 2: //middle
x = 300.0;
}
return;
}
void printNode(NNode* node, double x, double y, std::ofstream &myfile){
int type = node->type;
//nodetype is 1, which is transition
if(type){
myfile << "<transition id=\"" << node->node_id << "\">\n";
myfile << "<graphics>\n";
myfile << "<position x=\"" << x << "\" y=\"" << y << "\"/>\n";
myfile << "</graphics>\n";
myfile << "<name>\n";
myfile << "<value>" << node->node_id << "_";
switch(node->action_ID){
case 0:
myfile << "move right";
break;
case 1:
myfile << "move up";
break;
case 2:
myfile << "move left";
break;
case 3:
myfile << "move down";
break;
}
myfile << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</name>\n";
myfile << "<orientation>\n";
myfile << "<value>0</value>\n";
myfile << "</orientation>\n";
myfile << "<rate>\n";
myfile << "<value>1.0</value>\n";
myfile << "</rate>\n";
myfile << "<timed>\n";
myfile << "<value>false</value>\n";
myfile << "</timed>\n";
myfile << "</transition>\n";
}
else{ ////nodetype is 0, which is place
myfile << "<place id=\"" << node->node_id << "\">\n";
myfile << "<graphics>\n";
myfile << "<position x=\"" << x << "\" y=\"" << y << "\"/>\n";
myfile << "</graphics>\n";
myfile << "<name>\n";
myfile << "<value>" << node->node_id << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</name>\n";
myfile << "<initialMarking>\n";
myfile << "<value>" << node->tok_count << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</initialMarking>\n";
myfile << "</place>\n";
}
}
void printLink(Link* nlink, std::map<NNode*, int> npos, std::vector<double> xpos, std::vector<double> ypos, std::ofstream &myfile){
NNode* in = nlink->in_node;
NNode* out = nlink->out_node;
int in_ptr = npos[in];
int out_ptr = npos[out];
myfile << "<arc id=\"" << in->node_id << " to " << out->node_id << "\" ";
myfile << "source=\"" << in->node_id << "\" target=\"" << out->node_id <<"\">\n";
myfile << "<graphics/>\n";
myfile << "<inscription>\n";
myfile << "<value>" << (int)nlink->weight << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</inscription>\n";
myfile << "<arcpath id=\"000\" x=\"" << ((int)xpos[in_ptr]) + 11;
myfile << "\" y=\"" << ((int)ypos[in_ptr]) + 5 << "\" curvePoint=\"false\"/>\n";
myfile << "<arcpath id=\"001\" x=\"" << ((int)xpos[out_ptr]) + 11;
myfile << "\" y=\"" << ((int)ypos[out_ptr]) + 5 << "\" curvePoint=\"false\"/>\n";
myfile << "</arc>\n";
}
int netdrawer(const Network* network){
//build an xml file for the network
//initialize the xml file
std::ofstream myfile;
char buff[100];
sprintf(buff, "PetriNet_%d.xml", network->net_id);
myfile.open(buff, std::ofstream::out);
myfile <<"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<pnml>\n<net id=\"Net-One\" type=\"P/T net\">";
//a hashmap to record posiitons of nodes using node pointer (NNode*) and position number(int)
std::map<NNode*, int> nodepos;
//two vectors to record positions of the nodes
std::vector<double> xpos;
std::vector<double> ypos;
//Write all the places
std::vector<NNode*>::const_iterator curnode;
int count = 0;
double x, y = 50.0;
setPositionX(x, 2); //setting positions for transitions
//Write all the transitions
for(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){
//generate an position
nodepos[*curnode] = count;
xpos.push_back(x);
ypos.push_back(y);
printNode(*curnode, x, y, myfile);
y += 50;
count++;
}
y = 50.0;
//Write all the places
for(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {
//generate an random position for curnode;
int side = randint(0, 1);
setPositionX(x, side);
nodepos[*curnode] = count;
xpos.push_back(x);
ypos.push_back(y);
y += 50;
printNode(*curnode, x, y, myfile);
count++;
}
//Write all the links
std::vector<Link*>::const_iterator curlink;
for(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {
for(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){
printLink(*curlink, nodepos, xpos, ypos, myfile);
}
}
for(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){
for(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){
printLink(*curlink, nodepos, xpos, ypos, myfile);
}
}
//closing xml file
myfile <<"</net>\n</pnml>";
myfile.close();
return 0;
}
<commit_msg>Changed the name of the transistion<commit_after>#include "netdrawer.h"
using namespace NEAT;
using namespace std;
/*
//void setPosition(double &x, double &y, double Min, double Max){
void setPosition(double &x, double &y){
//randomly generate position for a node;
double Min = 0.0, Max = 1000.0;
double p = (double)rand() / RAND_MAX;
x = Min + p * (Max - Min);
x = (floor(x * 10))/10; //only keep one digit after the decimal point
double q = (double)rand() / RAND_MAX;
y = Min + q * (Max - Min);
y = (floor(y * 10))/10;
return;
}
*/
void setPositionX(double &x, int side){
//side can only be 0, 1, 2 (representing left, right, middle)
switch(side){
case 0:
x = 100.0;
break;
case 1:
x = 500.0;
break;
case 2: //middle
x = 300.0;
}
return;
}
void printNode(NNode* node, double x, double y, std::ofstream &myfile){
int type = node->type;
//nodetype is 1, which is transition
if(type){
myfile << "<transition id=\"" << node->node_id << "\">\n";
myfile << "<graphics>\n";
myfile << "<position x=\"" << x << "\" y=\"" << y << "\"/>\n";
myfile << "</graphics>\n";
myfile << "<name>\n";
myfile << "<value>" << node->node_id << " - ";
switch(node->action_ID){
case 0:
myfile << "move right";
break;
case 1:
myfile << "move up";
break;
case 2:
myfile << "move left";
break;
case 3:
myfile << "move down";
break;
}
myfile << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</name>\n";
myfile << "<orientation>\n";
myfile << "<value>0</value>\n";
myfile << "</orientation>\n";
myfile << "<rate>\n";
myfile << "<value>1.0</value>\n";
myfile << "</rate>\n";
myfile << "<timed>\n";
myfile << "<value>false</value>\n";
myfile << "</timed>\n";
myfile << "</transition>\n";
}
else{ ////nodetype is 0, which is place
myfile << "<place id=\"" << node->node_id << "\">\n";
myfile << "<graphics>\n";
myfile << "<position x=\"" << x << "\" y=\"" << y << "\"/>\n";
myfile << "</graphics>\n";
myfile << "<name>\n";
myfile << "<value>" << node->node_id << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</name>\n";
myfile << "<initialMarking>\n";
myfile << "<value>" << node->tok_count << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</initialMarking>\n";
myfile << "</place>\n";
}
}
void printLink(Link* nlink, std::map<NNode*, int> npos, std::vector<double> xpos, std::vector<double> ypos, std::ofstream &myfile){
NNode* in = nlink->in_node;
NNode* out = nlink->out_node;
int in_ptr = npos[in];
int out_ptr = npos[out];
myfile << "<arc id=\"" << in->node_id << " to " << out->node_id << "\" ";
myfile << "source=\"" << in->node_id << "\" target=\"" << out->node_id <<"\">\n";
myfile << "<graphics/>\n";
myfile << "<inscription>\n";
myfile << "<value>" << (int)nlink->weight << "</value>\n";
myfile << "<graphics/>\n";
myfile << "</inscription>\n";
myfile << "<arcpath id=\"000\" x=\"" << ((int)xpos[in_ptr]) + 11;
myfile << "\" y=\"" << ((int)ypos[in_ptr]) + 5 << "\" curvePoint=\"false\"/>\n";
myfile << "<arcpath id=\"001\" x=\"" << ((int)xpos[out_ptr]) + 11;
myfile << "\" y=\"" << ((int)ypos[out_ptr]) + 5 << "\" curvePoint=\"false\"/>\n";
myfile << "</arc>\n";
}
int netdrawer(const Network* network){
//build an xml file for the network
//initialize the xml file
std::ofstream myfile;
char buff[100];
sprintf(buff, "PetriNet_%d.xml", network->net_id);
myfile.open(buff, std::ofstream::out);
myfile <<"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<pnml>\n<net id=\"Net-One\" type=\"P/T net\">";
//a hashmap to record posiitons of nodes using node pointer (NNode*) and position number(int)
std::map<NNode*, int> nodepos;
//two vectors to record positions of the nodes
std::vector<double> xpos;
std::vector<double> ypos;
//Write all the places
std::vector<NNode*>::const_iterator curnode;
int count = 0;
double x, y = 50.0;
setPositionX(x, 2); //setting positions for transitions
//Write all the transitions
for(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){
//generate an position
nodepos[*curnode] = count;
xpos.push_back(x);
ypos.push_back(y);
printNode(*curnode, x, y, myfile);
y += 50;
count++;
}
y = 50.0;
//Write all the places
for(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {
//generate an random position for curnode;
int side = randint(0, 1);
setPositionX(x, side);
nodepos[*curnode] = count;
xpos.push_back(x);
ypos.push_back(y);
y += 50;
printNode(*curnode, x, y, myfile);
count++;
}
//Write all the links
std::vector<Link*>::const_iterator curlink;
for(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {
for(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){
printLink(*curlink, nodepos, xpos, ypos, myfile);
}
}
for(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){
for(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){
printLink(*curlink, nodepos, xpos, ypos, myfile);
}
}
//closing xml file
myfile <<"</net>\n</pnml>";
myfile.close();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef _mex_array_hpp__
#define _mex_array_hpp__
// Copyright(c) Andre Caron, 2009-2011
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
#include "__configure__.hpp"
#include "types.hpp"
#include "traits.hpp"
#include <algorithm>
#include <exception>
#include <typeinfo>
namespace mex {
inline size_t numel ( const ::mxArray * backend )
{
return (::mxGetNumberOfElements(backend));
}
class array_base
{
/* nested types. */
public:
typedef mex::size_t size_type;
typedef void * pointer;
typedef const void * const_pointer;
/* data. */
private:
::mxArray * myBackend;
/* construction. */
public:
array_base ( ::mxArray * backend, const claim_t& )
: myBackend(backend)
{
}
array_base ( const ::mxArray * backend, const clone_t& )
: myBackend(::mxDuplicateArray(backend))
{
}
array_base ( const array_base& other )
: myBackend(::mxDuplicateArray(other.backend()))
{
}
~array_base ()
{
::mxDestroyArray(myBackend);
}
/* methods. */
protected:
void swap ( array_base& other )
{
std::swap(myBackend, other.myBackend);
}
public:
::mxArray * backend () const
{
return (myBackend);
}
::mxArray * release ()
{
::mxArray * backend = myBackend; myBackend = 0; return (backend);
}
bool empty () const
{
return (::mxIsEmpty(myBackend));
}
size_type dims () const
{
return (::mxGetNumberOfDimensions(myBackend));
}
size_type dim ( size_type i ) const
{
return (::mxGetDimensions(myBackend)[i]);
}
size_type numel () const
{
return (::mxGetNumberOfElements(myBackend));
}
size_type elsiz () const
{
return (::mxGetElementSize(myBackend));
}
size_type M () const
{
return (::mxGetM(myBackend));
}
size_type N () const
{
return (::mxGetN(myBackend));
}
bool is ( const char * klass ) const
{
return (::mxIsClass(myBackend, klass));
}
pointer data ()
{
return (::mxGetData(myBackend));
}
const_pointer data () const
{
return (::mxGetData(myBackend));
}
size_type offset ( int nsubs, ::mwIndex * subs ) const
{
return (::mxCalcSingleSubscript(myBackend, nsubs, subs));
}
size_type offset ( size_type i ) const
{
::mwIndex subs[] = { i };
return (offset(1, subs));
}
size_type offset ( size_type i, size_type j ) const
{
::mwIndex subs[] = { i, j };
return (offset(2, subs));
}
size_type offset ( size_type i, size_type j, size_type k ) const
{
::mwIndex subs[] = { i, j, k };
return (offset(3, subs));
}
/* operators. */
private:
array_base& operator= ( const array_base& other );
};
template<typename T>
class array :
public array_base
{
/* nested types. */
public:
typedef traits<T> traits_type;
typedef typename traits_type::value_type value_type;
typedef typename traits_type::pointer pointer;
typedef typename traits_type::const_pointer const_pointer;
typedef pointer iterator;
typedef const_pointer const_iterator;
/* construction. */
public:
array ( size_type m, size_type n )
: array_base(traits_type::matrix(m, n, real), claim)
{
}
array ( size_type m, size_type n, const real_t& )
: array_base(traits_type::matrix(m, n, real), claim)
{
}
array ( size_type m, size_type n, const complex_t& )
: array_base(traits_type::matrix(m, n, complex), claim)
{
}
array ( const ::mxArray * backend, const clone_t& )
: array_base(traits_type::check(backend), clone)
{
}
array ( ::mxArray * backend, const claim_t& )
: array_base(traits_type::check(backend), claim)
{
}
array ( const array<T>& other )
: array_base(::mxDuplicateArray(other.backend()), claim)
{
}
/* methods. */
public:
void swap ( array<T> & other )
{
other.array_base::swap(*this);
}
pointer data ()
{
return (reinterpret_cast<pointer>(array_base::data()));
}
const_pointer data () const
{
return (reinterpret_cast<const_pointer>(array_base::data()));
}
iterator begin ()
{
return (reinterpret_cast<iterator>(array_base::data()));
}
const_iterator begin () const
{
return (reinterpret_cast<const_iterator>(array_base::data()));
}
iterator end ()
{
return (begin() + numel());
}
const_iterator end () const
{
return (begin() + numel());
}
/* operators. */
public:
array<T>& operator= ( const array<T>& other )
{
array<T> copy(other); copy.swap(*this); return (*this);
}
value_type& operator() ( size_type i )
{
return (data()[offset(i)]);
}
value_type& operator() ( size_type i, size_type j )
{
return (data()[offset(i,j)]);
}
value_type& operator() ( size_type i, size_type j, size_type k )
{
return (data()[offset(i,j,k)]);
}
value_type operator() ( size_type i ) const
{
return (data()[offset(i)]);
}
value_type operator() ( size_type i, size_type j ) const
{
return (data()[offset(i,j)]);
}
value_type operator() ( size_type i, size_type j, size_type k ) const
{
return (data()[offset(i,j,k)]);
}
};
}
#endif /* _mex_array_hpp__ */
<commit_msg>Added argument-dependent lookup for swap.<commit_after>#ifndef _mex_array_hpp__
#define _mex_array_hpp__
// Copyright(c) Andre Caron, 2009-2011
//
// This document is covered by the Artistic License 2.0 (Open Source Initiative
// approved license). A copy of the license should have been provided alongside
// this software package (see "license.rtf"). If not, the license is available
// online at "http://www.opensource.org/licenses/artistic-license-2.0.php".
#include "__configure__.hpp"
#include "types.hpp"
#include "traits.hpp"
#include <algorithm>
#include <exception>
#include <typeinfo>
namespace mex {
inline size_t numel ( const ::mxArray * backend )
{
return (::mxGetNumberOfElements(backend));
}
class array_base
{
/* nested types. */
public:
typedef mex::size_t size_type;
typedef void * pointer;
typedef const void * const_pointer;
/* data. */
private:
::mxArray * myBackend;
/* construction. */
public:
array_base ( ::mxArray * backend, const claim_t& )
: myBackend(backend)
{
}
array_base ( const ::mxArray * backend, const clone_t& )
: myBackend(::mxDuplicateArray(backend))
{
}
array_base ( const array_base& other )
: myBackend(::mxDuplicateArray(other.backend()))
{
}
~array_base ()
{
::mxDestroyArray(myBackend);
}
/* methods. */
protected:
void swap ( array_base& other )
{
std::swap(myBackend, other.myBackend);
}
public:
::mxArray * backend () const
{
return (myBackend);
}
::mxArray * release ()
{
::mxArray * backend = myBackend; myBackend = 0; return (backend);
}
bool empty () const
{
return (::mxIsEmpty(myBackend));
}
size_type dims () const
{
return (::mxGetNumberOfDimensions(myBackend));
}
size_type dim ( size_type i ) const
{
return (::mxGetDimensions(myBackend)[i]);
}
size_type numel () const
{
return (::mxGetNumberOfElements(myBackend));
}
size_type elsiz () const
{
return (::mxGetElementSize(myBackend));
}
size_type M () const
{
return (::mxGetM(myBackend));
}
size_type N () const
{
return (::mxGetN(myBackend));
}
bool is ( const char * klass ) const
{
return (::mxIsClass(myBackend, klass));
}
pointer data ()
{
return (::mxGetData(myBackend));
}
const_pointer data () const
{
return (::mxGetData(myBackend));
}
size_type offset ( int nsubs, ::mwIndex * subs ) const
{
return (::mxCalcSingleSubscript(myBackend, nsubs, subs));
}
size_type offset ( size_type i ) const
{
::mwIndex subs[] = { i };
return (offset(1, subs));
}
size_type offset ( size_type i, size_type j ) const
{
::mwIndex subs[] = { i, j };
return (offset(2, subs));
}
size_type offset ( size_type i, size_type j, size_type k ) const
{
::mwIndex subs[] = { i, j, k };
return (offset(3, subs));
}
/* operators. */
private:
array_base& operator= ( const array_base& other );
};
template<typename T>
class array :
public array_base
{
/* nested types. */
public:
typedef traits<T> traits_type;
typedef typename traits_type::value_type value_type;
typedef typename traits_type::pointer pointer;
typedef typename traits_type::const_pointer const_pointer;
typedef pointer iterator;
typedef const_pointer const_iterator;
/* construction. */
public:
array ( size_type m, size_type n )
: array_base(traits_type::matrix(m, n, real), claim)
{
}
array ( size_type m, size_type n, const real_t& )
: array_base(traits_type::matrix(m, n, real), claim)
{
}
array ( size_type m, size_type n, const complex_t& )
: array_base(traits_type::matrix(m, n, complex), claim)
{
}
array ( const ::mxArray * backend, const clone_t& )
: array_base(traits_type::check(backend), clone)
{
}
array ( ::mxArray * backend, const claim_t& )
: array_base(traits_type::check(backend), claim)
{
}
array ( const array<T>& other )
: array_base(::mxDuplicateArray(other.backend()), claim)
{
}
/* methods. */
public:
void swap ( array<T> & other )
{
other.array_base::swap(*this);
}
pointer data ()
{
return (reinterpret_cast<pointer>(array_base::data()));
}
const_pointer data () const
{
return (reinterpret_cast<const_pointer>(array_base::data()));
}
iterator begin ()
{
return (reinterpret_cast<iterator>(array_base::data()));
}
const_iterator begin () const
{
return (reinterpret_cast<const_iterator>(array_base::data()));
}
iterator end ()
{
return (begin() + numel());
}
const_iterator end () const
{
return (begin() + numel());
}
/* operators. */
public:
array<T>& operator= ( const array<T>& other )
{
array<T> copy(other); copy.swap(*this); return (*this);
}
value_type& operator() ( size_type i )
{
return (data()[offset(i)]);
}
value_type& operator() ( size_type i, size_type j )
{
return (data()[offset(i,j)]);
}
value_type& operator() ( size_type i, size_type j, size_type k )
{
return (data()[offset(i,j,k)]);
}
value_type operator() ( size_type i ) const
{
return (data()[offset(i)]);
}
value_type operator() ( size_type i, size_type j ) const
{
return (data()[offset(i,j)]);
}
value_type operator() ( size_type i, size_type j, size_type k ) const
{
return (data()[offset(i,j,k)]);
}
};
template<typename T>
void swap ( array<T>& lhs, array<T>& rhs )
{
lhs.swap(rhs);
}
}
#endif /* _mex_array_hpp__ */
<|endoftext|> |
<commit_before>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <boost/foreach.hpp>
namespace rstudio {
namespace core {
namespace {
std::string makePidString()
{
// get the pid (as a string)
std::stringstream ss;
ss << (long) ::getpid();
return ss.str();
}
const std::string& pidString()
{
static std::string instance = makePidString();
return instance;
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string makeThreadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str().substr(2);
}
const std::string& threadId()
{
static boost::thread_specific_ptr<std::string> instance;
if (instance.get() == NULL)
instance.reset(new std::string(makeThreadId()));
return *instance;
}
std::string proxyLockFileName()
{
return std::string() +
".rstudio-lock" + "-" +
hostName() + "-" +
pidString() + "-" +
threadId();
}
struct CloseFileScope
{
CloseFileScope(int fd, ErrorLocation location)
: fd_(fd), location_(location)
{}
~CloseFileScope()
{
int errc = ::close(fd_);
if (errc)
LOG_ERROR(systemError(errno, location_));
}
int fd_;
ErrorLocation location_;
};
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
~LockRegistration()
{
try
{
clearLocks();
}
catch (...)
{
}
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
if (proxyPath.exists())
return fileExistsError(ERROR_LOCATION);
Error error = core::writeStringToFile(proxyPath, "");
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return -1;
#endif
}
bool isLockFileStale(const FilePath& lockFilePath, double seconds = 30.0)
{
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
Error beginLocking(const FilePath& lockingPath)
{
// attempt to clean up stale lockfiles
if (lockingPath.exists() && isLockFileStale(lockingPath))
{
Error error = lockingPath.remove();
if (error)
LOG_ERROR(error);
}
// write the lock file to take ownership
return writeLockFile(lockingPath);
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath)
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// use filesystem-based mutex to ensure interprocess locking; ie, attempt to
// ensure that only one process can attempt to acquire a lock at a time
FilePath lockingPath = lockFilePath.parent().complete(".rstudio-locking");
Error error = beginLocking(lockingPath);
if (error)
return error;
RemoveOnExitScope scope(lockingPath, ERROR_LOCATION);
// bail if the lock file exists and is active
if (lockFilePath.exists() && !isLockFileStale(lockFilePath))
return fileExistsError(ERROR_LOCATION);
// create or update the modified time of the lockfile (this allows
// us to claim ownership of the file)
if (lockFilePath.exists())
{
lockFilePath.setLastWriteTime();
}
else
{
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
error = writeLockFile(lockFilePath);
if (error)
return error;
}
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
} // namespace core
} // namespace rstudio
<commit_msg>remove thread id caching<commit_after>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <boost/foreach.hpp>
namespace rstudio {
namespace core {
namespace {
std::string makePidString()
{
// get the pid (as a string)
std::stringstream ss;
ss << (long) ::getpid();
return ss.str();
}
const std::string& pidString()
{
static std::string instance = makePidString();
return instance;
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str().substr(2);
}
std::string proxyLockFileName()
{
return std::string() +
".rstudio-lock" + "-" +
hostName() + "-" +
pidString() + "-" +
threadId();
}
struct CloseFileScope
{
CloseFileScope(int fd, ErrorLocation location)
: fd_(fd), location_(location)
{}
~CloseFileScope()
{
int errc = ::close(fd_);
if (errc)
LOG_ERROR(systemError(errno, location_));
}
int fd_;
ErrorLocation location_;
};
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
~LockRegistration()
{
try
{
clearLocks();
}
catch (...)
{
}
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
if (proxyPath.exists())
return fileExistsError(ERROR_LOCATION);
Error error = core::writeStringToFile(proxyPath, "");
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return -1;
#endif
}
bool isLockFileStale(const FilePath& lockFilePath, double seconds = 30.0)
{
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
Error beginLocking(const FilePath& lockingPath)
{
// attempt to clean up stale lockfiles
if (lockingPath.exists() && isLockFileStale(lockingPath))
{
Error error = lockingPath.remove();
if (error)
LOG_ERROR(error);
}
// write the lock file to take ownership
return writeLockFile(lockingPath);
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath)
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// use filesystem-based mutex to ensure interprocess locking; ie, attempt to
// ensure that only one process can attempt to acquire a lock at a time
FilePath lockingPath = lockFilePath.parent().complete(".rstudio-locking");
Error error = beginLocking(lockingPath);
if (error)
return error;
RemoveOnExitScope scope(lockingPath, ERROR_LOCATION);
// bail if the lock file exists and is active
if (lockFilePath.exists() && !isLockFileStale(lockFilePath))
return fileExistsError(ERROR_LOCATION);
// create or update the modified time of the lockfile (this allows
// us to claim ownership of the file)
if (lockFilePath.exists())
{
lockFilePath.setLastWriteTime();
}
else
{
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
error = writeLockFile(lockFilePath);
if (error)
return error;
}
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "dawn/CodeGen/CXXNaive/ASTStencilBody.h"
#include "dawn/CodeGen/CXXNaive/ASTStencilFunctionParamVisitor.h"
#include "dawn/CodeGen/CXXUtil.h"
#include "dawn/Optimizer/OptimizerContext.h"
#include "dawn/Optimizer/StencilFunctionInstantiation.h"
#include "dawn/Optimizer/StencilInstantiation.h"
#include "dawn/SIR/AST.h"
#include "dawn/Support/Unreachable.h"
namespace dawn {
namespace codegen {
namespace cxxnaive {
ASTStencilBody::ASTStencilBody(const dawn::StencilInstantiation* stencilInstantiation,
StencilContext stencilContext)
: ASTCodeGenCXX(), instantiation_(stencilInstantiation), offsetPrinter_(",", "(", ")"),
currentFunction_(nullptr), nestingOfStencilFunArgLists_(0), stencilContext_(stencilContext) {}
ASTStencilBody::~ASTStencilBody() {}
std::string ASTStencilBody::getName(const std::shared_ptr<Stmt>& stmt) const {
if(currentFunction_)
return currentFunction_->getNameFromAccessID(currentFunction_->getAccessIDFromStmt(stmt));
else
return instantiation_->getNameFromAccessID(instantiation_->getAccessIDFromStmt(stmt));
}
std::string ASTStencilBody::getName(const std::shared_ptr<Expr>& expr) const {
if(currentFunction_)
return currentFunction_->getNameFromAccessID(currentFunction_->getAccessIDFromExpr(expr));
else
return instantiation_->getNameFromAccessID(instantiation_->getAccessIDFromExpr(expr));
}
int ASTStencilBody::getAccessID(const std::shared_ptr<Expr>& expr) const {
if(currentFunction_)
return currentFunction_->getAccessIDFromExpr(expr);
else
return instantiation_->getAccessIDFromExpr(expr);
}
//===------------------------------------------------------------------------------------------===//
// Stmt
//===------------------------------------------------------------------------------------------===//
void ASTStencilBody::visit(const std::shared_ptr<BlockStmt>& stmt) { Base::visit(stmt); }
void ASTStencilBody::visit(const std::shared_ptr<ExprStmt>& stmt) { Base::visit(stmt); }
void ASTStencilBody::visit(const std::shared_ptr<ReturnStmt>& stmt) {
if(scopeDepth_ == 0)
ss_ << std::string(indent_, ' ');
ss_ << "return ";
stmt->getExpr()->accept(*this);
ss_ << ";\n";
}
void ASTStencilBody::visit(const std::shared_ptr<VarDeclStmt>& stmt) { Base::visit(stmt); }
void ASTStencilBody::visit(const std::shared_ptr<VerticalRegionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "VerticalRegionDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<StencilCallDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "StencilCallDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<BoundaryConditionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "BoundaryConditionDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<IfStmt>& stmt) { Base::visit(stmt); }
//===------------------------------------------------------------------------------------------===//
// Expr
//===------------------------------------------------------------------------------------------===//
void ASTStencilBody::visit(const std::shared_ptr<UnaryOperator>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<BinaryOperator>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<AssignmentExpr>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<TernaryOperator>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<FunCallExpr>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<StencilFunCallExpr>& expr) {
if(nestingOfStencilFunArgLists_++)
ss_ << ", ";
const std::shared_ptr<dawn::StencilFunctionInstantiation>& stencilFun =
currentFunction_ ? currentFunction_->getStencilFunctionInstantiation(expr)
: instantiation_->getStencilFunctionInstantiation(expr);
ss_ << dawn::StencilFunctionInstantiation::makeCodeGenName(*stencilFun) << "(i,j,k";
// int n = 0;
ASTStencilFunctionParamVisitor fieldAccessVisitor(currentFunction_, instantiation_);
for(auto& arg : expr->getArguments()) {
arg->accept(fieldAccessVisitor);
// ++n;
}
ss_ << fieldAccessVisitor.getCodeAndResetStream();
nestingOfStencilFunArgLists_--;
ss_ << ")";
}
void ASTStencilBody::visit(const std::shared_ptr<StencilFunArgExpr>& expr) {}
void ASTStencilBody::visit(const std::shared_ptr<VarAccessExpr>& expr) {
std::string name = getName(expr);
int AccessID = getAccessID(expr);
if(instantiation_->isGlobalVariable(AccessID)) {
ss_ << "globals::get()." << name << ".get_value()";
} else {
ss_ << name;
if(expr->isArrayAccess()) {
ss_ << "[";
expr->getIndex()->accept(*this);
ss_ << "]";
}
}
}
void ASTStencilBody::visit(const std::shared_ptr<LiteralAccessExpr>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<FieldAccessExpr>& expr) {
if(currentFunction_) {
// extract the arg index, from the AccessID
int argIndex = -1;
for(auto idx : currentFunction_->ArgumentIndexToCallerAccessIDMap()) {
if(idx.second == currentFunction_->getAccessIDFromExpr(expr))
argIndex = idx.first;
}
DAWN_ASSERT(argIndex != -1);
// In order to explain the algorithm, let assume the following example
// stencil_function fn {
// offset off1;
// storage st1;
// Do {
// st1(off1+2);
// }
// }
// ... Inside a stencil computation, there is a call to fn
// fn(offset_fn1, gn(offset_gn1, storage2, storage3)) ;
// If the arg index corresponds to a function instantation,
// it means the function was called passing another function as argument,
// i.e. gn in the example
if(currentFunction_->isArgStencilFunctionInstantiation(argIndex)) {
StencilFunctionInstantiation& argStencilFn =
*(currentFunction_->getFunctionInstantiationOfArgField(argIndex));
ss_ << StencilFunctionInstantiation::makeCodeGenName(argStencilFn) << "(i,j,k";
// parse the arguments of the argument stencil gn call
for(int argIdx = 0; argIdx < argStencilFn.numArgs(); ++argIdx) {
// parse the argument if it is a field. Ignore offsets/directions,
// since they are "inlined" in the code generation of the function
if(argStencilFn.isArgField(argIdx)) {
Array3i offset = expr->getOffset();
// parse the offsets of the field access, that should be used to offset the evaluation
// of gn(), i.e. off1+2 in the example
for(auto idx : expr->getArgumentMap()) {
if(idx != -1) {
DAWN_ASSERT_MSG((argStencilFn.isArgOffset(idx)),
"index identified by argument map is not an offset arg");
int dim = argStencilFn.getCallerOffsetOfArgOffset(idx)[0];
int off = argStencilFn.getCallerOffsetOfArgOffset(idx)[1];
DAWN_ASSERT(dim < offset.size());
offset[dim] = off;
}
}
std::string accessName =
currentFunction_->getArgNameFromFunctionCall(argStencilFn.getName());
ss_ << ", "
<< "pw_" + accessName << ".cloneWithOffset(std::array<int,"
<< std::to_string(offset.size()) << ">{";
bool init = false;
for(auto idxIt : offset) {
if(init)
ss_ << ",";
ss_ << std::to_string(idxIt);
init = true;
}
ss_ << "})";
}
}
ss_ << ")";
} else {
std::string accessName = currentFunction_->getOriginalNameFromCallerAccessID(
currentFunction_->getAccessIDFromExpr(expr));
ss_ << accessName
<< offsetPrinter_(ijkfyOffset(currentFunction_->evalOffsetOfFieldAccessExpr(expr, false),
accessName));
}
} else {
std::string accessName = getName(expr);
ss_ << accessName << offsetPrinter_(ijkfyOffset(expr->getOffset(), accessName));
}
}
void ASTStencilBody::setCurrentStencilFunction(
const std::shared_ptr<StencilFunctionInstantiation>& currentFunction) {
currentFunction_ = currentFunction;
}
} // namespace cxxnaive
} // namespace codegen
} // namespace dawn
<commit_msg>Nested fctn calls (#64)<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===//
// _
// | |
// __| | __ ___ ___ ___
// / _` |/ _` \ \ /\ / / '_ |
// | (_| | (_| |\ V V /| | | |
// \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "dawn/CodeGen/CXXNaive/ASTStencilBody.h"
#include "dawn/CodeGen/CXXNaive/ASTStencilFunctionParamVisitor.h"
#include "dawn/CodeGen/CXXUtil.h"
#include "dawn/Optimizer/OptimizerContext.h"
#include "dawn/Optimizer/StencilFunctionInstantiation.h"
#include "dawn/Optimizer/StencilInstantiation.h"
#include "dawn/SIR/AST.h"
#include "dawn/Support/Unreachable.h"
namespace dawn {
namespace codegen {
namespace cxxnaive {
ASTStencilBody::ASTStencilBody(const dawn::StencilInstantiation* stencilInstantiation,
StencilContext stencilContext)
: ASTCodeGenCXX(), instantiation_(stencilInstantiation), offsetPrinter_(",", "(", ")"),
currentFunction_(nullptr), nestingOfStencilFunArgLists_(0), stencilContext_(stencilContext) {}
ASTStencilBody::~ASTStencilBody() {}
std::string ASTStencilBody::getName(const std::shared_ptr<Stmt>& stmt) const {
if(currentFunction_)
return currentFunction_->getNameFromAccessID(currentFunction_->getAccessIDFromStmt(stmt));
else
return instantiation_->getNameFromAccessID(instantiation_->getAccessIDFromStmt(stmt));
}
std::string ASTStencilBody::getName(const std::shared_ptr<Expr>& expr) const {
if(currentFunction_)
return currentFunction_->getNameFromAccessID(currentFunction_->getAccessIDFromExpr(expr));
else
return instantiation_->getNameFromAccessID(instantiation_->getAccessIDFromExpr(expr));
}
int ASTStencilBody::getAccessID(const std::shared_ptr<Expr>& expr) const {
if(currentFunction_)
return currentFunction_->getAccessIDFromExpr(expr);
else
return instantiation_->getAccessIDFromExpr(expr);
}
//===------------------------------------------------------------------------------------------===//
// Stmt
//===------------------------------------------------------------------------------------------===//
void ASTStencilBody::visit(const std::shared_ptr<BlockStmt>& stmt) { Base::visit(stmt); }
void ASTStencilBody::visit(const std::shared_ptr<ExprStmt>& stmt) { Base::visit(stmt); }
void ASTStencilBody::visit(const std::shared_ptr<ReturnStmt>& stmt) {
if(scopeDepth_ == 0)
ss_ << std::string(indent_, ' ');
ss_ << "return ";
stmt->getExpr()->accept(*this);
ss_ << ";\n";
}
void ASTStencilBody::visit(const std::shared_ptr<VarDeclStmt>& stmt) { Base::visit(stmt); }
void ASTStencilBody::visit(const std::shared_ptr<VerticalRegionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "VerticalRegionDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<StencilCallDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "StencilCallDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<BoundaryConditionDeclStmt>& stmt) {
DAWN_ASSERT_MSG(0, "BoundaryConditionDeclStmt not allowed in this context");
}
void ASTStencilBody::visit(const std::shared_ptr<IfStmt>& stmt) { Base::visit(stmt); }
//===------------------------------------------------------------------------------------------===//
// Expr
//===------------------------------------------------------------------------------------------===//
void ASTStencilBody::visit(const std::shared_ptr<UnaryOperator>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<BinaryOperator>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<AssignmentExpr>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<TernaryOperator>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<FunCallExpr>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<StencilFunCallExpr>& expr) {
if(nestingOfStencilFunArgLists_++)
ss_ << ", ";
const std::shared_ptr<dawn::StencilFunctionInstantiation>& stencilFun =
currentFunction_ ? currentFunction_->getStencilFunctionInstantiation(expr)
: instantiation_->getStencilFunctionInstantiation(expr);
ss_ << dawn::StencilFunctionInstantiation::makeCodeGenName(*stencilFun) << "(i,j,k";
// int n = 0;
ASTStencilFunctionParamVisitor fieldAccessVisitor(currentFunction_, instantiation_);
for(auto& arg : expr->getArguments()) {
arg->accept(fieldAccessVisitor);
// ++n;
}
ss_ << fieldAccessVisitor.getCodeAndResetStream();
nestingOfStencilFunArgLists_--;
ss_ << ")";
}
void ASTStencilBody::visit(const std::shared_ptr<StencilFunArgExpr>& expr) {}
void ASTStencilBody::visit(const std::shared_ptr<VarAccessExpr>& expr) {
std::string name = getName(expr);
int AccessID = getAccessID(expr);
if(instantiation_->isGlobalVariable(AccessID)) {
ss_ << "globals::get()." << name << ".get_value()";
} else {
ss_ << name;
if(expr->isArrayAccess()) {
ss_ << "[";
expr->getIndex()->accept(*this);
ss_ << "]";
}
}
}
void ASTStencilBody::visit(const std::shared_ptr<LiteralAccessExpr>& expr) { Base::visit(expr); }
void ASTStencilBody::visit(const std::shared_ptr<FieldAccessExpr>& expr) {
if(currentFunction_) {
// extract the arg index, from the AccessID
int argIndex = -1;
for(auto idx : currentFunction_->ArgumentIndexToCallerAccessIDMap()) {
if(idx.second == currentFunction_->getAccessIDFromExpr(expr))
argIndex = idx.first;
}
DAWN_ASSERT(argIndex != -1);
// In order to explain the algorithm, let assume the following example
// stencil_function fn {
// offset off1;
// storage st1;
// Do {
// st1(off1+2);
// }
// }
// ... Inside a stencil computation, there is a call to fn
// fn(offset_fn1, gn(offset_gn1, storage2, storage3)) ;
// If the arg index corresponds to a function instantation,
// it means the function was called passing another function as argument,
// i.e. gn in the example
if(currentFunction_->isArgStencilFunctionInstantiation(argIndex)) {
StencilFunctionInstantiation& argStencilFn =
*(currentFunction_->getFunctionInstantiationOfArgField(argIndex));
ss_ << StencilFunctionInstantiation::makeCodeGenName(argStencilFn) << "(i,j,k";
// parse the arguments of the argument stencil gn call
for(int argIdx = 0; argIdx < argStencilFn.numArgs(); ++argIdx) {
// parse the argument if it is a field. Ignore offsets/directions,
// since they are "inlined" in the code generation of the function
if(argStencilFn.isArgField(argIdx)) {
Array3i offset = currentFunction_->evalOffsetOfFieldAccessExpr(expr, false);
std::string accessName =
currentFunction_->getArgNameFromFunctionCall(argStencilFn.getName());
ss_ << ", "
<< "pw_" + accessName << ".cloneWithOffset(std::array<int,"
<< std::to_string(offset.size()) << ">{";
bool init = false;
for(auto idxIt : offset) {
if(init)
ss_ << ",";
ss_ << std::to_string(idxIt);
init = true;
}
ss_ << "})";
}
}
ss_ << ")";
} else {
std::string accessName = currentFunction_->getOriginalNameFromCallerAccessID(
currentFunction_->getAccessIDFromExpr(expr));
ss_ << accessName
<< offsetPrinter_(ijkfyOffset(currentFunction_->evalOffsetOfFieldAccessExpr(expr, false),
accessName));
}
} else {
std::string accessName = getName(expr);
ss_ << accessName << offsetPrinter_(ijkfyOffset(expr->getOffset(), accessName));
}
}
void ASTStencilBody::setCurrentStencilFunction(
const std::shared_ptr<StencilFunctionInstantiation>& currentFunction) {
currentFunction_ = currentFunction;
}
} // namespace cxxnaive
} // namespace codegen
} // namespace dawn
<|endoftext|> |
<commit_before>/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lower.h"
#include "lib/gmputil.h"
namespace BMV2 {
const IR::Expression* LowerExpressions::shift(const IR::Operation_Binary* expression) const {
auto rhs = expression->right;
auto rhstype = typeMap->getType(rhs, true);
if (rhstype->is<IR::Type_InfInt>()) {
auto cst = rhs->to<IR::Constant>();
mpz_class maxShift = Util::shift_left(1, LowerExpressions::maxShiftWidth);
if (cst->value > maxShift)
::error("%1%: shift amount limited to %2% on this target", expression, maxShift);
} else {
BUG_CHECK(rhstype->is<IR::Type_Bits>(), "%1%: expected a bit<> type", rhstype);
auto bs = rhstype->to<IR::Type_Bits>();
if (bs->size > LowerExpressions::maxShiftWidth)
::error("%1%: shift amount limited to %2% bits on this target",
expression, LowerExpressions::maxShiftWidth);
}
return expression;
}
const IR::Node* LowerExpressions::postorder(IR::Neg* expression) {
auto type = typeMap->getType(getOriginal(), true);
auto zero = new IR::Constant(type, 0);
auto sub = new IR::Sub(expression->srcInfo, zero, expression->expr);
typeMap->setType(zero, type);
typeMap->setType(sub, type);
LOG1("Replaced " << expression << " with " << sub);
return sub;
}
const IR::Node* LowerExpressions::postorder(IR::Cast* expression) {
// handle bool <-> bit casts
auto destType = typeMap->getType(getOriginal(), true);
auto srcType = typeMap->getType(expression->expr, true);
if (destType->is<IR::Type_Boolean>() && srcType->is<IR::Type_Bits>()) {
auto zero = new IR::Constant(srcType, 0);
auto cmp = new IR::Equ(expression->srcInfo, expression->expr, zero);
typeMap->setType(cmp, destType);
LOG1("Replaced " << expression << " with " << cmp);
return cmp;
} else if (destType->is<IR::Type_Bits>() && srcType->is<IR::Type_Boolean>()) {
auto mux = new IR::Mux(expression->srcInfo, expression->expr,
new IR::Constant(destType, 1),
new IR::Constant(destType, 0));
typeMap->setType(mux, destType);
LOG1("Replaced " << expression << " with " << mux);
return mux;
}
return expression;
}
const IR::Node* LowerExpressions::postorder(IR::Expression* expression) {
// Just update the typeMap incrementally.
auto type = typeMap->getType(getOriginal(), true);
typeMap->setType(expression, type);
return expression;
}
const IR::Node* LowerExpressions::postorder(IR::Slice* expression) {
// This is in a RHS expression a[m:l] -> (cast)(a >> l)
int h = expression->getH();
int l = expression->getL();
auto sh = new IR::Shr(expression->e0->srcInfo, expression->e0, new IR::Constant(l));
auto e0type = typeMap->getType(expression->e0, true);
typeMap->setType(sh, e0type);
auto type = IR::Type_Bits::get(h - l + 1);
auto result = new IR::Cast(expression->srcInfo, type, sh);
typeMap->setType(result, type);
LOG1("Replaced " << expression << " with " << result);
return result;
}
const IR::Node* LowerExpressions::postorder(IR::Concat* expression) {
// a ++ b -> ((cast)a << sizeof(b)) | ((cast)b & mask)
auto type = typeMap->getType(expression->right, true);
auto resulttype = typeMap->getType(getOriginal(), true);
BUG_CHECK(type->is<IR::Type_Bits>(), "%1%: expected a bitstring got a %2%",
expression->right, type);
BUG_CHECK(resulttype->is<IR::Type_Bits>(), "%1%: expected a bitstring got a %2%",
expression->right, type);
unsigned sizeofb = type->to<IR::Type_Bits>()->size;
unsigned sizeofresult = resulttype->to<IR::Type_Bits>()->size;
auto cast0 = new IR::Cast(expression->left->srcInfo, resulttype, expression->left);
auto cast1 = new IR::Cast(expression->right->srcInfo, resulttype, expression->right);
auto sh = new IR::Shl(cast0->srcInfo, cast0, new IR::Constant(sizeofb));
mpz_class m = Util::maskFromSlice(sizeofb, 0);
auto mask = new IR::Constant(expression->right->srcInfo,
IR::Type_Bits::get(sizeofresult), m, 16);
auto and0 = new IR::BAnd(expression->right->srcInfo, cast1, mask);
auto result = new IR::BOr(expression->srcInfo, sh, and0);
typeMap->setType(cast0, resulttype);
typeMap->setType(cast1, resulttype);
typeMap->setType(result, resulttype);
typeMap->setType(sh, resulttype);
typeMap->setType(and0, resulttype);
LOG1("Replaced " << expression << " with " << result);
return result;
}
} // namespace BMV2
<commit_msg>Bugfix for lowering pass: fixes test_config_23_* test<commit_after>/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lower.h"
#include "lib/gmputil.h"
namespace BMV2 {
// We make an effort to update the typeMap as we proceed
// since parent expression trees may need the information
// when processing in post-order.
const IR::Expression* LowerExpressions::shift(const IR::Operation_Binary* expression) const {
auto rhs = expression->right;
auto rhstype = typeMap->getType(rhs, true);
if (rhstype->is<IR::Type_InfInt>()) {
auto cst = rhs->to<IR::Constant>();
mpz_class maxShift = Util::shift_left(1, LowerExpressions::maxShiftWidth);
if (cst->value > maxShift)
::error("%1%: shift amount limited to %2% on this target", expression, maxShift);
} else {
BUG_CHECK(rhstype->is<IR::Type_Bits>(), "%1%: expected a bit<> type", rhstype);
auto bs = rhstype->to<IR::Type_Bits>();
if (bs->size > LowerExpressions::maxShiftWidth)
::error("%1%: shift amount limited to %2% bits on this target",
expression, LowerExpressions::maxShiftWidth);
}
auto ltype = typeMap->getType(getOriginal(), true);
typeMap->setType(expression, ltype);
return expression;
}
const IR::Node* LowerExpressions::postorder(IR::Neg* expression) {
auto type = typeMap->getType(getOriginal(), true);
auto zero = new IR::Constant(type, 0);
auto sub = new IR::Sub(expression->srcInfo, zero, expression->expr);
typeMap->setType(zero, type);
typeMap->setType(sub, type);
LOG1("Replaced " << expression << " with " << sub);
return sub;
}
const IR::Node* LowerExpressions::postorder(IR::Cast* expression) {
// handle bool <-> bit casts
auto destType = typeMap->getType(getOriginal(), true);
auto srcType = typeMap->getType(expression->expr, true);
if (destType->is<IR::Type_Boolean>() && srcType->is<IR::Type_Bits>()) {
auto zero = new IR::Constant(srcType, 0);
auto cmp = new IR::Equ(expression->srcInfo, expression->expr, zero);
typeMap->setType(cmp, destType);
LOG1("Replaced " << expression << " with " << cmp);
return cmp;
} else if (destType->is<IR::Type_Bits>() && srcType->is<IR::Type_Boolean>()) {
auto mux = new IR::Mux(expression->srcInfo, expression->expr,
new IR::Constant(destType, 1),
new IR::Constant(destType, 0));
typeMap->setType(mux, destType);
LOG1("Replaced " << expression << " with " << mux);
return mux;
}
// This may be a new expression
typeMap->setType(expression, destType);
return expression;
}
const IR::Node* LowerExpressions::postorder(IR::Expression* expression) {
// Just update the typeMap incrementally.
auto type = typeMap->getType(getOriginal(), true);
typeMap->setType(expression, type);
return expression;
}
const IR::Node* LowerExpressions::postorder(IR::Slice* expression) {
// This is in a RHS expression a[m:l] -> (cast)(a >> l)
int h = expression->getH();
int l = expression->getL();
auto sh = new IR::Shr(expression->e0->srcInfo, expression->e0, new IR::Constant(l));
auto e0type = typeMap->getType(expression->e0, true);
typeMap->setType(sh, e0type);
auto type = IR::Type_Bits::get(h - l + 1);
auto result = new IR::Cast(expression->srcInfo, type, sh);
typeMap->setType(result, type);
LOG1("Replaced " << expression << " with " << result);
return result;
}
const IR::Node* LowerExpressions::postorder(IR::Concat* expression) {
// a ++ b -> ((cast)a << sizeof(b)) | ((cast)b & mask)
auto type = typeMap->getType(expression->right, true);
auto resulttype = typeMap->getType(getOriginal(), true);
BUG_CHECK(type->is<IR::Type_Bits>(), "%1%: expected a bitstring got a %2%",
expression->right, type);
BUG_CHECK(resulttype->is<IR::Type_Bits>(), "%1%: expected a bitstring got a %2%",
expression->right, type);
unsigned sizeofb = type->to<IR::Type_Bits>()->size;
unsigned sizeofresult = resulttype->to<IR::Type_Bits>()->size;
auto cast0 = new IR::Cast(expression->left->srcInfo, resulttype, expression->left);
auto cast1 = new IR::Cast(expression->right->srcInfo, resulttype, expression->right);
auto sh = new IR::Shl(cast0->srcInfo, cast0, new IR::Constant(sizeofb));
mpz_class m = Util::maskFromSlice(sizeofb, 0);
auto mask = new IR::Constant(expression->right->srcInfo,
IR::Type_Bits::get(sizeofresult), m, 16);
auto and0 = new IR::BAnd(expression->right->srcInfo, cast1, mask);
auto result = new IR::BOr(expression->srcInfo, sh, and0);
typeMap->setType(cast0, resulttype);
typeMap->setType(cast1, resulttype);
typeMap->setType(result, resulttype);
typeMap->setType(sh, resulttype);
typeMap->setType(and0, resulttype);
LOG1("Replaced " << expression << " with " << result);
return result;
}
} // namespace BMV2
<|endoftext|> |
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_UTILS_LOG_HPP
#define OUZEL_UTILS_LOG_HPP
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
#include "math/Matrix.hpp"
#include "math/Quaternion.hpp"
#include "math/Size.hpp"
#include "math/Vector.hpp"
namespace ouzel
{
class Logger;
class Log final
{
public:
enum class Level
{
OFF,
ERR,
WARN,
INFO,
ALL
};
explicit Log(const Logger& initLogger, Level initLevel = Level::INFO):
logger(initLogger), level(initLevel)
{
}
Log(const Log& other):
logger(other.logger),
level(other.level),
s(other.s)
{
}
Log(Log&& other):
logger(other.logger),
level(other.level),
s(std::move(other.s))
{
other.level = Level::INFO;
}
Log& operator=(const Log& other)
{
level = other.level;
s = other.s;
return *this;
}
Log& operator=(Log&& other)
{
if (&other != this)
{
level = other.level;
other.level = Level::INFO;
s = std::move(other.s);
}
return *this;
}
~Log();
template<typename T, typename std::enable_if<std::is_arithmetic<T>::value && !std::is_same<T, bool>::value>::type* = nullptr>
Log& operator<<(T val)
{
s += std::to_string(val);
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, bool>::value>::type* = nullptr>
Log& operator<<(T val)
{
s += val ? "true" : "false";
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, std::string>::value>::type* = nullptr>
Log& operator<<(const T& val)
{
s += val;
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, char>::value>::type* = nullptr>
Log& operator<<(const T* val)
{
s += val;
return *this;
}
template<typename T, typename std::enable_if<!std::is_same<T, char>::value>::type* = nullptr>
Log& operator<<(const T* val)
{
static constexpr const char* digits = "0123456789ABCDEF";
std::string str(sizeof(val) * 2, '0');
for (size_t i = 0; i < sizeof(val) * 2; ++i)
str[i] = digits[(reinterpret_cast<uintptr_t>(val) >> (sizeof(val) * 2 - i - 1) * 4) & 0x0f];
s += str;
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, std::vector<uint8_t>>::value>::type* = nullptr>
Log& operator<<(const T& val)
{
bool first = true;
for (uint8_t b : val)
{
if (!first) s += ", ";
first = false;
static constexpr const char* digits = "0123456789ABCDEF";
s += digits[(b >> 4) & 0x0f];
s += digits[b & 0x0f];
}
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, std::vector<std::string>>::value>::type* = nullptr>
Log& operator<<(const T& val)
{
bool first = true;
for (const std::string& str : val)
{
if (!first) s += ", ";
first = false;
s += str;
}
return *this;
}
template<size_t N, size_t M, class T>
Log& operator<<(const Matrix<N, M, T>& val)
{
s += std::to_string(val.m[0]) + "," + std::to_string(val.m[1]) + "," + std::to_string(val.m[2]) + "," + std::to_string(val.m[3]) + "\n" +
std::to_string(val.m[4]) + "," + std::to_string(val.m[5]) + "," + std::to_string(val.m[6]) + "," + std::to_string(val.m[7]) + "\n" +
std::to_string(val.m[8]) + "," + std::to_string(val.m[9]) + "," + std::to_string(val.m[10]) + "," + std::to_string(val.m[11]) + "\n" +
std::to_string(val.m[12]) + "," + std::to_string(val.m[13]) + "," + std::to_string(val.m[14]) + "," + std::to_string(val.m[15]);
return *this;
}
template<class T>
Log& operator<<(const Quaternion<T>& val)
{
s += std::to_string(val.v[0]) + "," + std::to_string(val.v[1]) + "," +
std::to_string(val.v[2]) + "," + std::to_string(val.v[3]);
return *this;
}
template<size_t N, class T>
Log& operator<<(const Size<N, T>& val)
{
bool first = true;
for (T c : val.v)
{
if (!first) s += ",";
first = false;
s += std::to_string(c);
}
return *this;
}
template<size_t N, class T>
Log& operator<<(const Vector<N, T>& val)
{
bool first = true;
for (T c : val.v)
{
if (!first) s += ",";
first = false;
s += std::to_string(c);
}
return *this;
}
private:
const Logger& logger;
Level level = Level::INFO;
std::string s;
};
class Logger final
{
public:
explicit Logger(Log::Level initThreshold = Log::Level::ALL):
threshold(initThreshold)
{
#if !defined(__EMSCRIPTEN__)
logThread = std::thread(&Logger::logLoop, this);
#endif
}
~Logger()
{
#if !defined(__EMSCRIPTEN__)
std::unique_lock<std::mutex> lock(queueMutex);
running = false;
lock.unlock();
logCondition.notify_all();
if (logThread.joinable()) logThread.join();
#endif
}
Log log(Log::Level level = Log::Level::INFO) const
{
return Log(*this, level);
}
void log(const std::string& str, Log::Level level = Log::Level::INFO) const
{
if (level <= threshold)
{
#if defined(__EMSCRIPTEN__)
logString(str, level);
#else
std::unique_lock<std::mutex> lock(queueMutex);
logQueue.push(std::make_pair(level, str));
lock.unlock();
logCondition.notify_all();
#endif
}
}
private:
static void logString(const std::string& str, Log::Level level = Log::Level::INFO);
#ifdef DEBUG
std::atomic<Log::Level> threshold{Log::Level::ALL};
#else
std::atomic<Log::Level> threshold{Log::Level::INFO};
#endif
#if !defined(__EMSCRIPTEN__)
void logLoop()
{
for (;;)
{
std::unique_lock<std::mutex> lock(queueMutex);
while (running && logQueue.empty()) logCondition.wait(lock);
if (!running) break;
std::pair<Log::Level, std::string> str = std::move(logQueue.front());
logQueue.pop();
lock.unlock();
logString(str.second, str.first);
}
}
mutable std::condition_variable logCondition;
mutable std::mutex queueMutex;
mutable std::queue<std::pair<Log::Level, std::string>> logQueue;
std::thread logThread;
bool running = true;
#endif
};
}
#endif // OUZEL_UTILS_LOG_HPP
<commit_msg>Log matrix on a single line and implement logging for matrices of all dimensions<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_UTILS_LOG_HPP
#define OUZEL_UTILS_LOG_HPP
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
#include "math/Matrix.hpp"
#include "math/Quaternion.hpp"
#include "math/Size.hpp"
#include "math/Vector.hpp"
namespace ouzel
{
class Logger;
class Log final
{
public:
enum class Level
{
OFF,
ERR,
WARN,
INFO,
ALL
};
explicit Log(const Logger& initLogger, Level initLevel = Level::INFO):
logger(initLogger), level(initLevel)
{
}
Log(const Log& other):
logger(other.logger),
level(other.level),
s(other.s)
{
}
Log(Log&& other):
logger(other.logger),
level(other.level),
s(std::move(other.s))
{
other.level = Level::INFO;
}
Log& operator=(const Log& other)
{
level = other.level;
s = other.s;
return *this;
}
Log& operator=(Log&& other)
{
if (&other != this)
{
level = other.level;
other.level = Level::INFO;
s = std::move(other.s);
}
return *this;
}
~Log();
template<typename T, typename std::enable_if<std::is_arithmetic<T>::value && !std::is_same<T, bool>::value>::type* = nullptr>
Log& operator<<(T val)
{
s += std::to_string(val);
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, bool>::value>::type* = nullptr>
Log& operator<<(T val)
{
s += val ? "true" : "false";
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, std::string>::value>::type* = nullptr>
Log& operator<<(const T& val)
{
s += val;
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, char>::value>::type* = nullptr>
Log& operator<<(const T* val)
{
s += val;
return *this;
}
template<typename T, typename std::enable_if<!std::is_same<T, char>::value>::type* = nullptr>
Log& operator<<(const T* val)
{
static constexpr const char* digits = "0123456789ABCDEF";
std::string str(sizeof(val) * 2, '0');
for (size_t i = 0; i < sizeof(val) * 2; ++i)
str[i] = digits[(reinterpret_cast<uintptr_t>(val) >> (sizeof(val) * 2 - i - 1) * 4) & 0x0f];
s += str;
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, std::vector<uint8_t>>::value>::type* = nullptr>
Log& operator<<(const T& val)
{
bool first = true;
for (uint8_t b : val)
{
if (!first) s += ", ";
first = false;
static constexpr const char* digits = "0123456789ABCDEF";
s += digits[(b >> 4) & 0x0f];
s += digits[b & 0x0f];
}
return *this;
}
template<typename T, typename std::enable_if<std::is_same<T, std::vector<std::string>>::value>::type* = nullptr>
Log& operator<<(const T& val)
{
bool first = true;
for (const std::string& str : val)
{
if (!first) s += ", ";
first = false;
s += str;
}
return *this;
}
template<size_t N, size_t M, class T>
Log& operator<<(const Matrix<N, M, T>& val)
{
bool first = true;
for (T c : val.m)
{
if (!first) s += ",";
first = false;
s += std::to_string(c);
}
return *this;
}
template<class T>
Log& operator<<(const Quaternion<T>& val)
{
s += std::to_string(val.v[0]) + "," + std::to_string(val.v[1]) + "," +
std::to_string(val.v[2]) + "," + std::to_string(val.v[3]);
return *this;
}
template<size_t N, class T>
Log& operator<<(const Size<N, T>& val)
{
bool first = true;
for (T c : val.v)
{
if (!first) s += ",";
first = false;
s += std::to_string(c);
}
return *this;
}
template<size_t N, class T>
Log& operator<<(const Vector<N, T>& val)
{
bool first = true;
for (T c : val.v)
{
if (!first) s += ",";
first = false;
s += std::to_string(c);
}
return *this;
}
private:
const Logger& logger;
Level level = Level::INFO;
std::string s;
};
class Logger final
{
public:
explicit Logger(Log::Level initThreshold = Log::Level::ALL):
threshold(initThreshold)
{
#if !defined(__EMSCRIPTEN__)
logThread = std::thread(&Logger::logLoop, this);
#endif
}
~Logger()
{
#if !defined(__EMSCRIPTEN__)
std::unique_lock<std::mutex> lock(queueMutex);
running = false;
lock.unlock();
logCondition.notify_all();
if (logThread.joinable()) logThread.join();
#endif
}
Log log(Log::Level level = Log::Level::INFO) const
{
return Log(*this, level);
}
void log(const std::string& str, Log::Level level = Log::Level::INFO) const
{
if (level <= threshold)
{
#if defined(__EMSCRIPTEN__)
logString(str, level);
#else
std::unique_lock<std::mutex> lock(queueMutex);
logQueue.push(std::make_pair(level, str));
lock.unlock();
logCondition.notify_all();
#endif
}
}
private:
static void logString(const std::string& str, Log::Level level = Log::Level::INFO);
#ifdef DEBUG
std::atomic<Log::Level> threshold{Log::Level::ALL};
#else
std::atomic<Log::Level> threshold{Log::Level::INFO};
#endif
#if !defined(__EMSCRIPTEN__)
void logLoop()
{
for (;;)
{
std::unique_lock<std::mutex> lock(queueMutex);
while (running && logQueue.empty()) logCondition.wait(lock);
if (!running) break;
std::pair<Log::Level, std::string> str = std::move(logQueue.front());
logQueue.pop();
lock.unlock();
logString(str.second, str.first);
}
}
mutable std::condition_variable logCondition;
mutable std::mutex queueMutex;
mutable std::queue<std::pair<Log::Level, std::string>> logQueue;
std::thread logThread;
bool running = true;
#endif
};
}
#endif // OUZEL_UTILS_LOG_HPP
<|endoftext|> |
<commit_before>// Copyright (2015) Gustav
#include "finans/core/commandline.h"
#include <cassert>
#include <algorithm>
namespace argparse {
ParserError::ParserError(const std::string& error)
: runtime_error("error: " + error)
{
}
Arguments::Arguments(int argc, char* argv[]) : name_(argv[0])
{
for (int i = 1; i < argc; ++i)
{
args_.push_back(argv[i]);
}
}
Arguments::Arguments(const std::string& name, const std::vector<std::string>& args) : name_(name), args_(args) {
}
const std::string Arguments::operator[](int index) const
{
return args_[index];
}
const bool Arguments::is_empty() const
{
return args_.empty();
}
const std::string Arguments::name() const
{
return name_;
}
const size_t Arguments::size() const
{
return args_.size();
}
const std::string Arguments::ConsumeOne(const std::string& error)
{
if (is_empty()) throw ParserError(error);
const std::string r = args_[0];
args_.erase(args_.begin());
return r;
}
Count::Count(size_t c)
: count_(c)
, type_(Const)
{
}
Count::Count(Count::Type t)
: count_(0)
, type_(t)
{
assert(t != Const);
}
Count::Type Count::type() const
{
return type_;
}
size_t Count::count() const
{
return count_;
}
Running::Running(const std::string& aapp, std::ostream& ao)
: app(aapp)
, o(ao)
{
}
Argument::~Argument()
{
}
Argument::Argument(const Count& co)
: count_(co)
, has_been_parsed_(false)
, has_several_(false)
{
}
bool Argument::has_been_parsed() const {
return has_been_parsed_;
}
void Argument::set_has_been_parsed(bool v) {
if (has_several_) return;
has_been_parsed_ = v;
}
void Argument::ConsumeArguments(Running& r, Arguments& args, const std::string& argname) {
switch (count_.type())
{
case Count::Const:
for (size_t i = 0; i < count_.count(); ++i)
{
std::stringstream ss;
ss << "argument " << argname << ": expected ";
if (count_.count() == 1)
{
ss << "one argument";
}
else
{
ss << count_.count() << " argument(s), " << i << " already given";
}
OnArgument(r, args.ConsumeOne(ss.str()));
// abort on optional?
}
return;
case Count::MoreThanOne:
OnArgument(r, args.ConsumeOne("argument " + argname + ": expected atleast one argument"));
// fall through
case Count::ZeroOrMore:
while (args.is_empty() == false)
{
OnArgument(r, args.ConsumeOne("internal error"));
}
return;
case Count::Optional:
if (args.is_empty()) {
OnArgument(r, "");
return;
}
if (IsOptional(args[0])) {
OnArgument(r, "");
return;
}
OnArgument(r, args.ConsumeOne("internal error"));
return;
case Count::None:
OnArgument(r, "");
return;
default:
assert(0 && "internal error, ArgumentT::parse invalid Count");
throw "internal error, ArgumentT::parse invalid Count";
}
}
void Argument::set_has_several() {
has_several_ = true;
}
bool IsOptional(const std::string& arg)
{
if (arg.empty()) return false; // todo: assert this?
return arg[0] == '-';
}
Extra::Extra()
: count_(1)
, has_several_(false)
{
}
Extra& Extra::help(const std::string& h)
{
help_ = h;
return *this;
}
const std::string& Extra::help() const
{
return help_;
}
Extra& Extra::count(const Count c)
{
count_ = c;
return *this;
}
const Count& Extra::count() const
{
return count_;
}
Extra& Extra::metavar(const std::string& metavar)
{
metaVar_ = metavar;
return *this;
}
const std::string& Extra::metavar() const
{
return metaVar_;
}
Extra& Extra::several() {
has_several_ = true;
return *this;
}
bool Extra::has_several() const {
return has_several_;
}
std::string ToUpper(const std::string& s)
{
std::string str = s;
std::transform(str.begin(), str.end(), str.begin(), toupper);
return str;
}
Help::Help(const std::string& name, const Extra& e)
: name_(name)
, help_(e.help())
, metavar_(e.metavar())
, count_(e.count().type())
, countcount_(e.count().count())
{
}
const std::string Help::GetUsage() const
{
if (IsOptional(name_))
{
return "[" + name_ + " " + GetMetavarReprestentation() + "]";
}
else
{
return GetMetavarReprestentation();
}
}
const std::string Help::GetMetavarReprestentation() const
{
switch (count_)
{
case Count::None:
return "";
case Count::MoreThanOne:
return GetMetavarName() + " [" + GetMetavarName() + " ...]";
case Count::Optional:
return "[" + GetMetavarName() + "]";
case Count::ZeroOrMore:
return "[" + GetMetavarName() + " [" + GetMetavarName() + " ...]]";
case Count::Const:
{
std::ostringstream ss;
ss << "[";
for (size_t i = 0; i < countcount_; ++i)
{
if (i != 0)
{
ss << " ";
}
ss << GetMetavarName();
}
ss << "]";
return ss.str();
}
default:
assert(false && "missing case");
throw "invalid count type in " __FUNCTION__;
}
}
const std::string Help::GetMetavarName() const
{
if (metavar_.empty() == false)
{
return metavar_;
}
else
{
if (IsOptional(name_))
{
return ToUpper(name_.substr(1));
}
else
{
return name_;
}
}
}
const std::string Help::GetHelpCommand() const
{
if (IsOptional(name_))
{
return name_ + " " + GetMetavarReprestentation();
}
else
{
return GetMetavarName();
}
}
const std::string& Help::help() const
{
return help_;
}
struct CallHelp : public Argument
{
CallHelp(Parser* on)
: Argument( Count(Count::Optional) )
, parser(on)
{
}
void OnArgument(Running& r, const std::string& argname) override
{
parser->WriteHelp(r);
exit(0);
}
Parser* parser;
};
Parser::Parser(const std::string& d, const std::string aappname)
: positionalIndex_(0)
, description_(d)
, appname_(aappname)
{
std::shared_ptr<Argument> arg(new CallHelp(this));
AddArgument("-h", arg, Extra().count(Count(Count::None)).help("show this help message and exit"));
}
Parser::ParseStatus Parser::ParseArgs(int argc, char* argv[], std::ostream& out, std::ostream& error) const
{
Arguments args(argc, argv);
return ParseArgs(args, out, error);
}
Parser::ParseStatus Parser::ParseArgs(const Arguments& arguments, std::ostream& out, std::ostream& error) const {
Arguments args = arguments;
Running running(arguments.name(), out);
try
{
while (false == args.is_empty())
{
bool isParsed = false;
const bool isParsingPositionals = positionalIndex_ < positionals_.size();
if (IsOptional(args[0]))
{
// optional
const std::string arg = args[0];
Optionals::const_iterator r = optionals_.find(arg);
if (r == optionals_.end())
{
if( isParsingPositionals == false ) {
throw ParserError("Unknown optional argument: " + arg); // todo: implement partial matching of arguments?
}
}
else {
if( false == r->second->has_been_parsed() ) {
isParsed = true;
args.ConsumeOne(); // the optional command = arg[0}
r->second->ConsumeArguments(running, args, arg);
r->second->set_has_been_parsed(true);
}
}
}
if( isParsed == false ) {
if (positionalIndex_ >= positionals_.size())
{
throw ParserError("All positional arguments have been consumed: " + args[0]);
}
ArgumentPtr p = positionals_[positionalIndex_];
++positionalIndex_;
p->ConsumeArguments(running, args, "POSITIONAL"); // todo: give better name or something
}
}
if (positionalIndex_ != positionals_.size())
{
throw ParserError("too few arguments."); // todo: list a few missing arguments...
}
return ParseComplete;
}
catch (ParserError& p)
{
WriteUsage(running);
error << p.what() << "\n";
out << "\n";
return ParseFailed;
}
}
void Parser::WriteHelp(Running& r) const
{
WriteUsage(r);
r.o << std::endl << description_ << std::endl << std::endl;
const std::string sep = "\t";
const std::string ins = " ";
if (helpPositional_.empty() == false)
{
r.o << "Positional arguments: " << std::endl;
for (const Help& positional : helpPositional_)
{
r.o << ins << positional.GetHelpCommand() << sep << positional.help() << std::endl;
}
r.o << std::endl;
}
if (helpOptional_.empty() == false)
{
r.o << "Optional arguments: " << std::endl;
for (const Help& optional : helpOptional_)
{
r.o << ins << optional.GetHelpCommand() << sep << optional.help() << std::endl;
}
}
r.o << std::endl;
}
void Parser::WriteUsage(Running& r) const
{
r.o << "Usage: " << r.app;
for (const Help& optional : helpOptional_)
{
r.o << " " << optional.GetUsage();
}
for (const Help& positional : helpPositional_)
{
r.o << " " << positional.GetUsage();
}
r.o << std::endl;
}
Parser& Parser::AddArgument(const std::string& commands, ArgumentPtr arg, const Extra& extra)
{
if( extra.has_several() ) {
arg->set_has_several();
}
const auto names = Tokenize(commands, ",", true);
for(const auto name: names) {
if (IsOptional(name))
{
optionals_.insert(Optionals::value_type(name, arg));
helpOptional_.push_back(Help(name, extra));
}
else
{
positionals_.push_back(arg);
helpPositional_.push_back(Help(name, extra));
}
}
return *this;
}
}
<commit_msg>fixed some spacing issues<commit_after>// Copyright (2015) Gustav
#include "finans/core/commandline.h"
#include <cassert>
#include <algorithm>
namespace argparse {
ParserError::ParserError(const std::string& error)
: runtime_error("error: " + error)
{
}
Arguments::Arguments(int argc, char* argv[]) : name_(argv[0])
{
for (int i = 1; i < argc; ++i)
{
args_.push_back(argv[i]);
}
}
Arguments::Arguments(const std::string& name, const std::vector<std::string>& args) : name_(name), args_(args) {
}
const std::string Arguments::operator[](int index) const
{
return args_[index];
}
const bool Arguments::is_empty() const
{
return args_.empty();
}
const std::string Arguments::name() const
{
return name_;
}
const size_t Arguments::size() const
{
return args_.size();
}
const std::string Arguments::ConsumeOne(const std::string& error)
{
if (is_empty()) throw ParserError(error);
const std::string r = args_[0];
args_.erase(args_.begin());
return r;
}
Count::Count(size_t c)
: count_(c)
, type_(Const)
{
}
Count::Count(Count::Type t)
: count_(0)
, type_(t)
{
assert(t != Const);
}
Count::Type Count::type() const
{
return type_;
}
size_t Count::count() const
{
return count_;
}
Running::Running(const std::string& aapp, std::ostream& ao)
: app(aapp)
, o(ao)
{
}
Argument::~Argument()
{
}
Argument::Argument(const Count& co)
: count_(co)
, has_been_parsed_(false)
, has_several_(false)
{
}
bool Argument::has_been_parsed() const {
return has_been_parsed_;
}
void Argument::set_has_been_parsed(bool v) {
if (has_several_) return;
has_been_parsed_ = v;
}
void Argument::ConsumeArguments(Running& r, Arguments& args, const std::string& argname) {
switch (count_.type())
{
case Count::Const:
for (size_t i = 0; i < count_.count(); ++i)
{
std::stringstream ss;
ss << "argument " << argname << ": expected ";
if (count_.count() == 1)
{
ss << "one argument";
}
else
{
ss << count_.count() << " argument(s), " << i << " already given";
}
OnArgument(r, args.ConsumeOne(ss.str()));
// abort on optional?
}
return;
case Count::MoreThanOne:
OnArgument(r, args.ConsumeOne("argument " + argname + ": expected atleast one argument"));
// fall through
case Count::ZeroOrMore:
while (args.is_empty() == false)
{
OnArgument(r, args.ConsumeOne("internal error"));
}
return;
case Count::Optional:
if (args.is_empty()) {
OnArgument(r, "");
return;
}
if (IsOptional(args[0])) {
OnArgument(r, "");
return;
}
OnArgument(r, args.ConsumeOne("internal error"));
return;
case Count::None:
OnArgument(r, "");
return;
default:
assert(0 && "internal error, ArgumentT::parse invalid Count");
throw "internal error, ArgumentT::parse invalid Count";
}
}
void Argument::set_has_several() {
has_several_ = true;
}
bool IsOptional(const std::string& arg)
{
if (arg.empty()) return false; // todo: assert this?
return arg[0] == '-';
}
Extra::Extra()
: count_(1)
, has_several_(false)
{
}
Extra& Extra::help(const std::string& h)
{
help_ = h;
return *this;
}
const std::string& Extra::help() const
{
return help_;
}
Extra& Extra::count(const Count c)
{
count_ = c;
return *this;
}
const Count& Extra::count() const
{
return count_;
}
Extra& Extra::metavar(const std::string& metavar)
{
metaVar_ = metavar;
return *this;
}
const std::string& Extra::metavar() const
{
return metaVar_;
}
Extra& Extra::several() {
has_several_ = true;
return *this;
}
bool Extra::has_several() const {
return has_several_;
}
std::string ToUpper(const std::string& s)
{
std::string str = s;
std::transform(str.begin(), str.end(), str.begin(), toupper);
return str;
}
Help::Help(const std::string& name, const Extra& e)
: name_(name)
, help_(e.help())
, metavar_(e.metavar())
, count_(e.count().type())
, countcount_(e.count().count())
{
}
const std::string Help::GetUsage() const
{
if (IsOptional(name_))
{
const auto rep = GetMetavarReprestentation();
if( rep.empty()) return "[" + name_ + "]";
return "[" + name_ + " " + rep + "]";
}
else
{
return GetMetavarReprestentation();
}
}
const std::string Help::GetMetavarReprestentation() const
{
switch (count_)
{
case Count::None:
return "";
case Count::MoreThanOne:
return GetMetavarName() + " [" + GetMetavarName() + " ...]";
case Count::Optional:
return "[" + GetMetavarName() + "]";
case Count::ZeroOrMore:
return "[" + GetMetavarName() + " [" + GetMetavarName() + " ...]]";
case Count::Const:
{
std::ostringstream ss;
ss << "[";
for (size_t i = 0; i < countcount_; ++i)
{
if (i != 0)
{
ss << " ";
}
ss << GetMetavarName();
}
ss << "]";
return ss.str();
}
default:
assert(false && "missing case");
throw "invalid count type in " __FUNCTION__;
}
}
const std::string Help::GetMetavarName() const
{
if (metavar_.empty() == false)
{
return metavar_;
}
else
{
if (IsOptional(name_))
{
return ToUpper(name_.substr(1));
}
else
{
return name_;
}
}
}
const std::string Help::GetHelpCommand() const
{
if (IsOptional(name_))
{
return name_ + " " + GetMetavarReprestentation();
}
else
{
return GetMetavarName();
}
}
const std::string& Help::help() const
{
return help_;
}
struct CallHelp : public Argument
{
CallHelp(Parser* on)
: Argument( Count(Count::Optional) )
, parser(on)
{
}
void OnArgument(Running& r, const std::string& argname) override
{
parser->WriteHelp(r);
exit(0);
}
Parser* parser;
};
Parser::Parser(const std::string& d, const std::string aappname)
: positionalIndex_(0)
, description_(d)
, appname_(aappname)
{
std::shared_ptr<Argument> arg(new CallHelp(this));
AddArgument("-h", arg, Extra().count(Count(Count::None)).help("show this help message and exit"));
}
Parser::ParseStatus Parser::ParseArgs(int argc, char* argv[], std::ostream& out, std::ostream& error) const
{
Arguments args(argc, argv);
return ParseArgs(args, out, error);
}
Parser::ParseStatus Parser::ParseArgs(const Arguments& arguments, std::ostream& out, std::ostream& error) const {
Arguments args = arguments;
Running running(arguments.name(), out);
try
{
while (false == args.is_empty())
{
bool isParsed = false;
const bool isParsingPositionals = positionalIndex_ < positionals_.size();
if (IsOptional(args[0]))
{
// optional
const std::string arg = args[0];
Optionals::const_iterator r = optionals_.find(arg);
if (r == optionals_.end())
{
if( isParsingPositionals == false ) {
throw ParserError("Unknown optional argument: " + arg); // todo: implement partial matching of arguments?
}
}
else {
if( false == r->second->has_been_parsed() ) {
isParsed = true;
args.ConsumeOne(); // the optional command = arg[0}
r->second->ConsumeArguments(running, args, arg);
r->second->set_has_been_parsed(true);
}
}
}
if( isParsed == false ) {
if (positionalIndex_ >= positionals_.size())
{
throw ParserError("All positional arguments have been consumed: " + args[0]);
}
ArgumentPtr p = positionals_[positionalIndex_];
++positionalIndex_;
p->ConsumeArguments(running, args, "POSITIONAL"); // todo: give better name or something
}
}
if (positionalIndex_ != positionals_.size())
{
throw ParserError("too few arguments."); // todo: list a few missing arguments...
}
return ParseComplete;
}
catch (ParserError& p)
{
WriteUsage(running);
error << p.what() << "\n";
out << "\n";
return ParseFailed;
}
}
void Parser::WriteHelp(Running& r) const
{
WriteUsage(r);
r.o << std::endl << description_ << std::endl << std::endl;
const std::string sep = "\t";
const std::string ins = " ";
if (helpPositional_.empty() == false)
{
r.o << "Positional arguments: " << std::endl;
for (const Help& positional : helpPositional_)
{
r.o << ins << positional.GetHelpCommand() << sep << positional.help() << std::endl;
}
r.o << std::endl;
}
if (helpOptional_.empty() == false)
{
r.o << "Optional arguments: " << std::endl;
for (const Help& optional : helpOptional_)
{
r.o << ins << optional.GetHelpCommand() << sep << optional.help() << std::endl;
}
}
r.o << std::endl;
}
void Parser::WriteUsage(Running& r) const
{
r.o << "Usage:";
for (const Help& optional : helpOptional_)
{
r.o << " " << optional.GetUsage();
}
for (const Help& positional : helpPositional_)
{
r.o << " " << positional.GetUsage();
}
}
Parser& Parser::AddArgument(const std::string& commands, ArgumentPtr arg, const Extra& extra)
{
if( extra.has_several() ) {
arg->set_has_several();
}
const auto names = Tokenize(commands, ",", true);
for(const auto name: names) {
if (IsOptional(name))
{
optionals_.insert(Optionals::value_type(name, arg));
helpOptional_.push_back(Help(name, extra));
}
else
{
positionals_.push_back(arg);
helpPositional_.push_back(Help(name, extra));
}
}
return *this;
}
}
<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file EC_3DGizmo.h
* @brief EC_3DGizmo enables manipulators for values
* @author Nathan Letwory | http://www.letworyinteractive.com
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_3DGizmo.h"
#include "IModule.h"
#include "Entity.h"
#include "Renderer.h"
#include "OgreMaterialUtils.h"
#include "EC_Placeable.h"
#include "EC_Mesh.h"
#include "EC_OgreCustomObject.h"
#include "EC_OpenSimPrim.h"
#include "LoggingFunctions.h"
#include "RexUUID.h"
#include <Ogre.h>
DEFINE_POCO_LOGGING_FUNCTIONS("EC_3DGizmo")
#include "MemoryLeakCheck.h"
EC_3DGizmo::EC_3DGizmo(IModule *module) :
IComponent(module->GetFramework())
{
renderer_ = module->GetFramework()->GetServiceManager()->GetService<OgreRenderer::Renderer>();
QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(Update3DGizmo()));
attributes_ = QList<IAttribute *>();
subproperties_ = QStringList();
attribute_ = QString();
}
EC_3DGizmo::~EC_3DGizmo()
{
}
void EC_3DGizmo::AddEditableAttribute(IComponent* component, QString attribute_name, QString subprop)
{
if(attribute_.isEmpty())
attribute_ = attribute_name;
if(attribute_ == attribute_name) {
IAttribute* attribute = component->GetAttribute(attribute_name);
attributes_ << attribute;
subproperties_ << subprop;
for( int i = 0; i < attributes_.size(); i++)
{
IAttribute *attr = attributes_.at(i);
std::cout << attr->GetNameString() << std::endl;
}
}
}
void EC_3DGizmo::RemoveEditableAttribute(IComponent* component, QString &attribute_name)
{
int remove_idx = -1;
IAttribute* attribute = component->GetAttribute(attribute_name);
for(int i = 0; i < attributes_.size(); i++)
{
IAttribute *attr = attributes_.at(i);
if(attr == attribute) {
remove_idx = i;
break;
}
}
if(remove_idx!=-1) {
attributes_.removeAt(remove_idx);
subproperties_.removeAt(remove_idx);
}
}
void EC_3DGizmo::ClearEditableAttributes()
{
attributes_.clear();
subproperties_.clear();
attribute_.clear();
}
void EC_3DGizmo::Manipulate(QVariant datum)
{
std::cout << "3dgizmo update" << std::endl;
for(int i = 0; i < attributes_.size(); i++) {
IAttribute * attr = attributes_.at(i);
if(attr->GetNameString() == "Transform") {
Attribute<Transform>* attribute = dynamic_cast<Attribute<Transform> *>(attr);
if(attribute && datum.type()==QVariant::Vector3D) {
Transform trans = attribute->Get();
QVector3D vec = datum.value<QVector3D>();
QString subproperty = subproperties_.at(i);
if(subproperty=="position") {
trans.position.x += vec.x();
trans.position.y += vec.y();
trans.position.z += vec.z();
} else if (subproperty=="scale") {
trans.scale.x += vec.x();
trans.scale.y += vec.y();
trans.scale.z += vec.z();
} else if (subproperty=="rotation") {
trans.rotation.x += vec.x();
trans.rotation.y += vec.y();
trans.rotation.z += vec.z();
}
attribute->Set(trans, AttributeChange::Default);
}
} else {
switch(datum.type()) {
case QVariant::Double:
{
float value = datum.toFloat();
Attribute<float> *attribute = dynamic_cast<Attribute<float> *>(attr);
if(attribute)
attribute->Set(attribute->Get() + value, AttributeChange::Default);
}
break;
case QVariant::Int:
{
int value = datum.toInt();
Attribute<int> *attribute = dynamic_cast<Attribute<int> *>(attr);
if(attribute)
attribute->Set(attribute->Get() + value, AttributeChange::Default);
}
break;
case QVariant::Bool:
{
bool value = datum.toBool();
Attribute<bool> *attribute = dynamic_cast<Attribute<bool> *>(attr);
if(attribute)
attribute->Set(value, AttributeChange::Default);
}
break;
case QVariant::Vector3D:
{
QVector3D vec = datum.value<QVector3D>();
Vector3df value(vec.x(), vec.y(), vec.z());
Attribute<Vector3df> *attribute = dynamic_cast<Attribute<Vector3df> *>(attr);
if(attribute)
attribute->Set(attribute->Get() + value, AttributeChange::Default);
}
break;
}
}
}
std::cout << " ... ok" << std::endl;
}
<commit_msg>remove dangling connect with demised slot<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file EC_3DGizmo.h
* @brief EC_3DGizmo enables manipulators for values
* @author Nathan Letwory | http://www.letworyinteractive.com
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_3DGizmo.h"
#include "IModule.h"
#include "Entity.h"
#include "Renderer.h"
#include "OgreMaterialUtils.h"
#include "EC_Placeable.h"
#include "EC_Mesh.h"
#include "EC_OgreCustomObject.h"
#include "EC_OpenSimPrim.h"
#include "LoggingFunctions.h"
#include "RexUUID.h"
#include <Ogre.h>
DEFINE_POCO_LOGGING_FUNCTIONS("EC_3DGizmo")
#include "MemoryLeakCheck.h"
EC_3DGizmo::EC_3DGizmo(IModule *module) :
IComponent(module->GetFramework())
{
renderer_ = module->GetFramework()->GetServiceManager()->GetService<OgreRenderer::Renderer>();
attributes_ = QList<IAttribute *>();
subproperties_ = QStringList();
attribute_ = QString();
}
EC_3DGizmo::~EC_3DGizmo()
{
}
void EC_3DGizmo::AddEditableAttribute(IComponent* component, QString attribute_name, QString subprop)
{
if(attribute_.isEmpty())
attribute_ = attribute_name;
if(attribute_ == attribute_name) {
IAttribute* attribute = component->GetAttribute(attribute_name);
attributes_ << attribute;
subproperties_ << subprop;
for( int i = 0; i < attributes_.size(); i++)
{
IAttribute *attr = attributes_.at(i);
std::cout << attr->GetNameString() << std::endl;
}
}
}
void EC_3DGizmo::RemoveEditableAttribute(IComponent* component, QString &attribute_name)
{
int remove_idx = -1;
IAttribute* attribute = component->GetAttribute(attribute_name);
for(int i = 0; i < attributes_.size(); i++)
{
IAttribute *attr = attributes_.at(i);
if(attr == attribute) {
remove_idx = i;
break;
}
}
if(remove_idx!=-1) {
attributes_.removeAt(remove_idx);
subproperties_.removeAt(remove_idx);
}
}
void EC_3DGizmo::ClearEditableAttributes()
{
attributes_.clear();
subproperties_.clear();
attribute_.clear();
}
void EC_3DGizmo::Manipulate(QVariant datum)
{
std::cout << "3dgizmo update" << std::endl;
for(int i = 0; i < attributes_.size(); i++) {
IAttribute * attr = attributes_.at(i);
if(attr->GetNameString() == "Transform") {
Attribute<Transform>* attribute = dynamic_cast<Attribute<Transform> *>(attr);
if(attribute && datum.type()==QVariant::Vector3D) {
Transform trans = attribute->Get();
QVector3D vec = datum.value<QVector3D>();
QString subproperty = subproperties_.at(i);
if(subproperty=="position") {
trans.position.x += vec.x();
trans.position.y += vec.y();
trans.position.z += vec.z();
} else if (subproperty=="scale") {
trans.scale.x += vec.x();
trans.scale.y += vec.y();
trans.scale.z += vec.z();
} else if (subproperty=="rotation") {
trans.rotation.x += vec.x();
trans.rotation.y += vec.y();
trans.rotation.z += vec.z();
}
attribute->Set(trans, AttributeChange::Default);
}
} else {
switch(datum.type()) {
case QVariant::Double:
{
float value = datum.toFloat();
Attribute<float> *attribute = dynamic_cast<Attribute<float> *>(attr);
if(attribute)
attribute->Set(attribute->Get() + value, AttributeChange::Default);
}
break;
case QVariant::Int:
{
int value = datum.toInt();
Attribute<int> *attribute = dynamic_cast<Attribute<int> *>(attr);
if(attribute)
attribute->Set(attribute->Get() + value, AttributeChange::Default);
}
break;
case QVariant::Bool:
{
bool value = datum.toBool();
Attribute<bool> *attribute = dynamic_cast<Attribute<bool> *>(attr);
if(attribute)
attribute->Set(value, AttributeChange::Default);
}
break;
case QVariant::Vector3D:
{
QVector3D vec = datum.value<QVector3D>();
Vector3df value(vec.x(), vec.y(), vec.z());
Attribute<Vector3df> *attribute = dynamic_cast<Attribute<Vector3df> *>(attr);
if(attribute)
attribute->Set(attribute->Get() + value, AttributeChange::Default);
}
break;
}
}
}
std::cout << " ... ok" << std::endl;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MStatement.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hjs $ $Date: 2004-06-25 18:30:13 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_SSTATEMENT_HXX
#define CONNECTIVITY_SSTATEMENT_HXX
#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_
#include <com/sun/star/sdbc/XStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XBATCHEXECUTION_HPP_
#include <com/sun/star/sdbc/XBatchExecution.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_
#include <com/sun/star/sdbc/XCloseable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef INCLUDED_LIST
#include <list>
#define INCLUDED_LIST
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include "connectivity/sqliterator.hxx"
#endif
#ifndef _CONNECTIVITY_PARSE_SQLPARSE_HXX_
#include "connectivity/sqlparse.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_VALUE_HXX_
#include <connectivity/FValue.hxx>
#endif
#include "MConnection.hxx"
#include "MTable.hxx"
namespace connectivity
{
namespace mozab
{
class OResultSet;
typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::sdbc::XStatement,
::com::sun::star::sdbc::XWarningsSupplier,
::com::sun::star::sdbc::XCloseable> OStatement_BASE;
//**************************************************************
//************ Class: OStatement_Base
// is a base class for the normal statement and for the prepared statement
//**************************************************************
class OStatement_Base : public comphelper::OBaseMutex,
public OStatement_BASE,
public ::cppu::OPropertySetHelper,
public ::comphelper::OPropertyArrayUsageHelper<OStatement_Base>
{
::com::sun::star::sdbc::SQLWarning m_aLastWarning;
protected:
::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XResultSet> m_xResultSet; // The last ResultSet created
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> m_xDBMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xColNames; // table columns
// for this Statement
::std::list< ::rtl::OUString> m_aBatchList;
OTable* m_pTable;
OConnection* m_pConnection; // The owning Connection object
OValueRow m_aRow;
connectivity::OSQLParser m_aParser;
connectivity::OSQLParseTreeIterator m_aSQLIterator;
connectivity::OSQLParseNode* m_pParseTree;
::std::vector<sal_Int32> m_aColMapping;
::std::vector<sal_Int32> m_aOrderbyColumnNumber;
::std::vector<sal_Int16> m_aOrderbyAscending;
protected:
void disposeResultSet();
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
// OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any & rConvertedValue,
::com::sun::star::uno::Any & rOldValue,
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);
virtual void SAL_CALL getFastPropertyValue(
::com::sun::star::uno::Any& rValue,
sal_Int32 nHandle) const;
virtual ~OStatement_Base();
protected:
//
// Driver Internal Methods
//
virtual sal_Bool parseSql( const ::rtl::OUString& sql , sal_Bool bAdjusted = sal_False) throw (
::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );
OResultSet* createResultSet();
virtual void initializeResultSet( OResultSet* _pResult );
void createColumnMapping();
void analyseSQL();
void setOrderbyColumn( connectivity::OSQLParseNode* pColumnRef,
connectivity::OSQLParseNode* pAscendingDescending);
void reset () throw( ::com::sun::star::sdbc::SQLException);
void clearMyResultSet () throw( ::com::sun::star::sdbc::SQLException);
virtual void createTable( ) throw (
::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );
public:
// other methods
OConnection* getOwnConnection() const { return m_pConnection;}
::cppu::OBroadcastHelper& rBHelper;
OStatement_Base(OConnection* _pConnection );
using OStatement_BASE::operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >;
// OComponentHelper
virtual void SAL_CALL disposing(void){OStatement_BASE::disposing();}
// XInterface
virtual void SAL_CALL release() throw();
virtual void SAL_CALL acquire() throw();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
//XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
// XStatement
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
virtual sal_Int32 SAL_CALL executeUpdate( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
virtual sal_Bool SAL_CALL execute( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
// XWarningsSupplier
virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
class OStatement_BASE2 :public OStatement_Base
,public ::connectivity::OSubComponent<OStatement_BASE2, OStatement_BASE>
{
friend class OSubComponent<OStatement_BASE2, OStatement_BASE>;
public:
OStatement_BASE2(OConnection* _pConnection ) : OStatement_Base(_pConnection ),
::connectivity::OSubComponent<OStatement_BASE2, OStatement_BASE>((::cppu::OWeakObject*)_pConnection, this){}
// OComponentHelper
virtual void SAL_CALL disposing(void);
// XInterface
virtual void SAL_CALL release() throw();
};
class OStatement : public OStatement_BASE2,
public ::com::sun::star::lang::XServiceInfo
{
protected:
~OStatement(){}
public:
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
OStatement( OConnection* _pConnection) : OStatement_BASE2( _pConnection){}
DECLARE_SERVICE_INFO();
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
};
}
}
#endif // CONNECTIVITY_SSTATEMENT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.138); FILE MERGED 2005/09/05 17:24:25 rt 1.4.138.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MStatement.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:21:06 $
*
* 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 CONNECTIVITY_SSTATEMENT_HXX
#define CONNECTIVITY_SSTATEMENT_HXX
#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_
#include <com/sun/star/sdbc/XStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XBATCHEXECUTION_HPP_
#include <com/sun/star/sdbc/XBatchExecution.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_
#include <com/sun/star/sdbc/XCloseable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef INCLUDED_LIST
#include <list>
#define INCLUDED_LIST
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include "connectivity/sqliterator.hxx"
#endif
#ifndef _CONNECTIVITY_PARSE_SQLPARSE_HXX_
#include "connectivity/sqlparse.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_VALUE_HXX_
#include <connectivity/FValue.hxx>
#endif
#include "MConnection.hxx"
#include "MTable.hxx"
namespace connectivity
{
namespace mozab
{
class OResultSet;
typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::sdbc::XStatement,
::com::sun::star::sdbc::XWarningsSupplier,
::com::sun::star::sdbc::XCloseable> OStatement_BASE;
//**************************************************************
//************ Class: OStatement_Base
// is a base class for the normal statement and for the prepared statement
//**************************************************************
class OStatement_Base : public comphelper::OBaseMutex,
public OStatement_BASE,
public ::cppu::OPropertySetHelper,
public ::comphelper::OPropertyArrayUsageHelper<OStatement_Base>
{
::com::sun::star::sdbc::SQLWarning m_aLastWarning;
protected:
::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XResultSet> m_xResultSet; // The last ResultSet created
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> m_xDBMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xColNames; // table columns
// for this Statement
::std::list< ::rtl::OUString> m_aBatchList;
OTable* m_pTable;
OConnection* m_pConnection; // The owning Connection object
OValueRow m_aRow;
connectivity::OSQLParser m_aParser;
connectivity::OSQLParseTreeIterator m_aSQLIterator;
connectivity::OSQLParseNode* m_pParseTree;
::std::vector<sal_Int32> m_aColMapping;
::std::vector<sal_Int32> m_aOrderbyColumnNumber;
::std::vector<sal_Int16> m_aOrderbyAscending;
protected:
void disposeResultSet();
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
// OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any & rConvertedValue,
::com::sun::star::uno::Any & rOldValue,
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);
virtual void SAL_CALL getFastPropertyValue(
::com::sun::star::uno::Any& rValue,
sal_Int32 nHandle) const;
virtual ~OStatement_Base();
protected:
//
// Driver Internal Methods
//
virtual sal_Bool parseSql( const ::rtl::OUString& sql , sal_Bool bAdjusted = sal_False) throw (
::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );
OResultSet* createResultSet();
virtual void initializeResultSet( OResultSet* _pResult );
void createColumnMapping();
void analyseSQL();
void setOrderbyColumn( connectivity::OSQLParseNode* pColumnRef,
connectivity::OSQLParseNode* pAscendingDescending);
void reset () throw( ::com::sun::star::sdbc::SQLException);
void clearMyResultSet () throw( ::com::sun::star::sdbc::SQLException);
virtual void createTable( ) throw (
::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );
public:
// other methods
OConnection* getOwnConnection() const { return m_pConnection;}
::cppu::OBroadcastHelper& rBHelper;
OStatement_Base(OConnection* _pConnection );
using OStatement_BASE::operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >;
// OComponentHelper
virtual void SAL_CALL disposing(void){OStatement_BASE::disposing();}
// XInterface
virtual void SAL_CALL release() throw();
virtual void SAL_CALL acquire() throw();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
//XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
// XStatement
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
virtual sal_Int32 SAL_CALL executeUpdate( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
virtual sal_Bool SAL_CALL execute( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
// XWarningsSupplier
virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
class OStatement_BASE2 :public OStatement_Base
,public ::connectivity::OSubComponent<OStatement_BASE2, OStatement_BASE>
{
friend class OSubComponent<OStatement_BASE2, OStatement_BASE>;
public:
OStatement_BASE2(OConnection* _pConnection ) : OStatement_Base(_pConnection ),
::connectivity::OSubComponent<OStatement_BASE2, OStatement_BASE>((::cppu::OWeakObject*)_pConnection, this){}
// OComponentHelper
virtual void SAL_CALL disposing(void);
// XInterface
virtual void SAL_CALL release() throw();
};
class OStatement : public OStatement_BASE2,
public ::com::sun::star::lang::XServiceInfo
{
protected:
~OStatement(){}
public:
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
OStatement( OConnection* _pConnection) : OStatement_BASE2( _pConnection){}
DECLARE_SERVICE_INFO();
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
};
}
}
#endif // CONNECTIVITY_SSTATEMENT_HXX
<|endoftext|> |
<commit_before>#include <mbed.h>
#include <cmsis_os.h>
#include <memory>
#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"
#include "RJBaseUSBDevice.hpp"
#define RJ_WATCHDOG_TIMER_VALUE 2 // seconds
using namespace std;
// USBHID interface. The false at the end tells it not to connect initially
RJBaseUSBDevice usbLink(RJ_BASE2015_VENDOR_ID, RJ_BASE2015_PRODUCT_ID,
RJ_BASE2015_RELEASE);
bool initRadio() {
// setup SPI bus
shared_ptr<SharedSPI> sharedSPI =
make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
sharedSPI->format(8, 0); // 8 bits per transfer
// RX/TX leds
auto rxTimeoutLED = make_shared<FlashingTimeoutLED>(LED1);
auto txTimeoutLED = make_shared<FlashingTimeoutLED>(LED2);
// Startup the CommModule interface
CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
shared_ptr<CommModule> commModule = CommModule::Instance;
// Create a new physical hardware communication link
global_radio =
new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
sizeof(preferredSettings) / sizeof(registerSetting_t));
return global_radio->isConnected();
}
void radioRxHandler(rtp::packet* pkt) {
LOG(INF3, "radioRxHandler()");
// write packet content out to endpoint 1
vector<uint8_t> buffer;
pkt->pack(&buffer);
bool success = usbLink.writeNB(1, buffer.data(), buffer.size(),
MAX_PACKET_SIZE_EPBULK);
if (!success) {
LOG(WARN, "Failed to transfer received packet over usb");
}
}
int main() {
// set baud rate to higher value than the default for faster terminal
Serial s(RJ_SERIAL_RXTX);
s.baud(57600);
printf("****************************************\r\n");
// Set the default logging configurations
isLogging = RJ_LOGGING_EN;
rjLogLevel = INF3;
LOG(INIT, "Base station starting...");
if (initRadio()) {
LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());
// register handlers for any ports we might use
for (rtp::port port :
{rtp::port::CONTROL, rtp::port::PING, rtp::port::LEGACY}) {
CommModule::Instance->setRxHandler(&radioRxHandler, port);
CommModule::Instance->setTxHandler((CommLink*)global_radio,
&CommLink::sendPacket, port);
}
} else {
LOG(FATAL, "No radio interface found!");
}
DigitalOut radioStatusLed(LED4, global_radio->isConnected());
// set callbacks for usb control transfers
usbLink.writeRegisterCallback =
[](uint8_t reg, uint8_t val) { global_radio->writeReg(reg, val); };
usbLink.readRegisterCallback =
[](uint8_t reg) { return global_radio->readReg(reg); };
usbLink.strobeCallback =
[](uint8_t strobe) { global_radio->strobe(strobe); };
LOG(INIT, "Initializing USB interface...");
usbLink.connect(); // note: this blocks until the link is connected
LOG(INIT, "Initialized USB interface!");
// Set the watdog timer's initial config
Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);
LOG(INIT, "Listening for commands over USB");
uint8_t buf[MAX_PACKET_SIZE_EPBULK];
uint32_t bufSize;
while (true) {
// make sure we can always reach back to main by renewing the watchdog
// timer periodically
Watchdog::Renew();
// attempt to read data from endpoint 2
// if data is available, write it into @pkt and send it
if (usbLink.readEP_NB(2, buf, &bufSize, sizeof(buf))) {
LOG(INF3, "Read %d bytes from BULK IN", bufSize);
// construct packet from buffer received over USB
rtp::packet pkt;
pkt.recv(buf, bufSize);
// transmit!
CommModule::Instance->send(pkt);
}
}
}
<commit_msg>fixed bulk read in base station<commit_after>#include <mbed.h>
#include <cmsis_os.h>
#include <memory>
#include "SharedSPI.hpp"
#include "CC1201Radio.hpp"
#include "logger.hpp"
#include "pins.hpp"
#include "usb-interface.hpp"
#include "watchdog.hpp"
#include "RJBaseUSBDevice.hpp"
#define RJ_WATCHDOG_TIMER_VALUE 2 // seconds
using namespace std;
// USBHID interface. The false at the end tells it not to connect initially
RJBaseUSBDevice usbLink(RJ_BASE2015_VENDOR_ID, RJ_BASE2015_PRODUCT_ID,
RJ_BASE2015_RELEASE);
bool initRadio() {
// setup SPI bus
shared_ptr<SharedSPI> sharedSPI =
make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK);
sharedSPI->format(8, 0); // 8 bits per transfer
// RX/TX leds
auto rxTimeoutLED = make_shared<FlashingTimeoutLED>(LED1);
auto txTimeoutLED = make_shared<FlashingTimeoutLED>(LED2);
// Startup the CommModule interface
CommModule::Instance = make_shared<CommModule>(rxTimeoutLED, txTimeoutLED);
shared_ptr<CommModule> commModule = CommModule::Instance;
// Create a new physical hardware communication link
global_radio =
new CC1201(sharedSPI, RJ_RADIO_nCS, RJ_RADIO_INT, preferredSettings,
sizeof(preferredSettings) / sizeof(registerSetting_t));
return global_radio->isConnected();
}
void radioRxHandler(rtp::packet* pkt) {
LOG(INF3, "radioRxHandler()");
// write packet content out to endpoint 1
vector<uint8_t> buffer;
pkt->pack(&buffer);
bool success = usbLink.writeNB(1, buffer.data(), buffer.size(),
MAX_PACKET_SIZE_EPBULK);
if (!success) {
LOG(WARN, "Failed to transfer received packet over usb");
}
}
int main() {
// set baud rate to higher value than the default for faster terminal
Serial s(RJ_SERIAL_RXTX);
s.baud(57600);
printf("****************************************\r\n");
// Set the default logging configurations
isLogging = RJ_LOGGING_EN;
rjLogLevel = INF3;
LOG(INIT, "Base station starting...");
if (initRadio()) {
LOG(INIT, "Radio interface ready on %3.2fMHz!", global_radio->freq());
// register handlers for any ports we might use
for (rtp::port port :
{rtp::port::CONTROL, rtp::port::PING, rtp::port::LEGACY}) {
CommModule::Instance->setRxHandler(&radioRxHandler, port);
CommModule::Instance->setTxHandler((CommLink*)global_radio,
&CommLink::sendPacket, port);
}
} else {
LOG(FATAL, "No radio interface found!");
}
DigitalOut radioStatusLed(LED4, global_radio->isConnected());
// set callbacks for usb control transfers
usbLink.writeRegisterCallback =
[](uint8_t reg, uint8_t val) { global_radio->writeReg(reg, val); };
usbLink.readRegisterCallback =
[](uint8_t reg) { return global_radio->readReg(reg); };
usbLink.strobeCallback =
[](uint8_t strobe) { global_radio->strobe(strobe); };
LOG(INIT, "Initializing USB interface...");
usbLink.connect(); // note: this blocks until the link is connected
LOG(INIT, "Initialized USB interface!");
// Set the watdog timer's initial config
Watchdog::Set(RJ_WATCHDOG_TIMER_VALUE);
LOG(INIT, "Listening for commands over USB");
// buffer to read data from usb bulk transfers into
// buf[0] will contain the length of the rest of the buffer
uint8_t buf[MAX_PACKET_SIZE_EPBULK + 1];
uint32_t bufSize;
while (true) {
// make sure we can always reach back to main by renewing the watchdog
// timer periodically
Watchdog::Renew();
// attempt to read data from endpoint 2
// if data is available, write it into @pkt and send it
if (usbLink.readEP_NB(EPBULK_OUT, &buf[1], &bufSize, sizeof(buf) - 1)) {
LOG(INF3, "Read %d bytes from BULK IN", bufSize);
// construct packet from buffer received over USB
rtp::packet pkt;
buf[0] = (uint8_t)bufSize;
pkt.recv(buf, bufSize + 1);
// TODO: remove this, the buffer should contain this
pkt.port(rtp::port::CONTROL);
// transmit!
CommModule::Instance->send(pkt);
}
}
}
<|endoftext|> |
<commit_before>#include <vector>
#include "gtest/gtest.h"
#include "tests/hom/common.hh"
#include "tests/hom/common_inductives.hh"
/*-------------------------------------------------------------------------------------------*/
const SDD one = sdd::one<conf>();
const hom id = sdd::hom::Id<conf>();
typedef sdd::hom::saturation_sum<conf>::optional_type optional;
struct hom_saturation_sum_test
: public testing::Test
{
};
/*-------------------------------------------------------------------------------------------*/
TEST_F(hom_saturation_sum_test, construction)
{
{
std::vector<hom> g {id, Inductive<conf>(targeted_noop(0))};
ASSERT_EQ( SaturationSum<conf>(0, optional(), g.begin(), g.end(), optional())
, SaturationSum<conf>(0, optional(), g.begin(), g.end(), optional()));
}
{
std::vector<hom> g1 {id, Inductive<conf>(targeted_noop(0))};
std::vector<hom> g2 {id, Inductive<conf>(targeted_noop(2))};
ASSERT_NE( SaturationSum<conf>(0, optional(), g1.begin(), g1.end(), optional())
, SaturationSum<conf>(0, optional(), g2.begin(), g2.end(), optional()));
}
}
/*-------------------------------------------------------------------------------------------*/
TEST_F(hom_saturation_sum_test, evaluation)
{
{
SDD s0('a', {0}, SDD('b', {0}, SDD('c', {0}, one)));
std::vector<hom> empty_g;
const hom s = SaturationSum<conf>( 'c', Inductive<conf>(incr(1))
, empty_g.begin(), empty_g.end(), optional());
std::vector<hom> g {Inductive<conf>(incr(1))};
const hom h = SaturationSum<conf>('b', s, g.begin(), g.end(), optional());
SDD ref = SDD('a', {0}, SDD('b', {1}, SDD('c', {0}, one)))
+ SDD('a', {0}, SDD('b', {0}, SDD('c', {1}, one)));
ASSERT_EQ(ref, h(s0));
}
}
/*-------------------------------------------------------------------------------------------*/
<commit_msg>Meaningful test for Saturation Sum.<commit_after>#include <vector>
#include "gtest/gtest.h"
#include "tests/hom/common.hh"
#include "tests/hom/common_inductives.hh"
/*-------------------------------------------------------------------------------------------*/
const SDD one = sdd::one<conf>();
const hom id = sdd::hom::Id<conf>();
typedef sdd::hom::saturation_sum<conf>::optional_type optional;
struct hom_saturation_sum_test
: public testing::Test
{
};
/*-------------------------------------------------------------------------------------------*/
TEST_F(hom_saturation_sum_test, construction)
{
{
std::vector<hom> g {id, Inductive<conf>(targeted_noop(0))};
ASSERT_EQ( SaturationSum<conf>(0, optional(), g.begin(), g.end(), optional())
, SaturationSum<conf>(0, optional(), g.begin(), g.end(), optional()));
}
{
std::vector<hom> g1 {id, Inductive<conf>(targeted_noop(0))};
std::vector<hom> g2 {id, Inductive<conf>(targeted_noop(2))};
ASSERT_NE( SaturationSum<conf>(0, optional(), g1.begin(), g1.end(), optional())
, SaturationSum<conf>(0, optional(), g2.begin(), g2.end(), optional()));
}
}
/*-------------------------------------------------------------------------------------------*/
TEST_F(hom_saturation_sum_test, evaluation)
{
{
SDD s0('a', {0}, SDD('b', {0}, SDD('c', {0}, one)));
std::vector<hom> empty_g;
const hom s = SaturationSum<conf>( 'c', Inductive<conf>(targeted_incr('c', 1))
, empty_g.begin(), empty_g.end(), optional());
std::vector<hom> g {Inductive<conf>(targeted_incr('b', 1))};
const hom h = SaturationSum<conf>('b', s, g.begin(), g.end(), optional());
SDD ref = SDD('a', {0}, SDD('b', {1}, SDD('c', {0}, one)))
+ SDD('a', {0}, SDD('b', {0}, SDD('c', {1}, one)));
ASSERT_EQ(ref, h(s0));
}
}
/*-------------------------------------------------------------------------------------------*/
<|endoftext|> |
<commit_before>#include "make_system.h"
#include "vector.h"
#include "rotor.h"
#include "memory.h"
// Did I mention that 'make_system' works by magic?
template <typename T>
inline void demarcate (char * & memory, T * & pointer, unsigned N)
{
pointer = (T *) memory;
memory += N * sizeof (T);
}
void make_system (unsigned q, unsigned r, const float (& xyz_in) [3] [4], float (* xyz) [4], unsigned (* indices) [6])
{
unsigned * P, * Q, * R; // Permutations taking black triangles around nodes.
unsigned * Px, * Qx, * Rx; // Take a triangle to its P-, Q- or R-node.
unsigned * P0, * R0; // One of the triangles around each P- and R- node.
// This is too much memory to allocate on the stack in one go under -nostdlib.
void * const memory = allocate_internal (410 * sizeof (unsigned));
unsigned * memp = (unsigned *) memory;
P = memp; memp += 60;
Q = memp; memp += 60;
R = memp; memp += 60;
Px = memp; memp += 60;
Qx = memp; memp += 60;
Rx = memp; memp += 60;
P0 = memp; memp += 30;
R0 = memp; // memp += 20;
const unsigned p = 2, N = 2 * p*q*r / (q*r + r*p + p*q - p*q*r), Np = N / p, Nq = N / q, Nr = N / r;
float (* x) [4] = xyz;
float (* y) [4] = x + Np;
float (* z) [4] = y + Nq;
store4f (x [0], load4f (xyz_in [0]));
store4f (y [0], load4f (xyz_in [1]));
store4f (z [0], load4f (xyz_in [2]));
for (unsigned n = 0; n != N; ++ n) {
n [P] = N;
n [Q] = n - n % q + (n + 1) % q;
n [R] = N;
Qx [n] = n / q;
if (n < q) {
Px [n] = n;
Rx [n] = n;
P0 [n] = n;
R0 [n] = n;
}
else
{
Px [n] = Np;
Rx [n] = Nr;
if (n < Np) P0 [n] = N;
if (n < Nr) R0 [n] = N;
}
}
float two_pi = 0x1.921fb6P2;
float A = two_pi / p;
float B = two_pi / q;
// We know the co-ordinates of the P- and R-nodes around Q-node 0.
rotor_t Y_rotate (y [0], B);
for (unsigned k = 1; k != q; ++ k) {
Y_rotate (x [P0 [k - 1]], x [P0 [k]]);
Y_rotate (z [R0 [k - 1]], z [R0 [k]]);
}
unsigned n0 = 0, p_node = q, r_node = q;
for (unsigned m0 = q; m0 != N; m0 += q) {
while (n0 [P] != N) ++ n0;
// Triangles m and n share a P-node.
Px [m0] = Px [n0];
// At this point we learn the co-ordinates of the next Q-node.
// We can't yet say much about its surrounding P- and R-nodes,
// because we don't know which of them should be identified
// with nodes which are already known (from earlier Q-nodes)
// and which are new.
rotor_t X_rotate (x [Px [n0]], A);
X_rotate (y [Qx [n0]], y [Qx [m0]]);
// Work out the consequences of identifying the two P-nodes.
// This is where the magic happens.
unsigned n = n0, m = m0;
do {
n [P] = m;
m = m [Q];
m [R] = n;
if (Rx [m] == Nr) {
Rx [m] = Rx [n];
}
else if (Rx [n] == Nr) {
Rx [n] = Rx [m];
}
unsigned d = 1;
while (d != r && n [R] != N) {
n = n [R];
++ d;
}
while (d != r && m [P] != N) {
m = m [P] [Q];
++ d;
}
if (d == r - 1) {
n [R] = m;
n = n - n % q + (n + q - 1) % q;
m [P] = n;
if (Px [m] == Np) {
Px [m] = Px [n];
}
else if (Px [n] == Np) {
Px [n] = Px [m];
}
}
if (n [P] != N) {
n = m0;
m = n0;
}
} while (n [P] == N);
// Now all the nodes that our new triangles share with old triangles
// are identified with nodes that are already labelled, so we can give
// new labels to the remaining nodes and compute their vectors.
rotor_t Y_rotate (y [Qx [m0]], B);
for (unsigned n = m0 + 1; n != m0 + q; ++ n) {
if (Px [n] == Np) {
P0 [p_node] = n;
Px [n] = p_node ++;
Y_rotate (x [Px [n - 1]], x [Px [n]]);
}
if (Rx [n] == Nr) {
R0 [r_node] = n;
Rx [n] = r_node ++;
Y_rotate (z [Rx [n - 1]], z [Rx [n]]);
}
}
}
for (unsigned n = 0; n != N; ++ n) {
unsigned i = n;
unsigned j = i [R];
unsigned k = j [P];
indices [n] [0] = Px [j];
indices [n] [1] = Qx [j] + N / p;
indices [n] [2] = Rx [i] + N / p + N / q;
indices [n] [3] = Px [i];
indices [n] [4] = Qx [k] + N / p;
indices [n] [5] = Rx [k] + N / p + N / q;
}
deallocate (memory);
}
<commit_msg>Delete unused demarcate function.<commit_after>#include "make_system.h"
#include "vector.h"
#include "rotor.h"
#include "memory.h"
// Did I mention that 'make_system' works by magic?
void make_system (unsigned q, unsigned r, const float (& xyz_in) [3] [4], float (* xyz) [4], unsigned (* indices) [6])
{
unsigned * P, * Q, * R; // Permutations taking black triangles around nodes.
unsigned * Px, * Qx, * Rx; // Take a triangle to its P-, Q- or R-node.
unsigned * P0, * R0; // One of the triangles around each P- and R- node.
// This is too much memory to allocate on the stack in one go under -nostdlib.
void * const memory = allocate_internal (410 * sizeof (unsigned));
unsigned * memp = (unsigned *) memory;
P = memp; memp += 60;
Q = memp; memp += 60;
R = memp; memp += 60;
Px = memp; memp += 60;
Qx = memp; memp += 60;
Rx = memp; memp += 60;
P0 = memp; memp += 30;
R0 = memp; // memp += 20;
const unsigned p = 2, N = 2 * p*q*r / (q*r + r*p + p*q - p*q*r), Np = N / p, Nq = N / q, Nr = N / r;
float (* x) [4] = xyz;
float (* y) [4] = x + Np;
float (* z) [4] = y + Nq;
store4f (x [0], load4f (xyz_in [0]));
store4f (y [0], load4f (xyz_in [1]));
store4f (z [0], load4f (xyz_in [2]));
for (unsigned n = 0; n != N; ++ n) {
n [P] = N;
n [Q] = n - n % q + (n + 1) % q;
n [R] = N;
Qx [n] = n / q;
if (n < q) {
Px [n] = n;
Rx [n] = n;
P0 [n] = n;
R0 [n] = n;
}
else
{
Px [n] = Np;
Rx [n] = Nr;
if (n < Np) P0 [n] = N;
if (n < Nr) R0 [n] = N;
}
}
float two_pi = 0x1.921fb6P2;
float A = two_pi / p;
float B = two_pi / q;
// We know the co-ordinates of the P- and R-nodes around Q-node 0.
rotor_t Y_rotate (y [0], B);
for (unsigned k = 1; k != q; ++ k) {
Y_rotate (x [P0 [k - 1]], x [P0 [k]]);
Y_rotate (z [R0 [k - 1]], z [R0 [k]]);
}
unsigned n0 = 0, p_node = q, r_node = q;
for (unsigned m0 = q; m0 != N; m0 += q) {
while (n0 [P] != N) ++ n0;
// Triangles m and n share a P-node.
Px [m0] = Px [n0];
// At this point we learn the co-ordinates of the next Q-node.
// We can't yet say much about its surrounding P- and R-nodes,
// because we don't know which of them should be identified
// with nodes which are already known (from earlier Q-nodes)
// and which are new.
rotor_t X_rotate (x [Px [n0]], A);
X_rotate (y [Qx [n0]], y [Qx [m0]]);
// Work out the consequences of identifying the two P-nodes.
// This is where the magic happens.
unsigned n = n0, m = m0;
do {
n [P] = m;
m = m [Q];
m [R] = n;
if (Rx [m] == Nr) {
Rx [m] = Rx [n];
}
else if (Rx [n] == Nr) {
Rx [n] = Rx [m];
}
unsigned d = 1;
while (d != r && n [R] != N) {
n = n [R];
++ d;
}
while (d != r && m [P] != N) {
m = m [P] [Q];
++ d;
}
if (d == r - 1) {
n [R] = m;
n = n - n % q + (n + q - 1) % q;
m [P] = n;
if (Px [m] == Np) {
Px [m] = Px [n];
}
else if (Px [n] == Np) {
Px [n] = Px [m];
}
}
if (n [P] != N) {
n = m0;
m = n0;
}
} while (n [P] == N);
// Now all the nodes that our new triangles share with old triangles
// are identified with nodes that are already labelled, so we can give
// new labels to the remaining nodes and compute their vectors.
rotor_t Y_rotate (y [Qx [m0]], B);
for (unsigned n = m0 + 1; n != m0 + q; ++ n) {
if (Px [n] == Np) {
P0 [p_node] = n;
Px [n] = p_node ++;
Y_rotate (x [Px [n - 1]], x [Px [n]]);
}
if (Rx [n] == Nr) {
R0 [r_node] = n;
Rx [n] = r_node ++;
Y_rotate (z [Rx [n - 1]], z [Rx [n]]);
}
}
}
for (unsigned n = 0; n != N; ++ n) {
unsigned i = n;
unsigned j = i [R];
unsigned k = j [P];
indices [n] [0] = Px [j];
indices [n] [1] = Qx [j] + N / p;
indices [n] [2] = Rx [i] + N / p + N / q;
indices [n] [3] = Px [i];
indices [n] [4] = Qx [k] + N / p;
indices [n] [5] = Rx [k] + N / p + N / q;
}
deallocate (memory);
}
<|endoftext|> |
<commit_before>//
// Copyright 2013 Jeff Bush
//
// 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 "assert.h"
#include "Debug.h"
#include "RenderTarget.h"
#include "ParameterInterpolator.h"
#include "Rasterizer.h"
#include "PixelShader.h"
#include "TextureSampler.h"
#include "utils.h"
#define COLOR_SHADER 0
#define TEXTURE_SHADER 1
const int kMaxTileIndex = (640 / 64) * ((480 / 64) + 1);
int nextTileIndex = 0;
extern char *kImage;
struct Vertex
{
float coord[3];
float params[kMaxParams];
};
class ColorShader : public PixelShader
{
public:
ColorShader(ParameterInterpolator *interp, RenderTarget *target)
: PixelShader(interp, target)
{}
virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask);
};
void ColorShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short /* mask */)
{
for (int i = 0; i < 3; i++)
outParams[i] = inParams[i];
outParams[3] = __builtin_vp_makevectorf(0.7f);
}
class CheckerboardShader : public PixelShader
{
public:
CheckerboardShader(ParameterInterpolator *interp, RenderTarget *target)
: PixelShader(interp, target)
{}
virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask);
};
void CheckerboardShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short /* mask */)
{
veci16 u = ((__builtin_vp_vftoi(inParams[0] * __builtin_vp_makevectorf(65535.0)))
>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);
veci16 v = ((__builtin_vp_vftoi(inParams[1] * __builtin_vp_makevectorf(65535.0)))
>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);
veci16 color = u ^ v;
outParams[0] = outParams[1] = outParams[2] = __builtin_vp_vitof(color);
outParams[3] = __builtin_vp_makevectorf(0.7f);
}
class TextureShader : public PixelShader
{
public:
TextureShader(ParameterInterpolator *interp, RenderTarget *target)
: PixelShader(interp, target)
{}
void bindTexture(Surface *surface)
{
fSampler.bind(surface);
}
virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask);
private:
TextureSampler fSampler;
};
void TextureShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask)
{
veci16 values = fSampler.readPixels(inParams[0], inParams[1]);
outParams[2] = __builtin_vp_vitof((values >> __builtin_vp_makevectori(16))
& __builtin_vp_makevectori(255)) / __builtin_vp_makevectorf(255.0f); // R
outParams[1] = __builtin_vp_vitof((values >> __builtin_vp_makevectori(8))
& __builtin_vp_makevectori(255)) / __builtin_vp_makevectorf(255.0f); // G
outParams[0] = __builtin_vp_vitof(values & __builtin_vp_makevectori(255))
/ __builtin_vp_makevectorf(255.0f); // B
outParams[3] = __builtin_vp_vitof((values >> __builtin_vp_makevectori(24))
& __builtin_vp_makevectori(255)) / __builtin_vp_makevectorf(255.0f); // A
}
const int kFbWidth = 640;
const int kFbHeight = 480;
// Hard-coded for now. This normally would be generated during the geometry phase...
Vertex gVertices[] = {
#if TEXTURE_SHADER
{ { 0.3, 0.1, 0.6 }, { 0.0, 0.0 } },
{ { 0.9, 0.5, 0.4 }, { 1.0, 0.0 } },
{ { 0.1, 0.9, 0.1 }, { 0.0, 1.0 } },
#elif COLOR_SHADER
{ { 0.3, 0.1, 0.6 }, { 1.0, 0.0, 0.0 } },
{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0, 0.0 } },
{ { 0.1, 0.9, 0.1 }, { 0.0, 0.0, 1.0 } },
{ { 0.3, 0.9, 0.3 }, { 1.0, 1.0, 0.0 } },
{ { 0.5, 0.1, 0.3 }, { 0.0, 1.0, 1.0 } },
{ { 0.8, 0.8, 0.3 }, { 1.0, 0.0, 1.0 } },
#else
{ { 0.3, 0.1, 0.6 }, { 0.0, 0.0 } },
{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0 } },
{ { 0.1, 0.9, 0.1 }, { 1.0, 1.0 } },
{ { 0.3, 0.9, 0.3 }, { 1.0, 1.0 } },
{ { 0.5, 0.1, 0.3 }, { 0.0, 1.0 } },
{ { 0.8, 0.8, 0.3 }, { 1.0, 0.0 } },
#endif
};
#if COLOR_SHADER
int gNumVertexParams = 3;
#else
int gNumVertexParams = 2;
#endif
#if TEXTURE_SHADER
int gNumVertices = 3;
#else
int gNumVertices = 6;
#endif
//
// All threads start execution here
//
int main()
{
Rasterizer rasterizer;
RenderTarget renderTarget;
Surface colorBuffer(0x100000, kFbWidth, kFbHeight);
Surface zBuffer(0x240000, kFbWidth, kFbHeight);
renderTarget.setColorBuffer(&colorBuffer);
renderTarget.setZBuffer(&zBuffer);
ParameterInterpolator interp(kFbWidth, kFbHeight);
#if TEXTURE_SHADER
Surface texture((unsigned int) kImage, 128, 128);
TextureShader shader(&interp, &renderTarget);
shader.bindTexture(&texture);
#elif COLOR_SHADER
ColorShader shader(&interp, &renderTarget);
#else
CheckerboardShader shader(&interp, &renderTarget);
#endif
shader.enableZBuffer(true);
// shader.enableBlend(true);
while (nextTileIndex < kMaxTileIndex)
{
// Grab the next available tile to begin working on.
int myTileIndex = __sync_fetch_and_add(&nextTileIndex, 1);
if (myTileIndex >= kMaxTileIndex)
break;
unsigned int tileXI, tileYI;
udiv(myTileIndex, 10, tileYI, tileXI);
int tileX = tileXI * 64;
int tileY = tileYI * 64;
#if ENABLE_CLEAR
renderTarget.getColorBuffer()->clearTile(tileX, tileY, 0);
#endif
if (shader.isZBufferEnabled())
renderTarget.getZBuffer()->clearTile(tileX, tileY, 0x40000000);
// Cycle through all triangles and attempt to render into this
// 64x64 tile.
for (int vidx = 0; vidx < gNumVertices; vidx += 3)
{
Vertex *vertex = &gVertices[vidx];
// XXX could do some trivial rejections here for triangles that
// obviously aren't in this tile.
interp.setUpTriangle(
vertex[0].coord[0], vertex[0].coord[1], vertex[0].coord[2],
vertex[1].coord[0], vertex[1].coord[1], vertex[1].coord[2],
vertex[2].coord[0], vertex[2].coord[1], vertex[2].coord[2]);
for (int param = 0; param < gNumVertexParams; param++)
{
interp.setUpParam(param, vertex[0].params[param],
vertex[1].params[param], vertex[2].params[param]);
}
rasterizer.rasterizeTriangle(&shader, tileX, tileY,
(int)(vertex[0].coord[0] * kFbWidth),
(int)(vertex[0].coord[1] * kFbHeight),
(int)(vertex[1].coord[0] * kFbWidth),
(int)(vertex[1].coord[1] * kFbHeight),
(int)(vertex[2].coord[0] * kFbWidth),
(int)(vertex[2].coord[1] * kFbHeight));
}
renderTarget.getColorBuffer()->flushTile(tileX, tileY);
}
#if COUNT_STATS
if (__builtin_vp_get_current_strand() == 0)
{
Debug::debug << renderTarget.getTotalPixels() << " total pixels\n";
Debug::debug << renderTarget.getTotalBlocks() << " total blocks\n";
}
#endif
return 0;
}
Debug Debug::debug;
<commit_msg>Fix up coordinates<commit_after>//
// Copyright 2013 Jeff Bush
//
// 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 "assert.h"
#include "Debug.h"
#include "RenderTarget.h"
#include "ParameterInterpolator.h"
#include "Rasterizer.h"
#include "PixelShader.h"
#include "TextureSampler.h"
#include "utils.h"
#define COLOR_SHADER 0
#define TEXTURE_SHADER 1
const int kMaxTileIndex = (640 / 64) * ((480 / 64) + 1);
int nextTileIndex = 0;
extern char *kImage;
struct Vertex
{
float coord[3];
float params[kMaxParams];
};
class ColorShader : public PixelShader
{
public:
ColorShader(ParameterInterpolator *interp, RenderTarget *target)
: PixelShader(interp, target)
{}
virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask);
};
void ColorShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short /* mask */)
{
for (int i = 0; i < 3; i++)
outParams[i] = inParams[i];
outParams[3] = __builtin_vp_makevectorf(0.7f);
}
class CheckerboardShader : public PixelShader
{
public:
CheckerboardShader(ParameterInterpolator *interp, RenderTarget *target)
: PixelShader(interp, target)
{}
virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask);
};
void CheckerboardShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short /* mask */)
{
veci16 u = ((__builtin_vp_vftoi(inParams[0] * __builtin_vp_makevectorf(65535.0)))
>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);
veci16 v = ((__builtin_vp_vftoi(inParams[1] * __builtin_vp_makevectorf(65535.0)))
>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);
veci16 color = u ^ v;
outParams[0] = outParams[1] = outParams[2] = __builtin_vp_vitof(color);
outParams[3] = __builtin_vp_makevectorf(0.7f);
}
class TextureShader : public PixelShader
{
public:
TextureShader(ParameterInterpolator *interp, RenderTarget *target)
: PixelShader(interp, target)
{}
void bindTexture(Surface *surface)
{
fSampler.bind(surface);
}
virtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask);
private:
TextureSampler fSampler;
};
void TextureShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],
unsigned short mask)
{
veci16 values = fSampler.readPixels(inParams[0], inParams[1]);
outParams[2] = __builtin_vp_vitof((values >> __builtin_vp_makevectori(16))
& __builtin_vp_makevectori(255)) / __builtin_vp_makevectorf(255.0f); // R
outParams[1] = __builtin_vp_vitof((values >> __builtin_vp_makevectori(8))
& __builtin_vp_makevectori(255)) / __builtin_vp_makevectorf(255.0f); // G
outParams[0] = __builtin_vp_vitof(values & __builtin_vp_makevectori(255))
/ __builtin_vp_makevectorf(255.0f); // B
outParams[3] = __builtin_vp_vitof((values >> __builtin_vp_makevectori(24))
& __builtin_vp_makevectori(255)) / __builtin_vp_makevectorf(255.0f); // A
}
const int kFbWidth = 640;
const int kFbHeight = 480;
// Hard-coded for now. This normally would be generated during the geometry phase...
Vertex gVertices[] = {
#if TEXTURE_SHADER
{ { 0.3, 0.1, 0.4 }, { 0.0, 0.0 } },
{ { 0.9, 0.5, 0.5 }, { 3.0, 0.0 } },
{ { 0.1, 0.9, 0.1 }, { 0.0, 3.0 } },
#elif COLOR_SHADER
{ { 0.3, 0.1, 0.6 }, { 1.0, 0.0, 0.0 } },
{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0, 0.0 } },
{ { 0.1, 0.9, 0.1 }, { 0.0, 0.0, 1.0 } },
{ { 0.3, 0.9, 0.3 }, { 1.0, 1.0, 0.0 } },
{ { 0.5, 0.1, 0.3 }, { 0.0, 1.0, 1.0 } },
{ { 0.8, 0.8, 0.3 }, { 1.0, 0.0, 1.0 } },
#else
{ { 0.3, 0.1, 0.6 }, { 0.0, 0.0 } },
{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0 } },
{ { 0.1, 0.9, 0.1 }, { 1.0, 1.0 } },
{ { 0.3, 0.9, 0.3 }, { 1.0, 1.0 } },
{ { 0.5, 0.1, 0.3 }, { 0.0, 1.0 } },
{ { 0.8, 0.8, 0.3 }, { 1.0, 0.0 } },
#endif
};
#if COLOR_SHADER
int gNumVertexParams = 3;
#else
int gNumVertexParams = 2;
#endif
#if TEXTURE_SHADER
int gNumVertices = 3;
#else
int gNumVertices = 6;
#endif
//
// All threads start execution here
//
int main()
{
Rasterizer rasterizer;
RenderTarget renderTarget;
Surface colorBuffer(0x100000, kFbWidth, kFbHeight);
Surface zBuffer(0x240000, kFbWidth, kFbHeight);
renderTarget.setColorBuffer(&colorBuffer);
renderTarget.setZBuffer(&zBuffer);
ParameterInterpolator interp(kFbWidth, kFbHeight);
#if TEXTURE_SHADER
Surface texture((unsigned int) kImage, 128, 128);
TextureShader shader(&interp, &renderTarget);
shader.bindTexture(&texture);
#elif COLOR_SHADER
ColorShader shader(&interp, &renderTarget);
#else
CheckerboardShader shader(&interp, &renderTarget);
#endif
shader.enableZBuffer(true);
// shader.enableBlend(true);
while (nextTileIndex < kMaxTileIndex)
{
// Grab the next available tile to begin working on.
int myTileIndex = __sync_fetch_and_add(&nextTileIndex, 1);
if (myTileIndex >= kMaxTileIndex)
break;
unsigned int tileXI, tileYI;
udiv(myTileIndex, 10, tileYI, tileXI);
int tileX = tileXI * 64;
int tileY = tileYI * 64;
#if ENABLE_CLEAR
renderTarget.getColorBuffer()->clearTile(tileX, tileY, 0);
#endif
if (shader.isZBufferEnabled())
renderTarget.getZBuffer()->clearTile(tileX, tileY, 0x40000000);
// Cycle through all triangles and attempt to render into this
// 64x64 tile.
for (int vidx = 0; vidx < gNumVertices; vidx += 3)
{
Vertex *vertex = &gVertices[vidx];
// XXX could do some trivial rejections here for triangles that
// obviously aren't in this tile.
interp.setUpTriangle(
vertex[0].coord[0], vertex[0].coord[1], vertex[0].coord[2],
vertex[1].coord[0], vertex[1].coord[1], vertex[1].coord[2],
vertex[2].coord[0], vertex[2].coord[1], vertex[2].coord[2]);
for (int param = 0; param < gNumVertexParams; param++)
{
interp.setUpParam(param, vertex[0].params[param],
vertex[1].params[param], vertex[2].params[param]);
}
rasterizer.rasterizeTriangle(&shader, tileX, tileY,
(int)(vertex[0].coord[0] * kFbWidth),
(int)(vertex[0].coord[1] * kFbHeight),
(int)(vertex[1].coord[0] * kFbWidth),
(int)(vertex[1].coord[1] * kFbHeight),
(int)(vertex[2].coord[0] * kFbWidth),
(int)(vertex[2].coord[1] * kFbHeight));
}
renderTarget.getColorBuffer()->flushTile(tileX, tileY);
}
#if COUNT_STATS
if (__builtin_vp_get_current_strand() == 0)
{
Debug::debug << renderTarget.getTotalPixels() << " total pixels\n";
Debug::debug << renderTarget.getTotalBlocks() << " total blocks\n";
}
#endif
return 0;
}
Debug Debug::debug;
<|endoftext|> |
<commit_before>/**
* @file libadopter.hpp
* @brief internal standard library adopter(loader)
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 8. 19
* @details COSSB library adopter
*/
#ifndef _COSSB_LIBADOPTER_HPP_
#define _COSSB_LIBADOPTER_HPP_
#include <dlfcn.h>
#include <string>
#include "util/format.h"
using namespace std;
namespace cossb {
namespace base {
template<class T>
class libadopter {
public:
libadopter(const char* solib):_so(solib) {
string libpath = fmt::format(".{}",_so);
_handle = dlopen(libpath.c_str(), RTLD_NOW|RTLD_GLOBAL);
}
virtual ~libadopter() {
if(_handle) {
dlclose(_handle);
_handle = nullptr;
}
}
private:
void* _handle = nullptr;
string _so;
};
} /* namespace base */
} /* namespace cossb */
#endif /* _COSSB_LIBADOPTER_HPP_ */
<commit_msg>edit constructor and deconstructor to create and destroy local instance<commit_after>/**
* @file libadopter.hpp
* @brief internal standard library adopter(loader)
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 8. 19
* @details COSSB library adopter
*/
#ifndef _COSSB_LIBADOPTER_HPP_
#define _COSSB_LIBADOPTER_HPP_
#include <dlfcn.h>
#include <string>
#include "util/format.h"
using namespace std;
namespace cossb {
namespace base {
template<class T>
class libadopter {
public:
libadopter(const char* solib):_so(solib) {
string libpath = fmt::format("./{}",_so);
_handle = dlopen(libpath.c_str(), RTLD_NOW|RTLD_GLOBAL);
if(_handle) {
typedef T* create_t(void);
create_t* pfcreate = (create_t*)dlsym(_handle, "create");
if(pfcreate)
_lib = pfcreate();
}
}
virtual ~libadopter() {
if(_lib) {
typedef void(destroy_t)(T* arg);
destroy_t* pfdestroy = (destroy_t*)dlsym(_handle, "destroy");
if(pfdestroy)
pfdestroy(_lib);
_lib = nullptr;
}
if(_handle) {
dlclose(_handle);
_handle = nullptr;
}
}
T* get_lib() { return _lib; }
private:
void* _handle = nullptr;
string _so;
T* _lib = nullptr;
};
} /* namespace base */
} /* namespace cossb */
#endif /* _COSSB_LIBADOPTER_HPP_ */
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/mac/aggregate_device_manager.h"
#include <CoreAudio/AudioHardware.h>
#include <string>
#include "base/mac/mac_logging.h"
#include "base/mac/scoped_cftyperef.h"
#include "media/audio/audio_parameters.h"
#include "media/audio/mac/audio_manager_mac.h"
using base::mac::ScopedCFTypeRef;
namespace media {
AggregateDeviceManager::AggregateDeviceManager()
: plugin_id_(kAudioObjectUnknown),
input_device_(kAudioDeviceUnknown),
output_device_(kAudioDeviceUnknown),
aggregate_device_(kAudioObjectUnknown) {
}
AggregateDeviceManager::~AggregateDeviceManager() {
DestroyAggregateDevice();
}
AudioDeviceID AggregateDeviceManager::GetDefaultAggregateDevice() {
// Use a lazily created aggregate device if it's already available
// and still appropriate.
if (aggregate_device_ != kAudioObjectUnknown) {
// TODO(crogers): handle default device changes for synchronized I/O.
// For now, we check to make sure the default devices haven't changed
// since we lazily created the aggregate device.
AudioDeviceID current_input_device;
AudioDeviceID current_output_device;
AudioManagerMac::GetDefaultInputDevice(¤t_input_device);
AudioManagerMac::GetDefaultOutputDevice(¤t_output_device);
if (current_input_device == input_device_ &&
current_output_device == output_device_)
return aggregate_device_;
// For now, once lazily created don't attempt to create another
// aggregate device.
return kAudioDeviceUnknown;
}
AudioManagerMac::GetDefaultInputDevice(&input_device_);
AudioManagerMac::GetDefaultOutputDevice(&output_device_);
// Only create an aggregrate device if the clock domains match.
UInt32 input_clockdomain = GetClockDomain(input_device_);
UInt32 output_clockdomain = GetClockDomain(output_device_);
DVLOG(1) << "input_clockdomain: " << input_clockdomain;
DVLOG(1) << "output_clockdomain: " << output_clockdomain;
if (input_clockdomain == 0 || input_clockdomain != output_clockdomain)
return kAudioDeviceUnknown;
OSStatus result = CreateAggregateDevice(
input_device_,
output_device_,
&aggregate_device_);
if (result != noErr)
DestroyAggregateDevice();
return aggregate_device_;
}
CFStringRef AggregateDeviceManager::GetDeviceUID(AudioDeviceID id) {
static const AudioObjectPropertyAddress kDeviceUIDAddress = {
kAudioDevicePropertyDeviceUID,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
// As stated in the CoreAudio header (AudioHardwareBase.h),
// the caller is responsible for releasing the device_UID.
CFStringRef device_UID;
UInt32 size = sizeof(device_UID);
OSStatus result = AudioObjectGetPropertyData(
id,
&kDeviceUIDAddress,
0,
0,
&size,
&device_UID);
return (result == noErr) ? device_UID : NULL;
}
void AggregateDeviceManager::GetDeviceName(
AudioDeviceID id, char* name, UInt32 size) {
static const AudioObjectPropertyAddress kDeviceNameAddress = {
kAudioDevicePropertyDeviceName,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(
id,
&kDeviceNameAddress,
0,
0,
&size,
name);
if (result != noErr && size > 0)
name[0] = 0;
}
UInt32 AggregateDeviceManager::GetClockDomain(AudioDeviceID device_id) {
static const AudioObjectPropertyAddress kClockDomainAddress = {
kAudioDevicePropertyClockDomain,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 clockdomain = 0;
UInt32 size = sizeof(UInt32);
OSStatus result = AudioObjectGetPropertyData(
device_id,
&kClockDomainAddress,
0,
0,
&size,
&clockdomain);
return (result == noErr) ? clockdomain : 0;
}
OSStatus AggregateDeviceManager::GetPluginID(AudioObjectID* id) {
DCHECK(id);
// Get the audio hardware plugin.
CFStringRef bundle_name = CFSTR("com.apple.audio.CoreAudio");
AudioValueTranslation plugin_translation;
plugin_translation.mInputData = &bundle_name;
plugin_translation.mInputDataSize = sizeof(bundle_name);
plugin_translation.mOutputData = id;
plugin_translation.mOutputDataSize = sizeof(*id);
static const AudioObjectPropertyAddress kPlugInAddress = {
kAudioHardwarePropertyPlugInForBundleID,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 size = sizeof(plugin_translation);
OSStatus result = AudioObjectGetPropertyData(
kAudioObjectSystemObject,
&kPlugInAddress,
0,
0,
&size,
&plugin_translation);
DVLOG(1) << "CoreAudio plugin ID: " << *id;
return result;
}
CFMutableDictionaryRef
AggregateDeviceManager::CreateAggregateDeviceDictionary(
AudioDeviceID input_id,
AudioDeviceID output_id) {
CFMutableDictionaryRef aggregate_device_dict = CFDictionaryCreateMutable(
NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (!aggregate_device_dict)
return NULL;
const CFStringRef kAggregateDeviceName =
CFSTR("ChromeAggregateAudioDevice");
const CFStringRef kAggregateDeviceUID =
CFSTR("com.google.chrome.AggregateAudioDevice");
// Add name and UID of the device to the dictionary.
CFDictionaryAddValue(
aggregate_device_dict,
CFSTR(kAudioAggregateDeviceNameKey),
kAggregateDeviceName);
CFDictionaryAddValue(
aggregate_device_dict,
CFSTR(kAudioAggregateDeviceUIDKey),
kAggregateDeviceUID);
// Add a "private aggregate key" to the dictionary.
// The 1 value means that the created aggregate device will
// only be accessible from the process that created it, and
// won't be visible to outside processes.
int value = 1;
ScopedCFTypeRef<CFNumberRef> aggregate_device_number(CFNumberCreate(
NULL,
kCFNumberIntType,
&value));
CFDictionaryAddValue(
aggregate_device_dict,
CFSTR(kAudioAggregateDeviceIsPrivateKey),
aggregate_device_number);
return aggregate_device_dict;
}
CFMutableArrayRef
AggregateDeviceManager::CreateSubDeviceArray(
CFStringRef input_device_UID, CFStringRef output_device_UID) {
CFMutableArrayRef sub_devices_array = CFArrayCreateMutable(
NULL,
0,
&kCFTypeArrayCallBacks);
CFArrayAppendValue(sub_devices_array, input_device_UID);
CFArrayAppendValue(sub_devices_array, output_device_UID);
return sub_devices_array;
}
OSStatus AggregateDeviceManager::CreateAggregateDevice(
AudioDeviceID input_id,
AudioDeviceID output_id,
AudioDeviceID* aggregate_device) {
DCHECK(aggregate_device);
const size_t kMaxDeviceNameLength = 256;
scoped_ptr<char[]> input_device_name(new char[kMaxDeviceNameLength]);
GetDeviceName(
input_id,
input_device_name.get(),
sizeof(input_device_name));
DVLOG(1) << "Input device: \n" << input_device_name;
scoped_ptr<char[]> output_device_name(new char[kMaxDeviceNameLength]);
GetDeviceName(
output_id,
output_device_name.get(),
sizeof(output_device_name));
DVLOG(1) << "Output device: \n" << output_device_name;
OSStatus result = GetPluginID(&plugin_id_);
if (result != noErr)
return result;
// Create a dictionary for the aggregate device.
ScopedCFTypeRef<CFMutableDictionaryRef> aggregate_device_dict(
CreateAggregateDeviceDictionary(input_id, output_id));
if (!aggregate_device_dict)
return -1;
// Create the aggregate device.
static const AudioObjectPropertyAddress kCreateAggregateDeviceAddress = {
kAudioPlugInCreateAggregateDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 size = sizeof(*aggregate_device);
result = AudioObjectGetPropertyData(
plugin_id_,
&kCreateAggregateDeviceAddress,
sizeof(aggregate_device_dict),
&aggregate_device_dict,
&size,
aggregate_device);
if (result != noErr) {
DLOG(ERROR) << "Error creating aggregate audio device!";
return result;
}
// Set the sub-devices for the aggregate device.
// In this case we use two: the input and output devices.
ScopedCFTypeRef<CFStringRef> input_device_UID(GetDeviceUID(input_id));
ScopedCFTypeRef<CFStringRef> output_device_UID(GetDeviceUID(output_id));
if (!input_device_UID || !output_device_UID) {
DLOG(ERROR) << "Error getting audio device UID strings.";
return -1;
}
ScopedCFTypeRef<CFMutableArrayRef> sub_devices_array(
CreateSubDeviceArray(input_device_UID, output_device_UID));
if (sub_devices_array == NULL) {
DLOG(ERROR) << "Error creating sub-devices array.";
return -1;
}
static const AudioObjectPropertyAddress kSetSubDevicesAddress = {
kAudioAggregateDevicePropertyFullSubDeviceList,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
size = sizeof(CFMutableArrayRef);
result = AudioObjectSetPropertyData(
*aggregate_device,
&kSetSubDevicesAddress,
0,
NULL,
size,
&sub_devices_array);
if (result != noErr) {
DLOG(ERROR) << "Error setting aggregate audio device sub-devices!";
return result;
}
// Use the input device as the master device.
static const AudioObjectPropertyAddress kSetMasterDeviceAddress = {
kAudioAggregateDevicePropertyMasterSubDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
size = sizeof(CFStringRef);
result = AudioObjectSetPropertyData(
*aggregate_device,
&kSetMasterDeviceAddress,
0,
NULL,
size,
&input_device_UID);
if (result != noErr) {
DLOG(ERROR) << "Error setting aggregate audio device master device!";
return result;
}
DVLOG(1) << "New aggregate device: " << *aggregate_device;
return noErr;
}
void AggregateDeviceManager::DestroyAggregateDevice() {
if (aggregate_device_ == kAudioObjectUnknown)
return;
static const AudioObjectPropertyAddress kDestroyAddress = {
kAudioPlugInDestroyAggregateDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 size = sizeof(aggregate_device_);
OSStatus result = AudioObjectGetPropertyData(
plugin_id_,
&kDestroyAddress,
0,
NULL,
&size,
&aggregate_device_);
if (result != noErr) {
DLOG(ERROR) << "Error destroying aggregate audio device!";
return;
}
aggregate_device_ = kAudioObjectUnknown;
}
} // namespace media
<commit_msg>Make sure not to use aggregate devices if sample-rates of input and output devices don't match<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/mac/aggregate_device_manager.h"
#include <CoreAudio/AudioHardware.h>
#include <string>
#include "base/mac/mac_logging.h"
#include "base/mac/scoped_cftyperef.h"
#include "media/audio/audio_parameters.h"
#include "media/audio/mac/audio_manager_mac.h"
using base::mac::ScopedCFTypeRef;
namespace media {
AggregateDeviceManager::AggregateDeviceManager()
: plugin_id_(kAudioObjectUnknown),
input_device_(kAudioDeviceUnknown),
output_device_(kAudioDeviceUnknown),
aggregate_device_(kAudioObjectUnknown) {
}
AggregateDeviceManager::~AggregateDeviceManager() {
DestroyAggregateDevice();
}
AudioDeviceID AggregateDeviceManager::GetDefaultAggregateDevice() {
AudioDeviceID current_input_device;
AudioDeviceID current_output_device;
AudioManagerMac::GetDefaultInputDevice(¤t_input_device);
AudioManagerMac::GetDefaultOutputDevice(¤t_output_device);
if (AudioManagerMac::HardwareSampleRateForDevice(current_input_device) !=
AudioManagerMac::HardwareSampleRateForDevice(current_output_device)) {
// TODO(crogers): with some extra work we can make aggregate devices work
// if the clock domain is the same but the sample-rate differ.
// For now we fallback to the synchronized path.
return kAudioDeviceUnknown;
}
// Use a lazily created aggregate device if it's already available
// and still appropriate.
if (aggregate_device_ != kAudioObjectUnknown) {
// TODO(crogers): handle default device changes for synchronized I/O.
// For now, we check to make sure the default devices haven't changed
// since we lazily created the aggregate device.
if (current_input_device == input_device_ &&
current_output_device == output_device_)
return aggregate_device_;
// For now, once lazily created don't attempt to create another
// aggregate device.
return kAudioDeviceUnknown;
}
input_device_ = current_input_device;
output_device_ = current_output_device;
// Only create an aggregrate device if the clock domains match.
UInt32 input_clockdomain = GetClockDomain(input_device_);
UInt32 output_clockdomain = GetClockDomain(output_device_);
DVLOG(1) << "input_clockdomain: " << input_clockdomain;
DVLOG(1) << "output_clockdomain: " << output_clockdomain;
if (input_clockdomain == 0 || input_clockdomain != output_clockdomain)
return kAudioDeviceUnknown;
OSStatus result = CreateAggregateDevice(
input_device_,
output_device_,
&aggregate_device_);
if (result != noErr)
DestroyAggregateDevice();
return aggregate_device_;
}
CFStringRef AggregateDeviceManager::GetDeviceUID(AudioDeviceID id) {
static const AudioObjectPropertyAddress kDeviceUIDAddress = {
kAudioDevicePropertyDeviceUID,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
// As stated in the CoreAudio header (AudioHardwareBase.h),
// the caller is responsible for releasing the device_UID.
CFStringRef device_UID;
UInt32 size = sizeof(device_UID);
OSStatus result = AudioObjectGetPropertyData(
id,
&kDeviceUIDAddress,
0,
0,
&size,
&device_UID);
return (result == noErr) ? device_UID : NULL;
}
void AggregateDeviceManager::GetDeviceName(
AudioDeviceID id, char* name, UInt32 size) {
static const AudioObjectPropertyAddress kDeviceNameAddress = {
kAudioDevicePropertyDeviceName,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(
id,
&kDeviceNameAddress,
0,
0,
&size,
name);
if (result != noErr && size > 0)
name[0] = 0;
}
UInt32 AggregateDeviceManager::GetClockDomain(AudioDeviceID device_id) {
static const AudioObjectPropertyAddress kClockDomainAddress = {
kAudioDevicePropertyClockDomain,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 clockdomain = 0;
UInt32 size = sizeof(UInt32);
OSStatus result = AudioObjectGetPropertyData(
device_id,
&kClockDomainAddress,
0,
0,
&size,
&clockdomain);
return (result == noErr) ? clockdomain : 0;
}
OSStatus AggregateDeviceManager::GetPluginID(AudioObjectID* id) {
DCHECK(id);
// Get the audio hardware plugin.
CFStringRef bundle_name = CFSTR("com.apple.audio.CoreAudio");
AudioValueTranslation plugin_translation;
plugin_translation.mInputData = &bundle_name;
plugin_translation.mInputDataSize = sizeof(bundle_name);
plugin_translation.mOutputData = id;
plugin_translation.mOutputDataSize = sizeof(*id);
static const AudioObjectPropertyAddress kPlugInAddress = {
kAudioHardwarePropertyPlugInForBundleID,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 size = sizeof(plugin_translation);
OSStatus result = AudioObjectGetPropertyData(
kAudioObjectSystemObject,
&kPlugInAddress,
0,
0,
&size,
&plugin_translation);
DVLOG(1) << "CoreAudio plugin ID: " << *id;
return result;
}
CFMutableDictionaryRef
AggregateDeviceManager::CreateAggregateDeviceDictionary(
AudioDeviceID input_id,
AudioDeviceID output_id) {
CFMutableDictionaryRef aggregate_device_dict = CFDictionaryCreateMutable(
NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (!aggregate_device_dict)
return NULL;
const CFStringRef kAggregateDeviceName =
CFSTR("ChromeAggregateAudioDevice");
const CFStringRef kAggregateDeviceUID =
CFSTR("com.google.chrome.AggregateAudioDevice");
// Add name and UID of the device to the dictionary.
CFDictionaryAddValue(
aggregate_device_dict,
CFSTR(kAudioAggregateDeviceNameKey),
kAggregateDeviceName);
CFDictionaryAddValue(
aggregate_device_dict,
CFSTR(kAudioAggregateDeviceUIDKey),
kAggregateDeviceUID);
// Add a "private aggregate key" to the dictionary.
// The 1 value means that the created aggregate device will
// only be accessible from the process that created it, and
// won't be visible to outside processes.
int value = 1;
ScopedCFTypeRef<CFNumberRef> aggregate_device_number(CFNumberCreate(
NULL,
kCFNumberIntType,
&value));
CFDictionaryAddValue(
aggregate_device_dict,
CFSTR(kAudioAggregateDeviceIsPrivateKey),
aggregate_device_number);
return aggregate_device_dict;
}
CFMutableArrayRef
AggregateDeviceManager::CreateSubDeviceArray(
CFStringRef input_device_UID, CFStringRef output_device_UID) {
CFMutableArrayRef sub_devices_array = CFArrayCreateMutable(
NULL,
0,
&kCFTypeArrayCallBacks);
CFArrayAppendValue(sub_devices_array, input_device_UID);
CFArrayAppendValue(sub_devices_array, output_device_UID);
return sub_devices_array;
}
OSStatus AggregateDeviceManager::CreateAggregateDevice(
AudioDeviceID input_id,
AudioDeviceID output_id,
AudioDeviceID* aggregate_device) {
DCHECK(aggregate_device);
const size_t kMaxDeviceNameLength = 256;
scoped_ptr<char[]> input_device_name(new char[kMaxDeviceNameLength]);
GetDeviceName(
input_id,
input_device_name.get(),
sizeof(input_device_name));
DVLOG(1) << "Input device: \n" << input_device_name;
scoped_ptr<char[]> output_device_name(new char[kMaxDeviceNameLength]);
GetDeviceName(
output_id,
output_device_name.get(),
sizeof(output_device_name));
DVLOG(1) << "Output device: \n" << output_device_name;
OSStatus result = GetPluginID(&plugin_id_);
if (result != noErr)
return result;
// Create a dictionary for the aggregate device.
ScopedCFTypeRef<CFMutableDictionaryRef> aggregate_device_dict(
CreateAggregateDeviceDictionary(input_id, output_id));
if (!aggregate_device_dict)
return -1;
// Create the aggregate device.
static const AudioObjectPropertyAddress kCreateAggregateDeviceAddress = {
kAudioPlugInCreateAggregateDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 size = sizeof(*aggregate_device);
result = AudioObjectGetPropertyData(
plugin_id_,
&kCreateAggregateDeviceAddress,
sizeof(aggregate_device_dict),
&aggregate_device_dict,
&size,
aggregate_device);
if (result != noErr) {
DLOG(ERROR) << "Error creating aggregate audio device!";
return result;
}
// Set the sub-devices for the aggregate device.
// In this case we use two: the input and output devices.
ScopedCFTypeRef<CFStringRef> input_device_UID(GetDeviceUID(input_id));
ScopedCFTypeRef<CFStringRef> output_device_UID(GetDeviceUID(output_id));
if (!input_device_UID || !output_device_UID) {
DLOG(ERROR) << "Error getting audio device UID strings.";
return -1;
}
ScopedCFTypeRef<CFMutableArrayRef> sub_devices_array(
CreateSubDeviceArray(input_device_UID, output_device_UID));
if (sub_devices_array == NULL) {
DLOG(ERROR) << "Error creating sub-devices array.";
return -1;
}
static const AudioObjectPropertyAddress kSetSubDevicesAddress = {
kAudioAggregateDevicePropertyFullSubDeviceList,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
size = sizeof(CFMutableArrayRef);
result = AudioObjectSetPropertyData(
*aggregate_device,
&kSetSubDevicesAddress,
0,
NULL,
size,
&sub_devices_array);
if (result != noErr) {
DLOG(ERROR) << "Error setting aggregate audio device sub-devices!";
return result;
}
// Use the input device as the master device.
static const AudioObjectPropertyAddress kSetMasterDeviceAddress = {
kAudioAggregateDevicePropertyMasterSubDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
size = sizeof(CFStringRef);
result = AudioObjectSetPropertyData(
*aggregate_device,
&kSetMasterDeviceAddress,
0,
NULL,
size,
&input_device_UID);
if (result != noErr) {
DLOG(ERROR) << "Error setting aggregate audio device master device!";
return result;
}
DVLOG(1) << "New aggregate device: " << *aggregate_device;
return noErr;
}
void AggregateDeviceManager::DestroyAggregateDevice() {
if (aggregate_device_ == kAudioObjectUnknown)
return;
static const AudioObjectPropertyAddress kDestroyAddress = {
kAudioPlugInDestroyAggregateDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
UInt32 size = sizeof(aggregate_device_);
OSStatus result = AudioObjectGetPropertyData(
plugin_id_,
&kDestroyAddress,
0,
NULL,
&size,
&aggregate_device_);
if (result != noErr) {
DLOG(ERROR) << "Error destroying aggregate audio device!";
return;
}
aggregate_device_ = kAudioObjectUnknown;
}
} // namespace media
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include <lxqt/lxqtapplication.h>
#include <qtxdg/xdgicon.h>
#include <lxqt/lxqtsettings.h>
#include <lxqt/lxqtconfigdialog.h>
#include "iconthemeconfig.h"
#include "razortranslate.h"
#include "lxqtthemeconfig.h"
int main (int argc, char **argv)
{
LxQt::Application app(argc, argv);
TRANSLATE_APP;
LxQt::Settings* settings = new LxQt::Settings("razor");
LxQt::ConfigDialog* dialog = new LxQt::ConfigDialog(QObject::tr("Razor Appearance Configuration"), settings);
IconThemeConfig* iconPage = new IconThemeConfig(settings);
dialog->addPage(iconPage, QObject::tr("Icons Theme"), QStringList() << "preferences-desktop-icons" << "preferences-desktop");
QObject::connect(dialog, SIGNAL(reset()), iconPage, SLOT(initControls()));
RazorThemeConfig* themePage = new RazorThemeConfig(settings);
dialog->addPage(themePage, QObject::tr("Razor Theme"), QStringList() << "preferences-desktop-color" << "preferences-desktop");
QObject::connect(dialog, SIGNAL(reset()), themePage, SLOT(initControls()));
dialog->show();
return app.exec();
}
<commit_msg>Fix wrong config name.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include <lxqt/lxqtapplication.h>
#include <qtxdg/xdgicon.h>
#include <lxqt/lxqtsettings.h>
#include <lxqt/lxqtconfigdialog.h>
#include "iconthemeconfig.h"
#include "razortranslate.h"
#include "lxqtthemeconfig.h"
int main (int argc, char **argv)
{
LxQt::Application app(argc, argv);
TRANSLATE_APP;
LxQt::Settings* settings = new LxQt::Settings("lxqt");
LxQt::ConfigDialog* dialog = new LxQt::ConfigDialog(QObject::tr("Razor Appearance Configuration"), settings);
IconThemeConfig* iconPage = new IconThemeConfig(settings);
dialog->addPage(iconPage, QObject::tr("Icons Theme"), QStringList() << "preferences-desktop-icons" << "preferences-desktop");
QObject::connect(dialog, SIGNAL(reset()), iconPage, SLOT(initControls()));
RazorThemeConfig* themePage = new RazorThemeConfig(settings);
dialog->addPage(themePage, QObject::tr("Razor Theme"), QStringList() << "preferences-desktop-color" << "preferences-desktop");
QObject::connect(dialog, SIGNAL(reset()), themePage, SLOT(initControls()));
dialog->show();
return app.exec();
}
<|endoftext|> |
<commit_before>#include "player.hpp"
#include "lvl.hpp"
#include "../visnav/visgraph.hpp"
#include <vector>
#include <string>
#include <cstdio>
void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);
// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);
// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
// Maxx is the maximum travel distance in the x-direction
// in a single frame.
static const double Maxx = Runspeed;
// Maxy is the maximum travel distance in the y-direction
// in a single frame.
static const double Maxy = Jmpspeed > Body::Maxdy ? Jmpspeed : Body::Maxdy;
// W is the minimum width of a tile in 'frames'. I.e., at max
// speed how many frames does it require to traverse the
// width of a tile.
static const double W = Tile::Width / Maxx;
// H is the minimum height of a tile in 'frames'.
static const double H = Tile::Height / Maxy;
struct Plat2d {
typedef double Cost;
typedef int Oper;
enum { Nop = -1 };
Plat2d(FILE*);
~Plat2d();
struct State {
State() : h(-1) { }
State(unsigned int x, unsigned int y, unsigned int z,
unsigned int w, unsigned int h) : player(x, y, w, h), h(-1) { }
static const int K = 3;
void vector(const Plat2d *d, double vec[]) const {
auto p = player.body.bbox.center();
p.y = d->maxy - p.y;
p.scale(1.0/d->maxx, 1.0/d->maxy);
vec[0] = p.x;
vec[1] = p.y;
vec[2] = (player.body.dy+Body::Maxdy)/(2*Body::Maxdy);
}
Player player;
Cost h;
};
struct PackedState {
bool eq(const Plat2d*, const PackedState &o) const {
return jframes == o.jframes &&
geom2d::doubleeq(x, o.x) &&
geom2d::doubleeq(y, o.y) &&
geom2d::doubleeq(dy, o.dy);
}
unsigned long hash(const Plat2d*) {
static const unsigned int sz = sizeof(x) +
sizeof(y) + sizeof(dy) + sizeof(jframes);
unsigned char bytes[sz];
unsigned int i = 0;
char *p = (char*) &x;
for (unsigned int j = 0; j < sizeof(x); j++)
bytes[i++] = p[j];
p = (char*) &y;
for (unsigned int j = 0; j < sizeof(y); j++)
bytes[i++] = p[j];
p = (char*) &dy;
for (unsigned int j = 0; j < sizeof(dy); j++)
bytes[i++] = p[j];
bytes[i++] = jframes;
assert (i <= sz);
return hashbytes(bytes, i);
}
double x, y, dy;
// The body's fall flag is packed as the high-order bit
// of jframes.
unsigned char jframes;
};
State initialstate();
Cost h(State &s) {
if (s.h < 0)
s.h = hvis(s);
return s.h;
}
Cost d(State &s) {
return h(s);
}
bool isgoal(State &s) {
Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
return bi.x == gx && bi.y == gy;
}
struct Operators {
Operators(const Plat2d&, const State &s) : n(Nops) {
// If jumping will have no effect then allow left, right and jump.
// This is a bit of a hack, but the 'jump' action that is allowed
// here will end up being a 'do nothing' and just fall action.
// Effectively, we prune off the jump/left and jump/right actions
// since they are the same as just doing left and right in this case.
if (!s.player.canjump())
n = 3;
}
unsigned int size() const {
return n;
}
Oper operator[](unsigned int i) const {
return Ops[i];
}
private:
unsigned int n;
static const unsigned int Ops[];
static const unsigned int Nops;
};
struct Edge {
Cost cost;
Oper revop;
Cost revcost;
State state;
Edge(Plat2d &d, State &s, Oper op) : revop(Nop), revcost(-1), state(s) {
state.h = -1;
state.player.act(d.lvl, (unsigned int) op);
cost = 1; // geom2d::Pt::distance(s.player.body.bbox.min, state.player.body.bbox.min));
if (s.player.body.bbox.min.y == state.player.body.bbox.min.y) {
if (op == Player::Left) {
revop = Player::Right;
revcost = cost;
}
else if (op == Player::Right) {
revop = Player::Left;
revcost = cost;
}
}
double dy = fabs(s.player.body.bbox.center().y - state.player.body.bbox.center().y);
double dx = fabs(s.player.body.bbox.center().x - state.player.body.bbox.center().x);
assert (dx <= Maxx);
assert (dy <= Maxy);
}
};
void pack(PackedState &dst, State &src) {
dst.x = src.player.body.bbox.min.x;
dst.y = src.player.body.bbox.min.y;
dst.dy = src.player.body.dy;
dst.jframes = src.player.jframes;
if (src.player.body.fall)
dst.jframes |= 1 << 7;
}
State &unpack(State &buf, PackedState &pkd) {
buf.player.jframes = pkd.jframes & 0x7F;
buf.player.body.fall = pkd.jframes & (1 << 7);
buf.player.body.dy = pkd.dy;
buf.player.body.bbox.min.x = pkd.x;
buf.player.body.bbox.min.y = pkd.y;
buf.player.body.bbox.max.x = pkd.x + Player::Width;
buf.player.body.bbox.max.y = pkd.y + Player::Height;
return buf;
}
static void dumpstate(FILE *out, State &s) {
fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
}
Cost pathcost(const std::vector<State>&, const std::vector<Oper>&);
// Drawmap returns an image of the map.
Image *drawmap() const;
unsigned int gx, gy; // goal tile location
unsigned int x0, y0; // initial location
Lvl lvl;
private:
struct Node {
int v; // vertex ID
int prev; // previous along path
long i; // prio queue index
double d; // distance to goal
static void setind(Node *n, unsigned long ind) { n->i = ind; }
static bool pred(const Node *a, const Node *b) { return a->d < b->d; }
};
void initvg();
double hvis(State &s) const {
const Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);
if (bi.x == gx && bi.y == gy)
return 0;
geom2d::Pt loc(s.player.body.bbox.center());
loc.x /= Maxx; // Pixel to squished vismap coords.
loc.y /= Maxy;
int c = centers[bi.x * lvl.height() + bi.y];
geom2d::Pt g = goalpt(bi, loc);
if (togoal[c].prev == gcenter || vg->map.isvisible(loc, g)) {
double dx = fabs(g.x - loc.x);
double dy = fabs(g.y - loc.y);
double h = floor(std::max(dx, dy));
return h <= 0 ? 1 : h;
}
// Account for goal vertex being at its tile center.
static const double diag = std::max(W/2, H/2);
// Account for distance from player to center of tile.
double middx = fabs(loc.x - vg->verts[c].pt.x);
double middy = fabs(loc.y - vg->verts[c].pt.y);
double tomid = std::max(middx, middy);
double h = togoal[c].d - tomid - diag;
if (h <= 0)
h = 1;
h = floor(h);
if (h <= 0)
h = 1;
return h;
}
// goalpt returns a point in the goal cell that is closest
// to the given location.
geom2d::Pt goalpt(const Lvl::Blkinfo &bi, const geom2d::Pt &loc) const {
geom2d::Pt pt;
if (bi.y == gy)
pt.y = loc.y;
else if (bi.y < gy)
pt.y = gtop;
else
pt.y = gbottom;
if (bi.x == gx)
pt.x = loc.x;
else if (bi.x < gx)
pt.x = gleft;
else
pt.x = gright;
return pt;
}
// savemap draws the visibility map used for the heuristic
// to the given file.;
void savemap(const char*) const;
VisGraph *vg;
std::vector<long> centers;
std::vector<Node> togoal;
int gcenter; // vertex ID of the goal center
double gleft, gright, gtop, gbottom;
double maxx, maxy; // width and height in pixels.
};
<commit_msg>plat2d: costs are ints…<commit_after>#include "player.hpp"
#include "lvl.hpp"
#include "../visnav/visgraph.hpp"
#include <vector>
#include <string>
#include <cstdio>
void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);
// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);
// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
// Maxx is the maximum travel distance in the x-direction
// in a single frame.
static const double Maxx = Runspeed;
// Maxy is the maximum travel distance in the y-direction
// in a single frame.
static const double Maxy = Jmpspeed > Body::Maxdy ? Jmpspeed : Body::Maxdy;
// W is the minimum width of a tile in 'frames'. I.e., at max
// speed how many frames does it require to traverse the
// width of a tile.
static const double W = Tile::Width / Maxx;
// H is the minimum height of a tile in 'frames'.
static const double H = Tile::Height / Maxy;
struct Plat2d {
typedef int Cost;
typedef int Oper;
enum { Nop = -1 };
Plat2d(FILE*);
~Plat2d();
struct State {
State() : h(-1) { }
State(unsigned int x, unsigned int y, unsigned int z,
unsigned int w, unsigned int h) : player(x, y, w, h), h(-1) { }
static const int K = 3;
void vector(const Plat2d *d, double vec[]) const {
auto p = player.body.bbox.center();
p.y = d->maxy - p.y;
p.scale(1.0/d->maxx, 1.0/d->maxy);
vec[0] = p.x;
vec[1] = p.y;
vec[2] = (player.body.dy+Body::Maxdy)/(2*Body::Maxdy);
}
Player player;
Cost h;
};
struct PackedState {
bool eq(const Plat2d*, const PackedState &o) const {
return jframes == o.jframes &&
geom2d::doubleeq(x, o.x) &&
geom2d::doubleeq(y, o.y) &&
geom2d::doubleeq(dy, o.dy);
}
unsigned long hash(const Plat2d*) {
static const unsigned int sz = sizeof(x) +
sizeof(y) + sizeof(dy) + sizeof(jframes);
unsigned char bytes[sz];
unsigned int i = 0;
char *p = (char*) &x;
for (unsigned int j = 0; j < sizeof(x); j++)
bytes[i++] = p[j];
p = (char*) &y;
for (unsigned int j = 0; j < sizeof(y); j++)
bytes[i++] = p[j];
p = (char*) &dy;
for (unsigned int j = 0; j < sizeof(dy); j++)
bytes[i++] = p[j];
bytes[i++] = jframes;
assert (i <= sz);
return hashbytes(bytes, i);
}
double x, y, dy;
// The body's fall flag is packed as the high-order bit
// of jframes.
unsigned char jframes;
};
State initialstate();
Cost h(State &s) {
if (s.h < 0)
s.h = hvis(s);
return s.h;
}
Cost d(State &s) {
return h(s);
}
bool isgoal(State &s) {
Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
return bi.x == gx && bi.y == gy;
}
struct Operators {
Operators(const Plat2d&, const State &s) : n(Nops) {
// If jumping will have no effect then allow left, right and jump.
// This is a bit of a hack, but the 'jump' action that is allowed
// here will end up being a 'do nothing' and just fall action.
// Effectively, we prune off the jump/left and jump/right actions
// since they are the same as just doing left and right in this case.
if (!s.player.canjump())
n = 3;
}
unsigned int size() const {
return n;
}
Oper operator[](unsigned int i) const {
return Ops[i];
}
private:
unsigned int n;
static const unsigned int Ops[];
static const unsigned int Nops;
};
struct Edge {
Cost cost;
Oper revop;
Cost revcost;
State state;
Edge(Plat2d &d, State &s, Oper op) : revop(Nop), revcost(-1), state(s) {
state.h = -1;
state.player.act(d.lvl, (unsigned int) op);
cost = 1; // geom2d::Pt::distance(s.player.body.bbox.min, state.player.body.bbox.min));
if (s.player.body.bbox.min.y == state.player.body.bbox.min.y) {
if (op == Player::Left) {
revop = Player::Right;
revcost = cost;
}
else if (op == Player::Right) {
revop = Player::Left;
revcost = cost;
}
}
double dy = fabs(s.player.body.bbox.center().y - state.player.body.bbox.center().y);
double dx = fabs(s.player.body.bbox.center().x - state.player.body.bbox.center().x);
assert (dx <= Maxx);
assert (dy <= Maxy);
}
};
void pack(PackedState &dst, State &src) {
dst.x = src.player.body.bbox.min.x;
dst.y = src.player.body.bbox.min.y;
dst.dy = src.player.body.dy;
dst.jframes = src.player.jframes;
if (src.player.body.fall)
dst.jframes |= 1 << 7;
}
State &unpack(State &buf, PackedState &pkd) {
buf.player.jframes = pkd.jframes & 0x7F;
buf.player.body.fall = pkd.jframes & (1 << 7);
buf.player.body.dy = pkd.dy;
buf.player.body.bbox.min.x = pkd.x;
buf.player.body.bbox.min.y = pkd.y;
buf.player.body.bbox.max.x = pkd.x + Player::Width;
buf.player.body.bbox.max.y = pkd.y + Player::Height;
return buf;
}
static void dumpstate(FILE *out, State &s) {
fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
}
Cost pathcost(const std::vector<State>&, const std::vector<Oper>&);
// Drawmap returns an image of the map.
Image *drawmap() const;
unsigned int gx, gy; // goal tile location
unsigned int x0, y0; // initial location
Lvl lvl;
private:
struct Node {
int v; // vertex ID
int prev; // previous along path
long i; // prio queue index
double d; // distance to goal
static void setind(Node *n, unsigned long ind) { n->i = ind; }
static bool pred(const Node *a, const Node *b) { return a->d < b->d; }
};
void initvg();
double hvis(State &s) const {
const Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);
if (bi.x == gx && bi.y == gy)
return 0;
geom2d::Pt loc(s.player.body.bbox.center());
loc.x /= Maxx; // Pixel to squished vismap coords.
loc.y /= Maxy;
int c = centers[bi.x * lvl.height() + bi.y];
geom2d::Pt g = goalpt(bi, loc);
if (togoal[c].prev == gcenter || vg->map.isvisible(loc, g)) {
double dx = fabs(g.x - loc.x);
double dy = fabs(g.y - loc.y);
double h = floor(std::max(dx, dy));
return h <= 0 ? 1 : h;
}
// Account for goal vertex being at its tile center.
static const double diag = std::max(W/2, H/2);
// Account for distance from player to center of tile.
double middx = fabs(loc.x - vg->verts[c].pt.x);
double middy = fabs(loc.y - vg->verts[c].pt.y);
double tomid = std::max(middx, middy);
double h = togoal[c].d - tomid - diag;
if (h <= 0)
h = 1;
h = floor(h);
if (h <= 0)
h = 1;
return h;
}
// goalpt returns a point in the goal cell that is closest
// to the given location.
geom2d::Pt goalpt(const Lvl::Blkinfo &bi, const geom2d::Pt &loc) const {
geom2d::Pt pt;
if (bi.y == gy)
pt.y = loc.y;
else if (bi.y < gy)
pt.y = gtop;
else
pt.y = gbottom;
if (bi.x == gx)
pt.x = loc.x;
else if (bi.x < gx)
pt.x = gleft;
else
pt.x = gright;
return pt;
}
// savemap draws the visibility map used for the heuristic
// to the given file.;
void savemap(const char*) const;
VisGraph *vg;
std::vector<long> centers;
std::vector<Node> togoal;
int gcenter; // vertex ID of the goal center
double gleft, gright, gtop, gbottom;
double maxx, maxy; // width and height in pixels.
};
<|endoftext|> |
<commit_before>// The Moving Least Squares Material Point Method in 88 LoC (with comments)
// To compile: g++ mls-mpm88.cpp -std=c++14 -g -lX11 -lpthread -O2 -o mls-mpm
#include "taichi.h" // Single header version of (part of) taichi
using namespace taichi;
const int n = 64 /*grid resolution (cells)*/, window_size = 800;
const real dt = 1e-4_f, frame_dt = 1e-3_f, dx = 1.0_f / n, inv_dx = 1.0_f / dx;
auto particle_mass = 1.0_f, vol = 1.0_f;
auto hardening = 10.0_f, E = 1e4_f, nu = 0.2_f;
real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1+nu) * (1 - 2 * nu));
using Vec = Vector2; using Mat = Matrix2;
struct Particle { Vec x, v; Mat F, C; real Jp;
Particle(Vec x, Vec v=Vec(0)) : x(x), v(v), F(1), C(0), Jp(1) {} };
std::vector<Particle> particles;
Vector3 grid[n + 1][n + 1]; // velocity + mass, node res = cell res + 1
void advance(real dt) {
std::memset(grid, 0, sizeof(grid)); // Reset grid
for (auto &p : particles) { // P2G
Vector2i base_coord = (p.x*inv_dx-Vec(0.5_f)).cast<int>();
Vec fx = p.x * inv_dx - base_coord.cast<real>();
// Quadratic kernels, see http://mpm.graphics Formula (123)
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
auto e = std::exp(hardening * (1.0_f - p.Jp)), mu=mu_0*e, lambda=lambda_0*e;
real J = determinant(p.F); // Current volume
Mat r, s; polar_decomp(p.F, r, s); //Polor decomp. for fixed corotated model
auto stress = // Cauchy stress times dt and inv_dx
-inv_dx*dt*vol*(2*mu * (p.F-r) * transposed(p.F) + lambda * (J-1) * J);
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { // Scatter to grid
auto dpos = Vec(i, j) - fx;
Vector3 contrib(p.v * particle_mass, particle_mass);
grid[base_coord.x + i][base_coord.y + j] +=
w[i].x*w[j].y*(contrib+Vector3(4.0_f*(stress+p.C*particle_mass)*dpos));
}
}
for(int i = 0; i <= n; i++) for(int j = 0; j <= n; j++) { //For all grid nodes
auto &g = grid[i][j];
if (g[2] > 0) { // No need for epsilon here
g /= g[2]; // Normalize by mass
g += dt * Vector3(0, -100, 0); // Gravity
real boundary=0.05,x=(real)i/n,y=real(j)/n; //boundary thick.,node coord
if (x < boundary||x > 1-boundary||y > 1-boundary) g=Vector3(0); //Sticky
if (y < boundary) g[1] = std::max(0.0_f, g[1]); //"Separate"
}
}
for (auto &p : particles) { // Grid to particle
Vector2i base_coord = (p.x * inv_dx - Vec(0.5_f)).cast<int>();
Vec fx = p.x * inv_dx - base_coord.cast<real>();
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
p.C = Mat(0); p.v = Vec(0);
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) {
auto dpos = Vec(i, j) - fx,
grid_v = Vec(grid[base_coord.x + i][base_coord.y + j]);
auto weight = w[i].x * w[j].y;
p.v += weight * grid_v; // Velocity
p.C += Mat::outer_product(weight * grid_v, dpos); // APIC C
}
p.x += dt * p.v; // Advection
auto F = (Mat(1) + (4 * inv_dx * dt) * p.C) * p.F; // MLS-MPM F-update
Mat svd_u, sig, svd_v; svd(F, svd_u, sig, svd_v);
for (int i = 0; i < 2; i++) // Snow Plasticity
sig[i][i] = clamp(sig[i][i], 1.0_f - 2.5e-2_f, 1.0_f + 7.5e-3_f);
real oldJ = determinant(F); F = svd_u * sig * transposed(svd_v);
real Jp_new = clamp(p.Jp * oldJ / determinant(F), 0.6_f, 20.0_f);
p.Jp = Jp_new; p.F = F;
}
}
void add_object(Vec center) { // Seed particles
for (int i = 0; i < 1000; i++) // Randomly sample 1000 particles in the square
particles.push_back(Particle((Vec::rand()*2.0_f-Vec(1))*0.08_f+center));
}
int main() {
GUI gui("Taichi Demo: Real-time MLS-MPM 2D ", window_size, window_size);
add_object(Vec(0.5,0.4));add_object(Vec(0.45,0.6));add_object(Vec(0.55,0.8));
for (int i = 0;; i++) { // Main Loop
advance(dt); // Advance simulation
if (i % int(frame_dt / dt) == 0) { // Redraw frame
gui.get_canvas().clear(Vector4(0.2, 0.4, 0.7, 1.0_f)); // Clear background
for (auto p : particles) // Draw particles
gui.buffer[(p.x * (inv_dx*window_size/n)).cast<int>()] = Vector4(0.8);
gui.update(); // Update image
}//Reference: A Moving Least Squares Material Point Method with Displacement
} // Discontinuity and Two-Way Rigid Body Coupling (SIGGRAPH 2018)
} // By Yuanming Hu (who also wrote this 88-line version), Yu Fang, Ziheng Ge,
// Ziyin Qu, Yixin Zhu, Andre Pradhana, Chenfanfu Jiang<commit_msg>updated mls-mpm88.cpp<commit_after>// 88-Line Moving Least Squares Material Point Method (MLS-MPM) [with comments]
// To compile: g++ mls-mpm88.cpp -std=c++14 -g -lX11 -lpthread -O2 -o mls-mpm
#include "taichi.h" // Single header version of (part of) taichi
using namespace taichi;
const int n = 64 /*grid resolution (cells)*/, window_size = 800;
const real dt = 1e-4_f, frame_dt = 1e-3_f, dx = 1.0_f / n, inv_dx = 1.0_f / dx;
auto particle_mass = 1.0_f, vol = 1.0_f;
auto hardening = 10.0_f, E = 1e4_f, nu = 0.2_f;
real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1+nu) * (1 - 2 * nu));
using Vec = Vector2; using Mat = Matrix2;
struct Particle { Vec x, v; Mat F, C; real Jp;
Particle(Vec x, Vec v=Vec(0)) : x(x), v(v), F(1), C(0), Jp(1) {} };
std::vector<Particle> particles;
Vector3 grid[n + 1][n + 1]; // velocity + mass, node res = cell res + 1
void advance(real dt) {
std::memset(grid, 0, sizeof(grid)); // Reset grid
for (auto &p : particles) { // P2G
Vector2i base_coord = (p.x*inv_dx-Vec(0.5_f)).cast<int>();
Vec fx = p.x * inv_dx - base_coord.cast<real>();
// Quadratic kernels, see http://mpm.graphics Formula (123)
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
auto e = std::exp(hardening * (1.0_f - p.Jp)), mu=mu_0*e, lambda=lambda_0*e;
real J = determinant(p.F); // Current volume
Mat r, s; polar_decomp(p.F, r, s); //Polor decomp. for fixed corotated model
auto stress = // Cauchy stress times dt and inv_dx
-inv_dx*dt*vol*(2*mu * (p.F-r) * transposed(p.F) + lambda * (J-1) * J);
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { // Scatter to grid
auto dpos = Vec(i, j) - fx;
Vector3 contrib(p.v * particle_mass, particle_mass);
grid[base_coord.x + i][base_coord.y + j] +=
w[i].x*w[j].y*(contrib+Vector3(4.0_f*(stress+p.C*particle_mass)*dpos));
}
}
for(int i = 0; i <= n; i++) for(int j = 0; j <= n; j++) { //For all grid nodes
auto &g = grid[i][j];
if (g[2] > 0) { // No need for epsilon here
g /= g[2]; // Normalize by mass
g += dt * Vector3(0, -100, 0); // Gravity
real boundary=0.05,x=(real)i/n,y=real(j)/n; //boundary thick.,node coord
if (x < boundary||x > 1-boundary||y > 1-boundary) g=Vector3(0); //Sticky
if (y < boundary) g[1] = std::max(0.0_f, g[1]); //"Separate"
}
}
for (auto &p : particles) { // Grid to particle
Vector2i base_coord = (p.x * inv_dx - Vec(0.5_f)).cast<int>();
Vec fx = p.x * inv_dx - base_coord.cast<real>();
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
p.C = Mat(0); p.v = Vec(0);
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) {
auto dpos = Vec(i, j) - fx,
grid_v = Vec(grid[base_coord.x + i][base_coord.y + j]);
auto weight = w[i].x * w[j].y;
p.v += weight * grid_v; // Velocity
p.C += Mat::outer_product(weight * grid_v, dpos); // APIC C
}
p.x += dt * p.v; // Advection
auto F = (Mat(1) + (4 * inv_dx * dt) * p.C) * p.F; // MLS-MPM F-update
Mat svd_u, sig, svd_v; svd(F, svd_u, sig, svd_v);
for (int i = 0; i < 2; i++) // Snow Plasticity
sig[i][i] = clamp(sig[i][i], 1.0_f - 2.5e-2_f, 1.0_f + 7.5e-3_f);
real oldJ = determinant(F); F = svd_u * sig * transposed(svd_v);
real Jp_new = clamp(p.Jp * oldJ / determinant(F), 0.6_f, 20.0_f);
p.Jp = Jp_new; p.F = F;
}
}
void add_object(Vec center) { // Seed particles
for (int i = 0; i < 1000; i++) // Randomly sample 1000 particles in the square
particles.push_back(Particle((Vec::rand()*2.0_f-Vec(1))*0.08_f+center));
}
int main() {
GUI gui("Taichi Demo: Real-time MLS-MPM 2D ", window_size, window_size);
add_object(Vec(0.5,0.4));add_object(Vec(0.45,0.6));add_object(Vec(0.55,0.8));
for (int i = 0;; i++) { // Main Loop
advance(dt); // Advance simulation
if (i % int(frame_dt / dt) == 0) { // Redraw frame
gui.get_canvas().clear(Vector4(0.2, 0.4, 0.7, 1.0_f)); // Clear background
for (auto p : particles) // Draw particles
gui.buffer[(p.x * (inv_dx*window_size/n)).cast<int>()] = Vector4(0.8);
gui.update(); // Update image
}//Reference: A Moving Least Squares Material Point Method with Displacement
} // Discontinuity and Two-Way Rigid Body Coupling (SIGGRAPH 2018)
} // By Yuanming Hu (who also wrote this 88-line version), Yu Fang, Ziheng Ge,
// Ziyin Qu, Yixin Zhu, Andre Pradhana, Chenfanfu Jiang<|endoftext|> |
<commit_before><commit_msg>Framework: fix record issue (#1160)<commit_after><|endoftext|> |
<commit_before> // $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Oystein Djuvsland *
* *
* 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. *
**************************************************************************/
#include "AliHLTPHOSDigitMakerComponent.h"
#include "AliHLTPHOSDigitMaker.h"
#include "AliHLTPHOSDigitDataStruct.h"
#include "AliHLTPHOSChannelDataHeaderStruct.h"
#include "AliHLTPHOSChannelDataStruct.h"
#include "TFile.h"
#include <sys/stat.h>
#include <sys/types.h>
/**
* @file AliHLTPHOSDigitMakerComponent.cxx
* @author Oystein Djuvsland
* @date
* @brief A digit maker component for PHOS HLT
*/
// see below for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
AliHLTPHOSDigitMakerComponent gAliHLTPHOSDigitMakerComponent;
AliHLTPHOSDigitMakerComponent::AliHLTPHOSDigitMakerComponent() :
AliHLTPHOSProcessor(),
fDigitMakerPtr(0),
fDigitContainerPtr(0)
{
//see header file for documentation
}
AliHLTPHOSDigitMakerComponent::~AliHLTPHOSDigitMakerComponent()
{
//see header file for documentation
}
int
AliHLTPHOSDigitMakerComponent::Deinit()
{
//see header file for documentation
if(fDigitMakerPtr)
{
delete fDigitMakerPtr;
fDigitMakerPtr = 0;
}
return 0;
}
const char*
AliHLTPHOSDigitMakerComponent::GetComponentID()
{
//see header file for documentation
return "PhosDigitMaker";
}
void
AliHLTPHOSDigitMakerComponent::GetInputDataTypes(vector<AliHLTComponentDataType>& list)
{
//see header file for documentation
list.clear();
list.push_back(AliHLTPHOSDefinitions::fgkChannelDataType);
}
AliHLTComponentDataType
AliHLTPHOSDigitMakerComponent::GetOutputDataType()
{
//see header file for documentation
return AliHLTPHOSDefinitions::fgkDigitDataType;
}
void
AliHLTPHOSDigitMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
//see header file for documentation
constBase = 0;
inputMultiplier = (float)sizeof(AliHLTPHOSDigitDataStruct)/sizeof(AliHLTPHOSChannelDataStruct) + 1;
}
int
AliHLTPHOSDigitMakerComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size,
std::vector<AliHLTComponentBlockData>& outputBlocks)
{
//see header file for documentation
UInt_t offset = 0;
UInt_t mysize = 0;
Int_t digitCount = 0;
Int_t ret = 0;
AliHLTUInt8_t* outBPtr;
outBPtr = outputPtr;
const AliHLTComponentBlockData* iter = 0;
unsigned long ndx;
UInt_t specification = 0;
AliHLTPHOSChannelDataHeaderStruct* tmpChannelData = 0;
fDigitMakerPtr->SetDigitHeaderPtr(reinterpret_cast<AliHLTPHOSDigitHeaderStruct*>(outputPtr));
for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
{
iter = blocks+ndx;
if(iter->fDataType != AliHLTPHOSDefinitions::fgkChannelDataType)
{
HLTDebug("Data block is not of type fgkChannelDataType");
continue;
}
specification |= iter->fSpecification;
tmpChannelData = reinterpret_cast<AliHLTPHOSChannelDataHeaderStruct*>(iter->fPtr);
ret = fDigitMakerPtr->MakeDigits(tmpChannelData, size-(digitCount*sizeof(AliHLTPHOSDigitDataStruct)));
if(ret == -1)
{
HLTError("Trying to write over buffer size");
return -ENOBUFS;
}
digitCount += ret;
}
mysize += digitCount*sizeof(AliHLTPHOSDigitDataStruct);
// HLTDebug("# of digits: %d, used memory size: %d, available size: %d", digitCount, mysize, size);
if(mysize > 0)
{
AliHLTComponentBlockData bd;
FillBlockData( bd );
bd.fOffset = offset;
bd.fSize = mysize;
bd.fDataType = AliHLTPHOSDefinitions::fgkDigitDataType;
bd.fSpecification = specification;
outputBlocks.push_back(bd);
}
fDigitMakerPtr->Reset();
size = mysize;
return 0;
}
int
AliHLTPHOSDigitMakerComponent::DoInit(int argc, const char** argv )
{
//see header file for documentation
fDigitMakerPtr = new AliHLTPHOSDigitMaker();
for(int i = 0; i < argc; i++)
{
if(!strcmp("-lowgainfactor", argv[i]))
{
fDigitMakerPtr->SetGlobalLowGainFactor(atof(argv[i+1]));
}
if(!strcmp("-highgainfactor", argv[i]))
{
fDigitMakerPtr->SetGlobalHighGainFactor(atof(argv[i+1]));
}
if(!strcmp("-reverseorder", argv[i]))
{
fDigitMakerPtr->SetOrdered(false);
}
}
//fDigitMakerPtr->SetDigitThreshold(2);
return 0;
}
AliHLTComponent*
AliHLTPHOSDigitMakerComponent::Spawn()
{
//see header file for documentation
return new AliHLTPHOSDigitMakerComponent();
}
<commit_msg>- fixing bug in digitmaker - option to push raw data in raw analyzer - protection in clusterizer<commit_after> // $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Oystein Djuvsland *
* *
* 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. *
**************************************************************************/
#include "AliHLTPHOSDigitMakerComponent.h"
#include "AliHLTPHOSDigitMaker.h"
#include "AliHLTPHOSDigitDataStruct.h"
#include "AliHLTPHOSChannelDataHeaderStruct.h"
#include "AliHLTPHOSChannelDataStruct.h"
#include "TFile.h"
#include <sys/stat.h>
#include <sys/types.h>
/**
* @file AliHLTPHOSDigitMakerComponent.cxx
* @author Oystein Djuvsland
* @date
* @brief A digit maker component for PHOS HLT
*/
// see below for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
AliHLTPHOSDigitMakerComponent gAliHLTPHOSDigitMakerComponent;
AliHLTPHOSDigitMakerComponent::AliHLTPHOSDigitMakerComponent() :
AliHLTPHOSProcessor(),
fDigitMakerPtr(0),
fDigitContainerPtr(0)
{
//see header file for documentation
}
AliHLTPHOSDigitMakerComponent::~AliHLTPHOSDigitMakerComponent()
{
//see header file for documentation
}
int
AliHLTPHOSDigitMakerComponent::Deinit()
{
//see header file for documentation
if(fDigitMakerPtr)
{
delete fDigitMakerPtr;
fDigitMakerPtr = 0;
}
return 0;
}
const char*
AliHLTPHOSDigitMakerComponent::GetComponentID()
{
//see header file for documentation
return "PhosDigitMaker";
}
void
AliHLTPHOSDigitMakerComponent::GetInputDataTypes(vector<AliHLTComponentDataType>& list)
{
//see header file for documentation
list.clear();
list.push_back(AliHLTPHOSDefinitions::fgkChannelDataType);
}
AliHLTComponentDataType
AliHLTPHOSDigitMakerComponent::GetOutputDataType()
{
//see header file for documentation
return AliHLTPHOSDefinitions::fgkDigitDataType;
}
void
AliHLTPHOSDigitMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
//see header file for documentation
constBase = 0;
inputMultiplier = (float)sizeof(AliHLTPHOSDigitDataStruct)/sizeof(AliHLTPHOSChannelDataStruct) + 1;
}
int
AliHLTPHOSDigitMakerComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size,
std::vector<AliHLTComponentBlockData>& outputBlocks)
{
//see header file for documentation
UInt_t offset = 0;
UInt_t mysize = 0;
Int_t digitCount = 0;
Int_t ret = 0;
AliHLTUInt8_t* outBPtr;
outBPtr = outputPtr;
const AliHLTComponentBlockData* iter = 0;
unsigned long ndx;
UInt_t specification = 0;
AliHLTPHOSChannelDataHeaderStruct* tmpChannelData = 0;
fDigitMakerPtr->SetDigitHeaderPtr(reinterpret_cast<AliHLTPHOSDigitHeaderStruct*>(outputPtr));
for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
{
iter = blocks+ndx;
if(iter->fDataType != AliHLTPHOSDefinitions::fgkChannelDataType)
{
HLTDebug("Data block is not of type fgkChannelDataType");
continue;
}
specification |= iter->fSpecification;
tmpChannelData = reinterpret_cast<AliHLTPHOSChannelDataHeaderStruct*>(iter->fPtr);
ret = fDigitMakerPtr->MakeDigits(tmpChannelData, size-(digitCount*sizeof(AliHLTPHOSDigitDataStruct)));
if(ret == -1)
{
HLTError("Trying to write over buffer size");
return -ENOBUFS;
}
digitCount += ret;
}
mysize += digitCount*sizeof(AliHLTPHOSDigitDataStruct);
// HLTDebug("# of digits: %d, used memory size: %d, available size: %d", digitCount, mysize, size);
if(mysize > 0)
{
AliHLTComponentBlockData bd;
FillBlockData( bd );
bd.fOffset = offset;
bd.fSize = mysize;
bd.fDataType = AliHLTPHOSDefinitions::fgkDigitDataType;
bd.fSpecification = specification;
outputBlocks.push_back(bd);
}
fDigitMakerPtr->Reset();
size = mysize;
return 0;
}
int
AliHLTPHOSDigitMakerComponent::DoInit(int argc, const char** argv )
{
//see header file for documentation
fDigitMakerPtr = new AliHLTPHOSDigitMaker();
for(int i = 0; i < argc; i++)
{
if(!strcmp("-lowgainfactor", argv[i]))
{
fDigitMakerPtr->SetGlobalLowGainFactor(atof(argv[i+1]));
}
if(!strcmp("-highgainfactor", argv[i]))
{
fDigitMakerPtr->SetGlobalHighGainFactor(atof(argv[i+1]));
}
if(!strcmp("-reverseorder", argv[i]))
{
fDigitMakerPtr->SetOrdered(false);
}
}
//fDigitMakerPtr->SetDigitThreshold(2);
return 0;
}
AliHLTComponent*
AliHLTPHOSDigitMakerComponent::Spawn()
{
//see header file for documentation
return new AliHLTPHOSDigitMakerComponent();
}
<|endoftext|> |
<commit_before>//
// Created by Vadim N. on 18/03/2015.
//
#ifndef _BENCHMARK_H_
#define _BENCHMARK_H_
#define BENCH_DATA_FOLDER string("/Users/vdn/ymir/benchmark/data/")
#include <chrono>
#include <ctime>
#include "parser.h"
#include "statisticalinferencealgorithm.h"
using namespace ymir;
int main() {
std::chrono::system_clock::time_point tp1, tp2;
RepertoireParser parser;
parser.loadConfig(BENCH_DATA_FOLDER + "../../parsers/mitcrdots.json");
//
// TCR alpha chain repertoire - VJ recombination
//
VDJRecombinationGenes vj_genes("Vgene",
BENCH_DATA_FOLDER + "trav.txt",
"Jgene",
BENCH_DATA_FOLDER + "traj.txt");
tp1 = std::chrono::system_clock::now();
Cloneset cloneset_vj;
parser.parse(BENCH_DATA_FOLDER + "mitcr.alpha.500k.txt",
&cloneset_vj,
vj_genes,
RepertoireParser::AlignmentColumnOptions()
.setV(RepertoireParser::MAKE_IF_NOT_FOUND)
.setJ(RepertoireParser::MAKE_IF_NOT_FOUND)
.setD(RepertoireParser::SKIP));
tp2 = std::chrono::system_clock::now();
cout << "Parsing VJ, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
//
// TCR beta chain repertoire - VDJ recombination
//
VDJRecombinationGenes vdj_genes("Vgene",
BENCH_DATA_FOLDER + "trbv.txt",
"Jgene",
BENCH_DATA_FOLDER + "trbj.txt",
"Dgene",
BENCH_DATA_FOLDER + "trbd.txt");
tp1 = std::chrono::system_clock::now();
Cloneset cloneset_vdj;
parser.parse(BENCH_DATA_FOLDER + "mitcr.beta.500k.txt",
&cloneset_vdj,
vdj_genes,
RepertoireParser::AlignmentColumnOptions()
.setV(RepertoireParser::MAKE_IF_NOT_FOUND)
.setJ(RepertoireParser::MAKE_IF_NOT_FOUND)
.setD(RepertoireParser::OVERWRITE));
tp2 = std::chrono::system_clock::now();
cout << "Parsing VDJ, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
//
// VJ MAAG
//
ProbabilisticAssemblingModel vj_model(BENCH_DATA_FOLDER + "../../models/hTRA");
tp1 = std::chrono::system_clock::now();
vj_model.buildGraphs(cloneset_vj, true);
tp2 = std::chrono::system_clock::now();
cout << "VJ MAAG with metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
tp1 = std::chrono::system_clock::now();
vj_model.computeFullProbabilities(cloneset_vj);
tp2 = std::chrono::system_clock::now();
cout << "VJ MAAG without metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
//
// VDJ MAAG
//
ProbabilisticAssemblingModel vdj_model(BENCH_DATA_FOLDER + "../../models/hTRB");
tp1 = std::chrono::system_clock::now();
vdj_model.buildGraphs(cloneset_vdj, true);
tp2 = std::chrono::system_clock::now();
cout << "VDJ MAAG with metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
tp1 = std::chrono::system_clock::now();
vdj_model.computeFullProbabilities(cloneset_vdj);
tp2 = std::chrono::system_clock::now();
cout << "VDJ MAAG without metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
// Cloneset repertoire50K, repertoire200K, repertoire500K;
// With and without parallelisation
// Compute simple one-alignment full probabilities.
// 1 V ; 1 J
// repertoire1K;
// repertoire10K;
// repertoire100K;
// 1000
// 10000
// 500000
// 1 V ; 2 Ds ; 1 J
// repertoire1K;
// repertoire10K;
// repertoire100K;
// 1000
// 10000
// 500000
// Compute simple one-alignment full probabilities with storing additional data like CDR3 sequences.
// 1 V ; 1 J
// 1000
// 10000
// 500000
// 1 V ; 2 Ds ; 1 J
// 1000
// 10000
// 500000
// Compute various multi-alignment full probabilities.
// 2 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 5 Js
// 1000
// 10000
// 500000
// 2 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 5 Js
// 1000
// 10000
// 500000
// Compute various multi-alignment full probabilities with full graph building.
// 2 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 5 Js
// 1000
// 10000
// 500000
// 2 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 5 Js
// 1000
// 10000
// 500000
return 0;
}
#endif //_BENCHMARK_H_
<commit_msg>minor changes to benchmark, just for testing purposes<commit_after>//
// Created by Vadim N. on 18/03/2015.
//
#ifndef _BENCHMARK_H_
#define _BENCHMARK_H_
#define BENCH_DATA_FOLDER string("/Users/vdn/ymir/benchmark/data/")
#include <chrono>
#include <ctime>
#include "parser.h"
#include "statisticalinferencealgorithm.h"
using namespace ymir;
int main() {
std::chrono::system_clock::time_point tp1, tp2;
RepertoireParser parser;
parser.loadConfig(BENCH_DATA_FOLDER + "../../parsers/mitcrdots.json");
/*
//
// TCR alpha chain repertoire - VJ recombination
//
VDJRecombinationGenes vj_genes("Vgene",
BENCH_DATA_FOLDER + "trav.txt",
"Jgene",
BENCH_DATA_FOLDER + "traj.txt");
tp1 = std::chrono::system_clock::now();
Cloneset cloneset_vj;
parser.parse(BENCH_DATA_FOLDER + "mitcr.alpha.500k.txt",
&cloneset_vj,
vj_genes,
RepertoireParser::AlignmentColumnOptions()
.setV(RepertoireParser::MAKE_IF_NOT_FOUND)
.setJ(RepertoireParser::MAKE_IF_NOT_FOUND)
.setD(RepertoireParser::SKIP));
tp2 = std::chrono::system_clock::now();
cout << "Parsing VJ, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
*/
//
// TCR beta chain repertoire - VDJ recombination
//
VDJRecombinationGenes vdj_genes("Vgene",
BENCH_DATA_FOLDER + "trbv.txt",
"Jgene",
BENCH_DATA_FOLDER + "trbj.txt",
"Dgene",
BENCH_DATA_FOLDER + "trbd.txt");
tp1 = std::chrono::system_clock::now();
Cloneset cloneset_vdj;
parser.parse(BENCH_DATA_FOLDER + "mitcr.beta.500k.txt",
&cloneset_vdj,
vdj_genes,
RepertoireParser::AlignmentColumnOptions()
.setV(RepertoireParser::MAKE_IF_NOT_FOUND)
.setJ(RepertoireParser::MAKE_IF_NOT_FOUND)
.setD(RepertoireParser::OVERWRITE));
tp2 = std::chrono::system_clock::now();
cout << "Parsing VDJ, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
//
// VJ MAAG
//
/*
ProbabilisticAssemblingModel vj_model(BENCH_DATA_FOLDER + "../../models/hTRA");
tp1 = std::chrono::system_clock::now();
vj_model.buildGraphs(cloneset_vj, true);
tp2 = std::chrono::system_clock::now();
cout << "VJ MAAG with metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
tp1 = std::chrono::system_clock::now();
vj_model.computeFullProbabilities(cloneset_vj);
tp2 = std::chrono::system_clock::now();
cout << "VJ MAAG without metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
*/
//
// VDJ MAAG
//
ProbabilisticAssemblingModel vdj_model(BENCH_DATA_FOLDER + "../../models/hTRB");
tp1 = std::chrono::system_clock::now();
vdj_model.computeFullProbabilities(cloneset_vdj);
tp2 = std::chrono::system_clock::now();
cout << "VDJ MAAG without metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
tp1 = std::chrono::system_clock::now();
vdj_model.buildGraphs(cloneset_vdj, true);
tp2 = std::chrono::system_clock::now();
cout << "VDJ MAAG with metadata, seconds: " << (std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1)) << endl;
// Cloneset repertoire50K, repertoire200K, repertoire500K;
// With and without parallelisation
// Compute simple one-alignment full probabilities.
// 1 V ; 1 J
// repertoire1K;
// repertoire10K;
// repertoire100K;
// 1000
// 10000
// 500000
// 1 V ; 2 Ds ; 1 J
// repertoire1K;
// repertoire10K;
// repertoire100K;
// 1000
// 10000
// 500000
// Compute simple one-alignment full probabilities with storing additional data like CDR3 sequences.
// 1 V ; 1 J
// 1000
// 10000
// 500000
// 1 V ; 2 Ds ; 1 J
// 1000
// 10000
// 500000
// Compute various multi-alignment full probabilities.
// 2 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 5 Js
// 1000
// 10000
// 500000
// 2 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 5 Js
// 1000
// 10000
// 500000
// Compute various multi-alignment full probabilities with full graph building.
// 2 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 5 Js
// 1000
// 10000
// 500000
// 2 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 1 Js
// 1000
// 10000
// 500000
// 5 Vs ; 2 Ds ; 5 Js
// 1000
// 10000
// 500000
return 0;
}
#endif //_BENCHMARK_H_
<|endoftext|> |
<commit_before>#include "timezonelistitem.h"
#include "dcptimezonedata.h"
#include <QGraphicsGridLayout>
#include <QSizePolicy>
#include <duibutton.h>
#include <duilabel.h>
#include <duiseparator.h>
#include <QGraphicsSceneMouseEvent>
const int height = 75;
TimeZoneListItem::TimeZoneListItem(QString timezone, QString country, QString gmt,
QString city, DuiWidget *parent)
:DuiWidget(parent),
m_TimeZone(timezone),
m_Country(country),
m_Gmt(gmt),
m_City(city),
m_Checked(false),
m_Filtered(true)
{
initWidget();
}
TimeZoneListItem::~TimeZoneListItem()
{
}
QString TimeZoneListItem::timeZone()
{
return m_TimeZone;
}
QString TimeZoneListItem::country()
{
return m_Country;
}
QString TimeZoneListItem::gmt()
{
return m_Gmt;
}
QString TimeZoneListItem::city()
{
return m_City;
}
void TimeZoneListItem::checked(bool ok)
{
m_Checked = ok;
m_CheckMark->setVisible(m_Checked);
if (m_Checked) {
m_CountryLabel->setObjectName("CountryLabelSelected");
m_GmtCityLabel->setObjectName("GmtCityLabelSelected");
} else {
m_CountryLabel->setObjectName("CountryLabel");
m_GmtCityLabel->setObjectName("GmtCityLabel");
}
}
bool TimeZoneListItem::isChecked()
{
return m_Checked;
}
void TimeZoneListItem::filtered(bool ok)
{
m_Filtered = ok;
}
bool TimeZoneListItem::isFiltered()
{
return m_Filtered;
}
void TimeZoneListItem::setVisibleSeparator(bool enable)
{
m_GraySeparator->setVisible(enable);
}
void TimeZoneListItem::initWidget()
{
// mainLayout
QGraphicsGridLayout *mainLayout = new QGraphicsGridLayout(this);
mainLayout->setContentsMargins(0.0, 0.0, 0.0, 0.0);
mainLayout->setSpacing(0);
// set height
this->setMinimumHeight(height);
this->setMaximumHeight(height);
// m_CountryLabel
m_CountryLabel = new DuiLabel(m_Country, this);
m_CountryLabel->setObjectName("CountryLabel");
m_CountryLabel->setAlignment(Qt::AlignBottom);
// m_GmtCityLabel
m_GmtCityLabel = new DuiLabel(m_Gmt + " " + m_City, this);
m_GmtCityLabel->setObjectName("GmtCityLabel");
m_GmtCityLabel->setAlignment(Qt::AlignTop);
mainLayout->addItem(m_CountryLabel, 0,0, 1,2); // FIXME: what to do with long names
mainLayout->addItem(m_GmtCityLabel, 1,0);
// m_CheckMark
m_CheckMark = new DuiButton(this);
m_CheckMark->setObjectName("TimeZoneCheckMark");
m_CheckMark->setAcceptedMouseButtons(0);
m_CheckMark->setVisible(false);
// m_GreySeparator
m_GraySeparator = new DuiSeparator(this);
mainLayout->addItem(m_CheckMark, 0,1, 2,1, Qt::AlignCenter);
mainLayout->addItem(m_GraySeparator, 2,0, 1,2, Qt::AlignRight);
}
void TimeZoneListItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
DuiWidget::mousePressEvent(event);
event->accept();
emit clicked(this);
}
void TimeZoneListItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
DuiWidget::mouseReleaseEvent(event);
event->accept();
}
<commit_msg>Makes gridlayout cell usage ok for timezonelistitem<commit_after>#include "timezonelistitem.h"
#include "dcptimezonedata.h"
#include <QGraphicsGridLayout>
#include <QSizePolicy>
#include <duibutton.h>
#include <duilabel.h>
#include <duiseparator.h>
#include <QGraphicsSceneMouseEvent>
const int height = 75;
TimeZoneListItem::TimeZoneListItem(QString timezone, QString country, QString gmt,
QString city, DuiWidget *parent)
:DuiWidget(parent),
m_TimeZone(timezone),
m_Country(country),
m_Gmt(gmt),
m_City(city),
m_Checked(false),
m_Filtered(true)
{
initWidget();
}
TimeZoneListItem::~TimeZoneListItem()
{
}
QString TimeZoneListItem::timeZone()
{
return m_TimeZone;
}
QString TimeZoneListItem::country()
{
return m_Country;
}
QString TimeZoneListItem::gmt()
{
return m_Gmt;
}
QString TimeZoneListItem::city()
{
return m_City;
}
void TimeZoneListItem::checked(bool ok)
{
m_Checked = ok;
m_CheckMark->setVisible(m_Checked);
if (m_Checked) {
m_CountryLabel->setObjectName("CountryLabelSelected");
m_GmtCityLabel->setObjectName("GmtCityLabelSelected");
} else {
m_CountryLabel->setObjectName("CountryLabel");
m_GmtCityLabel->setObjectName("GmtCityLabel");
}
}
bool TimeZoneListItem::isChecked()
{
return m_Checked;
}
void TimeZoneListItem::filtered(bool ok)
{
m_Filtered = ok;
}
bool TimeZoneListItem::isFiltered()
{
return m_Filtered;
}
void TimeZoneListItem::setVisibleSeparator(bool enable)
{
m_GraySeparator->setVisible(enable);
}
void TimeZoneListItem::initWidget()
{
// mainLayout
QGraphicsGridLayout *mainLayout = new QGraphicsGridLayout(this);
mainLayout->setContentsMargins(0.0, 0.0, 0.0, 0.0);
mainLayout->setSpacing(0);
// set height
this->setMinimumHeight(height);
this->setMaximumHeight(height);
// m_CountryLabel
m_CountryLabel = new DuiLabel(m_Country, this);
m_CountryLabel->setObjectName("CountryLabel");
m_CountryLabel->setAlignment(Qt::AlignBottom);
// m_GmtCityLabel
m_GmtCityLabel = new DuiLabel(m_Gmt + " " + m_City, this);
m_GmtCityLabel->setObjectName("GmtCityLabel");
m_GmtCityLabel->setAlignment(Qt::AlignTop);
mainLayout->addItem(m_CountryLabel, 0,0);
mainLayout->addItem(m_GmtCityLabel, 1,0);
// m_CheckMark
m_CheckMark = new DuiButton(this);
m_CheckMark->setObjectName("TimeZoneCheckMark");
m_CheckMark->setAcceptedMouseButtons(0);
m_CheckMark->setVisible(false);
// m_GreySeparator
m_GraySeparator = new DuiSeparator(this);
mainLayout->addItem(m_CheckMark, 0,1, 2,1, Qt::AlignCenter);
mainLayout->addItem(m_GraySeparator, 2,0, 1,2, Qt::AlignRight);
}
void TimeZoneListItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
DuiWidget::mousePressEvent(event);
event->accept();
emit clicked(this);
}
void TimeZoneListItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
DuiWidget::mouseReleaseEvent(event);
event->accept();
}
<|endoftext|> |
<commit_before>// @(#)root/gl:$Name: $:$Id: TSocket.h,v 1.20 2005/07/29 14:26:51 rdm Exp $
// Author: Matevz Tadel 7/4/2006
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifdef WIN32
#include "Windows4root.h"
#endif
#include "TPointSet3DGL.h"
#include "TPointSet3D.h"
#include <GL/gl.h>
//______________________________________________________________________
// TPointSet3DGLRenderer
//
ClassImp(TPointSet3DGL)
//______________________________________________________________________________
TPointSet3DGL::TPointSet3DGL() : TGLObject()
{}
//______________________________________________________________________________
Bool_t TPointSet3DGL::SetModel(TObject* obj)
{
Bool_t is_class = set_model(obj, "TPointSet3D");
if (is_class) {
set_axis_aligned_bbox(((TPointSet3D*)fExternalObj)->AssertBBox());
}
return is_class;
}
//______________________________________________________________________________
void TPointSet3DGL::SetBBox()
{
set_axis_aligned_bbox(((TPointSet3D*)fExternalObj)->AssertBBox());
}
//______________________________________________________________________________
void TPointSet3DGL::DirectDraw(const TGLDrawFlags & /*flags*/) const
{
// printf("TPointSet3DGL::DirectDraw Style %d, LOD %d\n", flags.Style(), flags.LOD());
TPointSet3D& Q = * (TPointSet3D*) fExternalObj;
if (Q.GetN() <= 0) return;
Int_t Qms = Q.GetMarkerStyle();
glPushAttrib(GL_POINT_BIT | GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
if (Qms == 20 || Qms == 21) { // 20 ~ full scalable circle; 21 ~ fs square
glEnable(GL_BLEND);
glPointSize(Q.GetMarkerSize());
}
if (Q.GetMarkerStyle() == 20) {
glEnable(GL_POINT_SMOOTH);
} else {
glDisable(GL_POINT_SMOOTH);
}
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
glVertexPointer(3, GL_FLOAT, 0, Q.GetP());
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_POINTS, 0, Q.GetN());
glPopClientAttrib();
glPopAttrib();
}
<commit_msg>From Matevz: Removed bounding-box code forgotten in SetModel() after introducing SetBBox().<commit_after>// @(#)root/gl:$Name: $:$Id: TPointSet3DGL.cxx,v 1.4 2006/04/07 09:20:43 rdm Exp $
// Author: Matevz Tadel 7/4/2006
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifdef WIN32
#include "Windows4root.h"
#endif
#include "TPointSet3DGL.h"
#include "TPointSet3D.h"
#include <GL/gl.h>
//______________________________________________________________________
// TPointSet3DGLRenderer
//
ClassImp(TPointSet3DGL)
//______________________________________________________________________________
TPointSet3DGL::TPointSet3DGL() : TGLObject()
{}
//______________________________________________________________________________
Bool_t TPointSet3DGL::SetModel(TObject* obj)
{
return set_model(obj, "TPointSet3D");
}
//______________________________________________________________________________
void TPointSet3DGL::SetBBox()
{
set_axis_aligned_bbox(((TPointSet3D*)fExternalObj)->AssertBBox());
}
//______________________________________________________________________________
void TPointSet3DGL::DirectDraw(const TGLDrawFlags & /*flags*/) const
{
// printf("TPointSet3DGL::DirectDraw Style %d, LOD %d\n", flags.Style(), flags.LOD());
TPointSet3D& Q = * (TPointSet3D*) fExternalObj;
if (Q.GetN() <= 0) return;
Int_t Qms = Q.GetMarkerStyle();
glPushAttrib(GL_POINT_BIT | GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
if (Qms == 20 || Qms == 21) { // 20 ~ full scalable circle; 21 ~ fs square
glEnable(GL_BLEND);
glPointSize(Q.GetMarkerSize());
}
if (Q.GetMarkerStyle() == 20) {
glEnable(GL_POINT_SMOOTH);
} else {
glDisable(GL_POINT_SMOOTH);
}
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
glVertexPointer(3, GL_FLOAT, 0, Q.GetP());
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_POINTS, 0, Q.GetN());
glPopClientAttrib();
glPopAttrib();
}
<|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 test suite 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 <QtCore/QtCore>
#include <QtTest/QtTest>
class tst_Headers: public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void privateSlots_data() { allHeadersData(); }
void privateSlots();
void macros_data() { allHeadersData(); }
void macros();
private:
static QStringList getHeaders(const QString &path);
void allHeadersData();
QStringList headers;
QString qtModuleDir;
};
QStringList tst_Headers::getHeaders(const QString &path)
{
QStringList result;
QProcess git;
git.setWorkingDirectory(path);
git.start("git", QStringList() << "ls-files");
// Wait for git to start
if (!git.waitForStarted())
qFatal("Error running 'git': %s", qPrintable(git.errorString()));
// Continue reading the data until EOF reached
QByteArray data;
while (git.waitForReadyRead(-1))
data.append(git.readAll());
// wait until the process has finished
if ((git.state() != QProcess::NotRunning) && !git.waitForFinished(30000))
qFatal("'git ls-files' did not complete within 30 seconds: %s", qPrintable(git.errorString()));
// Check for the git's exit code
if (0 != git.exitCode())
qFatal("Error running 'git ls-files': %s", qPrintable(git.readAllStandardError()));
// Create a QStringList of files out of the standard output
QString string(data);
QStringList entries = string.split( "\n" );
// We just want to check header files
entries = entries.filter(QRegExp("\\.h$"));
entries = entries.filter(QRegExp("^(?!ui_)"));
// Recreate the whole file path so we can open the file from disk
foreach (QString entry, entries)
result += path + "/" + entry;
return result;
}
void tst_Headers::initTestCase()
{
qtModuleDir = QString::fromLocal8Bit(qgetenv("QT_MODULE_TO_TEST"));
if (qtModuleDir.isEmpty()) {
QSKIP("$QT_MODULE_TO_TEST is unset - nothing to test. Set QT_MODULE_TO_TEST to the path "
"of a Qt module to test.");
}
if (!qtModuleDir.contains("phonon") && !qtModuleDir.contains("qttools")) {
QDir dir(qtModuleDir + "/src");
if (dir.exists())
headers = getHeaders(dir.absolutePath());
if (headers.isEmpty()) {
QSKIP("It seems there are no headers in this module; this test is "
"not applicable");
}
} else {
QWARN("Some test functions will be skipped, because we ignore them for phonon and qttools.");
}
}
void tst_Headers::allHeadersData()
{
QTest::addColumn<QString>("header");
if (headers.isEmpty())
QSKIP("can't find any headers in your $QT_MODULE_TO_TEST/src.");
foreach (QString hdr, headers) {
if (hdr.contains("/3rdparty/") || hdr.endsWith("/src/tools/uic/qclass_lib_map.h"))
continue;
QTest::newRow(qPrintable(hdr)) << hdr;
}
}
void tst_Headers::privateSlots()
{
QFETCH(QString, header);
if (header.endsWith("/qobjectdefs.h"))
return;
QFile f(header);
QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));
QStringList content = QString::fromLocal8Bit(f.readAll()).split("\n");
foreach (QString line, content) {
if (line.contains("Q_PRIVATE_SLOT("))
QVERIFY(line.contains("_q_"));
}
}
void tst_Headers::macros()
{
QFETCH(QString, header);
if (header.endsWith("_p.h") || header.endsWith("_pch.h")
|| header.contains("global/qconfig-") || header.endsWith("/qconfig.h")
|| header.contains("/src/tools/") || header.contains("/src/plugins/")
|| header.contains("/src/imports/")
|| header.contains("/src/uitools/")
|| header.endsWith("/qiconset.h") || header.endsWith("/qfeatures.h")
|| header.endsWith("qt_windows.h"))
return;
QFile f(header);
QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));
QByteArray data = f.readAll();
QStringList content = QString::fromLocal8Bit(data.replace('\r', "")).split("\n");
int beginHeader = content.indexOf("QT_BEGIN_HEADER");
int endHeader = content.lastIndexOf("QT_END_HEADER");
QVERIFY(beginHeader >= 0);
QVERIFY(endHeader >= 0);
QVERIFY(beginHeader < endHeader);
// "signals" and "slots" should be banned in public headers
// headers which use signals/slots wouldn't compile if Qt is configured with QT_NO_KEYWORDS
QVERIFY2(content.indexOf(QRegExp("\\bslots\\s*:")) == -1, "Header contains `slots' - use `Q_SLOTS' instead!");
QVERIFY2(content.indexOf(QRegExp("\\bsignals\\s*:")) == -1, "Header contains `signals' - use `Q_SIGNALS' instead!");
if (header.contains("/sql/drivers/") || header.contains("/arch/qatomic")
|| header.endsWith("qglobal.h")
|| header.endsWith("qwindowdefs_win.h"))
return;
int qtmodule = content.indexOf(QRegExp("^QT_MODULE\\(.*\\)$"));
QVERIFY(qtmodule != -1);
QVERIFY(qtmodule > beginHeader);
QVERIFY(qtmodule < endHeader);
int beginNamespace = content.indexOf("QT_BEGIN_NAMESPACE");
int endNamespace = content.lastIndexOf("QT_END_NAMESPACE");
QVERIFY(beginNamespace != -1);
QVERIFY(endNamespace != -1);
QVERIFY(beginHeader < beginNamespace);
QVERIFY(beginNamespace < endNamespace);
QVERIFY(endNamespace < endHeader);
}
QTEST_MAIN(tst_Headers)
#include "tst_headers.moc"
<commit_msg>tst_headers: put relative, not absolute, paths in the failure message<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 test suite 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 <QtCore/QtCore>
#include <QtTest/QtTest>
class tst_Headers: public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void privateSlots_data() { allHeadersData(); }
void privateSlots();
void macros_data() { allHeadersData(); }
void macros();
private:
static QStringList getHeaders(const QString &path);
void allHeadersData();
QStringList headers;
QString qtModuleDir;
};
QStringList tst_Headers::getHeaders(const QString &path)
{
QStringList result;
QProcess git;
git.setWorkingDirectory(path);
git.start("git", QStringList() << "ls-files");
// Wait for git to start
if (!git.waitForStarted())
qFatal("Error running 'git': %s", qPrintable(git.errorString()));
// Continue reading the data until EOF reached
QByteArray data;
while (git.waitForReadyRead(-1))
data.append(git.readAll());
// wait until the process has finished
if ((git.state() != QProcess::NotRunning) && !git.waitForFinished(30000))
qFatal("'git ls-files' did not complete within 30 seconds: %s", qPrintable(git.errorString()));
// Check for the git's exit code
if (0 != git.exitCode())
qFatal("Error running 'git ls-files': %s", qPrintable(git.readAllStandardError()));
// Create a QStringList of files out of the standard output
QString string(data);
QStringList entries = string.split( "\n" );
// We just want to check header files
entries = entries.filter(QRegExp("\\.h$"));
entries = entries.filter(QRegExp("^(?!ui_)"));
// Recreate the whole file path so we can open the file from disk
foreach (QString entry, entries)
result += path + "/" + entry;
return result;
}
void tst_Headers::initTestCase()
{
qtModuleDir = QString::fromLocal8Bit(qgetenv("QT_MODULE_TO_TEST"));
if (qtModuleDir.isEmpty()) {
QSKIP("$QT_MODULE_TO_TEST is unset - nothing to test. Set QT_MODULE_TO_TEST to the path "
"of a Qt module to test.");
}
QDir dir(qtModuleDir);
QString module = dir.dirName(); // git module name, e.g. qtbase, qtdeclarative
if (module != "phonon" && module != "qttools") {
if (dir.exists("src")) {
/*
Let all paths be relative to the directory containing the module.
For example, if the full path is:
/home/qt/build/qt5/qtbase/src/corelib/tools/qstring.h
... the first part of the path is useless noise, and causes the
test log to look different on different machines.
Cut it down to only the important part:
qtbase/src/corelib/tools/qstring.h
*/
QVERIFY(QDir::setCurrent(dir.absolutePath() + "/.."));
headers = getHeaders(module + "/src");
}
if (headers.isEmpty()) {
QSKIP("It seems there are no headers in this module; this test is "
"not applicable");
}
} else {
QWARN("Some test functions will be skipped, because we ignore them for phonon and qttools.");
}
}
void tst_Headers::allHeadersData()
{
QTest::addColumn<QString>("header");
if (headers.isEmpty())
QSKIP("can't find any headers in your $QT_MODULE_TO_TEST/src.");
foreach (QString hdr, headers) {
if (hdr.contains("/3rdparty/") || hdr.endsWith("/src/tools/uic/qclass_lib_map.h"))
continue;
QTest::newRow(qPrintable(hdr)) << hdr;
}
}
void tst_Headers::privateSlots()
{
QFETCH(QString, header);
if (header.endsWith("/qobjectdefs.h"))
return;
QFile f(header);
QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));
QStringList content = QString::fromLocal8Bit(f.readAll()).split("\n");
foreach (QString line, content) {
if (line.contains("Q_PRIVATE_SLOT("))
QVERIFY(line.contains("_q_"));
}
}
void tst_Headers::macros()
{
QFETCH(QString, header);
if (header.endsWith("_p.h") || header.endsWith("_pch.h")
|| header.contains("global/qconfig-") || header.endsWith("/qconfig.h")
|| header.contains("/src/tools/") || header.contains("/src/plugins/")
|| header.contains("/src/imports/")
|| header.contains("/src/uitools/")
|| header.endsWith("/qiconset.h") || header.endsWith("/qfeatures.h")
|| header.endsWith("qt_windows.h"))
return;
QFile f(header);
QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString()));
QByteArray data = f.readAll();
QStringList content = QString::fromLocal8Bit(data.replace('\r', "")).split("\n");
int beginHeader = content.indexOf("QT_BEGIN_HEADER");
int endHeader = content.lastIndexOf("QT_END_HEADER");
QVERIFY(beginHeader >= 0);
QVERIFY(endHeader >= 0);
QVERIFY(beginHeader < endHeader);
// "signals" and "slots" should be banned in public headers
// headers which use signals/slots wouldn't compile if Qt is configured with QT_NO_KEYWORDS
QVERIFY2(content.indexOf(QRegExp("\\bslots\\s*:")) == -1, "Header contains `slots' - use `Q_SLOTS' instead!");
QVERIFY2(content.indexOf(QRegExp("\\bsignals\\s*:")) == -1, "Header contains `signals' - use `Q_SIGNALS' instead!");
if (header.contains("/sql/drivers/") || header.contains("/arch/qatomic")
|| header.endsWith("qglobal.h")
|| header.endsWith("qwindowdefs_win.h"))
return;
int qtmodule = content.indexOf(QRegExp("^QT_MODULE\\(.*\\)$"));
QVERIFY(qtmodule != -1);
QVERIFY(qtmodule > beginHeader);
QVERIFY(qtmodule < endHeader);
int beginNamespace = content.indexOf("QT_BEGIN_NAMESPACE");
int endNamespace = content.lastIndexOf("QT_END_NAMESPACE");
QVERIFY(beginNamespace != -1);
QVERIFY(endNamespace != -1);
QVERIFY(beginHeader < beginNamespace);
QVERIFY(beginNamespace < endNamespace);
QVERIFY(endNamespace < endHeader);
}
QTEST_MAIN(tst_Headers)
#include "tst_headers.moc"
<|endoftext|> |
<commit_before>2d162354-2e3a-11e5-b65f-c03896053bdd<commit_msg>2d25dd9e-2e3a-11e5-b6e8-c03896053bdd<commit_after>2d25dd9e-2e3a-11e5-b6e8-c03896053bdd<|endoftext|> |
<commit_before>21c81158-585b-11e5-8f73-6c40088e03e4<commit_msg>21cf9d1a-585b-11e5-9253-6c40088e03e4<commit_after>21cf9d1a-585b-11e5-9253-6c40088e03e4<|endoftext|> |
<commit_before>2022615a-2e3a-11e5-80bd-c03896053bdd<commit_msg>2031cd78-2e3a-11e5-8d2f-c03896053bdd<commit_after>2031cd78-2e3a-11e5-8d2f-c03896053bdd<|endoftext|> |
<commit_before>ba553edc-2e4f-11e5-8bb8-28cfe91dbc4b<commit_msg>ba5ce719-2e4f-11e5-ba80-28cfe91dbc4b<commit_after>ba5ce719-2e4f-11e5-ba80-28cfe91dbc4b<|endoftext|> |
<commit_before>5f894a06-2d16-11e5-af21-0401358ea401<commit_msg>5f894a07-2d16-11e5-af21-0401358ea401<commit_after>5f894a07-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5055a858-5216-11e5-9fb3-6c40088e03e4<commit_msg>505c18ee-5216-11e5-b23c-6c40088e03e4<commit_after>505c18ee-5216-11e5-b23c-6c40088e03e4<|endoftext|> |
<commit_before>ac0e0126-2e4f-11e5-814f-28cfe91dbc4b<commit_msg>ac14d1c0-2e4f-11e5-9ac7-28cfe91dbc4b<commit_after>ac14d1c0-2e4f-11e5-9ac7-28cfe91dbc4b<|endoftext|> |
<commit_before>#ifndef K3_RUNTIME_IOHANDLE_HPP
#define K3_RUNTIME_IOHANDLE_HPP
#include <memory>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/line.hpp>
#include <runtime/cpp/Common.hpp>
#include <runtime/cpp/Network.hpp>
namespace K3
{
using namespace std;
using namespace boost::iostreams;
//--------------------------
// IO handles
class IOHandle : public virtual LogMT
{
public:
typedef tuple<shared_ptr<Codec >, shared_ptr<Net::NEndpoint> > SourceDetails;
typedef tuple<shared_ptr<Codec >, shared_ptr<Net::NConnection> > SinkDetails;
IOHandle(shared_ptr<Codec > cdec) : LogMT("IOHandle"), codec(cdec) {}
virtual bool hasRead() = 0;
virtual shared_ptr<Value> doRead() = 0;
virtual bool hasWrite() = 0;
virtual void doWrite(Value& v) = 0;
virtual void close() = 0;
virtual bool builtin() = 0;
virtual bool file() = 0;
virtual SourceDetails networkSource() = 0;
virtual SinkDetails networkSink() = 0;
protected:
shared_ptr<Codec > codec;
};
class split_line_filter : public line_filter {
public:
split_line_filter() {}
string do_filter(const string& line) { return line; }
};
class LineInputHandle : public virtual LogMT
{
public:
template<typename Source>
LineInputHandle(const Source& src) : LogMT("LineInputHandle") {
input = shared_ptr<filtering_istream>(new filtering_istream());
input->push(split_line_filter());
input->push(src);
}
bool hasRead() { return input? input->good() : false; }
shared_ptr<string> doRead() {
if ( !input ) { return shared_ptr<string>(); }
stringstream r;
(*input) >> r.rdbuf();
return shared_ptr<string>(new string(r.str()));
}
bool hasWrite() {
BOOST_LOG(*this) << "Invalid write operation on input handle";
return false;
}
void doWrite(string& data) {
BOOST_LOG(*this) << "Invalid write operation on input handle";
}
// Invoke the destructor on the filtering_istream, which in
// turn closes all associated iostream filters and devices.
void close() { if ( input ) { input->reset(); } }
protected:
shared_ptr<filtering_istream> input;
};
class LineOutputHandle : public virtual LogMT
{
public:
template<typename Sink>
LineOutputHandle(const Sink& sink) : LogMT("LineOutputHandle") {
output = shared_ptr<filtering_ostream>(new filtering_ostream());
output->push(split_line_filter());
output->push(sink);
}
bool hasRead() {
BOOST_LOG(*this) << "Invalid read operation on output handle";
return false;
}
shared_ptr<string> doRead() {
BOOST_LOG(*this) << "Invalid read operation on output handle";
return shared_ptr<string>();
}
bool hasWrite() { return output? output->good() : false; }
void doWrite(string& data) { if ( output ) { (*output) << data; } }
void close() { if ( output ) { output->reset(); } }
protected:
shared_ptr<filtering_ostream> output;
};
class LineBasedHandle : public IOHandle
{
public:
struct Input {};
struct Output {};
template<typename Source>
LineBasedHandle(shared_ptr<Codec > cdec, Input i, const Source& src)
: LogMT("LineBasedHandle"), IOHandle(cdec)
{
inImpl = shared_ptr<LineInputHandle>(new LineInputHandle(src));
}
template<typename Sink>
LineBasedHandle(shared_ptr<Codec > cdec, Output o, const Sink& sink)
: LogMT("LineBasedHandle"), IOHandle(cdec)
{
outImpl = shared_ptr<LineOutputHandle>(new LineOutputHandle(sink));
}
bool hasRead() {
bool r = false;
if ( inImpl ) { r = inImpl->hasRead(); }
else { BOOST_LOG(*this) << "Invalid hasRead on LineBasedHandle"; }
return r;
}
bool hasWrite() {
bool r = false;
if ( outImpl ) { r = outImpl->hasWrite(); }
else { BOOST_LOG(*this) << "Invalid hasWrite on LineBasedHandle"; }
return r;
}
shared_ptr<Value> doRead() {
shared_ptr<Value> r;
if ( inImpl && this->codec ) {
shared_ptr<string> data = inImpl->doRead();
r = this->codec->decode(*data);
}
else { BOOST_LOG(*this) << "Invalid doRead on LineBasedHandle"; }
return r;
}
void doWrite(Value& v) {
if ( outImpl && this->codec ) {
string data = this->codec->encode(v);
outImpl->doWrite(data);
}
else { BOOST_LOG(*this) << "Invalid doWrite on LineBasedHandle"; }
}
void close() {
if ( inImpl ) { inImpl->close(); }
else if ( outImpl ) { outImpl->close(); }
}
protected:
shared_ptr<LineInputHandle> inImpl;
shared_ptr<LineOutputHandle> outImpl;
};
// TODO
//class MultiLineHandle;
//class FrameBasedHandle;
class BuiltinHandle : public LineBasedHandle
{
public:
struct Stdin {};
struct Stdout {};
struct Stderr {};
BuiltinHandle(shared_ptr<Codec > cdec, Stdin s)
: LogMT("BuiltinHandle"), LineBasedHandle(cdec, typename LineBasedHandle::Input(), cin)
{}
BuiltinHandle(shared_ptr<Codec > cdec, Stdout s)
: LogMT("BuiltinHandle"), LineBasedHandle(cdec, typename LineBasedHandle::Output(), cout)
{}
BuiltinHandle(shared_ptr<Codec > cdec, Stderr s)
: LogMT("BuiltinHandle"), LineBasedHandle(cdec, typename LineBasedHandle::Output(), cerr)
{}
bool builtin () { return true; }
bool file() { return false; }
typename IOHandle::SourceDetails
networkSource() {
return make_tuple(shared_ptr<Codec >(), shared_ptr<Net::NEndpoint>());
}
typename IOHandle::SinkDetails
networkSink() {
return make_tuple(shared_ptr<Codec >(), shared_ptr<Net::NConnection>());
}
};
class FileHandle : public LineBasedHandle
{
public:
FileHandle(shared_ptr<Codec > cdec, const string& path,
typename LineBasedHandle::Input i)
: LogMT("FileHandle"), LineBasedHandle(cdec, i, file_source(path))
{}
FileHandle(shared_ptr<Codec > cdec, const string& path,
typename LineBasedHandle::Output o)
: LogMT("FileHandle"), LineBasedHandle(cdec, o, file_sink(path))
{}
bool builtin () { return false; }
bool file() { return true; }
typename IOHandle::SourceDetails
networkSource() {
return make_tuple(shared_ptr<Codec >(), shared_ptr<Net::NEndpoint>());
}
typename IOHandle::SinkDetails
networkSink() {
return make_tuple(shared_ptr<Codec >(), shared_ptr<Net::NConnection>());
}
};
class NetworkHandle : public IOHandle
{
public:
NetworkHandle(shared_ptr<Codec > cdec, shared_ptr<Net::NConnection> c) : LogMT("NetworkHandle"), connection(c), IOHandle(cdec) {}
NetworkHandle(shared_ptr<Codec > cdec, shared_ptr<Net::NEndpoint> e) : LogMT("NetworkHandle"), endpoint(e), IOHandle(cdec) {}
bool hasRead() {
BOOST_LOG(*this) << "Invalid hasRead on NetworkHandle";
return false;
}
bool hasWrite() {
bool r = false;
if ( connection ) { r = connection->good(); }
else { BOOST_LOG(*this) << "Invalid hasWrite on NetworkHandle"; }
return r;
}
shared_ptr<Value> doRead() {
BOOST_LOG(*this) << "Invalid doRead on NetworkHandle";
return shared_ptr<Value>();
}
void doWrite(Value& v) {
if ( connection && this->codec ) {
string data = this->codec->encode(v);
(*connection) << data;
}
else { BOOST_LOG(*this) << "Invalid doWrite on NetworkHandle"; }
}
void close() {
if ( connection ) { connection->close(); }
else if ( endpoint ) { endpoint->close(); }
}
bool builtin () { return false; }
bool file() { return false; }
typename IOHandle::SourceDetails
networkSource() {
shared_ptr<Codec > cdec = endpoint? this->codec : shared_ptr<Codec >();
return make_tuple(cdec, endpoint);
}
typename IOHandle::SinkDetails
networkSink() {
shared_ptr<Codec > cdec = connection? this->codec : shared_ptr<Codec >();
return make_tuple(cdec, connection);
}
protected:
shared_ptr<Net::NConnection> connection;
shared_ptr<Net::NEndpoint> endpoint;
};
}
#endif
<commit_msg>Fixed partial template specialization issues with IOHandle<commit_after>#ifndef K3_RUNTIME_IOHANDLE_HPP
#define K3_RUNTIME_IOHANDLE_HPP
#include <memory>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/line.hpp>
#include <runtime/cpp/Common.hpp>
#include <runtime/cpp/Network.hpp>
namespace K3
{
using namespace std;
using namespace boost::iostreams;
//--------------------------
// IO handles
class IOHandle : public virtual LogMT
{
public:
typedef tuple<shared_ptr<Codec>, shared_ptr<Net::NEndpoint> > SourceDetails;
typedef tuple<shared_ptr<Codec>, shared_ptr<Net::NConnection> > SinkDetails;
IOHandle(shared_ptr<Codec> cdec) : LogMT("IOHandle"), codec(cdec) {}
virtual bool hasRead() = 0;
virtual shared_ptr<Value> doRead() = 0;
virtual bool hasWrite() = 0;
virtual void doWrite(Value& v) = 0;
virtual void close() = 0;
virtual bool builtin() = 0;
virtual bool file() = 0;
virtual SourceDetails networkSource() = 0;
virtual SinkDetails networkSink() = 0;
protected:
shared_ptr<Codec> codec;
};
class split_line_filter : public line_filter {
public:
split_line_filter() {}
string do_filter(const string& line) { return line; }
};
class LineInputHandle : public virtual LogMT
{
public:
template<typename Source>
LineInputHandle(Source& src) : LogMT("LineInputHandle")
{
input = shared_ptr<filtering_istream>(new filtering_istream());
input->push(split_line_filter());
input->push(src);
}
bool hasRead() { return input? input->good() : false; }
shared_ptr<string> doRead() {
if ( !input ) { return shared_ptr<string>(); }
stringstream r;
(*input) >> r.rdbuf();
return shared_ptr<string>(new string(r.str()));
}
bool hasWrite() {
BOOST_LOG(*this) << "Invalid write operation on input handle";
return false;
}
void doWrite(string& data) {
BOOST_LOG(*this) << "Invalid write operation on input handle";
}
// Invoke the destructor on the filtering_istream, which in
// turn closes all associated iostream filters and devices.
void close() { if ( input ) { input->reset(); } }
protected:
shared_ptr<filtering_istream> input;
};
class LineOutputHandle : public virtual LogMT
{
public:
template<typename Sink>
LineOutputHandle(Sink& sink) : LogMT("LineOutputHandle")
{
output = shared_ptr<filtering_ostream>(new filtering_ostream());
output->push(split_line_filter());
output->push(sink);
}
bool hasRead() {
BOOST_LOG(*this) << "Invalid read operation on output handle";
return false;
}
shared_ptr<string> doRead() {
BOOST_LOG(*this) << "Invalid read operation on output handle";
return shared_ptr<string>();
}
bool hasWrite() { return output? output->good() : false; }
void doWrite(string& data) { if ( output ) { (*output) << data; } }
void close() { if ( output ) { output->reset(); } }
protected:
shared_ptr<filtering_ostream> output;
};
class LineBasedHandle : public IOHandle
{
public:
struct Input {};
struct Output {};
template<typename Source>
LineBasedHandle(shared_ptr<Codec> cdec, Input i, Source& src)
: LogMT("LineBasedHandle"), IOHandle(cdec)
{
inImpl = shared_ptr<LineInputHandle>(new LineInputHandle(src));
}
template<typename Sink>
LineBasedHandle(shared_ptr<Codec> cdec, Output o, Sink& sink)
: LogMT("LineBasedHandle"), IOHandle(cdec)
{
outImpl = shared_ptr<LineOutputHandle>(new LineOutputHandle(sink));
}
bool hasRead() {
bool r = false;
if ( inImpl ) { r = inImpl->hasRead(); }
else { BOOST_LOG(*this) << "Invalid hasRead on LineBasedHandle"; }
return r;
}
bool hasWrite() {
bool r = false;
if ( outImpl ) { r = outImpl->hasWrite(); }
else { BOOST_LOG(*this) << "Invalid hasWrite on LineBasedHandle"; }
return r;
}
shared_ptr<Value> doRead() {
shared_ptr<Value> r;
if ( inImpl && this->codec ) {
shared_ptr<string> data = inImpl->doRead();
r = this->codec->decode(*data);
}
else { BOOST_LOG(*this) << "Invalid doRead on LineBasedHandle"; }
return r;
}
void doWrite(Value& v) {
if ( outImpl && this->codec ) {
string data = this->codec->encode(v);
outImpl->doWrite(data);
}
else { BOOST_LOG(*this) << "Invalid doWrite on LineBasedHandle"; }
}
void close() {
if ( inImpl ) { inImpl->close(); }
else if ( outImpl ) { outImpl->close(); }
}
protected:
shared_ptr<LineInputHandle> inImpl;
shared_ptr<LineOutputHandle> outImpl;
};
// TODO
//class MultiLineHandle;
//class FrameBasedHandle;
class BuiltinHandle : public LineBasedHandle
{
public:
struct Stdin {};
struct Stdout {};
struct Stderr {};
BuiltinHandle(shared_ptr<Codec> cdec, Stdin s)
: LogMT("BuiltinHandle"), LineBasedHandle(cdec, LineBasedHandle::Input(), cin)
{}
BuiltinHandle(shared_ptr<Codec> cdec, Stdout s)
: LogMT("BuiltinHandle"), LineBasedHandle(cdec, LineBasedHandle::Output(), cout)
{}
BuiltinHandle(shared_ptr<Codec> cdec, Stderr s)
: LogMT("BuiltinHandle"), LineBasedHandle(cdec, LineBasedHandle::Output(), cerr)
{}
bool builtin () { return true; }
bool file() { return false; }
IOHandle::SourceDetails networkSource()
{
return make_tuple(shared_ptr<Codec>(), shared_ptr<Net::NEndpoint>());
}
IOHandle::SinkDetails networkSink()
{
return make_tuple(shared_ptr<Codec>(), shared_ptr<Net::NConnection>());
}
};
class FileHandle : public LineBasedHandle
{
public:
FileHandle(shared_ptr<Codec> cdec, const string& path, LineBasedHandle::Input i)
: fileSrc(shared_ptr<file_source>(new file_source(path))),
LogMT("FileHandle"), LineBasedHandle(cdec, i, *fileSrc)
{}
FileHandle(shared_ptr<Codec> cdec, const string& path, LineBasedHandle::Output o)
: fileSink(shared_ptr<file_sink>(new file_sink(path))),
LogMT("FileHandle"), LineBasedHandle(cdec, o, *fileSink)
{}
bool builtin () { return false; }
bool file() { return true; }
IOHandle::SourceDetails networkSource()
{
return make_tuple(shared_ptr<Codec>(), shared_ptr<Net::NEndpoint>());
}
IOHandle::SinkDetails networkSink()
{
return make_tuple(shared_ptr<Codec>(), shared_ptr<Net::NConnection>());
}
private:
shared_ptr<file_source> fileSrc;
shared_ptr<file_sink> fileSink;
};
class NetworkHandle : public IOHandle
{
public:
NetworkHandle(shared_ptr<Codec> cdec, shared_ptr<Net::NConnection> c)
: LogMT("NetworkHandle"), connection(c), IOHandle(cdec)
{}
NetworkHandle(shared_ptr<Codec> cdec, shared_ptr<Net::NEndpoint> e)
: LogMT("NetworkHandle"), endpoint(e), IOHandle(cdec)
{}
bool hasRead() {
BOOST_LOG(*this) << "Invalid hasRead on NetworkHandle";
return false;
}
bool hasWrite() {
bool r = false;
if ( connection ) { r = connection->good(); }
else { BOOST_LOG(*this) << "Invalid hasWrite on NetworkHandle"; }
return r;
}
shared_ptr<Value> doRead() {
BOOST_LOG(*this) << "Invalid doRead on NetworkHandle";
return shared_ptr<Value>();
}
void doWrite(Value& v) {
if ( connection && this->codec ) {
string data = this->codec->encode(v);
(*connection) << data;
}
else { BOOST_LOG(*this) << "Invalid doWrite on NetworkHandle"; }
}
void close() {
if ( connection ) { connection->close(); }
else if ( endpoint ) { endpoint->close(); }
}
bool builtin () { return false; }
bool file() { return false; }
IOHandle::SourceDetails networkSource()
{
shared_ptr<Codec> cdec = endpoint? this->codec : shared_ptr<Codec>();
return make_tuple(cdec, endpoint);
}
IOHandle::SinkDetails networkSink()
{
shared_ptr<Codec> cdec = connection? this->codec : shared_ptr<Codec>();
return make_tuple(cdec, connection);
}
protected:
shared_ptr<Net::NConnection> connection;
shared_ptr<Net::NEndpoint> endpoint;
};
}
#endif
<|endoftext|> |
<commit_before>/** Copyright (c) 2013, Sean Kasun */
#include <QtWidgets/QApplication>
#include <QTranslator>
#include <QLocale>
#include "./minutor.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QString locale = QLocale::system().name();
QTranslator translator;
translator.load(QString("minutor_")+locale);
app.installTranslator(&translator);
app.setApplicationName("Minutor");
app.setApplicationVersion("2.2.0");
app.setOrganizationName("seancode");
Minutor minutor;
// Process the cmdline arguments:
QStringList args = app.arguments();
int numArgs = args.size();
int ex_Xmin = 0;
int ex_Xmax = 0;
int ex_Zmin = 0;
int ex_Zmax = 0;
bool regionChecker = false;
bool chunkChecker = false;
for (int i = 0; i < numArgs; i++) {
if (args[i].length() > 2) {
// convert long variants to lower case
args[i] = args[i].toLower();
}
if ((args[i] == "-w" || args[i] == "--world") && i + 1 < numArgs) {
minutor.loadWorld(args[i + 1]);
i += 1;
continue;
}
if (args[i] == "--regionchecker") {
regionChecker = true;
continue;
}
if (args[i] == "--chunkchecker") {
chunkChecker = true;
continue;
}
if ((args[i] == "-r" || args[i] == "--exportrange") && i + 4 < numArgs) {
ex_Xmin = args[i + 1].toInt();
ex_Xmax = args[i + 2].toInt();
ex_Zmin = args[i + 3].toInt();
ex_Zmax = args[i + 4].toInt();
i += 4;
continue;
}
if ((args[i] == "-s" || args[i] == "--savepng") && i + 1 < numArgs) {
minutor.savePNG(args[i + 1], true, regionChecker, chunkChecker,
ex_Zmin, ex_Xmin, ex_Zmax, ex_Xmax);
i += 1;
continue;
}
if ((args[i] == "-j" || args[i] == "--jump") && i + 2 < numArgs) {
minutor.jumpToXZ(args[i + 1].toInt(), args[i + 2].toInt());
i += 2;
continue;
}
if ((args[i] == "-y" || args[i] == "--depth") && i + 1 < numArgs) {
minutor.setDepth(args[i + 1].toInt());
i += 1;
continue;
}
// menu View->
if (args[i] == "-L" || args[i] == "--lighting") {
minutor.setViewLighting(true);
continue;
}
if (args[i] == "-M" || args[i] == "--mobspawning") {
minutor.setViewMobspawning(true);
continue;
}
if (args[i] == "-D" || args[i] == "--depthshading") {
minutor.setViewDepthshading(true);
continue;
}
if (args[i] == "-B" || args[i] == "--biomecolors") {
minutor.setViewBiomeColors(true);
continue;
}
if (args[i] == "-C" || args[i] == "--cavemode") {
minutor.setViewCavemode(true);
continue;
}
}
minutor.show();
return app.exec();
}
<commit_msg>for sl<commit_after>/** Copyright (c) 2013, Sean Kasun */
#include <QtWidgets/QApplication>
#include <QTranslator>
#include <QLocale>
#include "./minutor.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QString locale = QLocale::system().name();
QTranslator translator;
translator.load(QString("minutor_")+locale);
app.installTranslator(&translator);
app.setApplicationName("Minutor");
app.setApplicationVersion("2.2.0");
app.setOrganizationName("seancode");
Minutor minutor;
// Process the cmdline arguments:
QStringList args = app.arguments();
int numArgs = args.size();
int ex_Xmin = 0;
int ex_Xmax = 0;
int ex_Zmin = 0;
int ex_Zmax = 0;
bool regionChecker = false;
bool chunkChecker = false;
for (int i = 0; i < numArgs; i++) {
if (args[i].length() > 2) {
// convert long variants to lower case
args[i] = args[i].toLower();
}
if ((args[i] == "-w" || args[i] == "--world") && i + 1 < numArgs) {
minutor.loadWorld(args[i + 1]);
i += 1;
continue;
}
if (args[i] == "--regionchecker") {
regionChecker = true;
continue;
}
if (args[i] == "--chunkchecker") {
chunkChecker = true;
continue;
}
if ((args[i] == "-r" || args[i] == "--exportrange") && i + 4 < numArgs) {
ex_Xmin = args[i + 1].toInt();
ex_Xmax = args[i + 2].toInt();
ex_Zmin = args[i + 3].toInt();
ex_Zmax = args[i + 4].toInt();
i += 4;
continue;
}
if ((args[i] == "-s" || args[i] == "--savepng") && i + 1 < numArgs) {
minutor.savePNG(args[i + 1], true, regionChecker, chunkChecker,
ex_Zmin, ex_Xmin, ex_Zmax, ex_Xmax);
i += 1;
continue;
}
if ((args[i] == "-j" || args[i] == "--jump") && i + 2 < numArgs) {
minutor.jumpToXZ(args[i + 1].toInt(), args[i + 2].toInt());
i += 2;
continue;
}
if ((args[i] == "-y" || args[i] == "--depth") && i + 1 < numArgs) {
minutor.setDepth(args[i + 1].toInt());
i += 1;
continue;
}
// menu View->
if (args[i] == "-L" || args[i] == "--lighting") {
minutor.setViewLighting(true);
continue;
}
if (args[i] == "-M" || args[i] == "--mobspawning") {
minutor.setViewMobspawning(true);
continue;
}
if (args[i] == "-D" || args[i] == "--depthshading") {
minutor.setViewDepthshading(true);
continue;
}
if (args[i] == "-B" || args[i] == "--biomecolors") {
minutor.setViewBiomeColors(true);
continue;
}
if (args[i] == "-C" || args[i] == "--cavemode") {
minutor.setViewCavemode(true);
continue;
}
if (args[i] == "-sl" || args[i] == "--singlelayer")) {
minutor.setSingleLayer(true);
continue;
}
}
minutor.show();
return app.exec();
}
<|endoftext|> |
<commit_before>8fd04988-2d14-11e5-af21-0401358ea401<commit_msg>8fd04989-2d14-11e5-af21-0401358ea401<commit_after>8fd04989-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>cd4259eb-2e4e-11e5-81b7-28cfe91dbc4b<commit_msg>cd4a58cc-2e4e-11e5-84c2-28cfe91dbc4b<commit_after>cd4a58cc-2e4e-11e5-84c2-28cfe91dbc4b<|endoftext|> |
<commit_before>4d0e6238-2e4f-11e5-89ac-28cfe91dbc4b<commit_msg>4d1763cf-2e4f-11e5-9701-28cfe91dbc4b<commit_after>4d1763cf-2e4f-11e5-9701-28cfe91dbc4b<|endoftext|> |
<commit_before>b73ee01a-35ca-11e5-8b34-6c40088e03e4<commit_msg>b74595a4-35ca-11e5-bdb7-6c40088e03e4<commit_after>b74595a4-35ca-11e5-bdb7-6c40088e03e4<|endoftext|> |
<commit_before>8a7f8907-2e4f-11e5-b1b6-28cfe91dbc4b<commit_msg>8a88214c-2e4f-11e5-84fc-28cfe91dbc4b<commit_after>8a88214c-2e4f-11e5-84fc-28cfe91dbc4b<|endoftext|> |
<commit_before>952e76c0-ad5a-11e7-b16f-ac87a332f658<commit_msg>Bug fixes and performance improvements<commit_after>95d55c38-ad5a-11e7-914b-ac87a332f658<|endoftext|> |
<commit_before>809e921d-2d15-11e5-af21-0401358ea401<commit_msg>809e921e-2d15-11e5-af21-0401358ea401<commit_after>809e921e-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8d6dfcf8-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcf9-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcf9-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
<commit_msg>Set window icon<commit_after>#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
app.setWindowIcon(QIcon(":/pictures/polygon_area.png"));
MainWindow window;
window.show();
return app.exec();
}
<|endoftext|> |
<commit_before>c9d3d966-4b02-11e5-aa18-28cfe9171a43<commit_msg>I hope I am done<commit_after>c9e1f10f-4b02-11e5-9710-28cfe9171a43<|endoftext|> |
<commit_before>e1e1e0e8-313a-11e5-942a-3c15c2e10482<commit_msg>e1e7adfd-313a-11e5-87d1-3c15c2e10482<commit_after>e1e7adfd-313a-11e5-87d1-3c15c2e10482<|endoftext|> |
<commit_before>63992840-2e3a-11e5-aa5a-c03896053bdd<commit_msg>63a69822-2e3a-11e5-a195-c03896053bdd<commit_after>63a69822-2e3a-11e5-a195-c03896053bdd<|endoftext|> |
<commit_before>f07cd068-2e4e-11e5-8d4e-28cfe91dbc4b<commit_msg>f083fe42-2e4e-11e5-9b1f-28cfe91dbc4b<commit_after>f083fe42-2e4e-11e5-9b1f-28cfe91dbc4b<|endoftext|> |
<commit_before>5e58942d-2d16-11e5-af21-0401358ea401<commit_msg>5e58942e-2d16-11e5-af21-0401358ea401<commit_after>5e58942e-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>2cb03d36-2f67-11e5-b687-6c40088e03e4<commit_msg>2cb6edc0-2f67-11e5-bdc6-6c40088e03e4<commit_after>2cb6edc0-2f67-11e5-bdc6-6c40088e03e4<|endoftext|> |
<commit_before>cce421a8-327f-11e5-8e9e-9cf387a8033e<commit_msg>cce9ce0a-327f-11e5-aac6-9cf387a8033e<commit_after>cce9ce0a-327f-11e5-aac6-9cf387a8033e<|endoftext|> |
<commit_before>e2c165ee-4b02-11e5-a387-28cfe9171a43<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>e2d0b67a-4b02-11e5-a6dd-28cfe9171a43<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Jeremy Letang
//
// 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 <iostream>
#include <utility>
#include <vector>
#include <string>
#include <sstream>
// c terminal utility
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
// CLimg library
#include <CImg.h>
namespace preview {
namespace term {
struct size {
unsigned int column;
unsigned int row;
size(unsigned int column, unsigned int row)
: column(column), row(row) {}
};
size get_term_size() {
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
return {w.ws_col, w.ws_row};
}
struct color {
float r,g,b;
bool fg;
color() = delete;
color(uint8_t r, uint8_t g, uint8_t b, bool fg = false)
: r(static_cast<float>(r) / 255. * 5.)
, g(static_cast<float>(g) / 255. * 5.)
, b(static_cast<float>(b) / 255. * 5.)
, fg(fg) {}
static color from_float(float r_, float g_, float b_, bool fg_ = false) {
auto this_ = color{0, 0, 0};
this_.r = r_;
this_.g = g_;
this_.b = b_;
this_.fg = fg_;
return this_;
}
};
struct clear_t {};
static clear_t clear;
template <typename CharT, typename Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os, const color& c) {
unsigned int _c = 16. + 36. * c.r + 6. * c.g + c.b;
if (not c.fg) {os << "\x1b[48;5;" << _c << "m";}
else {os << "\x1b[38;5;" << _c << "m";}
return os;
}
template <typename CharT, typename Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os, const clear_t&) {
os << "\x1b[39;49;00m";
return os;
}
std::pair<bool, cimg_library::CImg<float>> load_img(const std::string& path) try {
auto i = cimg_library::CImg<float>(path.c_str());
return std::make_pair(true, i);
} catch (...) {
std::cout << color{255, 0, 0, true} << "error" << clear << ": "
<< "no such file " << path << ", or unsupported image file format." << std::endl;
return std::make_pair(false, cimg_library::CImg<float>());
}
struct arguments {
std::vector<std::string> filenames;
bool h;
arguments() = default;
arguments(std::vector<std::string> filenames, bool h = false)
: filenames(filenames), h(h) {}
~arguments() = default;
};
std::pair<int, arguments> parse_cmdline(int ac, char* av[]) {
auto args = arguments{};
int index;
int c;
opterr = 0;
while ((c = getopt (ac, av, "h")) != -1) {
switch (c) {
case 'h': args.h = true; break;
case '?':
if (isprint(optopt)) {
std::cout << color{255, 0, 0, true} << "error" << clear << ": "
<< "unknown option -" << static_cast<char>(optopt) << std::endl;
}
return std::make_pair(1, args);
default: return std::make_pair(0, args);
}
}
for (index = optind; index < ac; index++) {
args.filenames.push_back(av[index]);
}
return std::make_pair(0, args);
}
void print_help(const std::string& program_name) {
std::cout << "usage: " << program_name << " [imgs ...] -h" << std::endl;
}
const auto red_value = 0;
const auto green_value = 1;
const auto blue_value = 2;
void print_one(unsigned int x,
unsigned int y,
unsigned int x_lag,
unsigned int y_lag,
const cimg_library::CImg<float>& img,
std::stringstream& ss) {
auto x_end = x+x_lag;
auto y_end = y+y_lag;
auto acc_red = 0;
auto acc_green = 0;
auto acc_blue = 0;
auto x_iter = x;
auto y_iter = y;
int i = 0;
while ((x_iter < x_end)) {
y_iter = y;
while (y_iter < y_end) {
i+=1;
acc_red += img(x_iter, y_iter, 0, red_value);
acc_green += img(x_iter, y_iter, 0, green_value);
acc_blue += img(x_iter, y_iter, blue_value);
y_iter += 1;
}
x_iter += 1;
}
acc_red = acc_red / (x_lag*y_lag);
acc_green = acc_green / (x_lag*y_lag);
acc_blue = acc_blue / (x_lag*y_lag);
auto c = color{
static_cast<uint8_t>(acc_red),
static_cast<uint8_t>(acc_green),
static_cast<uint8_t>(acc_blue)
};
ss << c << " " << clear;
}
void print_image(cimg_library::CImg<float>& img) {
auto ss = std::stringstream{};
auto term_size = get_term_size();
img.resize(term_size.column/2, -((term_size.column/2.)/img.width()*100));
auto img_width = img.width();
auto img_height = img.height();
auto x = 0;
auto y = 0;
while (y < img_height) {
x = 0;
while (x < img_width) {
auto red_bg = static_cast<uint8_t>(img(x, y, 0, red_value));
auto green_bg = static_cast<uint8_t>(img(x, y, 0, green_value));
auto blue_bg = static_cast<uint8_t>(img(x, y, blue_value));
auto red_fg = static_cast<uint8_t>(img(x, y+1, 0, red_value));
auto green_fg = static_cast<uint8_t>(img(x, y+1, 0, green_value));
auto blue_fg = static_cast<uint8_t>(img(x, y+1, blue_value));
ss << color{red_bg, green_bg, blue_bg} << color{red_fg, green_fg, blue_fg, true}
<< "\u2584" << clear;
x+=1;
}
ss << std::endl;
y+=2;
}
std::cout << ss.str() << std::endl;
}
}}
int main (int ac, char* av[]) {
// get commandline arguments
auto args = preview::term::parse_cmdline(ac, av);
// an error occured, exit
if (args.first not_eq 0) { return EXIT_FAILURE; }
// if h == true display help
if (args.first == 0 and args.second.h == true) {
preview::term::print_help(av[0]);
return 0;
}
// if no files specified
if (args.second.filenames.empty()) {
std::cout << preview::term::color{255, 0, 0, true} << "error" << preview::term::clear << ": "
<< "preview needs at least one input file" << std::endl;
return EXIT_FAILURE;
}
auto img = preview::term::load_img(args.second.filenames[0]);
preview::term::print_image(img.second);
if (not img.first) { return EXIT_FAILURE; }
}<commit_msg>working + clean some stuff.<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Jeremy Letang
//
// 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 <iostream>
#include <utility>
#include <vector>
#include <string>
#include <sstream>
// c terminal utility
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
// CLimg library
#include <CImg.h>
namespace preview {
namespace term {
struct size {
unsigned int column;
unsigned int row;
size(unsigned int column, unsigned int row)
: column(column), row(row) {}
};
size get_term_size() {
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
return {w.ws_col, w.ws_row};
}
struct color {
uint8_t r,g,b;
bool fg;
color() = delete;
color(uint8_t r, uint8_t g, uint8_t b, bool fg = false)
: r(static_cast<uint8_t>(r) / 255. * 5.)
, g(static_cast<uint8_t>(g) / 255. * 5.)
, b(static_cast<uint8_t>(b) / 255. * 5.)
, fg(fg) {}
};
struct clear_t {};
static clear_t clear;
template <typename CharT, typename Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os, const color& c) {
unsigned int _c = 16 + 36 * c.r + 6 * c.g + c.b;
if (not c.fg) {os << "\x1b[48;5;" << _c << "m";}
else {os << "\x1b[38;5;" << _c << "m";}
return os;
}
template <typename CharT, typename Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os, const clear_t&) {
os << "\x1b[39;49;00m";
return os;
}
std::pair<bool, cimg_library::CImg<float>> load_img(const std::string& path) try {
auto i = cimg_library::CImg<float>(path.c_str());
return std::make_pair(true, i);
} catch (...) {
std::cout << color{255, 0, 0, true} << "error" << clear << ": "
<< "no such file " << path << ", or unsupported image file format." << std::endl;
return std::make_pair(false, cimg_library::CImg<float>());
}
struct arguments {
std::vector<std::string> filenames;
bool h;
arguments() = default;
arguments(std::vector<std::string> filenames, bool h = false)
: filenames(filenames), h(h) {}
~arguments() = default;
};
std::pair<int, arguments> parse_cmdline(int ac, char* av[]) {
auto args = arguments{};
int index;
int c;
opterr = 0;
while ((c = getopt (ac, av, "h")) != -1) {
switch (c) {
case 'h': args.h = true; break;
case '?':
if (isprint(optopt)) {
std::cout << color{255, 0, 0, true} << "error" << clear << ": "
<< "unknown option -" << static_cast<char>(optopt) << std::endl;
}
return std::make_pair(1, args);
default: return std::make_pair(0, args);
}
}
for (index = optind; index < ac; index++) {
args.filenames.push_back(av[index]);
}
return std::make_pair(0, args);
}
void print_help(const std::string& program_name) {
std::cout << "usage: " << program_name << " [imgs ...] -h" << std::endl;
}
void print_image(cimg_library::CImg<float>& img) {
// get rgb inside a pixel
const auto red_value = 0;
const auto green_value = 1;
const auto blue_value = 2;
// output
auto ss = std::stringstream{};
auto term_size = get_term_size();
// resize the image
img.resize(term_size.column/2, -((term_size.column/2.)/img.width()*100));
auto x = 0;
auto y = 0;
while (y < img.height()) {
x = 0;
while (x < img.width()) {
auto red_fg = static_cast<uint8_t>(img(x, y, 0, red_value));
auto green_fg = static_cast<uint8_t>(img(x, y, 0, green_value));
auto blue_fg = static_cast<uint8_t>(img(x, y, blue_value));
ss << color{red_fg, green_fg, blue_fg, true};
// if we always are on the image
if (y+1 < img.height()) {
auto red_bg = static_cast<uint8_t>(img(x, y+1, 0, red_value));
auto green_bg = static_cast<uint8_t>(img(x, y+1, 0, green_value));
auto blue_bg = static_cast<uint8_t>(img(x, y+1, blue_value));
ss << color{red_bg, green_bg, blue_bg} << "\u2580";
} else { // use the same color thant y for y+1
ss << " ";
}
ss << clear;
x+=1;
}
ss << "\n";
y+=2;
}
std::cout << ss.str() << std::endl;
}
}}
int main (int ac, char* av[]) {
// get commandline arguments
auto args = preview::term::parse_cmdline(ac, av);
// an error occured, exit
if (args.first not_eq 0) { return EXIT_FAILURE; }
// if h == true display help
if (args.first == 0 and args.second.h == true) {
preview::term::print_help(av[0]);
return 0;
}
// if no files specified
if (args.second.filenames.empty()) {
std::cout << preview::term::color{255, 0, 0, true} << "error" << preview::term::clear << ": "
<< "preview needs at least one input file" << std::endl;
return EXIT_FAILURE;
}
auto img = preview::term::load_img(args.second.filenames[0]);
if (not img.first) { return EXIT_FAILURE; }
preview::term::print_image(img.second);
}<|endoftext|> |
<commit_before>
#include<stdio.h>
#include<dos.h>
#include<conio.h>
#include<graphics.h>
#include<time.h>
unsigned int offs, seg;
union REGS ur;
union REGS urOut;
struct SREGS sr;
union REGS reg, oreg;
struct SREGS sreg;
// fonction de creation d'un dossier
void creerDossier(char *path){
disable();
reg.h.ah = 0x39;
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
printf("Repertoire bien cree \n");
getch();
}else if(reg.x.cflag==1){
if(reg.x.ax==2){
printf("Chemin introuvable\n");
getch();
}
else if(reg.x.ax==5){
printf("Pas de permissions\n");
getch();
}
else{
printf("NON GERE");
getch();
}
}
enable();
}
void supprimerDossier(char * path){
union REGS reg, oreg;
struct SREGS sreg;
reg.h.ah = 0x3a;
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
printf("Sous-repertoire supprime avec succes\n");
getch();
}else if(reg.x.cflag==1){
if(reg.x.ax==2){
printf("Chemin introuvable\n");
getch();
}
else if(reg.x.ax==5){
printf("Pas de permissions\n");
getch();
}
else{
printf("Erreur de suppression");
getch();
}
}
}
/* changer de repertoire courant */
void changerDeDossier(char* path){
disable();
reg.h.ah = 0x3b;
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
printf("Cette valeur permet d'indiquer que le sous-répertoire a été changé avec succès\n");
getch();
}else if(reg.x.cflag==1){
if(reg.x.ax==2)
printf("Chemin introuvable\n");
else
printf("Cas non pris en compte\n");
getch();
}
enable();
}
void dossierCourant(char * path){
disable();
reg.h.ah = 0x47;
reg.h.dl = 0; //unite de disque courante
reg.x.si = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
//printf("");
//getch();
}else if(reg.x.cflag==1){
if(reg.x.ax==15)
printf("Unite de disque inconnue\n");
getch();
}
enable();
}
void creerFichier(char * path){
disable();
reg.h.ah = 0x3c;
reg.x.cx = 0;//attribut du fichier
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
// printf("Fichier bien crée\n");
//getch();
}else if(reg.x.cflag==1){
if(reg.x.ax==3)
printf("Chemin introuvable\n");
else if(reg.x.ax==4)
printf("il y a trop de fichiers ouverts simultanément\n");
else if(reg.x.ax==5)
printf("accès refusé\n");
getch();
}
enable();
}
int ouvrirFichier(char * path){
int handle=-1;
disable();
reg.h.ah = 0x3d;
//reg.h.al = 2; //fichier lu et ecrit 010
//reg.h.al = reg.h.al|(3; //autre programme peut lire et écrit le fichier 011
reg.h.al = 4*64+2;
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,&oreg,&sreg);
if(oreg.x.cflag==0){
// printf("ouverture du fichier a été un succès\n");
handle=oreg.x.ax;
//getch();
}else if(oreg.x.cflag==1){
if(oreg.x.ax==1)
printf(" numéro de la fonction n'est pas valide et que vous n'avez pas de logiciel de partage de fichier\n");
else if(oreg.x.ax==3)
printf("chemin est introuvable\n");
else if(oreg.x.ax==4)
printf("il y a trop de fichiers ouverts simultanément\n");
else if(oreg.x.ax==5)
printf("accès refusé\n");
else if(oreg.x.ax==12)
printf("code d'accès est incorrecte\n");
getch();
}
enable();
return handle;
}
void fermerFichier(char * path, int handle){
disable();
reg.h.ah = 0x3e;
reg.x.bx = handle; //descripteur du fichier
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,&oreg,&sreg);
if(oreg.x.cflag==0){
}else if(oreg.x.cflag==1){
if(oreg.x.ax==1)
printf(" numéro de la fonction n'est pas valide et que vous n'avez pas de logiciel de partage de fichier\n");
else if(oreg.x.ax==3)
printf("chemin est introuvable\n");
else if(oreg.x.ax==4)
printf("il y a trop de fichiers ouverts simultanément\n");
else if(oreg.x.ax==5)
printf("accès refusé\n");
else if(oreg.x.ax==12)
printf("code d'accès est incorrecte\n");
getch();
}
enable();
}
void supprimerFichier(char * path){
disable();
reg.h.ah = 0x41;
reg.x.cx = 0;//attribut du fichier
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
//printf("Fichier bien supprime\n");
//getch();
}else if(reg.x.cflag==1){
if(reg.x.ax==2)
printf("Chemin introuvable\n");
else if(reg.x.ax==5)
printf("accès refusé\n");
getch();
}
enable();
}
int ecrireFichier(char *path, char * data){
int taille = strlen(data); //nombre de bytes des donnees
//ouvrir le fichier et recuperer le descripteur
int handle = ouvrirFichierPourAction(path);
//nombre de bytes écrits avec succes
int nb_data_write =0;
disable();
reg.h.ah = 0x40;
reg.x.bx = handle; //descripteur du fichier
reg.x.cx = taille; //nombre d'octets a ecrire
reg.x.dx = FP_OFF(data); //adresse de l'offset des donnees
sreg.ds = FP_SEG(data); //adresse du segment des donnees
intdosx(®,&oreg,&sreg);
if(oreg.x.cflag==0){
// printf("L'ecriture du fichier s'est fait avec succès\n");
nb_data_write = oreg.x.ax;
//getch();
}else if(oreg.x.cflag==1){
if(oreg.x.ax==6)
printf("Handle est inconnu\n");
else if(oreg.x.ax==5)
printf("accès refusé\n");
getch();
}
enable();
//fermer le fichier
fermerFichierPourAction(path, handle);
return nb_data_write;
}
char* lireFichier(char * path){
char* chaine = "";
int nb_read=0;
int prec=0, temp=0;
do{
nb_read += 100;
prec = temp;
temp=lireUnePartieFichier(path, chaine, nb_read);
}while(temp != prec);
return chaine;
}
void renommerFichier(char * ancien_filename, char *nouveau_filename){
disable();
reg.h.ah = 0x56;
//ancien fichier
reg.x.dx = FP_OFF(ancien_filename); //adresse de l'offset
sreg.ds = FP_SEG(ancien_filename); //adresse du segment
//nouveau nom de fichier
reg.x.di = FP_OFF(nouveau_filename);
sreg.es = FP_SEG(nouveau_filename);
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
//printf("Fichier bien deplacer\n");
//getch();
}else if(reg.x.cflag==1){
if(reg.x.ax==2)
printf("Chemin introuvable\n");
else if(reg.x.ax==3)
printf("Chemin introuvable\n");
else if(reg.x.ax==5)
printf("accès refusé\n");
else if(reg.x.ax==11)
printf("format invalide\n");
getch();
}
enable();
}
void demanderAttribut(char * path_file){
int res = -1;
disable();
reg.h.ah = 0x4300;
printf(" la tete est");
//ancien fichier
reg.x.dx = FP_OFF(path_file); //adresse de l'offset
sreg.ds = FP_SEG(path_file); //adresse du segment
intdosx(®,®,&sreg);
if(reg.x.cflag==0){
res = reg.x.cx;
if(reg.x.cx == 1)
printf("Mode lecture seulement\n");
if(reg.x.cx == 2)
printf("Fichier en mode caché\n");
if(reg.x.cx == 4)
printf("Fichier en mode systeme\n");
if(reg.x.cx == 32)
printf("Fichier en mode archivage\n");
getch();
}
else if(reg.x.cflag==1){
if(reg.x.ax==1)
printf("fonction invalide\n");
else if(reg.x.ax==2)
printf("ficher introuvable\n");
else if(reg.x.ax==3)
printf("chemin introuvable\n");
getch();
}
enable();
}
int lireUnePartieFichier(char * path, char* data_read, int nb_read){
//ouvrir le fichier et recuperer le descripteur
int handle = ouvrirFichierPourAction(path);
int nb_data_read=0;
disable();
reg.h.ah = 0x3f;
reg.x.bx = handle; //descripteur du fichier
reg.x.cx = nb_read; //nombre d'octets a ecrire
reg.x.dx = FP_OFF(data_read); //adresse de l'offset
sreg.ds = FP_SEG(data_read); //adresse du segment
intdosx(®,&oreg,&sreg);
if(oreg.x.cflag==0){
//printf("L'ecriture du fichier a été un succès\n");
nb_data_read = oreg.x.ax;
// getch();
}else if(oreg.x.cflag==1){
if(oreg.x.ax==6)
printf("Handle est inconnu\n");
else if(oreg.x.ax==5)
printf("accès refusé\n");
getch();
}
enable();
fermerFichierPourAction(path, handle);
return nb_data_read;
}
int fermerFichierPourAction(char * path, int handle){
disable();
reg.h.ah = 0x3e;
reg.x.bx = handle; //descripteur du fichier
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,&oreg,&sreg);
enable();
return oreg.x.cflag;
}
int ouvrirFichierPourAction(char * path){
int handle=-1;
disable();
reg.h.ah = 0x3d;
//reg.h.al = 2; //fichier lu et ecrit 010
//reg.h.al = reg.h.al|(3; //autre programme peut lire et écrit le fichier 011
reg.h.al = 4*64+2;
reg.x.dx = FP_OFF(path); //adresse de l'offset
sreg.ds = FP_SEG(path); //adresse du segment
intdosx(®,&oreg,&sreg);
if(oreg.x.cflag==0){
handle=oreg.x.ax;
// getch();
}
enable();
return handle;
}
void get_date(){
ur.h.ah = 0x2A;
int86(0x21,&ur,&urOut);
printf("Date du jour : %d \/ %d \/ %d \n", _DL, _DH, _CX);
}
//fonction permettant de mettre à jour la date su système
const int set_date(unsigned int jour, unsigned int mois, unsigned int annee){
ur.h.ah = 0x2B;
ur.x.cx = annee;
ur.h.dh = mois;
ur.h.dl = jour;
int86(0x21, &ur, &urOut);
return ur.h.al;
}
//fonction permettant d'afficher l'heure du systeme
void get_heure(){
ur.h.ah = 0x2C;
int86(0x21,&ur,&urOut);
printf("\nHeure : %d: %d: %d", _CH, _CL, _DH);
}
//fonction permettant de mettre à jour l'heure su système
const int set_heure(unsigned int h, unsigned int mn, unsigned int secondes){
ur.h.ah = 0x2D;
ur.h.ch = h;
ur.h.cl = mn;
ur.h.dh = secondes;
int86(0x21, &ur, &urOut);
return ur.h.al;
}
void espacelibre(){
ur.h.ah = 0x36;
ur.h.dl = 3;//le numero du volume de disque
int86(021, &ur, &urOut);
printf("Nombre de secteur par cluster %d\n", ur.x.ax);
printf("Nombre de cluster encore libre %d\n", ur.x.bx);
printf("Nombre d'octect par secteurs %d\n", ur.x.cx);
printf("Nombre de clusters sur l'unite %d\n", ur.x.dx);
}
void disquecourant(){
ur.h.ah = 0x19;
int86(021, &ur, &urOut);
printf("le numero du disque courant est %d", ur.h.al );
}
void affichecurseur(){
ur.h.ah = 0x1;
ur.h.ch = 0x50;
ur.h.cl= 0x50;
int86(010, &ur, &urOut);
}
//fonction permettant de retourner l espace total du disque
const int espacetotal(){
ur.h.ah = 0x36;
ur.h.dl = 0;//le numero du volume de disque
int86(021, &ur, &urOut);
printf("\n%d", ur.x.ax);
printf("\n%d", ur.x.bx);
printf("\n%d", ur.x.cx);
printf("\n%d", ur.x.dx);
return ur.x.ax * ur.x.cx * ur.x.dx;
}
void affichePixel(unsigned x, unsigned y, char couleur){
char far *vga =(char far *)MK_FP(0xA000,0x0000);
*(vga + x + 320*y) = couleur;
}
int affichecouleure()
{
union REGS r_inreg;
int i=0,j=0,k=128;
_AX = 0x0013;
geninterrupt(0x10);
for (k =0 ; k < 255; k+=10)
{
for (i = 0; i <= 320; i++)
{
for(j = 0; j < 200; j++)
{
affichePixel(i,j,k);
}
}
_AX=0x0003;
// geninterrupt(0x10);
sleep(1);
}
return 0;
}
void initialiser(){
ur.x.ax = 0;
int86(033, &ur, &urOut);
}
void affichesouris(){
ur.x.ax = 7;
ur.x.cx = 50;
ur.x.dx = 50;
int86(0x33, &ur, &urOut);
}
int masquage() {
int res,cur,count=0;
clrscr();
res = inport(0x21);
printf("%2x\n",res);
while(count <= 15){
if (count == 5){
printf("\n Debut du blocage \n");
//cur = res & 0x00;
outport(0x21,res | 0x01);
}
else
if (count == 10){
printf("\n Fin du blocage \n");
outport(0x21,res);
}
printf("\n nbr interrupt = %d",clock());
delay(1000);
count++;
if (count==16){
printf("\n");
getch();
}
}
return 0;
}<commit_msg>Delete FONCTION.H<commit_after><|endoftext|> |
<commit_before>133c596c-585b-11e5-8a5f-6c40088e03e4<commit_msg>1344cbec-585b-11e5-8026-6c40088e03e4<commit_after>1344cbec-585b-11e5-8026-6c40088e03e4<|endoftext|> |
<commit_before>9595d59a-35ca-11e5-887c-6c40088e03e4<commit_msg>959cf94c-35ca-11e5-9a98-6c40088e03e4<commit_after>959cf94c-35ca-11e5-9a98-6c40088e03e4<|endoftext|> |
<commit_before>1645bdfa-2d3f-11e5-8133-c82a142b6f9b<commit_msg>169ef638-2d3f-11e5-b751-c82a142b6f9b<commit_after>169ef638-2d3f-11e5-b751-c82a142b6f9b<|endoftext|> |
<commit_before>//! \file
//! Entry point
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include "MainState.h"
#include "Renderer.h"
#include "InputHandler.h"
#include "NetworkManager.h"
static void change(MainState *¤tState, MainStateEnum nextState);
std::vector<MainState *> states;
int main()
{
Renderer::LoadFont("../prstartk.ttf");
Renderer::TileScale = 3.0f;
Renderer::SpriteScale = 3.0f;
Renderer::CreateWindow(768, 768, "My window");
states = std::vector<MainState *>(MAINSTATEENUM_NUMITEMS);
states[MainMenu] = new MainMenuState();
states[HostLobby] = new HostLobbyState();
states[HostGameplay] = new HostGameplayState();
states[Join] = new JoinState();
states[ClientWaiting] = new ClientWaitingState();
states[ClientConnected] = new ClientConnectedState();
states[Gameplay] = new GameplayState();
states[Exiting] = new ExitingState();
MainMenuState *State_MainMenu = (MainMenuState *)states[MainMenu];
HostLobbyState *State_HostLobby = (HostLobbyState *)states[HostLobby];
HostGameplayState *State_HostGameplay =
(HostGameplayState *)states[HostGameplay];
JoinState *State_Join = (JoinState *)states[Join];
ClientWaitingState *State_ClientWaiting =
(ClientWaitingState *)states[ClientWaiting];
ClientConnectedState *State_ClientConnected =
(ClientConnectedState *)states[ClientConnected];
GameplayState *State_Gameplay = (GameplayState *)states[Gameplay];
// Initialize state data
State_MainMenu->Index = 0;
State_MainMenu->Menu_EN.push_back("Host game");
State_MainMenu->Menu_EN.push_back("Join game");
State_MainMenu->Menu_EN.push_back("Quit");
MenuItem item1, item2, item3;
item1.Text = 0;
item1.Function = HostLobby;
State_MainMenu->MenuItems.push_back(item1);
item2.Text = 1;
item2.Function = Join;
State_MainMenu->MenuItems.push_back(item2);
item3.Text = 2;
item3.Function = Exiting;
State_MainMenu->MenuItems.push_back(item3);
State_Join->Index = 0;
std::string myAddress = NetworkManager::GetAddress();
std::stringstream addr(myAddress);
std::string part;
for (unsigned int i = 0; i < 4 && std::getline(addr, part, '.'); i++)
{
std::stringstream num(part);
unsigned short n;
num >> n;
State_Join->IP[i] = n;
}
State_Join->Port = 0;
State_ClientConnected->Index = 0;
// Initialize sprites
State_ClientConnected->PacmanSprite.Index =
Renderer::CreateSprite("../spritesheet.png");
Animation pac_move(4);
pac_move.AddFrame(1, 1, 16, 16);
pac_move.AddFrame(18, 1, 16, 16);
pac_move.AddFrame(35, 1, 16, 16);
pac_move.AddFrame(18, 1, 16, 16);
State_ClientConnected->PacmanSprite.Animations.push_back(pac_move);
Animation pac_die(4);
for (int i = 3; i <= 15; i++)
{
pac_die.AddFrame(1 + 17 * i, 1, 16, 16);
}
State_ClientConnected->PacmanSprite.Animations.push_back(pac_die);
State_ClientConnected->GhostSprites.resize(4);
for (unsigned int i = 0; i < 4; i++)
{
State_ClientConnected->GhostSprites[i].Index =
Renderer::CreateSprite("../spritesheet.png");
Animation gho_hori(8);
gho_hori.AddFrame(1, 18 + 17 * i, 16, 16);
gho_hori.AddFrame(18, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_hori);
Animation gho_up(8);
gho_up.AddFrame(35, 18 + 17 * i, 16, 16);
gho_up.AddFrame(52, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_up);
Animation gho_down(8);
gho_down.AddFrame(69, 18 + 17 * i, 16, 16);
gho_down.AddFrame(86, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_down);
Animation gho_fear(8);
gho_fear.AddFrame(205, 18 + 17 * i, 16, 16);
gho_fear.AddFrame(222, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_fear);
}
// Initialize NetworkManager
NetworkManager::Init();
// Start the state machine
MainState* currentState = states[MainMenu];
while (Renderer::WindowOpen())
{
InputHandler::PollEvents();
if (InputHandler::WindowClosed)
{
break;
}
change(currentState, currentState->ProcessData());
change(currentState, currentState->LocalUpdate());
Renderer::Clear();
currentState->Render();
Renderer::Display();
}
Renderer::Deinit();
return 0;
}
static void change(MainState *¤tState, MainStateEnum nextState)
{
if (currentState == states[nextState])
{
return;
}
if (nextState == HostLobby)
{
HostLobbyState *host = (HostLobbyState *)states[HostLobby];
host->PlayerCount = 0;
}
else if (nextState == HostGameplay)
{
HostLobbyState *host_lobby = (HostLobbyState *)states[HostLobby];
HostGameplayState *host_game = (HostGameplayState *)states[HostGameplay];
host_game->PlayerCount = host_lobby->PlayerCount;
host_game->Characters = host_lobby->Characters;
}
else if (nextState == ClientConnected)
{
ClientWaitingState *waiting =
(ClientWaitingState *)states[ClientWaiting];
ClientConnectedState *connected =
(ClientConnectedState *)states[ClientConnected];
connected->PlayerNumber = waiting->PlayerNumber;
connected->SelectedCharacter = PacMan;
connected->Ready = false;
connected->StartingGame = NULL;
}
else if (nextState == Gameplay)
{
ClientConnectedState *client =
(ClientConnectedState *)states[ClientConnected];
GameplayState *gameplay = (GameplayState *)states[Gameplay];
gameplay->Local = client->StartingGame;
gameplay->Synced = new Game(*gameplay->Local);
gameplay->PlayerNumber = client->PlayerNumber;
unsigned int count = gameplay->Local->Players.size();
gameplay->PlayerInputs = std::vector<std::vector<Position> >(
count, std::vector<Position>(InputData_size, Left));
gameplay->ReceivedFrames = std::vector<unsigned short>(count);
}
currentState = states[nextState];
}
<commit_msg>Fixed a server crash at game end<commit_after>//! \file
//! Entry point
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include "MainState.h"
#include "Renderer.h"
#include "InputHandler.h"
#include "NetworkManager.h"
static void change(MainState *¤tState, MainStateEnum nextState);
std::vector<MainState *> states;
int main()
{
Renderer::LoadFont("../prstartk.ttf");
Renderer::TileScale = 3.0f;
Renderer::SpriteScale = 3.0f;
Renderer::CreateWindow(768, 768, "My window");
states = std::vector<MainState *>(MAINSTATEENUM_NUMITEMS);
states[MainMenu] = new MainMenuState();
states[HostLobby] = new HostLobbyState();
states[HostGameplay] = new HostGameplayState();
states[Join] = new JoinState();
states[ClientWaiting] = new ClientWaitingState();
states[ClientConnected] = new ClientConnectedState();
states[Gameplay] = new GameplayState();
states[Exiting] = new ExitingState();
MainMenuState *State_MainMenu = (MainMenuState *)states[MainMenu];
HostLobbyState *State_HostLobby = (HostLobbyState *)states[HostLobby];
HostGameplayState *State_HostGameplay =
(HostGameplayState *)states[HostGameplay];
JoinState *State_Join = (JoinState *)states[Join];
ClientWaitingState *State_ClientWaiting =
(ClientWaitingState *)states[ClientWaiting];
ClientConnectedState *State_ClientConnected =
(ClientConnectedState *)states[ClientConnected];
GameplayState *State_Gameplay = (GameplayState *)states[Gameplay];
// Initialize state data
State_MainMenu->Index = 0;
State_MainMenu->Menu_EN.push_back("Host game");
State_MainMenu->Menu_EN.push_back("Join game");
State_MainMenu->Menu_EN.push_back("Quit");
MenuItem item1, item2, item3;
item1.Text = 0;
item1.Function = HostLobby;
State_MainMenu->MenuItems.push_back(item1);
item2.Text = 1;
item2.Function = Join;
State_MainMenu->MenuItems.push_back(item2);
item3.Text = 2;
item3.Function = Exiting;
State_MainMenu->MenuItems.push_back(item3);
State_Join->Index = 0;
std::string myAddress = NetworkManager::GetAddress();
std::stringstream addr(myAddress);
std::string part;
for (unsigned int i = 0; i < 4 && std::getline(addr, part, '.'); i++)
{
std::stringstream num(part);
unsigned short n;
num >> n;
State_Join->IP[i] = n;
}
State_Join->Port = 0;
State_ClientConnected->Index = 0;
// Initialize sprites
State_ClientConnected->PacmanSprite.Index =
Renderer::CreateSprite("../spritesheet.png");
Animation pac_move(4);
pac_move.AddFrame(1, 1, 16, 16);
pac_move.AddFrame(18, 1, 16, 16);
pac_move.AddFrame(35, 1, 16, 16);
pac_move.AddFrame(18, 1, 16, 16);
State_ClientConnected->PacmanSprite.Animations.push_back(pac_move);
Animation pac_die(4);
for (int i = 3; i <= 15; i++)
{
pac_die.AddFrame(1 + 17 * i, 1, 16, 16);
}
State_ClientConnected->PacmanSprite.Animations.push_back(pac_die);
State_ClientConnected->GhostSprites.resize(4);
for (unsigned int i = 0; i < 4; i++)
{
State_ClientConnected->GhostSprites[i].Index =
Renderer::CreateSprite("../spritesheet.png");
Animation gho_hori(8);
gho_hori.AddFrame(1, 18 + 17 * i, 16, 16);
gho_hori.AddFrame(18, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_hori);
Animation gho_up(8);
gho_up.AddFrame(35, 18 + 17 * i, 16, 16);
gho_up.AddFrame(52, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_up);
Animation gho_down(8);
gho_down.AddFrame(69, 18 + 17 * i, 16, 16);
gho_down.AddFrame(86, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_down);
Animation gho_fear(8);
gho_fear.AddFrame(205, 18 + 17 * i, 16, 16);
gho_fear.AddFrame(222, 18 + 17 * i, 16, 16);
State_ClientConnected->GhostSprites[i].Animations.push_back(gho_fear);
}
// Initialize NetworkManager
NetworkManager::Init();
// Start the state machine
MainState* currentState = states[MainMenu];
while (Renderer::WindowOpen())
{
InputHandler::PollEvents();
if (InputHandler::WindowClosed)
{
break;
}
change(currentState, currentState->ProcessData());
change(currentState, currentState->LocalUpdate());
Renderer::Clear();
currentState->Render();
Renderer::Display();
}
Renderer::Deinit();
return 0;
}
static void change(MainState *¤tState, MainStateEnum nextState)
{
if (currentState == states[nextState])
{
return;
}
if (nextState == HostLobby)
{
HostLobbyState *host = (HostLobbyState *)states[HostLobby];
host->PlayerCount = 0;
}
else if (nextState == HostGameplay)
{
HostLobbyState *host_lobby = (HostLobbyState *)states[HostLobby];
HostGameplayState *host_game = (HostGameplayState *)states[HostGameplay];
host_game->PlayerCount = host_lobby->PlayerCount;
host_game->Characters = host_lobby->Characters;
host_game->GameEnded = std::vector<bool>(host_game->PlayerCount);
}
else if (nextState == ClientConnected)
{
ClientWaitingState *waiting =
(ClientWaitingState *)states[ClientWaiting];
ClientConnectedState *connected =
(ClientConnectedState *)states[ClientConnected];
connected->PlayerNumber = waiting->PlayerNumber;
connected->SelectedCharacter = PacMan;
connected->Ready = false;
connected->StartingGame = NULL;
}
else if (nextState == Gameplay)
{
ClientConnectedState *client =
(ClientConnectedState *)states[ClientConnected];
GameplayState *gameplay = (GameplayState *)states[Gameplay];
gameplay->Local = client->StartingGame;
gameplay->Synced = new Game(*gameplay->Local);
gameplay->PlayerNumber = client->PlayerNumber;
unsigned int count = gameplay->Local->Players.size();
gameplay->PlayerInputs = std::vector<std::vector<Position> >(
count, std::vector<Position>(InputData_size, Left));
gameplay->ReceivedFrames = std::vector<unsigned short>(count);
}
currentState = states[nextState];
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
const int SIZE = 32;
const int NEURONS = 24;
const int TRAIN_ITER = 15;
const double sigma = 0.01;
double alpha = .1;
#define f first
#define s second
typedef pair<int,int> ii;
struct Matrix{
int digit;
double cells[SIZE][SIZE];
Matrix(){}
Matrix(double _cells[SIZE][SIZE]){
memcpy(cells,_cells,sizeof cells);
}
Matrix(double _cells[SIZE][SIZE],int _digit){
digit = _digit;
memcpy(cells,_cells,sizeof cells);
}
Matrix operator-(Matrix &o){
double r[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
r[i][j] = cells[i][j]-o[i][j];
return Matrix(r);
}
Matrix operator+(Matrix &o){
double r[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
r[i][j] = cells[i][j]+o[i][j];
return Matrix(r);
}
Matrix operator*(double scale){
double r[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
r[i][j] = cells[i][j]*scale;
return Matrix(r);
}
double* operator[](int i){
return cells[i];
}
void print(bool trunc){
for(int i = 0; i < SIZE; i++){
for(int j = 0; j < SIZE; j++)
if(trunc) printf("%d ",(int)(cells[i][j]+0.5));
else printf("%.4lf ",cells[i][j]);
printf("\n");
}
}
};
double sq_euclidean_distance(Matrix &a,Matrix &b){
double sq_distance = 0.;
for(int i = 0; i < SIZE; i++){
for(int j = 0; j < SIZE; j++){
double dij = a[i][j] - b[i][j];
sq_distance += dij*dij;
}
}
return sq_distance;
}
double sq_euclidean_distance(ii a,ii b){
double dx = a.f-b.f;
double dy = a.s-b.s;
return dx*dx+dy*dy;
}
vector<Matrix> train,test;
Matrix neurons[NEURONS][NEURONS];
void read_digits(vector<Matrix> &m,FILE *src){
int a;
fscanf(src,"%d\n",&a);
for (int i = 0,c; i < a; i++) {
double digit[SIZE][SIZE];
for(int j = 0; j < SIZE; j++){
for(int k = 0; k < SIZE; k++){
fscanf(src," %c",&c);
digit[j][k] = c-'0';
}
}
fscanf(src," %c ",&c);
m.push_back(Matrix(digit,c-'0'));
}
}
void init_neurons(){
srand(time(NULL));
for(int i = 0; i < NEURONS; i++)
for(int i2 = 0; i2 < NEURONS; i2++)
for(int j = 0; j < SIZE; j++)
for(int k = 0; k < SIZE; k++)
neurons[i][i2][j][k] = (double)rand() / RAND_MAX;
}
ii closest_neuron(Matrix &m){
ii BMU;
double min_dist = SIZE*SIZE;
for(int j = 0; j < NEURONS; j++)
for(int j2 = 0; j2 < NEURONS; j2++){
double dist_ji = sq_euclidean_distance(m,neurons[j][j2]);
if(dist_ji < min_dist){
BMU = ii(j,j2);
min_dist = dist_ji;
}
}
return BMU;
}
vector<int> randomic_order(int n){
list<int> elem;
for(int i = 0; i < n; i++) elem.push_back(i);
vector<int> order;
while(!elem.empty()){
auto it = elem.begin();
advance(it,rand()%elem.size());
order.push_back(*it);
elem.erase(it);
}
return order;
}
void train_neurons(){
vector<int> training_order = randomic_order(train.size());
for(int i = 0; i < (int)train.size(); i++){
ii BMU = closest_neuron(train[training_order[i]]);
//updating the neighborhood of BMU.
for(int j = 0; j < NEURONS; j++){
for(int j2 = 0; j2 < NEURONS; j2++){
double dist = sq_euclidean_distance(BMU,ii(j,j2));
Matrix shift = (train[i]-neurons[j][j2])*pow(M_E, -dist/sigma)*alpha;
neurons[j][j2] = neurons[j][j2] + shift;
}
}
}
}
int matches[NEURONS][NEURONS];
void print_matches(){
int frequence[10];
memset(frequence,0,sizeof(frequence));
for(int i = 0; i < NEURONS; i++){
for(int i2 = 0; i2 < NEURONS; i2++){
int mn = 0;
double mn_dist = sq_euclidean_distance(neurons[i][i2],train[mn]);
for(int j = 1; j < (int)train.size(); j++){
double dist = sq_euclidean_distance(neurons[i][i2],train[j]);
if(mn_dist > dist){
mn = j;
mn_dist = dist;
}
}
printf("%d %d\n",i,i2);
neurons[i][i2].print(true);
printf("\n");
train[mn].print(true);
frequence[train[mn].digit]++;
matches[i][i2] = train[mn].digit;
printf("\n");
}
}
for(int i = 0; i < 10; i++) printf("%d %d\n",i,frequence[i]);
for(int i = 0; i < NEURONS; i++){
for(int i2 = 0; i2 < NEURONS; i2++)
printf("%d ",matches[i][i2]);
printf("\n");
}
}
void load_neurons(string dir){
FILE *neurons_file = fopen(dir.c_str(),"r");
for(int i = 0; i < NEURONS; i++)
for(int i2 = 0; i2 < NEURONS; i2++) {
double w;
double digit[SIZE][SIZE];
for(int j = 0; j < SIZE; j++)
for(int k = 0; k < SIZE; k++){
fscanf(neurons_file," %lf",&w);
digit[j][k] = w;
}
neurons[i][i2] = Matrix(digit);
}
fclose(neurons_file);
}
void save_neurons(string dir){
}
//--tes path/to/test/file
//--tra path/to/training/file
//--lnet path/to/load/trained_neurons/file
//--snet path/to/save/trained_neurons/file
int main(int argc, char const *argv[]) {
map<string,string> param;
for(int i = 1; i < argc; i += 2) param[argv[i]] = argv[i+1];
if(param.find("--lnet") != param.end()) load_neurons(param["--lnet"]);
else init_neurons();
if(param.find("--tra") != param.end()){
//reading training set
FILE *training_file = fopen(param["--tra"].c_str(),"r");
read_digits(train,training_file);
fclose(training_file);
for(int l = 0; alpha > 0 && l < TRAIN_ITER; l++, alpha -= .0001)
train_neurons();
print_matches();
}
if(param.find("--tes") != param.end()){
//reading testing set
FILE *testing_file = fopen(param["--tes"].c_str(),"r");
read_digits(test,testing_file);
fclose(testing_file);
}
if(param.find("--snet") != param.end()) save_neurons(param["--snet"]);
return 0;
}
<commit_msg>Done save_neurons function.<commit_after>#include <bits/stdc++.h>
using namespace std;
const int SIZE = 32;
const int NEURONS = 10;
const int TRAIN_ITER = 1;
const double sigma = 0.01;
double alpha = .1;
#define f first
#define s second
typedef pair<int,int> ii;
struct Matrix{
int digit;
double cells[SIZE][SIZE];
Matrix(){}
Matrix(double _cells[SIZE][SIZE]){
memcpy(cells,_cells,sizeof cells);
}
Matrix(double _cells[SIZE][SIZE],int _digit){
digit = _digit;
memcpy(cells,_cells,sizeof cells);
}
Matrix operator-(Matrix &o){
double r[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
r[i][j] = cells[i][j]-o[i][j];
return Matrix(r);
}
Matrix operator+(Matrix &o){
double r[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
r[i][j] = cells[i][j]+o[i][j];
return Matrix(r);
}
Matrix operator*(double scale){
double r[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
r[i][j] = cells[i][j]*scale;
return Matrix(r);
}
double* operator[](int i){
return cells[i];
}
void print(bool trunc){
for(int i = 0; i < SIZE; i++){
for(int j = 0; j < SIZE; j++)
if(trunc) printf("%d ",(int)(cells[i][j]+0.5));
else printf("%.4lf ",cells[i][j]);
printf("\n");
}
}
};
double sq_euclidean_distance(Matrix &a,Matrix &b){
double sq_distance = 0.;
for(int i = 0; i < SIZE; i++){
for(int j = 0; j < SIZE; j++){
double dij = a[i][j] - b[i][j];
sq_distance += dij*dij;
}
}
return sq_distance;
}
double sq_euclidean_distance(ii a,ii b){
double dx = a.f-b.f;
double dy = a.s-b.s;
return dx*dx+dy*dy;
}
vector<Matrix> train,test;
Matrix neurons[NEURONS][NEURONS];
void read_digits(vector<Matrix> &m,FILE *src){
int a;
fscanf(src,"%d\n",&a);
for (int i = 0,c; i < a; i++) {
double digit[SIZE][SIZE];
for(int j = 0; j < SIZE; j++){
for(int k = 0; k < SIZE; k++){
fscanf(src," %c",&c);
digit[j][k] = c-'0';
}
}
fscanf(src," %c ",&c);
m.push_back(Matrix(digit,c-'0'));
}
}
void init_neurons(){
printf("Inicializando rede.\n");
srand(time(NULL));
for(int i = 0; i < NEURONS; i++)
for(int i2 = 0; i2 < NEURONS; i2++)
for(int j = 0; j < SIZE; j++)
for(int k = 0; k < SIZE; k++)
neurons[i][i2][j][k] = ((double)rand()) / RAND_MAX;
}
ii closest_neuron(Matrix &m){
ii BMU;
double min_dist = SIZE*SIZE;
for(int j = 0; j < NEURONS; j++)
for(int j2 = 0; j2 < NEURONS; j2++){
double dist_ji = sq_euclidean_distance(m,neurons[j][j2]);
if(dist_ji < min_dist){
BMU = ii(j,j2);
min_dist = dist_ji;
}
}
return BMU;
}
vector<int> randomic_order(int n){
list<int> elem;
for(int i = 0; i < n; i++) elem.push_back(i);
vector<int> order;
while(!elem.empty()){
auto it = elem.begin();
advance(it,rand()%elem.size());
order.push_back(*it);
elem.erase(it);
}
return order;
}
void train_neurons(){
printf("Treinando rede.\n");
vector<int> training_order = randomic_order(train.size());
for(int i = 0; i < (int)train.size(); i++){
ii BMU = closest_neuron(train[training_order[i]]);
//updating the neighborhood of BMU.
for(int j = 0; j < NEURONS; j++){
for(int j2 = 0; j2 < NEURONS; j2++){
double dist = sq_euclidean_distance(BMU,ii(j,j2));
Matrix shift = (train[i]-neurons[j][j2])*pow(M_E, -dist/sigma)*alpha;
neurons[j][j2] = neurons[j][j2] + shift;
}
}
}
}
int matches[NEURONS][NEURONS];
void print_matches(){
int frequence[10];
memset(frequence,0,sizeof(frequence));
for(int i = 0; i < NEURONS; i++){
for(int i2 = 0; i2 < NEURONS; i2++){
int mn = 0;
double mn_dist = sq_euclidean_distance(neurons[i][i2],train[mn]);
for(int j = 1; j < (int)train.size(); j++){
double dist = sq_euclidean_distance(neurons[i][i2],train[j]);
if(mn_dist > dist){
mn = j;
mn_dist = dist;
}
}
printf("%d %d\n",i,i2);
neurons[i][i2].print(true);
printf("\n");
train[mn].print(true);
frequence[train[mn].digit]++;
matches[i][i2] = train[mn].digit;
printf("\n");
}
}
for(int i = 0; i < 10; i++) printf("%d %d\n",i,frequence[i]);
for(int i = 0; i < NEURONS; i++){
for(int i2 = 0; i2 < NEURONS; i2++)
printf("%d ",matches[i][i2]);
printf("\n");
}
}
void load_neurons(string dir){
printf("Carregando rede.\n");
FILE *neurons_file = fopen(dir.c_str(),"r");
for(int i = 0; i < NEURONS; i++)
for(int i2 = 0; i2 < NEURONS; i2++) {
double w;
double digit[SIZE][SIZE];
for(int j = 0; j < SIZE; j++)
for(int k = 0; k < SIZE; k++){
fscanf(neurons_file," %lf",&w);
digit[j][k] = w;
}
neurons[i][i2] = Matrix(digit);
}
fclose(neurons_file);
}
void save_neurons(string dir){
printf("Salvando rede.\n");
FILE *neurons_file = fopen(dir.c_str(),"w");
for(int i = 0; i < NEURONS; i++)
for(int i2 = 0; i2 < NEURONS; i2++){
for(int j = 0; j < SIZE; j++){
for(int k = 0; k < SIZE; k++)
fprintf(neurons_file," %lf",neurons[i][i2][j][k]);
fprintf(neurons_file,"\n");
}
fprintf(neurons_file,"\n");
}
fclose(neurons_file);
}
//--tes path/to/test/file
//--tra path/to/training/file
//--lnet path/to/load/trained_neurons/file
//--snet path/to/save/trained_neurons/file
int main(int argc, char const *argv[]) {
map<string,string> param;
for(int i = 1; i < argc; i += 2) param[argv[i]] = argv[i+1];
if(param.find("--lnet") != param.end()) load_neurons(param["--lnet"]);
else init_neurons();
if(param.find("--tra") != param.end()){
//reading training set
FILE *training_file = fopen(param["--tra"].c_str(),"r");
read_digits(train,training_file);
fclose(training_file);
for(int l = 0; alpha > 0 && l < TRAIN_ITER; l++, alpha -= .0001)
train_neurons();
//print_matches();
}
if(param.find("--tes") != param.end()){
//reading testing set
FILE *testing_file = fopen(param["--tes"].c_str(),"r");
read_digits(test,testing_file);
fclose(testing_file);
}
if(param.find("--snet") != param.end()) save_neurons(param["--snet"]);
return 0;
}
<|endoftext|> |
<commit_before>fbb69f8f-2e4e-11e5-9109-28cfe91dbc4b<commit_msg>fbbe2235-2e4e-11e5-b9d5-28cfe91dbc4b<commit_after>fbbe2235-2e4e-11e5-b9d5-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <curl/curl.h>
#include <vector>
using std::string;
using std::cout;
struct pair {
string key, value;
pair() {}
pair(string k, string v) {
key = k;
value = v;
}
bool operator<(const pair &other) const {
if (key == other.key) {
return value < other.value;
}
return key < other.key;
}
string to_string() { return key + "=" + value; }
};
const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}
string gen_alphanum(int len) {
string buff;
std::srand(time(0));
for (int i = 0; i < len; i++) {
buff += ASCII_TABLE[std::rand() % 62];
}
return buff;
}
void sort_min(std::vector<string> &src) {
for (int i = 0; i + 1 < src.size(); i++) {
std::vector<string> sub(src.begin(), src.begin() + i + 1);
for (int j = 0; j < sub.size(); j++) {
if (sub[j] > src[i + 1]) {
std::swap(src[j], src[i + 1]);
}
}
}
}
int main() {
string username;
cout << "Enter Twitter Username: ";
getline(std::cin, username);
::pair app_info[8] = {::pair("screen_name", username),
::pair("oauth_consumer_key", username),
::pair("oauth_nonce", gen_alphanum(42)),
::pair("oauth_signature", ""),
::pair("oauth_signature_method", "HMAC_SHA1"),
::pair("oauth_timestamp", std::to_string(time(0))),
::pair("oauth_token", ""),
::pair("oauth_version", "1.0")};
string line;
std::ifstream infile("twitter.conf");
while (std::getline(infile, line)) {
if (line.find("ckey") != string::npos) {
find_and_replace(line, "ckey=", "");
app_info[1].value = line;
} else if (line.find("atoken") != string::npos) {
find_and_replace(line, "atoken=", "");
app_info[6].value = line;
} else {
continue;
}
}
::pair encode_info[8];
CURL *curl = curl_easy_init();
char *temp0;
for (int i = 0; i < 8; i++) {
temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
encode_info[i] = pair(string(temp0), "");
curl_free(temp0);
temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
encode_info[i].value = string(temp0);
curl_free(temp0);
}
std::sort(encode_info, encode_info + 7);
string out = encode_info[0].to_string();
for (int i = 1; i < 7; i++) {
out += "&" + encode_info[i].to_string();
}
string url = "https://api.twitter.com/1.1/users/lookup.json";
temp0 = curl_easy_escape(curl, url.c_str(), url.size());
char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
out = "GET&" + string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
cout << out + "\n";
/*string command = "curl --get 'https://api.twitter.com/1.1/users/lookup.json' --data
'screen_name=" + username + "' --header 'Authorization: OAuth oauth_consumer_key=\"" +
appinfo[0] + "\", oauth_nonce=\"" + nonce + "\",
oauth_signature=\"h18hZk1pMPAc8uaxBNLqvc1fQLU\%3D\", oauth_signature_method=\"HMAC-SHA1\",
oauth_timestamp=\"1457318794\", oauth_token=\"" + appinfo[2] + "\", oauth_version=\"1.0\"'
--verbose > lookup.json";
std::system(command.c_str());*/
/*string url = "https://twitter.com/" + username + "#page-container";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}*/
curl_easy_cleanup(curl);
return 0;
}
<commit_msg>Added preliminary stuff for HMAC SHA1 hashing<commit_after>#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <curl/curl.h>
#include <openssl/hmac.h>
using std::string;
using std::cout;
struct pair {
string key, value;
pair() {}
pair(string k, string v) {
key = k;
value = v;
}
bool operator<(const pair &other) const {
if (key == other.key) {
return value < other.value;
}
return key < other.key;
}
string to_string() { return key + "=" + value; }
};
const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}
string gen_alphanum(int len) {
string buff;
std::srand(time(0));
for (int i = 0; i < len; i++) {
buff += ASCII_TABLE[std::rand() % 62];
}
return buff;
}
int main() {
string username;
cout << "Enter Twitter Username: ";
getline(std::cin, username);
::pair app_info[8] = {::pair("screen_name", username),
::pair("oauth_consumer_key", username),
::pair("oauth_nonce", gen_alphanum(42)),
::pair("oauth_signature", ""),
::pair("oauth_signature_method", "HMAC_SHA1"),
::pair("oauth_timestamp", std::to_string(time(0))),
::pair("oauth_token", ""),
::pair("oauth_version", "1.0")};
string secrets[2];
string line;
std::ifstream infile("twitter.conf");
while (std::getline(infile, line)) {
if (line.find("ckey") != string::npos) {
find_and_replace(line, "ckey=", "");
app_info[1].value = line;
} else if (line.find("csecret") != string::npos) {
find_and_replace(line, "csecret=", "");
secrets[0] = line;
} else if (line.find("atoken") != string::npos) {
find_and_replace(line, "atoken=", "");
app_info[6].value = line;
} else if (line.find("asecret") != string::npos) {
find_and_replace(line, "asecret=", "");
secrets[1] = line;
} else {
continue;
}
}
::pair encode_info[8];
CURL *curl = curl_easy_init();
char *temp0;
for (int i = 0; i < 8; i++) {
temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
encode_info[i] = pair(string(temp0), "");
curl_free(temp0);
temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
encode_info[i].value = string(temp0);
curl_free(temp0);
}
std::sort(encode_info, encode_info + 7);
string out = encode_info[0].to_string();
for (int i = 1; i < 7; i++) {
out += "&" + encode_info[i].to_string();
}
string url = "https://api.twitter.com/1.1/users/lookup.json";
temp0 = curl_easy_escape(curl, url.c_str(), url.size());
char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
out = "GET&" + string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
cout << out + "\n";
string sign_key;
temp0 = curl_easy_escape(curl, secrets[0].c_str(), secrets[0].size());
temp1 = curl_easy_escape(curl, secrets[1].c_str(), secrets[1].size());
sign_key = string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
cout << sign_key + "\n";
/*string command = "curl --get 'https://api.twitter.com/1.1/users/lookup.json' --data
'screen_name=" + username + "' --header 'Authorization: OAuth oauth_consumer_key=\"" +
appinfo[0] + "\", oauth_nonce=\"" + nonce + "\",
oauth_signature=\"h18hZk1pMPAc8uaxBNLqvc1fQLU\%3D\", oauth_signature_method=\"HMAC-SHA1\",
oauth_timestamp=\"1457318794\", oauth_token=\"" + appinfo[2] + "\", oauth_version=\"1.0\"'
--verbose > lookup.json";
std::system(command.c_str());*/
/*string url = "https://twitter.com/" + username + "#page-container";
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}*/
curl_easy_cleanup(curl);
return 0;
}
<|endoftext|> |
<commit_before>d7988f4c-2e4e-11e5-8504-28cfe91dbc4b<commit_msg>d79fc6a3-2e4e-11e5-a283-28cfe91dbc4b<commit_after>d79fc6a3-2e4e-11e5-a283-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <time.h>
using namespace std;
/****************************** STRUCTS DECLARATION *******************************/
typedef struct node
{
const char* string;
node* next_Node;
}Node;
typedef struct header
{
Node* first_Node;
int size;
}Header;
typedef struct wrong_word
{
int line;
int column;
string word;
}Wrong_word;
/****************************** STRUCTS DECLARATION *******************************/
const int buckets = 200000; //number of buckets used in hash table
int cont_correct = 0; //number of correct words
int cont_wrong=0; //number of wrong words
float total_time; //time calculated in proccess (used to print results)
clock_t initial_time, final_time; //time = final - initial
string words_list[307860]; //copy of dictionary words (used to generate hash table)
Header table[buckets]; //array of Headers that will save a linked list and the size
std::vector<Wrong_word> vector_wrong; //vector used to save the wrong words found in text
/****************************** HASH FUNCTIONS *******************************/
int hash_lose(const char *string)
{
unsigned int hash = 0;
int c;
while (c = *string++)
hash += c;
hash = hash % buckets;
return hash;
}
/****
*Author: Ozan Yigit
*
* hash_sdbm(): This was created for sdbm database library.
* The hashing scheme used is a form of extendible hashing,
* so that the hashing scheme expands as new buckets are added to the database.
* It was found to do well in scrambling bits, causing better distribution of
* the keys and fewer splits
*
* Parameters: a string to be converted (hashed)
*
* Return: A int number that represents the string hashed
*
****/
int hash_sdbm(const char* string)
{
unsigned long int hash = 0;
int c;
while (c = *string++)
hash = c + (hash << 6) + (hash << 16) - hash;
hash = hash % buckets;
return hash;
}
/****
*Author: Daniel J. Bernstein
* hash_djb2(): This is one of the best
* known hash functions for strings. Because it is both computed very
* fast and distributes very well.
*
* The magic of number 33, i.e. why it works better than many other
* constants, prime or not, has never been adequately explained by
* anyone.
*
* Parameters: a string to be converted (hashed)
*
* Return: A int number that represents the string hashed
*
****/
int hash_djb2(const char* string)
{
unsigned long int hash = 5381;
int c;
while(c = *string++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
hash = hash % buckets; //the buckets define the range
return hash;
}
/****
*Author: Diogo Dantas and Higor Anjos
* to_lowerCase(): This function is used to convert a string to its equivalent lowercase form
*
* Parameters: a string to be converted to lowercase
*
* Return: a string in lowercase form
*
****/
string to_lowerCase(string word)
{
int i=0;
if(word[0]!=tolower(word[0])) { //if the word starts with lowercase, isn't necessary to convert
while(word[i]!='\0'){
word[i]=tolower(word[i]); //converts to lower
i++;
}
}
return word;
}
/****
*Author: Diogo Dantas and Higor Anjos
* preprocessing(): This function does all preprocessing needed to use the spell-checker
* creates the array of headers, the array of the dictionary words and generates the table
*
* Parameters: none
*
* Return: none
*
****/
void preprocessing(){
ifstream file;
file.open ("dictionary.txt"); //opening file
if (!file.is_open()) return; //if something gets wrong...
/******* CREATING AND PREPARING THE ARRAY ****/
for (int i = 0; i < buckets; ++i) //setting all to 0 or NULL
{
Header * tmp = new Header;
table[i] = *tmp;
table[i].size = 0;
table[i].first_Node = NULL;
}
/******* CREATING AND PREPARING THE ARRAY ****/
/******* CONVERTING TO LOWERCASE AND SAVING IN THE ARRAY*****/
string word;
int j=0;
while (file >> word) //jumps from word to word
{
words_list[j++] = to_lowerCase(word); //converting
}
file.close();
/******* CONVERTING TO LOWERCASE AND SAVING IN THE ARRAY*****/
/******* APPLYING HASH AND GENERATING TABLE *****/
for (int i = 0; i < j; ++i)
{
int hashed = hash_sdbm(words_list[i].c_str()); //using the dictionary words to hash
table[hashed].size++; //increasing the size of the linked list of this bucket
Node* tmp = new Node;
if (!table[hashed].first_Node) //if first
{
table[hashed].first_Node = tmp;
table[hashed].first_Node->next_Node = NULL;
table[hashed].first_Node->string = words_list[i].c_str();
} else {
tmp->string = words_list[i].c_str();
tmp->next_Node = table[hashed].first_Node;
table[hashed].first_Node = tmp;
}
}
/******* APPLYING HASH AND GENERATING TABLE *****/
} //END OF preprocessing()
/****
*Author: Diogo Dantas and Higor Anjos
* compare(): This function sweeps a linked list comparing its nodes to a string
*
* Parameters: string to be compared
*
* Return: a boolean indicating if is equal or not
*
****/
bool compare(string word)
{
word = to_lowerCase(word);
int hashed = hash_sdbm(word.c_str());
Node* aux = table[hashed].first_Node;
while(aux) //while is not in the end of the list
{
if (word == aux->string)
return true;
aux=aux->next_Node;
}
return false;
}
/****
*Author: Diogo Dantas and Higor Anjos based on DVC (Diablo Valley College) parsing algorithm
* parse_text(): This function sweeps an linked list comparing its nodes
*
* Parameters: none
*
* Return: none
*
****/
/************** PARSING TEXT *******************************/
void parse_text(){
const int CHARS_PARAGRAPH = 5250; //5250 characters per line * 7 lines (paragraph)
const int WORDS_LINE = 1000; //1000 words in a line
const char* const DELIMITER = " ,.:?;!\""; //these are ignorated as words
int line_count = -1; //used to save the quantity of lines
ifstream file;
file.open("text.txt");
if (!file.good())
cout<<"problem loading file"<<endl;
while (!file.eof())
{
line_count++;
// read an entire line into memory
char buf[CHARS_PARAGRAPH];
file.getline(buf, CHARS_PARAGRAPH);
// parse the line into DELIMITER
int n = 0;
// array to store pointers of the words in buf
const char* words[WORDS_LINE] = {}; // initialize to 0
// parse the line
words[0] = strtok(buf, DELIMITER); // first words
if (words[0]) // zero if line is blank
{
for (n = 1; n < WORDS_LINE; n++)
{
words[n] = strtok(0, DELIMITER); // subsequent words
if (!words[n]) break; // no more words
}
}
// process (print) the words
for (int i = 0; i < n; i++){ // n = number of words
if(compare(words[i])){
cont_correct++; //if is equal just increase
}else{
cont_wrong++;
Wrong_word * tmp = new Wrong_word;
tmp->line = line_count; //in wich line the words is
tmp->column = i; //in wich column the words is
tmp->word = words[i];
vector_wrong.push_back(*tmp); //adding to vector
delete tmp;
}
}
}
file.close();
}
/************** PARSING TEXT *******************************/
/****
*Author: Diogo Dantas and Higor Anjos
* print_results(): This function prints the results of the program,
* such as number of wrong words and time
*
* Parameters: none
*
* Return: none
*
****/
/************** PRINTING RESULTS ******************************/
void print_results(){
cout<<endl;
cout<<"Número total de palavras do texto: "<<cont_correct+cont_wrong<<endl;
cout<<"time de verificação: "<<total_time<<"ms."<<endl;
cout<<"Número de palavras que falharam no spell check: "<<cont_wrong<<endl;
cout<<"Lista de palavras que falharam no spell check: "<<endl;
cout<<endl;
cout<<"Linha - Coluna : Palavra "<<endl;
cout<<"------------------------------------------"<<endl;
for (int i = 0; i < cont_wrong; ++i)
{
cout<<vector_wrong[i].line+1<<" - "<<vector_wrong[i].column+1<<" : "<<vector_wrong[i].word<<endl;
}
}
/************** PRINTING RESULTS **************************************/
/****
*Author: Diogo Dantas and Higor Anjos
* print_stats(): This function prints the statistics of the program. If the
* hash function distriuted well and so on...
*
* Parameters: none
*
* Return: none
*
****/
/************** PRINTING STATS ******************************/
void print_stats(){
char option;
int indexb, indexw, greater=0, lower=0, equal=0;
int average=307860/buckets;
int worst=0;
int best = buckets; //used for comparison
int numZero = 0;
cout<<endl;
for (int i = 0; i < buckets; ++i)
{
if(table[i].size == 0)
numZero++;
if(table[i].size > worst){
worst = table[i].size;
indexw = i;
}
if(table[i].size < best){
if(table[i].size > 0 )
{
best = table[i].size;
indexb = i;
}
}
if(table[i].size > average){
greater++;
} else if(table[i].size < average){
lower++;
} else {
equal++;
}
}
cout<<"SOME STATISTICS"<<endl;
cout<<"-----------------------"<<endl;
cout<<"Number of buckets: "<<buckets<<endl;
cout<<"Average collision: "<<average<<" collisions"<<endl;
cout<<"Buckets above average: "<<greater<<endl;
cout<<"Buckets below average: "<<lower<<endl;
cout<<"Buckets equal average: "<<equal<<endl;
cout<<"Empty Buckets: "<<numZero<<endl<<endl;
cout<<"'Best Bucket'"<<endl;
cout<<"Number ["<<indexb<<"]"<<endl;
cout<<best<<" collisions"<<endl<<endl;
cout<<"'Worst Bucket'"<<endl;
cout<<"Number ["<<indexw<<"]"<<endl;
cout<<worst<<" collisions"<<endl<<endl;
cout<<"-----------------------"<<endl;
cout<<endl;
cout<<"Want to print buckets list? [y/n]"<<endl;
cin>>option;
if (option=='y')
{
for (int i = 0; i < buckets; ++i)
{
cout<<"Bucket "<<i<<" - "<<table[i].size<<" collisions"<<endl;
}
} else {
cout << "Thanks for using this program!"<<endl;
}
}
/************** PRINTING STATS ******************************/
int main(int argc, char const *argv[])
{
preprocessing();
initial_time = clock();
parse_text();
final_time = clock();
// FINAL TIME - INITIAL TIME
total_time = ((float)(final_time - initial_time)/CLOCKS_PER_SEC)*1000;
print_results();
//print_stats();
return 0;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|> |
<commit_before>df7c28ae-313a-11e5-a8d9-3c15c2e10482<commit_msg>df828605-313a-11e5-9497-3c15c2e10482<commit_after>df828605-313a-11e5-9497-3c15c2e10482<|endoftext|> |
<commit_before>eb09cfd4-313a-11e5-bb47-3c15c2e10482<commit_msg>eb0fd71c-313a-11e5-a4b0-3c15c2e10482<commit_after>eb0fd71c-313a-11e5-a4b0-3c15c2e10482<|endoftext|> |
<commit_before>ad4d3207-327f-11e5-a34f-9cf387a8033e<commit_msg>ad543940-327f-11e5-a663-9cf387a8033e<commit_after>ad543940-327f-11e5-a663-9cf387a8033e<|endoftext|> |
<commit_before>d4873fa3-ad5b-11e7-8f6c-ac87a332f658<commit_msg>No longer crashes if X<commit_after>d529f95e-ad5b-11e7-8ecb-ac87a332f658<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ofstream output_file ("output.txt");
if (output_file.is_open())
{
}
else cout << "Unable to open file";
string line, line1;
ifstream input_file ("input.txt");
if (input_file.is_open())
{
getline (input_file,line);
line1 = line;
while ( getline (input_file,line) )
{
if (!(line==line1)) {
cout << line << '\n';
output_file << line << '\n';
}
line1 = line;
}
output_file.close();
input_file.close();
}
cin >> line;
return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ofstream output_file ("output.txt");
if (output_file.is_open())
{
}
else cout << "Unable to open output file";
string line, line1;
ifstream input_file ("input.txt");
if (input_file.is_open())
{
getline (input_file,line);
line1 = line;
while ( getline (input_file,line) )
{
if (!(line==line1)) {
cout << line << '\n';
output_file << line << '\n';
}
line1 = line;
}
output_file.close();
input_file.close();
}
else cout << "Unable to open input file";
cin >> line;
return 0;
}
<|endoftext|> |
<commit_before>895aaf6b-2e4f-11e5-b18c-28cfe91dbc4b<commit_msg>89618abd-2e4f-11e5-b7b8-28cfe91dbc4b<commit_after>89618abd-2e4f-11e5-b7b8-28cfe91dbc4b<|endoftext|> |
<commit_before>/*
* Copyright 2013-2016 Canonical Ltd.
* Copyright 2011 Wolfgang Koller - http://www.gofg.at/
*
* 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 <QtCore>
#include <QApplication>
#include <QtQuick>
#include <QtNetwork/QNetworkInterface>
const int kDebuggingDevtoolsDefaultPort = 9222;
void customMessageOutput(
QtMsgType type,
const QMessageLogContext &,
const QString &msg) {
switch (type) {
case QtDebugMsg:
if (QString::fromUtf8(qgetenv("DEBUG")) == "1") {
fprintf(stderr, "Debug: %s\n", msg.toStdString().c_str());
}
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg.toStdString().c_str());
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg.toStdString().c_str());
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg.toStdString().c_str());
abort();
break;
}
}
QString getDebuggingDevtoolsIp()
{
QString host;
Q_FOREACH(QHostAddress address, QNetworkInterface::allAddresses()) {
if (!address.isLoopback() && (address.protocol() == QAbstractSocket::IPv4Protocol)) {
host = address.toString();
break;
}
}
return host;
}
int main(int argc, char *argv[]) {
printf("\nApache Cordova native platform version %s is starting\n\n"
, CORDOVA_UBUNTU_VERSION);
fflush(stdout);
qInstallMessageHandler(customMessageOutput);
QApplication app(argc, argv);
//TODO: switch to options parser
// temprory hack to filter --desktop_file_hint
QStringList args = app.arguments().filter(QRegularExpression("^[^-]"));
QDir wwwDir;
if (QDir(args[args.size() - 1]).exists()) {
wwwDir = QDir(args[args.size() - 1]);
} else {
wwwDir = QDir(QApplication::applicationDirPath());
wwwDir.cd("www");
}
QQmlApplicationEngine view;
QDir workingDir = QApplication::applicationDirPath();
bool debuggingEnabled =
(qEnvironmentVariableIsSet("DEBUG")
&& QString(qgetenv("DEBUG")) == "1");
// TODO revamp this for something cleaner, uniform
// and runtime bound
#if !defined(NDEBUG)
debuggingEnabled = true;
#endif
view.rootContext()->setContextProperty(
"debuggingEnabled", debuggingEnabled);
QString debuggingDevtoolsIp;
int debuggingDevtoolsPort = -1;
if (debuggingEnabled) {
debuggingDevtoolsIp = getDebuggingDevtoolsIp();
debuggingDevtoolsPort = kDebuggingDevtoolsDefaultPort;
qDebug() << QString("Devtools started at http://%1:%2")
.arg(debuggingDevtoolsIp)
.arg(debuggingDevtoolsPort);
}
view.rootContext()->setContextProperty(
"debuggingDevtoolsIp", debuggingDevtoolsIp);
view.rootContext()->setContextProperty(
"debuggingDevtoolsPort", debuggingDevtoolsPort);
view.rootContext()->setContextProperty(
"www", wwwDir.absolutePath());
view.load(QUrl(QString("%1/qml/main.qml").arg(workingDir.absolutePath())));
return app.exec();
}
<commit_msg>tweak devtools url message<commit_after>/*
* Copyright 2013-2016 Canonical Ltd.
* Copyright 2011 Wolfgang Koller - http://www.gofg.at/
*
* 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 <QtCore>
#include <QApplication>
#include <QtQuick>
#include <QtNetwork/QNetworkInterface>
const int kDebuggingDevtoolsDefaultPort = 9222;
void customMessageOutput(
QtMsgType type,
const QMessageLogContext &,
const QString &msg) {
switch (type) {
case QtDebugMsg:
if (QString::fromUtf8(qgetenv("DEBUG")) == "1") {
fprintf(stderr, "Debug: %s\n", msg.toStdString().c_str());
}
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg.toStdString().c_str());
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg.toStdString().c_str());
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg.toStdString().c_str());
abort();
break;
}
}
QString getDebuggingDevtoolsIp()
{
QString host;
Q_FOREACH(QHostAddress address, QNetworkInterface::allAddresses()) {
if (!address.isLoopback() && (address.protocol() == QAbstractSocket::IPv4Protocol)) {
host = address.toString();
break;
}
}
return host;
}
int main(int argc, char *argv[]) {
printf("\nApache Cordova native platform version %s is starting\n\n"
, CORDOVA_UBUNTU_VERSION);
fflush(stdout);
qInstallMessageHandler(customMessageOutput);
QApplication app(argc, argv);
//TODO: switch to options parser
// temprory hack to filter --desktop_file_hint
QStringList args = app.arguments().filter(QRegularExpression("^[^-]"));
QDir wwwDir;
if (QDir(args[args.size() - 1]).exists()) {
wwwDir = QDir(args[args.size() - 1]);
} else {
wwwDir = QDir(QApplication::applicationDirPath());
wwwDir.cd("www");
}
QQmlApplicationEngine view;
QDir workingDir = QApplication::applicationDirPath();
bool debuggingEnabled =
(qEnvironmentVariableIsSet("DEBUG")
&& QString(qgetenv("DEBUG")) == "1");
// TODO revamp this for something cleaner, uniform
// and runtime bound
#if !defined(NDEBUG)
debuggingEnabled = true;
#endif
view.rootContext()->setContextProperty(
"debuggingEnabled", debuggingEnabled);
QString debuggingDevtoolsIp;
int debuggingDevtoolsPort = -1;
if (debuggingEnabled) {
debuggingDevtoolsIp = getDebuggingDevtoolsIp();
debuggingDevtoolsPort = kDebuggingDevtoolsDefaultPort;
qDebug() << QString("Devtools URL: http://%1:%2")
.arg(debuggingDevtoolsIp)
.arg(debuggingDevtoolsPort);
}
view.rootContext()->setContextProperty(
"debuggingDevtoolsIp", debuggingDevtoolsIp);
view.rootContext()->setContextProperty(
"debuggingDevtoolsPort", debuggingDevtoolsPort);
view.rootContext()->setContextProperty(
"www", wwwDir.absolutePath());
view.load(QUrl(QString("%1/qml/main.qml").arg(workingDir.absolutePath())));
return app.exec();
}
<|endoftext|> |
<commit_before>9101ad78-2d14-11e5-af21-0401358ea401<commit_msg>9101ad79-2d14-11e5-af21-0401358ea401<commit_after>9101ad79-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Remi Thebault
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 <organization> 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 <COPYRIGHT HOLDER> 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 "StringUtils.h"
#include "FileUtils.h"
#include "QtTool.h"
#ifdef _WIN32
#include <Windows.h>
#endif
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <stdexcept>
#include <cstdlib>
#include <cstdio>
using namespace std;
string guessQtBinPath()
{
string qtBinPath;
char *qt = getenv("QT5");
if (qt) {
qtBinPath = string(qt);
if (qtBinPath.back() != fu::pathSep) qtBinPath.push_back(fu::pathSep);
qtBinPath.append("bin");
qtBinPath.push_back(fu::pathSep);
}
else {
string path = string(getenv("PATH"));
vector<string> pathComps;
su::split(path, fu::pathVarSep, back_inserter(pathComps));
for (size_t i=0; i<pathComps.size(); ++i) {
string p = pathComps[i];
if (p.back() != fu::pathSep) p.push_back(fu::pathSep);
#ifdef _WIN32
string qmake = p + string("qmake.exe");
#else
string qmake = p + string("qmake");
#endif
ifstream test (qmake, ios::binary);
if (test) {
test.close();
qtBinPath = p;
break;
}
}
}
return qtBinPath;
}
string qtBinPath;
string inD;
string outD;
QtMocTool moc;
QtUicTool uic;
QtRccTool rcc;
class Driver {
public:
void run() {
tools_.clear();
oldFiles_.clear();
newFiles_.clear();
genFiles_.clear();
updatedFiles_.clear();
untouchedFiles_.clear();
deletedFiles_.clear();
errors_.clear();
tools_.push_back(&moc);
tools_.push_back(&uic);
tools_.push_back(&rcc);
for (int i=0; i<3; ++i) {
tools_[i]->init(qtBinPath);
}
if (inD.back() != fu::pathSep) inD.push_back(fu::pathSep);
if (outD.back() != fu::pathSep) outD.push_back(fu::pathSep);
if (!fu::isDir(outD)) {
if (!fu::mkDir(outD)) {
throw runtime_error("could not create the output directory");
}
}
fu::listDir(outD, back_inserter(oldFiles_));
for (size_t i=0; i<oldFiles_.size(); ++i) {
oldFiles_[i] = outD + oldFiles_[i];
}
fu::walk(inD, *this);
for (size_t i=0; i<oldFiles_.size(); ++i) {
auto found = find(newFiles_.begin(), newFiles_.end(), oldFiles_[i]);
if (found == newFiles_.end()) {
if (fu::rm(oldFiles_[i])) {
deletedFiles_.push_back(oldFiles_[i]);
}
else {
cerr << "could not delete " << oldFiles_[i] << "\n";
}
}
}
// printing report
string sep (79, '-');
cout << sep << '\n';
cout << ' ' << inD << '\n';
cout << sep << '\n';
if (genFiles_.size() > 0) {
for (size_t i=0; i<genFiles_.size(); ++i) {
cout << "generated: " << genFiles_[i] << '\n';
}
cout << sep << '\n';
}
if (updatedFiles_.size() > 0) {
for (size_t i=0; i<updatedFiles_.size(); ++i) {
cout << "updated: " << updatedFiles_[i] << '\n';
}
cout << sep << '\n';
}
if (deletedFiles_.size() > 0) {
for (size_t i=0; i<deletedFiles_.size(); ++i) {
cout << "deleted: " << deletedFiles_[i] << '\n';
}
cout << sep << '\n';
}
cout << untouchedFiles_.size() << " file(s) were already up-to-date\n";
cout << genFiles_.size() << " file(s) have been generated\n";
cout << updatedFiles_.size() << " file(s) have been updated\n";
cout << deletedFiles_.size() << " file(s) have been deleted\n";
if (errors_.size() > 0) {
cout << sep << '\n';
cout << "error occured when processing the following file(s):\n";
for (size_t i=0; i<errors_.size(); ++i) {
cout << errors_[i] << '\n';
}
}
}
void operator()(const string& root, const string& filename, bool isdir) {
string inFile = root + filename;
for (int i=0; i<3; ++i) {
QtTool *tool = tools_[i];
if(tool->isFileInput(inFile)) {
string outFilename = tool->getOutFilename(filename);
string outFile = outD + outFilename;
try {
bool existed = fu::isFile(outFile);
if (tool->runIfNeeded(inFile, outFile)) {
if (existed) {
updatedFiles_.push_back(outFile);
}
else {
genFiles_.push_back(outFile);
}
}
else {
untouchedFiles_.push_back(outFile);
}
newFiles_.push_back(outFile);
}
catch (const runtime_error& err) {
ostringstream out;
out << filename << ": " << err.what();
errors_.push_back(out.str());
}
break;
}
}
}
private:
vector<QtTool *> tools_;
vector<string> oldFiles_;
vector<string> newFiles_;
vector<string> genFiles_;
vector<string> updatedFiles_;
vector<string> untouchedFiles_;
vector<string> deletedFiles_;
vector<string> errors_;
};
void usage(const string& err)
{
cout << "Usage: QtGenTools --inD=<IN_DIR> --outD=<OUT_DIR> [Options]\n";
if (err.size() > 0) {
cout << "Error: " << err << "\n";
}
cout << "Options:\n"
<< " --inD=<in_dir> Specify the input directory (mandatory)\n"
<< " --outD=<out_dir> Specify the output directory (mandatory)\n"
<< " --mocOpts=<opts> Command line options given to moc\n"
<< " --uicOpts=<opts> Command line options given to uic\n"
<< " --rccOpts=<opts> Command line options given to rcc\n";
}
int main (int argc, char *argv[])
{
for (int i=1; i<argc; ++i) {
string arg = string(argv[i]);
if (su::beginsWith(arg, string("--qt="))) {
qtBinPath = arg.substr(5);
if (qtBinPath.back() == '\\') qtBinPath.push_back('\\');
qtBinPath += "bin\\";
}
else if (su::beginsWith(arg, string("--inD="))) {
inD = arg.substr(6);
}
else if (su::beginsWith(arg, string("--outD="))) {
outD = arg.substr(7);
}
else if (su::beginsWith(arg, string("--mocOpts="))) {
moc.setCmdOpts(arg.substr(10));
}
else if (su::beginsWith(arg, string("--uicOpts="))) {
uic.setCmdOpts(arg.substr(10));
}
else if (su::beginsWith(arg, string("--rccOpts="))) {
rcc.setCmdOpts(arg.substr(10));
}
}
if (qtBinPath.size() == 0) {
qtBinPath = guessQtBinPath();
}
if (qtBinPath.size() == 0) {
usage("qt bin path was not found");
return 1;
}
if (!fu::isDir(qtBinPath)) {
usage("qt bin directory is not valid");
return 1;
}
if (inD.size() == 0) {
usage("input directory was not specified");
return 1;
}
if (!fu::isDir(inD)) {
usage("input directory is not valid");
return 1;
}
if (outD.size() == 0) {
usage("output directory was not specified");
return 1;
}
Driver d;
d.run();
return 0;
}
<commit_msg>add version and help options<commit_after>/*
Copyright (c) 2013, Remi Thebault
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 <organization> 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 <COPYRIGHT HOLDER> 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 "StringUtils.h"
#include "FileUtils.h"
#include "QtTool.h"
#include "Version.h"
#ifdef _WIN32
#include <Windows.h>
#endif
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <stdexcept>
#include <cstdlib>
#include <cstdio>
using namespace std;
string guessQtBinPath()
{
string qtBinPath;
char *qt = getenv("QT5");
if (qt) {
qtBinPath = string(qt);
if (qtBinPath.back() != fu::pathSep) qtBinPath.push_back(fu::pathSep);
qtBinPath.append("bin");
qtBinPath.push_back(fu::pathSep);
}
else {
string path = string(getenv("PATH"));
vector<string> pathComps;
su::split(path, fu::pathVarSep, back_inserter(pathComps));
for (size_t i=0; i<pathComps.size(); ++i) {
string p = pathComps[i];
if (p.back() != fu::pathSep) p.push_back(fu::pathSep);
#ifdef _WIN32
string qmake = p + string("qmake.exe");
#else
string qmake = p + string("qmake");
#endif
ifstream test (qmake, ios::binary);
if (test) {
test.close();
qtBinPath = p;
break;
}
}
}
return qtBinPath;
}
string qtBinPath;
string inD;
string outD;
QtMocTool moc;
QtUicTool uic;
QtRccTool rcc;
class Driver {
public:
void run() {
tools_.clear();
oldFiles_.clear();
newFiles_.clear();
genFiles_.clear();
updatedFiles_.clear();
untouchedFiles_.clear();
deletedFiles_.clear();
errors_.clear();
tools_.push_back(&moc);
tools_.push_back(&uic);
tools_.push_back(&rcc);
for (int i=0; i<3; ++i) {
tools_[i]->init(qtBinPath);
}
if (inD.back() != fu::pathSep) inD.push_back(fu::pathSep);
if (outD.back() != fu::pathSep) outD.push_back(fu::pathSep);
if (!fu::isDir(outD)) {
if (!fu::mkDir(outD)) {
throw runtime_error("could not create the output directory");
}
}
fu::listDir(outD, back_inserter(oldFiles_));
for (size_t i=0; i<oldFiles_.size(); ++i) {
oldFiles_[i] = outD + oldFiles_[i];
}
fu::walk(inD, *this);
for (size_t i=0; i<oldFiles_.size(); ++i) {
auto found = find(newFiles_.begin(), newFiles_.end(), oldFiles_[i]);
if (found == newFiles_.end()) {
if (fu::rm(oldFiles_[i])) {
deletedFiles_.push_back(oldFiles_[i]);
}
else {
cerr << "could not delete " << oldFiles_[i] << "\n";
}
}
}
// printing report
string sep (79, '-');
cout << sep << '\n';
cout << ' ' << inD << '\n';
cout << sep << '\n';
if (genFiles_.size() > 0) {
for (size_t i=0; i<genFiles_.size(); ++i) {
cout << "generated: " << genFiles_[i] << '\n';
}
cout << sep << '\n';
}
if (updatedFiles_.size() > 0) {
for (size_t i=0; i<updatedFiles_.size(); ++i) {
cout << "updated: " << updatedFiles_[i] << '\n';
}
cout << sep << '\n';
}
if (deletedFiles_.size() > 0) {
for (size_t i=0; i<deletedFiles_.size(); ++i) {
cout << "deleted: " << deletedFiles_[i] << '\n';
}
cout << sep << '\n';
}
cout << untouchedFiles_.size() << " file(s) were already up-to-date\n";
cout << genFiles_.size() << " file(s) have been generated\n";
cout << updatedFiles_.size() << " file(s) have been updated\n";
cout << deletedFiles_.size() << " file(s) have been deleted\n";
if (errors_.size() > 0) {
cout << sep << '\n';
cout << "error occured when processing the following file(s):\n";
for (size_t i=0; i<errors_.size(); ++i) {
cout << errors_[i] << '\n';
}
}
}
void operator()(const string& root, const string& filename, bool isdir) {
string inFile = root + filename;
for (int i=0; i<3; ++i) {
QtTool *tool = tools_[i];
if(tool->isFileInput(inFile)) {
string outFilename = tool->getOutFilename(filename);
string outFile = outD + outFilename;
try {
bool existed = fu::isFile(outFile);
if (tool->runIfNeeded(inFile, outFile)) {
if (existed) {
updatedFiles_.push_back(outFile);
}
else {
genFiles_.push_back(outFile);
}
}
else {
untouchedFiles_.push_back(outFile);
}
newFiles_.push_back(outFile);
}
catch (const runtime_error& err) {
ostringstream out;
out << filename << ": " << err.what();
errors_.push_back(out.str());
}
break;
}
}
}
private:
vector<QtTool *> tools_;
vector<string> oldFiles_;
vector<string> newFiles_;
vector<string> genFiles_;
vector<string> updatedFiles_;
vector<string> untouchedFiles_;
vector<string> deletedFiles_;
vector<string> errors_;
};
void usage(const string& err="")
{
if (err.size() > 0) {
cout << "Error: " << err << "\n";
}
cout <<
"Usage: QtGenTools --inD=<IN_DIR> --outD=<OUT_DIR> [Options]\n"
" QtGenTools --version\n"
" QtGenTools --help\n"
" version " VERSION_STR "\n"
"Options:\n"
" --inD=<in_dir> Specify the input directory (mandatory)\n"
" --outD=<out_dir> Specify the output directory (mandatory)\n"
" --mocOpts=<opts> Command line options given to moc\n"
" --uicOpts=<opts> Command line options given to uic\n"
" --rccOpts=<opts> Command line options given to rcc\n"
" --version Prints the version and exits\n"
" --help Prints this message and exits\n";
}
int main (int argc, char *argv[])
{
for (int i=1; i<argc; ++i) {
string arg = string(argv[i]);
if (arg == "--help") {
usage();
return 0;
}
else if (arg == "--version") {
std::cout << VERSION_STR "\n";
return 0;
}
else if (su::beginsWith(arg, string("--qt="))) {
qtBinPath = arg.substr(5);
if (qtBinPath.back() == '\\') qtBinPath.push_back('\\');
qtBinPath += "bin\\";
}
else if (su::beginsWith(arg, string("--inD="))) {
inD = arg.substr(6);
}
else if (su::beginsWith(arg, string("--outD="))) {
outD = arg.substr(7);
}
else if (su::beginsWith(arg, string("--mocOpts="))) {
moc.setCmdOpts(arg.substr(10));
}
else if (su::beginsWith(arg, string("--uicOpts="))) {
uic.setCmdOpts(arg.substr(10));
}
else if (su::beginsWith(arg, string("--rccOpts="))) {
rcc.setCmdOpts(arg.substr(10));
}
}
if (qtBinPath.size() == 0) {
qtBinPath = guessQtBinPath();
}
if (qtBinPath.size() == 0) {
usage("qt bin path was not found");
return 1;
}
if (!fu::isDir(qtBinPath)) {
usage("qt bin directory is not valid");
return 1;
}
if (inD.size() == 0) {
usage("input directory was not specified");
return 1;
}
if (!fu::isDir(inD)) {
usage("input directory is not valid");
return 1;
}
if (outD.size() == 0) {
usage("output directory was not specified");
return 1;
}
Driver d;
d.run();
return 0;
}
<|endoftext|> |
<commit_before>9a8402e6-327f-11e5-946a-9cf387a8033e<commit_msg>9a89d13a-327f-11e5-a160-9cf387a8033e<commit_after>9a89d13a-327f-11e5-a160-9cf387a8033e<|endoftext|> |
<commit_before>7f6cf5b2-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf5b3-2d15-11e5-af21-0401358ea401<commit_after>7f6cf5b3-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>d57eb110-585a-11e5-ace4-6c40088e03e4<commit_msg>d58570e2-585a-11e5-833b-6c40088e03e4<commit_after>d58570e2-585a-11e5-833b-6c40088e03e4<|endoftext|> |
<commit_before>8df50cd4-2e4f-11e5-9c19-28cfe91dbc4b<commit_msg>8dfc4ede-2e4f-11e5-bf19-28cfe91dbc4b<commit_after>8dfc4ede-2e4f-11e5-bf19-28cfe91dbc4b<|endoftext|> |
<commit_before>/*
* main.cpp
*
* Created on: Jan 16, 2015
* Author: radoslav
*/
#include "compound.h"
#include "environment.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string program;
while (!cin.eof())
{
string line;
getline(cin, line);
program += line + '\n';
}
const char* program_cstr = program.c_str();
CompoundStatement cs(program_cstr);
Environment e;
cs.execute(e);
return 0;
}
<commit_msg>added code to stop entering the program when an `--' is encountered<commit_after>/*
* main.cpp
*
* Created on: Jan 16, 2015
* Author: radoslav
*/
#include "compound.h"
#include "environment.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string program, line;
do
{
getline(cin, line);
program += line + '\n';
}
while (!cin.eof() && line != "--");
const char* program_cstr = program.c_str();
CompoundStatement cs(program_cstr);
Environment e;
cs.execute(e);
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <unistd.h>
#include "glm/glm.hpp"
#include "graphics/context.h"
#include "graphics/renderer.h"
#include "objects/mesh.h"
#include "objects/box.h"
#include "physic/pworld.h"
#define width 1024
#define height 768
using namespace std ;
int main(int argc, char** argv)
{
string filename = "cube.obj";
if (argc > 1)
{
filename = string(argv[1]);
}
Renderer renderer;
Context context(renderer);
if (!context.init(width, height, "obj viewer", 4))
{
cerr << "Impossible d'initialiser le contexte OpenGL." << endl;
return 0;
}
Mesh obj(filename);
//obj.rotate(glm::vec3(3.1415 / 2.0, 0, 0)); // 90 degrés
Shader shdr1("shaders/vert.vert", "shaders/couleur3D.frag");
Shader shdr2("shaders/gris.vert", "shaders/texture.frag");
while (context.eventLoop())
{
//world.update(0.05);
obj.sync();
context.clean();
obj.setShader(&shdr2);
renderer.draw(obj);
obj.setShader(&shdr1);
renderer.draw(obj, GL_LINE);
context.show();
//obj.rotate(glm::vec3(0,0.02,0));
usleep(50000);
}
return 0;
}
<commit_msg>main avec physique<commit_after>#include <string>
#include <iostream>
#include <unistd.h>
#include "glm/glm.hpp"
#include "graphics/context.h"
#include "graphics/renderer.h"
#include "objects/mesh.h"
#include "objects/box.h"
#include "physic/pworld.h"
#define width 1024
#define height 768
using namespace std ;
int main(int argc, char** argv)
{
string filename = "suzanne.obj";
if (argc > 1)
{
filename = string(argv[1]);
}
Renderer renderer;
Context context(renderer);
if (!context.init(width, height, "obj viewer", 4))
{
cerr << "Impossible d'initialiser le contexte OpenGL." << endl;
return 0;
}
PWorld world(glm::vec3(0,0,-9.81));
Mesh obj(filename);
Box obj2(15,20,8);
obj2.translate(glm::vec3(20,20,20));
world.addObject(obj.getPObject());
world.addObject(obj2.getPObject());
//obj.rotate(glm::vec3(3.1415 / 2.0, 0, 0)); // 90 degrés
Shader shdr1("shaders/vert.vert", "shaders/couleur3D.frag");
Shader shdr2("shaders/gris.vert", "shaders/couleur3D.frag");
while (context.eventLoop())
{
world.update(0.05);
obj.sync();
obj2.sync();
context.clean();
obj.setShader(&shdr2);
obj2.setShader(&shdr2);
renderer.draw(obj);
renderer.draw(obj2);
obj.setShader(&shdr1);
obj2.setShader(&shdr1);
renderer.draw(obj, GL_LINE);
renderer.draw(obj2, GL_LINE);
context.show();
//obj.rotate(glm::vec3(0,0.02,0));
usleep(50000);
}
return 0;
}
<|endoftext|> |
<commit_before>e5dcfe23-2747-11e6-ae7c-e0f84713e7b8<commit_msg>Stuff changed<commit_after>e5f3bfb0-2747-11e6-a845-e0f84713e7b8<|endoftext|> |
<commit_before>///
/// @file primesieve.hpp
/// @brief primesieve C++ API. primesieve is a library for fast prime
/// number generation, in case an error occurs a
/// primesieve::primesieve_error exception (derived form
/// std::runtime_error) will be thrown.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License.
///
#ifndef PRIMESIEVE_HPP
#define PRIMESIEVE_HPP
#define PRIMESIEVE_VERSION "5.7.3"
#define PRIMESIEVE_VERSION_MAJOR 5
#define PRIMESIEVE_VERSION_MINOR 7
#define PRIMESIEVE_VERSION_PATCH 3
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/Callback.hpp>
#include <primesieve/cancel_callback.hpp>
#include <primesieve/iterator.hpp>
#include <primesieve/PushBackPrimes.hpp>
#include <primesieve/primesieve_error.hpp>
#include <stdint.h>
#include <vector>
#include <string>
/// Contains primesieve's C++ functions and classes.
namespace primesieve {
/// Store the primes <= stop in the primes vector.
template <typename T>
inline void generate_primes(uint64_t stop, std::vector<T>* primes)
{
if (primes)
{
PushBackPrimes<std::vector<T> > pb(*primes);
pb.pushBackPrimes(0, stop);
}
}
/// Store the primes within the interval [start, stop]
/// in the primes vector.
///
template <typename T>
inline void generate_primes(uint64_t start, uint64_t stop, std::vector<T>* primes)
{
if (primes)
{
PushBackPrimes<std::vector<T> > pb(*primes);
pb.pushBackPrimes(start, stop);
}
}
/// Store the first n primes in the primes vector.
template <typename T>
inline void generate_n_primes(uint64_t n, std::vector<T>* primes)
{
if (primes)
{
PushBack_N_Primes<std::vector<T> > pb(*primes);
pb.pushBack_N_Primes(n, 0);
}
}
/// Store the first n primes >= start in the primes vector.
template <typename T>
inline void generate_n_primes(uint64_t n, uint64_t start, std::vector<T>* primes)
{
if (primes)
{
PushBack_N_Primes<std::vector<T> > pb(*primes);
pb.pushBack_N_Primes(n, start);
}
}
/// Find the nth prime.
/// @param n if n = 0 finds the 1st prime >= start, <br/>
/// if n > 0 finds the nth prime > start, <br/>
/// if n < 0 finds the nth prime < start (backwards).
///
uint64_t nth_prime(int64_t n, uint64_t start = 0);
/// Find the nth prime in parallel.
/// By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
/// @param n if n = 0 finds the 1st prime >= start, <br/>
/// if n > 0 finds the nth prime > start, <br/>
/// if n < 0 finds the nth prime < start (backwards).
///
uint64_t parallel_nth_prime(int64_t n, uint64_t start = 0);
/// Count the primes within the interval [start, stop].
uint64_t count_primes(uint64_t start, uint64_t stop);
/// Count the twin primes within the interval [start, stop].
uint64_t count_twins(uint64_t start, uint64_t stop);
/// Count the prime triplets within the interval [start, stop].
uint64_t count_triplets(uint64_t start, uint64_t stop);
/// Count the prime quadruplets within the interval [start, stop].
uint64_t count_quadruplets(uint64_t start, uint64_t stop);
/// Count the prime quintuplets within the interval [start, stop].
uint64_t count_quintuplets(uint64_t start, uint64_t stop);
/// Count the prime sextuplets within the interval [start, stop].
uint64_t count_sextuplets(uint64_t start, uint64_t stop);
/// Count the primes within the interval [start, stop] in
/// parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_primes(uint64_t start, uint64_t stop);
/// Count the twin primes within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_twins(uint64_t start, uint64_t stop);
/// Count the prime triplets within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_triplets(uint64_t start, uint64_t stop);
/// Count the prime quadruplets within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_quadruplets(uint64_t start, uint64_t stop);
/// Count the prime quintuplets within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_quintuplets(uint64_t start, uint64_t stop);
/// Count the prime sextuplets within the interval [start, stop] in
/// parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_sextuplets(uint64_t start, uint64_t stop);
/// Print the primes within the interval [start, stop]
/// to the standard output.
///
void print_primes(uint64_t start, uint64_t stop);
/// Print the twin primes within the interval [start, stop]
/// to the standard output.
///
void print_twins(uint64_t start, uint64_t stop);
/// Print the prime triplets within the interval [start, stop]
/// to the standard output.
///
void print_triplets(uint64_t start, uint64_t stop);
/// Print the prime quadruplets within the interval [start, stop]
/// to the standard output.
///
void print_quadruplets(uint64_t start, uint64_t stop);
/// Print the prime quintuplets within the interval [start, stop]
/// to the standard output.
///
void print_quintuplets(uint64_t start, uint64_t stop);
/// Print the prime sextuplets within the interval [start, stop]
/// to the standard output.
///
void print_sextuplets(uint64_t start, uint64_t stop);
/// Call back the primes within the interval [start, stop].
/// @param callback A callback function.
///
void callback_primes(uint64_t start, uint64_t stop, void (*callback)(uint64_t prime));
/// Call back the primes within the interval [start, stop].
/// @param callback An object derived from primesieve::Callback<uint64_t>.
///
void callback_primes(uint64_t start, uint64_t stop, primesieve::Callback<uint64_t>* callback);
/// Get the current set sieve size in kilobytes.
int get_sieve_size();
/// Get the current set number of threads.
int get_num_threads();
/// Returns the largest valid stop number for primesieve.
/// @return 2^64-1 (UINT64_MAX).
///
uint64_t get_max_stop();
/// Set the sieve size in kilobytes.
/// The best sieving performance is achieved with a sieve size of
/// your CPU's L1 data cache size (per core). For sieving >= 10^17 a
/// sieve size of your CPU's L2 cache size sometimes performs
/// better.
/// @param sieve_size Sieve size in kilobytes.
/// @pre sieve_size >= 1 && sieve_size <= 2048.
///
void set_sieve_size(int sieve_size);
/// Set the number of threads for use in subsequent
/// primesieve::parallel_* function calls.
///
void set_num_threads(int num_threads);
/// Run extensive correctness tests.
/// The tests last about one minute on a quad core CPU from
/// 2013 and use up to 1 gigabyte of memory.
/// @return true if success else false.
///
bool primesieve_test();
/// Get the primesieve version number, in the form “i.j.k”.
std::string primesieve_version();
}
#endif
<commit_msg>Update copyright year<commit_after>///
/// @file primesieve.hpp
/// @brief primesieve C++ API. primesieve is a library for fast prime
/// number generation, in case an error occurs a
/// primesieve::primesieve_error exception (derived form
/// std::runtime_error) will be thrown.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License.
///
#ifndef PRIMESIEVE_HPP
#define PRIMESIEVE_HPP
#define PRIMESIEVE_VERSION "5.7.3"
#define PRIMESIEVE_VERSION_MAJOR 5
#define PRIMESIEVE_VERSION_MINOR 7
#define PRIMESIEVE_VERSION_PATCH 3
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/Callback.hpp>
#include <primesieve/cancel_callback.hpp>
#include <primesieve/iterator.hpp>
#include <primesieve/PushBackPrimes.hpp>
#include <primesieve/primesieve_error.hpp>
#include <stdint.h>
#include <vector>
#include <string>
/// Contains primesieve's C++ functions and classes.
namespace primesieve {
/// Store the primes <= stop in the primes vector.
template <typename T>
inline void generate_primes(uint64_t stop, std::vector<T>* primes)
{
if (primes)
{
PushBackPrimes<std::vector<T> > pb(*primes);
pb.pushBackPrimes(0, stop);
}
}
/// Store the primes within the interval [start, stop]
/// in the primes vector.
///
template <typename T>
inline void generate_primes(uint64_t start, uint64_t stop, std::vector<T>* primes)
{
if (primes)
{
PushBackPrimes<std::vector<T> > pb(*primes);
pb.pushBackPrimes(start, stop);
}
}
/// Store the first n primes in the primes vector.
template <typename T>
inline void generate_n_primes(uint64_t n, std::vector<T>* primes)
{
if (primes)
{
PushBack_N_Primes<std::vector<T> > pb(*primes);
pb.pushBack_N_Primes(n, 0);
}
}
/// Store the first n primes >= start in the primes vector.
template <typename T>
inline void generate_n_primes(uint64_t n, uint64_t start, std::vector<T>* primes)
{
if (primes)
{
PushBack_N_Primes<std::vector<T> > pb(*primes);
pb.pushBack_N_Primes(n, start);
}
}
/// Find the nth prime.
/// @param n if n = 0 finds the 1st prime >= start, <br/>
/// if n > 0 finds the nth prime > start, <br/>
/// if n < 0 finds the nth prime < start (backwards).
///
uint64_t nth_prime(int64_t n, uint64_t start = 0);
/// Find the nth prime in parallel.
/// By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
/// @param n if n = 0 finds the 1st prime >= start, <br/>
/// if n > 0 finds the nth prime > start, <br/>
/// if n < 0 finds the nth prime < start (backwards).
///
uint64_t parallel_nth_prime(int64_t n, uint64_t start = 0);
/// Count the primes within the interval [start, stop].
uint64_t count_primes(uint64_t start, uint64_t stop);
/// Count the twin primes within the interval [start, stop].
uint64_t count_twins(uint64_t start, uint64_t stop);
/// Count the prime triplets within the interval [start, stop].
uint64_t count_triplets(uint64_t start, uint64_t stop);
/// Count the prime quadruplets within the interval [start, stop].
uint64_t count_quadruplets(uint64_t start, uint64_t stop);
/// Count the prime quintuplets within the interval [start, stop].
uint64_t count_quintuplets(uint64_t start, uint64_t stop);
/// Count the prime sextuplets within the interval [start, stop].
uint64_t count_sextuplets(uint64_t start, uint64_t stop);
/// Count the primes within the interval [start, stop] in
/// parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_primes(uint64_t start, uint64_t stop);
/// Count the twin primes within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_twins(uint64_t start, uint64_t stop);
/// Count the prime triplets within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_triplets(uint64_t start, uint64_t stop);
/// Count the prime quadruplets within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_quadruplets(uint64_t start, uint64_t stop);
/// Count the prime quintuplets within the interval [start, stop]
/// in parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_quintuplets(uint64_t start, uint64_t stop);
/// Count the prime sextuplets within the interval [start, stop] in
/// parallel. By default all CPU cores are used, use
/// primesieve::set_num_threads(int) to change the number of
/// threads.
///
uint64_t parallel_count_sextuplets(uint64_t start, uint64_t stop);
/// Print the primes within the interval [start, stop]
/// to the standard output.
///
void print_primes(uint64_t start, uint64_t stop);
/// Print the twin primes within the interval [start, stop]
/// to the standard output.
///
void print_twins(uint64_t start, uint64_t stop);
/// Print the prime triplets within the interval [start, stop]
/// to the standard output.
///
void print_triplets(uint64_t start, uint64_t stop);
/// Print the prime quadruplets within the interval [start, stop]
/// to the standard output.
///
void print_quadruplets(uint64_t start, uint64_t stop);
/// Print the prime quintuplets within the interval [start, stop]
/// to the standard output.
///
void print_quintuplets(uint64_t start, uint64_t stop);
/// Print the prime sextuplets within the interval [start, stop]
/// to the standard output.
///
void print_sextuplets(uint64_t start, uint64_t stop);
/// Call back the primes within the interval [start, stop].
/// @param callback A callback function.
///
void callback_primes(uint64_t start, uint64_t stop, void (*callback)(uint64_t prime));
/// Call back the primes within the interval [start, stop].
/// @param callback An object derived from primesieve::Callback<uint64_t>.
///
void callback_primes(uint64_t start, uint64_t stop, primesieve::Callback<uint64_t>* callback);
/// Get the current set sieve size in kilobytes.
int get_sieve_size();
/// Get the current set number of threads.
int get_num_threads();
/// Returns the largest valid stop number for primesieve.
/// @return 2^64-1 (UINT64_MAX).
///
uint64_t get_max_stop();
/// Set the sieve size in kilobytes.
/// The best sieving performance is achieved with a sieve size of
/// your CPU's L1 data cache size (per core). For sieving >= 10^17 a
/// sieve size of your CPU's L2 cache size sometimes performs
/// better.
/// @param sieve_size Sieve size in kilobytes.
/// @pre sieve_size >= 1 && sieve_size <= 2048.
///
void set_sieve_size(int sieve_size);
/// Set the number of threads for use in subsequent
/// primesieve::parallel_* function calls.
///
void set_num_threads(int num_threads);
/// Run extensive correctness tests.
/// The tests last about one minute on a quad core CPU from
/// 2013 and use up to 1 gigabyte of memory.
/// @return true if success else false.
///
bool primesieve_test();
/// Get the primesieve version number, in the form “i.j.k”.
std::string primesieve_version();
}
#endif
<|endoftext|> |
<commit_before>8fd04875-2d14-11e5-af21-0401358ea401<commit_msg>8fd04876-2d14-11e5-af21-0401358ea401<commit_after>8fd04876-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>ace223fa-2e4f-11e5-8d4b-28cfe91dbc4b<commit_msg>aceced00-2e4f-11e5-97b8-28cfe91dbc4b<commit_after>aceced00-2e4f-11e5-97b8-28cfe91dbc4b<|endoftext|> |
<commit_before>#ifndef _STRX_MANIP_H
#define _STRX_MANIP_H
#ifndef _STRING_
#ifndef _GLIBCXX_STRING
#include <string>
#endif
#endif
#ifndef _CSTRING_
#ifndef _GLIBCXX_cSTRING
#include <cstring>
#endif
#endif
#ifndef _VECTOR_
#ifndef _GLIBCXX_VECTOR
#include <vector>
#endif
#endif
namespace strx {
/// <summary>
/// String constant containing the common white-space characters.
/// </summary>
extern const ::std::string whitespace;
/// <summary>
/// Checks if the given character exists within the provided string.
/// </summary>
/// <param name="str">String to be searched.</param>
/// <param name="c">Character to search for.</param>
/// <returns>true if the character is found; otherwise false.</returns>
inline bool contains(const ::std::string &str, const char &c) { return str.find_first_of(c) != ::std::string::npos; }
/// <summary>
/// Checks if the given query exists within the provided target.
/// </summary>
/// <param name="target">Target string to be searched.</param>
/// <param name="query">String to be searched for</param>
/// <returns>true if the query is found; otherwise false.</returns>
inline bool contains(const ::std::string &target, const ::std::string &query) { return target.find(query) != ::std::string::npos; }
/// <summary>
/// Checks if the provided string starts with the provided pattern.
/// </summary>
/// <param name="str">String to be checked.</param>
/// <param name="pattern">String to look for.</param>
/// <returns>true if the pattern is found; otherwise false</returns>
inline bool starts_with(const ::std::string & str, const ::std::string &pattern) { return str.size() >= pattern.size() && str.find_first_of(pattern) == 0; }
/// <summary>
/// Searches the provided string and returns the index of the first occurrence of the provided <paramref name="pattern"/>.
/// </summary>
/// <param name="str">String to be searched.</param>
/// <param name="pattern">Pattern to look for.</param>
/// <returns>true if the pattern is found; otherwise false</returns>
::std::size_t find_first_of_pat(const ::std::string &str, const ::std::string &pattern);
/// <summary>
/// Splits the provided string into an array of strings using a provided delimiter as the split point.
/// </summary>
/// <param name="str">String to be split.</param>
/// <param name="delim">Delimiter to be split at and removed from the string.</param>
/// <returns>Array of strings</returns>
::std::vector<::std::string> split(::std::string str, const char &delim);
/// <summary>
/// Joins together an array of strings, using the provided delimiter to separate each token in the resulting string.
/// </summary>
/// <param name="tokens">Tokens to be joined into a single string.</param>
/// <param name="delim">Delimiter to separate the tokens within the new string.</param>
/// <returns>Single string of concatenated tokens and delimiters.</returns>
::std::string join(const ::std::vector<::std::string> &tokens, const char &delim);
/// <summary>
/// Joins together an array of strings, using the provided delimiter to separate each token in the resulting string.
/// </summary>
/// <param name="tokens">Tokens to be joined into a single string.</param>
/// <param name="delim">Delimiter to separate the tokens within the new string.</param>
/// <returns>Single string of concatenated tokens and delimiters.</returns>
::std::string join(const ::std::vector<::std::string> &tokens, const ::std::string &delim);
/// <summary>
/// Replaces portions of the provided string that match the patterns with the provided replacement string.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="patterns">Array of patterns to look for.</param>
/// <param name="length">Length of pattern array</param>
/// <param name="replacement">Replacement string.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const ::std::string patterns[], ::std::size_t length, const ::std::string &replacement);
/// <summary>
/// Replaces portions of the provided string that match the pattern with the provided replacement.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="patterns">Pattern to look for.</param>
/// <param name="replacement">Replacement string.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const ::std::string &pattern, const ::std::string &replacement);
/// <summary>
/// Replaces the provided character in the given string with the provided replacement.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="c">Character to be replaced.</param>
/// <param name="replacement">Replacement string.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const char &c, const ::std::string &replacement);
/// <summary>
/// Replaces the provided pattern in the given string with the provided replacement character.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="pattern">pattern to look for.</param>
/// <param name="replacement">Replacement character.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const ::std::string &pattern, const char &replacement);
/// <summary>
/// Replaces the provided pattern character in the given string with the provided replacement character.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="pattern">Character to be replaced.</param>
/// <param name="replacement">Replacement character.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const char &pattern, const char &replacement);
/// <summary>
/// Left pads the given string to fit a minimum width. Empty space is filled with the provided <paramref name="pad"/>.
/// </summary>
/// <param name="str">String to be padded.</param>
/// <param name="width">Width to pad to.</param>
/// <param name="pad">Character to pad with (default: ' ')</param>
/// <returns>Padded string</returns>
inline ::std::string lpad(::std::string str, ::std::size_t width, const char pad = ' ')
{
width -= str.size();
return width > 0 ? str.insert(0, width, pad) : str;
}
/// <summary>
/// Right pads the given string to fit a minimum width. Empty space is filled with the provided <paramref name="pad"/>.
/// </summary>
/// <param name="str">String to be padded.</param>
/// <param name="width">Width to pad to.</param>
/// <param name="pad">Character to pad with (default: ' ')</param>
/// <returns>Padded string</returns>
inline ::std::string rpad(::std::string str, ::std::size_t width, const char pad = ' ')
{
size_t size = str.size();
width -= size;
return width > 0 ? str.insert(size, width, pad) : str;
}
/// <summary>
/// Trims any excess white-space characters off the left end of the string.
/// </summary>
/// <param name="str">String to be trimmed.</param>
/// <returns>Trimmed string</returns>
inline ::std::string ltrim(::std::string str)
{
if (str.size() == 0) return str;
str.erase(str.begin(), str.begin() + str.find_first_not_of(whitespace));
return str;
}
/// <summary>
/// Trims any excess white-space characters off the right end of the string.
/// </summary>
/// <param name="str">String to be trimmed.</param>
/// <returns>Trimmed string</returns>
inline ::std::string rtrim(::std::string str)
{
if (str.size() == 0) return str;
str.erase(str.begin() + str.find_last_not_of(whitespace) + 1, str.end());
return str;
}
/// <summary>
/// Trims any excess white-space characters off the ends of the string.
/// </summary>
/// <param name="str">String to be trimmed.</param>
/// <returns>Trimmed string</returns>
inline ::std::string trim(const ::std::string &str) { return rtrim(ltrim(str)); }
/// <summary>
/// Checks if the provided string is empty
/// </summary>
/// <param name="str">String to be checked.</param>
/// <returns>true if the string is empty; otherwise false.</returns>
inline bool s_empty(const ::std::string &str) { return str.size() == 0; }
/// <summary>
/// Checks if the provided string is empty or only filled with white-space characters.
/// </summary>
/// <param name="str">String to be checked.</param>
/// <returns>true if the string is empty; otherwise false;</returns>
inline bool s_whitespace(const ::std::string &str) { return str.size() == 0 || str.find_first_not_of(whitespace) != ::std::string::npos; }
/// <summary>
/// Converts all characters in the provided string to their lower case variants.
/// </summary>
/// <param name="str">String to be lower cased.</param>
/// <returns>Lower cased string.</returns>
::std::string str2lower(::std::string str);
/// <summary>
/// Converts all characters in the provided string to their upper case variants.
/// </summary>
/// <param name="str">String to be upper cased.</param>
/// <returns>Lower cased string.</returns>
::std::string str2upper(::std::string str);
/// <summary>
/// Converts the string to a boolean value based on its contents.
/// </summary>
/// <param name="str">String to be converted.</param>
/// <returns>true if the string is equal to "true" or "1" (case insensitive).</returns>
inline bool stob(::std::string str) {
str = str2lower(trim(str));
return str == "true" || str == "1";
}
/// <summary>
/// Converts the given string to a single signed 8bit integer value.
/// </summary>
/// <param name="str">String to be converted.</param>
/// <returns>Converted value.</returns>
inline int8_t stobyte(::std::string str) { return (int8_t)stol(str); }
/// <summary>
/// Converts the given string to a single unsigned 8bit integer value.
/// </summary>
/// <param name="str">String to be converted.</param>
/// <returns>Converted value.</returns>
inline uint8_t stoubyte(::std::string str) { return (uint8_t)stoul(str); }
/// <summary>
/// Reads all the contents of the given file into an in-memory string.
/// </summary>
/// <param name="path">Path to the file to be read.</param>
/// <returns>String containing all of the file's contents.</returns>
::std::string ftos(::std::string path);
/// <summary>
/// Reads all the contents of the given file into an in-memory string.
/// </summary>
/// <param name="file">Pointer to the file to be read.</param>
/// <returns>String containing all of the file's contents.</returns>
::std::string ftos(FILE* file);
}
#endif<commit_msg>Fixed minor error in lpad/rpad functions<commit_after>#ifndef _STRX_MANIP_H
#define _STRX_MANIP_H
#ifndef _STRING_
#ifndef _GLIBCXX_STRING
#include <string>
#endif
#endif
#ifndef _CSTRING_
#ifndef _GLIBCXX_cSTRING
#include <cstring>
#endif
#endif
#ifndef _VECTOR_
#ifndef _GLIBCXX_VECTOR
#include <vector>
#endif
#endif
namespace strx {
/// <summary>
/// String constant containing the common white-space characters.
/// </summary>
extern const ::std::string whitespace;
/// <summary>
/// Checks if the given character exists within the provided string.
/// </summary>
/// <param name="str">String to be searched.</param>
/// <param name="c">Character to search for.</param>
/// <returns>true if the character is found; otherwise false.</returns>
inline bool contains(const ::std::string &str, const char &c) { return str.find_first_of(c) != ::std::string::npos; }
/// <summary>
/// Checks if the given query exists within the provided target.
/// </summary>
/// <param name="target">Target string to be searched.</param>
/// <param name="query">String to be searched for</param>
/// <returns>true if the query is found; otherwise false.</returns>
inline bool contains(const ::std::string &target, const ::std::string &query) { return target.find(query) != ::std::string::npos; }
/// <summary>
/// Checks if the provided string starts with the provided pattern.
/// </summary>
/// <param name="str">String to be checked.</param>
/// <param name="pattern">String to look for.</param>
/// <returns>true if the pattern is found; otherwise false</returns>
inline bool starts_with(const ::std::string & str, const ::std::string &pattern) { return str.size() >= pattern.size() && str.find_first_of(pattern) == 0; }
/// <summary>
/// Searches the provided string and returns the index of the first occurrence of the provided <paramref name="pattern"/>.
/// </summary>
/// <param name="str">String to be searched.</param>
/// <param name="pattern">Pattern to look for.</param>
/// <returns>true if the pattern is found; otherwise false</returns>
::std::size_t find_first_of_pat(const ::std::string &str, const ::std::string &pattern);
/// <summary>
/// Splits the provided string into an array of strings using a provided delimiter as the split point.
/// </summary>
/// <param name="str">String to be split.</param>
/// <param name="delim">Delimiter to be split at and removed from the string.</param>
/// <returns>Array of strings</returns>
::std::vector<::std::string> split(::std::string str, const char &delim);
/// <summary>
/// Joins together an array of strings, using the provided delimiter to separate each token in the resulting string.
/// </summary>
/// <param name="tokens">Tokens to be joined into a single string.</param>
/// <param name="delim">Delimiter to separate the tokens within the new string.</param>
/// <returns>Single string of concatenated tokens and delimiters.</returns>
::std::string join(const ::std::vector<::std::string> &tokens, const char &delim);
/// <summary>
/// Joins together an array of strings, using the provided delimiter to separate each token in the resulting string.
/// </summary>
/// <param name="tokens">Tokens to be joined into a single string.</param>
/// <param name="delim">Delimiter to separate the tokens within the new string.</param>
/// <returns>Single string of concatenated tokens and delimiters.</returns>
::std::string join(const ::std::vector<::std::string> &tokens, const ::std::string &delim);
/// <summary>
/// Replaces portions of the provided string that match the patterns with the provided replacement string.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="patterns">Array of patterns to look for.</param>
/// <param name="length">Length of pattern array</param>
/// <param name="replacement">Replacement string.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const ::std::string patterns[], ::std::size_t length, const ::std::string &replacement);
/// <summary>
/// Replaces portions of the provided string that match the pattern with the provided replacement.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="patterns">Pattern to look for.</param>
/// <param name="replacement">Replacement string.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const ::std::string &pattern, const ::std::string &replacement);
/// <summary>
/// Replaces the provided character in the given string with the provided replacement.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="c">Character to be replaced.</param>
/// <param name="replacement">Replacement string.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const char &c, const ::std::string &replacement);
/// <summary>
/// Replaces the provided pattern in the given string with the provided replacement character.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="pattern">pattern to look for.</param>
/// <param name="replacement">Replacement character.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const ::std::string &pattern, const char &replacement);
/// <summary>
/// Replaces the provided pattern character in the given string with the provided replacement character.
/// </summary>
/// <param name="str">String to be modified.</param>
/// <param name="pattern">Character to be replaced.</param>
/// <param name="replacement">Replacement character.</param>
/// <returns>Modified string.</returns>
::std::string replace(const ::std::string &str, const char &pattern, const char &replacement);
/// <summary>
/// Left pads the given string to fit a minimum width. Empty space is filled with the provided <paramref name="pad"/>.
/// </summary>
/// <param name="str">String to be padded.</param>
/// <param name="width">Width to pad to.</param>
/// <param name="pad">Character to pad with (default: ' ')</param>
/// <returns>Padded string</returns>
inline ::std::string lpad(::std::string str, ::std::size_t width, const char pad = ' ')
{
if (width < str.size()) return str;
width -= str.size();
return width > 0 ? str.insert(0, width, pad) : str;
}
/// <summary>
/// Right pads the given string to fit a minimum width. Empty space is filled with the provided <paramref name="pad"/>.
/// </summary>
/// <param name="str">String to be padded.</param>
/// <param name="width">Width to pad to.</param>
/// <param name="pad">Character to pad with (default: ' ')</param>
/// <returns>Padded string</returns>
inline ::std::string rpad(::std::string str, ::std::size_t width, const char pad = ' ')
{
size_t size = str.size();
if (width < size) return str;
width -= size;
return width > 0 ? str.insert(size, width, pad) : str;
}
/// <summary>
/// Trims any excess white-space characters off the left end of the string.
/// </summary>
/// <param name="str">String to be trimmed.</param>
/// <returns>Trimmed string</returns>
inline ::std::string ltrim(::std::string str)
{
if (str.size() == 0) return str;
str.erase(str.begin(), str.begin() + str.find_first_not_of(whitespace));
return str;
}
/// <summary>
/// Trims any excess white-space characters off the right end of the string.
/// </summary>
/// <param name="str">String to be trimmed.</param>
/// <returns>Trimmed string</returns>
inline ::std::string rtrim(::std::string str)
{
if (str.size() == 0) return str;
str.erase(str.begin() + str.find_last_not_of(whitespace) + 1, str.end());
return str;
}
/// <summary>
/// Trims any excess white-space characters off the ends of the string.
/// </summary>
/// <param name="str">String to be trimmed.</param>
/// <returns>Trimmed string</returns>
inline ::std::string trim(const ::std::string &str) { return rtrim(ltrim(str)); }
/// <summary>
/// Checks if the provided string is empty
/// </summary>
/// <param name="str">String to be checked.</param>
/// <returns>true if the string is empty; otherwise false.</returns>
inline bool s_empty(const ::std::string &str) { return str.size() == 0; }
/// <summary>
/// Checks if the provided string is empty or only filled with white-space characters.
/// </summary>
/// <param name="str">String to be checked.</param>
/// <returns>true if the string is empty; otherwise false;</returns>
inline bool s_whitespace(const ::std::string &str) { return str.size() == 0 || str.find_first_not_of(whitespace) != ::std::string::npos; }
/// <summary>
/// Converts all characters in the provided string to their lower case variants.
/// </summary>
/// <param name="str">String to be lower cased.</param>
/// <returns>Lower cased string.</returns>
::std::string str2lower(::std::string str);
/// <summary>
/// Converts all characters in the provided string to their upper case variants.
/// </summary>
/// <param name="str">String to be upper cased.</param>
/// <returns>Lower cased string.</returns>
::std::string str2upper(::std::string str);
/// <summary>
/// Converts the string to a boolean value based on its contents.
/// </summary>
/// <param name="str">String to be converted.</param>
/// <returns>true if the string is equal to "true" or "1" (case insensitive).</returns>
inline bool stob(::std::string str) {
str = str2lower(trim(str));
return str == "true" || str == "1";
}
/// <summary>
/// Converts the given string to a single signed 8bit integer value.
/// </summary>
/// <param name="str">String to be converted.</param>
/// <returns>Converted value.</returns>
inline int8_t stobyte(::std::string str) { return (int8_t)stol(str); }
/// <summary>
/// Converts the given string to a single unsigned 8bit integer value.
/// </summary>
/// <param name="str">String to be converted.</param>
/// <returns>Converted value.</returns>
inline uint8_t stoubyte(::std::string str) { return (uint8_t)stoul(str); }
/// <summary>
/// Reads all the contents of the given file into an in-memory string.
/// </summary>
/// <param name="path">Path to the file to be read.</param>
/// <returns>String containing all of the file's contents.</returns>
::std::string ftos(::std::string path);
/// <summary>
/// Reads all the contents of the given file into an in-memory string.
/// </summary>
/// <param name="file">Pointer to the file to be read.</param>
/// <returns>String containing all of the file's contents.</returns>
::std::string ftos(FILE* file);
}
#endif<|endoftext|> |
<commit_before>cdf248ae-327f-11e5-ba84-9cf387a8033e<commit_msg>cdf84b00-327f-11e5-a046-9cf387a8033e<commit_after>cdf84b00-327f-11e5-a046-9cf387a8033e<|endoftext|> |
<commit_before>8c3d213f-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2140-2d14-11e5-af21-0401358ea401<commit_after>8c3d2140-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>d95323f8-313a-11e5-85ae-3c15c2e10482<commit_msg>d95a0007-313a-11e5-b40a-3c15c2e10482<commit_after>d95a0007-313a-11e5-b40a-3c15c2e10482<|endoftext|> |
<commit_before>ce1f5154-2d3d-11e5-a187-c82a142b6f9b<commit_msg>ce8f7efd-2d3d-11e5-98ad-c82a142b6f9b<commit_after>ce8f7efd-2d3d-11e5-98ad-c82a142b6f9b<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.