text stringlengths 54 60.6k |
|---|
<commit_before>//! @author @TungWah @Alan
//! @date 4 Oct,2014.
//!
//! Exercise 9.45:
//! Write a funtion that takes a string representing a name and two other
//! strings representing a prefix, such as “Mr.” or “Ms.” and a suffix,
//! such as “Jr.” or “III”. Using iterators and the insert and append functions,
//! generate and return a new string with the suffix and prefix added to the
//! given name.
//!
#include <iostream>
#include <string>
//! Exercise 9.45
std::string
pre_suffix(const std::string &name, const std::string &pre, const std::string &su);
int main()
{
std::string name("alan");
std::cout << pre_suffix(name, "Mr.", ",Jr.");
return 0;
}
inline std::string
pre_suffix(const std::string &name, const std::string &pre, const std::string &su)
{
std::string ret(name);
ret.insert(0, pre);
ret.append(su);
return ret;
}
<commit_msg>revert to old version and fixed #267<commit_after>//! @author @TungWah @Alan
//! @date 4 Oct,2014.
//!
//! Exercise 9.45:
//! Write a funtion that takes a string representing a name and two other
//! strings representing a prefix, such as “Mr.” or “Ms.” and a suffix,
//! such as “Jr.” or “III”. Using iterators and the insert and append functions,
//! generate and return a new string with the suffix and prefix added to the
//! given name.
//!
#include <iostream>
#include <string>
//! Exercise 9.45
std::string
pre_suffix(const std::string &name, const std::string &pre, const std::string &su);
int main()
{
std::string name("alan");
std::cout << pre_suffix(name, "Mr.", ",Jr.") << std::endl;
return 0;
}
inline std::string
pre_suffix(const std::string &name, const std::string &pre, const std::string &su)
{
auto ret = name;
ret.insert(ret.begin(), pre.begin(), pre.end());
ret.append(su);
return ret;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <mips/interpreter/encoder/format_V_encoder.hpp>
using namespace MIPS;
TEST(FormatVEncoder, encodeJumpPositiveOffset) {
std::vector<char*> params;
params.push_back((char*) "j");
params.push_back((char*) "1067");
FormatVEncoder encoder;
encoder.parse(params);
instruction_t instruction = encoder.encode();
ASSERT_EQ(instruction, 9259);
}
TEST(FormatVEncoder, encodeJumpNegativeOffset) {
std::vector<char*> params;
params.push_back((char*) "j");
params.push_back((char*) "-1067");
FormatVEncoder encoder;
encoder.parse(params);
instruction_t instruction = encoder.encode();
ASSERT_EQ(instruction, 11221);
}
<commit_msg>Conserta o teste do jump<commit_after>#include <gtest/gtest.h>
#include <mips/interpreter/encoder/format_V_encoder.hpp>
using namespace MIPS;
TEST(FormatVEncoder, encodeJumpPositiveOffset) {
std::vector<char*> params;
params.push_back((char*) "j");
params.push_back((char*) "1067");
FormatVEncoder encoder;
encoder.parse(params);
instruction_t instruction = encoder.encode();
ASSERT_EQ(instruction, 9259);
}
TEST(FormatVEncoder, encodeJumpNegativeOffset) {
std::vector<char*> params;
params.push_back((char*) "j");
params.push_back((char*) "-1067");
FormatVEncoder encoder;
encoder.parse(params);
instruction_t instruction = encoder.encode();
ASSERT_EQ(instruction, 12287);
}
<|endoftext|> |
<commit_before>#include "GateInterpreter.h"
unsigned char* executionInputLayer = NULL;
unsigned char* executionMiddleLayerIn = NULL;
unsigned char* executionMiddleLayerOut = NULL;
unsigned char* executionOutputLayer = NULL;
int GateInterpreter::executeCircuit(GA1DArrayGenome<GENOME_ITEM_TYPE>* pGenome, unsigned char* inputs, unsigned char* outputs) {
// allocate repeatedly used variables
int offsetConnectors;
int offsetFunctions;
GENOME_ITEM_TYPE absoluteConnectors;
GENOME_ITEM_TYPE function;
int status;
// initial memory inputs are zero
memset(executionOutputLayer, 0, pGlobals->settings->gateCircuit.sizeOutputLayer);
// compute number of memory cycles
int numMemoryCycles = !pGlobals->settings->gateCircuit.useMemory ? 1 : pGlobals->settings->testVectors.inputLength / pGlobals->settings->main.circuitSizeInput;
// execute entire circuit for each memory cycle
for (int memoryCycle = 0; memoryCycle < numMemoryCycles; memoryCycle++) {
// prepare initial input layer values (memory + inputs)
memcpy(executionInputLayer, executionOutputLayer, pGlobals->settings->gateCircuit.sizeMemory);
memcpy(executionInputLayer + pGlobals->settings->gateCircuit.sizeMemory, inputs, pGlobals->settings->main.circuitSizeInput);
// execute first layer
offsetConnectors = 0;
offsetFunctions = pGlobals->settings->gateCircuit.genomeWidth;
for (int slot = 0; slot < pGlobals->settings->gateCircuit.sizeLayer; slot++) {
absoluteConnectors = relativeToAbsoluteConnectorMask(pGenome->gene(offsetConnectors + slot), slot, pGlobals->settings->gateCircuit.sizeInputLayer,
pGlobals->settings->gateCircuit.sizeInputLayer);
function = pGenome->gene(offsetFunctions + slot);
status = executeFunction(function, absoluteConnectors, executionInputLayer,
(executionMiddleLayerOut[slot]));
if (status != STAT_OK) return status;
}
// copy results to new inputs
memcpy(executionMiddleLayerIn, executionMiddleLayerOut, pGlobals->settings->gateCircuit.sizeLayer);
// execute inside layers
for (int layer = 1; layer < pGlobals->settings->gateCircuit.numLayers - 1; layer++) {
offsetConnectors = 2 * layer * pGlobals->settings->gateCircuit.genomeWidth;
offsetFunctions = offsetConnectors + pGlobals->settings->gateCircuit.genomeWidth;
for (int slot = 0; slot < pGlobals->settings->gateCircuit.sizeLayer; slot++) {
absoluteConnectors = relativeToAbsoluteConnectorMask(pGenome->gene(offsetConnectors + slot), slot, pGlobals->settings->gateCircuit.sizeLayer,
pGlobals->settings->gateCircuit.numConnectors);
function = pGenome->gene(offsetFunctions + slot);
status = executeFunction(function, absoluteConnectors, executionMiddleLayerIn,
(executionMiddleLayerOut[slot]));
if (status != STAT_OK) return status;
}
// copy results to new inputs
memcpy(executionMiddleLayerIn, executionMiddleLayerOut, pGlobals->settings->gateCircuit.sizeLayer);
}
// execute last layer
offsetConnectors = 2 * (pGlobals->settings->gateCircuit.numLayers - 1) * pGlobals->settings->gateCircuit.genomeWidth;
offsetFunctions = offsetConnectors + pGlobals->settings->gateCircuit.genomeWidth;
for (int slot = 0; slot < pGlobals->settings->gateCircuit.sizeOutputLayer; slot++) {
absoluteConnectors = relativeToAbsoluteConnectorMask(pGenome->gene(offsetConnectors + slot), slot % pGlobals->settings->gateCircuit.sizeLayer,
pGlobals->settings->gateCircuit.sizeLayer, pGlobals->settings->gateCircuit.sizeLayer);
function = pGenome->gene(offsetFunctions + slot);
status = executeFunction(function, absoluteConnectors, executionMiddleLayerIn,
(executionOutputLayer[slot]));
if (status != STAT_OK) return status;
}
}
// copy final outputs
memcpy(outputs, executionOutputLayer + pGlobals->settings->gateCircuit.sizeMemory, pGlobals->settings->main.circuitSizeOutput);
return STAT_OK;
}
int GateInterpreter::pruneCircuit(GAGenome &originalGenome, GAGenome &prunnedGenome) {
return STAT_NOT_IMPLEMENTED_YET;
}
int GateInterpreter::executeFunction(GENOME_ITEM_TYPE node, GENOME_ITEM_TYPE absoluteConnectors, unsigned char* layerInputValues, unsigned char& result) {
// temporary variables
int connection = 0;
int connection2 = 0;
unsigned char function = nodeGetFunction(node);
unsigned char argument1 = nodeGetArgument(node,1);
// start result with neutral value
result = getNeutralValue(function);
switch (function) {
case FNC_NOP:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection]; }
break;
case FNC_CONS:
result = argument1;
break;
case FNC_AND:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result &= layerInputValues[connection]; }
break;
case FNC_NAND:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result &= layerInputValues[connection]; }
result = ~result;
break;
case FNC_OR:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result |= layerInputValues[connection]; }
break;
case FNC_XOR:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result ^= layerInputValues[connection]; }
break;
case FNC_NOR:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result |= layerInputValues[connection]; }
result = ~result;
break;
case FNC_NOT:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = ~(layerInputValues[connection]); }
break;
case FNC_SHIL:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection] << (argument1 % BITS_IN_UCHAR); }
break;
case FNC_SHIR:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection] >> (argument1 % BITS_IN_UCHAR); }
break;
case FNC_ROTL:
if (connectorsDiscartFirst(absoluteConnectors,connection)) {
if (argument1 % BITS_IN_UCHAR == 0) {
layerInputValues[connection];
} else {
result = (layerInputValues[connection] << (argument1 % BITS_IN_UCHAR))
| (layerInputValues[connection] >> (BITS_IN_UCHAR - argument1 % BITS_IN_UCHAR));
}
}
break;
case FNC_ROTR:
if (connectorsDiscartFirst(absoluteConnectors,connection)) {
if (argument1 % BITS_IN_UCHAR == 0) {
layerInputValues[connection];
} else {
result = (layerInputValues[connection] >> (argument1 % BITS_IN_UCHAR))
| (layerInputValues[connection] << (BITS_IN_UCHAR - argument1 % BITS_IN_UCHAR));
}
}
break;
case FNC_EQ:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] == layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_LT:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] < layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_GT:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] > layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_LEQ:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] <= layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_GEQ:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] >= layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_BSLC:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection] & argument1; }
break;
case FNC_READ:
result = executionInputLayer[argument1 % pGlobals->settings->gateCircuit.sizeInputLayer];
break;
case FNC_JVM:
return executeExternalFunction(node, absoluteConnectors, layerInputValues, result);
// unknown function constant
default:
mainLogger.out(LOGGER_ERROR) << "Unknown circuit function (" << nodeGetFunction(function) << ")." << endl;
return STAT_CIRCUIT_INCONSISTENT;
}
return STAT_OK;
}
int GateInterpreter::executeExternalFunction(GENOME_ITEM_TYPE node, GENOME_ITEM_TYPE absoluteConnectors, unsigned char* layerInputValues, unsigned char &result) {
int connection = 0;
// Prepare all inputs values to JVM stack
while (connectorsDiscartFirst(absoluteConnectors, connection))
pGlobals->settings->gateCircuit.jvmSim->push_int((int32_t)layerInputValues[connection]);
// Obtain arguments of JVM function
unsigned char argument1 = nodeGetArgument(node, 1); // function ID (name)
unsigned char argument2 = nodeGetArgument(node, 2); // instruction from
unsigned char argument3 = nodeGetArgument(node, 3); // instruction to
// Execute given subpart of bytecode
//int runval = pGlobals->settings->gateCircuit.jvmSim->jvmsim_run("FFMul", 1, 10, false);
int runval = pGlobals->settings->gateCircuit.jvmSim->jvmsim_run(pGlobals->settings->gateCircuit.jvmSim->getFunctionNameByID(argument1), argument2, argument3, false);
if (runval != 0) {
//assert(runval == 0);
//mainLogger.out(LOGGER_ERROR) << "jvmsim_run failed to execute with value " << runval << ")." << endl;
}
// Combine output of function as xor of values left on stack
while (!(pGlobals->settings->gateCircuit.jvmSim->stack_empty()))
{
unsigned char stack = (unsigned char)pGlobals->settings->gateCircuit.jvmSim->pop_int();
result ^= stack;
}
return STAT_OK;
}
<commit_msg>fix of JVMSim compilation<commit_after>#include "GateInterpreter.h"
#include "JVMSimulator.h"
unsigned char* executionInputLayer = NULL;
unsigned char* executionMiddleLayerIn = NULL;
unsigned char* executionMiddleLayerOut = NULL;
unsigned char* executionOutputLayer = NULL;
int GateInterpreter::executeCircuit(GA1DArrayGenome<GENOME_ITEM_TYPE>* pGenome, unsigned char* inputs, unsigned char* outputs) {
// allocate repeatedly used variables
int offsetConnectors;
int offsetFunctions;
GENOME_ITEM_TYPE absoluteConnectors;
GENOME_ITEM_TYPE function;
int status;
// initial memory inputs are zero
memset(executionOutputLayer, 0, pGlobals->settings->gateCircuit.sizeOutputLayer);
// compute number of memory cycles
int numMemoryCycles = !pGlobals->settings->gateCircuit.useMemory ? 1 : pGlobals->settings->testVectors.inputLength / pGlobals->settings->main.circuitSizeInput;
// execute entire circuit for each memory cycle
for (int memoryCycle = 0; memoryCycle < numMemoryCycles; memoryCycle++) {
// prepare initial input layer values (memory + inputs)
memcpy(executionInputLayer, executionOutputLayer, pGlobals->settings->gateCircuit.sizeMemory);
memcpy(executionInputLayer + pGlobals->settings->gateCircuit.sizeMemory, inputs, pGlobals->settings->main.circuitSizeInput);
// execute first layer
offsetConnectors = 0;
offsetFunctions = pGlobals->settings->gateCircuit.genomeWidth;
for (int slot = 0; slot < pGlobals->settings->gateCircuit.sizeLayer; slot++) {
absoluteConnectors = relativeToAbsoluteConnectorMask(pGenome->gene(offsetConnectors + slot), slot, pGlobals->settings->gateCircuit.sizeInputLayer,
pGlobals->settings->gateCircuit.sizeInputLayer);
function = pGenome->gene(offsetFunctions + slot);
status = executeFunction(function, absoluteConnectors, executionInputLayer,
(executionMiddleLayerOut[slot]));
if (status != STAT_OK) return status;
}
// copy results to new inputs
memcpy(executionMiddleLayerIn, executionMiddleLayerOut, pGlobals->settings->gateCircuit.sizeLayer);
// execute inside layers
for (int layer = 1; layer < pGlobals->settings->gateCircuit.numLayers - 1; layer++) {
offsetConnectors = 2 * layer * pGlobals->settings->gateCircuit.genomeWidth;
offsetFunctions = offsetConnectors + pGlobals->settings->gateCircuit.genomeWidth;
for (int slot = 0; slot < pGlobals->settings->gateCircuit.sizeLayer; slot++) {
absoluteConnectors = relativeToAbsoluteConnectorMask(pGenome->gene(offsetConnectors + slot), slot, pGlobals->settings->gateCircuit.sizeLayer,
pGlobals->settings->gateCircuit.numConnectors);
function = pGenome->gene(offsetFunctions + slot);
status = executeFunction(function, absoluteConnectors, executionMiddleLayerIn,
(executionMiddleLayerOut[slot]));
if (status != STAT_OK) return status;
}
// copy results to new inputs
memcpy(executionMiddleLayerIn, executionMiddleLayerOut, pGlobals->settings->gateCircuit.sizeLayer);
}
// execute last layer
offsetConnectors = 2 * (pGlobals->settings->gateCircuit.numLayers - 1) * pGlobals->settings->gateCircuit.genomeWidth;
offsetFunctions = offsetConnectors + pGlobals->settings->gateCircuit.genomeWidth;
for (int slot = 0; slot < pGlobals->settings->gateCircuit.sizeOutputLayer; slot++) {
absoluteConnectors = relativeToAbsoluteConnectorMask(pGenome->gene(offsetConnectors + slot), slot % pGlobals->settings->gateCircuit.sizeLayer,
pGlobals->settings->gateCircuit.sizeLayer, pGlobals->settings->gateCircuit.sizeLayer);
function = pGenome->gene(offsetFunctions + slot);
status = executeFunction(function, absoluteConnectors, executionMiddleLayerIn,
(executionOutputLayer[slot]));
if (status != STAT_OK) return status;
}
}
// copy final outputs
memcpy(outputs, executionOutputLayer + pGlobals->settings->gateCircuit.sizeMemory, pGlobals->settings->main.circuitSizeOutput);
return STAT_OK;
}
int GateInterpreter::pruneCircuit(GAGenome &originalGenome, GAGenome &prunnedGenome) {
return STAT_NOT_IMPLEMENTED_YET;
}
int GateInterpreter::executeFunction(GENOME_ITEM_TYPE node, GENOME_ITEM_TYPE absoluteConnectors, unsigned char* layerInputValues, unsigned char& result) {
// temporary variables
int connection = 0;
int connection2 = 0;
unsigned char function = nodeGetFunction(node);
unsigned char argument1 = nodeGetArgument(node,1);
// start result with neutral value
result = getNeutralValue(function);
switch (function) {
case FNC_NOP:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection]; }
break;
case FNC_CONS:
result = argument1;
break;
case FNC_AND:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result &= layerInputValues[connection]; }
break;
case FNC_NAND:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result &= layerInputValues[connection]; }
result = ~result;
break;
case FNC_OR:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result |= layerInputValues[connection]; }
break;
case FNC_XOR:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result ^= layerInputValues[connection]; }
break;
case FNC_NOR:
while (connectorsDiscartFirst(absoluteConnectors,connection)) { result |= layerInputValues[connection]; }
result = ~result;
break;
case FNC_NOT:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = ~(layerInputValues[connection]); }
break;
case FNC_SHIL:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection] << (argument1 % BITS_IN_UCHAR); }
break;
case FNC_SHIR:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection] >> (argument1 % BITS_IN_UCHAR); }
break;
case FNC_ROTL:
if (connectorsDiscartFirst(absoluteConnectors,connection)) {
if (argument1 % BITS_IN_UCHAR == 0) {
layerInputValues[connection];
} else {
result = (layerInputValues[connection] << (argument1 % BITS_IN_UCHAR))
| (layerInputValues[connection] >> (BITS_IN_UCHAR - argument1 % BITS_IN_UCHAR));
}
}
break;
case FNC_ROTR:
if (connectorsDiscartFirst(absoluteConnectors,connection)) {
if (argument1 % BITS_IN_UCHAR == 0) {
layerInputValues[connection];
} else {
result = (layerInputValues[connection] >> (argument1 % BITS_IN_UCHAR))
| (layerInputValues[connection] << (BITS_IN_UCHAR - argument1 % BITS_IN_UCHAR));
}
}
break;
case FNC_EQ:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] == layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_LT:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] < layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_GT:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] > layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_LEQ:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] <= layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_GEQ:
if (connectorsDiscartFirst(absoluteConnectors,connection) && connectorsDiscartFirst(absoluteConnectors,connection2)) {
if (layerInputValues[connection] >= layerInputValues[connection2]) { result = UCHAR_MAX; }
}
break;
case FNC_BSLC:
if (connectorsDiscartFirst(absoluteConnectors,connection)) { result = layerInputValues[connection] & argument1; }
break;
case FNC_READ:
result = executionInputLayer[argument1 % pGlobals->settings->gateCircuit.sizeInputLayer];
break;
case FNC_JVM:
return executeExternalFunction(node, absoluteConnectors, layerInputValues, result);
// unknown function constant
default:
mainLogger.out(LOGGER_ERROR) << "Unknown circuit function (" << nodeGetFunction(function) << ")." << endl;
return STAT_CIRCUIT_INCONSISTENT;
}
return STAT_OK;
}
int GateInterpreter::executeExternalFunction(GENOME_ITEM_TYPE node, GENOME_ITEM_TYPE absoluteConnectors, unsigned char* layerInputValues, unsigned char &result) {
int connection = 0;
// Prepare all inputs values to JVM stack
while (connectorsDiscartFirst(absoluteConnectors, connection))
pGlobals->settings->gateCircuit.jvmSim->push_int((int32_t)layerInputValues[connection]);
// Obtain arguments of JVM function
unsigned char argument1 = nodeGetArgument(node, 1); // function ID (name)
unsigned char argument2 = nodeGetArgument(node, 2); // instruction from
unsigned char argument3 = nodeGetArgument(node, 3); // instruction to
// Execute given subpart of bytecode
//int runval = pGlobals->settings->gateCircuit.jvmSim->jvmsim_run("FFMul", 1, 10, false);
int runval = pGlobals->settings->gateCircuit.jvmSim->jvmsim_run(pGlobals->settings->gateCircuit.jvmSim->getFunctionNameByID(argument1), argument2, argument3, false);
if (runval != 0) {
//assert(runval == 0);
//mainLogger.out(LOGGER_ERROR) << "jvmsim_run failed to execute with value " << runval << ")." << endl;
}
// Combine output of function as xor of values left on stack
while (!(pGlobals->settings->gateCircuit.jvmSim->stack_empty()))
{
unsigned char stack = (unsigned char)pGlobals->settings->gateCircuit.jvmSim->pop_int();
result ^= stack;
}
return STAT_OK;
}
<|endoftext|> |
<commit_before>#include "testing/testing.hpp"
#include "editor/user_stats.hpp"
#include "platform/platform_tests_support/writable_dir_changer.hpp"
namespace editor
{
namespace
{
auto constexpr kEditorTestDir = "editor-tests";
// This user has made only 9 changes and then renamed himself, so there will be no further edits from him.
auto constexpr kUserName = "Nikita Bokiy";
UNIT_TEST(UserStatsLoader_Smoke)
{
WritableDirChanger wdc(kEditorTestDir, WritableDirChanger::SettingsDirPolicy::UseWritableDir);
{
UserStatsLoader statsLoader;
TEST(!statsLoader.GetStats(kUserName), ());
}
{
UserStatsLoader statsLoader;
statsLoader.Update(kUserName);
auto const userStats = statsLoader.GetStats(kUserName);
TEST(userStats, ());
int32_t rank, changesCount;
TEST(userStats.GetRank(rank), ());
TEST(userStats.GetChangesCount(changesCount), ());
TEST_GREATER_OR_EQUAL(rank, 2100, ());
TEST_EQUAL(changesCount, 9, ());
}
// This test checks if user stats info was stored in setting.
// NOTE: there Update function is not called.
{
UserStatsLoader statsLoader;
TEST_EQUAL(statsLoader.GetUserName(), kUserName, ());
auto const userStats = statsLoader.GetStats(kUserName);
TEST(userStats, ());
int32_t rank, changesCount;
TEST(userStats.GetRank(rank), ());
TEST(userStats.GetChangesCount(changesCount), ());
TEST_GREATER_OR_EQUAL(rank, 2100, ());
TEST_EQUAL(changesCount, 9, ());
}
}
} // namespace
} // namespace editor
<commit_msg>[tests] Fix user stats and building level validation tests<commit_after>#include "testing/testing.hpp"
#include "editor/user_stats.hpp"
#include "platform/platform_tests_support/writable_dir_changer.hpp"
namespace editor
{
namespace
{
auto constexpr kEditorTestDir = "editor-tests";
// This user has made only 9 changes and then renamed himself, so there will be no further edits from him.
auto constexpr kUserName = "Nikita Bokiy";
UNIT_TEST(UserStatsLoader_Smoke)
{
WritableDirChanger wdc(kEditorTestDir, WritableDirChanger::SettingsDirPolicy::UseWritableDir);
{
UserStatsLoader statsLoader;
TEST(!statsLoader.GetStats(kUserName), ());
}
{
UserStatsLoader statsLoader;
statsLoader.Update(kUserName);
auto const userStats = statsLoader.GetStats(kUserName);
TEST(userStats, ());
int32_t rank, changesCount;
TEST(userStats.GetRank(rank), ());
TEST(userStats.GetChangesCount(changesCount), ());
TEST_GREATER_OR_EQUAL(rank, 2100, ());
TEST_EQUAL(changesCount, 9, ());
}
// This test checks if user stats info was stored in setting.
// NOTE: there Update function is not called.
{
UserStatsLoader statsLoader;
TEST_EQUAL(statsLoader.GetUserName(), kUserName, ());
auto const userStats = statsLoader.GetStats(kUserName);
TEST(userStats, ());
int32_t rank, changesCount;
TEST(userStats.GetRank(rank), ());
TEST(userStats.GetChangesCount(changesCount), ());
TEST_GREATER_OR_EQUAL(rank, 2100, ());
TEST_EQUAL(changesCount, 9, ());
}
}
} // namespace
} // namespace editor
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TimSortTest
#include <boost/test/unit_test.hpp>
#include "timsort.hpp"
using namespace gfx;
BOOST_AUTO_TEST_CASE( simple0 ) {
std::vector<int> a;
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 0 );
}
BOOST_AUTO_TEST_CASE( simple1 ) {
std::vector<int> a;
a.push_back(42);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 1 );
BOOST_CHECK_EQUAL( a[0], 42 );
}
BOOST_AUTO_TEST_CASE( simple2 ) {
std::vector<int> a;
a.push_back(10);
a.push_back(20);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 2 );
BOOST_CHECK_EQUAL( a[0], 10);
BOOST_CHECK_EQUAL( a[1], 20 );
a.clear();
a.push_back(20);
a.push_back(10);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 2 );
BOOST_CHECK_EQUAL( a[0], 10);
BOOST_CHECK_EQUAL( a[1], 20 );
}
BOOST_AUTO_TEST_CASE( simple10 ) {
std::vector<int> a;
a.push_back(60);
a.push_back(50);
a.push_back( 1);
a.push_back(40);
a.push_back(80);
a.push_back(20);
a.push_back(30);
a.push_back(70);
a.push_back(10);
a.push_back(90);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a[0], 1 );
BOOST_CHECK_EQUAL( a[1], 10 );
BOOST_CHECK_EQUAL( a[2], 20 );
BOOST_CHECK_EQUAL( a[3], 30 );
BOOST_CHECK_EQUAL( a[4], 40 );
BOOST_CHECK_EQUAL( a[5], 50 );
BOOST_CHECK_EQUAL( a[6], 60 );
BOOST_CHECK_EQUAL( a[7], 70 );
BOOST_CHECK_EQUAL( a[8], 80 );
BOOST_CHECK_EQUAL( a[9], 90 );
std::reverse(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a[0], 1 );
BOOST_CHECK_EQUAL( a[1], 10 );
BOOST_CHECK_EQUAL( a[2], 20 );
BOOST_CHECK_EQUAL( a[3], 30 );
BOOST_CHECK_EQUAL( a[4], 40 );
BOOST_CHECK_EQUAL( a[5], 50 );
BOOST_CHECK_EQUAL( a[6], 60 );
BOOST_CHECK_EQUAL( a[7], 70 );
BOOST_CHECK_EQUAL( a[8], 80 );
BOOST_CHECK_EQUAL( a[9], 90 );
}
BOOST_AUTO_TEST_CASE( shuffle30 ) {
const int size = 30;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle31 ) {
const int size = 31;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle32 ) {
const int size = 32;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle128 ) {
const int size = 128;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle1023 ) {
const int size = 1023; // odd number of elements
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( shuffle1024 ) {
const int size = 1024; // even number of elements
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_shuffle1023 ) {
const int size = 1023;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.begin() + (size / 2));
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_shuffle1024 ) {
const int size = 1024;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.begin() + (size / 2));
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( shuffle1024r ) {
const int size = 1024;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::greater<int>());
int j = size;
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (--j+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_reversed1023 ) {
const int size = 1023;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::reverse(a.begin(), a.begin() + (size / 2)); // partial reversed
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_reversed1024 ) {
const int size = 1024;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::reverse(a.begin(), a.begin() + (size / 2)); // partial reversed
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( c_array ) {
int a[] = { 7, 1, 5, 3, 9 };
timsort(a, a + sizeof(a) / sizeof(int), std::less<int>());
BOOST_CHECK_EQUAL(a[0], 1);
BOOST_CHECK_EQUAL(a[1], 3);
BOOST_CHECK_EQUAL(a[2], 5);
BOOST_CHECK_EQUAL(a[3], 7);
BOOST_CHECK_EQUAL(a[4], 9);
}
BOOST_AUTO_TEST_CASE( string_array ) {
std::string a[] = { "7", "1", "5", "3", "9" };
timsort(a, a + sizeof(a) / sizeof(std::string), std::less<std::string>());
BOOST_CHECK_EQUAL(a[0], "1");
BOOST_CHECK_EQUAL(a[1], "3");
BOOST_CHECK_EQUAL(a[2], "5");
BOOST_CHECK_EQUAL(a[3], "7");
BOOST_CHECK_EQUAL(a[4], "9");
}
struct NonDefaultConstructible
{
int i;
NonDefaultConstructible( int i_ )
: i( i_ ) {}
friend bool operator<( NonDefaultConstructible const& x, NonDefaultConstructible const& y ) {
return x.i < y.i;
}
};
BOOST_AUTO_TEST_CASE( non_default_constructible ) {
NonDefaultConstructible a[] = { 7, 1, 5, 3, 9 };
timsort(a, a + sizeof(a) / sizeof(a[0]), std::less<NonDefaultConstructible>());
BOOST_CHECK_EQUAL(a[0].i, 1);
BOOST_CHECK_EQUAL(a[1].i, 3);
BOOST_CHECK_EQUAL(a[2].i, 5);
BOOST_CHECK_EQUAL(a[3].i, 7);
BOOST_CHECK_EQUAL(a[4].i, 9);
}
enum id { foo, bar, baz };
typedef std::pair<int, id> pair_t;
bool less_in_first(pair_t x, pair_t y) {
return x.first < y.first;
}
BOOST_AUTO_TEST_CASE( stability ) {
std::vector< pair_t > a;
for(int i = 100; i >= 0; --i) {
a.push_back( std::make_pair(i, foo) );
a.push_back( std::make_pair(i, bar) );
a.push_back( std::make_pair(i, baz) );
}
timsort(a.begin(), a.end(), &less_in_first);
BOOST_CHECK_EQUAL(a[0].first, 0);
BOOST_CHECK_EQUAL(a[0].second, foo);
BOOST_CHECK_EQUAL(a[1].first, 0);
BOOST_CHECK_EQUAL(a[1].second, bar);
BOOST_CHECK_EQUAL(a[2].first, 0);
BOOST_CHECK_EQUAL(a[2].second, baz);
BOOST_CHECK_EQUAL(a[3].first, 1);
BOOST_CHECK_EQUAL(a[3].second, foo);
BOOST_CHECK_EQUAL(a[4].first, 1);
BOOST_CHECK_EQUAL(a[4].second, bar);
BOOST_CHECK_EQUAL(a[5].first, 1);
BOOST_CHECK_EQUAL(a[5].second, baz);
BOOST_CHECK_EQUAL(a[6].first, 2);
BOOST_CHECK_EQUAL(a[6].second, foo);
BOOST_CHECK_EQUAL(a[7].first, 2);
BOOST_CHECK_EQUAL(a[7].second, bar);
BOOST_CHECK_EQUAL(a[8].first, 2);
BOOST_CHECK_EQUAL(a[8].second, baz);
BOOST_CHECK_EQUAL(a[9].first, 3);
BOOST_CHECK_EQUAL(a[9].second, foo);
BOOST_CHECK_EQUAL(a[10].first, 3);
BOOST_CHECK_EQUAL(a[10].second, bar);
BOOST_CHECK_EQUAL(a[11].first, 3);
BOOST_CHECK_EQUAL(a[11].second, baz);
}
<commit_msg>more tests<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TimSortTest
#include <boost/test/unit_test.hpp>
#include "timsort.hpp"
using namespace gfx;
BOOST_AUTO_TEST_CASE( simple0 ) {
std::vector<int> a;
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 0 );
}
BOOST_AUTO_TEST_CASE( simple1 ) {
std::vector<int> a;
a.push_back(42);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 1 );
BOOST_CHECK_EQUAL( a[0], 42 );
}
BOOST_AUTO_TEST_CASE( simple2 ) {
std::vector<int> a;
a.push_back(10);
a.push_back(20);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 2 );
BOOST_CHECK_EQUAL( a[0], 10);
BOOST_CHECK_EQUAL( a[1], 20 );
a.clear();
a.push_back(20);
a.push_back(10);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a.size(), 2 );
BOOST_CHECK_EQUAL( a[0], 10);
BOOST_CHECK_EQUAL( a[1], 20 );
}
BOOST_AUTO_TEST_CASE( simple10 ) {
std::vector<int> a;
a.push_back(60);
a.push_back(50);
a.push_back( 1);
a.push_back(40);
a.push_back(80);
a.push_back(20);
a.push_back(30);
a.push_back(70);
a.push_back(10);
a.push_back(90);
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a[0], 1 );
BOOST_CHECK_EQUAL( a[1], 10 );
BOOST_CHECK_EQUAL( a[2], 20 );
BOOST_CHECK_EQUAL( a[3], 30 );
BOOST_CHECK_EQUAL( a[4], 40 );
BOOST_CHECK_EQUAL( a[5], 50 );
BOOST_CHECK_EQUAL( a[6], 60 );
BOOST_CHECK_EQUAL( a[7], 70 );
BOOST_CHECK_EQUAL( a[8], 80 );
BOOST_CHECK_EQUAL( a[9], 90 );
std::reverse(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL( a[0], 1 );
BOOST_CHECK_EQUAL( a[1], 10 );
BOOST_CHECK_EQUAL( a[2], 20 );
BOOST_CHECK_EQUAL( a[3], 30 );
BOOST_CHECK_EQUAL( a[4], 40 );
BOOST_CHECK_EQUAL( a[5], 50 );
BOOST_CHECK_EQUAL( a[6], 60 );
BOOST_CHECK_EQUAL( a[7], 70 );
BOOST_CHECK_EQUAL( a[8], 80 );
BOOST_CHECK_EQUAL( a[9], 90 );
}
BOOST_AUTO_TEST_CASE( shuffle30 ) {
const int size = 30;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle31 ) {
const int size = 31;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle32 ) {
const int size = 32;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle128 ) {
const int size = 128;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
BOOST_CHECK_EQUAL(a.size(), size);
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
BOOST_AUTO_TEST_CASE( shuffle1023 ) {
const int size = 1023; // odd number of elements
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( shuffle1024 ) {
const int size = 1024; // even number of elements
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_shuffle1023 ) {
const int size = 1023;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
// sorted-shuffled-sorted pattern
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin() + (size/3 * 1), a.begin() + (size/3 * 2));
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
// shuffled-sorted-shuffled pattern
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin() , a.begin() + (size/3 * 1));
std::random_shuffle(a.begin() + (size/3 * 2), a.end());
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_shuffle1024 ) {
const int size = 1024;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
// sorted-shuffled-sorted pattern
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin() + (size/3 * 1), a.begin() + (size/3 * 2));
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
// shuffled-sorted-shuffled pattern
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin() , a.begin() + (size/3 * 1));
std::random_shuffle(a.begin() + (size/3 * 2), a.end());
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( shuffle1024r ) {
const int size = 1024;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::random_shuffle(a.begin(), a.end());
timsort(a.begin(), a.end(), std::greater<int>());
int j = size;
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (--j+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_reversed1023 ) {
const int size = 1023;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::reverse(a.begin(), a.begin() + (size / 2)); // partial reversed
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( partial_reversed1024 ) {
const int size = 1024;
std::vector<int> a;
for(int i = 0; i < size; ++i) {
a.push_back((i+1) * 10);
}
for(int n = 0; n < 100; ++n) {
std::reverse(a.begin(), a.begin() + (size / 2)); // partial reversed
timsort(a.begin(), a.end(), std::less<int>());
for(int i = 0; i < size; ++i) {
BOOST_CHECK_EQUAL( a[i], (i+1) * 10 );
}
}
}
BOOST_AUTO_TEST_CASE( c_array ) {
int a[] = { 7, 1, 5, 3, 9 };
timsort(a, a + sizeof(a) / sizeof(int), std::less<int>());
BOOST_CHECK_EQUAL(a[0], 1);
BOOST_CHECK_EQUAL(a[1], 3);
BOOST_CHECK_EQUAL(a[2], 5);
BOOST_CHECK_EQUAL(a[3], 7);
BOOST_CHECK_EQUAL(a[4], 9);
}
BOOST_AUTO_TEST_CASE( string_array ) {
std::string a[] = { "7", "1", "5", "3", "9" };
timsort(a, a + sizeof(a) / sizeof(std::string), std::less<std::string>());
BOOST_CHECK_EQUAL(a[0], "1");
BOOST_CHECK_EQUAL(a[1], "3");
BOOST_CHECK_EQUAL(a[2], "5");
BOOST_CHECK_EQUAL(a[3], "7");
BOOST_CHECK_EQUAL(a[4], "9");
}
struct NonDefaultConstructible
{
int i;
NonDefaultConstructible( int i_ )
: i( i_ ) {}
friend bool operator<( NonDefaultConstructible const& x, NonDefaultConstructible const& y ) {
return x.i < y.i;
}
};
BOOST_AUTO_TEST_CASE( non_default_constructible ) {
NonDefaultConstructible a[] = { 7, 1, 5, 3, 9 };
timsort(a, a + sizeof(a) / sizeof(a[0]), std::less<NonDefaultConstructible>());
BOOST_CHECK_EQUAL(a[0].i, 1);
BOOST_CHECK_EQUAL(a[1].i, 3);
BOOST_CHECK_EQUAL(a[2].i, 5);
BOOST_CHECK_EQUAL(a[3].i, 7);
BOOST_CHECK_EQUAL(a[4].i, 9);
}
enum id { foo, bar, baz };
typedef std::pair<int, id> pair_t;
bool less_in_first(pair_t x, pair_t y) {
return x.first < y.first;
}
BOOST_AUTO_TEST_CASE( stability ) {
std::vector< pair_t > a;
for(int i = 100; i >= 0; --i) {
a.push_back( std::make_pair(i, foo) );
a.push_back( std::make_pair(i, bar) );
a.push_back( std::make_pair(i, baz) );
}
timsort(a.begin(), a.end(), &less_in_first);
BOOST_CHECK_EQUAL(a[0].first, 0);
BOOST_CHECK_EQUAL(a[0].second, foo);
BOOST_CHECK_EQUAL(a[1].first, 0);
BOOST_CHECK_EQUAL(a[1].second, bar);
BOOST_CHECK_EQUAL(a[2].first, 0);
BOOST_CHECK_EQUAL(a[2].second, baz);
BOOST_CHECK_EQUAL(a[3].first, 1);
BOOST_CHECK_EQUAL(a[3].second, foo);
BOOST_CHECK_EQUAL(a[4].first, 1);
BOOST_CHECK_EQUAL(a[4].second, bar);
BOOST_CHECK_EQUAL(a[5].first, 1);
BOOST_CHECK_EQUAL(a[5].second, baz);
BOOST_CHECK_EQUAL(a[6].first, 2);
BOOST_CHECK_EQUAL(a[6].second, foo);
BOOST_CHECK_EQUAL(a[7].first, 2);
BOOST_CHECK_EQUAL(a[7].second, bar);
BOOST_CHECK_EQUAL(a[8].first, 2);
BOOST_CHECK_EQUAL(a[8].second, baz);
BOOST_CHECK_EQUAL(a[9].first, 3);
BOOST_CHECK_EQUAL(a[9].second, foo);
BOOST_CHECK_EQUAL(a[10].first, 3);
BOOST_CHECK_EQUAL(a[10].second, bar);
BOOST_CHECK_EQUAL(a[11].first, 3);
BOOST_CHECK_EQUAL(a[11].second, baz);
}
<|endoftext|> |
<commit_before>#include <SDL.h>
#include GLCXX_GL_INCLUDE
#include <iostream>
using namespace std;
#define WIDTH 800
#define HEIGHT 600
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
}
void display(SDL_Window * window)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_GL_SwapWindow(window);
}
int main(int argc, char *argv[])
{
if (SDL_Init(SDL_INIT_VIDEO))
{
printf("Failed to initialize SDL!\n");
return 1;
}
atexit(SDL_Quit);
SDL_Window * window = SDL_CreateWindow(argv[0],
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WIDTH,
HEIGHT,
SDL_WINDOW_OPENGL);
if (!window)
{
printf("Failed to create window!\n");
SDL_Quit();
return 2;
}
SDL_GL_CreateContext(window);
if (gl3wInit())
{
cerr << "Failed to initialize gl3w!" << endl;
return 1;
}
if (!gl3wIsSupported(3, 0))
{
cerr << "OpenGL 3.0 is not supported!" << endl;
return 1;
}
init();
display(window);
SDL_Event event;
while (SDL_WaitEvent(&event))
{
if (event.type == SDL_QUIT)
break;
else if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_ESCAPE)
break;
if (event.key.keysym.sym == SDLK_RETURN)
display(window);
}
}
return 0;
}
<commit_msg>begin testing library from test application<commit_after>#include <SDL.h>
#include GLCXX_GL_INCLUDE
#include <iostream>
#include "glcxx.hpp"
using namespace std;
#define WIDTH 800
#define HEIGHT 600
shared_ptr<glcxx::Shader> vs;
shared_ptr<glcxx::Shader> fs;
shared_ptr<glcxx::Program> program;
bool init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
try
{
vs->create_from_file(GL_VERTEX_SHADER, "test/vert.glsl");
fs->create_from_file(GL_FRAGMENT_SHADER, "test/frag.glsl");
program->create(vs, fs);
}
catch (glcxx::Error & e)
{
cerr << "glcxx error: " << e.what() << endl;
return false;
}
return true;
}
void display(SDL_Window * window)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_GL_SwapWindow(window);
}
int main(int argc, char *argv[])
{
if (SDL_Init(SDL_INIT_VIDEO))
{
printf("Failed to initialize SDL!\n");
return 1;
}
atexit(SDL_Quit);
SDL_Window * window = SDL_CreateWindow(argv[0],
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WIDTH,
HEIGHT,
SDL_WINDOW_OPENGL);
if (!window)
{
printf("Failed to create window!\n");
SDL_Quit();
return 2;
}
SDL_GL_CreateContext(window);
if (gl3wInit())
{
cerr << "Failed to initialize gl3w!" << endl;
return 1;
}
if (!gl3wIsSupported(3, 0))
{
cerr << "OpenGL 3.0 is not supported!" << endl;
return 1;
}
if (!init())
{
return 1;
}
display(window);
SDL_Event event;
while (SDL_WaitEvent(&event))
{
if (event.type == SDL_QUIT)
break;
else if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_ESCAPE)
break;
if (event.key.keysym.sym == SDLK_RETURN)
display(window);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#ifdef _WIN32
#define _UNICODE _UNICODE
#define UNICODE UNICODE
#define TCHAR wchar_t
#else
#define TCHAR char
#endif
#include "../src/sliprock.h"
#include <gtest/gtest.h>
#include <thread>
TEST(CanCreateConnection, ItWorks) {
int fds[2];
ASSERT_EQ(pipe(fds), 0);
SliprockConnection *con =
sliprock_socket("dummy_val", sizeof("dummy_val") - 1);
ASSERT_NE(con, nullptr);
char buf[] = "Test message!";
char buf2[sizeof buf];
bool accept_succeeded = false, open_succeeded = false,
write_succeeded = false, read_succeeded = false;
std::thread thread([&] () {
auto handle = sliprock_accept(con);
if (handle < 0)
return;
if (write(handle, buf, sizeof buf) != sizeof buf)
return;
if (close(handle))
return;
write_succeeded = true;
});
int fd = -1;
SliprockReceiver *receiver = sliprock_open("dummy_val", strlen("dummy_val"), getpid());
if (receiver == nullptr) {
perror("sliprock_open");
goto fail;
}
fd = sliprock_connect(receiver);
if (fd <= 0) {
perror("sliprock_connect");
goto fail;
}
if (read(fd, buf2, sizeof buf) != sizeof buf) {
perror("read");
goto fail;
}
EXPECT_EQ(memcmp(buf2, buf, sizeof buf), 0);
EXPECT_GT(fd, -1);
EXPECT_EQ(close(fd), 0);
fd = -1;
read_succeeded = true;
fail:
EXPECT_EQ(read_succeeded, true);
EXPECT_NE(receiver, nullptr);
close(fd);
sliprock_close_receiver(receiver);
thread.join();
EXPECT_EQ(write_succeeded, true);
sliprock_close(con);
}
int main(int argc, TCHAR **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>clang-format test suite<commit_after>#ifdef _WIN32
#define _UNICODE _UNICODE
#define UNICODE UNICODE
#define TCHAR wchar_t
#else
#define TCHAR char
#endif
#include "../src/sliprock.h"
#include <gtest/gtest.h>
#include <thread>
TEST(CanCreateConnection, ItWorks) {
int fds[2];
ASSERT_EQ(pipe(fds), 0);
SliprockConnection *con =
sliprock_socket("dummy_val", sizeof("dummy_val") - 1);
ASSERT_NE(con, nullptr);
char buf[] = "Test message!";
char buf2[sizeof buf];
bool accept_succeeded = false, open_succeeded = false,
write_succeeded = false, read_succeeded = false;
std::thread thread([&]() {
auto handle = sliprock_accept(con);
if (handle < 0)
return;
if (write(handle, buf, sizeof buf) != sizeof buf)
return;
if (close(handle))
return;
write_succeeded = true;
});
int fd = -1;
SliprockReceiver *receiver =
sliprock_open("dummy_val", strlen("dummy_val"), getpid());
if (receiver == nullptr) {
perror("sliprock_open");
goto fail;
}
fd = sliprock_connect(receiver);
if (fd <= 0) {
perror("sliprock_connect");
goto fail;
}
if (read(fd, buf2, sizeof buf) != sizeof buf) {
perror("read");
goto fail;
}
EXPECT_EQ(memcmp(buf2, buf, sizeof buf), 0);
EXPECT_GT(fd, -1);
EXPECT_EQ(close(fd), 0);
fd = -1;
read_succeeded = true;
fail:
EXPECT_EQ(read_succeeded, true);
EXPECT_NE(receiver, nullptr);
close(fd);
sliprock_close_receiver(receiver);
thread.join();
EXPECT_EQ(write_succeeded, true);
sliprock_close(con);
}
int main(int argc, TCHAR **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#include <err_common.hpp>
#include <type_util.hpp>
#include <string>
#include <iostream>
#include <sstream>
using std::string;
using std::stringstream;
using std::cerr;
AfError::AfError(const char * const funcName,
const int line,
const char * const message, af_err err)
: logic_error (message),
functionName (funcName),
lineNumber(line),
error(err)
{}
AfError::AfError(string funcName,
const int line,
string message, af_err err)
: logic_error (message),
functionName (funcName),
lineNumber(line),
error(err)
{}
const string&
AfError::getFunctionName() const
{
return functionName;
}
int
AfError::getLine() const
{
return lineNumber;
}
af_err
AfError::getError() const
{
return error;
}
AfError::~AfError() throw() {}
TypeError::TypeError(const char * const funcName,
const int line,
const int index, const af_dtype type)
: AfError (funcName, line, "Invalid data type", AF_ERR_INVALID_TYPE),
argIndex(index),
errTypeName(getName(type))
{}
const string& TypeError::getTypeName() const
{
return errTypeName;
}
int TypeError::getArgIndex() const
{
return argIndex;
}
ArgumentError::ArgumentError(const char * const funcName,
const int line,
const int index,
const char * const expectString)
: AfError(funcName, line, "Invalid argument", AF_ERR_INVALID_ARG),
argIndex(index),
expected(expectString)
{
}
const string& ArgumentError::getExpectedCondition() const
{
return expected;
}
int ArgumentError::getArgIndex() const
{
return argIndex;
}
SupportError::SupportError(const char * const funcName,
const int line,
const char * const back)
: AfError(funcName, line, "Unsupported Error", AF_ERR_NOT_SUPPORTED),
backend(back)
{}
const string& SupportError::getBackendName() const
{
return backend;
}
DimensionError::DimensionError(const char * const funcName,
const int line,
const int index,
const char * const expectString)
: AfError(funcName, line, "Invalid dimension", AF_ERR_SIZE),
argIndex(index),
expected(expectString)
{
}
const string& DimensionError::getExpectedCondition() const
{
return expected;
}
int DimensionError::getArgIndex() const
{
return argIndex;
}
af_err processException()
{
stringstream ss;
af_err err= AF_ERR_INTERNAL;
try {
throw;
} catch (const DimensionError &ex) {
ss << "In function " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< "Invalid dimension for argument " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
cerr << ss.str();
err = AF_ERR_SIZE;
} catch (const ArgumentError &ex) {
ss << "In function " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< "Invalid argument at index " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
cerr << ss.str();
err = AF_ERR_SIZE;
} catch (const SupportError &ex) {
ss << ex.getFunctionName()
<< " not supported for " << ex.getBackendName()
<< " backend\n";
cerr << ss.str();
err = AF_ERR_NOT_SUPPORTED;
} catch (const TypeError &ex) {
ss << "In function " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< "Invalid type for argument " << ex.getArgIndex() << "\n";
cerr << ss.str();
err = AF_ERR_INVALID_TYPE;
} catch (const AfError &ex) {
ss << "Internal error in " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< ex.what() << "\n";
cerr << ss.str();
err = ex.getError();
} catch (...) {
cerr << "Unknown error\n";
err = AF_ERR_UNKNOWN;
}
return err;
}
<commit_msg>Fixing a minor bug for ArgumentError<commit_after>#include <err_common.hpp>
#include <type_util.hpp>
#include <string>
#include <iostream>
#include <sstream>
using std::string;
using std::stringstream;
using std::cerr;
AfError::AfError(const char * const funcName,
const int line,
const char * const message, af_err err)
: logic_error (message),
functionName (funcName),
lineNumber(line),
error(err)
{}
AfError::AfError(string funcName,
const int line,
string message, af_err err)
: logic_error (message),
functionName (funcName),
lineNumber(line),
error(err)
{}
const string&
AfError::getFunctionName() const
{
return functionName;
}
int
AfError::getLine() const
{
return lineNumber;
}
af_err
AfError::getError() const
{
return error;
}
AfError::~AfError() throw() {}
TypeError::TypeError(const char * const funcName,
const int line,
const int index, const af_dtype type)
: AfError (funcName, line, "Invalid data type", AF_ERR_INVALID_TYPE),
argIndex(index),
errTypeName(getName(type))
{}
const string& TypeError::getTypeName() const
{
return errTypeName;
}
int TypeError::getArgIndex() const
{
return argIndex;
}
ArgumentError::ArgumentError(const char * const funcName,
const int line,
const int index,
const char * const expectString)
: AfError(funcName, line, "Invalid argument", AF_ERR_INVALID_ARG),
argIndex(index),
expected(expectString)
{
}
const string& ArgumentError::getExpectedCondition() const
{
return expected;
}
int ArgumentError::getArgIndex() const
{
return argIndex;
}
SupportError::SupportError(const char * const funcName,
const int line,
const char * const back)
: AfError(funcName, line, "Unsupported Error", AF_ERR_NOT_SUPPORTED),
backend(back)
{}
const string& SupportError::getBackendName() const
{
return backend;
}
DimensionError::DimensionError(const char * const funcName,
const int line,
const int index,
const char * const expectString)
: AfError(funcName, line, "Invalid dimension", AF_ERR_SIZE),
argIndex(index),
expected(expectString)
{
}
const string& DimensionError::getExpectedCondition() const
{
return expected;
}
int DimensionError::getArgIndex() const
{
return argIndex;
}
af_err processException()
{
stringstream ss;
af_err err= AF_ERR_INTERNAL;
try {
throw;
} catch (const DimensionError &ex) {
ss << "In function " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< "Invalid dimension for argument " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
cerr << ss.str();
err = AF_ERR_SIZE;
} catch (const ArgumentError &ex) {
ss << "In function " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< "Invalid argument at index " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
cerr << ss.str();
err = AF_ERR_ARG;
} catch (const SupportError &ex) {
ss << ex.getFunctionName()
<< " not supported for " << ex.getBackendName()
<< " backend\n";
cerr << ss.str();
err = AF_ERR_NOT_SUPPORTED;
} catch (const TypeError &ex) {
ss << "In function " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< "Invalid type for argument " << ex.getArgIndex() << "\n";
cerr << ss.str();
err = AF_ERR_INVALID_TYPE;
} catch (const AfError &ex) {
ss << "Internal error in " << ex.getFunctionName()
<< "(" << ex.getLine() << "):\n"
<< ex.what() << "\n";
cerr << ss.str();
err = ex.getError();
} catch (...) {
cerr << "Unknown error\n";
err = AF_ERR_UNKNOWN;
}
return err;
}
<|endoftext|> |
<commit_before>/****************************************************************************
* Copyright (C) 2017 by Savoir-faire Linux *
* Author : Nicolas Jäger <nicolas.jager@savoirfairelinux.com> *
* *
* 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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "bannedcontactmodel.h"
//Qt
#include <QtCore/QDateTime>
// LRC
#include "dbus/configurationmanager.h"
#include "contactmethod.h"
#include "phonedirectorymodel.h"
#include <contactrequest.h>
#include <certificate.h>
#include <account.h>
#include "private/pendingcontactrequestmodel_p.h"
#include "person.h"
#include "contactmethod.h"
class BannedContactModelPrivate
{
public:
//Constructor
BannedContactModelPrivate(BannedContactModel* parent);
//Attributes
QList<ContactMethod*> m_lBanned;
Account* m_pAccount ;
private:
BannedContactModel* q_ptr;
};
/**
* constructor of BannedContactModelPrivate.
*/
BannedContactModelPrivate::BannedContactModelPrivate(BannedContactModel* p) : q_ptr(p)
{
}
/**
* constructor of BannedContactModel.
*/
BannedContactModel::BannedContactModel(Account* a) : QAbstractTableModel(a),
d_ptr(new BannedContactModelPrivate(this))
{
d_ptr->m_pAccount = a;
// Load the contacts associated from the daemon and create the cms.
const auto account_contacts
= static_cast<QVector<QMap<QString, QString>>>(ConfigurationManager::instance().getContacts(a->id().data()));
if (a->protocol() == Account::Protocol::RING) {
for (auto contact_info : account_contacts) {
if (contact_info["banned"] == "true") {
auto cm = PhoneDirectoryModel::instance().getNumber(contact_info["id"], a);
add(cm);
}
}
}
}
/**
* destructor of BannedContactModel.
*/
BannedContactModel::~BannedContactModel()
{
delete d_ptr;
}
/**
* QAbstractTableModel function used to return the data.
*/
QVariant
BannedContactModel::data( const QModelIndex& index, int role ) const
{
if (!index.isValid())
return QVariant();
switch(index.column()) {
case Columns::PEER_ID:
switch(role) {
case Qt::DisplayRole:
return d_ptr->m_lBanned[index.row()]->bestId();
case static_cast<int>(ContactMethod::Role::Object):
return QVariant::fromValue(d_ptr->m_lBanned[index.row()]);
}
break;
case Columns::COUNT__:
switch(role) {
case Qt::DisplayRole:
return static_cast<int>(BannedContactModel::Columns::COUNT__);
}
break;
}
return QVariant();
}
/**
* return the number of rows from the model.
*/
int
BannedContactModel::rowCount( const QModelIndex& parent ) const
{
return parent.isValid()? 0 : d_ptr->m_lBanned.size();
}
/**
* return the number of columns from the model.
*/
int
BannedContactModel::columnCount( const QModelIndex& parent ) const
{
return parent.isValid()? 0 : static_cast<int>(BannedContactModel::Columns::COUNT__);
}
/**
* this function add a ContactMethod to the banned list.
* @param cm, the ContactMethod to add to the list.
*/
void
BannedContactModel::add(ContactMethod* cm)
{
beginInsertRows(QModelIndex(),d_ptr->m_lBanned.size(),d_ptr->m_lBanned.size());
d_ptr->m_lBanned << cm;
endInsertRows();
}
/**
* this function removes a ContactMethod from the banned list.
* @param cm, the ContactMethod to remove from the list.
*/
void
BannedContactModel::remove(ContactMethod* cm)
{
auto rowIndex = d_ptr->m_lBanned.indexOf(cm);
beginRemoveRows(QModelIndex(), rowIndex, rowIndex);
d_ptr->m_lBanned.removeAt(rowIndex);
endRemoveRows();
if (!cm->account()) {
qWarning() << "BannedContactModel, cannot remove. cm->account is nullptr";
return;
}
ConfigurationManager::instance().addContact(cm->account()->id(), cm->uri());
}
<commit_msg>BannedContactModel: check if entry exists<commit_after>/****************************************************************************
* Copyright (C) 2017 by Savoir-faire Linux *
* Author : Nicolas Jäger <nicolas.jager@savoirfairelinux.com> *
* *
* 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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "bannedcontactmodel.h"
//Qt
#include <QtCore/QDateTime>
// LRC
#include "dbus/configurationmanager.h"
#include "contactmethod.h"
#include "phonedirectorymodel.h"
#include <contactrequest.h>
#include <certificate.h>
#include <account.h>
#include "private/pendingcontactrequestmodel_p.h"
#include "person.h"
#include "contactmethod.h"
class BannedContactModelPrivate
{
public:
//Constructor
BannedContactModelPrivate(BannedContactModel* parent);
//Attributes
QList<ContactMethod*> m_lBanned;
Account* m_pAccount ;
private:
BannedContactModel* q_ptr;
};
/**
* constructor of BannedContactModelPrivate.
*/
BannedContactModelPrivate::BannedContactModelPrivate(BannedContactModel* p) : q_ptr(p)
{
}
/**
* constructor of BannedContactModel.
*/
BannedContactModel::BannedContactModel(Account* a) : QAbstractTableModel(a),
d_ptr(new BannedContactModelPrivate(this))
{
d_ptr->m_pAccount = a;
// Load the contacts associated from the daemon and create the cms.
const auto account_contacts
= static_cast<QVector<QMap<QString, QString>>>(ConfigurationManager::instance().getContacts(a->id().data()));
if (a->protocol() == Account::Protocol::RING) {
for (auto contact_info : account_contacts) {
if (contact_info["banned"] == "true") {
auto cm = PhoneDirectoryModel::instance().getNumber(contact_info["id"], a);
add(cm);
}
}
}
}
/**
* destructor of BannedContactModel.
*/
BannedContactModel::~BannedContactModel()
{
delete d_ptr;
}
/**
* QAbstractTableModel function used to return the data.
*/
QVariant
BannedContactModel::data( const QModelIndex& index, int role ) const
{
if (!index.isValid())
return QVariant();
switch(index.column()) {
case Columns::PEER_ID:
switch(role) {
case Qt::DisplayRole:
return d_ptr->m_lBanned[index.row()]->bestId();
case static_cast<int>(ContactMethod::Role::Object):
return QVariant::fromValue(d_ptr->m_lBanned[index.row()]);
}
break;
case Columns::COUNT__:
switch(role) {
case Qt::DisplayRole:
return static_cast<int>(BannedContactModel::Columns::COUNT__);
}
break;
}
return QVariant();
}
/**
* return the number of rows from the model.
*/
int
BannedContactModel::rowCount( const QModelIndex& parent ) const
{
return parent.isValid()? 0 : d_ptr->m_lBanned.size();
}
/**
* return the number of columns from the model.
*/
int
BannedContactModel::columnCount( const QModelIndex& parent ) const
{
return parent.isValid()? 0 : static_cast<int>(BannedContactModel::Columns::COUNT__);
}
/**
* this function add a ContactMethod to the banned list.
* @param cm, the ContactMethod to add to the list.
*/
void
BannedContactModel::add(ContactMethod* cm)
{
if (d_ptr->m_lBanned.contains(cm))
return;
beginInsertRows(QModelIndex(),d_ptr->m_lBanned.size(),d_ptr->m_lBanned.size());
d_ptr->m_lBanned << cm;
endInsertRows();
}
/**
* this function removes a ContactMethod from the banned list.
* @param cm, the ContactMethod to remove from the list.
*/
void
BannedContactModel::remove(ContactMethod* cm)
{
auto rowIndex = d_ptr->m_lBanned.indexOf(cm);
beginRemoveRows(QModelIndex(), rowIndex, rowIndex);
d_ptr->m_lBanned.removeAt(rowIndex);
endRemoveRows();
if (!cm->account()) {
qWarning() << "BannedContactModel, cannot remove. cm->account is nullptr";
return;
}
ConfigurationManager::instance().addContact(cm->account()->id(), cm->uri());
}
<|endoftext|> |
<commit_before>
#include "world.hpp"
void collect_collisions_if_object_personal_space_is_at(world& w, unordered_set<object_or_tile_identifier> &results, object_identifier id, shape const& new_shape) {
unordered_set<object_or_tile_identifier> potential_collisions;
w.collect_things_exposed_to_collision_intersecting(potential_collisions, new_shape.bounds());
for (auto const& pc : potential_collisions){
if (const auto tlocp = pc.get_tile_location()) {
if (tile_shape(tlocp->coords()).intersects(new_shape)) {
results.insert(pc);
}
}
if (const auto oidp = pc.get_object_identifier()) {
if (*oidp != id) {
if (const auto ps_shape = find_as_pointer(w.get_object_personal_space_shapes(), *oidp)) {
if (ps_shape->intersects(new_shape)) {
results.insert(pc);
}
}
}
}
}
}
void actually_change_personal_space_shape(
object_identifier id, shape const& new_shape,
object_shapes_t &personal_space_shapes,
world_collision_detector &things_exposed_to_collision) {
personal_space_shapes[id] = new_shape;
things_exposed_to_collision.erase(id);
things_exposed_to_collision.insert(id, new_shape.bounds());
}
cardinal_direction approximate_direction_of_entry(vector3<fine_scalar> const& velocity, bounding_box const& my_bounds, bounding_box const& other_bounds) {
bounding_box overlapping_bounds(my_bounds);
overlapping_bounds.restrict_to(other_bounds);
assert(overlapping_bounds.is_anywhere);
cardinal_direction best_dir = cdir_xplus; // it shouldn't matter what I initialize it to
fine_scalar best = -1;
for (EACH_CARDINAL_DIRECTION(dir)) {
if (velocity.dot<fine_scalar>(dir.v) > 0) {
const fine_scalar overlap_in_this_dimension = overlapping_bounds.max[dir.which_dimension()] - overlapping_bounds.min[dir.which_dimension()];
if (best == -1 || overlap_in_this_dimension < best) {
best = overlap_in_this_dimension;
best_dir = dir;
}
}
}
return best_dir;
}
const int64_t whole_frame_duration = 1ULL << 32;
// Currently unused...
void cap_remaining_displacement_to_new_velocity(vector3<fine_scalar> &remaining_displacement, vector3<fine_scalar> const& new_velocity, int64_t remaining_time) {
for (int i = 0; i < 3; ++i) {
if (new_velocity[i] * remaining_displacement[i] > 0) {
const fine_scalar natural_remaining_displacement_in_this_direction = divide_rounding_towards_zero(new_velocity[i] * remaining_time, whole_frame_duration);
if (std::abs(natural_remaining_displacement_in_this_direction) < std::abs(remaining_displacement[i])) {
remaining_displacement[i] = natural_remaining_displacement_in_this_direction;
}
}
}
}
void update_moving_objects_(
world &w,
objects_map<mobile_object>::type &moving_objects,
object_shapes_t &personal_space_shapes,
object_shapes_t &detail_shapes,
world_collision_detector &things_exposed_to_collision) {
// This entire function is kludgy and horrifically un-optimized.
// Accelerate everything due to gravity.
for (pair<const object_identifier, shared_ptr<mobile_object>> &p : moving_objects) {
p.second->velocity += gravity_acceleration;
// Check any tile it happens to be in for whether there's water there.
// If the object is *partially* in water, it'll crash into a surface water on its first step, which will make this same adjustment.
if (w.make_tile_location(get_containing_tile_coordinates(personal_space_shapes[p.first].get_polygons()[0].get_vertices()[0]), CONTENTS_ONLY).stuff_at().contents() == WATER) {
const fine_scalar current_speed = p.second->velocity.magnitude_within_32_bits();
if (current_speed > max_object_speed_through_water) {
p.second->velocity = p.second->velocity * max_object_speed_through_water / current_speed;
}
}
}
world_collision_detector sweep_box_cd;
unordered_set<object_identifier> objects_with_some_overlap;
for (auto const& p : moving_objects) {
if (shape const* old_personal_space_shape = find_as_pointer(personal_space_shapes, p.first)) {
shape dst_personal_space_shape(*old_personal_space_shape);
dst_personal_space_shape.translate(p.second->velocity / velocity_scale_factor);
bounding_box sweep_bounds = dst_personal_space_shape.bounds();
sweep_bounds.combine_with(old_personal_space_shape->bounds());
sweep_box_cd.insert(p.first, sweep_bounds);
unordered_set<object_or_tile_identifier> this_overlaps;
sweep_box_cd.get_objects_overlapping(this_overlaps, sweep_bounds);
w.collect_things_exposed_to_collision_intersecting(this_overlaps, sweep_bounds);
bool this_is_overlapping = false;
for (object_or_tile_identifier const& foo : this_overlaps) {
if (object_identifier const* bar = foo.get_object_identifier()) {
if (*bar != p.first) {
objects_with_some_overlap.insert(*bar);
this_is_overlapping = true;
}
}
else {
// we must be a tile! nothing to do about that...
this_is_overlapping = true;
}
}
if (this_is_overlapping) objects_with_some_overlap.insert(p.first);
}
}
struct object_trajectory_info {
object_trajectory_info(){}
object_trajectory_info(vector3<fine_scalar>r):last_step_time(0),remaining_displacement(r),accumulated_displacement(0,0,0){}
int64_t last_step_time;
vector3<fine_scalar> remaining_displacement;
vector3<fine_scalar> accumulated_displacement;
};
unordered_map<object_identifier, object_trajectory_info> trajinfo;
struct stepping_times {
int64_t current_time;
std::multimap<int64_t, object_identifier> queued_steps;
stepping_times():current_time(0){}
void queue_next_step(object_identifier id, object_trajectory_info info) {
if (info.last_step_time == whole_frame_duration) return;
fine_scalar dispmag = info.remaining_displacement.magnitude_within_32_bits();
int64_t step_time;
if (dispmag == 0) step_time = whole_frame_duration;
else {
// We're content to move in increments of tile_width >> 5 or less
// ((whole_frame_duration - info.last_step_time) / dispmag) is simply the inverse speed (in normal fine units per time unit) over the rest of the frame
// With (max step distance) = (max step time) * (speed)
// (max step time) = (max step distance) / speed
// Recall that dispmag is in regular fine units instead of velocity units.
const int64_t max_normal_step_duration = (((tile_width >> 5) * (whole_frame_duration - info.last_step_time)) / dispmag);
if (info.last_step_time + max_normal_step_duration > current_time) step_time = info.last_step_time + max_normal_step_duration;
else step_time = current_time;
}
queued_steps.insert(make_pair(std::min(whole_frame_duration, step_time), id));
}
object_identifier pop_next_step() {
current_time = queued_steps.begin()->first;
object_identifier foo = queued_steps.begin()->second;
queued_steps.erase(queued_steps.begin());
return foo;
}
};
stepping_times times;
for (object_identifier id : objects_with_some_overlap) {
shared_ptr<mobile_object> objp = moving_objects[id];
trajinfo[id] = object_trajectory_info(objp->velocity / velocity_scale_factor);
times.queue_next_step(id, trajinfo[id]);
}
while(!times.queued_steps.empty()) {
object_identifier id = times.pop_next_step();
shared_ptr<mobile_object> objp = moving_objects[id];
object_trajectory_info &info = trajinfo[id];
shape new_shape(personal_space_shapes[id]);
vector3<fine_scalar> wanted_displacement_this_step = info.remaining_displacement * (times.current_time - info.last_step_time) / (whole_frame_duration - info.last_step_time);
new_shape.translate(wanted_displacement_this_step);
unordered_set<object_or_tile_identifier> this_overlaps;
w.collect_things_exposed_to_collision_intersecting(this_overlaps, new_shape.bounds());
// This collision code is kludgy because of the way it handles one collision at a time.
// TODO properly consider multiple collisions in the same step.
bool this_step_is_a_collision = false;
bool this_step_needs_adjusting = false;
for (object_or_tile_identifier const& them : this_overlaps) {
if (them != id) {
tile_location const* locp = them.get_tile_location();
if (locp && locp->stuff_at().contents() == WATER) {
const fine_scalar current_speed = objp->velocity.magnitude_within_32_bits();
if (current_speed > max_object_speed_through_water) {
objp->velocity = objp->velocity * max_object_speed_through_water / current_speed;
info.remaining_displacement = info.remaining_displacement * max_object_speed_through_water / current_speed;
this_step_needs_adjusting = true;
}
}
else {
shape their_shape = w.get_personal_space_shape_of_object_or_tile(them);
if (new_shape.intersects(their_shape)) {
this_step_is_a_collision = true;
cardinal_direction approx_impact_dir = approximate_direction_of_entry(objp->velocity, new_shape.bounds(), their_shape.bounds());
objp->velocity -= project_onto_cardinal_direction(objp->velocity, approx_impact_dir);
info.remaining_displacement -= project_onto_cardinal_direction(info.remaining_displacement, approx_impact_dir);
}
}
}
}
if (this_step_is_a_collision) {
info.remaining_displacement -= wanted_displacement_this_step;
info.last_step_time = times.current_time;
}
else if (this_step_needs_adjusting) {
// don't update last_step_time - it will compute another step at current_time
}
else {
actually_change_personal_space_shape(id, new_shape, personal_space_shapes, things_exposed_to_collision);
info.accumulated_displacement += wanted_displacement_this_step;
info.remaining_displacement -= wanted_displacement_this_step;
info.last_step_time = times.current_time;
}
times.queue_next_step(id, info);
if (false) { // if our velocity changed...
info.remaining_displacement = (objp->velocity * (whole_frame_duration - times.current_time)) / (whole_frame_duration * velocity_scale_factor);
unordered_set<object_or_tile_identifier> new_sweep_overlaps;
shape dst_personal_space_shape(personal_space_shapes[id]);
dst_personal_space_shape.translate(info.remaining_displacement);
bounding_box sweep_bounds = dst_personal_space_shape.bounds();
sweep_bounds.combine_with(personal_space_shapes[id].bounds());
sweep_box_cd.erase(id);
sweep_box_cd.insert(id, sweep_bounds);
sweep_box_cd.get_objects_overlapping(new_sweep_overlaps, sweep_bounds);
for (object_or_tile_identifier const& foo : this_overlaps) {
if (object_identifier const* bar = foo.get_object_identifier()) {
if (*bar != id) {
if (objects_with_some_overlap.find(*bar) == objects_with_some_overlap.end()) {
objects_with_some_overlap.insert(*bar);
trajinfo[*bar] = object_trajectory_info(moving_objects[*bar]->velocity / velocity_scale_factor);
times.queue_next_step(*bar, trajinfo[*bar]);
}
}
}
}
}
}
for (auto &p : moving_objects) {
if (objects_with_some_overlap.find(p.first) == objects_with_some_overlap.end()) {
personal_space_shapes[p.first].translate(p.second->velocity / velocity_scale_factor);
detail_shapes[p.first].translate(p.second->velocity / velocity_scale_factor);
}
else {
detail_shapes[p.first].translate(trajinfo[p.first].accumulated_displacement);
}
}
}
void world::update_moving_objects() {
update_moving_objects_(*this, moving_objects, object_personal_space_shapes, object_detail_shapes, things_exposed_to_collision);
}
// If objects overlap with the new position, returns their IDs. If not, changes the shape and returns an empty set.
unordered_set<object_or_tile_identifier> try_to_change_personal_space_shape_(world &w, object_shapes_t &personal_space_shapes, world_collision_detector &things_exposed_to_collision, object_identifier id, shape const& new_shape) {
unordered_set<object_or_tile_identifier> collisions;
collect_collisions_if_object_personal_space_is_at(w, collisions, id, new_shape);
if (collisions.empty()) {
// Actually move (and create if you weren't there):
actually_change_personal_space_shape(id, new_shape, personal_space_shapes, things_exposed_to_collision);
}
return collisions;
}
unordered_set<object_or_tile_identifier> world::try_to_change_personal_space_shape(object_identifier id, shape const& new_shape) {
return try_to_change_personal_space_shape_(*this, object_personal_space_shapes, things_exposed_to_collision, id, new_shape);
}
// Objects can't fail to change their detail shape, but it may cause effects (like blocking a laser beam)
void world::change_detail_shape(object_identifier id, shape const& new_shape) {
// Move
object_detail_shapes[id] = new_shape;
// Currently, moving a detail shape changes nothing.
/*unordered_set<object_identifier> potential_collisions;
collect_things_exposed_to_collision_intersecting(potential_collisions, new_shape.bounds());
for (auto const& pc : potential_collisions){
if (auto oidp = pc.get_object_identifier()) {
if (auto d_shape = find_as_pointer(mobile_object_detail_shapes, *oidp)) {
if (d_shape->intersects(new_shape)) {
}
}
}
}*/
}
<commit_msg>Fixed more errors.<commit_after>
#include "world.hpp"
void collect_collisions_if_object_personal_space_is_at(world& w, unordered_set<object_or_tile_identifier> &results, object_identifier id, shape const& new_shape) {
unordered_set<object_or_tile_identifier> potential_collisions;
w.collect_things_exposed_to_collision_intersecting(potential_collisions, new_shape.bounds());
for (auto const& pc : potential_collisions){
if (const auto tlocp = pc.get_tile_location()) {
if (tile_shape(tlocp->coords()).intersects(new_shape)) {
results.insert(pc);
}
}
if (const auto oidp = pc.get_object_identifier()) {
if (*oidp != id) {
if (const auto ps_shape = find_as_pointer(w.get_object_personal_space_shapes(), *oidp)) {
if (ps_shape->intersects(new_shape)) {
results.insert(pc);
}
}
}
}
}
}
void actually_change_personal_space_shape(
object_identifier id, shape const& new_shape,
object_shapes_t &personal_space_shapes,
world_collision_detector &things_exposed_to_collision) {
personal_space_shapes[id] = new_shape;
things_exposed_to_collision.erase(id);
things_exposed_to_collision.insert(id, new_shape.bounds());
}
cardinal_direction approximate_direction_of_entry(vector3<fine_scalar> const& velocity, bounding_box const& my_bounds, bounding_box const& other_bounds) {
bounding_box overlapping_bounds(my_bounds);
overlapping_bounds.restrict_to(other_bounds);
assert(overlapping_bounds.is_anywhere);
cardinal_direction best_dir = cdir_xplus; // it shouldn't matter what I initialize it to
fine_scalar best = -1;
for (EACH_CARDINAL_DIRECTION(dir)) {
if (velocity.dot<fine_scalar>(dir.v) > 0) {
const fine_scalar overlap_in_this_dimension = overlapping_bounds.max[dir.which_dimension()] - overlapping_bounds.min[dir.which_dimension()];
if (best == -1 || overlap_in_this_dimension < best) {
best = overlap_in_this_dimension;
best_dir = dir;
}
}
}
return best_dir;
}
const int64_t whole_frame_duration = 1ULL << 32;
// Currently unused...
void cap_remaining_displacement_to_new_velocity(vector3<fine_scalar> &remaining_displacement, vector3<fine_scalar> const& new_velocity, int64_t remaining_time) {
for (int i = 0; i < 3; ++i) {
if (new_velocity[i] * remaining_displacement[i] > 0) {
const fine_scalar natural_remaining_displacement_in_this_direction = divide_rounding_towards_zero(new_velocity[i] * remaining_time, whole_frame_duration);
if (std::abs(natural_remaining_displacement_in_this_direction) < std::abs(remaining_displacement[i])) {
remaining_displacement[i] = natural_remaining_displacement_in_this_direction;
}
}
}
}
void update_moving_objects_(
world &w,
objects_map<mobile_object>::type &moving_objects,
object_shapes_t &personal_space_shapes,
object_shapes_t &detail_shapes,
world_collision_detector &things_exposed_to_collision) {
// This entire function is kludgy and horrifically un-optimized.
// Accelerate everything due to gravity.
for (pair<const object_identifier, shared_ptr<mobile_object>> &p : moving_objects) {
p.second->velocity += gravity_acceleration;
// Check any tile it happens to be in for whether there's water there.
// If the object is *partially* in water, it'll crash into a surface water on its first step, which will make this same adjustment.
if (is_water(w.make_tile_location(get_containing_tile_coordinates(personal_space_shapes[p.first].get_polygons()[0].get_vertices()[0]), CONTENTS_ONLY).stuff_at().contents())) {
const fine_scalar current_speed = p.second->velocity.magnitude_within_32_bits();
if (current_speed > max_object_speed_through_water) {
p.second->velocity = p.second->velocity * max_object_speed_through_water / current_speed;
}
}
}
world_collision_detector sweep_box_cd;
unordered_set<object_identifier> objects_with_some_overlap;
for (auto const& p : moving_objects) {
if (shape const* old_personal_space_shape = find_as_pointer(personal_space_shapes, p.first)) {
shape dst_personal_space_shape(*old_personal_space_shape);
dst_personal_space_shape.translate(p.second->velocity / velocity_scale_factor);
bounding_box sweep_bounds = dst_personal_space_shape.bounds();
sweep_bounds.combine_with(old_personal_space_shape->bounds());
sweep_box_cd.insert(p.first, sweep_bounds);
unordered_set<object_or_tile_identifier> this_overlaps;
sweep_box_cd.get_objects_overlapping(this_overlaps, sweep_bounds);
w.collect_things_exposed_to_collision_intersecting(this_overlaps, sweep_bounds);
bool this_is_overlapping = false;
for (object_or_tile_identifier const& foo : this_overlaps) {
if (object_identifier const* bar = foo.get_object_identifier()) {
if (*bar != p.first) {
objects_with_some_overlap.insert(*bar);
this_is_overlapping = true;
}
}
else {
// we must be a tile! nothing to do about that...
this_is_overlapping = true;
}
}
if (this_is_overlapping) objects_with_some_overlap.insert(p.first);
}
}
struct object_trajectory_info {
object_trajectory_info(){}
object_trajectory_info(vector3<fine_scalar>r):last_step_time(0),remaining_displacement(r),accumulated_displacement(0,0,0){}
int64_t last_step_time;
vector3<fine_scalar> remaining_displacement;
vector3<fine_scalar> accumulated_displacement;
};
unordered_map<object_identifier, object_trajectory_info> trajinfo;
struct stepping_times {
int64_t current_time;
std::multimap<int64_t, object_identifier> queued_steps;
stepping_times():current_time(0){}
void queue_next_step(object_identifier id, object_trajectory_info info) {
if (info.last_step_time == whole_frame_duration) return;
fine_scalar dispmag = info.remaining_displacement.magnitude_within_32_bits();
int64_t step_time;
if (dispmag == 0) step_time = whole_frame_duration;
else {
// We're content to move in increments of tile_width >> 5 or less
// ((whole_frame_duration - info.last_step_time) / dispmag) is simply the inverse speed (in normal fine units per time unit) over the rest of the frame
// With (max step distance) = (max step time) * (speed)
// (max step time) = (max step distance) / speed
// Recall that dispmag is in regular fine units instead of velocity units.
const int64_t max_normal_step_duration = (((tile_width >> 5) * (whole_frame_duration - info.last_step_time)) / dispmag);
if (info.last_step_time + max_normal_step_duration > current_time) step_time = info.last_step_time + max_normal_step_duration;
else step_time = current_time;
}
queued_steps.insert(make_pair(std::min(whole_frame_duration, step_time), id));
}
object_identifier pop_next_step() {
current_time = queued_steps.begin()->first;
object_identifier foo = queued_steps.begin()->second;
queued_steps.erase(queued_steps.begin());
return foo;
}
};
stepping_times times;
for (object_identifier id : objects_with_some_overlap) {
shared_ptr<mobile_object> objp = moving_objects[id];
trajinfo[id] = object_trajectory_info(objp->velocity / velocity_scale_factor);
times.queue_next_step(id, trajinfo[id]);
}
while(!times.queued_steps.empty()) {
object_identifier id = times.pop_next_step();
shared_ptr<mobile_object> objp = moving_objects[id];
object_trajectory_info &info = trajinfo[id];
shape new_shape(personal_space_shapes[id]);
vector3<fine_scalar> wanted_displacement_this_step = info.remaining_displacement * (times.current_time - info.last_step_time) / (whole_frame_duration - info.last_step_time);
new_shape.translate(wanted_displacement_this_step);
unordered_set<object_or_tile_identifier> this_overlaps;
w.collect_things_exposed_to_collision_intersecting(this_overlaps, new_shape.bounds());
// This collision code is kludgy because of the way it handles one collision at a time.
// TODO properly consider multiple collisions in the same step.
bool this_step_is_a_collision = false;
bool this_step_needs_adjusting = false;
for (object_or_tile_identifier const& them : this_overlaps) {
if (them != id) {
tile_location const* locp = them.get_tile_location();
if (locp && is_water(locp->stuff_at().contents())) {
const fine_scalar current_speed = objp->velocity.magnitude_within_32_bits();
if (current_speed > max_object_speed_through_water) {
objp->velocity = objp->velocity * max_object_speed_through_water / current_speed;
info.remaining_displacement = info.remaining_displacement * max_object_speed_through_water / current_speed;
this_step_needs_adjusting = true;
}
}
else {
shape their_shape = w.get_personal_space_shape_of_object_or_tile(them);
if (new_shape.intersects(their_shape)) {
this_step_is_a_collision = true;
cardinal_direction approx_impact_dir = approximate_direction_of_entry(objp->velocity, new_shape.bounds(), their_shape.bounds());
objp->velocity -= project_onto_cardinal_direction(objp->velocity, approx_impact_dir);
info.remaining_displacement -= project_onto_cardinal_direction(info.remaining_displacement, approx_impact_dir);
}
}
}
}
if (this_step_is_a_collision) {
info.remaining_displacement -= wanted_displacement_this_step;
info.last_step_time = times.current_time;
}
else if (this_step_needs_adjusting) {
// don't update last_step_time - it will compute another step at current_time
}
else {
actually_change_personal_space_shape(id, new_shape, personal_space_shapes, things_exposed_to_collision);
info.accumulated_displacement += wanted_displacement_this_step;
info.remaining_displacement -= wanted_displacement_this_step;
info.last_step_time = times.current_time;
}
times.queue_next_step(id, info);
if (false) { // if our velocity changed...
info.remaining_displacement = (objp->velocity * (whole_frame_duration - times.current_time)) / (whole_frame_duration * velocity_scale_factor);
unordered_set<object_or_tile_identifier> new_sweep_overlaps;
shape dst_personal_space_shape(personal_space_shapes[id]);
dst_personal_space_shape.translate(info.remaining_displacement);
bounding_box sweep_bounds = dst_personal_space_shape.bounds();
sweep_bounds.combine_with(personal_space_shapes[id].bounds());
sweep_box_cd.erase(id);
sweep_box_cd.insert(id, sweep_bounds);
sweep_box_cd.get_objects_overlapping(new_sweep_overlaps, sweep_bounds);
for (object_or_tile_identifier const& foo : this_overlaps) {
if (object_identifier const* bar = foo.get_object_identifier()) {
if (*bar != id) {
if (objects_with_some_overlap.find(*bar) == objects_with_some_overlap.end()) {
objects_with_some_overlap.insert(*bar);
trajinfo[*bar] = object_trajectory_info(moving_objects[*bar]->velocity / velocity_scale_factor);
times.queue_next_step(*bar, trajinfo[*bar]);
}
}
}
}
}
}
for (auto &p : moving_objects) {
if (objects_with_some_overlap.find(p.first) == objects_with_some_overlap.end()) {
personal_space_shapes[p.first].translate(p.second->velocity / velocity_scale_factor);
detail_shapes[p.first].translate(p.second->velocity / velocity_scale_factor);
}
else {
detail_shapes[p.first].translate(trajinfo[p.first].accumulated_displacement);
}
}
}
void world::update_moving_objects() {
update_moving_objects_(*this, moving_objects, object_personal_space_shapes, object_detail_shapes, things_exposed_to_collision);
}
// If objects overlap with the new position, returns their IDs. If not, changes the shape and returns an empty set.
unordered_set<object_or_tile_identifier> try_to_change_personal_space_shape_(world &w, object_shapes_t &personal_space_shapes, world_collision_detector &things_exposed_to_collision, object_identifier id, shape const& new_shape) {
unordered_set<object_or_tile_identifier> collisions;
collect_collisions_if_object_personal_space_is_at(w, collisions, id, new_shape);
if (collisions.empty()) {
// Actually move (and create if you weren't there):
actually_change_personal_space_shape(id, new_shape, personal_space_shapes, things_exposed_to_collision);
}
return collisions;
}
unordered_set<object_or_tile_identifier> world::try_to_change_personal_space_shape(object_identifier id, shape const& new_shape) {
return try_to_change_personal_space_shape_(*this, object_personal_space_shapes, things_exposed_to_collision, id, new_shape);
}
// Objects can't fail to change their detail shape, but it may cause effects (like blocking a laser beam)
void world::change_detail_shape(object_identifier id, shape const& new_shape) {
// Move
object_detail_shapes[id] = new_shape;
// Currently, moving a detail shape changes nothing.
/*unordered_set<object_identifier> potential_collisions;
collect_things_exposed_to_collision_intersecting(potential_collisions, new_shape.bounds());
for (auto const& pc : potential_collisions){
if (auto oidp = pc.get_object_identifier()) {
if (auto d_shape = find_as_pointer(mobile_object_detail_shapes, *oidp)) {
if (d_shape->intersects(new_shape)) {
}
}
}
}*/
}
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_POTENTIAL_UNIFORM_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_UNIFORM_POTENTIAL_HPP
#include <limits>
namespace mjolnir
{
template<typename T> class System;
// Uniform potential is for test potentila.
// V(r) = 1
// dV/dr = 0
template<typename realT>
class UniformPotential
{
public:
using real_type = realT;
public:
UniformPotential(const real_type k) noexcept
: k_(k)
{}
~UniformPotential() = default;
real_type potential(const real_type) const noexcept
{
return k_;
}
real_type derivative(const real_type) const noexcept
{
return 0.0;
}
template<typename T>
void update(const System<T>&) const noexcept {return;}
static const char* name() noexcept {return "Uniform";}
real_type k() const noexcept {return k_;}
real_type cutoff() const noexcept {return std::numeric_limits<real_type>::infinity();}
private:
real_type k_;
};
} // mjolnir
#endif /* MJOLNIR_UNIFORM_POTENTIAL */
<commit_msg>refactor: fix duplicate include guard<commit_after>#ifndef MJOLNIR_POTENTIAL_LOCAL_UNIFORM_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_LOCAL_UNIFORM_POTENTIAL_HPP
#include <limits>
namespace mjolnir
{
template<typename T> class System;
// Uniform potential is for test potentila.
// V(r) = 1
// dV/dr = 0
template<typename realT>
class UniformPotential
{
public:
using real_type = realT;
public:
UniformPotential(const real_type k) noexcept
: k_(k)
{}
~UniformPotential() = default;
real_type potential(const real_type) const noexcept
{
return k_;
}
real_type derivative(const real_type) const noexcept
{
return 0.0;
}
template<typename T>
void update(const System<T>&) const noexcept {return;}
static const char* name() noexcept {return "Uniform";}
real_type k() const noexcept {return k_;}
real_type cutoff() const noexcept {return std::numeric_limits<real_type>::infinity();}
private:
real_type k_;
};
} // mjolnir
#endif /* MJOLNIR_POTENTIAL_LOCAL_UNIFORM_POTENTIAL_HPP */
<|endoftext|> |
<commit_before>#include "Circle.hpp"
#include <glm/gtx/constants.hpp>
Circle::Circle(GLSLProgram* glslProgram, int segments) :
Mesh::Mesh(glslProgram),
segments(segments)
{
GLfloat anglePerSegmentRads = 3.141 * 2.0f / (float)segments;
//top
vertexData.push_back(Vertex( glm::vec3( 0.0f, 1.0f , 0.0f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5f, 1.0f) ));
for(int i = 1 ; i <= segments ; ++i)
{
//center
vertexData.push_back(Vertex( glm::vec3( 0.0f, 0.0f , 0.0f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5f, 0.5f) ));
GLfloat angleRads = anglePerSegmentRads * i;
GLfloat x = sin(angleRads);
GLfloat y = cos(angleRads);
Vertex v = Vertex( glm::vec3( x,y , 0.000f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5*(x+1),0.5*(y+1)) );
vertexData.push_back(v);
if (i < segments) vertexData.push_back(v);
}
bufferData();
}
<commit_msg>fix glm::two_pi issue - include correct constants file, and use appropriately<commit_after>#include "Circle.hpp"
#include <glm/gtc/constants.hpp>
Circle::Circle(GLSLProgram* glslProgram, int segments) :
Mesh::Mesh(glslProgram),
segments(segments)
{
const static float TWO_PI = glm::two_pi<float>();
GLfloat anglePerSegmentRads = TWO_PI / (float)segments;
//top
vertexData.push_back(Vertex( glm::vec3( 0.0f, 1.0f , 0.0f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5f, 1.0f) ));
for(int i = 1 ; i <= segments ; ++i)
{
//center
vertexData.push_back(Vertex( glm::vec3( 0.0f, 0.0f , 0.0f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5f, 0.5f) ));
GLfloat angleRads = anglePerSegmentRads * i;
GLfloat x = sin(angleRads);
GLfloat y = cos(angleRads);
Vertex v = Vertex( glm::vec3( x,y , 0.000f), glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec2(0.5*(x+1),0.5*(y+1)) );
vertexData.push_back(v);
if (i < segments) vertexData.push_back(v);
}
bufferData();
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
#ifdef BUILD_WITH_PYTHON
#include <iostream>
#include <QApplication>
#include <QClipboard>
#include <QKeyEvent>
#include <QPointer>
#include <QTextCursor>
#include <QTextEdit>
#include <QScrollBar>
#include <QVBoxLayout>
#include <Core/Python/PythonInterpreter.h>
#include <Interface/Application/PythonConsoleWidget.h>
#include <Interface/Application/NetworkEditor.h>
using namespace SCIRun::Core;
using namespace SCIRun::Gui;
class PythonConsoleEdit;
typedef QPointer< PythonConsoleEdit > PythonConsoleEditQWeakPointer;
class PythonConsoleEdit : public QTextEdit
{
public:
PythonConsoleEdit(NetworkEditor* rootNetworkEditor, PythonConsoleWidget* parent);
virtual void keyPressEvent(QKeyEvent* e);
//virtual void focusOutEvent( QFocusEvent* e );
const int document_end();
QString& command_buffer();
void update_command_buffer();
void replace_command_buffer(const QString& text);
void issue_command();
void prompt(const std::string& text) { promptImpl(QString::fromStdString(text)); }
void print_output(const std::string& text){ print_outputImpl(QString::fromStdString(text)); }
void print_error(const std::string& text){ print_errorImpl(QString::fromStdString(text)); }
void print_command(const std::string& text){ print_commandImpl(QString::fromStdString(text)); }
private:
void promptImpl(const QString& text);
void print_outputImpl(const QString& text);
void print_errorImpl(const QString& text);
void print_commandImpl(const QString& text);
NetworkEditor* rootNetworkEditor_;
public:
// The beginning of the area of interactive input, outside which
// changes can't be made to the text edit contents.
int interactive_position_;
// Command history plus the current command buffer
QStringList command_history_;
// Current position in the command history
int command_position_;
//public:
// static void Prompt( PythonConsoleEditQWeakPointer edit, const std::string& text );
// static void PrintOutput( PythonConsoleEditQWeakPointer edit, const std::string& text );
// static void PrintError( PythonConsoleEditQWeakPointer edit, const std::string& text );
// static void PrintCommand( PythonConsoleEditQWeakPointer edit, const std::string& text );
};
PythonConsoleEdit::PythonConsoleEdit(NetworkEditor* rootNetworkEditor, PythonConsoleWidget* parent) :
QTextEdit(parent), rootNetworkEditor_(rootNetworkEditor)
{
this->interactive_position_ = this->document_end();
this->setTabChangesFocus(false);
this->setAcceptDrops(false);
this->setAcceptRichText(false);
this->setUndoRedoEnabled(false);
//this->setLineWrapMode( QTextEdit::NoWrap );
this->document()->setMaximumBlockCount(2048);
QFont f;
f.setFamily("Courier");
f.setStyleHint(QFont::TypeWriter);
f.setFixedPitch(true);
// Set the tab width to 4 spaces
QFontMetrics fm(f, this);
this->setTabStopWidth(fm.width(" "));
QTextCharFormat format;
format.setFont(f);
format.setForeground(QColor(0, 0, 0));
this->setCurrentCharFormat(format);
this->command_history_.append("");
this->command_position_ = 0;
setStyleSheet("background-color: lightgray");
}
void PythonConsoleEdit::keyPressEvent(QKeyEvent* e)
{
this->setTextColor(Qt::black);
QTextCursor text_cursor = this->textCursor();
// Whether there's a current selection
const bool selection = text_cursor.anchor() != text_cursor.position();
// Whether the cursor overlaps the history area
const bool history_area = text_cursor.anchor() < this->interactive_position_ ||
text_cursor.position() < this->interactive_position_;
// Allow copying anywhere in the console ...
if (e->key() == Qt::Key_C && e->modifiers() == Qt::ControlModifier)
{
if (selection)
{
this->copy();
}
else
{
//Core::PythonInterpreter::Instance()->interrupt();
}
e->accept();
return;
}
// Allow cut only if the selection is limited to the interactive area ...
if (e->key() == Qt::Key_X && e->modifiers() == Qt::ControlModifier)
{
if (selection && !history_area)
{
this->cut();
}
e->accept();
return;
}
// Allow paste only if the selection is in the interactive area ...
if (e->key() == Qt::Key_V && e->modifiers() == Qt::ControlModifier)
{
if (!history_area)
{
const QMimeData* const clipboard = QApplication::clipboard()->mimeData();
const QString text = clipboard->text();
if (!text.isNull())
{
text_cursor.insertText(text);
this->update_command_buffer();
}
}
e->accept();
return;
}
// Force the cursor back to the interactive area
if (history_area && e->key() != Qt::Key_Control)
{
text_cursor.setPosition(this->document_end());
this->setTextCursor(text_cursor);
}
switch (e->key())
{
case Qt::Key_Up:
e->accept();
if (this->command_position_ > 0)
{
this->replace_command_buffer(this->command_history_[--this->command_position_]);
}
break;
case Qt::Key_Down:
e->accept();
if (this->command_position_ < this->command_history_.size() - 2)
{
this->replace_command_buffer(this->command_history_[++this->command_position_]);
}
else
{
this->command_position_ = this->command_history_.size() - 1;
this->replace_command_buffer("");
}
break;
case Qt::Key_Left:
if (text_cursor.position() > this->interactive_position_)
{
QTextEdit::keyPressEvent(e);
}
else
{
e->accept();
}
break;
case Qt::Key_Delete:
e->accept();
QTextEdit::keyPressEvent(e);
this->update_command_buffer();
break;
case Qt::Key_Backspace:
e->accept();
if (text_cursor.position() > this->interactive_position_)
{
QTextEdit::keyPressEvent(e);
this->update_command_buffer();
}
break;
case Qt::Key_Tab:
e->accept();
QTextEdit::keyPressEvent(e);
break;
case Qt::Key_Home:
e->accept();
text_cursor.setPosition(this->interactive_position_);
this->setTextCursor(text_cursor);
break;
case Qt::Key_Return:
case Qt::Key_Enter:
e->accept();
text_cursor.setPosition(this->document_end());
this->setTextCursor(text_cursor);
this->issue_command();
break;
default:
e->accept();
QTextEdit::keyPressEvent(e);
this->update_command_buffer();
break;
}
}
const int PythonConsoleEdit::document_end()
{
QTextCursor c(this->document());
c.movePosition(QTextCursor::End);
return c.position();
}
QString& PythonConsoleEdit::command_buffer()
{
return this->command_history_.back();
}
void PythonConsoleEdit::update_command_buffer()
{
this->command_buffer() = this->toPlainText().mid(this->interactive_position_);
}
void PythonConsoleEdit::replace_command_buffer(const QString& text)
{
this->command_buffer() = text;
QTextCursor c(this->document());
c.setPosition(this->interactive_position_);
c.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
c.removeSelectedText();
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::black);
c.setCharFormat(char_format);
c.insertText(text);
}
void PythonConsoleEdit::issue_command()
{
QString command = this->command_buffer();
// Update the command history.
if (!command.isEmpty())
{
this->command_history_.push_back("");
this->command_position_ = this->command_history_.size() - 1;
}
QTextCursor c(this->document());
c.movePosition(QTextCursor::End);
c.insertText("\n");
this->interactive_position_ = this->document_end();
NetworkEditor::InEditingContext iec(rootNetworkEditor_);
auto lines = command.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
for (const auto& line : lines)
{
if (!line.isEmpty())
PythonInterpreter::Instance().run_string(line.toStdString());
}
}
void PythonConsoleEdit::promptImpl(const QString& text)
{
QTextCursor text_cursor(this->document());
// Move the cursor to the end of the document
text_cursor.setPosition(this->document_end());
// if the cursor is currently on a clean line, do nothing, otherwise we move
// the cursor to a new line before showing the prompt.
text_cursor.movePosition(QTextCursor::StartOfLine);
int startpos = text_cursor.position();
text_cursor.movePosition(QTextCursor::EndOfLine);
int endpos = text_cursor.position();
// Make sure the new text will be in the right color
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::green);
text_cursor.setCharFormat(char_format);
if (endpos != startpos)
{
text_cursor.insertText("\n");
}
text_cursor.insertText(text);
this->setTextCursor(text_cursor);
this->interactive_position_ = this->document_end();
this->ensureCursorVisible();
}
void PythonConsoleEdit::print_outputImpl(const QString& text)
{
QTextCursor text_cursor(this->document());
// Move the cursor to the end of the document
text_cursor.setPosition(this->document_end());
// Set the proper text color
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::black);
text_cursor.setCharFormat(char_format);
text_cursor.insertText(text);
this->setTextCursor(text_cursor);
this->interactive_position_ = this->document_end();
this->ensureCursorVisible();
}
void PythonConsoleEdit::print_errorImpl(const QString& text)
{
QTextCursor text_cursor(this->document());
// Move the cursor to the end of the document
text_cursor.setPosition(this->document_end());
// Set the proper text color
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::red);
text_cursor.setCharFormat(char_format);
text_cursor.insertText(text);
this->setTextCursor(text_cursor);
this->interactive_position_ = this->document_end();
this->ensureCursorVisible();
}
void PythonConsoleEdit::print_commandImpl(const QString& text)
{
QTextCursor text_cursor = this->textCursor();
text_cursor.setPosition(this->document_end());
this->setTextCursor(text_cursor);
text_cursor.insertText(text);
this->update_command_buffer();
this->ensureCursorVisible();
}
class PythonConsoleWidgetPrivate
{
public:
PythonConsoleEdit* console_edit_;
};
PythonConsoleWidget::PythonConsoleWidget(NetworkEditor* rootNetworkEditor, QWidget* parent) :
QDockWidget(parent),
private_(new PythonConsoleWidgetPrivate)
{
private_->console_edit_ = new PythonConsoleEdit(rootNetworkEditor, this);
setWidget(private_->console_edit_);
setMinimumSize(500, 500);
setWindowTitle("Python console");
PythonInterpreter::Instance().prompt_signal_.connect(boost::bind(&PythonConsoleEdit::prompt, private_->console_edit_, _1));
PythonInterpreter::Instance().output_signal_.connect(boost::bind(&PythonConsoleEdit::print_output, private_->console_edit_, _1));
PythonInterpreter::Instance().error_signal_.connect(boost::bind(&PythonConsoleEdit::print_error, private_->console_edit_, _1));
showBanner();
PythonInterpreter::Instance().importSCIRunLibrary();
}
PythonConsoleWidget::~PythonConsoleWidget()
{
//this->disconnect_all();
}
void PythonConsoleWidget::showBanner()
{
PythonInterpreter::Instance().print_banner();
}
#endif
<commit_msg>Clang fix<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
#ifdef BUILD_WITH_PYTHON
#include <iostream>
#include <QApplication>
#include <QClipboard>
#include <QKeyEvent>
#include <QPointer>
#include <QTextCursor>
#include <QTextEdit>
#include <QScrollBar>
#include <QVBoxLayout>
#include <Interface/Application/NetworkEditor.h>
#include <Core/Python/PythonInterpreter.h>
#include <Interface/Application/PythonConsoleWidget.h>
using namespace SCIRun::Core;
using namespace SCIRun::Gui;
class PythonConsoleEdit;
typedef QPointer< PythonConsoleEdit > PythonConsoleEditQWeakPointer;
class PythonConsoleEdit : public QTextEdit
{
public:
PythonConsoleEdit(NetworkEditor* rootNetworkEditor, PythonConsoleWidget* parent);
virtual void keyPressEvent(QKeyEvent* e);
//virtual void focusOutEvent( QFocusEvent* e );
const int document_end();
QString& command_buffer();
void update_command_buffer();
void replace_command_buffer(const QString& text);
void issue_command();
void prompt(const std::string& text) { promptImpl(QString::fromStdString(text)); }
void print_output(const std::string& text){ print_outputImpl(QString::fromStdString(text)); }
void print_error(const std::string& text){ print_errorImpl(QString::fromStdString(text)); }
void print_command(const std::string& text){ print_commandImpl(QString::fromStdString(text)); }
private:
void promptImpl(const QString& text);
void print_outputImpl(const QString& text);
void print_errorImpl(const QString& text);
void print_commandImpl(const QString& text);
NetworkEditor* rootNetworkEditor_;
public:
// The beginning of the area of interactive input, outside which
// changes can't be made to the text edit contents.
int interactive_position_;
// Command history plus the current command buffer
QStringList command_history_;
// Current position in the command history
int command_position_;
//public:
// static void Prompt( PythonConsoleEditQWeakPointer edit, const std::string& text );
// static void PrintOutput( PythonConsoleEditQWeakPointer edit, const std::string& text );
// static void PrintError( PythonConsoleEditQWeakPointer edit, const std::string& text );
// static void PrintCommand( PythonConsoleEditQWeakPointer edit, const std::string& text );
};
PythonConsoleEdit::PythonConsoleEdit(NetworkEditor* rootNetworkEditor, PythonConsoleWidget* parent) :
QTextEdit(parent), rootNetworkEditor_(rootNetworkEditor)
{
this->interactive_position_ = this->document_end();
this->setTabChangesFocus(false);
this->setAcceptDrops(false);
this->setAcceptRichText(false);
this->setUndoRedoEnabled(false);
//this->setLineWrapMode( QTextEdit::NoWrap );
this->document()->setMaximumBlockCount(2048);
QFont f;
f.setFamily("Courier");
f.setStyleHint(QFont::TypeWriter);
f.setFixedPitch(true);
// Set the tab width to 4 spaces
QFontMetrics fm(f, this);
this->setTabStopWidth(fm.width(" "));
QTextCharFormat format;
format.setFont(f);
format.setForeground(QColor(0, 0, 0));
this->setCurrentCharFormat(format);
this->command_history_.append("");
this->command_position_ = 0;
setStyleSheet("background-color: lightgray");
}
void PythonConsoleEdit::keyPressEvent(QKeyEvent* e)
{
this->setTextColor(Qt::black);
QTextCursor text_cursor = this->textCursor();
// Whether there's a current selection
const bool selection = text_cursor.anchor() != text_cursor.position();
// Whether the cursor overlaps the history area
const bool history_area = text_cursor.anchor() < this->interactive_position_ ||
text_cursor.position() < this->interactive_position_;
// Allow copying anywhere in the console ...
if (e->key() == Qt::Key_C && e->modifiers() == Qt::ControlModifier)
{
if (selection)
{
this->copy();
}
else
{
//Core::PythonInterpreter::Instance()->interrupt();
}
e->accept();
return;
}
// Allow cut only if the selection is limited to the interactive area ...
if (e->key() == Qt::Key_X && e->modifiers() == Qt::ControlModifier)
{
if (selection && !history_area)
{
this->cut();
}
e->accept();
return;
}
// Allow paste only if the selection is in the interactive area ...
if (e->key() == Qt::Key_V && e->modifiers() == Qt::ControlModifier)
{
if (!history_area)
{
const QMimeData* const clipboard = QApplication::clipboard()->mimeData();
const QString text = clipboard->text();
if (!text.isNull())
{
text_cursor.insertText(text);
this->update_command_buffer();
}
}
e->accept();
return;
}
// Force the cursor back to the interactive area
if (history_area && e->key() != Qt::Key_Control)
{
text_cursor.setPosition(this->document_end());
this->setTextCursor(text_cursor);
}
switch (e->key())
{
case Qt::Key_Up:
e->accept();
if (this->command_position_ > 0)
{
this->replace_command_buffer(this->command_history_[--this->command_position_]);
}
break;
case Qt::Key_Down:
e->accept();
if (this->command_position_ < this->command_history_.size() - 2)
{
this->replace_command_buffer(this->command_history_[++this->command_position_]);
}
else
{
this->command_position_ = this->command_history_.size() - 1;
this->replace_command_buffer("");
}
break;
case Qt::Key_Left:
if (text_cursor.position() > this->interactive_position_)
{
QTextEdit::keyPressEvent(e);
}
else
{
e->accept();
}
break;
case Qt::Key_Delete:
e->accept();
QTextEdit::keyPressEvent(e);
this->update_command_buffer();
break;
case Qt::Key_Backspace:
e->accept();
if (text_cursor.position() > this->interactive_position_)
{
QTextEdit::keyPressEvent(e);
this->update_command_buffer();
}
break;
case Qt::Key_Tab:
e->accept();
QTextEdit::keyPressEvent(e);
break;
case Qt::Key_Home:
e->accept();
text_cursor.setPosition(this->interactive_position_);
this->setTextCursor(text_cursor);
break;
case Qt::Key_Return:
case Qt::Key_Enter:
e->accept();
text_cursor.setPosition(this->document_end());
this->setTextCursor(text_cursor);
this->issue_command();
break;
default:
e->accept();
QTextEdit::keyPressEvent(e);
this->update_command_buffer();
break;
}
}
const int PythonConsoleEdit::document_end()
{
QTextCursor c(this->document());
c.movePosition(QTextCursor::End);
return c.position();
}
QString& PythonConsoleEdit::command_buffer()
{
return this->command_history_.back();
}
void PythonConsoleEdit::update_command_buffer()
{
this->command_buffer() = this->toPlainText().mid(this->interactive_position_);
}
void PythonConsoleEdit::replace_command_buffer(const QString& text)
{
this->command_buffer() = text;
QTextCursor c(this->document());
c.setPosition(this->interactive_position_);
c.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
c.removeSelectedText();
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::black);
c.setCharFormat(char_format);
c.insertText(text);
}
void PythonConsoleEdit::issue_command()
{
QString command = this->command_buffer();
// Update the command history.
if (!command.isEmpty())
{
this->command_history_.push_back("");
this->command_position_ = this->command_history_.size() - 1;
}
QTextCursor c(this->document());
c.movePosition(QTextCursor::End);
c.insertText("\n");
this->interactive_position_ = this->document_end();
NetworkEditor::InEditingContext iec(rootNetworkEditor_);
auto lines = command.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
for (const auto& line : lines)
{
if (!line.isEmpty())
PythonInterpreter::Instance().run_string(line.toStdString());
}
}
void PythonConsoleEdit::promptImpl(const QString& text)
{
QTextCursor text_cursor(this->document());
// Move the cursor to the end of the document
text_cursor.setPosition(this->document_end());
// if the cursor is currently on a clean line, do nothing, otherwise we move
// the cursor to a new line before showing the prompt.
text_cursor.movePosition(QTextCursor::StartOfLine);
int startpos = text_cursor.position();
text_cursor.movePosition(QTextCursor::EndOfLine);
int endpos = text_cursor.position();
// Make sure the new text will be in the right color
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::green);
text_cursor.setCharFormat(char_format);
if (endpos != startpos)
{
text_cursor.insertText("\n");
}
text_cursor.insertText(text);
this->setTextCursor(text_cursor);
this->interactive_position_ = this->document_end();
this->ensureCursorVisible();
}
void PythonConsoleEdit::print_outputImpl(const QString& text)
{
QTextCursor text_cursor(this->document());
// Move the cursor to the end of the document
text_cursor.setPosition(this->document_end());
// Set the proper text color
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::black);
text_cursor.setCharFormat(char_format);
text_cursor.insertText(text);
this->setTextCursor(text_cursor);
this->interactive_position_ = this->document_end();
this->ensureCursorVisible();
}
void PythonConsoleEdit::print_errorImpl(const QString& text)
{
QTextCursor text_cursor(this->document());
// Move the cursor to the end of the document
text_cursor.setPosition(this->document_end());
// Set the proper text color
QTextCharFormat char_format = this->currentCharFormat();
char_format.setForeground(Qt::red);
text_cursor.setCharFormat(char_format);
text_cursor.insertText(text);
this->setTextCursor(text_cursor);
this->interactive_position_ = this->document_end();
this->ensureCursorVisible();
}
void PythonConsoleEdit::print_commandImpl(const QString& text)
{
QTextCursor text_cursor = this->textCursor();
text_cursor.setPosition(this->document_end());
this->setTextCursor(text_cursor);
text_cursor.insertText(text);
this->update_command_buffer();
this->ensureCursorVisible();
}
class PythonConsoleWidgetPrivate
{
public:
PythonConsoleEdit* console_edit_;
};
PythonConsoleWidget::PythonConsoleWidget(NetworkEditor* rootNetworkEditor, QWidget* parent) :
QDockWidget(parent),
private_(new PythonConsoleWidgetPrivate)
{
private_->console_edit_ = new PythonConsoleEdit(rootNetworkEditor, this);
setWidget(private_->console_edit_);
setMinimumSize(500, 500);
setWindowTitle("Python console");
PythonInterpreter::Instance().prompt_signal_.connect(boost::bind(&PythonConsoleEdit::prompt, private_->console_edit_, _1));
PythonInterpreter::Instance().output_signal_.connect(boost::bind(&PythonConsoleEdit::print_output, private_->console_edit_, _1));
PythonInterpreter::Instance().error_signal_.connect(boost::bind(&PythonConsoleEdit::print_error, private_->console_edit_, _1));
showBanner();
PythonInterpreter::Instance().importSCIRunLibrary();
}
PythonConsoleWidget::~PythonConsoleWidget()
{
//this->disconnect_all();
}
void PythonConsoleWidget::showBanner()
{
PythonInterpreter::Instance().print_banner();
}
#endif
<|endoftext|> |
<commit_before>
// This file is part of node-lmdb, the Node.js binding for lmdb
// Copyright (c) 2013 Timur Kristóf
// Licensed to you under the terms of the MIT license
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "node-lmdb.h"
#include <string.h>
using namespace v8;
using namespace node;
CursorWrap::CursorWrap(MDB_cursor *cursor) {
this->cursor = cursor;
this->freeKey = nullptr;
}
CursorWrap::~CursorWrap() {
if (this->cursor) {
this->dw->Unref();
this->tw->Unref();
mdb_cursor_close(this->cursor);
}
}
NAN_METHOD(CursorWrap::ctor) {
Nan::HandleScope scope;
if (info.Length() < 2) {
Nan::ThrowTypeError("Wrong number of arguments");
return;
}
// Extra pessimism...
Nan::MaybeLocal<v8::Object> arg0 = Nan::To<v8::Object>(info[0]);
Nan::MaybeLocal<v8::Object> arg1 = Nan::To<v8::Object>(info[1]);
if (arg0.IsEmpty() || arg1.IsEmpty()) {
Nan::ThrowTypeError("Invalid argument");
return;
}
TxnWrap *tw = Nan::ObjectWrap::Unwrap<TxnWrap>(arg0.ToLocalChecked());
DbiWrap *dw = Nan::ObjectWrap::Unwrap<DbiWrap>(arg1.ToLocalChecked());
// Support 4 cursor modes
// binaryKey parameter missing - legacy behaviour. Might get fixed later...
// binaryKey === true - keys are buffers - always
// binaryKey === false - keys MUST be utf16le zero terminated on disk. If not, throws.
node_lmdb::KeyType kt = dw->keyIsUint32 ? node_lmdb::uint32Key : node_lmdb::legacyStringKey;
if ((info.Length() > 2) && (kt != node_lmdb::uint32Key)) {
bool arg2 = Nan::To<bool>(info[2]).FromMaybe(false);
kt = arg2 ? node_lmdb::binaryKey : node_lmdb::stringKey;
}
// Open the cursor
MDB_cursor *cursor;
int rc = mdb_cursor_open(tw->txn, dw->dbi, &cursor);
if (rc != 0) {
return Nan::ThrowError(mdb_strerror(rc));
}
// Create wrapper
CursorWrap* cw = new CursorWrap(cursor);
cw->dw = dw;
cw->dw->Ref();
cw->tw = tw;
cw->tw->Ref();
cw->kt = kt;
cw->Wrap(info.This());
NanReturnThis();
}
NAN_METHOD(CursorWrap::close) {
Nan::HandleScope scope;
CursorWrap *cw = Nan::ObjectWrap::Unwrap<CursorWrap>(info.This());
mdb_cursor_close(cw->cursor);
cw->dw->Unref();
cw->tw->Unref();
cw->cursor = nullptr;
return;
}
NAN_METHOD(CursorWrap::del) {
Nan::HandleScope scope;
CursorWrap *cw = Nan::ObjectWrap::Unwrap<CursorWrap>(info.This());
// TODO: wrap MDB_NODUPDATA flag
int rc = mdb_cursor_del(cw->cursor, 0);
if (rc != 0) {
return Nan::ThrowError(mdb_strerror(rc));
}
return;
}
Nan::NAN_METHOD_RETURN_TYPE CursorWrap::getCommon(
Nan::NAN_METHOD_ARGS_TYPE info,
MDB_cursor_op op,
argtokey_callback_t (*setKey)(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val&),
void (*setData)(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val&),
void (*freeData)(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val&),
Local<Value> (*convertFunc)(MDB_val &data)
) {
Nan::HandleScope scope;
int al = info.Length();
CursorWrap *cw = Nan::ObjectWrap::Unwrap<CursorWrap>(info.This());
// When a new key is manually set
if (setKey) {
// If we must free the current cw->key, free it now
if (cw->freeKey) {
cw->freeKey(cw->key);
}
// Set new key and assign the deleter function
cw->freeKey = setKey(cw, info, cw->key);
}
if (setData) {
setData(cw, info, cw->data);
}
// Temporary thing, so that we can free up the data if we want to
MDB_val tempdata;
tempdata.mv_size = cw->data.mv_size;
tempdata.mv_data = cw->data.mv_data;
// Temporary bookkeeping for the current key
MDB_val tempKey;
tempKey.mv_size = cw->key.mv_size;
tempKey.mv_data = cw->key.mv_data;
int rc = mdb_cursor_get(cw->cursor, &(cw->key), &(cw->data), op);
// When cw->key.mv_data changes, it means it points inside the database now,
// so we should free the old key now.
if (tempKey.mv_data != cw->key.mv_data) {
if (cw->freeKey) {
cw->freeKey(tempKey);
}
// No need to free the key that points to the database.
cw->freeKey = nullptr;
}
if (rc == MDB_NOTFOUND) {
return info.GetReturnValue().Set(Nan::Null());
}
else if (rc != 0) {
return Nan::ThrowError(mdb_strerror(rc));
}
Local<Value> keyHandle = Nan::Undefined();
if (cw->key.mv_size) {
keyHandle = keyToHandle(cw->key, cw->kt);
}
Local<Value> dataHandle = Nan::Undefined();
if (convertFunc) {
dataHandle = convertFunc(cw->data);
if (al > 0 && info[al - 1]->IsFunction()) {
// In this case, we expect the key/data pair to be correctly filled
const unsigned argc = 2;
Local<Value> argv[argc] = { keyHandle, dataHandle };
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[info.Length() - 1]));
callback->Call(argc, argv);
delete callback;
}
}
if (freeData) {
freeData(cw, info, tempdata);
}
if (convertFunc) {
return info.GetReturnValue().Set(dataHandle);
}
else if (cw->key.mv_size) {
return info.GetReturnValue().Set(keyHandle);
}
return info.GetReturnValue().Set(Nan::True());
}
Nan::NAN_METHOD_RETURN_TYPE CursorWrap::getCommon(Nan::NAN_METHOD_ARGS_TYPE info, MDB_cursor_op op) {
return getCommon(info, op, nullptr, nullptr, nullptr, nullptr);
}
NAN_METHOD(CursorWrap::getCurrentString) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToString);
}
NAN_METHOD(CursorWrap::getCurrentStringUnsafe) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToStringUnsafe);
}
NAN_METHOD(CursorWrap::getCurrentBinary) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToBinary);
}
NAN_METHOD(CursorWrap::getCurrentBinaryUnsafe) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToBinaryUnsafe);
}
NAN_METHOD(CursorWrap::getCurrentNumber) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToNumber);
}
NAN_METHOD(CursorWrap::getCurrentBoolean) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToBoolean);
}
#define MAKE_GET_FUNC(name, op) NAN_METHOD(CursorWrap::name) { return getCommon(info, op); }
MAKE_GET_FUNC(goToFirst, MDB_FIRST);
MAKE_GET_FUNC(goToLast, MDB_LAST);
MAKE_GET_FUNC(goToNext, MDB_NEXT);
MAKE_GET_FUNC(goToPrev, MDB_PREV);
MAKE_GET_FUNC(goToFirstDup, MDB_FIRST_DUP);
MAKE_GET_FUNC(goToLastDup, MDB_LAST_DUP);
MAKE_GET_FUNC(goToNextDup, MDB_NEXT_DUP);
MAKE_GET_FUNC(goToPrevDup, MDB_PREV_DUP);
NAN_METHOD(CursorWrap::goToKey) {
return getCommon(info, MDB_SET, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, nullptr, nullptr, nullptr);
}
NAN_METHOD(CursorWrap::goToRange) {
return getCommon(info, MDB_SET_RANGE, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, nullptr, nullptr, nullptr);
}
static void fillDataFromArg1(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &data) {
if (info[1]->IsString()) {
CustomExternalStringResource::writeTo(info[1]->ToString(), &data);
}
else if (node::Buffer::HasInstance(info[1])) {
data.mv_size = node::Buffer::Length(info[1]);
data.mv_data = node::Buffer::Data(info[1]);
}
else if (info[1]->IsNumber()) {
data.mv_size = sizeof(double);
data.mv_data = new double;
*((double*)data.mv_data) = info[1]->ToNumber(Nan::GetCurrentContext()).ToLocalChecked()->Value();
}
else if (info[1]->IsBoolean()) {
data.mv_size = sizeof(double);
data.mv_data = new bool;
*((bool*)data.mv_data) = info[1]->ToBoolean()->Value();
}
else {
Nan::ThrowError("Invalid data type.");
}
}
static void freeDataFromArg1(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &data) {
if (info[1]->IsString()) {
delete[] (uint16_t*)data.mv_data;
}
else if (node::Buffer::HasInstance(info[1])) {
// I think the data is owned by the node::Buffer so we don't need to free it - need to clarify
}
else if (info[1]->IsNumber()) {
delete (double*)data.mv_data;
}
else if (info[1]->IsBoolean()) {
delete (bool*)data.mv_data;
}
else {
Nan::ThrowError("Invalid data type.");
}
}
NAN_METHOD(CursorWrap::goToDup) {
return getCommon(info, MDB_GET_BOTH, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, fillDataFromArg1, freeDataFromArg1, nullptr);
}
NAN_METHOD(CursorWrap::goToDupRange) {
return getCommon(info, MDB_GET_BOTH_RANGE, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, fillDataFromArg1, freeDataFromArg1, nullptr);
}
void CursorWrap::setupExports(Handle<Object> exports) {
// CursorWrap: Prepare constructor template
Local<FunctionTemplate> cursorTpl = Nan::New<FunctionTemplate>(CursorWrap::ctor);
cursorTpl->SetClassName(Nan::New<String>("Cursor").ToLocalChecked());
cursorTpl->InstanceTemplate()->SetInternalFieldCount(1);
// CursorWrap: Add functions to the prototype
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("close").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::close));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentString").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentString));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentStringUnsafe").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentStringUnsafe));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentBinary").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentBinary));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentBinaryUnsafe").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentBinaryUnsafe));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentNumber").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentNumber));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentBoolean").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentBoolean));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToFirst").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToFirst));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToLast").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToLast));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToNext").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToNext));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToPrev").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToPrev));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToKey").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToKey));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToRange").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToRange));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToFirstDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToFirstDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToLastDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToLastDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToNextDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToNextDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToPrevDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToPrevDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToDupRange").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToDupRange));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("del").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::del));
// Set exports
exports->Set(Nan::New<String>("Cursor").ToLocalChecked(), cursorTpl->GetFunction());
}
<commit_msg>Free key in cursor d'tor...<commit_after>
// This file is part of node-lmdb, the Node.js binding for lmdb
// Copyright (c) 2013 Timur Kristóf
// Licensed to you under the terms of the MIT license
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "node-lmdb.h"
#include <string.h>
using namespace v8;
using namespace node;
CursorWrap::CursorWrap(MDB_cursor *cursor) {
this->cursor = cursor;
this->freeKey = nullptr;
}
CursorWrap::~CursorWrap() {
if (this->cursor) {
this->dw->Unref();
this->tw->Unref();
mdb_cursor_close(this->cursor);
}
if (freeKey) freeKey(key);
}
NAN_METHOD(CursorWrap::ctor) {
Nan::HandleScope scope;
if (info.Length() < 2) {
Nan::ThrowTypeError("Wrong number of arguments");
return;
}
// Extra pessimism...
Nan::MaybeLocal<v8::Object> arg0 = Nan::To<v8::Object>(info[0]);
Nan::MaybeLocal<v8::Object> arg1 = Nan::To<v8::Object>(info[1]);
if (arg0.IsEmpty() || arg1.IsEmpty()) {
Nan::ThrowTypeError("Invalid argument");
return;
}
TxnWrap *tw = Nan::ObjectWrap::Unwrap<TxnWrap>(arg0.ToLocalChecked());
DbiWrap *dw = Nan::ObjectWrap::Unwrap<DbiWrap>(arg1.ToLocalChecked());
// Support 4 cursor modes
// binaryKey parameter missing - legacy behaviour. Might get fixed later...
// binaryKey === true - keys are buffers - always
// binaryKey === false - keys MUST be utf16le zero terminated on disk. If not, throws.
node_lmdb::KeyType kt = dw->keyIsUint32 ? node_lmdb::uint32Key : node_lmdb::legacyStringKey;
if ((info.Length() > 2) && (kt != node_lmdb::uint32Key)) {
bool arg2 = Nan::To<bool>(info[2]).FromMaybe(false);
kt = arg2 ? node_lmdb::binaryKey : node_lmdb::stringKey;
}
// Open the cursor
MDB_cursor *cursor;
int rc = mdb_cursor_open(tw->txn, dw->dbi, &cursor);
if (rc != 0) {
return Nan::ThrowError(mdb_strerror(rc));
}
// Create wrapper
CursorWrap* cw = new CursorWrap(cursor);
cw->dw = dw;
cw->dw->Ref();
cw->tw = tw;
cw->tw->Ref();
cw->kt = kt;
cw->Wrap(info.This());
NanReturnThis();
}
NAN_METHOD(CursorWrap::close) {
Nan::HandleScope scope;
CursorWrap *cw = Nan::ObjectWrap::Unwrap<CursorWrap>(info.This());
mdb_cursor_close(cw->cursor);
cw->dw->Unref();
cw->tw->Unref();
cw->cursor = nullptr;
return;
}
NAN_METHOD(CursorWrap::del) {
Nan::HandleScope scope;
CursorWrap *cw = Nan::ObjectWrap::Unwrap<CursorWrap>(info.This());
// TODO: wrap MDB_NODUPDATA flag
int rc = mdb_cursor_del(cw->cursor, 0);
if (rc != 0) {
return Nan::ThrowError(mdb_strerror(rc));
}
return;
}
Nan::NAN_METHOD_RETURN_TYPE CursorWrap::getCommon(
Nan::NAN_METHOD_ARGS_TYPE info,
MDB_cursor_op op,
argtokey_callback_t (*setKey)(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val&),
void (*setData)(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val&),
void (*freeData)(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val&),
Local<Value> (*convertFunc)(MDB_val &data)
) {
Nan::HandleScope scope;
int al = info.Length();
CursorWrap *cw = Nan::ObjectWrap::Unwrap<CursorWrap>(info.This());
// When a new key is manually set
if (setKey) {
// If we must free the current cw->key, free it now
if (cw->freeKey) {
cw->freeKey(cw->key);
}
// Set new key and assign the deleter function
cw->freeKey = setKey(cw, info, cw->key);
}
if (setData) {
setData(cw, info, cw->data);
}
// Temporary thing, so that we can free up the data if we want to
MDB_val tempdata;
tempdata.mv_size = cw->data.mv_size;
tempdata.mv_data = cw->data.mv_data;
// Temporary bookkeeping for the current key
MDB_val tempKey;
tempKey.mv_size = cw->key.mv_size;
tempKey.mv_data = cw->key.mv_data;
int rc = mdb_cursor_get(cw->cursor, &(cw->key), &(cw->data), op);
// When cw->key.mv_data changes, it means it points inside the database now,
// so we should free the old key now.
if (tempKey.mv_data != cw->key.mv_data) {
if (cw->freeKey) {
cw->freeKey(tempKey);
}
// No need to free the key that points to the database.
cw->freeKey = nullptr;
}
if (rc == MDB_NOTFOUND) {
return info.GetReturnValue().Set(Nan::Null());
}
else if (rc != 0) {
return Nan::ThrowError(mdb_strerror(rc));
}
Local<Value> keyHandle = Nan::Undefined();
if (cw->key.mv_size) {
keyHandle = keyToHandle(cw->key, cw->kt);
}
Local<Value> dataHandle = Nan::Undefined();
if (convertFunc) {
dataHandle = convertFunc(cw->data);
if (al > 0 && info[al - 1]->IsFunction()) {
// In this case, we expect the key/data pair to be correctly filled
const unsigned argc = 2;
Local<Value> argv[argc] = { keyHandle, dataHandle };
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[info.Length() - 1]));
callback->Call(argc, argv);
delete callback;
}
}
if (freeData) {
freeData(cw, info, tempdata);
}
if (convertFunc) {
return info.GetReturnValue().Set(dataHandle);
}
else if (cw->key.mv_size) {
return info.GetReturnValue().Set(keyHandle);
}
return info.GetReturnValue().Set(Nan::True());
}
Nan::NAN_METHOD_RETURN_TYPE CursorWrap::getCommon(Nan::NAN_METHOD_ARGS_TYPE info, MDB_cursor_op op) {
return getCommon(info, op, nullptr, nullptr, nullptr, nullptr);
}
NAN_METHOD(CursorWrap::getCurrentString) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToString);
}
NAN_METHOD(CursorWrap::getCurrentStringUnsafe) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToStringUnsafe);
}
NAN_METHOD(CursorWrap::getCurrentBinary) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToBinary);
}
NAN_METHOD(CursorWrap::getCurrentBinaryUnsafe) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToBinaryUnsafe);
}
NAN_METHOD(CursorWrap::getCurrentNumber) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToNumber);
}
NAN_METHOD(CursorWrap::getCurrentBoolean) {
return getCommon(info, MDB_GET_CURRENT, nullptr, nullptr, nullptr, valToBoolean);
}
#define MAKE_GET_FUNC(name, op) NAN_METHOD(CursorWrap::name) { return getCommon(info, op); }
MAKE_GET_FUNC(goToFirst, MDB_FIRST);
MAKE_GET_FUNC(goToLast, MDB_LAST);
MAKE_GET_FUNC(goToNext, MDB_NEXT);
MAKE_GET_FUNC(goToPrev, MDB_PREV);
MAKE_GET_FUNC(goToFirstDup, MDB_FIRST_DUP);
MAKE_GET_FUNC(goToLastDup, MDB_LAST_DUP);
MAKE_GET_FUNC(goToNextDup, MDB_NEXT_DUP);
MAKE_GET_FUNC(goToPrevDup, MDB_PREV_DUP);
NAN_METHOD(CursorWrap::goToKey) {
return getCommon(info, MDB_SET, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, nullptr, nullptr, nullptr);
}
NAN_METHOD(CursorWrap::goToRange) {
return getCommon(info, MDB_SET_RANGE, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, nullptr, nullptr, nullptr);
}
static void fillDataFromArg1(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &data) {
if (info[1]->IsString()) {
CustomExternalStringResource::writeTo(info[1]->ToString(), &data);
}
else if (node::Buffer::HasInstance(info[1])) {
data.mv_size = node::Buffer::Length(info[1]);
data.mv_data = node::Buffer::Data(info[1]);
}
else if (info[1]->IsNumber()) {
data.mv_size = sizeof(double);
data.mv_data = new double;
*((double*)data.mv_data) = info[1]->ToNumber(Nan::GetCurrentContext()).ToLocalChecked()->Value();
}
else if (info[1]->IsBoolean()) {
data.mv_size = sizeof(double);
data.mv_data = new bool;
*((bool*)data.mv_data) = info[1]->ToBoolean()->Value();
}
else {
Nan::ThrowError("Invalid data type.");
}
}
static void freeDataFromArg1(CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &data) {
if (info[1]->IsString()) {
delete[] (uint16_t*)data.mv_data;
}
else if (node::Buffer::HasInstance(info[1])) {
// I think the data is owned by the node::Buffer so we don't need to free it - need to clarify
}
else if (info[1]->IsNumber()) {
delete (double*)data.mv_data;
}
else if (info[1]->IsBoolean()) {
delete (bool*)data.mv_data;
}
else {
Nan::ThrowError("Invalid data type.");
}
}
NAN_METHOD(CursorWrap::goToDup) {
return getCommon(info, MDB_GET_BOTH, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, fillDataFromArg1, freeDataFromArg1, nullptr);
}
NAN_METHOD(CursorWrap::goToDupRange) {
return getCommon(info, MDB_GET_BOTH_RANGE, [](CursorWrap* cw, Nan::NAN_METHOD_ARGS_TYPE info, MDB_val &key) -> argtokey_callback_t {
return argToKey(info[0], key, cw->kt);
}, fillDataFromArg1, freeDataFromArg1, nullptr);
}
void CursorWrap::setupExports(Handle<Object> exports) {
// CursorWrap: Prepare constructor template
Local<FunctionTemplate> cursorTpl = Nan::New<FunctionTemplate>(CursorWrap::ctor);
cursorTpl->SetClassName(Nan::New<String>("Cursor").ToLocalChecked());
cursorTpl->InstanceTemplate()->SetInternalFieldCount(1);
// CursorWrap: Add functions to the prototype
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("close").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::close));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentString").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentString));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentStringUnsafe").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentStringUnsafe));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentBinary").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentBinary));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentBinaryUnsafe").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentBinaryUnsafe));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentNumber").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentNumber));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("getCurrentBoolean").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::getCurrentBoolean));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToFirst").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToFirst));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToLast").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToLast));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToNext").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToNext));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToPrev").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToPrev));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToKey").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToKey));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToRange").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToRange));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToFirstDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToFirstDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToLastDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToLastDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToNextDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToNextDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToPrevDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToPrevDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToDup").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToDup));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("goToDupRange").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::goToDupRange));
cursorTpl->PrototypeTemplate()->Set(Nan::New<String>("del").ToLocalChecked(), Nan::New<FunctionTemplate>(CursorWrap::del));
// Set exports
exports->Set(Nan::New<String>("Cursor").ToLocalChecked(), cursorTpl->GetFunction());
}
<|endoftext|> |
<commit_before>#include "drawer.hh"
#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <stdexcept>
#include "bezier.hh"
namespace
{
const std::string svg_preambule(
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n"
);
struct svg_shape
{
svg_shape() = default;
svg_shape(const svg_shape &) = delete;
svg_shape & operator=(const svg_shape &) = delete;
virtual void flush(std::ostream & out) = 0;
virtual ~svg_shape()
{
}
};
struct svg_circle
: public svg_shape
{
CanvasPoint pos;
double radius;
std::string fill;
double stroke_width;
std::string stroke;
svg_circle(const CanvasPoint & pos, double radius, const std::string & fill,
double stroke_width, const std::string & stroke)
: pos(pos), radius(radius), fill(fill),
stroke_width(stroke_width), stroke(stroke)
{
}
virtual void flush(std::ostream & out)
{
out << "<circle cx='" << pos.x << "' cy='" << pos.y << "' r='" << radius << "' fill='" << fill << "' "
"stroke='" << stroke << "' stroke-width='" << stroke_width << "' />\n";
}
};
struct svg_rect
: public svg_shape
{
CanvasPoint start, size;
std::string fill;
svg_rect(const CanvasPoint & start, const CanvasPoint & size, const std::string & fill)
: start(start), size(size), fill(fill)
{
}
virtual void flush(std::ostream & out)
{
out << "<rect x='" << start.x << "' y='" << start.y << "' "
"width='" << size.x << "' height='" << size.y << "' fill='" << fill << "' />\n";
}
};
struct svg_cbezier
: public svg_shape
{
BezierCurve path;
std::string stroke;
double width;
svg_cbezier(const BezierCurve & path, const std::string & stroke, double width)
: path(std::move(path)), stroke(stroke), width(width)
{
}
virtual void flush(std::ostream & out)
{
/*
// drawing ugly control points, usefull for debugging
for (auto i(path.cbegin()), i_end(path.cend());
i != i_end; ++i)
{
out << "<circle cx='" << i->p.x << "' cy='" << i->p.y << "' r='2px' fill='black' />\n";
out << "<circle cx='" << i->cm.x << "' cy='" << i->cm.y << "' r='1px' fill='blue' />\n";
out << "<circle cx='" << i->cp.x << "' cy='" << i->cp.y << "' r='1px' fill='green' />\n";
}
*/
out << "<path stroke='gray' stroke-width='" << width << "' fill='none'\n d='";
auto prev(path.cbegin());
out << 'M' << prev->p.x << ',' << prev->p.y << ' ';
for (auto next(prev + 1), i_end(path.cend());
next != i_end; prev = next, ++next)
{
out << 'C' << prev->cp.x << ',' << prev->cp.y << ' '
<< next->cm.x << ',' << next->cm.y << ' '
<< next->p.x << ',' << next->p.y << ' ';
}
out << "' />\n";
}
};
struct svg_text
: public svg_shape
{
std::string body;
CanvasPoint pos;
double size;
svg_text(const std::string & body, const CanvasPoint & pos, double size)
: body(body), pos(pos), size(size)
{
}
virtual void flush(std::ostream & out)
{
out << "<text x='" << pos.x << "' y='" << pos.y << "' font-size='" << size << "' font-family='sans-serif'>\n"
<< body << "\n</text>\n";
}
};
}
struct Drawer::Implementation
{
std::shared_ptr<Projection> projection_;
double canvas_margin_;
const CanvasPoint canvas_, canvas_start_, canvas_end_;
std::deque<std::shared_ptr<svg_shape>> shapes_;
Implementation(const CanvasPoint & canvas, double canvas_margin)
: canvas_margin_(canvas_margin),
canvas_(canvas),
canvas_start_(-canvas.x / 2. - canvas_margin_, -canvas.y / 2. - canvas_margin_),
canvas_end_(canvas.x / 2. + canvas_margin_, canvas_.y / 2. + canvas_margin_)
{
}
bool in_canvas(const CanvasPoint & oc)
{
return oc.x >= canvas_start_.x && oc.y >= canvas_start_.y &&
oc.x <= canvas_end_.x && oc.y <= canvas_end_.y;
}
double mag2size(double mag)
{
static const double e(exp(1));
return exp(-mag / e);
}
double draw_by_magnitudo(const SolarObject & object, double jd, const CanvasPoint & coord)
{
double s(mag2size(object.get_magnitude(jd)));
shapes_.push_back(std::make_shared<svg_circle>(coord, s, "red", s/10., "blue"));
return s;
}
double draw_by_sdiam(const SolarObject & object, double jd, const CanvasPoint & coord, const ln_equ_posn & pos)
{
double s(object.get_sdiam(jd) * projection_->scale_at_point(pos) / 3600.);
shapes_.push_back(std::make_shared<svg_circle>(coord, s, "#22222", 0., ""));
return s;
}
enum {
inside = 0, // 0000
left = 1, // 0001
right = 2, // 0010
bottom = 4, // 0100
top = 8 // 1000
};
int Outcode(const CanvasPoint & p)
{
int code(0);
if (p.x < canvas_start_.x)
code |= left;
else if (p.x > canvas_end_.x)
code |= right;
if (p.y < canvas_start_.y)
code |= bottom;
else if (p.y > canvas_end_.y)
code |= top;
return code;
}
bool CohenSutherland(CanvasPoint p0, CanvasPoint p1)
{
int code0 = Outcode(p0);
int code1 = Outcode(p1);
bool ret(false);
while (true)
{
if (!(code0 | code1))
{
ret = true;
break;
}
else if (code0 & code1)
{
break;
}
else
{
CanvasPoint p;
int code = code0 ? code0 : code1;
// use formulas y = y0 + slope * (x - x0), x = x0 + (1 / slope) * (y - y0)
if (code & top)
{
p.x = p0.x + (p1.x - p0.x) * (canvas_end_.y - p0.y) / (p1.y - p0.y);
p.y = canvas_end_.y;
}
else if (code & bottom)
{
p.x = p0.x + (p1.x - p0.x) * (canvas_start_.y - p0.y) / (p1.y - p0.y);
p.y = canvas_start_.y;
}
else if (code & right)
{
p.y = p0.y + (p1.y - p0.y) * (canvas_end_.x - p0.x) / (p1.x - p0.x);
p.x = canvas_end_.x;
}
else if (code & left)
{
p.y = p0.y + (p1.y - p0.y) * (canvas_start_.x - p0.x) / (p1.x - p0.x);
p.x = canvas_start_.x;
}
if (code == code0)
{
p0 = p;
code0 = Outcode(p0);
}
else
{
p1 = p;
code1 = Outcode(p1);
}
}
}
return ret;
}
};
Drawer::Drawer(const CanvasPoint & canvas, double canvas_margin)
: imp_(new Implementation(canvas, canvas_margin))
{
std::string background_color("white");
imp_->shapes_.push_back(
std::make_shared<svg_rect>(CanvasPoint(-imp_->canvas_.x / 2., -imp_->canvas_.y / 2.),
CanvasPoint(imp_->canvas_.x, imp_->canvas_.y), background_color));
}
Drawer::~Drawer()
{
}
void Drawer::set_projection(const std::shared_ptr<Projection> & projection)
{
imp_->projection_ = projection;
}
void Drawer::store(const char * file) const
{
std::ofstream of(file);
if (! of)
throw std::runtime_error("Can't open file '" + std::string(file) + "' for writing " + std::strerror(errno));
of << svg_preambule;
of << "<svg width='" << imp_->canvas_.x << "mm' height='" << imp_->canvas_.y << "mm' "
"viewBox='" << -imp_->canvas_.x / 2. << ' ' << -imp_->canvas_.y / 2. <<
' ' << imp_->canvas_.x << ' ' << imp_->canvas_.y << "' "
"xmlns='http://www.w3.org/2000/svg' version='1.1'>\n";
for (auto shape(imp_->shapes_.begin()), shape_end(imp_->shapes_.end());
shape != shape_end; ++shape)
(*shape)->flush(of);
of << "</svg>\n";
}
void Drawer::draw(const Star & star)
{
static std::string black("black");
static std::string white("white");
CanvasPoint coord(imp_->projection_->project(star.pos_));
if (! imp_->in_canvas(coord))
return;
double s(imp_->mag2size(star.vmag_));
auto c(std::make_shared<svg_circle>(coord, s, black, .5 * s, white));
imp_->shapes_.push_back(c);
// if (star.vmag_ < 4. && ! star.common_name_.empty())
// imp_->board << Lb::Text(-star.pos_.ra + s, star.pos_.dec, star.common_name_, Lb::Fonts::Helvetica, 3.);
}
void Drawer::draw(const std::vector<ln_equ_posn> & path)
{
std::vector<std::vector<CanvasPoint>> ret(1);
for (auto i(path.begin()), i_end(path.end());
i != i_end; ++i)
{
auto p(imp_->projection_->project(*i));
if (! p.nan())
ret.back().push_back(p);
else if (! ret.back().empty())
ret.push_back(std::vector<CanvasPoint>());
}
std::vector<BezierCurve> strips(1);
for (auto b(ret.cbegin()), b_end(ret.cend());
b != b_end; ++b)
{
if (! strips.back().empty())
strips.push_back(BezierCurve());
auto beziered(interpolate_bezier(*b));
auto first(beziered.cbegin()), second(first + 1);
for (auto end(beziered.cend());
second != end; first = second, ++second)
{
if (imp_->CohenSutherland(first->p, second->p))
{
if (strips.back().empty())
strips.back().push_back(*first);
strips.back().push_back(*second);
}
else if (! strips.back().empty())
strips.push_back(BezierCurve());
}
}
for (auto i(strips.cbegin()), i_end(strips.cend());
i != i_end; ++i)
if (! i->empty())
imp_->shapes_.push_back(std::make_shared<svg_cbezier>(*i, "#888888", 0.1));
}
void Drawer::draw(const std::string & body, const ln_equ_posn & pos)
{
imp_->shapes_.push_back(std::make_shared<svg_text>(body, imp_->projection_->project(pos), 4.));
}
void Drawer::draw(const SolarObject & object, double jd, object_rendering_type type, bool label)
{
auto pos(object.get_equ_coords(jd));
auto coord(imp_->projection_->project(pos));
double s(0.);
switch (type)
{
case magnitudo:
s = imp_->draw_by_magnitudo(object, jd, coord);
break;
case sdiam:
s = imp_->draw_by_sdiam(object, jd, coord, pos);
break;
}
if (label)
{
coord.x += s;
coord.y += 1.;
imp_->shapes_.push_back(std::make_shared<svg_text>(object.name(), coord, 4.));
}
}
<commit_msg>use nan and clipping<commit_after>#include "drawer.hh"
#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <stdexcept>
#include "bezier.hh"
namespace
{
const std::string svg_preambule(
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n"
);
struct svg_shape
{
svg_shape() = default;
svg_shape(const svg_shape &) = delete;
svg_shape & operator=(const svg_shape &) = delete;
virtual void flush(std::ostream & out) = 0;
virtual ~svg_shape()
{
}
};
struct svg_circle
: public svg_shape
{
CanvasPoint pos;
double radius;
std::string fill;
double stroke_width;
std::string stroke;
svg_circle(const CanvasPoint & pos, double radius, const std::string & fill,
double stroke_width, const std::string & stroke)
: pos(pos), radius(radius), fill(fill),
stroke_width(stroke_width), stroke(stroke)
{
}
virtual void flush(std::ostream & out)
{
out << "<circle cx='" << pos.x << "' cy='" << pos.y << "' r='" << radius << "' fill='" << fill << "' "
"stroke='" << stroke << "' stroke-width='" << stroke_width << "' />\n";
}
};
struct svg_rect
: public svg_shape
{
CanvasPoint start, size;
std::string fill;
svg_rect(const CanvasPoint & start, const CanvasPoint & size, const std::string & fill)
: start(start), size(size), fill(fill)
{
}
virtual void flush(std::ostream & out)
{
out << "<rect x='" << start.x << "' y='" << start.y << "' "
"width='" << size.x << "' height='" << size.y << "' fill='" << fill << "' />\n";
}
};
struct svg_cbezier
: public svg_shape
{
BezierCurve path;
std::string stroke;
double width;
svg_cbezier(const BezierCurve & path, const std::string & stroke, double width)
: path(std::move(path)), stroke(stroke), width(width)
{
}
virtual void flush(std::ostream & out)
{
/*
// drawing ugly control points, usefull for debugging
for (auto i(path.cbegin()), i_end(path.cend());
i != i_end; ++i)
{
out << "<circle cx='" << i->p.x << "' cy='" << i->p.y << "' r='2px' fill='black' />\n";
out << "<circle cx='" << i->cm.x << "' cy='" << i->cm.y << "' r='1px' fill='blue' />\n";
out << "<circle cx='" << i->cp.x << "' cy='" << i->cp.y << "' r='1px' fill='green' />\n";
}
*/
out << "<path stroke='gray' stroke-width='" << width << "' fill='none'\n d='";
auto prev(path.cbegin());
out << 'M' << prev->p.x << ',' << prev->p.y << ' ';
for (auto next(prev + 1), i_end(path.cend());
next != i_end; prev = next, ++next)
{
out << 'C' << prev->cp.x << ',' << prev->cp.y << ' '
<< next->cm.x << ',' << next->cm.y << ' '
<< next->p.x << ',' << next->p.y << ' ';
}
out << "' />\n";
}
};
struct svg_text
: public svg_shape
{
std::string body;
CanvasPoint pos;
double size;
svg_text(const std::string & body, const CanvasPoint & pos, double size)
: body(body), pos(pos), size(size)
{
}
virtual void flush(std::ostream & out)
{
out << "<text x='" << pos.x << "' y='" << pos.y << "' font-size='" << size << "' font-family='sans-serif'>\n"
<< body << "\n</text>\n";
}
};
}
struct Drawer::Implementation
{
std::shared_ptr<Projection> projection_;
double canvas_margin_;
const CanvasPoint canvas_, canvas_start_, canvas_end_;
std::deque<std::shared_ptr<svg_shape>> shapes_;
Implementation(const CanvasPoint & canvas, double canvas_margin)
: canvas_margin_(canvas_margin),
canvas_(canvas),
canvas_start_(-canvas.x / 2. - canvas_margin_, -canvas.y / 2. - canvas_margin_),
canvas_end_(canvas.x / 2. + canvas_margin_, canvas_.y / 2. + canvas_margin_)
{
}
bool in_canvas(const CanvasPoint & oc)
{
return oc.x >= canvas_start_.x && oc.y >= canvas_start_.y &&
oc.x <= canvas_end_.x && oc.y <= canvas_end_.y;
}
double mag2size(double mag)
{
static const double e(exp(1));
return exp(-mag / e);
}
double draw_by_magnitudo(const SolarObject & object, double jd, const CanvasPoint & coord)
{
double s(mag2size(object.get_magnitude(jd)));
shapes_.push_back(std::make_shared<svg_circle>(coord, s, "red", s/10., "blue"));
return s;
}
double draw_by_sdiam(const SolarObject & object, double jd, const CanvasPoint & coord, const ln_equ_posn & pos)
{
double s(object.get_sdiam(jd) * projection_->scale_at_point(pos) / 3600.);
shapes_.push_back(std::make_shared<svg_circle>(coord, s, "#22222", 0., ""));
return s;
}
enum {
inside = 0, // 0000
left = 1, // 0001
right = 2, // 0010
bottom = 4, // 0100
top = 8 // 1000
};
int Outcode(const CanvasPoint & p)
{
int code(0);
if (p.x < canvas_start_.x)
code |= left;
else if (p.x > canvas_end_.x)
code |= right;
if (p.y < canvas_start_.y)
code |= bottom;
else if (p.y > canvas_end_.y)
code |= top;
return code;
}
bool CohenSutherland(CanvasPoint p0, CanvasPoint p1)
{
int code0 = Outcode(p0);
int code1 = Outcode(p1);
bool ret(false);
while (true)
{
if (!(code0 | code1))
{
ret = true;
break;
}
else if (code0 & code1)
{
break;
}
else
{
CanvasPoint p;
int code = code0 ? code0 : code1;
// use formulas y = y0 + slope * (x - x0), x = x0 + (1 / slope) * (y - y0)
if (code & top)
{
p.x = p0.x + (p1.x - p0.x) * (canvas_end_.y - p0.y) / (p1.y - p0.y);
p.y = canvas_end_.y;
}
else if (code & bottom)
{
p.x = p0.x + (p1.x - p0.x) * (canvas_start_.y - p0.y) / (p1.y - p0.y);
p.y = canvas_start_.y;
}
else if (code & right)
{
p.y = p0.y + (p1.y - p0.y) * (canvas_end_.x - p0.x) / (p1.x - p0.x);
p.x = canvas_end_.x;
}
else if (code & left)
{
p.y = p0.y + (p1.y - p0.y) * (canvas_start_.x - p0.x) / (p1.x - p0.x);
p.x = canvas_start_.x;
}
if (code == code0)
{
p0 = p;
code0 = Outcode(p0);
}
else
{
p1 = p;
code1 = Outcode(p1);
}
}
}
return ret;
}
};
Drawer::Drawer(const CanvasPoint & canvas, double canvas_margin)
: imp_(new Implementation(canvas, canvas_margin))
{
std::string background_color("white");
imp_->shapes_.push_back(
std::make_shared<svg_rect>(CanvasPoint(-imp_->canvas_.x / 2., -imp_->canvas_.y / 2.),
CanvasPoint(imp_->canvas_.x, imp_->canvas_.y), background_color));
}
Drawer::~Drawer()
{
}
void Drawer::set_projection(const std::shared_ptr<Projection> & projection)
{
imp_->projection_ = projection;
}
void Drawer::store(const char * file) const
{
std::ofstream of(file);
if (! of)
throw std::runtime_error("Can't open file '" + std::string(file) + "' for writing " + std::strerror(errno));
of << svg_preambule;
of << "<svg width='" << imp_->canvas_.x << "mm' height='" << imp_->canvas_.y << "mm' "
"viewBox='" << -imp_->canvas_.x / 2. << ' ' << -imp_->canvas_.y / 2. <<
' ' << imp_->canvas_.x << ' ' << imp_->canvas_.y << "' "
"xmlns='http://www.w3.org/2000/svg' version='1.1'>\n";
for (auto shape(imp_->shapes_.begin()), shape_end(imp_->shapes_.end());
shape != shape_end; ++shape)
(*shape)->flush(of);
of << "</svg>\n";
}
void Drawer::draw(const Star & star)
{
static std::string black("black");
static std::string white("white");
CanvasPoint coord(imp_->projection_->project(star.pos_));
if (! imp_->in_canvas(coord))
return;
double s(imp_->mag2size(star.vmag_));
auto c(std::make_shared<svg_circle>(coord, s, black, .5 * s, white));
imp_->shapes_.push_back(c);
// if (star.vmag_ < 4. && ! star.common_name_.empty())
// imp_->board << Lb::Text(-star.pos_.ra + s, star.pos_.dec, star.common_name_, Lb::Fonts::Helvetica, 3.);
}
void Drawer::draw(const std::vector<ln_equ_posn> & path)
{
std::vector<std::vector<CanvasPoint>> ret(1);
for (auto i(path.begin()), i_end(path.end());
i != i_end; ++i)
{
auto p(imp_->projection_->project(*i));
if (! p.nan())
ret.back().push_back(p);
else if (! ret.back().empty())
ret.push_back(std::vector<CanvasPoint>());
}
std::vector<BezierCurve> strips(1);
for (auto b(ret.cbegin()), b_end(ret.cend());
b != b_end; ++b)
{
if (! strips.back().empty())
strips.push_back(BezierCurve());
auto beziered(interpolate_bezier(*b));
auto first(beziered.cbegin()), second(first + 1);
for (auto end(beziered.cend());
second != end; first = second, ++second)
{
if (imp_->CohenSutherland(first->p, second->p))
{
if (strips.back().empty())
strips.back().push_back(*first);
strips.back().push_back(*second);
}
else if (! strips.back().empty())
strips.push_back(BezierCurve());
}
}
for (auto i(strips.cbegin()), i_end(strips.cend());
i != i_end; ++i)
if (! i->empty())
imp_->shapes_.push_back(std::make_shared<svg_cbezier>(*i, "#888888", 0.1));
}
void Drawer::draw(const std::string & body, const ln_equ_posn & pos)
{
auto coord(imp_->projection_->project(pos));
if (coord.nan() || ! imp_->in_canvas(coord))
return;
imp_->shapes_.push_back(std::make_shared<svg_text>(body, coord, 4.));
}
void Drawer::draw(const SolarObject & object, double jd, object_rendering_type type, bool label)
{
auto pos(object.get_equ_coords(jd));
auto coord(imp_->projection_->project(pos));
if (coord.nan() || ! imp_->in_canvas(coord))
return;
double s(0.);
switch (type)
{
case magnitudo:
s = imp_->draw_by_magnitudo(object, jd, coord);
break;
case sdiam:
s = imp_->draw_by_sdiam(object, jd, coord, pos);
break;
}
if (label)
{
coord.x += s;
coord.y += 1.;
imp_->shapes_.push_back(std::make_shared<svg_text>(object.name(), coord, 4.));
}
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* cursor.cxx
*
* DESCRIPTION
* implementation of libpqxx STL-style cursor classes.
* These classes wrap SQL cursors in STL-like interfaces
*
* Copyright (c) 2004-2006, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-internal.hxx"
#include <cstdlib>
#include "pqxx/cursor"
#include "pqxx/result"
#include "pqxx/transaction"
using namespace PGSTD;
namespace
{
/// Compute actual displacement based on requested and reported displacements
pqxx::cursor_base::difference_type adjust(
pqxx::cursor_base::difference_type d,
pqxx::cursor_base::difference_type r)
{
const pqxx::cursor_base::difference_type hoped = labs(d);
pqxx::cursor_base::difference_type actual = r;
if (hoped < 0 || r < hoped) ++actual;
return (d < 0) ? -actual : actual;
}
}
pqxx::cursor_base::cursor_base(transaction_base *context,
const PGSTD::string &Name,
bool embellish_name) :
m_context(context),
m_done(false),
m_name(embellish_name ? context->conn().adorn_name(Name) : Name),
m_adopted(false),
m_ownership(loose),
m_lastfetch(),
m_lastmove()
{
}
string pqxx::cursor_base::stridestring(difference_type n)
{
/* Some special-casing for ALL and BACKWARD ALL here. We used to use numeric
* "infinities" for difference_type for this (the highest and lowest possible
* values for "long"), but for PostgreSQL 8.0 at least, the backend appears to
* expect a 32-bit number and fails to parse large 64-bit numbers.
* We could change the typedef to match this behaviour, but that would break
* if/when Postgres is changed to accept 64-bit displacements.
*/
static const string All("ALL"), BackAll("BACKWARD ALL");
if (n == all()) return All;
else if (n == backward_all()) return BackAll;
return to_string(n);
}
namespace
{
/// Is this character a "useless trailing character" in a query?
/** A character is "useless" at the end of a query if it is either whitespace or
* a semicolon.
*/
inline bool useless_trail(char c)
{
return isspace(c) || c==';';
}
}
void pqxx::cursor_base::declare(const PGSTD::string &query,
accesspolicy ap,
updatepolicy up,
ownershippolicy op,
bool hold)
{
stringstream cq, qn;
/* Strip trailing semicolons (and whitespace, as side effect) off query. The
* whitespace is stripped because it might otherwise mask a semicolon. After
* this, the remaining useful query will be the sequence defined by
* query.begin() and last, i.e. last may be equal to query.end() or point to
* the first useless trailing character.
*/
string::const_iterator last = query.end();
for (--last; last!=query.begin() && useless_trail(*last); --last);
if (last==query.begin() && useless_trail(*last))
throw invalid_argument("Cursor created on empty query");
++last;
cq << "DECLARE \"" << name() << "\" ";
if (m_context->conn().supports(connection_base::cap_cursor_scroll))
{
if (ap == forward_only) cq << "NO ";
cq << "SCROLL ";
}
cq << "CURSOR ";
if (hold)
{
if (!m_context->conn().supports(connection_base::cap_cursor_with_hold))
throw runtime_error("Cursor " + name() + " "
"created for use outside of its originating transaction, "
"but this backend version does not support that.");
cq << "WITH HOLD ";
}
cq << "FOR " << string(query.begin(),last) << ' ';
if (up != update) cq << "FOR READ ONLY ";
else if (!m_context->conn().supports(connection_base::cap_cursor_update))
throw runtime_error("Cursor " + name() + " "
"created as updatable, "
"but this backend version does not support that.");
else cq << "FOR UPDATE ";
qn << "[DECLARE " << name() << ']';
m_context->exec(cq, qn.str());
// If we're creating a WITH HOLD cursor, noone is going to destroy it until
// after this transaction. That means the connection cannot be deactivated
// without losing the cursor.
m_ownership = op;
if (op==loose) m_context->m_reactivation_avoidance.add(1);
}
void pqxx::cursor_base::adopt(ownershippolicy op)
{
// If we take responsibility for destroying the cursor, that's one less reason
// not to allow the connection to be deactivated and reactivated.
if (op==owned) m_context->m_reactivation_avoidance.add(-1);
m_adopted = true;
m_ownership = op;
}
void pqxx::cursor_base::close() throw ()
{
if (m_ownership==owned)
{
try { m_context->exec("CLOSE " + name()); } catch (const exception &) { }
if (m_adopted) m_context->m_reactivation_avoidance.add(-1);
m_ownership = loose;
}
}
pqxx::result pqxx::cursor_base::fetch(difference_type n)
{
result r;
if (n)
{
// We cache the last-executed fetch query. If the current fetch uses the
// same distance, we just re-use the cached string instead of composing a
// new one.
const string fq(
(n == m_lastfetch.dist) ?
m_lastfetch.query :
"FETCH " + stridestring(n) + " IN \"" + name() + "\"");
// Set m_done on exception (but no need for try/catch)
m_done = true;
r = m_context->exec(fq);
if (!r.empty()) m_done = false;
}
return r;
}
pqxx::result pqxx::cursor_base::fetch(difference_type n, difference_type &d)
{
result r(cursor_base::fetch(n));
d = adjust(n, r.size());
return r;
}
template<> void
pqxx::cursor_base::check_displacement<pqxx::cursor_base::forward_only>(
difference_type d) const
{
if (d < 0)
throw logic_error("Attempt to move cursor " + name() + " "
"backwards (this cursor is only allowed to move forwards)");
}
pqxx::cursor_base::difference_type pqxx::cursor_base::move(difference_type n)
{
if (!n) return 0;
const string mq(
(n == m_lastmove.dist) ?
m_lastmove.query :
"MOVE " + stridestring(n) + " IN \"" + name() + "\"");
// Set m_done on exception (but no need for try/catch)
m_done = true;
const result r(m_context->exec(mq));
// Starting with the libpq in PostgreSQL 7.4, PQcmdTuples() (which we call
// indirectly here) also returns the number of rows skipped by a MOVE
difference_type d = r.affected_rows();
// We may not have PQcmdTuples(), or this may be a libpq version that doesn't
// implement it for MOVE yet. We'll also get zero if we decide to use a
// prepared statement for the MOVE.
if (!d)
{
static const string StdResponse("MOVE ");
if (strncmp(r.CmdStatus(), StdResponse.c_str(), StdResponse.size()) != 0)
throw internal_error("cursor MOVE returned "
"'" + string(r.CmdStatus()) + "' "
"(expected '" + StdResponse + "')");
from_string(r.CmdStatus()+StdResponse.size(), d);
}
m_done = (d != n);
return d;
}
pqxx::cursor_base::difference_type
pqxx::cursor_base::move(difference_type n, difference_type &d)
{
const difference_type got = cursor_base::move(n);
d = adjust(n, got);
return got;
}
pqxx::icursorstream::icursorstream(pqxx::transaction_base &context,
const PGSTD::string &query,
const PGSTD::string &basename,
difference_type Stride) :
super(&context, query, basename),
m_stride(Stride),
m_realpos(0),
m_reqpos(0),
m_iterators(0)
{
set_stride(Stride);
}
pqxx::icursorstream::icursorstream(transaction_base &Context,
const result::field &Name,
difference_type Stride) :
super(&Context, Name.c_str()),
m_stride(Stride),
m_realpos(0),
m_reqpos(0),
m_iterators(0)
{
set_stride(Stride);
}
void pqxx::icursorstream::set_stride(difference_type n)
{
if (n < 1)
throw invalid_argument("Attempt to set cursor stride to " + to_string(n));
m_stride = n;
}
pqxx::result pqxx::icursorstream::fetchblock()
{
const result r(fetch(m_stride));
m_realpos += r.size();
return r;
}
pqxx::icursorstream &pqxx::icursorstream::ignore(PGSTD::streamsize n)
{
m_realpos += move(n);
return *this;
}
pqxx::icursorstream::size_type pqxx::icursorstream::forward(size_type n)
{
m_reqpos += n*m_stride;
return m_reqpos;
}
void pqxx::icursorstream::insert_iterator(icursor_iterator *i) throw ()
{
i->m_next = m_iterators;
if (m_iterators) m_iterators->m_prev = i;
m_iterators = i;
}
void pqxx::icursorstream::remove_iterator(icursor_iterator *i) const throw ()
{
if (i == m_iterators)
{
m_iterators = i->m_next;
if (m_iterators) m_iterators->m_prev = 0;
}
else
{
i->m_prev->m_next = i->m_next;
if (i->m_next) i->m_next->m_prev = i->m_prev;
}
i->m_prev = 0;
i->m_next = 0;
}
void pqxx::icursorstream::service_iterators(size_type topos)
{
if (topos < m_realpos) return;
typedef multimap<size_type,icursor_iterator*> todolist;
todolist todo;
for (icursor_iterator *i = m_iterators; i; i = i->m_next)
if (i->m_pos >= m_realpos && i->m_pos <= topos)
todo.insert(todolist::value_type(i->m_pos, i));
const todolist::const_iterator todo_end(todo.end());
for (todolist::const_iterator i = todo.begin(); i != todo_end; )
{
const size_type readpos = i->first;
if (readpos > m_realpos) ignore(readpos - m_realpos);
const result r = fetchblock();
for ( ; i != todo_end && i->first == readpos; ++i)
i->second->fill(r);
}
}
pqxx::icursor_iterator::icursor_iterator() throw () :
m_stream(0),
m_here(),
m_pos(0),
m_prev(0),
m_next(0)
{
}
pqxx::icursor_iterator::icursor_iterator(istream_type &s) throw () :
m_stream(&s),
m_here(),
m_pos(s.forward(0)),
m_prev(0),
m_next(0)
{
s.insert_iterator(this);
}
pqxx::icursor_iterator::icursor_iterator(const icursor_iterator &rhs) throw () :
m_stream(rhs.m_stream),
m_here(rhs.m_here),
m_pos(rhs.m_pos),
m_prev(0),
m_next(0)
{
if (m_stream) m_stream->insert_iterator(this);
}
pqxx::icursor_iterator::~icursor_iterator() throw ()
{
if (m_stream) m_stream->remove_iterator(this);
}
pqxx::icursor_iterator pqxx::icursor_iterator::operator++(int)
{
icursor_iterator old(*this);
m_pos = m_stream->forward();
m_here.clear();
return old;
}
pqxx::icursor_iterator &pqxx::icursor_iterator::operator++()
{
m_pos = m_stream->forward();
m_here.clear();
return *this;
}
pqxx::icursor_iterator &pqxx::icursor_iterator::operator+=(difference_type n)
{
if (n <= 0)
{
if (!n) return *this;
throw invalid_argument("Advancing icursor_iterator by negative offset");
}
m_pos = m_stream->forward(n);
m_here.clear();
return *this;
}
pqxx::icursor_iterator &
pqxx::icursor_iterator::operator=(const icursor_iterator &rhs) throw ()
{
if (rhs.m_stream == m_stream)
{
m_here = rhs.m_here;
m_pos = rhs.m_pos;
}
else
{
if (m_stream) m_stream->remove_iterator(this);
m_here = rhs.m_here;
m_pos = rhs.m_pos;
m_stream = rhs.m_stream;
if (m_stream) m_stream->insert_iterator(this);
}
return *this;
}
bool pqxx::icursor_iterator::operator==(const icursor_iterator &rhs) const
{
if (m_stream == rhs.m_stream) return pos() == rhs.pos();
if (m_stream && rhs.m_stream) return false;
refresh();
rhs.refresh();
return m_here.empty() && rhs.m_here.empty();
}
bool pqxx::icursor_iterator::operator<(const icursor_iterator &rhs) const
{
if (m_stream == rhs.m_stream) return pos() < rhs.pos();
refresh();
rhs.refresh();
return !m_here.empty();
}
void pqxx::icursor_iterator::refresh() const
{
if (m_stream) m_stream->service_iterators(pos());
}
void pqxx::icursor_iterator::fill(const result &r)
{
m_here = r;
}
<commit_msg>Forgot to quote cursor name when closing (#81)<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* cursor.cxx
*
* DESCRIPTION
* implementation of libpqxx STL-style cursor classes.
* These classes wrap SQL cursors in STL-like interfaces
*
* Copyright (c) 2004-2006, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-internal.hxx"
#include <cstdlib>
#include "pqxx/cursor"
#include "pqxx/result"
#include "pqxx/transaction"
using namespace PGSTD;
namespace
{
/// Compute actual displacement based on requested and reported displacements
pqxx::cursor_base::difference_type adjust(
pqxx::cursor_base::difference_type d,
pqxx::cursor_base::difference_type r)
{
const pqxx::cursor_base::difference_type hoped = labs(d);
pqxx::cursor_base::difference_type actual = r;
if (hoped < 0 || r < hoped) ++actual;
return (d < 0) ? -actual : actual;
}
}
pqxx::cursor_base::cursor_base(transaction_base *context,
const PGSTD::string &Name,
bool embellish_name) :
m_context(context),
m_done(false),
m_name(embellish_name ? context->conn().adorn_name(Name) : Name),
m_adopted(false),
m_ownership(loose),
m_lastfetch(),
m_lastmove()
{
}
string pqxx::cursor_base::stridestring(difference_type n)
{
/* Some special-casing for ALL and BACKWARD ALL here. We used to use numeric
* "infinities" for difference_type for this (the highest and lowest possible
* values for "long"), but for PostgreSQL 8.0 at least, the backend appears to
* expect a 32-bit number and fails to parse large 64-bit numbers.
* We could change the typedef to match this behaviour, but that would break
* if/when Postgres is changed to accept 64-bit displacements.
*/
static const string All("ALL"), BackAll("BACKWARD ALL");
if (n == all()) return All;
else if (n == backward_all()) return BackAll;
return to_string(n);
}
namespace
{
/// Is this character a "useless trailing character" in a query?
/** A character is "useless" at the end of a query if it is either whitespace or
* a semicolon.
*/
inline bool useless_trail(char c)
{
return isspace(c) || c==';';
}
}
void pqxx::cursor_base::declare(const PGSTD::string &query,
accesspolicy ap,
updatepolicy up,
ownershippolicy op,
bool hold)
{
stringstream cq, qn;
/* Strip trailing semicolons (and whitespace, as side effect) off query. The
* whitespace is stripped because it might otherwise mask a semicolon. After
* this, the remaining useful query will be the sequence defined by
* query.begin() and last, i.e. last may be equal to query.end() or point to
* the first useless trailing character.
*/
string::const_iterator last = query.end();
for (--last; last!=query.begin() && useless_trail(*last); --last);
if (last==query.begin() && useless_trail(*last))
throw invalid_argument("Cursor created on empty query");
++last;
cq << "DECLARE \"" << name() << "\" ";
if (m_context->conn().supports(connection_base::cap_cursor_scroll))
{
if (ap == forward_only) cq << "NO ";
cq << "SCROLL ";
}
cq << "CURSOR ";
if (hold)
{
if (!m_context->conn().supports(connection_base::cap_cursor_with_hold))
throw runtime_error("Cursor " + name() + " "
"created for use outside of its originating transaction, "
"but this backend version does not support that.");
cq << "WITH HOLD ";
}
cq << "FOR " << string(query.begin(),last) << ' ';
if (up != update) cq << "FOR READ ONLY ";
else if (!m_context->conn().supports(connection_base::cap_cursor_update))
throw runtime_error("Cursor " + name() + " "
"created as updatable, "
"but this backend version does not support that.");
else cq << "FOR UPDATE ";
qn << "[DECLARE " << name() << ']';
m_context->exec(cq, qn.str());
// If we're creating a WITH HOLD cursor, noone is going to destroy it until
// after this transaction. That means the connection cannot be deactivated
// without losing the cursor.
m_ownership = op;
if (op==loose) m_context->m_reactivation_avoidance.add(1);
}
void pqxx::cursor_base::adopt(ownershippolicy op)
{
// If we take responsibility for destroying the cursor, that's one less reason
// not to allow the connection to be deactivated and reactivated.
if (op==owned) m_context->m_reactivation_avoidance.add(-1);
m_adopted = true;
m_ownership = op;
}
void pqxx::cursor_base::close() throw ()
{
if (m_ownership==owned)
{
try
{
m_context->exec("CLOSE \"" + name() + "\"");
}
catch (const exception &)
{
}
if (m_adopted) m_context->m_reactivation_avoidance.add(-1);
m_ownership = loose;
}
}
pqxx::result pqxx::cursor_base::fetch(difference_type n)
{
result r;
if (n)
{
// We cache the last-executed fetch query. If the current fetch uses the
// same distance, we just re-use the cached string instead of composing a
// new one.
const string fq(
(n == m_lastfetch.dist) ?
m_lastfetch.query :
"FETCH " + stridestring(n) + " IN \"" + name() + "\"");
// Set m_done on exception (but no need for try/catch)
m_done = true;
r = m_context->exec(fq);
if (!r.empty()) m_done = false;
}
return r;
}
pqxx::result pqxx::cursor_base::fetch(difference_type n, difference_type &d)
{
result r(cursor_base::fetch(n));
d = adjust(n, r.size());
return r;
}
template<> void
pqxx::cursor_base::check_displacement<pqxx::cursor_base::forward_only>(
difference_type d) const
{
if (d < 0)
throw logic_error("Attempt to move cursor " + name() + " "
"backwards (this cursor is only allowed to move forwards)");
}
pqxx::cursor_base::difference_type pqxx::cursor_base::move(difference_type n)
{
if (!n) return 0;
const string mq(
(n == m_lastmove.dist) ?
m_lastmove.query :
"MOVE " + stridestring(n) + " IN \"" + name() + "\"");
// Set m_done on exception (but no need for try/catch)
m_done = true;
const result r(m_context->exec(mq));
// Starting with the libpq in PostgreSQL 7.4, PQcmdTuples() (which we call
// indirectly here) also returns the number of rows skipped by a MOVE
difference_type d = r.affected_rows();
// We may not have PQcmdTuples(), or this may be a libpq version that doesn't
// implement it for MOVE yet. We'll also get zero if we decide to use a
// prepared statement for the MOVE.
if (!d)
{
static const string StdResponse("MOVE ");
if (strncmp(r.CmdStatus(), StdResponse.c_str(), StdResponse.size()) != 0)
throw internal_error("cursor MOVE returned "
"'" + string(r.CmdStatus()) + "' "
"(expected '" + StdResponse + "')");
from_string(r.CmdStatus()+StdResponse.size(), d);
}
m_done = (d != n);
return d;
}
pqxx::cursor_base::difference_type
pqxx::cursor_base::move(difference_type n, difference_type &d)
{
const difference_type got = cursor_base::move(n);
d = adjust(n, got);
return got;
}
pqxx::icursorstream::icursorstream(pqxx::transaction_base &context,
const PGSTD::string &query,
const PGSTD::string &basename,
difference_type Stride) :
super(&context, query, basename),
m_stride(Stride),
m_realpos(0),
m_reqpos(0),
m_iterators(0)
{
set_stride(Stride);
}
pqxx::icursorstream::icursorstream(transaction_base &Context,
const result::field &Name,
difference_type Stride) :
super(&Context, Name.c_str()),
m_stride(Stride),
m_realpos(0),
m_reqpos(0),
m_iterators(0)
{
set_stride(Stride);
}
void pqxx::icursorstream::set_stride(difference_type n)
{
if (n < 1)
throw invalid_argument("Attempt to set cursor stride to " + to_string(n));
m_stride = n;
}
pqxx::result pqxx::icursorstream::fetchblock()
{
const result r(fetch(m_stride));
m_realpos += r.size();
return r;
}
pqxx::icursorstream &pqxx::icursorstream::ignore(PGSTD::streamsize n)
{
m_realpos += move(n);
return *this;
}
pqxx::icursorstream::size_type pqxx::icursorstream::forward(size_type n)
{
m_reqpos += n*m_stride;
return m_reqpos;
}
void pqxx::icursorstream::insert_iterator(icursor_iterator *i) throw ()
{
i->m_next = m_iterators;
if (m_iterators) m_iterators->m_prev = i;
m_iterators = i;
}
void pqxx::icursorstream::remove_iterator(icursor_iterator *i) const throw ()
{
if (i == m_iterators)
{
m_iterators = i->m_next;
if (m_iterators) m_iterators->m_prev = 0;
}
else
{
i->m_prev->m_next = i->m_next;
if (i->m_next) i->m_next->m_prev = i->m_prev;
}
i->m_prev = 0;
i->m_next = 0;
}
void pqxx::icursorstream::service_iterators(size_type topos)
{
if (topos < m_realpos) return;
typedef multimap<size_type,icursor_iterator*> todolist;
todolist todo;
for (icursor_iterator *i = m_iterators; i; i = i->m_next)
if (i->m_pos >= m_realpos && i->m_pos <= topos)
todo.insert(todolist::value_type(i->m_pos, i));
const todolist::const_iterator todo_end(todo.end());
for (todolist::const_iterator i = todo.begin(); i != todo_end; )
{
const size_type readpos = i->first;
if (readpos > m_realpos) ignore(readpos - m_realpos);
const result r = fetchblock();
for ( ; i != todo_end && i->first == readpos; ++i)
i->second->fill(r);
}
}
pqxx::icursor_iterator::icursor_iterator() throw () :
m_stream(0),
m_here(),
m_pos(0),
m_prev(0),
m_next(0)
{
}
pqxx::icursor_iterator::icursor_iterator(istream_type &s) throw () :
m_stream(&s),
m_here(),
m_pos(s.forward(0)),
m_prev(0),
m_next(0)
{
s.insert_iterator(this);
}
pqxx::icursor_iterator::icursor_iterator(const icursor_iterator &rhs) throw () :
m_stream(rhs.m_stream),
m_here(rhs.m_here),
m_pos(rhs.m_pos),
m_prev(0),
m_next(0)
{
if (m_stream) m_stream->insert_iterator(this);
}
pqxx::icursor_iterator::~icursor_iterator() throw ()
{
if (m_stream) m_stream->remove_iterator(this);
}
pqxx::icursor_iterator pqxx::icursor_iterator::operator++(int)
{
icursor_iterator old(*this);
m_pos = m_stream->forward();
m_here.clear();
return old;
}
pqxx::icursor_iterator &pqxx::icursor_iterator::operator++()
{
m_pos = m_stream->forward();
m_here.clear();
return *this;
}
pqxx::icursor_iterator &pqxx::icursor_iterator::operator+=(difference_type n)
{
if (n <= 0)
{
if (!n) return *this;
throw invalid_argument("Advancing icursor_iterator by negative offset");
}
m_pos = m_stream->forward(n);
m_here.clear();
return *this;
}
pqxx::icursor_iterator &
pqxx::icursor_iterator::operator=(const icursor_iterator &rhs) throw ()
{
if (rhs.m_stream == m_stream)
{
m_here = rhs.m_here;
m_pos = rhs.m_pos;
}
else
{
if (m_stream) m_stream->remove_iterator(this);
m_here = rhs.m_here;
m_pos = rhs.m_pos;
m_stream = rhs.m_stream;
if (m_stream) m_stream->insert_iterator(this);
}
return *this;
}
bool pqxx::icursor_iterator::operator==(const icursor_iterator &rhs) const
{
if (m_stream == rhs.m_stream) return pos() == rhs.pos();
if (m_stream && rhs.m_stream) return false;
refresh();
rhs.refresh();
return m_here.empty() && rhs.m_here.empty();
}
bool pqxx::icursor_iterator::operator<(const icursor_iterator &rhs) const
{
if (m_stream == rhs.m_stream) return pos() < rhs.pos();
refresh();
rhs.refresh();
return !m_here.empty();
}
void pqxx::icursor_iterator::refresh() const
{
if (m_stream) m_stream->service_iterators(pos());
}
void pqxx::icursor_iterator::fill(const result &r)
{
m_here = r;
}
<|endoftext|> |
<commit_before>#include "i_ui.h"
#include <boost/algorithm/string.hpp>
#include <string.h>
Widget::WidgetIterator& Widget::WidgetIterator::operator++()
{
if( mThis->mFirstChild )
{
mThis = mThis->mFirstChild;
++mLevel;
}
else if( mThis->mNext )
{
mThis = mThis->mNext;
}
else
{
Widget const* Next = mThis;
while( Next && !Next->mNext && mLevel )
{
Next = Next->mParent;
--mLevel;
}
mThis = Next->mNext;
}
return *this;
}
void Widget::AddChild( Widget* Child )
{
assert( !Child->mPrev && !Child->mParent && !Child->mNext );
Widget* WhatWillBeNext = mFirstChild;
while( WhatWillBeNext && WhatWillBeNext->mZOrder < Child->mZOrder )
{
WhatWillBeNext = WhatWillBeNext->mNext;
}
if( WhatWillBeNext )
{
Child->mPrev = WhatWillBeNext->mPrev;
if( WhatWillBeNext->mPrev )
{
WhatWillBeNext->mPrev->mNext = Child;
}
Child->mNext = WhatWillBeNext;
WhatWillBeNext->mPrev = Child;
if( WhatWillBeNext == mFirstChild )
{
mFirstChild = Child;
}
}
else
{
if( !mFirstChild )
{
mFirstChild = Child;
}
mLastChild = Child;
}
Child->mParent = this;
Child->UpdateDimensions();
Child->UpdateChildrenDimensions();
}
Widget::Widget( int32_t Id )
: mTypeId( Id )
, mZOrder( 0 )
, mParent( NULL )
, mNext( NULL )
, mPrev( NULL )
, mFirstChild( NULL )
, mLastChild( NULL )
, mDimSet( false )
, mRelativeDimensions( 0, 0, 1, 1 )
, mProperties( this )
{
operator()( PT_Highlight ) = 0;
}
Widget const* Widget::Parent() const
{
return mParent;
}
Widget::~Widget()
{
Widget* What = mFirstChild;
while( What )
{
Widget* Next = What->mNext;
delete What;
What = Next;
}
if( mNext )
{
mNext->mPrev = mPrev;
}
if( mPrev )
{
mPrev->mNext = mNext;
}
if( mParent )
{
if( mParent->mFirstChild == this )
{
mParent->mFirstChild = mNext;
}
if( mParent->mLastChild == this )
{
mParent->mLastChild = mPrev;
}
}
}
glm::vec4 const& Widget::GetDimensions() const
{
return mDimensions;
}
Widget::const_iterator Widget::begin() const
{
return WidgetIterator( this );
}
Widget::const_iterator Widget::end() const
{
return WidgetIterator();
}
void Widget::UpdateDimensions()
{
UpdateSelfDimensions();
UpdateChildrenDimensions();
}
void Widget::UpdateSelfDimensions()
{
if( !mParent || !mParent->mDimSet )
{
return;
}
mDimSet = true;
glm::vec4 const& ParentDim = mParent->GetDimensions();
double const X = ParentDim.x;
double const Y = ParentDim.y;
double const Width = ParentDim.z;
double const Height = ParentDim.w;
mDimensions = glm::vec4( X + mRelativeDimensions.x * Width,
Y + mRelativeDimensions.y * Height,
mRelativeDimensions.z * Width,
mRelativeDimensions.w * Height );
}
void Widget::UpdateChildrenDimensions()
{
if( !mParent || !mParent->mDimSet )
{
return;
}
for( Widget* i = mFirstChild; i; i = i->mNext )
{
i->UpdateDimensions();
}
}
Widget* Widget::GetHit( const glm::vec2& Pos )
{
if( !IsInside( Pos ) )
{
return NULL;
}
for( Widget* i = mLastChild; i; i = i->mPrev )
{
Widget* Wdg = i->GetHit( Pos );
if( Wdg )
{
return Wdg;
}
}
return mProperties( PT_Enabled ).Value.ToInt ? this : NULL;
}
bool Widget::IsInside( const glm::vec2& Pos ) const
{
return mDimSet &&
Pos.x >= mDimensions.x &&
Pos.x <= mDimensions.x + mDimensions.z &&
Pos.y >= mDimensions.y &&
Pos.y <= mDimensions.y + mDimensions.w;
}
void Widget::SetRelativeDimensions( glm::vec4 const& Dim )
{
mRelativeDimensions = Dim;
UpdateDimensions();
}
bool Widget::AreDimensionsSet() const
{
return mDimSet;
}
Widget* Widget::GetNext() const
{
return mNext;
}
Widget::Prop const& Widget::operator()( PropertyType Property ) const
{
return mProperties( Property );
}
Widget::Prop& Widget::operator()( PropertyType Property )
{
return mProperties.Mutable( Property );
}
int32_t Widget::ParseColor( Json::Value& Color, int32_t Default )
{
int32_t i;
if( Json::GetColor( Color, i ) )
{
return i;
}
return Default;
}
void Widget::Init( Json::Value& Descriptor )
{
double d;
mRelativeDimensions.x = Json::GetDouble( Descriptor["x"], d ) ? d : 0;
mRelativeDimensions.y = Json::GetDouble( Descriptor["y"], d ) ? d : 0;
mRelativeDimensions.z = Json::GetDouble( Descriptor["w"], d ) ? d : 0;
mRelativeDimensions.w = Json::GetDouble( Descriptor["h"], d ) ? d : 0;
static const int32_t DefaultColor = 0x0000fa77;
int32_t i = ParseColor( Descriptor["color"], DefaultColor );
operator()( PT_Color ) = i;
operator()( PT_HighlightColor ) = ParseColor( Descriptor["highlight_color"], i );
ParseIntProp( PT_Enabled, Descriptor["enabled"], 0 );
ParseIntProp( PT_Visible, Descriptor["visible"], 0 );
Json::Value& Children = Descriptor["children"];
if( !Children.isArray() || !Children.size() )
{
return;
}
WidgetFactory& Fact( WidgetFactory::Get() );
for( Json::Value::iterator i = Children.begin(), e = Children.end(); i != e; ++i )
{
std::string Str;
if( !Json::GetStr( ( *i )["type"], Str ) )
{
continue;
}
std::auto_ptr<Widget> wdg = Fact( Str, *i );
AddChild( wdg.release() );
}
}
int32_t Widget::GetId() const
{
return mTypeId;
}
void Widget::ParseIntProp( PropertyType Pt, Json::Value& Val, int32_t Default )
{
ParseIntProp( operator()( Pt ), Val, Default );
}
void Widget::ParseIntProp( Prop& Pt, Json::Value& Val, int32_t Default )
{
if( Val.isString() )
{
Pt = Val.asString();
assert( Pt.IsResolvable() );
}
else
{
int32_t i;
Pt = Json::GetInt( Val, i ) ? i : Default;
}
}
void Widget::ParseDoubleProp( PropertyType Pt, Json::Value& Val, double Default )
{
ParseDoubleProp( operator()( Pt ), Val, Default );
}
void Widget::ParseDoubleProp( Prop& Pt, Json::Value& Val, double Default )
{
if( Val.isString() )
{
Pt = Val.asString();
assert( Pt.IsResolvable() );
}
else
{
double d;
Pt = Json::GetDouble( Val, d ) ? d : Default;
}
}
void Widget::ParseStrProp( PropertyType Pt, Json::Value& Val, std::string const& Default )
{
ParseStrProp( operator()( Pt ), Val, Default );
}
void Widget::ParseStrProp( Prop& Pt, Json::Value& Val, std::string const& Default )
{
Pt = Val.isString() ? Val.asString() : Default;
}
Widget::Prop::Prop( Widget* owner )
: Type( T_Null )
, mOwner( owner )
{
Value.ToInt = 0;
}
Widget* Widget::Prop::GetOwner() const
{
return mOwner;
}
Widget::Prop::Prop( Prop const& Other )
: Type( Other.Type )
, mOwner( Other.mOwner )
, Value( Other.Value )
{
if( Type == T_Str )
{
Init( std::string( Other.Value.ToStr ) );
}
}
Widget::Prop::~Prop()
{
Cleanup();
}
Widget::Prop::operator int32_t() const
{
if( IsResolvable() )
{
if( IsAutoId() )
{
return (int32_t)AutoId( Value.ToStr + 2 );
}
if( IsVectorModelValue() )
{
std::vector<int32_t> const& v = ResolveModel().operator std::vector<int32_t>();
int32_t idx = ResolveIndex();
return v.size() > idx ? v.at( idx ) : 0;
}
if( IsModelIndex() )
{
return ResolveIndex();
}
return( int32_t )ResolveModel();
}
assert( Type == T_Int || Type == T_Double );
return ( Type == T_Int ) ? Value.ToInt : ( Type == T_Double ? int32_t( Value.ToDouble ) : 0 );
}
Widget::Prop::operator double() const
{
if( IsResolvable() )
{
return( double )ResolveModel();
}
assert( Type == T_Int || Type == T_Double );
return ( Type == T_Double ) ? Value.ToDouble : ( Type == T_Int ? double( Value.ToInt ) : 0.0 );
}
Widget::Prop& Widget::Prop::operator=( std::string const& Str )
{
Cleanup();
Type = T_Str;
Init( Str );
return *this;
}
Widget::Prop& Widget::Prop::operator=( char const* Str )
{
Cleanup();
Type = T_Str;
Init( std::string( Str ) );
return *this;
}
Widget::Prop& Widget::Prop::operator=( int32_t I )
{
Cleanup();
Type = T_Int;
Value.ToInt = I;
return *this;
}
Widget::Prop& Widget::Prop::operator=( double D )
{
Cleanup();
Type = T_Double;
Value.ToDouble = D;
return *this;
}
void Widget::Prop::Init( std::string const& StrVal )
{
Type = T_Str;
const size_t Size = StrVal.size();
char* Buf = new char[Size + 1];
memset( Buf, 0, Size + 1 );
memcpy( Buf, StrVal.c_str(), Size );
Value.ToStr = Buf;
}
void Widget::Prop::Cleanup()
{
if( Type == T_Str )
{
delete[] Value.ToStr;
}
Type = T_Null;
}
Widget::Prop::operator std::string() const
{
if( IsResolvable() )
{
if( IsVectorModelValue() )
{
std::vector<std::string> const& v = ResolveModel().operator std::vector<std::string>();
int32_t idx = ResolveIndex();
return v.size() > idx ? v.at( idx ) : std::string();
}
return( std::string )ResolveModel();
}
assert( Type == T_Str );
return ( Type == T_Str ) ? Value.ToStr : NULL;
}
bool Widget::Prop::IsResolvable() const
{
return Type == T_Str && Value.ToStr && ( *Value.ToStr == '%' || *Value.ToStr == '#' );
}
bool Widget::Prop::IsAutoId() const
{
return IsResolvable() && Value.ToStr[1] == '%';
}
bool Widget::Prop::IsModelValue() const
{
return Type == T_Str && Value.ToStr && (( *Value.ToStr == '%' && Value.ToStr[1] != '%' ) || *Value.ToStr == '#');
}
bool Widget::Prop::IsModelIndex() const
{
return Type == T_Str && Value.ToStr && *Value.ToStr == '#';
}
bool Widget::Prop::IsVectorModelValue() const
{
return IsModelValue() && strrchr( Value.ToStr + 1, '#' ) != NULL ;
}
ModelValue const& Widget::Prop::ResolveModel() const
{
assert( IsResolvable() );
std::string name = std::string( ( *Value.ToStr == '#' ) ? "ui." : "" ) + std::string( Value.ToStr + 1);
typedef std::vector<std::string> Fields_t;
Fields_t fields;
boost::split( fields, name, boost::is_any_of( "#%" ) );
return RootModel::Get()[ fields[0] ];
}
int32_t Widget::Prop::ResolveIndex() const
{
assert( IsVectorModelValue() || IsModelIndex() );
typedef std::vector<std::string> Fields_t;
Fields_t fields;
boost::split( fields, Value.ToStr, boost::is_any_of( "#" ) );
std::string last = fields.back();
int32_t startindex = RootModel::Get()[ "ui." + last ].operator int32_t();
for( Widget const* w = mOwner; NULL != w; w = w->Parent() )
{
Prop const& p = w->operator()( PT_StartId );
if( p.GetType() != T_Str )
{
continue;
}
if( p.Value.ToStr + 1 != last )
{
continue;
}
// found a widget with the same startid
// check for index prop
Prop const& p2 = w->operator()( PT_Index );
if( p2.GetType() != T_Int )
{
continue;
}
return startindex + p2.operator int32_t();
}
return startindex;
}
Widget::PropertyRepo_t::PropertyRepo_t( Widget* owner )
: mOwner( owner )
, mDefaultProperty( owner )
, RepoBase( mDefaultProperty )
{
}
Widget::Prop& Widget::PropertyRepo_t::Mutable( PropertyType Property )
{
int32_t Id( Property );
ElementMap_t::iterator i = mElements.find( Id );
if( mElements.end() == i )
{
Prop* p = new Prop( mOwner );
mElements.insert( Id, p );
return *p;
}
return *i->second;
}
<commit_msg>B: don't pick subtree-hidden elements in the ui.<commit_after>#include "i_ui.h"
#include <boost/algorithm/string.hpp>
#include <string.h>
Widget::WidgetIterator& Widget::WidgetIterator::operator++()
{
if( mThis->mFirstChild )
{
mThis = mThis->mFirstChild;
++mLevel;
}
else if( mThis->mNext )
{
mThis = mThis->mNext;
}
else
{
Widget const* Next = mThis;
while( Next && !Next->mNext && mLevel )
{
Next = Next->mParent;
--mLevel;
}
mThis = Next->mNext;
}
return *this;
}
void Widget::AddChild( Widget* Child )
{
assert( !Child->mPrev && !Child->mParent && !Child->mNext );
Widget* WhatWillBeNext = mFirstChild;
while( WhatWillBeNext && WhatWillBeNext->mZOrder < Child->mZOrder )
{
WhatWillBeNext = WhatWillBeNext->mNext;
}
if( WhatWillBeNext )
{
Child->mPrev = WhatWillBeNext->mPrev;
if( WhatWillBeNext->mPrev )
{
WhatWillBeNext->mPrev->mNext = Child;
}
Child->mNext = WhatWillBeNext;
WhatWillBeNext->mPrev = Child;
if( WhatWillBeNext == mFirstChild )
{
mFirstChild = Child;
}
}
else
{
if( !mFirstChild )
{
mFirstChild = Child;
}
mLastChild = Child;
}
Child->mParent = this;
Child->UpdateDimensions();
Child->UpdateChildrenDimensions();
}
Widget::Widget( int32_t Id )
: mTypeId( Id )
, mZOrder( 0 )
, mParent( NULL )
, mNext( NULL )
, mPrev( NULL )
, mFirstChild( NULL )
, mLastChild( NULL )
, mDimSet( false )
, mRelativeDimensions( 0, 0, 1, 1 )
, mProperties( this )
{
operator()( PT_Highlight ) = 0;
}
Widget const* Widget::Parent() const
{
return mParent;
}
Widget::~Widget()
{
Widget* What = mFirstChild;
while( What )
{
Widget* Next = What->mNext;
delete What;
What = Next;
}
if( mNext )
{
mNext->mPrev = mPrev;
}
if( mPrev )
{
mPrev->mNext = mNext;
}
if( mParent )
{
if( mParent->mFirstChild == this )
{
mParent->mFirstChild = mNext;
}
if( mParent->mLastChild == this )
{
mParent->mLastChild = mPrev;
}
}
}
glm::vec4 const& Widget::GetDimensions() const
{
return mDimensions;
}
Widget::const_iterator Widget::begin() const
{
return WidgetIterator( this );
}
Widget::const_iterator Widget::end() const
{
return WidgetIterator();
}
void Widget::UpdateDimensions()
{
UpdateSelfDimensions();
UpdateChildrenDimensions();
}
void Widget::UpdateSelfDimensions()
{
if( !mParent || !mParent->mDimSet )
{
return;
}
mDimSet = true;
glm::vec4 const& ParentDim = mParent->GetDimensions();
double const X = ParentDim.x;
double const Y = ParentDim.y;
double const Width = ParentDim.z;
double const Height = ParentDim.w;
mDimensions = glm::vec4( X + mRelativeDimensions.x * Width,
Y + mRelativeDimensions.y * Height,
mRelativeDimensions.z * Width,
mRelativeDimensions.w * Height );
}
void Widget::UpdateChildrenDimensions()
{
if( !mParent || !mParent->mDimSet )
{
return;
}
for( Widget* i = mFirstChild; i; i = i->mNext )
{
i->UpdateDimensions();
}
}
Widget* Widget::GetHit( const glm::vec2& Pos )
{
if( !IsInside( Pos ) || mProperties( PT_SubtreeHidden ).Value.ToInt != 0 )
{
return NULL;
}
for( Widget* i = mLastChild; i; i = i->mPrev )
{
Widget* Wdg = i->GetHit( Pos );
if( Wdg )
{
return Wdg;
}
}
return mProperties( PT_Enabled ).Value.ToInt ? this : NULL;
}
bool Widget::IsInside( const glm::vec2& Pos ) const
{
return mDimSet &&
Pos.x >= mDimensions.x &&
Pos.x <= mDimensions.x + mDimensions.z &&
Pos.y >= mDimensions.y &&
Pos.y <= mDimensions.y + mDimensions.w;
}
void Widget::SetRelativeDimensions( glm::vec4 const& Dim )
{
mRelativeDimensions = Dim;
UpdateDimensions();
}
bool Widget::AreDimensionsSet() const
{
return mDimSet;
}
Widget* Widget::GetNext() const
{
return mNext;
}
Widget::Prop const& Widget::operator()( PropertyType Property ) const
{
return mProperties( Property );
}
Widget::Prop& Widget::operator()( PropertyType Property )
{
return mProperties.Mutable( Property );
}
int32_t Widget::ParseColor( Json::Value& Color, int32_t Default )
{
int32_t i;
if( Json::GetColor( Color, i ) )
{
return i;
}
return Default;
}
void Widget::Init( Json::Value& Descriptor )
{
double d;
mRelativeDimensions.x = Json::GetDouble( Descriptor["x"], d ) ? d : 0;
mRelativeDimensions.y = Json::GetDouble( Descriptor["y"], d ) ? d : 0;
mRelativeDimensions.z = Json::GetDouble( Descriptor["w"], d ) ? d : 0;
mRelativeDimensions.w = Json::GetDouble( Descriptor["h"], d ) ? d : 0;
static const int32_t DefaultColor = 0x0000fa77;
int32_t i = ParseColor( Descriptor["color"], DefaultColor );
operator()( PT_Color ) = i;
operator()( PT_HighlightColor ) = ParseColor( Descriptor["highlight_color"], i );
ParseIntProp( PT_Enabled, Descriptor["enabled"], 0 );
ParseIntProp( PT_Visible, Descriptor["visible"], 0 );
Json::Value& Children = Descriptor["children"];
if( !Children.isArray() || !Children.size() )
{
return;
}
WidgetFactory& Fact( WidgetFactory::Get() );
for( Json::Value::iterator i = Children.begin(), e = Children.end(); i != e; ++i )
{
std::string Str;
if( !Json::GetStr( ( *i )["type"], Str ) )
{
continue;
}
std::auto_ptr<Widget> wdg = Fact( Str, *i );
AddChild( wdg.release() );
}
}
int32_t Widget::GetId() const
{
return mTypeId;
}
void Widget::ParseIntProp( PropertyType Pt, Json::Value& Val, int32_t Default )
{
ParseIntProp( operator()( Pt ), Val, Default );
}
void Widget::ParseIntProp( Prop& Pt, Json::Value& Val, int32_t Default )
{
if( Val.isString() )
{
Pt = Val.asString();
assert( Pt.IsResolvable() );
}
else
{
int32_t i;
Pt = Json::GetInt( Val, i ) ? i : Default;
}
}
void Widget::ParseDoubleProp( PropertyType Pt, Json::Value& Val, double Default )
{
ParseDoubleProp( operator()( Pt ), Val, Default );
}
void Widget::ParseDoubleProp( Prop& Pt, Json::Value& Val, double Default )
{
if( Val.isString() )
{
Pt = Val.asString();
assert( Pt.IsResolvable() );
}
else
{
double d;
Pt = Json::GetDouble( Val, d ) ? d : Default;
}
}
void Widget::ParseStrProp( PropertyType Pt, Json::Value& Val, std::string const& Default )
{
ParseStrProp( operator()( Pt ), Val, Default );
}
void Widget::ParseStrProp( Prop& Pt, Json::Value& Val, std::string const& Default )
{
Pt = Val.isString() ? Val.asString() : Default;
}
Widget::Prop::Prop( Widget* owner )
: Type( T_Null )
, mOwner( owner )
{
Value.ToInt = 0;
}
Widget* Widget::Prop::GetOwner() const
{
return mOwner;
}
Widget::Prop::Prop( Prop const& Other )
: Type( Other.Type )
, mOwner( Other.mOwner )
, Value( Other.Value )
{
if( Type == T_Str )
{
Init( std::string( Other.Value.ToStr ) );
}
}
Widget::Prop::~Prop()
{
Cleanup();
}
Widget::Prop::operator int32_t() const
{
if( IsResolvable() )
{
if( IsAutoId() )
{
return (int32_t)AutoId( Value.ToStr + 2 );
}
if( IsVectorModelValue() )
{
std::vector<int32_t> const& v = ResolveModel().operator std::vector<int32_t>();
int32_t idx = ResolveIndex();
return v.size() > idx ? v.at( idx ) : 0;
}
if( IsModelIndex() )
{
return ResolveIndex();
}
return( int32_t )ResolveModel();
}
assert( Type == T_Int || Type == T_Double );
return ( Type == T_Int ) ? Value.ToInt : ( Type == T_Double ? int32_t( Value.ToDouble ) : 0 );
}
Widget::Prop::operator double() const
{
if( IsResolvable() )
{
return( double )ResolveModel();
}
assert( Type == T_Int || Type == T_Double );
return ( Type == T_Double ) ? Value.ToDouble : ( Type == T_Int ? double( Value.ToInt ) : 0.0 );
}
Widget::Prop& Widget::Prop::operator=( std::string const& Str )
{
Cleanup();
Type = T_Str;
Init( Str );
return *this;
}
Widget::Prop& Widget::Prop::operator=( char const* Str )
{
Cleanup();
Type = T_Str;
Init( std::string( Str ) );
return *this;
}
Widget::Prop& Widget::Prop::operator=( int32_t I )
{
Cleanup();
Type = T_Int;
Value.ToInt = I;
return *this;
}
Widget::Prop& Widget::Prop::operator=( double D )
{
Cleanup();
Type = T_Double;
Value.ToDouble = D;
return *this;
}
void Widget::Prop::Init( std::string const& StrVal )
{
Type = T_Str;
const size_t Size = StrVal.size();
char* Buf = new char[Size + 1];
memset( Buf, 0, Size + 1 );
memcpy( Buf, StrVal.c_str(), Size );
Value.ToStr = Buf;
}
void Widget::Prop::Cleanup()
{
if( Type == T_Str )
{
delete[] Value.ToStr;
}
Type = T_Null;
}
Widget::Prop::operator std::string() const
{
if( IsResolvable() )
{
if( IsVectorModelValue() )
{
std::vector<std::string> const& v = ResolveModel().operator std::vector<std::string>();
int32_t idx = ResolveIndex();
return v.size() > idx ? v.at( idx ) : std::string();
}
return( std::string )ResolveModel();
}
assert( Type == T_Str );
return ( Type == T_Str ) ? Value.ToStr : NULL;
}
bool Widget::Prop::IsResolvable() const
{
return Type == T_Str && Value.ToStr && ( *Value.ToStr == '%' || *Value.ToStr == '#' );
}
bool Widget::Prop::IsAutoId() const
{
return IsResolvable() && Value.ToStr[1] == '%';
}
bool Widget::Prop::IsModelValue() const
{
return Type == T_Str && Value.ToStr && (( *Value.ToStr == '%' && Value.ToStr[1] != '%' ) || *Value.ToStr == '#');
}
bool Widget::Prop::IsModelIndex() const
{
return Type == T_Str && Value.ToStr && *Value.ToStr == '#';
}
bool Widget::Prop::IsVectorModelValue() const
{
return IsModelValue() && strrchr( Value.ToStr + 1, '#' ) != NULL ;
}
ModelValue const& Widget::Prop::ResolveModel() const
{
assert( IsResolvable() );
std::string name = std::string( ( *Value.ToStr == '#' ) ? "ui." : "" ) + std::string( Value.ToStr + 1);
typedef std::vector<std::string> Fields_t;
Fields_t fields;
boost::split( fields, name, boost::is_any_of( "#%" ) );
return RootModel::Get()[ fields[0] ];
}
int32_t Widget::Prop::ResolveIndex() const
{
assert( IsVectorModelValue() || IsModelIndex() );
typedef std::vector<std::string> Fields_t;
Fields_t fields;
boost::split( fields, Value.ToStr, boost::is_any_of( "#" ) );
std::string last = fields.back();
int32_t startindex = RootModel::Get()[ "ui." + last ].operator int32_t();
for( Widget const* w = mOwner; NULL != w; w = w->Parent() )
{
Prop const& p = w->operator()( PT_StartId );
if( p.GetType() != T_Str )
{
continue;
}
if( p.Value.ToStr + 1 != last )
{
continue;
}
// found a widget with the same startid
// check for index prop
Prop const& p2 = w->operator()( PT_Index );
if( p2.GetType() != T_Int )
{
continue;
}
return startindex + p2.operator int32_t();
}
return startindex;
}
Widget::PropertyRepo_t::PropertyRepo_t( Widget* owner )
: mOwner( owner )
, mDefaultProperty( owner )
, RepoBase( mDefaultProperty )
{
}
Widget::Prop& Widget::PropertyRepo_t::Mutable( PropertyType Property )
{
int32_t Id( Property );
ElementMap_t::iterator i = mElements.find( Id );
if( mElements.end() == i )
{
Prop* p = new Prop( mOwner );
mElements.insert( Id, p );
return *p;
}
return *i->second;
}
<|endoftext|> |
<commit_before>#ifndef CONFIG_HPP
#define CONFIG_HPP
// Preprocessor helpers to check for definedness giving compile errors if used
// against features with missing #defines.
#define YES -1
#define NO -2
#define ENABLED(feature) (1 == 2 feature)
// Set up build features
#define USE_SHA1_HASH NO
#define USE_FAST_HASH YES
#if defined(_DEBUG)
#define USE_DLMALLOC YES
#define CHECKED_BUILD YES
#else
#define USE_DLMALLOC YES
#define CHECKED_BUILD NO
#endif
// Platform macros.
#if defined(__GNUC__)
#define RESTRICT __restrict
#define NORETURN __attribute__((noreturn))
#define ALIGNOF(t) __alignof(t)
#define ALIGN(n) __attribute__((aligned(n)))
#elif defined(_MSC_VER)
#define RESTRICT __restrict
#define NORETURN __declspec(noreturn)
#define ALIGNOF(t) __alignof(t)
#define ALIGN(n) __declspec(align(n))
#else
#error unsupported compiler
#endif
#if defined(__powerpc__)
#define USE_LITTLE_ENDIAN NO
#elif defined(_WIN32) || defined(__x86__) || defined(__x86_64__)
#define USE_LITTLE_ENDIAN YES
#else
#error add endian detection here
#endif
#if defined(__APPLE__)
#define TUNDRA_UNIX 1
#define TUNDRA_APPLE 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM YES
#define TUNDRA_EXE_SUFFIX ""
#elif defined(_WIN32)
#define TUNDRA_WIN32 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM YES
#define TUNDRA_EXE_SUFFIX ".exe"
#if defined(__GNUC__)
#define TUNDRA_WIN32_MINGW 1
#endif
#elif defined(__linux__)
#define TUNDRA_UNIX 1
#define TUNDRA_LINUX 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#elif defined(__FreeBSD__)
#define TUNDRA_UNIX 1
#define TUNDRA_FREEBSD 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#elif defined(__NetBSD__)
#define TUNDRA_UNIX 1
#define TUNDRA_NETBSD 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#elif defined(__OpenBSD__)
#define TUNDRA_UNIX 1
#define TUNDRA_OPENBSD 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#else
#error Unsupported OS
#endif
#if defined(TUNDRA_WIN32)
#define TUNDRA_STDCALL __stdcall
#else
#define TUNDRA_STDCALL
#endif
#if defined(TUNDRA_APPLE)
#define TUNDRA_PLATFORM_STRING "macosx"
#elif defined(TUNDRA_LINUX)
#define TUNDRA_PLATFORM_STRING "linux"
#elif defined(TUNDRA_WIN32)
#define TUNDRA_PLATFORM_STRING "windows"
#elif defined(TUNDRA_FREEBSD)
#define TUNDRA_PLATFORM_STRING "freebsd"
#elif defined(TUNDRA_OPENBSD)
#define TUNDRA_PLATFORM_STRING "openbsd"
#else
#error Unsupported OS
#endif
#if defined(TUNDRA_WIN32)
#define TD_PATHSEP '\\'
#define TD_PATHSEP_STR "\\"
#else
#define TD_PATHSEP '/'
#define TD_PATHSEP_STR "/"
#endif
#endif
<commit_msg>small buildfix for my local machine<commit_after>#ifndef CONFIG_HPP
#define CONFIG_HPP
// Preprocessor helpers to check for definedness giving compile errors if used
// against features with missing #defines.
#define YES -1
#define NO -2
#define ENABLED(feature) (1 == 2 feature)
// Set up build features
#define USE_SHA1_HASH NO
#define USE_FAST_HASH YES
#if defined(_DEBUG)
#define USE_DLMALLOC YES
#define CHECKED_BUILD YES
#else
#define USE_DLMALLOC YES
#define CHECKED_BUILD NO
#endif
// Platform macros.
#if defined(__GNUC__)
#define RESTRICT __restrict
#define NORETURN __attribute__((noreturn))
#define ALIGNOF(t) __alignof(t)
#define ALIGN(n) __attribute__((aligned(n)))
#elif defined(_MSC_VER)
#define RESTRICT __restrict
#define NORETURN __declspec(noreturn)
#define ALIGNOF(t) __alignof(t)
#define ALIGN(n) __declspec(align(n))
#else
#error unsupported compiler
#endif
#if defined(__powerpc__)
#define USE_LITTLE_ENDIAN NO
#elif defined(_WIN32) || defined(__x86__) || defined(__x86_64__) || defined(i386) || defined(__i386__)
#define USE_LITTLE_ENDIAN YES
#else
#error add endian detection here
#endif
#if defined(__APPLE__)
#define TUNDRA_UNIX 1
#define TUNDRA_APPLE 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM YES
#define TUNDRA_EXE_SUFFIX ""
#elif defined(_WIN32)
#define TUNDRA_WIN32 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM YES
#define TUNDRA_EXE_SUFFIX ".exe"
#if defined(__GNUC__)
#define TUNDRA_WIN32_MINGW 1
#endif
#elif defined(__linux__)
#define TUNDRA_UNIX 1
#define TUNDRA_LINUX 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#elif defined(__FreeBSD__)
#define TUNDRA_UNIX 1
#define TUNDRA_FREEBSD 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#elif defined(__NetBSD__)
#define TUNDRA_UNIX 1
#define TUNDRA_NETBSD 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#elif defined(__OpenBSD__)
#define TUNDRA_UNIX 1
#define TUNDRA_OPENBSD 1
#define TUNDRA_CASE_INSENSITIVE_FILESYSTEM NO
#define TUNDRA_EXE_SUFFIX ""
#else
#error Unsupported OS
#endif
#if defined(TUNDRA_WIN32)
#define TUNDRA_STDCALL __stdcall
#else
#define TUNDRA_STDCALL
#endif
#if defined(TUNDRA_APPLE)
#define TUNDRA_PLATFORM_STRING "macosx"
#elif defined(TUNDRA_LINUX)
#define TUNDRA_PLATFORM_STRING "linux"
#elif defined(TUNDRA_WIN32)
#define TUNDRA_PLATFORM_STRING "windows"
#elif defined(TUNDRA_FREEBSD)
#define TUNDRA_PLATFORM_STRING "freebsd"
#elif defined(TUNDRA_OPENBSD)
#define TUNDRA_PLATFORM_STRING "openbsd"
#else
#error Unsupported OS
#endif
#if defined(TUNDRA_WIN32)
#define TD_PATHSEP '\\'
#define TD_PATHSEP_STR "\\"
#else
#define TD_PATHSEP '/'
#define TD_PATHSEP_STR "/"
#endif
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <policy/fees.h>
#include <string>
std::string StringForFeeReason(FeeReason reason) {
static const std::map<FeeReason, std::string> fee_reason_strings = {
{FeeReason::NONE, "None"},
{FeeReason::HALF_ESTIMATE, "Half Target 60% Threshold"},
{FeeReason::FULL_ESTIMATE, "Target 85% Threshold"},
{FeeReason::DOUBLE_ESTIMATE, "Double Target 95% Threshold"},
{FeeReason::CONSERVATIVE, "Conservative Double Target longer horizon"},
{FeeReason::MEMPOOL_MIN, "Mempool Min Fee"},
{FeeReason::PAYTXFEE, "PayTxFee set"},
{FeeReason::FALLBACK, "Fallback fee"},
{FeeReason::REQUIRED, "Minimum Required Fee"},
};
auto reason_string = fee_reason_strings.find(reason);
if (reason_string == fee_reason_strings.end()) return "Unknown";
return reason_string->second;
}
bool FeeModeFromString(const std::string& mode_string, FeeEstimateMode& fee_estimate_mode) {
static const std::map<std::string, FeeEstimateMode> fee_modes = {
{"UNSET", FeeEstimateMode::UNSET},
{"ECONOMICAL", FeeEstimateMode::ECONOMICAL},
{"CONSERVATIVE", FeeEstimateMode::CONSERVATIVE},
};
auto mode = fee_modes.find(mode_string);
if (mode == fee_modes.end()) return false;
fee_estimate_mode = mode->second;
return true;
}
<commit_msg>util: Add missing headers to util/fees.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util/fees.h>
#include <policy/fees.h>
#include <map>
#include <string>
std::string StringForFeeReason(FeeReason reason) {
static const std::map<FeeReason, std::string> fee_reason_strings = {
{FeeReason::NONE, "None"},
{FeeReason::HALF_ESTIMATE, "Half Target 60% Threshold"},
{FeeReason::FULL_ESTIMATE, "Target 85% Threshold"},
{FeeReason::DOUBLE_ESTIMATE, "Double Target 95% Threshold"},
{FeeReason::CONSERVATIVE, "Conservative Double Target longer horizon"},
{FeeReason::MEMPOOL_MIN, "Mempool Min Fee"},
{FeeReason::PAYTXFEE, "PayTxFee set"},
{FeeReason::FALLBACK, "Fallback fee"},
{FeeReason::REQUIRED, "Minimum Required Fee"},
};
auto reason_string = fee_reason_strings.find(reason);
if (reason_string == fee_reason_strings.end()) return "Unknown";
return reason_string->second;
}
bool FeeModeFromString(const std::string& mode_string, FeeEstimateMode& fee_estimate_mode) {
static const std::map<std::string, FeeEstimateMode> fee_modes = {
{"UNSET", FeeEstimateMode::UNSET},
{"ECONOMICAL", FeeEstimateMode::ECONOMICAL},
{"CONSERVATIVE", FeeEstimateMode::CONSERVATIVE},
};
auto mode = fee_modes.find(mode_string);
if (mode == fee_modes.end()) return false;
fee_estimate_mode = mode->second;
return true;
}
<|endoftext|> |
<commit_before>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <chrono>
#include <iostream>
#include <string>
#include <redis3m/connection.h>
#include "parse.h"
#include "redis.h"
// Daemon Macros
#define DBY_CMD_QUEUE_LOCK_SUFFIX "_lock"
#define DBY_CMD_QUEUE_PREFIX "dby_command_queue_"
#define DBY_RSP_QUEUE_PREFIX "dby_response_queue_"
using namespace std;
/**
* This method handles fetching the next item to be
*
* TODO - handle ordering
*/
std::string getNextQueueKey(RedisHandler& rh) {
std::vector<std::string> keys = rh.keys(std::string(DBY_CMD_QUEUE_PREFIX) + std::string("*"));
if (keys.size() > 0)
return keys[0];
else
return "";
}
/**
* This method handles extracting the value from the redis command key. The parser
* functionality to tokenize strings is used to assist
*/
long getKeyOrderValue(Parser& p, std::string key) {
vector<std::string> pieces = p.tokenize(key);
if (pieces.length() > 0)
return pieces[pieces.length() - 1];
else
return -1; // error
}
int main() {
std::string line;
Parser* parser = new Parser();
RedisHandler* redisHandler = new RedisHandler(REDISHOST, REDISPORT);
parser->setDaemon(true);
cout << "" << endl;
// Read the input
while (1) {
// 1. Fetch next command off the queue
this->redisHandler->connect();
std::string key = getNextQueueKey(*redisHandler);
std::string lock;
if (this->redisHandler->exists(key) && strcmp(key.c_str(), "") != 0) {
line = redisHandler->read(key);
// 2. LOCK KEY. If it's already locked try again
lock = std::string(DBY_CMD_QUEUE_LOCK_SUFFIX) + key;
if (!redisHandler->exists(lock)) {
redisHandler->write(lock, "1"); // lock it
} else {
std::chrono::milliseconds(1);
continue;
}
}
// 3. Parse the command and write response to redis
long key_value = getKeyOrderValue(key);
redisHandler->write(std::string(DBY_RSP_QUEUE_PREFIX) + key_value, parser->parse(line));
parser->resetState();
// 4. Remove the element and it's lock
redisHandler->deleteKey(key);
redisHandler->deleteKey(lock);
// 5. execute timeout
std::chrono::milliseconds(10);
}
return 0;
}
<commit_msg>refactor on daemon along with addition of validation to the flow<commit_after>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <chrono>
#include <iostream>
#include <string>
#include <redis3m/connection.h>
#include "parse.h"
#include "redis.h"
// Daemon Macros
#define DBY_CMD_QUEUE_LOCK_SUFFIX "_lock"
#define DBY_CMD_QUEUE_PREFIX "dby_command_queue_"
#define DBY_RSP_QUEUE_PREFIX "dby_response_queue_"
#define REDIS_POLL_TIMEOUT 2000
#define REDIS_RETRY_TIMEOUT 1000
using namespace std;
/**
* This method handles fetching the next item to be
*
* TODO - handle ordering
*/
std::string getNextQueueKey(RedisHandler& rh) {
std::vector<std::string> keys = rh.keys(std::string(DBY_CMD_QUEUE_PREFIX) + std::string("*"));
if (keys.size() > 0)
return keys[0];
else
return "";
}
/**
* This method handles extracting the value from the redis command key. The parser
* functionality to tokenize strings is used to assist
*/
long getKeyOrderValue(Parser& p, std::string key) {
vector<std::string> pieces = p.tokenize(key);
if (pieces.length() > 0)
return pieces[pieces.length() - 1];
else
return -1; // error
}
int main() {
std::string line;
std::string lock;
std::string key;
Parser* parser = new Parser();
RedisHandler* redisHandler = new RedisHandler(REDISHOST, REDISPORT);
parser->setDaemon(true);
cout << "" << endl;
// Read the input
while (1) {
// 1. execute timeout
std::chrono::milliseconds(REDIS_POLL_TIMEOUT);
// 2. Fetch next command off the queue
this->redisHandler->connect();
key = getNextQueueKey(*redisHandler);
lock = "";
if (this->redisHandler->exists(key) && strcmp(key.c_str(), "") != 0) {
line = redisHandler->read(key);
// 3. LOCK KEY. If it's already locked try again
lock = std::string(DBY_CMD_QUEUE_LOCK_SUFFIX) + key;
if (!redisHandler->exists(lock)) {
redisHandler->write(lock, "1"); // lock it
} else {
std::chrono::milliseconds(REDIS_RETRY_TIMEOUT);
continue; // locked, try again after a timeout
}
} else {
continue; // If the key does not exist the
}
// 4. Parse the command and write response to redis
long key_value = getKeyOrderValue(key);
// 5. Parse the command and write response to redis
if (key_value != -1) {
redisHandler->write(std::string(DBY_RSP_QUEUE_PREFIX) + key_value, parser->parse(line));
parser->resetState();
} else {
// Badly formed key, drop the key and remove the lock
cout << key + std::string(" is badly formed, can't determine value - not processed.") << endl;
}
// 6. Remove the element and it's lock
redisHandler->deleteKey(key);
redisHandler->deleteKey(lock);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <BALL/STRUCTURE/connectedComponentsProcessor.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/atomContainer.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/KERNEL/forEach.h>
#include <map>
#include <vector>
namespace BALL
{
ConnectedComponentsProcessor::ConnectedComponentsProcessor()
{
}
ConnectedComponentsProcessor::~ConnectedComponentsProcessor()
{
}
bool ConnectedComponentsProcessor::start()
{
clear();
return true;
}
/// Computes processor intern "components_", which contains the molecules
/// separate molecules
Processor::Result ConnectedComponentsProcessor::operator () (AtomContainer& ac)
{
// if possible one should try to refactor this, so that we can use the
// disjoint set without having to rely on the mapping. The mappings take
// about 30-50% of the whole computation time in this method!!!
const int num_atoms = ac.countAtoms();
// mapping: atom to int, and int to atom:
Atom* i_to_atm[num_atoms];
std::map< Atom*, int> atm_to_i; // std::map was most efficient, compared with hashmaps
// create empty disjoint set:
std::vector <int> atm_rank(num_atoms);
std::vector <int> atm_parent(num_atoms);
DisjointSet dset(&atm_rank[0], &atm_parent[0]);
//------------------------------------------------
// Populate the dset with elements and
// create a mapping from atom pointer to vertex (for adding edges later)
// and from int to atom-pointer
AtomIterator atom_it;
int i1 = 0;
BALL_FOREACH_ATOM(ac, atom_it)
{
dset.make_set(i1); // enter singleton sets for every atom
// create the necessary mappings:
atm_to_i[&*atom_it] = i1;
i_to_atm[i1] = (&*atom_it);
i1++;
}
//------------------------------------------------
// Add edges from the atom container (ac) to the disjoint set
// (iterate over all unique bonds)
int v1, v2;
Atom::BondIterator bond_iter;
BALL_FOREACH_INTRABOND(ac, atom_it, bond_iter)
{
v1 = atm_to_i[bond_iter->getFirstAtom()];
v2 = atm_to_i[bond_iter->getSecondAtom()];
dset.union_set(v1, v2); // union the elements that are connected
}
//------------------------------------------------
// Iterate through the component indices
// split according to the ds-information:
std::vector <int> pnames (num_atoms, -1); // mapps representative parents
// to component numbers
int num = 0;
int par = -1;
int idx = -1;
for (int i = 0; i < num_atoms; i++)
{
par = dset.find_set(i); // get parent of element 'i'
idx = pnames[par];
if (idx != -1)
{ // add element to existing component
components_[idx].push_back(i_to_atm[i]);
}
else
{ // create new component for current element:
Component tmp;
tmp.push_back(i_to_atm[i]);
components_.push_back(tmp);
pnames[par] = num;
num++;
}
}
return Processor::BREAK;
}// END OF PROCESSOR
bool ConnectedComponentsProcessor::finish()
{
return true;
}
void ConnectedComponentsProcessor::clear()
{
components_.clear();
}
Size ConnectedComponentsProcessor::getNumberOfConnectedComponents()
{
return components_.size();
}
void ConnectedComponentsProcessor::getComponents(ComponentVector &comp)
{
comp.assign(components_.begin(), components_.end());
}
/// Return the component with most atoms
void ConnectedComponentsProcessor::getLargestComponent(Molecule& result)
{
int i, pos = 0, max = 0;
for(i = 0; i< components_.size(); i++)
{
int tmp = components_[i].size() ;
if (tmp > max)
{
max = tmp;
pos = i;
}
}
for ( int i = 0; i < components_[pos].size(); i++)
{
result.insert( *(components_[pos][i]) );
}
}
void ConnectedComponentsProcessor::getMinAtomsComponents(MolVec& result, const int& min)
{
for(int i = 0; i < components_.size(); i++)
{
int siz = components_[i].size();
if (siz >= min)
{
Molecule tmp = Molecule();
for(int k = 0; k < siz; k++)
{
tmp.insert( *(components_[i][k]) );
}
result.push_back(tmp);
}
}
}
void ConnectedComponentsProcessor::getAllComponents(MolVec& results)
{
for(int i = 0; i < components_.size(); i++)
{
Molecule tmp = Molecule();
for(int k = 0; k < components_[i].size(); k++)
{
tmp.insert( *(components_[i][k]) );
}
results.push_back(tmp);
}
}
}
<commit_msg>Fix for the VisualStudio Issue 552 found by Laura-K by replacing C++ array with STD::Vector.<commit_after>#include <BALL/STRUCTURE/connectedComponentsProcessor.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/atomContainer.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/KERNEL/forEach.h>
#include <map>
#include <vector>
namespace BALL
{
ConnectedComponentsProcessor::ConnectedComponentsProcessor()
{
}
ConnectedComponentsProcessor::~ConnectedComponentsProcessor()
{
}
bool ConnectedComponentsProcessor::start()
{
clear();
return true;
}
/// Computes processor intern "components_", which contains the molecules
/// separate molecules
Processor::Result ConnectedComponentsProcessor::operator () (AtomContainer& ac)
{
// if possible one should try to refactor this, so that we can use the
// disjoint set without having to rely on the mapping. The mappings take
// about 30-50% of the whole computation time in this method!!!
const int num_atoms = ac.countAtoms();
// mapping: atom to int, and int to atom:
std::vector <Atom*> i_to_atm(num_atoms, 0);
std::map< Atom*, int> atm_to_i; // std::map was most efficient, compared with hashmaps
// create empty disjoint set:
std::vector <int> atm_rank(num_atoms);
std::vector <int> atm_parent(num_atoms);
DisjointSet dset(&atm_rank[0], &atm_parent[0]);
//------------------------------------------------
// Populate the dset with elements and
// create a mapping from atom pointer to vertex (for adding edges later)
// and from int to atom-pointer
AtomIterator atom_it;
int i1 = 0;
BALL_FOREACH_ATOM(ac, atom_it)
{
dset.make_set(i1); // enter singleton sets for every atom
// create the necessary mappings:
atm_to_i[&*atom_it] = i1;
i_to_atm[i1] = (&*atom_it);
i1++;
}
//------------------------------------------------
// Add edges from the atom container (ac) to the disjoint set
// (iterate over all unique bonds)
int v1, v2;
Atom::BondIterator bond_iter;
BALL_FOREACH_INTRABOND(ac, atom_it, bond_iter)
{
v1 = atm_to_i[bond_iter->getFirstAtom()];
v2 = atm_to_i[bond_iter->getSecondAtom()];
dset.union_set(v1, v2); // union the elements that are connected
}
//------------------------------------------------
// Iterate through the component indices
// split according to the ds-information:
std::vector <int> pnames (num_atoms, -1); // mapps representative parents
// to component numbers
int num = 0;
int par = -1;
int idx = -1;
for (int i = 0; i < num_atoms; i++)
{
par = dset.find_set(i); // get parent of element 'i'
idx = pnames[par];
if (idx != -1)
{ // add element to existing component
components_[idx].push_back(i_to_atm[i]);
}
else
{ // create new component for current element:
Component tmp;
tmp.push_back(i_to_atm[i]);
components_.push_back(tmp);
pnames[par] = num;
num++;
}
}
return Processor::BREAK;
}// END OF PROCESSOR
bool ConnectedComponentsProcessor::finish()
{
return true;
}
void ConnectedComponentsProcessor::clear()
{
components_.clear();
}
Size ConnectedComponentsProcessor::getNumberOfConnectedComponents()
{
return components_.size();
}
void ConnectedComponentsProcessor::getComponents(ComponentVector &comp)
{
comp.assign(components_.begin(), components_.end());
}
/// Return the component with most atoms
void ConnectedComponentsProcessor::getLargestComponent(Molecule& result)
{
int i, pos = 0, max = 0;
for(i = 0; i< components_.size(); i++)
{
int tmp = components_[i].size() ;
if (tmp > max)
{
max = tmp;
pos = i;
}
}
for ( int i = 0; i < components_[pos].size(); i++)
{
result.insert( *(components_[pos][i]) );
}
}
void ConnectedComponentsProcessor::getMinAtomsComponents(MolVec& result, const int& min)
{
for(int i = 0; i < components_.size(); i++)
{
int siz = components_[i].size();
if (siz >= min)
{
Molecule tmp = Molecule();
for(int k = 0; k < siz; k++)
{
tmp.insert( *(components_[i][k]) );
}
result.push_back(tmp);
}
}
}
void ConnectedComponentsProcessor::getAllComponents(MolVec& results)
{
for(int i = 0; i < components_.size(); i++)
{
Molecule tmp = Molecule();
for(int k = 0; k < components_[i].size(); k++)
{
tmp.insert( *(components_[i][k]) );
}
results.push_back(tmp);
}
}
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* CompressZFP.cpp
*
* Created on: Jul 25, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#include "CompressZFP.h"
#include "adios2/helper/adiosFunctions.h"
#include <sstream>
namespace adios2
{
namespace core
{
namespace compress
{
CompressZFP::CompressZFP(const Params ¶meters) : Operator("zfp", parameters)
{
}
size_t CompressZFP::DoBufferMaxSize(const void *dataIn, const Dims &dimensions,
DataType type,
const Params ¶meters) const
{
Dims convertedDims = ConvertDims(dimensions, type, 3);
zfp_field *field = GetZFPField(dataIn, convertedDims, type);
zfp_stream *stream = GetZFPStream(convertedDims, type, parameters);
const size_t maxSize = zfp_stream_maximum_size(stream, field);
zfp_field_free(field);
zfp_stream_close(stream);
return maxSize;
}
size_t CompressZFP::Compress(const void *dataIn, const Dims &dimensions,
DataType type, void *bufferOut,
const Params ¶meters, Params &info)
{
Dims convertedDims = ConvertDims(dimensions, type, 3);
zfp_field *field = GetZFPField(dataIn, convertedDims, type);
zfp_stream *stream = GetZFPStream(convertedDims, type, parameters);
size_t maxSize = zfp_stream_maximum_size(stream, field);
// associate bitstream
bitstream *bitstream = stream_open(bufferOut, maxSize);
zfp_stream_set_bit_stream(stream, bitstream);
zfp_stream_rewind(stream);
size_t sizeOut = zfp_compress(stream, field);
if (sizeOut == 0)
{
throw std::invalid_argument("ERROR: zfp failed, compressed buffer "
"size is 0, in call to Compress");
}
zfp_field_free(field);
zfp_stream_close(stream);
stream_close(bitstream);
return sizeOut;
}
size_t CompressZFP::Decompress(const void *bufferIn, const size_t sizeIn,
void *dataOut, const DataType type,
const Dims &blockStart, const Dims &blockCount,
const Params ¶meters, Params &info)
{
auto lf_GetTypeSize = [](const zfp_type zfpType) -> size_t {
size_t size = 0;
if (zfpType == zfp_type_int32 || zfpType == zfp_type_float)
{
size = 4;
}
else if (zfpType == zfp_type_int64 || zfpType == zfp_type_double)
{
size = 8;
}
return size;
};
Dims convertedDims = ConvertDims(blockCount, type, 3);
zfp_field *field = GetZFPField(dataOut, convertedDims, type);
zfp_stream *stream = GetZFPStream(convertedDims, type, parameters);
// associate bitstream
bitstream *bitstream = stream_open(const_cast<void *>(bufferIn), sizeIn);
zfp_stream_set_bit_stream(stream, bitstream);
zfp_stream_rewind(stream);
int status = zfp_decompress(stream, field);
if (!status)
{
throw std::invalid_argument("ERROR: zfp failed with status " +
std::to_string(status) +
", in call to CompressZfp Decompress\n");
}
zfp_field_free(field);
zfp_stream_close(stream);
stream_close(bitstream);
const size_t typeSizeBytes = lf_GetTypeSize(GetZfpType(type));
const size_t dataSizeBytes =
helper::GetTotalSize(convertedDims) * typeSizeBytes;
return dataSizeBytes;
}
bool CompressZFP::IsDataTypeValid(const DataType type) const
{
#define declare_type(T) \
if (helper::GetDataType<T>() == type) \
{ \
return true; \
}
ADIOS2_FOREACH_ZFP_TYPE_1ARG(declare_type)
#undef declare_type
return false;
}
// PRIVATE
zfp_type CompressZFP::GetZfpType(DataType type) const
{
zfp_type zfpType = zfp_type_none;
if (type == helper::GetDataType<double>())
{
zfpType = zfp_type_double;
}
else if (type == helper::GetDataType<float>())
{
zfpType = zfp_type_float;
}
else if (type == helper::GetDataType<int64_t>())
{
zfpType = zfp_type_int64;
}
else if (type == helper::GetDataType<int32_t>())
{
zfpType = zfp_type_int32;
}
else if (type == helper::GetDataType<std::complex<float>>())
{
zfpType = zfp_type_float;
}
else if (type == helper::GetDataType<std::complex<double>>())
{
zfpType = zfp_type_double;
}
else
{
throw std::invalid_argument(
"ERROR: type " + ToString(type) +
" not supported by zfp, only "
"signed int32_t, signed int64_t, float, and "
"double types are acceptable, from class "
"CompressZfp Transform\n");
}
return zfpType;
}
zfp_field *CompressZFP::GetZFPField(const void *data, const Dims &dimensions,
DataType type) const
{
auto lf_CheckField = [](const zfp_field *field,
const std::string zfpFieldFunction, DataType type) {
if (field == nullptr || field == NULL)
{
throw std::invalid_argument(
"ERROR: " + zfpFieldFunction + " failed for data of type " +
ToString(type) +
", data pointer might be corrupted, from "
"class CompressZfp Transform\n");
}
};
zfp_type zfpType = GetZfpType(type);
zfp_field *field = nullptr;
if (dimensions.size() == 1)
{
field = zfp_field_1d(const_cast<void *>(data), zfpType, dimensions[0]);
lf_CheckField(field, "zfp_field_1d", type);
}
else if (dimensions.size() == 2)
{
field = zfp_field_2d(const_cast<void *>(data), zfpType, dimensions[0],
dimensions[1]);
lf_CheckField(field, "zfp_field_2d", type);
}
else if (dimensions.size() == 3)
{
field = zfp_field_3d(const_cast<void *>(data), zfpType, dimensions[0],
dimensions[1], dimensions[2]);
lf_CheckField(field, "zfp_field_3d", type);
}
else
{
throw std::invalid_argument(
"ERROR: zfp_field* failed for data of type " + ToString(type) +
", only 1D, 2D and 3D dimensions are supported, from "
"class CompressZfp Transform\n");
}
return field;
}
zfp_stream *CompressZFP::GetZFPStream(const Dims &dimensions, DataType type,
const Params ¶meters) const
{
zfp_stream *stream = zfp_stream_open(NULL);
auto itAccuracy = parameters.find("accuracy");
const bool hasAccuracy = itAccuracy != parameters.end();
auto itRate = parameters.find("rate");
const bool hasRate = itRate != parameters.end();
auto itPrecision = parameters.find("precision");
const bool hasPrecision = itPrecision != parameters.end();
if ((hasAccuracy && hasRate) || (hasAccuracy && hasPrecision) ||
(hasRate && hasPrecision) || !(hasAccuracy || hasRate || hasPrecision))
{
std::ostringstream oss;
oss << "\nError: Requisite parameters to zfp not found.";
oss << " The key must be one and only one of 'accuracy', 'rate', "
"or 'precision'.";
oss << " The key and value provided are ";
for (auto &p : parameters)
{
oss << "(" << p.first << ", " << p.second << ").";
}
throw std::invalid_argument(oss.str());
}
if (hasAccuracy)
{
const double accuracy = helper::StringTo<double>(
itAccuracy->second, "setting accuracy in call to CompressZfp\n");
zfp_stream_set_accuracy(stream, accuracy);
}
else if (hasRate)
{
const double rate = helper::StringTo<double>(
itRate->second, "setting Rate in call to CompressZfp\n");
// TODO support last argument write random access?
zfp_stream_set_rate(stream, rate, GetZfpType(type),
static_cast<unsigned int>(dimensions.size()), 0);
}
else if (hasPrecision)
{
const unsigned int precision =
static_cast<unsigned int>(helper::StringTo<uint32_t>(
itPrecision->second,
"setting Precision in call to CompressZfp\n"));
zfp_stream_set_precision(stream, precision);
}
return stream;
}
} // end namespace compress
} // end namespace core
} // end namespace adios2
<commit_msg>removed more meaningless lambda functions in zfp<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* CompressZFP.cpp
*
* Created on: Jul 25, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#include "CompressZFP.h"
#include "adios2/helper/adiosFunctions.h"
#include <sstream>
namespace adios2
{
namespace core
{
namespace compress
{
CompressZFP::CompressZFP(const Params ¶meters) : Operator("zfp", parameters)
{
}
size_t CompressZFP::DoBufferMaxSize(const void *dataIn, const Dims &dimensions,
DataType type,
const Params ¶meters) const
{
Dims convertedDims = ConvertDims(dimensions, type, 3);
zfp_field *field = GetZFPField(dataIn, convertedDims, type);
zfp_stream *stream = GetZFPStream(convertedDims, type, parameters);
const size_t maxSize = zfp_stream_maximum_size(stream, field);
zfp_field_free(field);
zfp_stream_close(stream);
return maxSize;
}
size_t CompressZFP::Compress(const void *dataIn, const Dims &dimensions,
DataType type, void *bufferOut,
const Params ¶meters, Params &info)
{
Dims convertedDims = ConvertDims(dimensions, type, 3);
zfp_field *field = GetZFPField(dataIn, convertedDims, type);
zfp_stream *stream = GetZFPStream(convertedDims, type, parameters);
size_t maxSize = zfp_stream_maximum_size(stream, field);
// associate bitstream
bitstream *bitstream = stream_open(bufferOut, maxSize);
zfp_stream_set_bit_stream(stream, bitstream);
zfp_stream_rewind(stream);
size_t sizeOut = zfp_compress(stream, field);
if (sizeOut == 0)
{
throw std::invalid_argument("ERROR: zfp failed, compressed buffer "
"size is 0, in call to Compress");
}
zfp_field_free(field);
zfp_stream_close(stream);
stream_close(bitstream);
return sizeOut;
}
size_t CompressZFP::Decompress(const void *bufferIn, const size_t sizeIn,
void *dataOut, const DataType type,
const Dims &blockStart, const Dims &blockCount,
const Params ¶meters, Params &info)
{
Dims convertedDims = ConvertDims(blockCount, type, 3);
zfp_field *field = GetZFPField(dataOut, convertedDims, type);
zfp_stream *stream = GetZFPStream(convertedDims, type, parameters);
// associate bitstream
bitstream *bitstream = stream_open(const_cast<void *>(bufferIn), sizeIn);
zfp_stream_set_bit_stream(stream, bitstream);
zfp_stream_rewind(stream);
int status = zfp_decompress(stream, field);
if (!status)
{
throw std::invalid_argument("ERROR: zfp failed with status " +
std::to_string(status) +
", in call to CompressZfp Decompress\n");
}
zfp_field_free(field);
zfp_stream_close(stream);
stream_close(bitstream);
const size_t typeSizeBytes = helper::GetDataTypeSize(type);
const size_t dataSizeBytes =
helper::GetTotalSize(convertedDims) * typeSizeBytes;
return dataSizeBytes;
}
bool CompressZFP::IsDataTypeValid(const DataType type) const
{
#define declare_type(T) \
if (helper::GetDataType<T>() == type) \
{ \
return true; \
}
ADIOS2_FOREACH_ZFP_TYPE_1ARG(declare_type)
#undef declare_type
return false;
}
// PRIVATE
zfp_type CompressZFP::GetZfpType(DataType type) const
{
zfp_type zfpType = zfp_type_none;
if (type == helper::GetDataType<double>())
{
zfpType = zfp_type_double;
}
else if (type == helper::GetDataType<float>())
{
zfpType = zfp_type_float;
}
else if (type == helper::GetDataType<int64_t>())
{
zfpType = zfp_type_int64;
}
else if (type == helper::GetDataType<int32_t>())
{
zfpType = zfp_type_int32;
}
else if (type == helper::GetDataType<std::complex<float>>())
{
zfpType = zfp_type_float;
}
else if (type == helper::GetDataType<std::complex<double>>())
{
zfpType = zfp_type_double;
}
else
{
throw std::invalid_argument(
"ERROR: type " + ToString(type) +
" not supported by zfp, only "
"signed int32_t, signed int64_t, float, and "
"double types are acceptable, from class "
"CompressZfp Transform\n");
}
return zfpType;
}
zfp_field *CompressZFP::GetZFPField(const void *data, const Dims &dimensions,
DataType type) const
{
zfp_type zfpType = GetZfpType(type);
zfp_field *field = nullptr;
if (dimensions.size() == 1)
{
field = zfp_field_1d(const_cast<void *>(data), zfpType, dimensions[0]);
}
else if (dimensions.size() == 2)
{
field = zfp_field_2d(const_cast<void *>(data), zfpType, dimensions[0],
dimensions[1]);
}
else if (dimensions.size() == 3)
{
field = zfp_field_3d(const_cast<void *>(data), zfpType, dimensions[0],
dimensions[1], dimensions[2]);
}
else
{
throw std::invalid_argument(
"ERROR: zfp_field* failed for data of type " + ToString(type) +
", only 1D, 2D and 3D dimensions are supported, from "
"class CompressZfp\n");
}
if (field == nullptr)
{
throw std::invalid_argument(
"ERROR: zfp_field_" + std::to_string(dimensions.size()) +
"d failed for data of type " + ToString(type) +
", data might be corrupted, from class CompressZfp\n");
}
return field;
}
zfp_stream *CompressZFP::GetZFPStream(const Dims &dimensions, DataType type,
const Params ¶meters) const
{
zfp_stream *stream = zfp_stream_open(NULL);
auto itAccuracy = parameters.find("accuracy");
const bool hasAccuracy = itAccuracy != parameters.end();
auto itRate = parameters.find("rate");
const bool hasRate = itRate != parameters.end();
auto itPrecision = parameters.find("precision");
const bool hasPrecision = itPrecision != parameters.end();
if ((hasAccuracy && hasRate) || (hasAccuracy && hasPrecision) ||
(hasRate && hasPrecision) || !(hasAccuracy || hasRate || hasPrecision))
{
std::ostringstream oss;
oss << "\nError: Requisite parameters to zfp not found.";
oss << " The key must be one and only one of 'accuracy', 'rate', "
"or 'precision'.";
oss << " The key and value provided are ";
for (auto &p : parameters)
{
oss << "(" << p.first << ", " << p.second << ").";
}
throw std::invalid_argument(oss.str());
}
if (hasAccuracy)
{
const double accuracy = helper::StringTo<double>(
itAccuracy->second, "setting accuracy in call to CompressZfp\n");
zfp_stream_set_accuracy(stream, accuracy);
}
else if (hasRate)
{
const double rate = helper::StringTo<double>(
itRate->second, "setting Rate in call to CompressZfp\n");
// TODO support last argument write random access?
zfp_stream_set_rate(stream, rate, GetZfpType(type),
static_cast<unsigned int>(dimensions.size()), 0);
}
else if (hasPrecision)
{
const unsigned int precision =
static_cast<unsigned int>(helper::StringTo<uint32_t>(
itPrecision->second,
"setting Precision in call to CompressZfp\n"));
zfp_stream_set_precision(stream, precision);
}
return stream;
}
} // end namespace compress
} // end namespace core
} // end namespace adios2
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "tcframe_test_commons.cpp"
class MyGenerator : public BaseGenerator<DefaultProblem> {
void Config() {
setTestCasesDir("testdata");
setSolutionCommand("java Solution");
}
};
TEST(GeneratorTest, DefaultOptions) {
BaseGenerator<DefaultProblem>* generator = new DefaultGenerator();
generator->applyGeneratorConfiguration();
EXPECT_EQ("tc", generator->getTestCasesDir());
EXPECT_EQ("./solution", generator->getSolutionCommand());
}
TEST(GeneratorTest, MyOptions) {
BaseGenerator<DefaultProblem>* generator = new MyGenerator();
generator->applyGeneratorConfiguration();
EXPECT_EQ("testdata", generator->getTestCasesDir());
EXPECT_EQ("java Solution", generator->getSolutionCommand());
}
TEST(GeneratorTest, CommandLineOptions) {
char* argv[] = {(char*) "<runner>", (char*)"--tc-dir=testcases", (char*)"--solution-command=\"python sol.py\""};
BaseGenerator<DefaultProblem>* generator = new MyGenerator();
generator->applyGeneratorConfiguration();
generator->applyGeneratorCommandLineOptions(3, argv);
EXPECT_EQ("testcases", generator->getTestCasesDir());
EXPECT_EQ("\"python sol.py\"", generator->getSolutionCommand());
}
TEST(GeneratorTest, GenerationWithSubtasksAndTestGroups) {
FakeGeneratorLogger logger;
GeneratorWithTestGroups gen(&logger, new FakeGeneratorOperatingSystem());
int exitCode = gen.generate();
EXPECT_EQ(0, exitCode);
EXPECT_EQ(0, logger.getFailures("problem_sample_1").size());
EXPECT_EQ(0, logger.getFailures("problem_1_1").size());
EXPECT_EQ(0, logger.getFailures("problem_1_2").size());
EXPECT_EQ(0, logger.getFailures("problem_2_1").size());
EXPECT_EQ(0, logger.getFailures("problem_2_2").size());
EXPECT_EQ(0, logger.getFailures("problem_3_1").size());
}
TEST(GeneratorTest, FailedGenerationWithSubtasksAndTestGroups) {
FakeGeneratorLogger logger;
InvalidGeneratorWithTestGroups gen(&logger, new FakeGeneratorOperatingSystem());
int exitCode = gen.generate();
EXPECT_NE(0, exitCode);
auto failures_sample_1 = logger.getFailures("problem_sample_1");
ASSERT_EQ(2, failures_sample_1.size());
EXPECT_EQ(Failure("Does not satisfy subtask 1, on constraints:", 0), failures_sample_1[0]);
EXPECT_EQ(Failure("1 <= B && B <= 1000", 1), failures_sample_1[1]);
auto failures_1_1 = logger.getFailures("problem_1_1");
ASSERT_EQ(0, failures_1_1.size());
auto failures_1_2 = logger.getFailures("problem_1_2");
ASSERT_EQ(2, failures_1_2.size());
EXPECT_EQ(Failure("Does not satisfy subtask 1, on constraints:", 0), failures_1_2[0]);
EXPECT_EQ(Failure("1 <= B && B <= 1000", 1), failures_1_2[1]);
auto failures_2_1 = logger.getFailures("problem_2_1");
ASSERT_EQ(1, failures_2_1.size());
EXPECT_EQ(Failure("Satisfies subtask 1 but is not assigned to it", 0), failures_2_1[0]);
auto failures_2_2 = logger.getFailures("problem_2_2");
ASSERT_EQ(4, failures_2_2.size());
EXPECT_EQ(Failure("Does not satisfy subtask 2, on constraints:", 0), failures_2_2[0]);
EXPECT_EQ(Failure("1 <= A && A <= 2000000000", 1), failures_2_2[1]);
EXPECT_EQ(Failure("1 <= B && B <= 2000000000", 1), failures_2_2[2]);
EXPECT_EQ(Failure("Satisfies subtask 3 but is not assigned to it", 0), failures_2_2[3]);
}
TEST(GeneratorTest, GenerationWithoutSubtasksAndWithoutTestGroups) {
FakeGeneratorLogger logger;
GeneratorWithoutTestGroups gen(&logger, new FakeGeneratorOperatingSystem());
int exitCode = gen.generate();
EXPECT_EQ(0, exitCode);
EXPECT_EQ(0, logger.getFailures("problem_sample_1").size());
EXPECT_EQ(0, logger.getFailures("problem_sample_2").size());
EXPECT_EQ(0, logger.getFailures("problem_1").size());
EXPECT_EQ(0, logger.getFailures("problem_2").size());
}
TEST(GeneratorTest, FailedGenerationWithoutSubtasksAndWithoutTestGroups) {
FakeGeneratorLogger logger;
InvalidGeneratorWithoutTestGroups gen(&logger, new FakeGeneratorOperatingSystem());
int exitCode = gen.generate();
EXPECT_NE(0, exitCode);
auto failures_sample_1 = logger.getFailures("problem_sample_1");
ASSERT_EQ(0, failures_sample_1.size());
auto failures_sample_2 = logger.getFailures("problem_sample_2");
ASSERT_EQ(2, failures_sample_2.size());
EXPECT_EQ(Failure("Does not satisfy constraints, on:", 0), failures_sample_2[0]);
EXPECT_EQ(Failure("0 <= K <= 100", 1), failures_sample_2[1]);
auto failures_1 = logger.getFailures("problem_1");
ASSERT_EQ(0, failures_1.size());
auto failures_2 = logger.getFailures("problem_2");
ASSERT_EQ(2, failures_sample_2.size());
EXPECT_EQ(Failure("Does not satisfy constraints, on:", 0), failures_2[0]);
EXPECT_EQ(Failure("1 <= B && B <= 1000", 1), failures_2[1]);
}
TEST(GeneratorTest, GenerationWithFailedExecution) {
FakeGeneratorLogger logger;
GeneratorWithoutTestGroups gen(&logger, new FakeGeneratorOperatingSystem({ {"problem_1-generation-evaluation", ExecutionResult{1, new istringstream(), new istringstream("Intentionally failed")} } }));
int exitCode = gen.generate();
EXPECT_NE(0, exitCode);
auto failures = logger.getFailures("problem_1");
ASSERT_EQ(3, failures.size());
EXPECT_EQ(Failure("Execution of solution failed:", 0), failures[0]);
EXPECT_EQ(Failure("Exit code: 1", 1), failures[1]);
EXPECT_EQ(Failure("Standard error: Intentionally failed", 1), failures[2]);
}
<commit_msg>Tidy up generator tests<commit_after>#include "gtest/gtest.h"
#include "tcframe_test_commons.cpp"
class MyGenerator : public BaseGenerator<DefaultProblem> {
void Config() {
setTestCasesDir("testdata");
setSolutionCommand("java Solution");
}
};
TEST(GeneratorTest, DefaultOptions) {
BaseGenerator<DefaultProblem>* generator = new DefaultGenerator();
generator->applyGeneratorConfiguration();
EXPECT_EQ("tc", generator->getTestCasesDir());
EXPECT_EQ("./solution", generator->getSolutionCommand());
}
TEST(GeneratorTest, MyOptions) {
BaseGenerator<DefaultProblem>* generator = new MyGenerator();
generator->applyGeneratorConfiguration();
EXPECT_EQ("testdata", generator->getTestCasesDir());
EXPECT_EQ("java Solution", generator->getSolutionCommand());
}
TEST(GeneratorTest, CommandLineOptions) {
char* argv[] = {(char*) "<runner>", (char*)"--tc-dir=testcases", (char*)"--solution-command=\"python sol.py\""};
BaseGenerator<DefaultProblem>* generator = new MyGenerator();
generator->applyGeneratorConfiguration();
generator->applyGeneratorCommandLineOptions(3, argv);
EXPECT_EQ("testcases", generator->getTestCasesDir());
EXPECT_EQ("\"python sol.py\"", generator->getSolutionCommand());
}
TEST(GeneratorTest, GenerationWithSubtasksAndTestGroups) {
FakeGeneratorLogger* logger = new FakeGeneratorLogger();
BaseGenerator<ProblemWithSubtasks>* generator = new GeneratorWithTestGroups(logger, new FakeGeneratorOperatingSystem());
int exitCode = generator->generate();
EXPECT_EQ(0, exitCode);
EXPECT_EQ(0, logger->getFailures("problem_sample_1").size());
EXPECT_EQ(0, logger->getFailures("problem_1_1").size());
EXPECT_EQ(0, logger->getFailures("problem_1_2").size());
EXPECT_EQ(0, logger->getFailures("problem_2_1").size());
EXPECT_EQ(0, logger->getFailures("problem_2_2").size());
EXPECT_EQ(0, logger->getFailures("problem_3_1").size());
}
TEST(GeneratorTest, FailedGenerationWithSubtasksAndTestGroups) {
FakeGeneratorLogger* logger = new FakeGeneratorLogger();
BaseGenerator<ProblemWithSubtasks>* generator = new InvalidGeneratorWithTestGroups(logger, new FakeGeneratorOperatingSystem());
int exitCode = generator->generate();
EXPECT_NE(0, exitCode);
auto failures_sample_1 = logger->getFailures("problem_sample_1");
ASSERT_EQ(2, failures_sample_1.size());
EXPECT_EQ(Failure("Does not satisfy subtask 1, on constraints:", 0), failures_sample_1[0]);
EXPECT_EQ(Failure("1 <= B && B <= 1000", 1), failures_sample_1[1]);
auto failures_1_1 = logger->getFailures("problem_1_1");
ASSERT_EQ(0, failures_1_1.size());
auto failures_1_2 = logger->getFailures("problem_1_2");
ASSERT_EQ(2, failures_1_2.size());
EXPECT_EQ(Failure("Does not satisfy subtask 1, on constraints:", 0), failures_1_2[0]);
EXPECT_EQ(Failure("1 <= B && B <= 1000", 1), failures_1_2[1]);
auto failures_2_1 = logger->getFailures("problem_2_1");
ASSERT_EQ(1, failures_2_1.size());
EXPECT_EQ(Failure("Satisfies subtask 1 but is not assigned to it", 0), failures_2_1[0]);
auto failures_2_2 = logger->getFailures("problem_2_2");
ASSERT_EQ(4, failures_2_2.size());
EXPECT_EQ(Failure("Does not satisfy subtask 2, on constraints:", 0), failures_2_2[0]);
EXPECT_EQ(Failure("1 <= A && A <= 2000000000", 1), failures_2_2[1]);
EXPECT_EQ(Failure("1 <= B && B <= 2000000000", 1), failures_2_2[2]);
EXPECT_EQ(Failure("Satisfies subtask 3 but is not assigned to it", 0), failures_2_2[3]);
}
TEST(GeneratorTest, GenerationWithoutSubtasksAndWithoutTestGroups) {
FakeGeneratorLogger* logger = new FakeGeneratorLogger();
BaseGenerator<ProblemWithoutSubtasks>* generator = new GeneratorWithoutTestGroups(logger, new FakeGeneratorOperatingSystem());
int exitCode = generator->generate();
EXPECT_EQ(0, exitCode);
EXPECT_EQ(0, logger->getFailures("problem_sample_1").size());
EXPECT_EQ(0, logger->getFailures("problem_sample_2").size());
EXPECT_EQ(0, logger->getFailures("problem_1").size());
EXPECT_EQ(0, logger->getFailures("problem_2").size());
}
TEST(GeneratorTest, FailedGenerationWithoutSubtasksAndWithoutTestGroups) {
FakeGeneratorLogger* logger = new FakeGeneratorLogger();
BaseGenerator<ProblemWithoutSubtasks>* generator = new InvalidGeneratorWithoutTestGroups(logger, new FakeGeneratorOperatingSystem());
int exitCode = generator->generate();
EXPECT_NE(0, exitCode);
auto failures_sample_1 = logger->getFailures("problem_sample_1");
ASSERT_EQ(0, failures_sample_1.size());
auto failures_sample_2 = logger->getFailures("problem_sample_2");
ASSERT_EQ(2, failures_sample_2.size());
EXPECT_EQ(Failure("Does not satisfy constraints, on:", 0), failures_sample_2[0]);
EXPECT_EQ(Failure("0 <= K <= 100", 1), failures_sample_2[1]);
auto failures_1 = logger->getFailures("problem_1");
ASSERT_EQ(0, failures_1.size());
auto failures_2 = logger->getFailures("problem_2");
ASSERT_EQ(2, failures_sample_2.size());
EXPECT_EQ(Failure("Does not satisfy constraints, on:", 0), failures_2[0]);
EXPECT_EQ(Failure("1 <= B && B <= 1000", 1), failures_2[1]);
}
TEST(GeneratorTest, GenerationWithFailedExecution) {
FakeGeneratorLogger* logger = new FakeGeneratorLogger();
map<string, ExecutionResult> arrangedResultsMap = {
{"problem_1-generation-evaluation", ExecutionResult{1, new istringstream(), new istringstream("Intentionally failed")} }
};
BaseGenerator<ProblemWithoutSubtasks>* generator = new GeneratorWithoutTestGroups(logger, new FakeGeneratorOperatingSystem(arrangedResultsMap));
int exitCode = generator->generate();
EXPECT_NE(0, exitCode);
auto failures = logger->getFailures("problem_1");
ASSERT_EQ(3, failures.size());
EXPECT_EQ(Failure("Execution of solution failed:", 0), failures[0]);
EXPECT_EQ(Failure("Exit code: 1", 1), failures[1]);
EXPECT_EQ(Failure("Standard error: Intentionally failed", 1), failures[2]);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, 2016, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest/gtest.h"
#include "mpi.h"
#ifndef NAME_MAX
#define NAME_MAX 1024
#endif
int main(int argc, char **argv)
{
int err = 0;
int rank = 0;
int comm_size = 0;
MPI_Init(&argc, &argv);
testing::InitGoogleTest(&argc, argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
char per_rank_log_name[NAME_MAX];
char per_rank_err_name[NAME_MAX];
snprintf(per_rank_log_name, NAME_MAX, ".geopm_mpi_test.%.3d.log", rank);
snprintf(per_rank_err_name, NAME_MAX, ".geopm_mpi_test.%.3d.err", rank);
int stdout_fileno_dup;
int stderr_fileno_dup;
stdout_fileno_dup = dup(STDOUT_FILENO);
stderr_fileno_dup = dup(STDERR_FILENO);
freopen(per_rank_log_name, "w", stdout);
freopen(per_rank_err_name, "w", stderr);
try {
err = RUN_ALL_TESTS();
}
catch (std::exception ex) {
err = err ? err : 1;
std::cerr << "Error: <geopm_mpi_test> [" << rank << "] " << ex.what() << std::endl;
}
fflush(stdout);
dup2(stdout_fileno_dup, STDOUT_FILENO);
dup2(stderr_fileno_dup, STDERR_FILENO);
MPI_Barrier(MPI_COMM_WORLD);
if (!rank) {
FILE *fid_in = NULL;
int nread;
char buffer[NAME_MAX];
for (int i = 0; i < comm_size; ++i) {
snprintf(per_rank_log_name, NAME_MAX, ".geopm_mpi_test.%.3d.log", i);
fid_in = fopen(per_rank_log_name, "r");
fprintf(stdout, "********** Log: <geopm_mpi_test> [%.3d] **********\n", i);
nread = -1;
while (fid_in && nread) {
nread = fread(buffer, 1, NAME_MAX, fid_in);
fwrite(buffer, 1, nread, stdout);
}
fprintf(stdout, "************************************************************\n");
fclose(fid_in);
unlink(per_rank_log_name);
snprintf(per_rank_err_name, NAME_MAX, ".geopm_mpi_test.%.3d.err", i);
fid_in = fopen(per_rank_err_name, "r");
nread = -1;
bool is_first_print = true;
bool is_err_empty = true;
while (fid_in && nread) {
nread = fread(buffer, 1, NAME_MAX, fid_in);
if (nread && is_first_print) {
fprintf(stdout, "********** Error: <geopm_mpi_test> [%.3d] **********\n", i);
is_err_empty = false;
}
fwrite(buffer, 1, nread, stdout);
is_first_print = false;
}
if (!is_err_empty) {
fprintf(stdout, "************************************************************\n");
}
fclose(fid_in);
unlink(per_rank_err_name);
}
fflush(stdout);
}
int all_err;
MPI_Allreduce(&err, &all_err, 1, MPI_INT, MPI_LOR, MPI_COMM_WORLD);
if (all_err) {
all_err = -255;
}
MPI_Finalize();
if (!err) {
err = all_err;
}
if (!rank) {
_exit(err);
}
return err;
}
<commit_msg>Added error checking for MPI_Init in unit tests.<commit_after>/*
* Copyright (c) 2015, 2016, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest/gtest.h"
#include "mpi.h"
#ifndef NAME_MAX
#define NAME_MAX 1024
#endif
int main(int argc, char **argv)
{
int err = 0;
int rank = 0;
int comm_size = 0;
err = MPI_Init(&argc, &argv);
if (err) {
std::cerr << "Error: <geopm_mpi_test>, MPI_Init failed: " << err << std::endl;
return err;
}
testing::InitGoogleTest(&argc, argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
char per_rank_log_name[NAME_MAX];
char per_rank_err_name[NAME_MAX];
snprintf(per_rank_log_name, NAME_MAX, ".geopm_mpi_test.%.3d.log", rank);
snprintf(per_rank_err_name, NAME_MAX, ".geopm_mpi_test.%.3d.err", rank);
int stdout_fileno_dup;
int stderr_fileno_dup;
stdout_fileno_dup = dup(STDOUT_FILENO);
stderr_fileno_dup = dup(STDERR_FILENO);
freopen(per_rank_log_name, "w", stdout);
freopen(per_rank_err_name, "w", stderr);
try {
err = RUN_ALL_TESTS();
}
catch (std::exception ex) {
err = err ? err : 1;
std::cerr << "Error: <geopm_mpi_test> [" << rank << "] " << ex.what() << std::endl;
}
fflush(stdout);
dup2(stdout_fileno_dup, STDOUT_FILENO);
dup2(stderr_fileno_dup, STDERR_FILENO);
MPI_Barrier(MPI_COMM_WORLD);
if (!rank) {
FILE *fid_in = NULL;
int nread;
char buffer[NAME_MAX];
for (int i = 0; i < comm_size; ++i) {
snprintf(per_rank_log_name, NAME_MAX, ".geopm_mpi_test.%.3d.log", i);
fid_in = fopen(per_rank_log_name, "r");
fprintf(stdout, "********** Log: <geopm_mpi_test> [%.3d] **********\n", i);
nread = -1;
while (fid_in && nread) {
nread = fread(buffer, 1, NAME_MAX, fid_in);
fwrite(buffer, 1, nread, stdout);
}
fprintf(stdout, "************************************************************\n");
fclose(fid_in);
unlink(per_rank_log_name);
snprintf(per_rank_err_name, NAME_MAX, ".geopm_mpi_test.%.3d.err", i);
fid_in = fopen(per_rank_err_name, "r");
nread = -1;
bool is_first_print = true;
bool is_err_empty = true;
while (fid_in && nread) {
nread = fread(buffer, 1, NAME_MAX, fid_in);
if (nread && is_first_print) {
fprintf(stdout, "********** Error: <geopm_mpi_test> [%.3d] **********\n", i);
is_err_empty = false;
}
fwrite(buffer, 1, nread, stdout);
is_first_print = false;
}
if (!is_err_empty) {
fprintf(stdout, "************************************************************\n");
}
fclose(fid_in);
unlink(per_rank_err_name);
}
fflush(stdout);
}
int all_err;
MPI_Allreduce(&err, &all_err, 1, MPI_INT, MPI_LOR, MPI_COMM_WORLD);
if (all_err) {
all_err = -255;
}
MPI_Finalize();
if (!err) {
err = all_err;
}
if (!rank) {
_exit(err);
}
return err;
}
<|endoftext|> |
<commit_before>#include "tests-base.hpp"
extern "C" {
#include "../internal/codepoint.h"
};
TEST(CodepointEncodedLength, SingleByte)
{
EXPECT_EQ(1, codepoint_encoded_length(0x0061));
}
TEST(CodepointEncodedLength, SingleByteMinimum)
{
EXPECT_EQ(1, codepoint_encoded_length(0x0000));
}
TEST(CodepointEncodedLength, SingleByteMaximum)
{
EXPECT_EQ(1, codepoint_encoded_length(0x007F));
}
TEST(CodepointEncodedLength, TwoBytes)
{
EXPECT_EQ(2, codepoint_encoded_length(0x02A0));
}
TEST(CodepointEncodedLength, TwoBytesMinimum)
{
EXPECT_EQ(2, codepoint_encoded_length(0x0080));
}
TEST(CodepointEncodedLength, TwoBytesMaximum)
{
EXPECT_EQ(2, codepoint_encoded_length(0x07FF));
}
TEST(CodepointEncodedLength, ThreeBytes)
{
EXPECT_EQ(3, codepoint_encoded_length(0xA2A3));
}
TEST(CodepointEncodedLength, ThreeBytesMinimum)
{
EXPECT_EQ(3, codepoint_encoded_length(0x0800));
}
TEST(CodepointEncodedLength, ThreeBytesMaximum)
{
EXPECT_EQ(3, codepoint_encoded_length(0xFFFF));
}
TEST(CodepointEncodedLength, FourBytes)
{
EXPECT_EQ(4, codepoint_encoded_length(0x23A88));
}
TEST(CodepointEncodedLength, FourBytesMinimum)
{
EXPECT_EQ(4, codepoint_encoded_length(0x10000));
}
TEST(CodepointEncodedLength, FourBytesMaximum)
{
EXPECT_EQ(4, codepoint_encoded_length(0x10FFFF));
}
TEST(CodepointEncodedLength, AboveLegalUnicode)
{
EXPECT_EQ(0, codepoint_encoded_length(0xDEADC0DE));
}<commit_msg>suite-codepoint-encoded-length: Renamed tests.<commit_after>#include "tests-base.hpp"
extern "C" {
#include "../internal/codepoint.h"
};
TEST(CodepointEncodedLength, SingleByte)
{
EXPECT_EQ(1, codepoint_encoded_length(0x0061));
}
TEST(CodepointEncodedLength, SingleByteFirst)
{
EXPECT_EQ(1, codepoint_encoded_length(0x0000));
}
TEST(CodepointEncodedLength, SingleByteLast)
{
EXPECT_EQ(1, codepoint_encoded_length(0x007F));
}
TEST(CodepointEncodedLength, TwoBytes)
{
EXPECT_EQ(2, codepoint_encoded_length(0x02A0));
}
TEST(CodepointEncodedLength, TwoBytesFirst)
{
EXPECT_EQ(2, codepoint_encoded_length(0x0080));
}
TEST(CodepointEncodedLength, TwoBytesLast)
{
EXPECT_EQ(2, codepoint_encoded_length(0x07FF));
}
TEST(CodepointEncodedLength, ThreeBytes)
{
EXPECT_EQ(3, codepoint_encoded_length(0xA2A3));
}
TEST(CodepointEncodedLength, ThreeBytesFirst)
{
EXPECT_EQ(3, codepoint_encoded_length(0x0800));
}
TEST(CodepointEncodedLength, ThreeBytesLast)
{
EXPECT_EQ(3, codepoint_encoded_length(0xFFFF));
}
TEST(CodepointEncodedLength, FourBytes)
{
EXPECT_EQ(4, codepoint_encoded_length(0x23A88));
}
TEST(CodepointEncodedLength, FourBytesFirst)
{
EXPECT_EQ(4, codepoint_encoded_length(0x10000));
}
TEST(CodepointEncodedLength, FourBytesLast)
{
EXPECT_EQ(4, codepoint_encoded_length(0x10FFFF));
}
TEST(CodepointEncodedLength, AboveLegalUnicode)
{
EXPECT_EQ(0, codepoint_encoded_length(0xDEADC0DE));
}<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/bind.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/zip_view.hpp>
#include <boost/fusion/include/vector.hpp>
#include <Eigen/Core>
namespace demo
{
// Data structure
template<typename T, int SIZE1, int SIZE2>
struct data
{
T ar1[SIZE1][SIZE2];
T ar2[SIZE1][SIZE2];
};
// Eigen Map to C-style arrays
template<typename T>
struct EigenMap
{
typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1> > type;
};
// Eigen Maps applied to data structures
template<typename T>
struct data_eigen
{
template <int SIZE1, int SIZE2>
data_eigen(data<T,SIZE1,SIZE2>& src)
: ar1(typename EigenMap<T>::type(&src.ar1[0][0], SIZE1*SIZE2)),
ar2(typename EigenMap<T>::type(&src.ar2[0][0], SIZE1*SIZE2))
{
}
typename EigenMap<T>::type ar1;
typename EigenMap<T>::type ar2;
};
// Print operator
struct print
{
template<typename T>
void operator()(const Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1> >& t) const
{
Eigen::IOFormat CommaInitFmt(Eigen::StreamPrecision,
Eigen::DontAlignCols,
", ", ", ", "", "", " ", "");
std::cout << t.transpose().format(CommaInitFmt) << std::endl;
}
};
// Scalar multiplication operator
struct scalarMult
{
template<typename T, typename U>
void operator()(T& t, U& u) const
{
t *= u;
}
};
// Addition operator
struct add
{
template <typename ZipView>
void operator() (const ZipView& t) const
{
boost::fusion::at_c<2>(t) = boost::fusion::at_c<0> (t)
+ boost::fusion::at_c<1> (t);
}
};
} // namespace demo
// Prepare boost::fusion code (in global namespace)
BOOST_FUSION_ADAPT_TPL_STRUCT
(
(T),
(demo::data_eigen) (T),
(typename demo::EigenMap<T>::type, ar1)
(typename demo::EigenMap<T>::type, ar2)
)
int main()
{
typedef float REALTYPE;
const int SIZE1 = 2;
const int SIZE2 = 2;
// Basic data structure with multidimensional arrays
demo::data<REALTYPE, SIZE1, SIZE2> d1;
for (uint i = 0; i < SIZE1; ++i)
for (uint j = 0; j < SIZE2; ++j)
{
d1.ar1[i][j] = (REALTYPE)((i+1)*(j+1));
d1.ar2[i][j] = (REALTYPE)(i + j);
}
demo::data<REALTYPE, SIZE1, SIZE2> d2;
demo::data<REALTYPE, SIZE1, SIZE2> d3;
memset(&d3, 0, sizeof(demo::data<REALTYPE, SIZE1, SIZE2>));
for (uint i = 0; i < SIZE1; ++i)
for (uint j = 0; j < SIZE2; ++j)
{
d2.ar1[i][j] = 1.0;
d2.ar2[i][j] = 2.0;
}
// Eigen::Map + BOOST_FUSION_ADAPT_TPL_STRUCT
demo::data_eigen<REALTYPE> eig_d1 (d1);
demo::data_eigen<REALTYPE> eig_d2 (d2);
demo::data_eigen<REALTYPE> eig_d3 (d3);
// Print test
std::cout << "d1:" << std::endl;
boost::fusion::for_each (eig_d1, demo::print ());
std::cout << std::endl;
// Scalar multiplication test
boost::fusion::for_each (eig_d1, boost::bind<void>
(demo::scalarMult (), _1, (REALTYPE)(2.0)));
std::cout << "d1 *= 2:" << std::endl;
boost::fusion::for_each (eig_d1, demo::print ());
std::cout << std::endl;
// Addition test
typedef demo::data_eigen<REALTYPE>& vector_ref;
typedef boost::fusion::vector<vector_ref,vector_ref,vector_ref> data_zip;
boost::fusion::for_each (boost::fusion::zip_view<data_zip>
(data_zip (eig_d1, eig_d2, eig_d3)),
demo::add());
std::cout << "d2:" << std::endl;
boost::fusion::for_each (eig_d2, demo::print ());
std::cout << std::endl;
std::cout << "d3 = d1 + d2:" << std::endl;
boost::fusion::for_each (eig_d3, demo::print());
std::cout << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>boost_fusion_eigen: add const map.<commit_after>#include <iostream>
#include <boost/bind.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/zip_view.hpp>
#include <boost/fusion/include/vector.hpp>
#include <Eigen/Core>
namespace demo
{
// Data structure
template<typename T, int SIZE1, int SIZE2>
struct data
{
T ar1[SIZE1][SIZE2];
T ar2[SIZE1][SIZE2];
};
// Eigen Map to C-style arrays
template<typename T>
struct EigenMap
{
typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1> > type;
};
template<typename T>
struct const_EigenMap
{
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1> > type;
};
// Eigen Maps applied to data structures
template<typename T>
struct data_eigen
{
template <int SIZE1, int SIZE2>
data_eigen (data<T,SIZE1,SIZE2>& src)
: ar1 (typename EigenMap<T>::type (&src.ar1[0][0], SIZE1*SIZE2)),
ar2 (typename EigenMap<T>::type (&src.ar2[0][0], SIZE1*SIZE2))
{
}
typename EigenMap<T>::type ar1;
typename EigenMap<T>::type ar2;
};
template<typename T>
struct const_data_eigen
{
template <int SIZE1, int SIZE2>
const_data_eigen (const data<T,SIZE1,SIZE2>& src)
: ar1 (typename const_EigenMap<T>::type (&src.ar1[0][0], SIZE1*SIZE2)),
ar2 (typename const_EigenMap<T>::type (&src.ar2[0][0], SIZE1*SIZE2))
{
}
typename const_EigenMap<T>::type ar1;
typename const_EigenMap<T>::type ar2;
};
// Print operator
struct print
{
template<typename U>
void operator() (const U& t) const
{
Eigen::IOFormat CommaInitFmt(Eigen::StreamPrecision,
Eigen::DontAlignCols,
", ", ", ", "", "", " ", "");
std::cout << t.transpose().format(CommaInitFmt) << std::endl;
}
};
// Scalar multiplication operator
struct scalarMult
{
template<typename T, typename U>
void operator()(T& t, U& u) const
{
t *= u;
}
};
// Addition operator
struct add
{
template <typename ZipView>
void operator() (const ZipView& t) const
{
boost::fusion::at_c<2>(t) = boost::fusion::at_c<0> (t)
+ boost::fusion::at_c<1> (t);
}
};
} // namespace demo
// Prepare boost::fusion code (in global namespace)
BOOST_FUSION_ADAPT_TPL_STRUCT
(
(T),
(demo::data_eigen) (T),
(typename demo::EigenMap<T>::type, ar1)
(typename demo::EigenMap<T>::type, ar2)
)
BOOST_FUSION_ADAPT_TPL_STRUCT
(
(T),
(demo::const_data_eigen) (T),
(typename demo::const_EigenMap<T>::type, ar1)
(typename demo::const_EigenMap<T>::type, ar2)
)
int main()
{
typedef float REALTYPE;
const int SIZE1 = 2;
const int SIZE2 = 2;
// Basic data structure with multidimensional arrays
demo::data<REALTYPE, SIZE1, SIZE2> d1;
for (uint i = 0; i < SIZE1; ++i)
for (uint j = 0; j < SIZE2; ++j)
{
d1.ar1[i][j] = (REALTYPE)((i+1)*(j+1));
d1.ar2[i][j] = (REALTYPE)(i + j);
}
demo::data<REALTYPE, SIZE1, SIZE2> d2;
demo::data<REALTYPE, SIZE1, SIZE2> d3;
memset (&d3, 0, sizeof(demo::data<REALTYPE, SIZE1, SIZE2>));
for (uint i = 0; i < SIZE1; ++i)
for (uint j = 0; j < SIZE2; ++j)
{
d2.ar1[i][j] = 1.0;
d2.ar2[i][j] = 2.0;
}
// Eigen::Map + BOOST_FUSION_ADAPT_TPL_STRUCT
demo::data_eigen<REALTYPE> eig_d1 (d1);
const demo::const_data_eigen<REALTYPE> eig_d2 (d2);
demo::data_eigen<REALTYPE> eig_d3 (d3);
// Print test
std::cout << "d1:" << std::endl;
boost::fusion::for_each (eig_d1, demo::print ());
std::cout << std::endl;
// Scalar multiplication test
boost::fusion::for_each (eig_d1, boost::bind<void>
(demo::scalarMult (), _1, (REALTYPE)(2.0)));
std::cout << "d1 *= 2:" << std::endl;
boost::fusion::for_each (eig_d1, demo::print ());
std::cout << std::endl;
// Addition test
typedef demo::data_eigen<REALTYPE>& vector_ref;
typedef const demo::const_data_eigen<REALTYPE>& const_vector_ref;
typedef boost::fusion::vector<vector_ref,
const_vector_ref,
vector_ref> data_zip;
boost::fusion::for_each (boost::fusion::zip_view<data_zip>
(data_zip (eig_d1, eig_d2, eig_d3)),
demo::add ());
std::cout << "d2:" << std::endl;
boost::fusion::for_each (eig_d2, demo::print ());
std::cout << std::endl;
std::cout << "d3 = d1 + d2:" << std::endl;
boost::fusion::for_each (eig_d3, demo::print());
std::cout << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright 2017 Open Source Robotics Foundation, 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 <string>
#include <vector>
#include "rosidl_typesupport_opensplice_cpp/misc.hpp"
namespace rosidl_typesupport_opensplice_cpp
{
static const char * const ros_topic_prefix = "rt";
static const char * const ros_service_request_prefix = "rq";
static const char * const ros_service_response_prefix = "rr";
const std::vector<std::string> &
get_ros_prefixes()
{
static const std::vector<std::string> ros_prefixes =
{ros_topic_prefix, ros_service_request_prefix, ros_service_response_prefix};
return ros_prefixes;
}
std::string
get_ros_topic_prefix()
{
return ros_topic_prefix;
}
std::string
get_ros_service_request_prefix()
{
return ros_service_request_prefix;
}
std::string
get_ros_service_response_prefix()
{
return ros_service_response_prefix;
}
bool
process_topic_name(
const char * topic_name,
bool avoid_ros_namespace_conventions,
std::string & topic_str,
std::string & partition_str)
{
const std::string topic_name_ = topic_name;
size_t pos;
pos = topic_name_.find_last_of('/');
partition_str.clear();
if (!avoid_ros_namespace_conventions) {
partition_str = ros_topic_prefix;
if (0 != topic_name_.substr(0, pos).size()) {
partition_str += '/';
}
}
partition_str += topic_name_.substr(0, pos);
topic_str = topic_name_.substr(pos + 1);
return true;
}
bool
process_service_name(
const char * service_name,
bool avoid_ros_namespace_conventions,
std::string & service_str,
std::string & request_partition_str,
std::string & response_partition_str)
{
const std::string service_name_ = service_name;
size_t pos;
pos = service_name_.find_last_of('/');
request_partition_str.clear();
response_partition_str.clear();
if (!avoid_ros_namespace_conventions) {
request_partition_str = ros_service_request_prefix;
response_partition_str = ros_service_response_prefix;
if (0 != service_name_.substr(0, pos).size()) {
request_partition_str += '/';
response_partition_str += '/';
}
}
request_partition_str += service_name_.substr(0, pos);
response_partition_str += service_name_.substr(0, pos);
service_str = service_name_.substr(pos + 1);
return true;
}
} // namespace rosidl_typesupport_opensplice_cpp
<commit_msg>don't add '/' if topic/service starts with a slash (#221)<commit_after>// Copyright 2017 Open Source Robotics Foundation, 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 <string>
#include <vector>
#include "rosidl_typesupport_opensplice_cpp/misc.hpp"
namespace rosidl_typesupport_opensplice_cpp
{
static const char * const ros_topic_prefix = "rt";
static const char * const ros_service_request_prefix = "rq";
static const char * const ros_service_response_prefix = "rr";
const std::vector<std::string> &
get_ros_prefixes()
{
static const std::vector<std::string> ros_prefixes =
{ros_topic_prefix, ros_service_request_prefix, ros_service_response_prefix};
return ros_prefixes;
}
std::string
get_ros_topic_prefix()
{
return ros_topic_prefix;
}
std::string
get_ros_service_request_prefix()
{
return ros_service_request_prefix;
}
std::string
get_ros_service_response_prefix()
{
return ros_service_response_prefix;
}
bool
process_topic_name(
const char * topic_name,
bool avoid_ros_namespace_conventions,
std::string & topic_str,
std::string & partition_str)
{
const std::string topic_name_ = topic_name;
size_t pos;
pos = topic_name_.find_last_of('/');
partition_str.clear();
if (!avoid_ros_namespace_conventions) {
partition_str = ros_topic_prefix;
if (0 != topic_name_.substr(0, pos).size() && topic_name_[0] != '/') {
partition_str += '/';
}
}
partition_str += topic_name_.substr(0, pos);
topic_str = topic_name_.substr(pos + 1);
return true;
}
bool
process_service_name(
const char * service_name,
bool avoid_ros_namespace_conventions,
std::string & service_str,
std::string & request_partition_str,
std::string & response_partition_str)
{
const std::string service_name_ = service_name;
size_t pos;
pos = service_name_.find_last_of('/');
request_partition_str.clear();
response_partition_str.clear();
if (!avoid_ros_namespace_conventions) {
request_partition_str = ros_service_request_prefix;
response_partition_str = ros_service_response_prefix;
if (0 != service_name_.substr(0, pos).size() && service_name_[0] != '/') {
request_partition_str += '/';
response_partition_str += '/';
}
}
request_partition_str += service_name_.substr(0, pos);
response_partition_str += service_name_.substr(0, pos);
service_str = service_name_.substr(pos + 1);
return true;
}
} // namespace rosidl_typesupport_opensplice_cpp
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Device.h"
namespace medialibrary
{
const std::string policy::DeviceTable::Name = "Device";
const std::string policy::DeviceTable::PrimaryKeyColumn = "id_device";
int64_t Device::* const policy::DeviceTable::PrimaryKey = &Device::m_id;
Device::Device( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
{
row >> m_id
>> m_uuid
>> m_scheme
>> m_isRemovable
>> m_isPresent;
//FIXME: It's probably a bad idea to load "isPresent" for DB. This field should
//only be here for sqlite triggering purposes
}
Device::Device( MediaLibraryPtr ml, const std::string& uuid, const std::string& scheme, bool isRemovable )
: m_ml( ml )
, m_id( 0 )
, m_uuid( uuid )
, m_scheme( scheme )
, m_isRemovable( isRemovable )
// Assume we can't add an absent device
, m_isPresent( true )
{
}
int64_t Device::id() const
{
return m_id;
}
const std::string&Device::uuid() const
{
return m_uuid;
}
bool Device::isRemovable() const
{
return m_isRemovable;
}
bool Device::isPresent() const
{
return m_isPresent;
}
void Device::setPresent(bool value)
{
static const std::string req = "UPDATE " + policy::DeviceTable::Name +
" SET is_present = ? WHERE id_device = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, value, m_id ) == false )
return;
m_isPresent = value;
}
const std::string& Device::scheme() const
{
return m_scheme;
}
std::shared_ptr<Device> Device::create( MediaLibraryPtr ml, const std::string& uuid, const std::string& scheme, bool isRemovable )
{
static const std::string req = "INSERT INTO " + policy::DeviceTable::Name
+ "(uuid, scheme, is_removable, is_present) VALUES(?, ?, ?, ?)";
auto self = std::make_shared<Device>( ml, uuid, scheme, isRemovable );
if ( insert( ml, self, req, uuid, scheme, isRemovable, self->isPresent() ) == false )
return nullptr;
return self;
}
void Device::createTable( sqlite::Connection* connection )
{
const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::DeviceTable::Name + "("
"id_device INTEGER PRIMARY KEY AUTOINCREMENT,"
"uuid TEXT UNIQUE ON CONFLICT FAIL,"
"scheme TEXT,"
"is_removable BOOLEAN,"
"is_present BOOLEAN"
")";
sqlite::Tools::executeRequest( connection, req );
}
std::shared_ptr<Device> Device::fromUuid( MediaLibraryPtr ml, const std::string& uuid )
{
static const std::string req = "SELECT * FROM " + policy::DeviceTable::Name +
" WHERE uuid = ?";
return fetch( ml, req, uuid );
}
}
<commit_msg>Device: Ensure the status of a device presence actually changes<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Device.h"
namespace medialibrary
{
const std::string policy::DeviceTable::Name = "Device";
const std::string policy::DeviceTable::PrimaryKeyColumn = "id_device";
int64_t Device::* const policy::DeviceTable::PrimaryKey = &Device::m_id;
Device::Device( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
{
row >> m_id
>> m_uuid
>> m_scheme
>> m_isRemovable
>> m_isPresent;
}
Device::Device( MediaLibraryPtr ml, const std::string& uuid, const std::string& scheme, bool isRemovable )
: m_ml( ml )
, m_id( 0 )
, m_uuid( uuid )
, m_scheme( scheme )
, m_isRemovable( isRemovable )
// Assume we can't add an absent device
, m_isPresent( true )
{
}
int64_t Device::id() const
{
return m_id;
}
const std::string&Device::uuid() const
{
return m_uuid;
}
bool Device::isRemovable() const
{
return m_isRemovable;
}
bool Device::isPresent() const
{
return m_isPresent;
}
void Device::setPresent(bool value)
{
assert( m_isPresent != value );
static const std::string req = "UPDATE " + policy::DeviceTable::Name +
" SET is_present = ? WHERE id_device = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, value, m_id ) == false )
return;
m_isPresent = value;
}
const std::string& Device::scheme() const
{
return m_scheme;
}
std::shared_ptr<Device> Device::create( MediaLibraryPtr ml, const std::string& uuid, const std::string& scheme, bool isRemovable )
{
static const std::string req = "INSERT INTO " + policy::DeviceTable::Name
+ "(uuid, scheme, is_removable, is_present) VALUES(?, ?, ?, ?)";
auto self = std::make_shared<Device>( ml, uuid, scheme, isRemovable );
if ( insert( ml, self, req, uuid, scheme, isRemovable, self->isPresent() ) == false )
return nullptr;
return self;
}
void Device::createTable( sqlite::Connection* connection )
{
const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::DeviceTable::Name + "("
"id_device INTEGER PRIMARY KEY AUTOINCREMENT,"
"uuid TEXT UNIQUE ON CONFLICT FAIL,"
"scheme TEXT,"
"is_removable BOOLEAN,"
"is_present BOOLEAN"
")";
sqlite::Tools::executeRequest( connection, req );
}
std::shared_ptr<Device> Device::fromUuid( MediaLibraryPtr ml, const std::string& uuid )
{
static const std::string req = "SELECT * FROM " + policy::DeviceTable::Name +
" WHERE uuid = ?";
return fetch( ml, req, uuid );
}
}
<|endoftext|> |
<commit_before>#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include "config.h"
#endif
#define HAVE_DUNE_DETAILED_DISCRETIZATIONS 1
#include <iostream>
#include <sstream>
#include <vector>
#include <boost/filesystem.hpp>
#include <dune/common/exceptions.hh>
#include <dune/common/static_assert.hh>
#include <dune/common/timer.hh>
#include <dune/common/dynvector.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
#include <dune/grid/part/leaf.hh>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>
#include <dune/stuff/la/solver.hh>
#include <dune/stuff/common/color.hh>
#include <dune/detailed/discretizations/space/discontinuouslagrange/fem-localfunctions.hh>
#include <dune/detailed/discretizations/la/containerfactory/eigen.hh>
#include <dune/detailed/discretizations/localevaluation/elliptic.hh>
#include <dune/detailed/discretizations/localoperator/codim0.hh>
#include <dune/detailed/discretizations/localevaluation/ipdg-fluxes.hh>
#include <dune/detailed/discretizations/localoperator/codim1.hh>
#include <dune/detailed/discretizations/localevaluation/product.hh>
#include <dune/detailed/discretizations/localfunctional/codim0.hh>
#include <dune/detailed/discretizations/localfunctional/codim1.hh>
#include <dune/detailed/discretizations/assembler/local/codim0.hh>
#include <dune/detailed/discretizations/assembler/local/codim1.hh>
#include <dune/detailed/discretizations/assembler/system.hh>
#include <dune/detailed/discretizations/discretefunction/default.hh>
const std::string id = "elliptic.discontinuousgalerkin-swip";
#ifndef POLORDER
const int polOrder = 1;
#else
const int polOrder = POLORDER;
#endif
dune_static_assert((polOrder > 0), "ERROR: polOrder hast to be positive!");
using namespace Dune::Detailed::Discretizations;
/**
\brief Creates a parameter file if it does not exist.
Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
keys and values.
\param[in] filename
(Relative) path to the file.
**/
void ensureSettings(const std::string& filename)
{
// only write param file if there is none
if (!boost::filesystem::exists(filename)) {
std::ofstream file;
file.open(filename);
file << "[" << id << "]" << std::endl;
file << "filename = " << id << std::endl;
file << "grid = gridprovider.cube" << std::endl;
file << "boundaryinfo = boundaryinfo.normalbased" << std::endl;
file << "penaltyFactor = 10.0" << std::endl;
file << "[gridprovider.cube]" << std::endl;
file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
file << "numElements = [12; 12; 12]" << std::endl;
file << "[boundaryinfo.normalbased]" << std::endl;
file << "default = dirichlet" << std::endl;
file << "compare_tolerance = 1e-10" << std::endl;
file << "neumann = [0.0; 1.0]" << std::endl;
file << "[diffusion]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[force]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[dirichlet]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [0.1*x[0]; 0.0; 0.0]" << std::endl;
file << "[neumann]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [0.1; 0.0; 0.0]" << std::endl;
file << "[solver]" << std::endl;
file << "type = bicgstab.ilut" << std::endl;
file << "maxIter = 5000" << std::endl;
file << "precision = 1.0e-8" << std::endl;
file << "preconditioner.dropTol = 1e-4" << std::endl;
file << "preconditioner.fillFactor = 10" << std::endl;
file.close();
} // only write param file if there is none
} // void ensureSettings()
int main(int argc, char** argv)
{
try {
std::cout << Dune::Stuff::Common::colorString("WARNING:")
<< " there still is something wrong for nonzero dirichlet values!" << std::endl;
// mpi
Dune::Fem::MPIManager::initialize(argc, argv);
// parameter
const std::string paramFilename = id + ".settings";
ensureSettings(paramFilename);
Dune::Stuff::Common::ExtendedParameterTree settings(argc, argv, paramFilename);
settings.assertSub(id);
const double penaltyFactor = settings.get< double >(id + ".penaltyFactor");
assert(penaltyFactor > 0.0 && "It better be!");
// logger
Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
Dune::Stuff::Common::LOG_CONSOLE);
Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
Dune::Timer timer;
info << "setting up grid:" << std::endl;
typedef Dune::Stuff::GridProviderInterface<> GridProviderType;
const GridProviderType* gridProvider
= Dune::Stuff::GridProviders<>::create(settings.get(id + ".grid", "gridprovider.cube"),
settings);
typedef GridProviderType::GridType GridType;
const std::shared_ptr< const GridType > grid = gridProvider->grid();
typedef Dune::grid::Part::Leaf::Const< GridType > GridPartType;
typedef typename GridPartType::GridViewType GridViewType;
const GridPartType gridPart(*grid);
typedef typename Dune::Stuff::GridboundaryInterface< typename GridPartType::GridViewType > BoundaryInfoType;
const std::shared_ptr< const BoundaryInfoType > boundaryInfo(
Dune::Stuff::Gridboundaries< typename GridPartType::GridViewType >::create(
settings.get(id + ".boundaryinfo", "boundaryinfo.alldirichlet"),
settings));
info << " took " << timer.elapsed() << " sec, has " << grid->size(0) << " entities" << std::endl;
info << "visualizing grid... " << std::flush;
timer.reset();
gridProvider->visualize(settings.get(id + ".boundaryinfo", "boundaryinfo.alldirichlet"),
settings,
settings.get(id + ".filename", id) + ".grid");
info << " done (took " << timer.elapsed() << " sek)" << std::endl;
const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
const unsigned int DUNE_UNUSED(dimRange) = 1;
typedef typename GridType::ctype DomainFieldType;
typedef double RangeFieldType;
typedef Dune::Stuff::FunctionExpression< DomainFieldType, dimDomain, RangeFieldType, dimRange >
ExpressionFunctionType;
const std::shared_ptr< const ExpressionFunctionType >
diffusion(ExpressionFunctionType::create(settings.sub("diffusion")));
const std::shared_ptr< const ExpressionFunctionType >
force(ExpressionFunctionType::create(settings.sub("force")));
const std::shared_ptr< const ExpressionFunctionType >
dirichlet(ExpressionFunctionType::create(settings.sub("dirichlet")));
const std::shared_ptr< const ExpressionFunctionType >
neumann(ExpressionFunctionType::create(settings.sub("neumann")));
info << "initializing space... " << std::flush;
timer.reset();
typedef DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper< GridPartType, polOrder, RangeFieldType, dimRange >
SpaceType;
const SpaceType space(gridPart);
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// left hand side
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< ExpressionFunctionType > > EllipticOperatorType;
const EllipticOperatorType ellipticOperator(*diffusion);
typedef LocalOperator::Codim1CouplingIntegral< LocalEvaluation::IPDGFluxes::CouplingPrimal< ExpressionFunctionType > >
CouplingOperatorType;
const CouplingOperatorType ipdgCouplingOperator(*diffusion, penaltyFactor);
typedef LocalOperator::Codim1BoundaryIntegral< LocalEvaluation::IPDGFluxes::BoundaryDirichletLHS< ExpressionFunctionType > >
DirichletOperatorType;
const DirichletOperatorType ipdgDirichletOperator(*diffusion, penaltyFactor);
// right hand side
typedef LocalFunctional::Codim0Integral< LocalEvaluation::Product< ExpressionFunctionType > > ForceFunctionalType;
const ForceFunctionalType forceFunctional(*force);
typedef LocalFunctional::Codim1Integral< LocalEvaluation::IPDGFluxes::BoundaryDirichletRHS< ExpressionFunctionType, ExpressionFunctionType > >
DirichletFunctionalType;
const DirichletFunctionalType dirichletFunctional(*diffusion, *dirichlet, penaltyFactor);
typedef LocalFunctional::Codim1Integral< LocalEvaluation::Product< ExpressionFunctionType > > NeumannFunctionalType;
const NeumannFunctionalType neumannFunctional(*neumann);
info << "initializing matrix (of size " << space.mapper().size() << "x" << space.mapper().size()
<< ") and vectors... " << std::flush;
// timer.reset();
typedef ContainerFactoryEigen< RangeFieldType > ContainerFactory;
typedef ContainerFactory::RowMajorSparseMatrixType MatrixType;
typedef ContainerFactory::DenseVectorType VectorType;
std::shared_ptr< MatrixType > systemMatrix(ContainerFactory::createRowMajorSparseMatrix(space, space));
std::shared_ptr< VectorType > rhsVector(ContainerFactory::createDenseVector(space));
std::shared_ptr< VectorType > solutionVector(ContainerFactory::createDenseVector(space));
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
info << "assembing system... " << std::flush;
timer.reset();
// * local matrix assembler
typedef LocalAssembler::Codim0Matrix< EllipticOperatorType > LocalVolumeMatrixAssemblerType;
const LocalVolumeMatrixAssemblerType diffusionMatrixAssembler(ellipticOperator);
typedef LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType > LocalCouplingMatrixAssemblerType;
const LocalCouplingMatrixAssemblerType couplingMatrixAssembler(ipdgCouplingOperator);
typedef LocalAssembler::Codim1BoundaryMatrix< DirichletOperatorType > LocalDirichletMatrixAssemblerType;
const LocalDirichletMatrixAssemblerType dirichletMatrixAssembler(ipdgDirichletOperator);
// * local vector assemblers
typedef LocalAssembler::Codim0Vector< ForceFunctionalType > LocalForceVectorAssemblerType;
const LocalForceVectorAssemblerType forceVectorAssembler(forceFunctional);
typedef LocalAssembler::Codim1Vector< DirichletFunctionalType > LocalDirichletVectorAssembler;
const LocalDirichletVectorAssembler dirichletVectorAssembler(dirichletFunctional);
typedef LocalAssembler::Codim1Vector< NeumannFunctionalType > LocalNeumannVectorAssembler;
const LocalNeumannVectorAssembler neumannVectorAssembler(neumannFunctional);
// * system assembler
typedef SystemAssembler< SpaceType, SpaceType > SystemAssemblerType;
SystemAssemblerType systemAssembler(space);
systemAssembler.addLocalAssembler(diffusionMatrixAssembler, *systemMatrix);
systemAssembler.addLocalAssembler(couplingMatrixAssembler,
SystemAssemblerType::AssembleOnInnerPrimally(),
*systemMatrix);
systemAssembler.addLocalAssembler(dirichletMatrixAssembler,
SystemAssemblerType::AssembleOnDirichlet(*boundaryInfo),
*systemMatrix);
systemAssembler.addLocalAssembler(forceVectorAssembler, *rhsVector);
systemAssembler.addLocalAssembler(dirichletVectorAssembler,
SystemAssemblerType::AssembleOnDirichlet(*boundaryInfo),
*rhsVector);
systemAssembler.addLocalAssembler(neumannVectorAssembler,
SystemAssemblerType::AssembleOnNeumann(*boundaryInfo),
*rhsVector);
systemAssembler.assemble();
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
info << "solving linear system (of size " << systemMatrix->rows() << "x" << systemMatrix->cols() << ")" << std::endl;
const Dune::Stuff::Common::ExtendedParameterTree linearSolverSettings = settings.sub("solver");
const std::string solverType = linearSolverSettings.get("type", "bicgstab.ilut");
info << " using '" << solverType << "'... " << std::flush;
timer.reset();
typedef typename Dune::Stuff::LA::SolverInterface< MatrixType, VectorType > SolverType;
std::shared_ptr< SolverType > solver(Dune::Stuff::LA::createSolver< MatrixType, VectorType >(solverType));
const size_t failure = solver->apply(*systemMatrix,
*rhsVector,
*solutionVector,
linearSolverSettings);
if (failure)
DUNE_THROW(Dune::MathError,
"\nERROR: linear solver '" << solverType << "' reported a problem!");
if (solutionVector->size() != space.mapper().size())
DUNE_THROW(Dune::MathError,
"\nERROR: linear solver '" << solverType << "' produced a solution of wrong size (is "
<< solutionVector->size() << ", should be " << space.mapper().size() << ")!");
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
const std::string solutionFilename = settings.get(id + ".filename", id) + ".solution";
const std::string solutionName = id + ".solution";
info << "writing solution to '" << solutionFilename;
if (dimDomain == 1)
info << ".vtp";
else
info << ".vtu";
info << "'... " << std::flush;
timer.reset();
typedef DiscreteFunctionDefaultConst< SpaceType, VectorType > DiscreteFunctionType;
const auto solution = std::make_shared< const DiscreteFunctionType >(space, solutionVector, solutionName);
typedef Dune::VTKWriter< GridViewType > VTKWriterType;
VTKWriterType vtkWriter(gridPart.gridView());
vtkWriter.addVertexData(solution);
vtkWriter.write(solutionFilename);
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// done
return 0;
} catch (Dune::Exception& e) {
std::cerr << "Dune reported error: " << e.what() << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
} // try
} // main
<commit_msg>[examples.elliptic.discontinuousgalerkin-swip] use swipdg fluxes<commit_after>#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include "config.h"
#endif
#define HAVE_DUNE_DETAILED_DISCRETIZATIONS 1
#include <iostream>
#include <sstream>
#include <vector>
#include <boost/filesystem.hpp>
#include <dune/common/exceptions.hh>
#include <dune/common/static_assert.hh>
#include <dune/common/timer.hh>
#include <dune/common/dynvector.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
#include <dune/grid/part/leaf.hh>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>
#include <dune/stuff/la/solver.hh>
#include <dune/stuff/common/color.hh>
#include <dune/detailed/discretizations/space/discontinuouslagrange/fem-localfunctions.hh>
#include <dune/detailed/discretizations/la/containerfactory/eigen.hh>
#include <dune/detailed/discretizations/localevaluation/elliptic.hh>
#include <dune/detailed/discretizations/localoperator/codim0.hh>
#include <dune/detailed/discretizations/localevaluation/swipdg-fluxes.hh>
#include <dune/detailed/discretizations/localoperator/codim1.hh>
#include <dune/detailed/discretizations/localevaluation/product.hh>
#include <dune/detailed/discretizations/localfunctional/codim0.hh>
#include <dune/detailed/discretizations/localfunctional/codim1.hh>
#include <dune/detailed/discretizations/assembler/local/codim0.hh>
#include <dune/detailed/discretizations/assembler/local/codim1.hh>
#include <dune/detailed/discretizations/assembler/system.hh>
#include <dune/detailed/discretizations/discretefunction/default.hh>
const std::string id = "elliptic.discontinuousgalerkin-swip";
#ifndef POLORDER
const int polOrder = 1;
#else
const int polOrder = POLORDER;
#endif
dune_static_assert((polOrder > 0), "ERROR: polOrder hast to be positive!");
using namespace Dune::Detailed::Discretizations;
/**
\brief Creates a parameter file if it does not exist.
Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
keys and values.
\param[in] filename
(Relative) path to the file.
**/
void ensureSettings(const std::string& filename)
{
// only write param file if there is none
if (!boost::filesystem::exists(filename)) {
std::ofstream file;
file.open(filename);
file << "[" << id << "]" << std::endl;
file << "filename = " << id << std::endl;
file << "grid = gridprovider.cube" << std::endl;
file << "boundaryinfo = boundaryinfo.normalbased" << std::endl;
file << "penaltyFactor = 10.0" << std::endl;
file << "[gridprovider.cube]" << std::endl;
file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
file << "numElements = [12; 12; 12]" << std::endl;
file << "[boundaryinfo.normalbased]" << std::endl;
file << "default = dirichlet" << std::endl;
file << "compare_tolerance = 1e-10" << std::endl;
file << "neumann = [0.0; 1.0]" << std::endl;
file << "[diffusion]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[force]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[dirichlet]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [0.1*x[0]; 0.0; 0.0]" << std::endl;
file << "[neumann]" << std::endl;
file << "order = 0" << std::endl;
file << "variable = x" << std::endl;
file << "expression = [0.1; 0.0; 0.0]" << std::endl;
file << "[solver]" << std::endl;
file << "type = bicgstab.ilut" << std::endl;
file << "maxIter = 5000" << std::endl;
file << "precision = 1.0e-8" << std::endl;
file << "preconditioner.dropTol = 1e-4" << std::endl;
file << "preconditioner.fillFactor = 10" << std::endl;
file.close();
} // only write param file if there is none
} // void ensureSettings()
int main(int argc, char** argv)
{
try {
std::cout << Dune::Stuff::Common::colorString("WARNING:")
<< " there still is something wrong for nonzero dirichlet values!" << std::endl;
// mpi
Dune::Fem::MPIManager::initialize(argc, argv);
// parameter
const std::string paramFilename = id + ".settings";
ensureSettings(paramFilename);
Dune::Stuff::Common::ExtendedParameterTree settings(argc, argv, paramFilename);
settings.assertSub(id);
const double penaltyFactor = settings.get< double >(id + ".penaltyFactor");
assert(penaltyFactor > 0.0 && "It better be!");
// logger
Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
Dune::Stuff::Common::LOG_CONSOLE);
Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
Dune::Timer timer;
info << "setting up grid:" << std::endl;
typedef Dune::Stuff::GridProviderInterface<> GridProviderType;
const GridProviderType* gridProvider
= Dune::Stuff::GridProviders<>::create(settings.get(id + ".grid", "gridprovider.cube"),
settings);
typedef GridProviderType::GridType GridType;
const std::shared_ptr< const GridType > grid = gridProvider->grid();
typedef Dune::grid::Part::Leaf::Const< GridType > GridPartType;
typedef typename GridPartType::GridViewType GridViewType;
const GridPartType gridPart(*grid);
typedef typename Dune::Stuff::GridboundaryInterface< typename GridPartType::GridViewType > BoundaryInfoType;
const std::shared_ptr< const BoundaryInfoType > boundaryInfo(
Dune::Stuff::Gridboundaries< typename GridPartType::GridViewType >::create(
settings.get(id + ".boundaryinfo", "boundaryinfo.alldirichlet"),
settings));
info << " took " << timer.elapsed() << " sec, has " << grid->size(0) << " entities" << std::endl;
info << "visualizing grid... " << std::flush;
timer.reset();
gridProvider->visualize(settings.get(id + ".boundaryinfo", "boundaryinfo.alldirichlet"),
settings,
settings.get(id + ".filename", id) + ".grid");
info << " done (took " << timer.elapsed() << " sek)" << std::endl;
const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
const unsigned int DUNE_UNUSED(dimRange) = 1;
typedef typename GridType::ctype DomainFieldType;
typedef double RangeFieldType;
typedef Dune::Stuff::FunctionExpression< DomainFieldType, dimDomain, RangeFieldType, dimRange >
ExpressionFunctionType;
const std::shared_ptr< const ExpressionFunctionType >
diffusion(ExpressionFunctionType::create(settings.sub("diffusion")));
const std::shared_ptr< const ExpressionFunctionType >
force(ExpressionFunctionType::create(settings.sub("force")));
const std::shared_ptr< const ExpressionFunctionType >
dirichlet(ExpressionFunctionType::create(settings.sub("dirichlet")));
const std::shared_ptr< const ExpressionFunctionType >
neumann(ExpressionFunctionType::create(settings.sub("neumann")));
info << "initializing space... " << std::flush;
timer.reset();
typedef DiscontinuousLagrangeSpace::FemLocalfunctionsWrapper< GridPartType, polOrder, RangeFieldType, dimRange >
SpaceType;
const SpaceType space(gridPart);
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// left hand side
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< ExpressionFunctionType > > EllipticOperatorType;
const EllipticOperatorType ellipticOperator(*diffusion);
typedef LocalOperator::Codim1CouplingIntegral< LocalEvaluation::SWIPDGFluxes::CouplingPrimal< ExpressionFunctionType > >
CouplingOperatorType;
const CouplingOperatorType ipdgCouplingOperator(*diffusion, penaltyFactor);
typedef LocalOperator::Codim1BoundaryIntegral< LocalEvaluation::SWIPDGFluxes::BoundaryDirichletLHS< ExpressionFunctionType > >
DirichletOperatorType;
const DirichletOperatorType ipdgDirichletOperator(*diffusion, penaltyFactor);
// right hand side
typedef LocalFunctional::Codim0Integral< LocalEvaluation::Product< ExpressionFunctionType > > ForceFunctionalType;
const ForceFunctionalType forceFunctional(*force);
typedef LocalFunctional::Codim1Integral< LocalEvaluation::SWIPDGFluxes::BoundaryDirichletRHS< ExpressionFunctionType, ExpressionFunctionType > >
DirichletFunctionalType;
const DirichletFunctionalType dirichletFunctional(*diffusion, *dirichlet, penaltyFactor);
typedef LocalFunctional::Codim1Integral< LocalEvaluation::Product< ExpressionFunctionType > > NeumannFunctionalType;
const NeumannFunctionalType neumannFunctional(*neumann);
info << "initializing matrix (of size " << space.mapper().size() << "x" << space.mapper().size()
<< ") and vectors... " << std::flush;
// timer.reset();
typedef ContainerFactoryEigen< RangeFieldType > ContainerFactory;
typedef ContainerFactory::RowMajorSparseMatrixType MatrixType;
typedef ContainerFactory::DenseVectorType VectorType;
std::shared_ptr< MatrixType > systemMatrix(ContainerFactory::createRowMajorSparseMatrix(space, space));
std::shared_ptr< VectorType > rhsVector(ContainerFactory::createDenseVector(space));
std::shared_ptr< VectorType > solutionVector(ContainerFactory::createDenseVector(space));
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
info << "assembing system... " << std::flush;
timer.reset();
// * local matrix assembler
typedef LocalAssembler::Codim0Matrix< EllipticOperatorType > LocalVolumeMatrixAssemblerType;
const LocalVolumeMatrixAssemblerType diffusionMatrixAssembler(ellipticOperator);
typedef LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType > LocalCouplingMatrixAssemblerType;
const LocalCouplingMatrixAssemblerType couplingMatrixAssembler(ipdgCouplingOperator);
typedef LocalAssembler::Codim1BoundaryMatrix< DirichletOperatorType > LocalDirichletMatrixAssemblerType;
const LocalDirichletMatrixAssemblerType dirichletMatrixAssembler(ipdgDirichletOperator);
// * local vector assemblers
typedef LocalAssembler::Codim0Vector< ForceFunctionalType > LocalForceVectorAssemblerType;
const LocalForceVectorAssemblerType forceVectorAssembler(forceFunctional);
typedef LocalAssembler::Codim1Vector< DirichletFunctionalType > LocalDirichletVectorAssembler;
const LocalDirichletVectorAssembler dirichletVectorAssembler(dirichletFunctional);
typedef LocalAssembler::Codim1Vector< NeumannFunctionalType > LocalNeumannVectorAssembler;
const LocalNeumannVectorAssembler neumannVectorAssembler(neumannFunctional);
// * system assembler
typedef SystemAssembler< SpaceType, SpaceType > SystemAssemblerType;
SystemAssemblerType systemAssembler(space);
systemAssembler.addLocalAssembler(diffusionMatrixAssembler, *systemMatrix);
systemAssembler.addLocalAssembler(couplingMatrixAssembler,
SystemAssemblerType::AssembleOnInnerPrimally(),
*systemMatrix);
systemAssembler.addLocalAssembler(dirichletMatrixAssembler,
SystemAssemblerType::AssembleOnDirichlet(*boundaryInfo),
*systemMatrix);
systemAssembler.addLocalAssembler(forceVectorAssembler, *rhsVector);
systemAssembler.addLocalAssembler(dirichletVectorAssembler,
SystemAssemblerType::AssembleOnDirichlet(*boundaryInfo),
*rhsVector);
systemAssembler.addLocalAssembler(neumannVectorAssembler,
SystemAssemblerType::AssembleOnNeumann(*boundaryInfo),
*rhsVector);
systemAssembler.assemble();
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
info << "solving linear system (of size " << systemMatrix->rows() << "x" << systemMatrix->cols() << ")" << std::endl;
const Dune::Stuff::Common::ExtendedParameterTree linearSolverSettings = settings.sub("solver");
const std::string solverType = linearSolverSettings.get("type", "bicgstab.ilut");
info << " using '" << solverType << "'... " << std::flush;
timer.reset();
typedef typename Dune::Stuff::LA::SolverInterface< MatrixType, VectorType > SolverType;
std::shared_ptr< SolverType > solver(Dune::Stuff::LA::createSolver< MatrixType, VectorType >(solverType));
const size_t failure = solver->apply(*systemMatrix,
*rhsVector,
*solutionVector,
linearSolverSettings);
if (failure)
DUNE_THROW(Dune::MathError,
"\nERROR: linear solver '" << solverType << "' reported a problem!");
if (solutionVector->size() != space.mapper().size())
DUNE_THROW(Dune::MathError,
"\nERROR: linear solver '" << solverType << "' produced a solution of wrong size (is "
<< solutionVector->size() << ", should be " << space.mapper().size() << ")!");
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
const std::string solutionFilename = settings.get(id + ".filename", id) + ".solution";
const std::string solutionName = id + ".solution";
info << "writing solution to '" << solutionFilename;
if (dimDomain == 1)
info << ".vtp";
else
info << ".vtu";
info << "'... " << std::flush;
timer.reset();
typedef DiscreteFunctionDefaultConst< SpaceType, VectorType > DiscreteFunctionType;
const auto solution = std::make_shared< const DiscreteFunctionType >(space, solutionVector, solutionName);
typedef Dune::VTKWriter< GridViewType > VTKWriterType;
VTKWriterType vtkWriter(gridPart.gridView());
vtkWriter.addVertexData(solution);
vtkWriter.write(solutionFilename);
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// done
return 0;
} catch (Dune::Exception& e) {
std::cerr << "Dune reported error: " << e.what() << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
} // try
} // main
<|endoftext|> |
<commit_before>#pragma once
#include <functional>
#include "debug.hpp"
#include "types.hpp"
namespace utki{
#if __cplusplus >= 201703L
template <typename C> class linq_collection_aggregator{
typename std::conditional<std::is_rvalue_reference<C>::value,
typename std::remove_reference<C>::type,
C
>::type collection;
public:
linq_collection_aggregator(C collection) :
collection(std::move(collection))
{}
decltype(collection) get(){
return std::move(this->collection);
}
template <typename F> auto select(F func){
typedef decltype(std::move(*this->collection.begin())) func_arg_type;
static constexpr bool func_one_arg = !std::is_same<void, typename type_or_void<std::invoke_result<F, func_arg_type>>::type>::value;
static_assert(
func_one_arg || !std::is_same<void, typename type_or_void<std::invoke_result<F, func_arg_type, size_t>>::type>::value,
"passed in function must have one argument or two arguments with the second argument of type size_t"
);
typedef typename std::conditional<
func_one_arg,
typename type_or_void<std::invoke_result<F, func_arg_type>>::type,
typename type_or_void<std::invoke_result<F, func_arg_type, size_t>>::type
>::type func_return_type;
std::vector<func_return_type> ret;
ret.reserve(this->collection.size());
if constexpr (func_one_arg){
for(auto&& e : this->collection){
ret.push_back(func(std::move(e)));
}
}else{ // two arguments
size_t i = 0;
for(auto&& e : this->collection){
ret.push_back(func(std::move(e), i));
++i;
}
}
return linq_collection_aggregator<decltype(ret)&&>(std::move(ret));
}
};
template <typename C> linq_collection_aggregator<const C&> linq(const C& collection){
return linq_collection_aggregator<const C&>(collection);
}
template <typename C> linq_collection_aggregator<const C&> linq(C& collection){
return linq_collection_aggregator<const C&>(collection);
}
template <typename C> linq_collection_aggregator<C&&> linq(C&& collection){
return linq_collection_aggregator<C&&>(std::move(collection));
}
#endif
}
<commit_msg>typedef<commit_after>#pragma once
#include <functional>
#include "debug.hpp"
#include "types.hpp"
namespace utki{
#if __cplusplus >= 201703L
template <typename C> class linq_collection_aggregator{
typename std::conditional<std::is_rvalue_reference<C>::value,
typename std::remove_reference<C>::type,
C
>::type collection;
typedef typename std::add_rvalue_reference<
typename std::remove_reference<decltype(collection)>::type::value_type
>::type func_arg_type;
public:
linq_collection_aggregator(C collection) :
collection(std::move(collection))
{}
decltype(collection) get(){
return std::move(this->collection);
}
template <typename F> auto select(F func){
static constexpr bool func_one_arg = !std::is_same<void, typename type_or_void<std::invoke_result<F, func_arg_type>>::type>::value;
static_assert(
func_one_arg || !std::is_same<void, typename type_or_void<std::invoke_result<F, func_arg_type, size_t>>::type>::value,
"passed in function must have one argument or two arguments with the second argument of type size_t"
);
typedef typename std::conditional<
func_one_arg,
typename type_or_void<std::invoke_result<F, func_arg_type>>::type,
typename type_or_void<std::invoke_result<F, func_arg_type, size_t>>::type
>::type func_return_type;
std::vector<func_return_type> ret;
ret.reserve(this->collection.size());
if constexpr (func_one_arg){
for(auto&& e : this->collection){
ret.push_back(func(std::move(e)));
}
}else{ // two arguments
size_t i = 0;
for(auto&& e : this->collection){
ret.push_back(func(std::move(e), i));
++i;
}
}
return linq_collection_aggregator<decltype(ret)&&>(std::move(ret));
}
};
template <typename C> linq_collection_aggregator<const C&> linq(const C& collection){
return linq_collection_aggregator<const C&>(collection);
}
template <typename C> linq_collection_aggregator<const C&> linq(C& collection){
return linq_collection_aggregator<const C&>(collection);
}
template <typename C> linq_collection_aggregator<C&&> linq(C&& collection){
return linq_collection_aggregator<C&&>(std::move(collection));
}
#endif
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
TORRENT_ASSERT(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return m_str && e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
#ifndef BOOST_NO_EXCEPTIONS
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
#endif
entry::entry()
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(data_type t)
: m_type(undefined_t)
{
construct(t);
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(const entry& e)
: m_type(undefined_t)
{
copy(e);
#ifndef NDEBUG
m_type_queried = e.m_type_queried;
#endif
}
entry::entry(dictionary_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(string_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) string_type(v);
m_type = string_t;
}
entry::entry(list_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) list_type(v);
m_type = list_t;
}
entry::entry(integer_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(dictionary_type const& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(string_type const& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(list_type const& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(integer_type const& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
TORRENT_ASSERT(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
switch(t)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
TORRENT_ASSERT(t == undefined_t);
}
m_type = t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::copy(entry const& e)
{
switch (e.type())
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
TORRENT_ASSERT(e.type() == undefined_t);
}
m_type = e.type();
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
TORRENT_ASSERT(m_type == undefined_t);
break;
}
m_type = undefined_t;
#ifndef NDEBUG
m_type_queried = false;
#endif
}
void entry::swap(entry& e)
{
// not implemented
TORRENT_ASSERT(false);
}
void entry::print(std::ostream& os, int indent) const
{
TORRENT_ASSERT(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << std::setfill('0') << std::setw(2)
<< static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t
&& i->second.type() != entry::int_t)
os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<commit_msg>fixed include issue in entry.cpp<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <iostream>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
TORRENT_ASSERT(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return m_str && e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
#ifndef BOOST_NO_EXCEPTIONS
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
#endif
entry::entry()
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(data_type t)
: m_type(undefined_t)
{
construct(t);
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(const entry& e)
: m_type(undefined_t)
{
copy(e);
#ifndef NDEBUG
m_type_queried = e.m_type_queried;
#endif
}
entry::entry(dictionary_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(string_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) string_type(v);
m_type = string_t;
}
entry::entry(list_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) list_type(v);
m_type = list_t;
}
entry::entry(integer_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(dictionary_type const& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(string_type const& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(list_type const& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(integer_type const& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
TORRENT_ASSERT(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
switch(t)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
TORRENT_ASSERT(t == undefined_t);
}
m_type = t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::copy(entry const& e)
{
switch (e.type())
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
TORRENT_ASSERT(e.type() == undefined_t);
}
m_type = e.type();
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
TORRENT_ASSERT(m_type == undefined_t);
break;
}
m_type = undefined_t;
#ifndef NDEBUG
m_type_queried = false;
#endif
}
void entry::swap(entry& e)
{
// not implemented
TORRENT_ASSERT(false);
}
void entry::print(std::ostream& os, int indent) const
{
TORRENT_ASSERT(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << std::setfill('0') << std::setw(2)
<< static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t
&& i->second.type() != entry::int_t)
os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: asynclink.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 20:53:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <asynclink.hxx>
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//--------------------------------------------------------------------
namespace svtools {
void AsynchronLink::CreateMutex()
{
if( !_pMutex ) _pMutex = new vos::OMutex;
}
void AsynchronLink::Call( void* pObj, BOOL
#ifdef DBG_UTIL
bAllowDoubles
#endif
, BOOL bUseTimer )
{
#ifdef DBG_UTIL
if ( bUseTimer || !_bInCall )
DBG_WARNING( "Recursives Call. Eher ueber Timer. TLX Fragen" );
#endif
if( _aLink.IsSet() )
{
_pArg = pObj;
DBG_ASSERT( bAllowDoubles ||
( !_nEventId && ( !_pTimer || !_pTimer->IsActive() ) ),
"Schon ein Call unterwegs" );
if( _nEventId )
{
if( _pMutex ) _pMutex->acquire();
Application::RemoveUserEvent( _nEventId );
if( _pMutex ) _pMutex->release();
}
if( _pTimer )_pTimer->Stop();
if( bUseTimer )
{
if( !_pTimer )
{
_pTimer = new Timer;
_pTimer->SetTimeout( 0 );
_pTimer->SetTimeoutHdl( STATIC_LINK(
this, AsynchronLink, HandleCall) );
}
_pTimer->Start();
}
else
{
if( _pMutex ) _pMutex->acquire();
Application::PostUserEvent( _nEventId, STATIC_LINK( this, AsynchronLink, HandleCall), 0 );
if( _pMutex ) _pMutex->release();
}
}
}
AsynchronLink::~AsynchronLink()
{
if( _nEventId )
{
Application::RemoveUserEvent( _nEventId );
}
delete _pTimer;
if( _pDeleted ) *_pDeleted = TRUE;
delete _pMutex;
}
IMPL_STATIC_LINK( AsynchronLink, HandleCall, void*, EMPTYARG )
{
if( pThis->_pMutex ) pThis->_pMutex->acquire();
pThis->_nEventId = 0;
if( pThis->_pMutex ) pThis->_pMutex->release();
pThis->Call_Impl( pThis->_pArg );
return 0;
}
void AsynchronLink::ForcePendingCall()
{
ClearPendingCall();
Call_Impl( _pArg );
}
void AsynchronLink::ClearPendingCall()
{
if( _pMutex ) _pMutex->acquire();
if( _nEventId )
{
Application::RemoveUserEvent( _nEventId );
_nEventId = 0;
}
if( _pMutex ) _pMutex->release();
if( _pTimer ) _pTimer->Stop();
}
void AsynchronLink::Call_Impl( void* pArg )
{
_bInCall = TRUE;
BOOL bDeleted = FALSE;
_pDeleted = &bDeleted;
_aLink.Call( pArg );
if( !bDeleted )
{
_bInCall = FALSE;
_pDeleted = 0;
}
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.92); FILE MERGED 2006/09/01 17:42:55 kaib 1.4.92.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: asynclink.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 14:36:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <asynclink.hxx>
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//--------------------------------------------------------------------
namespace svtools {
void AsynchronLink::CreateMutex()
{
if( !_pMutex ) _pMutex = new vos::OMutex;
}
void AsynchronLink::Call( void* pObj, BOOL
#ifdef DBG_UTIL
bAllowDoubles
#endif
, BOOL bUseTimer )
{
#ifdef DBG_UTIL
if ( bUseTimer || !_bInCall )
DBG_WARNING( "Recursives Call. Eher ueber Timer. TLX Fragen" );
#endif
if( _aLink.IsSet() )
{
_pArg = pObj;
DBG_ASSERT( bAllowDoubles ||
( !_nEventId && ( !_pTimer || !_pTimer->IsActive() ) ),
"Schon ein Call unterwegs" );
if( _nEventId )
{
if( _pMutex ) _pMutex->acquire();
Application::RemoveUserEvent( _nEventId );
if( _pMutex ) _pMutex->release();
}
if( _pTimer )_pTimer->Stop();
if( bUseTimer )
{
if( !_pTimer )
{
_pTimer = new Timer;
_pTimer->SetTimeout( 0 );
_pTimer->SetTimeoutHdl( STATIC_LINK(
this, AsynchronLink, HandleCall) );
}
_pTimer->Start();
}
else
{
if( _pMutex ) _pMutex->acquire();
Application::PostUserEvent( _nEventId, STATIC_LINK( this, AsynchronLink, HandleCall), 0 );
if( _pMutex ) _pMutex->release();
}
}
}
AsynchronLink::~AsynchronLink()
{
if( _nEventId )
{
Application::RemoveUserEvent( _nEventId );
}
delete _pTimer;
if( _pDeleted ) *_pDeleted = TRUE;
delete _pMutex;
}
IMPL_STATIC_LINK( AsynchronLink, HandleCall, void*, EMPTYARG )
{
if( pThis->_pMutex ) pThis->_pMutex->acquire();
pThis->_nEventId = 0;
if( pThis->_pMutex ) pThis->_pMutex->release();
pThis->Call_Impl( pThis->_pArg );
return 0;
}
void AsynchronLink::ForcePendingCall()
{
ClearPendingCall();
Call_Impl( _pArg );
}
void AsynchronLink::ClearPendingCall()
{
if( _pMutex ) _pMutex->acquire();
if( _nEventId )
{
Application::RemoveUserEvent( _nEventId );
_nEventId = 0;
}
if( _pMutex ) _pMutex->release();
if( _pTimer ) _pTimer->Stop();
}
void AsynchronLink::Call_Impl( void* pArg )
{
_bInCall = TRUE;
BOOL bDeleted = FALSE;
_pDeleted = &bDeleted;
_aLink.Call( pArg );
if( !bDeleted )
{
_bInCall = FALSE;
_pDeleted = 0;
}
}
}
<|endoftext|> |
<commit_before>/*
* validator.cpp
* cpds
*
* Copyright (c) 2016 Hannes Friederich.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "cpds/validator.hpp"
#include "cpds/node.hpp"
#include "cpds/exception.hpp"
#include <iostream>
namespace cpds {
// enforce local linkage
namespace {
// accepts nodes that match the type
void vType(const Node& node,
const Validator& validator)
{
if (node.type() != validator.type())
{
throw TypeException(node);
}
}
// accepts all maps
bool vAllMaps(const Node& /*node*/)
{
return true;
}
// integer range validator
void vIntRange(const Node& node,
const Validator& validator)
{
IntRange range = validator.intRange();
Int val = node.intValue();
if (val < range.first || val > range.second)
{
throw IntRangeException(range.first, range.second, val, node);
}
}
// floating point range validator
void vFloatRange(const Node& node,
const Validator& validator)
{
FloatRange range = validator.floatRange();
Float val = node.floatValue();
if (val < range.first || val > range.second)
{
throw FloatRangeException(range.first, range.second, val, node);
}
}
// sequence validator
void vSequence(const Node& node,
const Validator& validator)
{
const ValidatorVector& validators = validator.seqValidators();
if (validators.empty())
{
return; // nothing to validate against
}
for (const Node& child : node.sequence())
{
// any of the validators must succeed
bool success = false;
for (const Validator& vld : validators)
{
try
{
vld.validate(child);
success = true;
break;
}
catch (...)
{
}
}
if (!success)
{
throw ValidationException("sequence child failed to validate", child);
}
}
}
// map validator
void vMap(const Node& node,
const Validator& validator)
{
const MapGroupVector& groups = validator.mapGroups();
if (groups.empty())
{
return; // nothing to validate against
}
bool enabled = false; // at least one group must be enabled
for (const MapGroup& group : groups)
{
if (group.isEnabled(node))
{
group.validate(node);
enabled = true;
}
}
if (enabled == false)
{
throw ValidationException("map does not match any validation group", node);
}
}
} // unnamed namespace
//
// Validator implementation
//
Validator::Validator(NodeType type, ValidationFcn validation_fcn)
: type_(type)
, fcn_(validation_fcn)
{
aux_data_.int_range_ = nullptr;
}
Validator::Validator(IntRange int_range)
: type_(NodeType::Integer)
, fcn_(vIntRange)
{
aux_data_.int_range_ = new IntRange(int_range);
}
Validator::Validator(FloatRange float_range)
: type_(NodeType::FloatingPoint)
, fcn_(vFloatRange)
{
aux_data_.float_range_ = new FloatRange(float_range);
}
Validator::Validator(ValidatorVector seq_validators)
: type_(NodeType::Sequence)
, fcn_(vSequence)
{
aux_data_.seq_validators_ = new ValidatorVector(std::move(seq_validators));
}
Validator::Validator(MapGroupVector map_groups)
: type_(NodeType::Map)
, fcn_(vMap)
{
aux_data_.map_groups_ = new MapGroupVector(std::move(map_groups));
}
Validator::Validator(const Validator& other)
: type_(other.type_)
, fcn_(other.fcn_)
, aux_data_()
{
switch (type_)
{
case NodeType::Integer:
if (other.aux_data_.int_range_ != nullptr)
{
aux_data_.int_range_ = new IntRange(*other.aux_data_.int_range_);
}
break;
case NodeType::FloatingPoint:
if (other.aux_data_.float_range_ != nullptr)
{
aux_data_.float_range_ = new FloatRange(*other.aux_data_.float_range_);
}
break;
case NodeType::Sequence:
aux_data_.seq_validators_ =
new ValidatorVector(*other.aux_data_.seq_validators_);
break;
case NodeType::Map:
aux_data_.map_groups_ =
new MapGroupVector(*other.aux_data_.map_groups_);
break;
default:
break;
}
}
Validator::Validator(Validator&& other) noexcept
: type_(other.type_)
, fcn_(other.fcn_)
, aux_data_(other.aux_data_)
{
other.type_ = NodeType::Null;
other.aux_data_.int_range_ = nullptr;
}
Validator& Validator::operator=(Validator other) noexcept
{
swap(other);
return *this;
}
Validator::~Validator()
{
switch (type_)
{
case NodeType::Integer:
delete aux_data_.int_range_;
break;
case NodeType::FloatingPoint:
delete aux_data_.float_range_;
break;
case NodeType::Sequence:
delete aux_data_.seq_validators_;
break;
case NodeType::Map:
delete aux_data_.map_groups_;
break;
default:
break;
}
}
void Validator::validate(const Node& node) const
{
fcn_(node, *this);
}
const IntRange& Validator::intRange() const
{
checkType(NodeType::Integer);
if (aux_data_.int_range_ == nullptr)
{
throw TypeException("API error: missing integer range");
}
return *aux_data_.int_range_;
}
const FloatRange& Validator::floatRange() const
{
checkType(NodeType::FloatingPoint);
if (aux_data_.float_range_ == nullptr)
{
throw TypeException("API error: missing float range");
}
return *aux_data_.float_range_;
}
const ValidatorVector& Validator::seqValidators() const
{
checkType(NodeType::Sequence);
return *aux_data_.seq_validators_;
}
const MapGroupVector& Validator::mapGroups() const
{
checkType(NodeType::Map);
return *aux_data_.map_groups_;
}
void Validator::swap(Validator& other) noexcept
{
std::swap(type_, other.type_);
std::swap(fcn_, other.fcn_);
std::swap(aux_data_, other.aux_data_);
}
void Validator::checkType(NodeType type) const
{
if (type_ != type)
{
throw TypeException("API error: validator type mismatch");
}
}
//
// NullType implementation
//
NullType::NullType()
: Validator(NodeType::Null, vType)
{
}
//
// BooleanType implementation
//
BooleanType::BooleanType()
: Validator(NodeType::Boolean, vType)
{
}
BooleanType::BooleanType(ValidationFcn validation_fcn)
: Validator(NodeType::Boolean, validation_fcn)
{
}
//
// IntegerType implementation
//
IntegerType::IntegerType()
: Validator(NodeType::Integer, vType)
{
}
IntegerType::IntegerType(Int min, Int max)
: Validator(std::make_pair(min, max))
{
}
IntegerType::IntegerType(ValidationFcn validation_fcn)
: Validator(NodeType::Integer, validation_fcn)
{
}
//
// FloatingPointType implementation
//
FloatingPointType::FloatingPointType()
: Validator(NodeType::FloatingPoint, vType)
{
}
FloatingPointType::FloatingPointType(Float min, Float max)
: Validator(std::make_pair(min, max))
{
}
FloatingPointType::FloatingPointType(ValidationFcn validation_fcn)
: Validator(NodeType::FloatingPoint, validation_fcn)
{
}
//
// StringType implementation
//
StringType::StringType()
: Validator(NodeType::String, vType)
{
}
StringType::StringType(ValidationFcn validation_fcn)
: Validator(NodeType::String, validation_fcn)
{
}
//
// SequenceType implementation
//
SequenceType::SequenceType()
: Validator(ValidatorVector())
{
}
SequenceType::SequenceType(Validator child_validator)
: Validator(ValidatorVector({child_validator}))
{
}
SequenceType::SequenceType(ValidatorVector child_types)
: Validator(std::move(child_types))
{
}
SequenceType::SequenceType(ValidationFcn validation_fcn)
: Validator(NodeType::Sequence, validation_fcn)
{
}
//
// MapType implementation
//
MapType::MapType()
: Validator(MapGroupVector())
{
}
MapType::MapType(MapGroup group)
: MapType(MapGroupVector{ group })
{
}
MapType::MapType(MapGroupVector groups)
: Validator(std::move(groups))
{
}
//
// MapEntryType implementation
//
MapEntryType::MapEntryType(String key,
Validator validator,
Requiredness requiredness)
: key_(std::move(key))
, validator_(std::move(validator))
, requiredness_(requiredness)
{
}
void MapEntryType::validate(const Node& node) const
{
Map::const_iterator iter = node.find(key_);
if (iter == node.end())
{
if (requiredness_ == Optional)
{
return;
}
throw ValidationException("required key not present", node);
}
validator_.validate(iter->second);
}
//
// MapGroup implementation
//
MapGroup::MapGroup(MapEntryTypeVector entries, Closedness closedness)
: MapGroup(std::move(entries), closedness, vAllMaps)
{
}
MapGroup::MapGroup(MapEntryTypeVector entries,
Closedness closedness,
GroupEnableFcn enable_fcn)
: entries_(std::move(entries))
, closedness_(closedness)
, enable_fcn_(enable_fcn)
{
}
bool MapGroup::isEnabled(const Node& node) const
{
return enable_fcn_(node);
}
void MapGroup::validate(const Node& node) const
{
for (const MapEntryType& entry : entries_)
{
entry.validate(node);
}
// ensure there are no other entries
if (closedness_ == AllowMoreEntries)
{
return;
}
const Map& map = node.map();
for (const MapEntry& entry : map)
{
const String& key = entry.first;
bool found = false;
for (const MapEntryType& type : entries_)
{
if (type.key() == key)
{
found = true;
break;
}
} // entry type loop
if (!found)
{
throw ValidationException("extra key present in map", node);
}
} // map loop
}
} // namespace cpds
<commit_msg>more helpful error message<commit_after>/*
* validator.cpp
* cpds
*
* Copyright (c) 2016 Hannes Friederich.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "cpds/validator.hpp"
#include "cpds/node.hpp"
#include "cpds/exception.hpp"
#include <iostream>
namespace cpds {
// enforce local linkage
namespace {
// accepts nodes that match the type
void vType(const Node& node,
const Validator& validator)
{
if (node.type() != validator.type())
{
throw TypeException(node);
}
}
// accepts all maps
bool vAllMaps(const Node& /*node*/)
{
return true;
}
// integer range validator
void vIntRange(const Node& node,
const Validator& validator)
{
IntRange range = validator.intRange();
Int val = node.intValue();
if (val < range.first || val > range.second)
{
throw IntRangeException(range.first, range.second, val, node);
}
}
// floating point range validator
void vFloatRange(const Node& node,
const Validator& validator)
{
FloatRange range = validator.floatRange();
Float val = node.floatValue();
if (val < range.first || val > range.second)
{
throw FloatRangeException(range.first, range.second, val, node);
}
}
// sequence validator
void vSequence(const Node& node,
const Validator& validator)
{
const ValidatorVector& validators = validator.seqValidators();
if (validators.empty())
{
return; // nothing to validate against
}
for (const Node& child : node.sequence())
{
// any of the validators must succeed
bool success = false;
for (const Validator& vld : validators)
{
try
{
vld.validate(child);
success = true;
break;
}
catch (...)
{
}
}
if (!success)
{
throw ValidationException("sequence child failed to validate", child);
}
}
}
// map validator
void vMap(const Node& node,
const Validator& validator)
{
const MapGroupVector& groups = validator.mapGroups();
if (groups.empty())
{
return; // nothing to validate against
}
bool enabled = false; // at least one group must be enabled
for (const MapGroup& group : groups)
{
if (group.isEnabled(node))
{
group.validate(node);
enabled = true;
}
}
if (enabled == false)
{
throw ValidationException("map does not match any validation group", node);
}
}
} // unnamed namespace
//
// Validator implementation
//
Validator::Validator(NodeType type, ValidationFcn validation_fcn)
: type_(type)
, fcn_(validation_fcn)
{
aux_data_.int_range_ = nullptr;
}
Validator::Validator(IntRange int_range)
: type_(NodeType::Integer)
, fcn_(vIntRange)
{
aux_data_.int_range_ = new IntRange(int_range);
}
Validator::Validator(FloatRange float_range)
: type_(NodeType::FloatingPoint)
, fcn_(vFloatRange)
{
aux_data_.float_range_ = new FloatRange(float_range);
}
Validator::Validator(ValidatorVector seq_validators)
: type_(NodeType::Sequence)
, fcn_(vSequence)
{
aux_data_.seq_validators_ = new ValidatorVector(std::move(seq_validators));
}
Validator::Validator(MapGroupVector map_groups)
: type_(NodeType::Map)
, fcn_(vMap)
{
aux_data_.map_groups_ = new MapGroupVector(std::move(map_groups));
}
Validator::Validator(const Validator& other)
: type_(other.type_)
, fcn_(other.fcn_)
, aux_data_()
{
switch (type_)
{
case NodeType::Integer:
if (other.aux_data_.int_range_ != nullptr)
{
aux_data_.int_range_ = new IntRange(*other.aux_data_.int_range_);
}
break;
case NodeType::FloatingPoint:
if (other.aux_data_.float_range_ != nullptr)
{
aux_data_.float_range_ = new FloatRange(*other.aux_data_.float_range_);
}
break;
case NodeType::Sequence:
aux_data_.seq_validators_ =
new ValidatorVector(*other.aux_data_.seq_validators_);
break;
case NodeType::Map:
aux_data_.map_groups_ =
new MapGroupVector(*other.aux_data_.map_groups_);
break;
default:
break;
}
}
Validator::Validator(Validator&& other) noexcept
: type_(other.type_)
, fcn_(other.fcn_)
, aux_data_(other.aux_data_)
{
other.type_ = NodeType::Null;
other.aux_data_.int_range_ = nullptr;
}
Validator& Validator::operator=(Validator other) noexcept
{
swap(other);
return *this;
}
Validator::~Validator()
{
switch (type_)
{
case NodeType::Integer:
delete aux_data_.int_range_;
break;
case NodeType::FloatingPoint:
delete aux_data_.float_range_;
break;
case NodeType::Sequence:
delete aux_data_.seq_validators_;
break;
case NodeType::Map:
delete aux_data_.map_groups_;
break;
default:
break;
}
}
void Validator::validate(const Node& node) const
{
fcn_(node, *this);
}
const IntRange& Validator::intRange() const
{
checkType(NodeType::Integer);
if (aux_data_.int_range_ == nullptr)
{
throw TypeException("API error: missing integer range");
}
return *aux_data_.int_range_;
}
const FloatRange& Validator::floatRange() const
{
checkType(NodeType::FloatingPoint);
if (aux_data_.float_range_ == nullptr)
{
throw TypeException("API error: missing float range");
}
return *aux_data_.float_range_;
}
const ValidatorVector& Validator::seqValidators() const
{
checkType(NodeType::Sequence);
return *aux_data_.seq_validators_;
}
const MapGroupVector& Validator::mapGroups() const
{
checkType(NodeType::Map);
return *aux_data_.map_groups_;
}
void Validator::swap(Validator& other) noexcept
{
std::swap(type_, other.type_);
std::swap(fcn_, other.fcn_);
std::swap(aux_data_, other.aux_data_);
}
void Validator::checkType(NodeType type) const
{
if (type_ != type)
{
throw TypeException("API error: validator type mismatch");
}
}
//
// NullType implementation
//
NullType::NullType()
: Validator(NodeType::Null, vType)
{
}
//
// BooleanType implementation
//
BooleanType::BooleanType()
: Validator(NodeType::Boolean, vType)
{
}
BooleanType::BooleanType(ValidationFcn validation_fcn)
: Validator(NodeType::Boolean, validation_fcn)
{
}
//
// IntegerType implementation
//
IntegerType::IntegerType()
: Validator(NodeType::Integer, vType)
{
}
IntegerType::IntegerType(Int min, Int max)
: Validator(std::make_pair(min, max))
{
}
IntegerType::IntegerType(ValidationFcn validation_fcn)
: Validator(NodeType::Integer, validation_fcn)
{
}
//
// FloatingPointType implementation
//
FloatingPointType::FloatingPointType()
: Validator(NodeType::FloatingPoint, vType)
{
}
FloatingPointType::FloatingPointType(Float min, Float max)
: Validator(std::make_pair(min, max))
{
}
FloatingPointType::FloatingPointType(ValidationFcn validation_fcn)
: Validator(NodeType::FloatingPoint, validation_fcn)
{
}
//
// StringType implementation
//
StringType::StringType()
: Validator(NodeType::String, vType)
{
}
StringType::StringType(ValidationFcn validation_fcn)
: Validator(NodeType::String, validation_fcn)
{
}
//
// SequenceType implementation
//
SequenceType::SequenceType()
: Validator(ValidatorVector())
{
}
SequenceType::SequenceType(Validator child_validator)
: Validator(ValidatorVector({child_validator}))
{
}
SequenceType::SequenceType(ValidatorVector child_types)
: Validator(std::move(child_types))
{
}
SequenceType::SequenceType(ValidationFcn validation_fcn)
: Validator(NodeType::Sequence, validation_fcn)
{
}
//
// MapType implementation
//
MapType::MapType()
: Validator(MapGroupVector())
{
}
MapType::MapType(MapGroup group)
: MapType(MapGroupVector{ group })
{
}
MapType::MapType(MapGroupVector groups)
: Validator(std::move(groups))
{
}
//
// MapEntryType implementation
//
MapEntryType::MapEntryType(String key,
Validator validator,
Requiredness requiredness)
: key_(std::move(key))
, validator_(std::move(validator))
, requiredness_(requiredness)
{
}
void MapEntryType::validate(const Node& node) const
{
Map::const_iterator iter = node.find(key_);
if (iter == node.end())
{
if (requiredness_ == Optional)
{
return;
}
throw ValidationException("required key not present", node);
}
validator_.validate(iter->second);
}
//
// MapGroup implementation
//
MapGroup::MapGroup(MapEntryTypeVector entries, Closedness closedness)
: MapGroup(std::move(entries), closedness, vAllMaps)
{
}
MapGroup::MapGroup(MapEntryTypeVector entries,
Closedness closedness,
GroupEnableFcn enable_fcn)
: entries_(std::move(entries))
, closedness_(closedness)
, enable_fcn_(enable_fcn)
{
}
bool MapGroup::isEnabled(const Node& node) const
{
return enable_fcn_(node);
}
void MapGroup::validate(const Node& node) const
{
for (const MapEntryType& entry : entries_)
{
entry.validate(node);
}
// ensure there are no other entries
if (closedness_ == AllowMoreEntries)
{
return;
}
const Map& map = node.map();
for (const MapEntry& entry : map)
{
const String& key = entry.first;
bool found = false;
for (const MapEntryType& type : entries_)
{
if (type.key() == key)
{
found = true;
break;
}
} // entry type loop
if (!found)
{
String msg("extra key '");
msg += key;
msg += ("' present in map");
throw ValidationException(msg, node);
}
} // map loop
}
} // namespace cpds
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkCtkPythonShell.h"
#include <ctkAbstractPythonManager.h>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QUrl>
#include "mitkPythonService.h"
#include <usModuleContext.h>
#include <usServiceReference.h>
#include <usGetModuleContext.h>
struct QmitkCtkPythonShellData
{
mitk::PythonService* m_PythonService;
us::ServiceReference<mitk::PythonService> m_PythonServiceRef;
};
QmitkCtkPythonShell::QmitkCtkPythonShell(QWidget* parent)
: ctkPythonConsole(parent), d( new QmitkCtkPythonShellData )
{
MITK_DEBUG("QmitkCtkPythonShell") << "retrieving IPythonService";
us::ModuleContext* context = us::GetModuleContext();
d->m_PythonServiceRef = context->GetServiceReference<mitk::IPythonService>();
d->m_PythonService = dynamic_cast<mitk::PythonService*> ( context->GetService<mitk::IPythonService>(d->m_PythonServiceRef) );
MITK_DEBUG("QmitkCtkPythonShell") << "checking IPythonService";
Q_ASSERT( d->m_PythonService );
MITK_DEBUG("QmitkCtkPythonShell") << "initialize m_PythonService";
this->initialize( d->m_PythonService->GetPythonManager() );
MITK_DEBUG("QmitkCtkPythonShell") << "m_PythonService initialized";
}
QmitkCtkPythonShell::~QmitkCtkPythonShell()
{
us::ModuleContext* context = us::GetModuleContext();
context->UngetService( d->m_PythonServiceRef );
delete d;
}
void QmitkCtkPythonShell::dragEnterEvent(QDragEnterEvent *event)
{
event->accept();
}
void QmitkCtkPythonShell::dropEvent(QDropEvent *event)
{
QList<QUrl> urls = event->mimeData()->urls();
for(int i = 0; i < urls.size(); i++)
{
d->m_PythonService->Execute( urls[i].toString().toStdString(), mitk::IPythonService::SINGLE_LINE_COMMAND );
}
}
bool QmitkCtkPythonShell::canInsertFromMimeData( const QMimeData *source ) const
{
return true;
}
void QmitkCtkPythonShell::executeCommand(const QString& command)
{
MITK_DEBUG("QmitkCtkPythonShell") << "executing command " << command.toStdString();
ctkPythonConsole::executeCommand(command);
d->m_PythonService->NotifyObserver(command.toStdString());
}
void QmitkCtkPythonShell::Paste(const QString &command)
{
if( this->isVisible() )
{
this->exec( command );
//this->executeCommand( command );
}
}
<commit_msg>fixed running multiline snippets<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkCtkPythonShell.h"
#include <ctkAbstractPythonManager.h>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QUrl>
#include "mitkPythonService.h"
#include <usModuleContext.h>
#include <usServiceReference.h>
#include <usGetModuleContext.h>
struct QmitkCtkPythonShellData
{
mitk::PythonService* m_PythonService;
us::ServiceReference<mitk::PythonService> m_PythonServiceRef;
};
QmitkCtkPythonShell::QmitkCtkPythonShell(QWidget* parent)
: ctkPythonConsole(parent), d( new QmitkCtkPythonShellData )
{
MITK_DEBUG("QmitkCtkPythonShell") << "retrieving IPythonService";
us::ModuleContext* context = us::GetModuleContext();
d->m_PythonServiceRef = context->GetServiceReference<mitk::IPythonService>();
d->m_PythonService = dynamic_cast<mitk::PythonService*> ( context->GetService<mitk::IPythonService>(d->m_PythonServiceRef) );
MITK_DEBUG("QmitkCtkPythonShell") << "checking IPythonService";
Q_ASSERT( d->m_PythonService );
MITK_DEBUG("QmitkCtkPythonShell") << "initialize m_PythonService";
this->initialize( d->m_PythonService->GetPythonManager() );
MITK_DEBUG("QmitkCtkPythonShell") << "m_PythonService initialized";
}
QmitkCtkPythonShell::~QmitkCtkPythonShell()
{
us::ModuleContext* context = us::GetModuleContext();
context->UngetService( d->m_PythonServiceRef );
delete d;
}
void QmitkCtkPythonShell::dragEnterEvent(QDragEnterEvent *event)
{
event->accept();
}
void QmitkCtkPythonShell::dropEvent(QDropEvent *event)
{
QList<QUrl> urls = event->mimeData()->urls();
for(int i = 0; i < urls.size(); i++)
{
d->m_PythonService->Execute( urls[i].toString().toStdString(), mitk::IPythonService::SINGLE_LINE_COMMAND );
}
}
bool QmitkCtkPythonShell::canInsertFromMimeData( const QMimeData *source ) const
{
return true;
}
void QmitkCtkPythonShell::executeCommand(const QString& command)
{
MITK_DEBUG("QmitkCtkPythonShell") << "executing command " << command.toStdString();
d->m_PythonService->Execute(command.toStdString(),mitk::IPythonService::MULTI_LINE_COMMAND);
d->m_PythonService->NotifyObserver(command.toStdString());
}
void QmitkCtkPythonShell::Paste(const QString &command)
{
if( this->isVisible() )
{
this->exec( command );
//this->executeCommand( command );
}
}
<|endoftext|> |
<commit_before>#include "Variant.h"
#include "convert.h"
#include "join.h"
#include "split.h"
#include <set>
#include <getopt.h>
#include "Fasta.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace vcflib;
#define ALLELE_NULL -1
class SampleFastaFile {
public:
ofstream fastafile;
long int pos;
string linebuffer;
string filename;
string seqname;
int linewidth;
void write(string sequence) {
linebuffer += sequence;
while (linebuffer.length() > linewidth) {
fastafile << linebuffer.substr(0, linewidth) << endl;
linebuffer = linebuffer.substr(linewidth);
}
}
SampleFastaFile(void) { }
void open(string& m_filename, string& m_seqname, int m_linewidth = 80) {
filename = m_filename;
seqname = m_seqname;
pos = 0;
linewidth = m_linewidth;
if (fastafile.is_open()) fastafile.close();
fastafile.open(filename.c_str());
if (!fastafile.is_open()) {
cerr << "could not open " << filename << " for writing, exiting" << endl;
exit(1);
}
fastafile << ">" << seqname << endl;
}
~SampleFastaFile(void) {
if (fastafile.is_open()) {
write(""); // flush
fastafile << linebuffer << endl;
fastafile.close();
}
}
};
void printSummary(char** argv) {
cerr << "usage: " << argv[0] << " [options] [file]" << endl
<< endl
<< "options:" << endl
<< " -f, --reference REF Use this reference when decomposing samples." << endl
<< " -p, --prefix PREFIX Affix this output prefix to each file, none by default" << endl
<< " -P, --default-ploidy N Set a default ploidy for samples which do not have information in the first record (2)." << endl
<< endl
<< "Outputs sample_seq:N.fa for each sample, reference sequence, and chromosomal copy N in [0,1... ploidy]." << endl;
//<< "Impossible regions of haplotypes are noted with an error message. The corresponding" << endl
//<< "regions of the output FASTA files will be marked as N." << endl
exit(0);
}
map<string, int>& getPloidies(Variant& var, map<string, int>& ploidies, int defaultPloidy=2) {
for (vector<string>::iterator s = var.sampleNames.begin(); s != var.sampleNames.end(); ++s) {
int p = ploidy(decomposeGenotype(var.getGenotype(*s)));
if (p == 0) ploidies[*s] = defaultPloidy;
else ploidies[*s] = p;
}
return ploidies;
}
void closeOutputs(map<string, map<int, SampleFastaFile*> >& outputs) {
for (map<string, map<int, SampleFastaFile*> >::iterator f = outputs.begin(); f != outputs.end(); ++f) {
for (map<int, SampleFastaFile*>::iterator s = f->second.begin(); s != f->second.end(); ++s) {
delete s->second;
}
}
}
void initOutputs(map<string, map<int, SampleFastaFile*> >& outputs, vector<string>& sampleNames, string& seqName, map<string, int>& ploidies, string& prefix) {
closeOutputs(outputs);
for (vector<string>::iterator s = sampleNames.begin(); s != sampleNames.end(); ++s) {
map<int, SampleFastaFile*>& outs = outputs[*s];
int p = ploidies[*s];
for (int i = 0; i < p; ++i) {
string name = prefix + *s + "_" + seqName + ":" + convert(i) + ".fasta";
if (!outs[i]) {
SampleFastaFile* fp = new SampleFastaFile;
outs[i] = fp;
}
SampleFastaFile& f = *outs[i];
f.open(name, seqName);
}
}
}
void vcf2fasta(VariantCallFile& variantFile, FastaReference& reference, string& outputPrefix, int defaultPloidy) {
string lastSeq;
long int lastPos=0, lastEnd=0;
map<string, map<int, SampleFastaFile*> > outputs;
Variant var(variantFile);
map<string, int> lastPloidies;
while (variantFile.getNextVariant(var)) {
if (!var.isPhased()) {
cerr << "variant " << var.sequenceName << ":" << var.position << " is not phased, cannot convert to fasta" << endl;
exit(1);
}
map<string, int> ploidies;
getPloidies(var, ploidies, defaultPloidy);
if (var.sequenceName != lastSeq || lastSeq.empty()) {
if (!lastSeq.empty()) {
string ref5prime = reference.getSubSequence(lastSeq, lastEnd, reference.sequenceLength(lastSeq)-lastEnd);
for (map<string, map<int, SampleFastaFile*> >::iterator s = outputs.begin(); s != outputs.end(); ++s) {
map<int, SampleFastaFile*>& f = s->second;
for (map<int, SampleFastaFile*>::iterator o = f.begin(); o != f.end(); ++o) {
o->second->write(ref5prime);
}
}
}
initOutputs(outputs, var.sampleNames, var.sequenceName, ploidies, outputPrefix);
lastSeq = var.sequenceName;
lastPos = 0;
} else if (!lastPloidies.empty() && lastPloidies != ploidies) {
cerr << "cannot handle mid-sequence change of ploidy" << endl;
// in principle it should be possible...
// it's a matter of representation, GFASTA anyone?
exit(1);
}
lastPloidies = ploidies;
if (var.position < lastEnd) {
cerr << var.position << " vs " << lastEnd << endl;
cerr << "overlapping or out-of-order variants at " << var.sequenceName << ":" << var.position << endl;
exit(1);
}
// get reference sequences implied by last->current variant
string ref5prime;
if (var.position - 1 - lastEnd > 0) {
ref5prime = reference.getSubSequence(var.sequenceName, lastEnd, var.position - 1 - lastEnd);
}
// write alt/ref seqs for current variant based on phased genotypes
for (vector<string>::iterator s = var.sampleNames.begin(); s != var.sampleNames.end(); ++s) {
string& sample = *s;
vector<int> gt = decomposePhasedGenotype(var.getGenotype(sample));
// assume no-call == ref?
if (gt.empty()) {
cerr << "empty genotype for sample " << *s << " at " << var.sequenceName << ":" << var.position << endl;
exit(1);
}
int i = 0;
for (vector<int>::iterator g = gt.begin(); g != gt.end(); ++g, ++i) {
outputs[sample].at(i)->write(ref5prime+var.alleles.at(*g));
}
}
lastPos = var.position - 1;
lastEnd = lastPos + var.ref.size();
}
// write last sequences
{
string ref5prime = reference.getSubSequence(lastSeq, lastEnd, reference.sequenceLength(lastSeq)-lastEnd);
for (map<string, map<int, SampleFastaFile*> >::iterator s = outputs.begin(); s != outputs.end(); ++s) {
map<int, SampleFastaFile*>& f = s->second;
for (map<int, SampleFastaFile*>::iterator o = f.begin(); o != f.end(); ++o) {
o->second->write(ref5prime);
}
}
}
closeOutputs(outputs);
// outputs are closed by ~SampleFastaFile
}
int main(int argc, char** argv) {
VariantCallFile variantFile;
string fastaFileName;
int defaultPloidy;
string outputPrefix;
int c;
while (true) {
static struct option long_options[] =
{
/* These options set a flag. */
//{"verbose", no_argument, &verbose_flag, 1},
{"help", no_argument, 0, 'h'},
{"reference", required_argument, 0, 'f'},
{"prefix", required_argument, 0, 'p'},
{"default-ploidy", required_argument, 0, 'P'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "hmf:p:P:",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'f':
fastaFileName = optarg;
break;
case 'h':
printSummary(argv);
break;
case 'p':
outputPrefix = optarg;
break;
case 'P':
defaultPloidy = atoi(optarg);
break;
case '?':
printSummary(argv);
exit(1);
break;
default:
abort ();
}
}
FastaReference reference;
if (fastaFileName.empty()) {
cerr << "a reference is required for haplotype allele generation" << endl;
printSummary(argv);
exit(1);
}
reference.open(fastaFileName);
if (optind < argc) {
string filename = argv[optind];
variantFile.open(filename);
} else {
variantFile.open(std::cin);
}
if (!variantFile.is_open()) {
return 1;
}
vcf2fasta(variantFile, reference, outputPrefix, defaultPloidy);
return 0;
}
<commit_msg>Added -n option to vcf2fasta for missing calls<commit_after>#include "Variant.h"
#include "convert.h"
#include "join.h"
#include "split.h"
#include <set>
#include <getopt.h>
#include "Fasta.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace vcflib;
#define ALLELE_NULL -1
class SampleFastaFile {
public:
ofstream fastafile;
long int pos;
string linebuffer;
string filename;
string seqname;
int linewidth;
void write(string sequence) {
linebuffer += sequence;
while (linebuffer.length() > linewidth) {
fastafile << linebuffer.substr(0, linewidth) << endl;
linebuffer = linebuffer.substr(linewidth);
}
}
SampleFastaFile(void) { }
void open(string& m_filename, string& m_seqname, int m_linewidth = 80) {
filename = m_filename;
seqname = m_seqname;
pos = 0;
linewidth = m_linewidth;
if (fastafile.is_open()) fastafile.close();
fastafile.open(filename.c_str());
if (!fastafile.is_open()) {
cerr << "could not open " << filename << " for writing, exiting" << endl;
exit(1);
}
fastafile << ">" << seqname << endl;
}
~SampleFastaFile(void) {
if (fastafile.is_open()) {
write(""); // flush
fastafile << linebuffer << endl;
fastafile.close();
}
}
};
void printSummary(char** argv) {
cerr << "usage: " << argv[0] << " [options] [file]" << endl
<< endl
<< "options:" << endl
<< " -f, --reference REF Use this reference when decomposing samples." << endl
<< " -p, --prefix PREFIX Affix this output prefix to each file, none by default" << endl
<< " -P, --default-ploidy N Set a default ploidy for samples which do not have information in the first record (2)." << endl
<< endl
<< "Outputs sample_seq:N.fa for each sample, reference sequence, and chromosomal copy N in [0,1... ploidy]." << endl;
//<< "Impossible regions of haplotypes are noted with an error message. The corresponding" << endl
//<< "regions of the output FASTA files will be marked as N." << endl
exit(0);
}
map<string, int>& getPloidies(Variant& var, map<string, int>& ploidies, int defaultPloidy=2) {
for (vector<string>::iterator s = var.sampleNames.begin(); s != var.sampleNames.end(); ++s) {
int p = ploidy(decomposeGenotype(var.getGenotype(*s)));
if (p == 0) ploidies[*s] = defaultPloidy;
else ploidies[*s] = p;
}
return ploidies;
}
void closeOutputs(map<string, map<int, SampleFastaFile*> >& outputs) {
for (map<string, map<int, SampleFastaFile*> >::iterator f = outputs.begin(); f != outputs.end(); ++f) {
for (map<int, SampleFastaFile*>::iterator s = f->second.begin(); s != f->second.end(); ++s) {
delete s->second;
}
}
}
void initOutputs(map<string, map<int, SampleFastaFile*> >& outputs, vector<string>& sampleNames, string& seqName, map<string, int>& ploidies, string& prefix) {
closeOutputs(outputs);
for (vector<string>::iterator s = sampleNames.begin(); s != sampleNames.end(); ++s) {
map<int, SampleFastaFile*>& outs = outputs[*s];
int p = ploidies[*s];
for (int i = 0; i < p; ++i) {
string name = prefix + *s + "_" + seqName + ":" + convert(i) + ".fasta";
if (!outs[i]) {
SampleFastaFile* fp = new SampleFastaFile;
outs[i] = fp;
}
SampleFastaFile& f = *outs[i];
f.open(name, seqName);
}
}
}
void vcf2fasta(VariantCallFile& variantFile, FastaReference& reference, string& outputPrefix, int defaultPloidy, string& nullAlleleString) {
string lastSeq;
long int lastPos=0, lastEnd=0;
map<string, map<int, SampleFastaFile*> > outputs;
Variant var(variantFile);
map<string, int> lastPloidies;
while (variantFile.getNextVariant(var)) {
if (!var.isPhased()) {
cerr << "variant " << var.sequenceName << ":" << var.position << " is not phased, cannot convert to fasta" << endl;
exit(1);
}
map<string, int> ploidies;
getPloidies(var, ploidies, defaultPloidy);
if (var.sequenceName != lastSeq || lastSeq.empty()) {
if (!lastSeq.empty()) {
string ref5prime = reference.getSubSequence(lastSeq, lastEnd, reference.sequenceLength(lastSeq)-lastEnd);
for (map<string, map<int, SampleFastaFile*> >::iterator s = outputs.begin(); s != outputs.end(); ++s) {
map<int, SampleFastaFile*>& f = s->second;
for (map<int, SampleFastaFile*>::iterator o = f.begin(); o != f.end(); ++o) {
o->second->write(ref5prime);
}
}
}
initOutputs(outputs, var.sampleNames, var.sequenceName, ploidies, outputPrefix);
lastSeq = var.sequenceName;
lastPos = 0;
} else if (!lastPloidies.empty() && lastPloidies != ploidies) {
cerr << "cannot handle mid-sequence change of ploidy" << endl;
// in principle it should be possible...
// it's a matter of representation, GFASTA anyone?
exit(1);
}
lastPloidies = ploidies;
if (var.position < lastEnd) {
cerr << var.position << " vs " << lastEnd << endl;
cerr << "overlapping or out-of-order variants at " << var.sequenceName << ":" << var.position << endl;
exit(1);
}
// get reference sequences implied by last->current variant
string ref5prime;
if (var.position - 1 - lastEnd > 0) {
ref5prime = reference.getSubSequence(var.sequenceName, lastEnd, var.position - 1 - lastEnd);
}
// write alt/ref seqs for current variant based on phased genotypes
for (vector<string>::iterator s = var.sampleNames.begin(); s != var.sampleNames.end(); ++s) {
string& sample = *s;
vector<int> gt = decomposePhasedGenotype(var.getGenotype(sample));
// assume no-call == ref?
if (gt.empty()) {
cerr << "empty genotype for sample " << *s << " at " << var.sequenceName << ":" << var.position << endl;
exit(1);
}
int i = 0;
for (vector<int>::iterator g = gt.begin(); g != gt.end(); ++g, ++i) {
// @TCC handle uncalled genotypes (*g == NULL_ALLELE)
if( *g == NULL_ALLELE ){
if( nullAlleleString == "" ){
cerr << "empty genotype call for sample " << *s << " at " << var.sequenceName << ":" << var.position << endl;
cerr << "use -n option to set value to output for missing calls" << endl;
exit(1);
}else{
outputs[sample].at(i)->write(nullAlleleString);
}
}else{
outputs[sample].at(i)->write(ref5prime+var.alleles.at(*g));
}
}
}
lastPos = var.position - 1;
lastEnd = lastPos + var.ref.size();
}
// write last sequences
{
string ref5prime = reference.getSubSequence(lastSeq, lastEnd, reference.sequenceLength(lastSeq)-lastEnd);
for (map<string, map<int, SampleFastaFile*> >::iterator s = outputs.begin(); s != outputs.end(); ++s) {
map<int, SampleFastaFile*>& f = s->second;
for (map<int, SampleFastaFile*>::iterator o = f.begin(); o != f.end(); ++o) {
o->second->write(ref5prime);
}
}
}
closeOutputs(outputs);
// outputs are closed by ~SampleFastaFile
}
int main(int argc, char** argv) {
VariantCallFile variantFile;
string fastaFileName;
int defaultPloidy;
string outputPrefix;
string nullAlleleString;
int c;
while (true) {
static struct option long_options[] =
{
/* These options set a flag. */
//{"verbose", no_argument, &verbose_flag, 1},
{"help", no_argument, 0, 'h'},
{"reference", required_argument, 0, 'f'},
{"prefix", required_argument, 0, 'p'},
{"default-ploidy", required_argument, 0, 'P'},
{"no-call-string", required_argument, 0, 'n'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "hmf:p:P:n:",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'f':
fastaFileName = optarg;
break;
case 'h':
printSummary(argv);
break;
case 'p':
outputPrefix = optarg;
break;
case 'P':
defaultPloidy = atoi(optarg);
break;
case 'n':
nullAlleleString = optarg;
break;
case '?':
printSummary(argv);
exit(1);
break;
default:
abort ();
}
}
FastaReference reference;
if (fastaFileName.empty()) {
cerr << "a reference is required for haplotype allele generation" << endl;
printSummary(argv);
exit(1);
}
reference.open(fastaFileName);
if (optind < argc) {
string filename = argv[optind];
variantFile.open(filename);
} else {
variantFile.open(std::cin);
}
if (!variantFile.is_open()) {
return 1;
}
vcf2fasta(variantFile, reference, outputPrefix, defaultPloidy, nullAlleleString);
return 0;
}
<|endoftext|> |
<commit_before>/*********************************************************************
*
* Copyright (C) 2008, Simon Kagstrom
*
* Filename: string-instruction.cc
* Author: Simon Kagstrom <simon.kagstrom@gmail.com>
* Description: Instruction encoding to string
*
* $Id:$
*
********************************************************************/
#include <instruction.hh>
#include <mips.hh>
int instruction_to_string(Instruction *insn, char *buf, int buf_len)
{
const char *insn_name = mips_op_strings[insn->getOpcode()];
uint32_t rs, rt, rd;
uint32_t extra;
int out = 0;
rs = insn->getRs();
rt = insn->getRt();
rd = insn->getRd();
extra = insn->getExtra();
switch(insn->getOpcode())
{
/* rfmt */
case OP_ADDU:
case OP_ADD:
case OP_SUB:
case OP_SUBU:
case OP_XOR:
case OP_AND:
case OP_OR:
case OP_NOR:
case OP_SRAV:
case OP_SLLV:
case OP_SRLV:
case OP_SLTU:
case OP_SLT:
out = snprintf(buf, buf_len, "%s %s, %s, %s", insn_name, mips_reg_strings[rd],
mips_reg_strings[rs], mips_reg_strings[rt]);
break;
case OP_SLL:
case OP_SRA:
case OP_SRL:
out = snprintf(buf, buf_len, "%s %s, %s, %d", insn_name, mips_reg_strings[rd],
mips_reg_strings[rt], (int32_t)extra);
break;
/* Ifmt */
case OP_SLTIU:
case OP_SLTI:
case OP_ADDI:
case OP_ADDIU:
case OP_XORI:
case OP_ANDI:
case OP_ORI:
out = snprintf(buf, buf_len, "%s %s, %s, %d", insn_name, mips_reg_strings[rt],
mips_reg_strings[rs], (int32_t)extra);
break;
/* Jfmt */
case OP_BGEZAL:
case OP_JAL:
out = snprintf(buf, buf_len, "%s 0x%x", insn_name, (extra<<2));
break;
case OP_JR:
case OP_JALR:
out = snprintf(buf, buf_len, "%s %s", insn_name, mips_reg_strings[rs]);
break;
case OP_J:
out = snprintf(buf, buf_len, "%s 0x%x", insn_name, (extra<<2));
break;
/* Memory handling */
case OP_LW:
case OP_SW:
case OP_LB:
case OP_LBU:
case OP_LH:
case OP_LHU:
case OP_LWL:
case OP_LWR:
case OP_SB:
case OP_SH:
case OP_SWL:
case OP_SWR:
out = snprintf(buf, buf_len, "%s %s, %d(%s)", insn_name, mips_reg_strings[rt],
extra, mips_reg_strings[rs]);
break;
/* Misc other instructions */
case OP_BREAK:
out = snprintf(buf, buf_len, "break");
break;
case OP_MULT:
case OP_MULTU:
case OP_DIV:
case OP_DIVU:
out = snprintf(buf, buf_len, "%s %s, %s", insn_name, mips_reg_strings[rs],
mips_reg_strings[rt]);
break;
case OP_MFLO:
case OP_MFHI:
case OP_MTLO:
case OP_MTHI:
out = snprintf(buf, buf_len, "%s %s", insn_name, mips_reg_strings[rs]);
break;
case OP_LUI:
out = snprintf(buf, buf_len, "%s %s, 0x%x", insn_name, mips_reg_strings[rt], extra << 16);
break;
/* Conditional jumps, shifts */
case OP_BEQ:
case OP_BNE:
out = snprintf(buf, buf_len, "%s %s, %s, 0x%x", insn_name, mips_reg_strings[rs], mips_reg_strings[rt],
(insn->getAddress() + 4) + (extra << 2));
break;
case OP_BGEZ:
case OP_BGTZ:
case OP_BLEZ:
case OP_BLTZ:
out = snprintf(buf, buf_len, "%s %s, 0x%x", insn_name, mips_reg_strings[rs],
(insn->getAddress() + 4) + (extra << 2));
break;
default:
out = snprintf(buf, buf_len, "Unknown instruction 0x%x", insn->getOpcode());
}
return out;
}
<commit_msg>Panic if snprintf fail<commit_after>/*********************************************************************
*
* Copyright (C) 2008, Simon Kagstrom
*
* Filename: string-instruction.cc
* Author: Simon Kagstrom <simon.kagstrom@gmail.com>
* Description: Instruction encoding to string
*
* $Id:$
*
********************************************************************/
#include <instruction.hh>
#include <mips.hh>
int instruction_to_string(Instruction *insn, char *buf, int buf_len)
{
const char *insn_name = mips_op_strings[insn->getOpcode()];
uint32_t rs, rt, rd;
uint32_t extra;
int out = 0;
rs = insn->getRs();
rt = insn->getRt();
rd = insn->getRd();
extra = insn->getExtra();
switch(insn->getOpcode())
{
/* rfmt */
case OP_ADDU:
case OP_ADD:
case OP_SUB:
case OP_SUBU:
case OP_XOR:
case OP_AND:
case OP_OR:
case OP_NOR:
case OP_SRAV:
case OP_SLLV:
case OP_SRLV:
case OP_SLTU:
case OP_SLT:
out = snprintf(buf, buf_len, "%s %s, %s, %s", insn_name, mips_reg_strings[rd],
mips_reg_strings[rs], mips_reg_strings[rt]);
break;
case OP_SLL:
case OP_SRA:
case OP_SRL:
out = snprintf(buf, buf_len, "%s %s, %s, %d", insn_name, mips_reg_strings[rd],
mips_reg_strings[rt], (int32_t)extra);
break;
/* Ifmt */
case OP_SLTIU:
case OP_SLTI:
case OP_ADDI:
case OP_ADDIU:
case OP_XORI:
case OP_ANDI:
case OP_ORI:
out = snprintf(buf, buf_len, "%s %s, %s, %d", insn_name, mips_reg_strings[rt],
mips_reg_strings[rs], (int32_t)extra);
break;
/* Jfmt */
case OP_BGEZAL:
case OP_JAL:
out = snprintf(buf, buf_len, "%s 0x%x", insn_name, (extra<<2));
break;
case OP_JR:
case OP_JALR:
out = snprintf(buf, buf_len, "%s %s", insn_name, mips_reg_strings[rs]);
break;
case OP_J:
out = snprintf(buf, buf_len, "%s 0x%x", insn_name, (extra<<2));
break;
/* Memory handling */
case OP_LW:
case OP_SW:
case OP_LB:
case OP_LBU:
case OP_LH:
case OP_LHU:
case OP_LWL:
case OP_LWR:
case OP_SB:
case OP_SH:
case OP_SWL:
case OP_SWR:
out = snprintf(buf, buf_len, "%s %s, %d(%s)", insn_name, mips_reg_strings[rt],
extra, mips_reg_strings[rs]);
break;
/* Misc other instructions */
case OP_BREAK:
out = snprintf(buf, buf_len, "break");
break;
case OP_MULT:
case OP_MULTU:
case OP_DIV:
case OP_DIVU:
out = snprintf(buf, buf_len, "%s %s, %s", insn_name, mips_reg_strings[rs],
mips_reg_strings[rt]);
break;
case OP_MFLO:
case OP_MFHI:
case OP_MTLO:
case OP_MTHI:
out = snprintf(buf, buf_len, "%s %s", insn_name, mips_reg_strings[rs]);
break;
case OP_LUI:
out = snprintf(buf, buf_len, "%s %s, 0x%x", insn_name, mips_reg_strings[rt], extra << 16);
break;
/* Conditional jumps, shifts */
case OP_BEQ:
case OP_BNE:
out = snprintf(buf, buf_len, "%s %s, %s, 0x%x", insn_name, mips_reg_strings[rs], mips_reg_strings[rt],
(insn->getAddress() + 4) + (extra << 2));
break;
case OP_BGEZ:
case OP_BGTZ:
case OP_BLEZ:
case OP_BLTZ:
out = snprintf(buf, buf_len, "%s %s, 0x%x", insn_name, mips_reg_strings[rs],
(insn->getAddress() + 4) + (extra << 2));
break;
default:
out = snprintf(buf, buf_len, "Unknown instruction 0x%x", insn->getOpcode());
}
panic_if(out < 0 || out >= buf_len,
"buffer to small to write instruction string\n");
return out;
}
<|endoftext|> |
<commit_before> /*************************************************************************
*
* $RCSfile: accpreview.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2003-04-17 13:38:00 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif
#ifndef _ACCPREVIEW_HXX
#include <accpreview.hxx>
#endif
const sal_Char sServiceName[] = "drafts.com.sun.star.text.AccessibleTextDocumentPageView";
const sal_Char sImplementationName[] = "com.sun.star.comp.Writer.SwAccessibleDocumentPageView";
// using namespace ::drafts::com::sun::star::accessibility;
using ::com::sun::star::lang::IndexOutOfBoundsException;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
//
// SwAccessiblePreview
//
SwAccessiblePreview::SwAccessiblePreview( SwAccessibleMap *pMap ) :
SwAccessibleDocumentBase( pMap )
{
SetName( GetResource( STR_ACCESS_DOC_NAME ) );
}
SwAccessiblePreview::~SwAccessiblePreview()
{
}
OUString SwAccessiblePreview::getImplementationName( )
throw( RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( sImplementationName ) );
}
sal_Bool SwAccessiblePreview::supportsService( const OUString& rServiceName )
throw( RuntimeException )
{
return rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( sServiceName) ) ||
rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( sAccessibleServiceName ) );
}
Sequence<OUString> SwAccessiblePreview::getSupportedServiceNames( )
throw( RuntimeException )
{
Sequence<OUString> aSeq( 2 );
aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( sServiceName ) );
aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( sAccessibleServiceName ) );
return aSeq;
}
Sequence< sal_Int8 > SAL_CALL SwAccessiblePreview::getImplementationId()
throw(RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
<commit_msg>INTEGRATION: CWS uaa02 (1.5.10); FILE MERGED 2003/04/14 16:20:05 dvo 1.5.10.2: #108917# implement must-changes: move API away from drafts module throw IllegalArgumentException for illegal text type 2003/04/11 17:21:22 mt 1.5.10.1: #108656# Moved accessibility from drafts to final<commit_after> /*************************************************************************
*
* $RCSfile: accpreview.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2003-04-24 16:13:01 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif
#ifndef _ACCPREVIEW_HXX
#include <accpreview.hxx>
#endif
const sal_Char sServiceName[] = "com.sun.star.text.AccessibleTextDocumentPageView";
const sal_Char sImplementationName[] = "com.sun.star.comp.Writer.SwAccessibleDocumentPageView";
// using namespace ::com::sun::star::accessibility;
using ::com::sun::star::lang::IndexOutOfBoundsException;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
//
// SwAccessiblePreview
//
SwAccessiblePreview::SwAccessiblePreview( SwAccessibleMap *pMap ) :
SwAccessibleDocumentBase( pMap )
{
SetName( GetResource( STR_ACCESS_DOC_NAME ) );
}
SwAccessiblePreview::~SwAccessiblePreview()
{
}
OUString SwAccessiblePreview::getImplementationName( )
throw( RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( sImplementationName ) );
}
sal_Bool SwAccessiblePreview::supportsService( const OUString& rServiceName )
throw( RuntimeException )
{
return rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( sServiceName) ) ||
rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( sAccessibleServiceName ) );
}
Sequence<OUString> SwAccessiblePreview::getSupportedServiceNames( )
throw( RuntimeException )
{
Sequence<OUString> aSeq( 2 );
aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( sServiceName ) );
aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( sAccessibleServiceName ) );
return aSeq;
}
Sequence< sal_Int8 > SAL_CALL SwAccessiblePreview::getImplementationId()
throw(RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include "command.h"
#include "image.h"
#include "algo/threaded_loop.h"
#include "interp/linear.h"
#include <stack>
using namespace MR;
using namespace App;
class TransformBase {
public:
virtual ~TransformBase(){}
virtual Eigen::Vector3 transform_point (const Eigen::Vector3& input) = 0;
};
class Warp : public TransformBase {
public:
Warp (Image<default_type>& in) : interp (in) {}
Eigen::Vector3 transform_point (const Eigen::Vector3 &input) {
Eigen::Vector3 output;
if (interp.scanner (input))
output.row(3) = interp.row(3);
else
output.fill (NaN);
return output;
}
protected:
Interp::Linear<Image<default_type> > interp;
};
class Linear : public TransformBase {
public:
Linear (const transform_type& transform) : transform (transform) {}
Eigen::Vector3 transform_point (const Eigen::Vector3 &input) {
Eigen::Vector3 output = transform * input;
return output;
}
const transform_type transform;
};
void usage ()
{
AUTHOR = "David Raffelt (david.raffelt@florey.edu.au)";
DESCRIPTION
+ "composes any number of linear transformations and/or warps into a single transformation. "
"The input linear transforms must be supplied in as a 4x4 matrix in a text file (as per the output of mrregister)."
"The input warp fields must be supplied as a 4D image representing a deformation field (as output from mrrregister -nl_warp).";
ARGUMENTS
+ Argument ("input", "the input transforms (either linear or non-linear warps). List transforms in the order you like them to be "
"applied to an image (as if you were applying them seperately with mrtransform).").type_file_in().allow_multiple()
+ Argument ("output", "the output file. If all input transformations are linear, then the output will also be a linear "
"transformation saved as a 4x4 matrix in a text file. If a template image is supplied, then the output will "
"always be a deformation field (see below). If all inputs are warps, or a mix of linear and warps, then the "
"output will be a deformation field defined on the grid of the last input warp supplied.").type_file_out ();
OPTIONS
+ Option ("template", "define the output grid defined by a template image")
+ Argument ("image").type_image_in();
}
typedef float value_type;
void run ()
{
vector<TransformBase*> transform_list;
std::shared_ptr<Header> template_header;
for (size_t i = 0; i < argument.size() - 1; ++i) {
TransformBase* transform (nullptr);
try {
template_header = std::make_shared<Header> (Header::open (argument[i]));
auto image = Image<default_type>::open (argument[i]);
if (image.ndim() != 4)
throw Exception ("input warp is not a 4D image");
if (image.size(3) != 3)
throw Exception ("input warp should have 3 volumes in the 4th dimension");
transform = new Warp (image);
transform_list.push_back (transform);
} catch (Exception& E) {
try {
transform = new Linear (load_transform (argument[i]));
transform_list.push_back (transform);
} catch (Exception& E) {
throw Exception ("error reading input file: " + str(argument[i]) + ". Does not appear to be a 4D warp image or 4x4 linear transform.");
}
}
}
auto opt = get_options("template");
if (opt.size()) {
template_header = std::make_shared<Header> (Header::open (opt[0][0]));
// no template is supplied and there are input warps, then make sure the last transform in the list is a warp
} else if (template_header) {
if (!dynamic_cast<Warp*> (transform_list[transform_list.size() - 1]))
throw Exception ("Output deformation field grid not defined. When composing warps either use the -template "
"option to define the output deformation field grid, or ensure the last input transformation is a warp.");
}
// all inputs are linear so compose and output as text file
if (!template_header) {
transform_type composed = dynamic_cast<Linear*>(transform_list[transform_list.size() - 1])->transform;
ssize_t index = transform_list.size() - 2;
ProgressBar progress ("composing linear transformations", transform_list.size());
progress++;
while (index >= 0) {
composed = dynamic_cast<Linear*>(transform_list[index])->transform * composed;
index--;
progress++;
}
save_transform (composed, argument[argument.size() - 1]);
} else {
Header output_header (*template_header);
output_header.ndim() = 4;
output_header.size(3) = 3;
output_header.datatype() = DataType::Float32;
Image<float> output = Image<value_type>::create (argument [argument.size() - 1], output_header);
Transform template_transform (output);
for (auto i = Loop ("composing transformations", output) (output); i ; ++i) {
Eigen::Vector3 voxel ((default_type) output.index(0),
(default_type) output.index(1),
(default_type) output.index(2));
Eigen::Vector3 position = template_transform.voxel2scanner * voxel;
ssize_t index = transform_list.size() - 1;
while (index >= 0) {
position = transform_list[index]->transform_point (position);
index--;
}
output.row(3) = position;
}
}
}
<commit_msg>transformcompose: fix 2 bugs<commit_after>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include "command.h"
#include "image.h"
#include "algo/threaded_loop.h"
#include "interp/linear.h"
using namespace MR;
using namespace App;
class TransformBase {
public:
virtual ~TransformBase(){}
virtual Eigen::Vector3 transform_point (const Eigen::Vector3& input) = 0;
};
class Warp : public TransformBase {
public:
Warp (Image<default_type>& in) : interp (in) {}
Eigen::Vector3 transform_point (const Eigen::Vector3 &input) {
Eigen::Vector3 output;
if (interp.scanner (input))
output = interp.row(3);
else
output.fill (NaN);
return output;
}
protected:
Interp::Linear<Image<default_type> > interp;
};
class Linear : public TransformBase {
public:
Linear (const transform_type& transform) : transform (transform) {}
Eigen::Vector3 transform_point (const Eigen::Vector3 &input) {
Eigen::Vector3 output = transform * input;
return output;
}
const transform_type transform;
};
void usage ()
{
AUTHOR = "David Raffelt (david.raffelt@florey.edu.au)";
DESCRIPTION
+ "composes any number of linear transformations and/or warps into a single transformation. "
"The input linear transforms must be supplied in as a 4x4 matrix in a text file (as per the output of mrregister)."
"The input warp fields must be supplied as a 4D image representing a deformation field (as output from mrrregister -nl_warp).";
ARGUMENTS
+ Argument ("input", "the input transforms (either linear or non-linear warps). List transforms in the order you like them to be "
"applied to an image (as if you were applying them seperately with mrtransform).").type_file_in().allow_multiple()
+ Argument ("output", "the output file. If all input transformations are linear, then the output will also be a linear "
"transformation saved as a 4x4 matrix in a text file. If a template image is supplied, then the output will "
"always be a deformation field (see below). If all inputs are warps, or a mix of linear and warps, then the "
"output will be a deformation field defined on the grid of the last input warp supplied.").type_file_out ();
OPTIONS
+ Option ("template", "define the output grid defined by a template image")
+ Argument ("image").type_image_in();
}
typedef float value_type;
void run ()
{
vector<TransformBase*> transform_list;
std::shared_ptr<Header> template_header;
for (size_t i = 0; i < argument.size() - 1; ++i) {
TransformBase* transform (nullptr);
try {
template_header = std::make_shared<Header> (Header::open (argument[i]));
auto image = Image<default_type>::open (argument[i]);
if (image.ndim() != 4)
throw Exception ("input warp is not a 4D image");
if (image.size(3) != 3)
throw Exception ("input warp should have 3 volumes in the 4th dimension");
transform = new Warp (image);
transform_list.push_back (transform);
} catch (Exception& E) {
try {
transform = new Linear (load_transform (argument[i]));
transform_list.push_back (transform);
} catch (Exception& E) {
throw Exception ("error reading input file: " + str(argument[i]) + ". Does not appear to be a 4D warp image or 4x4 linear transform.");
}
}
}
auto opt = get_options("template");
if (opt.size()) {
template_header = std::make_shared<Header> (Header::open (opt[0][0]));
// no template is supplied and there are input warps, then make sure the last transform in the list is a warp
} else if (template_header) {
if (!dynamic_cast<Warp*> (transform_list[transform_list.size() - 1]))
throw Exception ("Output deformation field grid not defined. When composing warps either use the -template "
"option to define the output deformation field grid, or ensure the last input transformation is a warp.");
}
// all inputs are linear so compose and output as text file
if (!template_header) {
transform_type composed = dynamic_cast<Linear*>(transform_list[transform_list.size() - 1])->transform;
ssize_t index = transform_list.size() - 2;
ProgressBar progress ("composing linear transformations", transform_list.size());
progress++;
while (index >= 0) {
composed = dynamic_cast<Linear*>(transform_list[index])->transform * composed;
index--;
progress++;
}
save_transform (composed, argument[argument.size() - 1]);
} else {
Header output_header (*template_header);
output_header.ndim() = 4;
output_header.size(3) = 3;
output_header.datatype() = DataType::Float32;
Image<float> output = Image<value_type>::create (argument [argument.size() - 1], output_header);
Transform template_transform (output);
for (auto i = Loop ("composing transformations", output, 0, 3) (output); i ; ++i) {
Eigen::Vector3 voxel ((default_type) output.index(0),
(default_type) output.index(1),
(default_type) output.index(2));
Eigen::Vector3 position = template_transform.voxel2scanner * voxel;
ssize_t index = transform_list.size() - 1;
while (index >= 0) {
position = transform_list[index]->transform_point (position);
index--;
}
output.row(3) = position;
}
}
}
<|endoftext|> |
<commit_before>#include "NotifyGVContactsTable.h"
#include "ContactsParserObject.h"
GVContactsTable::GVContactsTable (QObject *parent)
: QObject (parent)
, nwMgr (this)
, mutex(QMutex::Recursive)
, bLoggedIn(false)
, bRefreshRequested (false)
{
}//GVContactsTable::GVContactsTable
GVContactsTable::~GVContactsTable ()
{
}//GVContactsTable::~GVContactsTable
QNetworkReply *
GVContactsTable::postRequest (QString strUrl,
QStringPairList arrPairs,
QObject *receiver,
const char *method)
{
QStringList arrParams;
foreach (QStringPair pairParam, arrPairs)
{
arrParams += QString("%1=%2")
.arg(pairParam.first)
.arg(pairParam.second);
}
QString strParams = arrParams.join ("&");
QUrl url (strUrl);
QNetworkRequest request(url);
request.setHeader (QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
if (0 != strGoogleAuth.size ())
{
QByteArray byAuth = QString("GoogleLogin auth=%1")
.arg(strGoogleAuth).toAscii ();
request.setRawHeader ("Authorization", byAuth);
}
QByteArray byPostData = strParams.toAscii ();
QObject::connect (&nwMgr , SIGNAL (finished (QNetworkReply *)),
receiver, method);
QNetworkReply *reply = nwMgr.post (request, byPostData);
return (reply);
}//GVContactsTable::postRequest
QNetworkReply *
GVContactsTable::getRequest (QString strUrl,
QObject *receiver,
const char *method)
{
QUrl url (strUrl);
QNetworkRequest request(url);
request.setHeader (QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
if (0 != strGoogleAuth.size ())
{
QByteArray byAuth = QString("GoogleLogin auth=%1")
.arg(strGoogleAuth).toAscii ();
request.setRawHeader ("Authorization", byAuth);
}
QObject::connect (&nwMgr , SIGNAL (finished (QNetworkReply *)),
receiver, method);
QNetworkReply *reply = nwMgr.get (request);
return (reply);
}//GVContactsTable::getRequest
void
GVContactsTable::refreshContacts ()
{
QMutexLocker locker(&mutex);
if (!bLoggedIn)
{
bRefreshRequested = true;
return;
}
bRefreshRequested = false;
bChangedSinceRefresh = false;
QString strUrl = QString ("http://www.google.com/m8/feeds/contacts/%1/full"
"?max-results=10000")
.arg (strUser);
bRefreshIsUpdate = false;
if (dtUpdate.isValid ()) {
QString strUpdate = dtUpdate.toString ("yyyy-MM-dd")
+ "T"
+ dtUpdate.toString ("hh:mm:ss");
strUrl += QString ("&updated-min=%1&showdeleted=true").arg (strUpdate);
bRefreshIsUpdate = true;
}
getRequest (strUrl, this , SLOT (onGotContacts (QNetworkReply *)));
}//GVContactsTable::refreshContacts
void
GVContactsTable::setUserPass (const QString &strU, const QString &strP)
{
QMutexLocker locker(&mutex);
strUser = strU;
strPass = strP;
}//GVContactsTable::setUserPass
void
GVContactsTable::loginSuccess ()
{
QMutexLocker locker(&mutex);
QStringPairList arrPairs;
arrPairs += QStringPair("accountType", "GOOGLE");
arrPairs += QStringPair("Email" , strUser);
arrPairs += QStringPair("Passwd" , strPass);
arrPairs += QStringPair("service" , "cp"); // name for contacts service
arrPairs += QStringPair("source" , "MyCompany-qgvdial-ver01");
postRequest (GV_CLIENTLOGIN, arrPairs,
this , SLOT (onLoginResponse (QNetworkReply *)));
}//GVContactsTable::loginSuccess
void
GVContactsTable::loggedOut ()
{
QMutexLocker locker(&mutex);
bLoggedIn = false;
strGoogleAuth.clear ();
}//GVContactsTable::loggedOut
void
GVContactsTable::onLoginResponse (QNetworkReply *reply)
{
QObject::disconnect (&nwMgr, SIGNAL (finished (QNetworkReply *)),
this , SLOT (onLoginResponse (QNetworkReply *)));
QString msg;
QString strReply = reply->readAll ();
QString strCaptchaToken, strCaptchaUrl;
strGoogleAuth.clear ();
do // Begin cleanup block (not a loop)
{
QStringList arrParsed = strReply.split ('\n');
foreach (QString strPair, arrParsed)
{
QStringList arrPair = strPair.split ('=');
if (arrPair[0] == "Auth")
{
strGoogleAuth = arrPair[1];
}
else if (arrPair[0] == "CaptchaToken")
{
strCaptchaToken = arrPair[1];
}
else if (arrPair[0] == "CaptchaUrl")
{
strCaptchaUrl = arrPair[1];
}
}
if (0 != strCaptchaUrl.size ())
{
qCritical ("Google requested CAPTCHA!!");
qApp->quit ();
break;
}
if (0 == strGoogleAuth.size ())
{
qWarning ("Failed to login!!");
break;
}
QMutexLocker locker (&mutex);
bLoggedIn = true;
if (bRefreshRequested)
{
refreshContacts ();
}
} while (0); // End cleanup block (not a loop)
reply->deleteLater ();
}//GVContactsTable::onLoginResponse
void
GVContactsTable::onGotContacts (QNetworkReply *reply)
{
QObject::disconnect (&nwMgr, SIGNAL (finished (QNetworkReply *)),
this , SLOT (onGotContacts (QNetworkReply *)));
do // Begin cleanup block (not a loop)
{
QByteArray byData = reply->readAll ();
if (byData.contains ("Authorization required"))
{
emit status("Authorization failed.");
break;
}
#if 0
QFile temp("dump.txt");
temp.open (QIODevice::ReadWrite);
temp.write (byData);
temp.close ();
#endif
dtUpdate = QDateTime::currentDateTime().toUTC ();
QThread *workerThread = new QThread(this);
ContactsParserObject *pObj = new ContactsParserObject(byData);
pObj->setEmitLog (false);
pObj->moveToThread (workerThread);
QObject::connect (workerThread, SIGNAL(started()),
pObj , SLOT (doWork()));
QObject::connect (pObj, SIGNAL(done(bool)),
this, SLOT (onContactsParsed(bool)));
QObject::connect (pObj , SIGNAL(done(bool)),
workerThread, SLOT (quit()));
QObject::connect (workerThread, SIGNAL(terminated()),
pObj , SLOT (deleteLater()));
QObject::connect (workerThread, SIGNAL(terminated()),
workerThread, SLOT (deleteLater()));
QObject::connect (pObj, SIGNAL (status(const QString &, int)),
this, SIGNAL (status(const QString &, int)));
QObject::connect (pObj, SIGNAL (gotOneContact (const ContactInfo &)),
this, SLOT (gotOneContact (const ContactInfo &)));
workerThread->start ();
} while (0); // End cleanup block (not a loop)
reply->deleteLater ();
}//GVContactsTable::onGotContacts
void
GVContactsTable::gotOneContact (const ContactInfo & /*contactInfo*/)
{
QMutexLocker locker(&mutex);
bChangedSinceRefresh = true;
}//GVContactsTable::gotOneContact
void
GVContactsTable::onContactsParsed (bool rv)
{
emit allContacts (bChangedSinceRefresh, rv);
}//GVContactsTable::onContactsParsed
<commit_msg>Correction for notify code<commit_after>#include "NotifyGVContactsTable.h"
#include "ContactsParserObject.h"
GVContactsTable::GVContactsTable (QObject *parent)
: QObject (parent)
, nwMgr (this)
, mutex(QMutex::Recursive)
, bLoggedIn(false)
, bRefreshRequested (false)
{
}//GVContactsTable::GVContactsTable
GVContactsTable::~GVContactsTable ()
{
}//GVContactsTable::~GVContactsTable
QNetworkReply *
GVContactsTable::postRequest (QString strUrl,
QStringPairList arrPairs,
QObject *receiver,
const char *method)
{
QStringList arrParams;
foreach (QStringPair pairParam, arrPairs)
{
arrParams += QString("%1=%2")
.arg(pairParam.first)
.arg(pairParam.second);
}
QString strParams = arrParams.join ("&");
QUrl url (strUrl);
QNetworkRequest request(url);
request.setHeader (QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
if (0 != strGoogleAuth.size ())
{
QByteArray byAuth = QString("GoogleLogin auth=%1")
.arg(strGoogleAuth).toAscii ();
request.setRawHeader ("Authorization", byAuth);
}
QByteArray byPostData = strParams.toAscii ();
QObject::connect (&nwMgr , SIGNAL (finished (QNetworkReply *)),
receiver, method);
QNetworkReply *reply = nwMgr.post (request, byPostData);
return (reply);
}//GVContactsTable::postRequest
QNetworkReply *
GVContactsTable::getRequest (QString strUrl,
QObject *receiver,
const char *method)
{
QUrl url (strUrl);
QNetworkRequest request(url);
request.setHeader (QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
if (0 != strGoogleAuth.size ())
{
QByteArray byAuth = QString("GoogleLogin auth=%1")
.arg(strGoogleAuth).toAscii ();
request.setRawHeader ("Authorization", byAuth);
}
QObject::connect (&nwMgr , SIGNAL (finished (QNetworkReply *)),
receiver, method);
QNetworkReply *reply = nwMgr.get (request);
return (reply);
}//GVContactsTable::getRequest
void
GVContactsTable::refreshContacts ()
{
QMutexLocker locker(&mutex);
if (!bLoggedIn)
{
bRefreshRequested = true;
return;
}
bRefreshRequested = false;
bChangedSinceRefresh = false;
QString strUrl = QString ("http://www.google.com/m8/feeds/contacts/%1/full"
"?max-results=10000")
.arg (strUser);
bRefreshIsUpdate = false;
if (dtUpdate.isValid ()) {
QString strUpdate = dtUpdate.toString ("yyyy-MM-dd")
+ "T"
+ dtUpdate.toString ("hh:mm:ss");
strUrl += QString ("&updated-min=%1&showdeleted=true").arg (strUpdate);
bRefreshIsUpdate = true;
}
getRequest (strUrl, this , SLOT (onGotContacts (QNetworkReply *)));
}//GVContactsTable::refreshContacts
void
GVContactsTable::setUserPass (const QString &strU, const QString &strP)
{
QMutexLocker locker(&mutex);
strUser = strU;
strPass = strP;
}//GVContactsTable::setUserPass
void
GVContactsTable::loginSuccess ()
{
QMutexLocker locker(&mutex);
QStringPairList arrPairs;
arrPairs += QStringPair("accountType", "GOOGLE");
arrPairs += QStringPair("Email" , strUser);
arrPairs += QStringPair("Passwd" , strPass);
arrPairs += QStringPair("service" , "cp"); // name for contacts service
arrPairs += QStringPair("source" , "MyCompany-qgvdial-ver01");
postRequest (GV_CLIENTLOGIN, arrPairs,
this , SLOT (onLoginResponse (QNetworkReply *)));
}//GVContactsTable::loginSuccess
void
GVContactsTable::loggedOut ()
{
QMutexLocker locker(&mutex);
bLoggedIn = false;
strGoogleAuth.clear ();
}//GVContactsTable::loggedOut
void
GVContactsTable::onLoginResponse (QNetworkReply *reply)
{
QObject::disconnect (&nwMgr, SIGNAL (finished (QNetworkReply *)),
this , SLOT (onLoginResponse (QNetworkReply *)));
QString msg;
QString strReply = reply->readAll ();
QString strCaptchaToken, strCaptchaUrl;
strGoogleAuth.clear ();
do // Begin cleanup block (not a loop)
{
QStringList arrParsed = strReply.split ('\n');
foreach (QString strPair, arrParsed)
{
QStringList arrPair = strPair.split ('=');
if (arrPair[0] == "Auth")
{
strGoogleAuth = arrPair[1];
}
else if (arrPair[0] == "CaptchaToken")
{
strCaptchaToken = arrPair[1];
}
else if (arrPair[0] == "CaptchaUrl")
{
strCaptchaUrl = arrPair[1];
}
}
if (0 != strCaptchaUrl.size ())
{
qCritical ("Google requested CAPTCHA!!");
qApp->quit ();
break;
}
if (0 == strGoogleAuth.size ())
{
qWarning ("Failed to login!!");
break;
}
QMutexLocker locker (&mutex);
bLoggedIn = true;
if (bRefreshRequested)
{
refreshContacts ();
}
} while (0); // End cleanup block (not a loop)
reply->deleteLater ();
}//GVContactsTable::onLoginResponse
void
GVContactsTable::onGotContacts (QNetworkReply *reply)
{
QObject::disconnect (&nwMgr, SIGNAL (finished (QNetworkReply *)),
this , SLOT (onGotContacts (QNetworkReply *)));
do // Begin cleanup block (not a loop)
{
QByteArray byData = reply->readAll ();
if (byData.contains ("Authorization required"))
{
emit status("Authorization failed.");
break;
}
#if 0
QFile temp("dump.txt");
temp.open (QIODevice::ReadWrite);
temp.write (byData);
temp.close ();
#endif
dtUpdate = QDateTime::currentDateTime().toUTC ();
QThread *workerThread = new QThread(this);
ContactsParserObject *pObj = new ContactsParserObject(byData, strGoogleAuth);
pObj->setEmitLog (false);
pObj->moveToThread (workerThread);
QObject::connect (workerThread, SIGNAL(started()),
pObj , SLOT (doWork()));
QObject::connect (pObj, SIGNAL(done(bool)),
this, SLOT (onContactsParsed(bool)));
QObject::connect (pObj , SIGNAL(done(bool)),
workerThread, SLOT (quit()));
QObject::connect (workerThread, SIGNAL(terminated()),
pObj , SLOT (deleteLater()));
QObject::connect (workerThread, SIGNAL(terminated()),
workerThread, SLOT (deleteLater()));
QObject::connect (pObj, SIGNAL (status(const QString &, int)),
this, SIGNAL (status(const QString &, int)));
QObject::connect (pObj, SIGNAL (gotOneContact (const ContactInfo &)),
this, SLOT (gotOneContact (const ContactInfo &)));
workerThread->start ();
} while (0); // End cleanup block (not a loop)
reply->deleteLater ();
}//GVContactsTable::onGotContacts
void
GVContactsTable::gotOneContact (const ContactInfo & /*contactInfo*/)
{
QMutexLocker locker(&mutex);
bChangedSinceRefresh = true;
}//GVContactsTable::gotOneContact
void
GVContactsTable::onContactsParsed (bool rv)
{
emit allContacts (bChangedSinceRefresh, rv);
}//GVContactsTable::onContactsParsed
<|endoftext|> |
<commit_before>#include "SysConfig.h"
#if(HAS_PCA9539)
#include <CI2C.h>
#include "CPCA9539.h"
#include "CTimer.h"
#include "NDataManager.h"
namespace
{
CTimer pcaSampleTimer;
uint32_t start;
bool toggle;
}
CPCA9539::CPCA9539( CI2C *i2cInterfaceIn )
: m_pca( i2cInterfaceIn )
{
}
void CPCA9539::Initialize()
{
Serial.println( "CPCA9539.Status:INIT;" );
//Timer resets
pcaSampleTimer.Reset();
start = millis();
toggle = true;
//Expander init
m_pca.Initialize();
m_pca.PinMode( OUTPUT );
Serial.println( "CPCA9539.Status:POST_INIT;");
}
void CPCA9539::Update( CCommand &commandIn )
{
if( pcaSampleTimer.HasElapsed( 1000 ) )
{
if( toggle )
{
toggle = false;
auto ret = m_pca.DigitalWriteHex( 0x15 );
Serial.println(ret);
}
else
{
toggle = true;
auto ret = m_pca.DigitalWriteDecimal( 10 );
Serial.println(ret);
}
}
}
#endif<commit_msg>more maths<commit_after>#include "SysConfig.h"
#if(HAS_PCA9539)
#include <CI2C.h>
#include "CPCA9539.h"
#include "CTimer.h"
#include "NDataManager.h"
namespace
{
CTimer pcaSampleTimer;
uint8_t counter;
}
CPCA9539::CPCA9539( CI2C *i2cInterfaceIn )
: m_pca( i2cInterfaceIn )
{
}
void CPCA9539::Initialize()
{
Serial.println( "CPCA9539.Status:INIT;" );
//Timer resets
pcaSampleTimer.Reset();
counter = 0;
//Expander init
m_pca.Initialize();
m_pca.PinMode( OUTPUT );
Serial.println( "CPCA9539.Status:POST_INIT;");
}
void CPCA9539::Update( CCommand &commandIn )
{
if( pcaSampleTimer.HasElapsed( 500 ) )
{
if( counter > 31)
{
counter = 0;
}
auto ret = m_pca.DigitalWriteDecimal( counter );
Serial.println(ret);
}
}
#endif<|endoftext|> |
<commit_before>/* libs/graphics/effects/SkCullPoints.cpp
**
** Copyright 2006, The Android Open Source Project
**
** 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 "SkCullPoints.h"
#include "Sk64.h"
static bool cross_product_is_neg(const SkIPoint& v, int dx, int dy)
{
#if 0
return v.fX * dy - v.fY * dx < 0;
#else
Sk64 tmp0, tmp1;
tmp0.setMul(v.fX, dy);
tmp1.setMul(dx, v.fY);
tmp0.sub(tmp1);
return tmp0.isNeg();
#endif
}
bool SkCullPoints::sect_test(int x0, int y0, int x1, int y1) const
{
const SkIRect& r = fR;
if (x0 < r.fLeft && x1 < r.fLeft ||
x0 > r.fRight && x1 > r.fRight ||
y0 < r.fTop && y1 < r.fTop ||
y0 > r.fBottom && y1 > r.fBottom)
return false;
// since the crossprod test is a little expensive, check for easy-in cases first
if (r.contains(x0, y0) || r.contains(x1, y1))
return true;
// At this point we're not sure, so we do a crossprod test
SkIPoint vec;
const SkIPoint* rAsQuad = fAsQuad;
vec.set(x1 - x0, y1 - y0);
bool isNeg = cross_product_is_neg(vec, x0 - rAsQuad[0].fX, y0 - rAsQuad[0].fY);
for (int i = 1; i < 4; i++) {
if (cross_product_is_neg(vec, x0 - rAsQuad[i].fX, y0 - rAsQuad[i].fY) != isNeg)
{
return true;
}
}
return false; // we didn't intersect
}
static void toQuad(const SkIRect& r, SkIPoint quad[4])
{
SkASSERT(quad);
quad[0].set(r.fLeft, r.fTop);
quad[1].set(r.fRight, r.fTop);
quad[2].set(r.fRight, r.fBottom);
quad[3].set(r.fLeft, r.fBottom);
}
SkCullPoints::SkCullPoints()
{
SkIRect r;
r.setEmpty();
this->reset(r);
}
SkCullPoints::SkCullPoints(const SkIRect& r)
{
this->reset(r);
}
void SkCullPoints::reset(const SkIRect& r)
{
fR = r;
toQuad(fR, fAsQuad);
fPrevPt.set(0, 0);
fPrevResult = kNo_Result;
}
void SkCullPoints::moveTo(int x, int y)
{
fPrevPt.set(x, y);
fPrevResult = kNo_Result; // so we trigger a movetolineto later
}
SkCullPoints::LineToResult SkCullPoints::lineTo(int x, int y, SkIPoint line[])
{
SkASSERT(line != NULL);
LineToResult result = kNo_Result;
int x0 = fPrevPt.fX;
int y0 = fPrevPt.fY;
// need to upgrade sect_test to chop the result
// and to correctly return kLineTo_Result when the result is connected
// to the previous call-out
if (this->sect_test(x0, y0, x, y))
{
line[0].set(x0, y0);
line[1].set(x, y);
if (fPrevResult != kNo_Result && fPrevPt.equals(x0, y0))
result = kLineTo_Result;
else
result = kMoveToLineTo_Result;
}
fPrevPt.set(x, y);
fPrevResult = result;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkPath.h"
SkCullPointsPath::SkCullPointsPath()
: fCP(), fPath(NULL)
{
}
SkCullPointsPath::SkCullPointsPath(const SkIRect& r, SkPath* dst)
: fCP(r), fPath(dst)
{
}
void SkCullPointsPath::reset(const SkIRect& r, SkPath* dst)
{
fCP.reset(r);
fPath = dst;
}
void SkCullPointsPath::moveTo(int x, int y)
{
fCP.moveTo(x, y);
}
void SkCullPointsPath::lineTo(int x, int y)
{
SkIPoint pts[2];
switch (fCP.lineTo(x, y, pts)) {
case SkCullPoints::kMoveToLineTo_Result:
fPath->moveTo(SkIntToScalar(pts[0].fX), SkIntToScalar(pts[0].fY));
// fall through to the lineto case
case SkCullPoints::kLineTo_Result:
fPath->lineTo(SkIntToScalar(pts[1].fX), SkIntToScalar(pts[1].fY));
break;
default:
break;
}
}
<commit_msg>Linux: GCC 4.3 warning fixes<commit_after>/* libs/graphics/effects/SkCullPoints.cpp
**
** Copyright 2006, The Android Open Source Project
**
** 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 "SkCullPoints.h"
#include "Sk64.h"
static bool cross_product_is_neg(const SkIPoint& v, int dx, int dy)
{
#if 0
return v.fX * dy - v.fY * dx < 0;
#else
Sk64 tmp0, tmp1;
tmp0.setMul(v.fX, dy);
tmp1.setMul(dx, v.fY);
tmp0.sub(tmp1);
return tmp0.isNeg();
#endif
}
bool SkCullPoints::sect_test(int x0, int y0, int x1, int y1) const
{
const SkIRect& r = fR;
if ((x0 < r.fLeft && x1 < r.fLeft) ||
(x0 > r.fRight && x1 > r.fRight) ||
(y0 < r.fTop && y1 < r.fTop) ||
(y0 > r.fBottom && y1 > r.fBottom))
return false;
// since the crossprod test is a little expensive, check for easy-in cases first
if (r.contains(x0, y0) || r.contains(x1, y1))
return true;
// At this point we're not sure, so we do a crossprod test
SkIPoint vec;
const SkIPoint* rAsQuad = fAsQuad;
vec.set(x1 - x0, y1 - y0);
bool isNeg = cross_product_is_neg(vec, x0 - rAsQuad[0].fX, y0 - rAsQuad[0].fY);
for (int i = 1; i < 4; i++) {
if (cross_product_is_neg(vec, x0 - rAsQuad[i].fX, y0 - rAsQuad[i].fY) != isNeg)
{
return true;
}
}
return false; // we didn't intersect
}
static void toQuad(const SkIRect& r, SkIPoint quad[4])
{
SkASSERT(quad);
quad[0].set(r.fLeft, r.fTop);
quad[1].set(r.fRight, r.fTop);
quad[2].set(r.fRight, r.fBottom);
quad[3].set(r.fLeft, r.fBottom);
}
SkCullPoints::SkCullPoints()
{
SkIRect r;
r.setEmpty();
this->reset(r);
}
SkCullPoints::SkCullPoints(const SkIRect& r)
{
this->reset(r);
}
void SkCullPoints::reset(const SkIRect& r)
{
fR = r;
toQuad(fR, fAsQuad);
fPrevPt.set(0, 0);
fPrevResult = kNo_Result;
}
void SkCullPoints::moveTo(int x, int y)
{
fPrevPt.set(x, y);
fPrevResult = kNo_Result; // so we trigger a movetolineto later
}
SkCullPoints::LineToResult SkCullPoints::lineTo(int x, int y, SkIPoint line[])
{
SkASSERT(line != NULL);
LineToResult result = kNo_Result;
int x0 = fPrevPt.fX;
int y0 = fPrevPt.fY;
// need to upgrade sect_test to chop the result
// and to correctly return kLineTo_Result when the result is connected
// to the previous call-out
if (this->sect_test(x0, y0, x, y))
{
line[0].set(x0, y0);
line[1].set(x, y);
if (fPrevResult != kNo_Result && fPrevPt.equals(x0, y0))
result = kLineTo_Result;
else
result = kMoveToLineTo_Result;
}
fPrevPt.set(x, y);
fPrevResult = result;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkPath.h"
SkCullPointsPath::SkCullPointsPath()
: fCP(), fPath(NULL)
{
}
SkCullPointsPath::SkCullPointsPath(const SkIRect& r, SkPath* dst)
: fCP(r), fPath(dst)
{
}
void SkCullPointsPath::reset(const SkIRect& r, SkPath* dst)
{
fCP.reset(r);
fPath = dst;
}
void SkCullPointsPath::moveTo(int x, int y)
{
fCP.moveTo(x, y);
}
void SkCullPointsPath::lineTo(int x, int y)
{
SkIPoint pts[2];
switch (fCP.lineTo(x, y, pts)) {
case SkCullPoints::kMoveToLineTo_Result:
fPath->moveTo(SkIntToScalar(pts[0].fX), SkIntToScalar(pts[0].fY));
// fall through to the lineto case
case SkCullPoints::kLineTo_Result:
fPath->lineTo(SkIntToScalar(pts[1].fX), SkIntToScalar(pts[1].fY));
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "state.h"
#include "../../common/lexers/streamfilters.h"
namespace embree
{
/* error flag */
tls_t State::g_error = nullptr; // FIXME: use thread local
std::vector<RTCError*> State::g_errors; // FIXME: use thread local
MutexSys State::g_errors_mutex;
State State::state;
State::State () {
clear();
}
void State::clear()
{
tri_accel = "default";
tri_builder = "default";
tri_traverser = "default";
tri_builder_replication_factor = 2.0f;
tri_accel_mb = "default";
tri_builder_mb = "default";
tri_traverser_mb = "default";
hair_accel = "default";
hair_builder = "default";
hair_traverser = "default";
hair_builder_replication_factor = 3.0f;
memory_preallocation_factor = 1.0f;
tessellation_cache_size = 0;
subdiv_accel = "default";
scene_flags = -1;
verbose = 0;
benchmark = 0;
regression_testing = 0;
g_numThreads = 0;
#if TASKING_TBB_INTERNAL || defined(__MIC__)
set_affinity = true;
#else
set_affinity = false;
#endif
{
Lock<MutexSys> lock(g_errors_mutex);
if (g_error == nullptr)
g_error = createTls();
}
g_error_function = nullptr;
g_memory_monitor_function = nullptr;
//Lock<MutexSys> lock(g_errors_mutex);
// for (size_t i=0; i<g_errors.size(); i++)
// delete g_errors[i];
// destroyTls(g_error);
// g_errors.clear();
}
const char* symbols[3] = { "=", ",", "|" };
bool State::parseFile(const FileName& fileName)
{
FILE* f = fopen(fileName.c_str(),"r");
if (f == nullptr) return false;
Ref<Stream<int> > file = new FileStream(f,fileName);
std::vector<std::string> syms;
for (size_t i=0; i<sizeof(symbols)/sizeof(void*); i++)
syms.push_back(symbols[i]);
Ref<TokenStream> cin = new TokenStream(new LineCommentFilter(file,"#"),
TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
TokenStream::separators,syms);
parse(cin);
return true;
}
void State::parseString(const char* cfg)
{
if (cfg == nullptr) return;
std::vector<std::string> syms;
for (size_t i=0; i<sizeof(symbols)/sizeof(void*); i++)
syms.push_back(symbols[i]);
Ref<TokenStream> cin = new TokenStream(new StrStream(cfg),
TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
TokenStream::separators,syms);
parse(cin);
}
void State::parse(Ref<TokenStream> cin)
{
/* parse until end of stream */
while (cin->peek() != Token::Eof())
{
const Token tok = cin->get();
if (tok == Token::Id("threads") && cin->trySymbol("="))
g_numThreads = cin->get().Int();
else if (tok == Token::Id("set_affinity"))
set_affinity = cin->get().Int();
else if (tok == Token::Id("isa") && cin->trySymbol("="))
{
std::string isa = cin->get().Identifier();
if (isa == "sse" ) setCPUFeatures(SSE);
else if (isa == "sse2") setCPUFeatures(SSE2);
else if (isa == "sse3") setCPUFeatures(SSE3);
else if (isa == "ssse3") setCPUFeatures(SSSE3);
else if (isa == "sse41") setCPUFeatures(SSE41);
else if (isa == "sse4.1") setCPUFeatures(SSE41);
else if (isa == "sse42") setCPUFeatures(SSE42);
else if (isa == "sse4.2") setCPUFeatures(SSE42);
else if (isa == "avx") setCPUFeatures(AVX);
else if (isa == "int8") setCPUFeatures(AVXI);
else if (isa == "avx2") setCPUFeatures(AVX2);
}
else if (tok == Token::Id("float_exceptions") && cin->trySymbol("="))
float_exceptions = cin->get().Int();
else if ((tok == Token::Id("tri_accel") || tok == Token::Id("accel")) && cin->trySymbol("="))
tri_accel = cin->get().Identifier();
else if ((tok == Token::Id("tri_builder") || tok == Token::Id("builder")) && cin->trySymbol("="))
tri_builder = cin->get().Identifier();
else if ((tok == Token::Id("tri_traverser") || tok == Token::Id("traverser")) && cin->trySymbol("="))
tri_traverser = cin->get().Identifier();
else if (tok == Token::Id("tri_builder_replication_factor") && cin->trySymbol("="))
tri_builder_replication_factor = cin->get().Int();
else if ((tok == Token::Id("tri_accel_mb") || tok == Token::Id("accel_mb")) && cin->trySymbol("="))
tri_accel_mb = cin->get().Identifier();
else if ((tok == Token::Id("tri_builder_mb") || tok == Token::Id("builder_mb")) && cin->trySymbol("="))
tri_builder_mb = cin->get().Identifier();
else if ((tok == Token::Id("tri_traverser_mb") || tok == Token::Id("traverser_mb")) && cin->trySymbol("="))
tri_traverser_mb = cin->get().Identifier();
else if (tok == Token::Id("hair_accel") && cin->trySymbol("="))
hair_accel = cin->get().Identifier();
else if (tok == Token::Id("hair_builder") && cin->trySymbol("="))
hair_builder = cin->get().Identifier();
else if (tok == Token::Id("hair_traverser") && cin->trySymbol("="))
hair_traverser = cin->get().Identifier();
else if (tok == Token::Id("hair_builder_replication_factor") && cin->trySymbol("="))
hair_builder_replication_factor = cin->get().Int();
else if (tok == Token::Id("subdiv_accel") && cin->trySymbol("="))
subdiv_accel = cin->get().Identifier();
else if (tok == Token::Id("verbose") && cin->trySymbol("="))
verbose = cin->get().Int();
else if (tok == Token::Id("benchmark") && cin->trySymbol("="))
benchmark = cin->get().Int();
else if (tok == Token::Id("flags")) {
scene_flags = 0;
if (cin->trySymbol("=")) {
do {
Token flag = cin->get();
if (flag == Token::Id("static") ) scene_flags |= RTC_SCENE_STATIC;
else if (flag == Token::Id("dynamic")) scene_flags |= RTC_SCENE_DYNAMIC;
else if (flag == Token::Id("compact")) scene_flags |= RTC_SCENE_COMPACT;
else if (flag == Token::Id("coherent")) scene_flags |= RTC_SCENE_COHERENT;
else if (flag == Token::Id("incoherent")) scene_flags |= RTC_SCENE_INCOHERENT;
else if (flag == Token::Id("high_quality")) scene_flags |= RTC_SCENE_HIGH_QUALITY;
else if (flag == Token::Id("robust")) scene_flags |= RTC_SCENE_ROBUST;
} while (cin->trySymbol("|"));
}
}
else if (tok == Token::Id("memory_preallocation_factor") && cin->trySymbol("="))
memory_preallocation_factor = cin->get().Float();
else if (tok == Token::Id("regression") && cin->trySymbol("="))
regression_testing = cin->get().Int();
else if (tok == Token::Id("tessellation_cache_size") && cin->trySymbol("="))
tessellation_cache_size = cin->get().Float() * 1024 * 1024;
cin->trySymbol(","); // optional , separator
}
}
RTCError* State::error()
{
RTCError* stored_error = (RTCError*) getTls(g_error);
if (stored_error == nullptr) {
Lock<MutexSys> lock(g_errors_mutex);
stored_error = new RTCError(RTC_NO_ERROR);
g_errors.push_back(stored_error);
setTls(g_error,stored_error);
}
return stored_error;
}
bool State::verbosity(int N) {
return N <= verbose;
}
void State::print()
{
std::cout << "general:" << std::endl;
std::cout << " build threads = " << g_numThreads << std::endl;
std::cout << " verbosity = " << verbose << std::endl;
std::cout << "triangles:" << std::endl;
std::cout << " accel = " << tri_accel << std::endl;
std::cout << " builder = " << tri_builder << std::endl;
std::cout << " traverser = " << tri_traverser << std::endl;
std::cout << " replications = " << tri_builder_replication_factor << std::endl;
std::cout << "motion blur triangles:" << std::endl;
std::cout << " accel = " << tri_accel_mb << std::endl;
std::cout << " builder = " << tri_builder_mb << std::endl;
std::cout << " traverser = " << tri_traverser_mb << std::endl;
std::cout << "hair:" << std::endl;
std::cout << " accel = " << hair_accel << std::endl;
std::cout << " builder = " << hair_builder << std::endl;
std::cout << " traverser = " << hair_traverser << std::endl;
std::cout << " replications = " << hair_builder_replication_factor << std::endl;
std::cout << "subdivision surfaces:" << std::endl;
std::cout << " accel = " << subdiv_accel << std::endl;
#if defined(__MIC__)
std::cout << "memory allocation:" << std::endl;
std::cout << " preallocation_factor = " << memory_preallocation_factor << std::endl;
#endif
}
}
<commit_msg>added max_isa option to rtcInit<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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 "state.h"
#include "../../common/lexers/streamfilters.h"
namespace embree
{
/* error flag */
tls_t State::g_error = nullptr; // FIXME: use thread local
std::vector<RTCError*> State::g_errors; // FIXME: use thread local
MutexSys State::g_errors_mutex;
State State::state;
State::State () {
clear();
}
void State::clear()
{
tri_accel = "default";
tri_builder = "default";
tri_traverser = "default";
tri_builder_replication_factor = 2.0f;
tri_accel_mb = "default";
tri_builder_mb = "default";
tri_traverser_mb = "default";
hair_accel = "default";
hair_builder = "default";
hair_traverser = "default";
hair_builder_replication_factor = 3.0f;
memory_preallocation_factor = 1.0f;
tessellation_cache_size = 0;
subdiv_accel = "default";
scene_flags = -1;
verbose = 0;
benchmark = 0;
regression_testing = 0;
g_numThreads = 0;
#if TASKING_TBB_INTERNAL || defined(__MIC__)
set_affinity = true;
#else
set_affinity = false;
#endif
{
Lock<MutexSys> lock(g_errors_mutex);
if (g_error == nullptr)
g_error = createTls();
}
g_error_function = nullptr;
g_memory_monitor_function = nullptr;
//Lock<MutexSys> lock(g_errors_mutex);
// for (size_t i=0; i<g_errors.size(); i++)
// delete g_errors[i];
// destroyTls(g_error);
// g_errors.clear();
}
const char* symbols[3] = { "=", ",", "|" };
bool State::parseFile(const FileName& fileName)
{
FILE* f = fopen(fileName.c_str(),"r");
if (f == nullptr) return false;
Ref<Stream<int> > file = new FileStream(f,fileName);
std::vector<std::string> syms;
for (size_t i=0; i<sizeof(symbols)/sizeof(void*); i++)
syms.push_back(symbols[i]);
Ref<TokenStream> cin = new TokenStream(new LineCommentFilter(file,"#"),
TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
TokenStream::separators,syms);
parse(cin);
return true;
}
void State::parseString(const char* cfg)
{
if (cfg == nullptr) return;
std::vector<std::string> syms;
for (size_t i=0; i<sizeof(symbols)/sizeof(void*); i++)
syms.push_back(symbols[i]);
Ref<TokenStream> cin = new TokenStream(new StrStream(cfg),
TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
TokenStream::separators,syms);
parse(cin);
}
int string_to_cpufeatures(const std::string& isa)
{
if (isa == "sse" ) return SSE;
else if (isa == "sse2") return SSE2;
else if (isa == "sse3") return SSE3;
else if (isa == "ssse3") return SSSE3;
else if (isa == "sse41") return SSE41;
else if (isa == "sse4.1") return SSE41;
else if (isa == "sse42") return SSE42;
else if (isa == "sse4.2") return SSE42;
else if (isa == "avx") return AVX;
else if (isa == "avxi") return AVXI;
else if (isa == "avx2") return AVX2;
else return SSE2;
}
void State::parse(Ref<TokenStream> cin)
{
/* parse until end of stream */
while (cin->peek() != Token::Eof())
{
const Token tok = cin->get();
if (tok == Token::Id("threads") && cin->trySymbol("="))
g_numThreads = cin->get().Int();
else if (tok == Token::Id("set_affinity"))
set_affinity = cin->get().Int();
else if (tok == Token::Id("isa") && cin->trySymbol("=")) {
std::string isa = strlwr(cin->get().Identifier());
setCPUFeatures(string_to_cpufeatures(isa));
}
else if (tok == Token::Id("max_isa") && cin->trySymbol("=")) {
std::string isa = strlwr(cin->get().Identifier());
setCPUFeatures(getCPUFeatures() & string_to_cpufeatures(isa));
}
else if (tok == Token::Id("float_exceptions") && cin->trySymbol("="))
float_exceptions = cin->get().Int();
else if ((tok == Token::Id("tri_accel") || tok == Token::Id("accel")) && cin->trySymbol("="))
tri_accel = cin->get().Identifier();
else if ((tok == Token::Id("tri_builder") || tok == Token::Id("builder")) && cin->trySymbol("="))
tri_builder = cin->get().Identifier();
else if ((tok == Token::Id("tri_traverser") || tok == Token::Id("traverser")) && cin->trySymbol("="))
tri_traverser = cin->get().Identifier();
else if (tok == Token::Id("tri_builder_replication_factor") && cin->trySymbol("="))
tri_builder_replication_factor = cin->get().Int();
else if ((tok == Token::Id("tri_accel_mb") || tok == Token::Id("accel_mb")) && cin->trySymbol("="))
tri_accel_mb = cin->get().Identifier();
else if ((tok == Token::Id("tri_builder_mb") || tok == Token::Id("builder_mb")) && cin->trySymbol("="))
tri_builder_mb = cin->get().Identifier();
else if ((tok == Token::Id("tri_traverser_mb") || tok == Token::Id("traverser_mb")) && cin->trySymbol("="))
tri_traverser_mb = cin->get().Identifier();
else if (tok == Token::Id("hair_accel") && cin->trySymbol("="))
hair_accel = cin->get().Identifier();
else if (tok == Token::Id("hair_builder") && cin->trySymbol("="))
hair_builder = cin->get().Identifier();
else if (tok == Token::Id("hair_traverser") && cin->trySymbol("="))
hair_traverser = cin->get().Identifier();
else if (tok == Token::Id("hair_builder_replication_factor") && cin->trySymbol("="))
hair_builder_replication_factor = cin->get().Int();
else if (tok == Token::Id("subdiv_accel") && cin->trySymbol("="))
subdiv_accel = cin->get().Identifier();
else if (tok == Token::Id("verbose") && cin->trySymbol("="))
verbose = cin->get().Int();
else if (tok == Token::Id("benchmark") && cin->trySymbol("="))
benchmark = cin->get().Int();
else if (tok == Token::Id("flags")) {
scene_flags = 0;
if (cin->trySymbol("=")) {
do {
Token flag = cin->get();
if (flag == Token::Id("static") ) scene_flags |= RTC_SCENE_STATIC;
else if (flag == Token::Id("dynamic")) scene_flags |= RTC_SCENE_DYNAMIC;
else if (flag == Token::Id("compact")) scene_flags |= RTC_SCENE_COMPACT;
else if (flag == Token::Id("coherent")) scene_flags |= RTC_SCENE_COHERENT;
else if (flag == Token::Id("incoherent")) scene_flags |= RTC_SCENE_INCOHERENT;
else if (flag == Token::Id("high_quality")) scene_flags |= RTC_SCENE_HIGH_QUALITY;
else if (flag == Token::Id("robust")) scene_flags |= RTC_SCENE_ROBUST;
} while (cin->trySymbol("|"));
}
}
else if (tok == Token::Id("memory_preallocation_factor") && cin->trySymbol("="))
memory_preallocation_factor = cin->get().Float();
else if (tok == Token::Id("regression") && cin->trySymbol("="))
regression_testing = cin->get().Int();
else if (tok == Token::Id("tessellation_cache_size") && cin->trySymbol("="))
tessellation_cache_size = cin->get().Float() * 1024 * 1024;
cin->trySymbol(","); // optional , separator
}
}
RTCError* State::error()
{
RTCError* stored_error = (RTCError*) getTls(g_error);
if (stored_error == nullptr) {
Lock<MutexSys> lock(g_errors_mutex);
stored_error = new RTCError(RTC_NO_ERROR);
g_errors.push_back(stored_error);
setTls(g_error,stored_error);
}
return stored_error;
}
bool State::verbosity(int N) {
return N <= verbose;
}
void State::print()
{
std::cout << "general:" << std::endl;
std::cout << " build threads = " << g_numThreads << std::endl;
std::cout << " verbosity = " << verbose << std::endl;
std::cout << "triangles:" << std::endl;
std::cout << " accel = " << tri_accel << std::endl;
std::cout << " builder = " << tri_builder << std::endl;
std::cout << " traverser = " << tri_traverser << std::endl;
std::cout << " replications = " << tri_builder_replication_factor << std::endl;
std::cout << "motion blur triangles:" << std::endl;
std::cout << " accel = " << tri_accel_mb << std::endl;
std::cout << " builder = " << tri_builder_mb << std::endl;
std::cout << " traverser = " << tri_traverser_mb << std::endl;
std::cout << "hair:" << std::endl;
std::cout << " accel = " << hair_accel << std::endl;
std::cout << " builder = " << hair_builder << std::endl;
std::cout << " traverser = " << hair_traverser << std::endl;
std::cout << " replications = " << hair_builder_replication_factor << std::endl;
std::cout << "subdivision surfaces:" << std::endl;
std::cout << " accel = " << subdiv_accel << std::endl;
#if defined(__MIC__)
std::cout << "memory allocation:" << std::endl;
std::cout << " preallocation_factor = " << memory_preallocation_factor << std::endl;
#endif
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003-2007 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/Log.h"
#include "base/util/utils.h"
#include <unistd.h>
Log LOG = Log(false);
char logmsg[512];
static FILE* logFile = NULL;
static BOOL logFileStdout = FALSE;
static char logName[1024] = LOG_NAME;
static char logPath[1024] = "/tmp" ;
static BOOL logRedirectStderr = FALSE;
// a copy of stderr before it was redirected
static int fderr = -1;
void setLogFile(const char *path, const char* name, BOOL redirectStderr) {
if (logName != name) {
strncpy(logName, name ? name : "", sizeof(logName));
logName[sizeof(logName) - 1] = 0;
}
if (logPath != path) {
strncpy(logPath, path ? path : "", sizeof(logPath));
logPath[sizeof(logPath) - 1] = 0;
}
logRedirectStderr = redirectStderr;
if (logFile) {
fclose(logFile);
logFile = NULL;
}
logFileStdout = FALSE;
if (!strcmp(name, "-")) {
// write to stdout
logFileStdout = TRUE;
} else if (path) {
char *filename = new char[strlen(path) + strlen(name) + 3];
sprintf(filename, "%s/%s", path, name);
logFile = fopen(filename, "a+" );
delete [] filename;
} else {
logFile = fopen(name, "a+" );
}
if (redirectStderr && logFile) {
if (fderr == -1) {
// remember original stderr
fderr = dup(2);
}
// overwrite stderr with log file fd,
// closing the current stderr if necessary
dup2(fileno(logFile), 2);
} else {
if (fderr != -1) {
// restore original stderr
dup2(fderr, 2);
}
}
}
void setLogFile(const char* name, BOOL redirectStderr)
{
setLogFile(0, name, redirectStderr);
}
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
static char* createCurrentTime(BOOL complete) {
time_t t = time(NULL);
struct tm *sys_time = localtime(&t);
char *fmtComplete = "%04d-%02d-%02d %02d:%02d:%02d GMT %c%d:%02d";
char *fmt = "%02d:%02d:%02d GMT %c%d:%02d";
char* ret = new char [64];
// calculate offset from UTC/GMT in hours:min, positive value means east of Greenwich (e.g. CET = GMT +1)
char direction = timezone < 0 ? '+' : '-';
long seconds = labs(timezone);
int hours = seconds / 60 / 60;
int minutes = (seconds / 60) % 60;
if (complete) {
sprintf(ret, fmtComplete, sys_time->tm_year, sys_time->tm_mon, sys_time->tm_mday,
sys_time->tm_hour, sys_time->tm_min, sys_time->tm_sec,
direction, hours, minutes);
} else {
sprintf(ret, fmt, sys_time->tm_hour, sys_time->tm_min, sys_time->tm_sec,
direction, hours, minutes);
}
return ret;
}
//---------------------------------------------------------------------- Constructors
Log::Log(BOOL resetLog, const char* path, const char* name) {
setLogPath(path);
setLogName(name);
if (resetLog) {
reset();
}
}
Log::~Log() {
if (logFile != NULL) {
fclose(logFile);
}
}
//---------------------------------------------------------------------- Public methods
void Log::setLogPath(const char* configLogPath) {
if (configLogPath != NULL) {
sprintf(logPath, "%s/", configLogPath);
} else {
sprintf(logPath, "%s", "./");
}
}
void Log::setLogName(const char* configLogName) {
if (configLogName != NULL) {
sprintf(logName, "%s", configLogName);
}
else {
sprintf(logName, "%s", LOG_NAME);
}
}
void Log::error(const char* msg, ...) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_ERROR, msg, argList);
va_end(argList);
}
void Log::info(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_INFO) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_INFO, msg, argList);
va_end(argList);
}
}
void Log::debug(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_DEBUG) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void Log::trace(const char* msg) {
}
void Log::setLevel(LogLevel level) {
logLevel = level;
}
LogLevel Log::getLevel() {
return logLevel;
}
BOOL Log::isLoggable(LogLevel level) {
return (level >= logLevel);
}
void Log::printMessage(const char* level, const char* msg, va_list argList) {
char* currentTime = NULL;
currentTime = createCurrentTime(false);
if (!logFileStdout && !logFile) {
reset();
}
FILE *out = logFile ? logFile : stdout ;
fprintf(out, "%s [%s] - ", currentTime, level );
vfprintf(out, msg, argList);
fputs("\n", out);
fflush(out);
delete[] currentTime;
}
void Log::reset(const char* title) {
setLogFile(logPath, logName, logRedirectStderr);
if (logFile) {
ftruncate(fileno(logFile), 0);
}
}
<commit_msg>use strftime() to format times: - shorter - more portable than "timezone" check - automatically takes summer savings time into account (the old code didn't!)<commit_after>/*
* Copyright (C) 2003-2007 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/Log.h"
#include "base/util/utils.h"
#include <unistd.h>
Log LOG = Log(false);
char logmsg[512];
static FILE* logFile = NULL;
static BOOL logFileStdout = FALSE;
static char logName[1024] = LOG_NAME;
static char logPath[1024] = "/tmp" ;
static BOOL logRedirectStderr = FALSE;
// a copy of stderr before it was redirected
static int fderr = -1;
void setLogFile(const char *path, const char* name, BOOL redirectStderr) {
if (logName != name) {
strncpy(logName, name ? name : "", sizeof(logName));
logName[sizeof(logName) - 1] = 0;
}
if (logPath != path) {
strncpy(logPath, path ? path : "", sizeof(logPath));
logPath[sizeof(logPath) - 1] = 0;
}
logRedirectStderr = redirectStderr;
if (logFile) {
fclose(logFile);
logFile = NULL;
}
logFileStdout = FALSE;
if (!strcmp(name, "-")) {
// write to stdout
logFileStdout = TRUE;
} else if (path) {
char *filename = new char[strlen(path) + strlen(name) + 3];
sprintf(filename, "%s/%s", path, name);
logFile = fopen(filename, "a+" );
delete [] filename;
} else {
logFile = fopen(name, "a+" );
}
if (redirectStderr && logFile) {
if (fderr == -1) {
// remember original stderr
fderr = dup(2);
}
// overwrite stderr with log file fd,
// closing the current stderr if necessary
dup2(fileno(logFile), 2);
} else {
if (fderr != -1) {
// restore original stderr
dup2(fderr, 2);
}
}
}
void setLogFile(const char* name, BOOL redirectStderr)
{
setLogFile(0, name, redirectStderr);
}
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
static char* createCurrentTime(BOOL complete) {
time_t t = time(NULL);
struct tm *sys_time = localtime(&t);
const size_t len = 64;
char *ret = new char [len];
if (complete) {
strftime(ret, len, "%F %T GMT %z", sys_time);
} else {
strftime(ret, len, "%T GMT %z", sys_time);
}
return ret;
}
//---------------------------------------------------------------------- Constructors
Log::Log(BOOL resetLog, const char* path, const char* name) {
setLogPath(path);
setLogName(name);
if (resetLog) {
reset();
}
}
Log::~Log() {
if (logFile != NULL) {
fclose(logFile);
}
}
//---------------------------------------------------------------------- Public methods
void Log::setLogPath(const char* configLogPath) {
if (configLogPath != NULL) {
sprintf(logPath, "%s/", configLogPath);
} else {
sprintf(logPath, "%s", "./");
}
}
void Log::setLogName(const char* configLogName) {
if (configLogName != NULL) {
sprintf(logName, "%s", configLogName);
}
else {
sprintf(logName, "%s", LOG_NAME);
}
}
void Log::error(const char* msg, ...) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_ERROR, msg, argList);
va_end(argList);
}
void Log::info(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_INFO) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_INFO, msg, argList);
va_end(argList);
}
}
void Log::debug(const char* msg, ...) {
if (logLevel >= LOG_LEVEL_DEBUG) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void Log::trace(const char* msg) {
}
void Log::setLevel(LogLevel level) {
logLevel = level;
}
LogLevel Log::getLevel() {
return logLevel;
}
BOOL Log::isLoggable(LogLevel level) {
return (level >= logLevel);
}
void Log::printMessage(const char* level, const char* msg, va_list argList) {
char* currentTime = NULL;
currentTime = createCurrentTime(false);
if (!logFileStdout && !logFile) {
reset();
}
FILE *out = logFile ? logFile : stdout ;
fprintf(out, "%s [%s] - ", currentTime, level );
vfprintf(out, msg, argList);
fputs("\n", out);
fflush(out);
delete[] currentTime;
}
void Log::reset(const char* title) {
setLogFile(logPath, logName, logRedirectStderr);
if (logFile) {
ftruncate(fileno(logFile), 0);
}
}
<|endoftext|> |
<commit_before>/* libs/graphics/effects/SkCullPoints.cpp
**
** Copyright 2006, Google 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 "SkCullPoints.h"
#include "Sk64.h"
static bool cross_product_is_neg(const SkIPoint& v, int dx, int dy)
{
#if 0
return v.fX * dy - v.fY * dx < 0;
#else
Sk64 tmp0, tmp1;
tmp0.setMul(v.fX, dy);
tmp1.setMul(dx, v.fY);
tmp0.sub(tmp1);
return tmp0.isNeg();
#endif
}
bool SkCullPoints::sect_test(int x0, int y0, int x1, int y1) const
{
const SkIRect& r = fR;
if (x0 < r.fLeft && x1 < r.fLeft ||
x0 > r.fRight && x1 > r.fRight ||
y0 < r.fTop && y1 < r.fTop ||
y0 > r.fBottom && y1 > r.fBottom)
return false;
// since the crossprod test is a little expensive, check for easy-in cases first
if (r.contains(x0, y0) || r.contains(x1, y1))
return true;
// At this point we're not sure, so we do a crossprod test
SkIPoint vec;
const SkIPoint* rAsQuad = fAsQuad;
vec.set(x1 - x0, y1 - y0);
bool isNeg = cross_product_is_neg(vec, x0 - rAsQuad[0].fX, y0 - rAsQuad[0].fY);
for (int i = 1; i < 4; i++) {
if (cross_product_is_neg(vec, x0 - rAsQuad[i].fX, y0 - rAsQuad[i].fY) != isNeg)
{
return true;
}
}
return false; // we didn't intersect
}
static void toQuad(const SkIRect& r, SkIPoint quad[4])
{
SkASSERT(quad);
quad[0].set(r.fLeft, r.fTop);
quad[1].set(r.fRight, r.fTop);
quad[2].set(r.fRight, r.fBottom);
quad[3].set(r.fLeft, r.fBottom);
}
SkCullPoints::SkCullPoints()
{
SkIRect r;
r.setEmpty();
this->reset(r);
}
SkCullPoints::SkCullPoints(const SkIRect& r)
{
this->reset(r);
}
void SkCullPoints::reset(const SkIRect& r)
{
fR = r;
toQuad(fR, fAsQuad);
fPrevPt.set(0, 0);
fPrevResult = kNo_Result;
}
void SkCullPoints::moveTo(int x, int y)
{
fPrevPt.set(x, y);
fPrevResult = kNo_Result; // so we trigger a movetolineto later
}
SkCullPoints::LineToResult SkCullPoints::lineTo(int x, int y, SkIPoint line[])
{
SkASSERT(line != NULL);
LineToResult result = kNo_Result;
int x0 = fPrevPt.fX;
int y0 = fPrevPt.fY;
// need to upgrade sect_test to chop the result
// and to correctly return kLineTo_Result when the result is connected
// to the previous call-out
if (this->sect_test(x0, y0, x, y))
{
line[0].set(x0, y0);
line[1].set(x, y);
if (fPrevResult != kNo_Result && fPrevPt.equals(x0, y0))
result = kLineTo_Result;
else
result = kMoveToLineTo_Result;
}
fPrevPt.set(x, y);
fPrevResult = result;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkPath.h"
SkCullPointsPath::SkCullPointsPath()
: fCP(), fPath(NULL)
{
}
SkCullPointsPath::SkCullPointsPath(const SkIRect& r, SkPath* dst)
: fCP(r), fPath(dst)
{
}
void SkCullPointsPath::reset(const SkIRect& r, SkPath* dst)
{
fCP.reset(r);
fPath = dst;
}
void SkCullPointsPath::moveTo(int x, int y)
{
fCP.moveTo(x, y);
}
void SkCullPointsPath::lineTo(int x, int y)
{
SkIPoint pts[2];
switch (fCP.lineTo(x, y, pts)) {
case SkCullPoints::kMoveToLineTo_Result:
fPath->moveTo(SkIntToScalar(pts[0].fX), SkIntToScalar(pts[0].fY));
// fall through to the lineto case
case SkCullPoints::kLineTo_Result:
fPath->lineTo(SkIntToScalar(pts[1].fX), SkIntToScalar(pts[1].fY));
break;
default:
break;
}
}
<commit_msg>Add suggested parentheses to fix build with GCC 4.3<commit_after>/* libs/graphics/effects/SkCullPoints.cpp
**
** Copyright 2006, Google 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 "SkCullPoints.h"
#include "Sk64.h"
static bool cross_product_is_neg(const SkIPoint& v, int dx, int dy)
{
#if 0
return v.fX * dy - v.fY * dx < 0;
#else
Sk64 tmp0, tmp1;
tmp0.setMul(v.fX, dy);
tmp1.setMul(dx, v.fY);
tmp0.sub(tmp1);
return tmp0.isNeg();
#endif
}
bool SkCullPoints::sect_test(int x0, int y0, int x1, int y1) const
{
const SkIRect& r = fR;
if ((x0 < r.fLeft && x1 < r.fLeft) ||
(x0 > r.fRight && x1 > r.fRight) ||
(y0 < r.fTop && y1 < r.fTop) ||
(y0 > r.fBottom && y1 > r.fBottom))
return false;
// since the crossprod test is a little expensive, check for easy-in cases first
if (r.contains(x0, y0) || r.contains(x1, y1))
return true;
// At this point we're not sure, so we do a crossprod test
SkIPoint vec;
const SkIPoint* rAsQuad = fAsQuad;
vec.set(x1 - x0, y1 - y0);
bool isNeg = cross_product_is_neg(vec, x0 - rAsQuad[0].fX, y0 - rAsQuad[0].fY);
for (int i = 1; i < 4; i++) {
if (cross_product_is_neg(vec, x0 - rAsQuad[i].fX, y0 - rAsQuad[i].fY) != isNeg)
{
return true;
}
}
return false; // we didn't intersect
}
static void toQuad(const SkIRect& r, SkIPoint quad[4])
{
SkASSERT(quad);
quad[0].set(r.fLeft, r.fTop);
quad[1].set(r.fRight, r.fTop);
quad[2].set(r.fRight, r.fBottom);
quad[3].set(r.fLeft, r.fBottom);
}
SkCullPoints::SkCullPoints()
{
SkIRect r;
r.setEmpty();
this->reset(r);
}
SkCullPoints::SkCullPoints(const SkIRect& r)
{
this->reset(r);
}
void SkCullPoints::reset(const SkIRect& r)
{
fR = r;
toQuad(fR, fAsQuad);
fPrevPt.set(0, 0);
fPrevResult = kNo_Result;
}
void SkCullPoints::moveTo(int x, int y)
{
fPrevPt.set(x, y);
fPrevResult = kNo_Result; // so we trigger a movetolineto later
}
SkCullPoints::LineToResult SkCullPoints::lineTo(int x, int y, SkIPoint line[])
{
SkASSERT(line != NULL);
LineToResult result = kNo_Result;
int x0 = fPrevPt.fX;
int y0 = fPrevPt.fY;
// need to upgrade sect_test to chop the result
// and to correctly return kLineTo_Result when the result is connected
// to the previous call-out
if (this->sect_test(x0, y0, x, y))
{
line[0].set(x0, y0);
line[1].set(x, y);
if (fPrevResult != kNo_Result && fPrevPt.equals(x0, y0))
result = kLineTo_Result;
else
result = kMoveToLineTo_Result;
}
fPrevPt.set(x, y);
fPrevResult = result;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkPath.h"
SkCullPointsPath::SkCullPointsPath()
: fCP(), fPath(NULL)
{
}
SkCullPointsPath::SkCullPointsPath(const SkIRect& r, SkPath* dst)
: fCP(r), fPath(dst)
{
}
void SkCullPointsPath::reset(const SkIRect& r, SkPath* dst)
{
fCP.reset(r);
fPath = dst;
}
void SkCullPointsPath::moveTo(int x, int y)
{
fCP.moveTo(x, y);
}
void SkCullPointsPath::lineTo(int x, int y)
{
SkIPoint pts[2];
switch (fCP.lineTo(x, y, pts)) {
case SkCullPoints::kMoveToLineTo_Result:
fPath->moveTo(SkIntToScalar(pts[0].fX), SkIntToScalar(pts[0].fY));
// fall through to the lineto case
case SkCullPoints::kLineTo_Result:
fPath->lineTo(SkIntToScalar(pts[1].fX), SkIntToScalar(pts[1].fY));
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "timer.hpp"
using namespace std;
int main()
{
cout << "Test timer class" << endl;
Timer timer;
cout << "Timer can at most run for " << timer.MaxTime() << " nanoseconds.\n";
cout << "Sleep for 1 sec.\n";
timer.StartTimer();
Sleep(1000); // ONLY WORKS ON WINDOWS. REPLACE DEPENDING ON YOUR OS!
timer.StopTimer();
cout << "Time in nanoseconds: " << timer.ElapsedTime() << endl;
cout << "Time in microseconds: " << timer.ElapsedTime("micro") << endl;
cout << "Time in seconds: " << timer.ElapsedTime("sec") << endl;
cout << "Sleep for 9 sec.\n";
timer.StartTimer();
Sleep(9000);
timer.StopTimer();
cout << "Time in seconds: " << timer.ElapsedTime("sec") << endl;
cout << "Time in minutes: " << timer.ElapsedTime("min") << endl;
cout << "Total time: " << timer.CumulativeTime("sec") << endl;
cout << "Finished.";
return 0;
}
<commit_msg>updated cout<commit_after>#include <iostream>
#include "timer.hpp"
using namespace std;
int main()
{
cout << "Test timer class" << endl;
Timer timer;
cout << "Timer can at most run for " << timer.MaxTime() << " nanoseconds.\n";
cout << "Sleep for 1 sec.\n";
timer.StartTimer();
Sleep(1000); // ONLY WORKS ON WINDOWS. REPLACE DEPENDING ON YOUR OS!
timer.StopTimer();
cout << "Time in nanoseconds: " << timer.ElapsedTime() << endl;
cout << "Time in microseconds: " << timer.ElapsedTime("micro") << endl;
cout << "Time in seconds: " << timer.ElapsedTime("sec") << endl;
cout << "Sleep for 9 sec.\n";
timer.StartTimer();
Sleep(9000);
timer.StopTimer();
cout << "Time in seconds: " << timer.ElapsedTime("sec") << endl;
cout << "Time in minutes: " << timer.ElapsedTime("min") << endl;
cout << "Total time in seconds: " << timer.CumulativeTime("sec") << endl;
cout << "Finished.";
return 0;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "IECore/Group.h"
#include "IECoreHoudini/FromHoudiniGroupConverter.h"
using namespace IECore;
using namespace IECoreHoudini;
IE_CORE_DEFINERUNTIMETYPED( FromHoudiniGroupConverter );
FromHoudiniGeometryConverter::Description<FromHoudiniGroupConverter> FromHoudiniGroupConverter::m_description( GroupTypeId );
FromHoudiniGroupConverter::FromHoudiniGroupConverter( const GU_DetailHandle &handle ) :
FromHoudiniGeometryConverter( handle, "Converts a Houdini GU_Detail to an IECore::Group." )
{
}
FromHoudiniGroupConverter::FromHoudiniGroupConverter( const SOP_Node *sop ) :
FromHoudiniGeometryConverter( sop, "Converts a Houdini GU_Detail to an IECore::Group." )
{
}
FromHoudiniGroupConverter::~FromHoudiniGroupConverter()
{
}
FromHoudiniGeometryConverter::Convertability FromHoudiniGroupConverter::canConvert( const GU_Detail *geo )
{
const GA_PrimitiveList &primitives = geo->getPrimitiveList();
// are there multiple primitives?
size_t numPrims = geo->getNumPrimitives();
if ( numPrims < 2 )
{
return Admissible;
}
// are there mixed primitive types?
GA_Iterator firstPrim = geo->getPrimitiveRange().begin();
GA_PrimitiveTypeId firstPrimId = primitives.get( firstPrim.getOffset() )->getTypeId();
for ( GA_Iterator it=firstPrim; !it.atEnd(); ++it )
{
if ( primitives.get( it.getOffset() )->getTypeId() != firstPrimId )
{
return Ideal;
}
}
// are the primitives split into groups?
UT_PtrArray<const GA_ElementGroup*> primGroups;
geo->getElementGroupList( GA_ATTRIB_PRIMITIVE, primGroups );
if ( primGroups.isEmpty() || primGroups[0]->entries() == numPrims )
{
return Admissible;
}
return Ideal;
}
ObjectPtr FromHoudiniGroupConverter::doConversion( ConstCompoundObjectPtr operands ) const
{
GU_DetailHandleAutoReadLock readHandle( handle() );
const GU_Detail *geo = readHandle.getGdp();
if ( !geo )
{
return 0;
}
size_t numResultPrims = 0;
size_t numOrigPrims = geo->getNumPrimitives();
GroupPtr result = new Group();
for ( GA_GroupTable::iterator<GA_ElementGroup> it=geo->primitiveGroups().beginTraverse(); !it.atEnd(); ++it )
{
GA_PrimitiveGroup *group = static_cast<GA_PrimitiveGroup*>( it.group() );
if ( group->getInternal() || group->isEmpty() )
{
continue;
}
VisibleRenderablePtr renderable = 0;
numResultPrims += doGroupConversion( geo, group, renderable );
if( !renderable )
{
continue;
}
result->addChild( renderable );
}
if ( numOrigPrims == numResultPrims )
{
return result;
}
GU_Detail ungroupedGeo( (GU_Detail*)geo );
GA_PrimitiveGroup *ungrouped = static_cast<GA_PrimitiveGroup*>( ungroupedGeo.createInternalElementGroup( GA_ATTRIB_PRIMITIVE, "FromHoudiniGroupConverter__ungroupedPrimitives" ) );
for ( GA_GroupTable::iterator<GA_ElementGroup> it=geo->primitiveGroups().beginTraverse(); !it.atEnd(); ++it )
{
*ungrouped |= *static_cast<GA_PrimitiveGroup*>( it.group() );
}
ungrouped->toggleRange( ungroupedGeo.getPrimitiveRange() );
if ( ungrouped->isEmpty() )
{
return result;
}
VisibleRenderablePtr renderable = 0;
doGroupConversion( &ungroupedGeo, ungrouped, renderable );
if ( renderable )
{
result->addChild( renderable );
}
return result;
}
size_t FromHoudiniGroupConverter::doGroupConversion( const GU_Detail *geo, GA_PrimitiveGroup *group, VisibleRenderablePtr &result ) const
{
GU_Detail groupGeo( (GU_Detail*)geo, group );
if ( !groupGeo.getNumPoints() )
{
return 0;
}
size_t numPrims = groupGeo.getNumPrimitives();
if ( numPrims < 2 )
{
result = doPrimitiveConversion( &groupGeo );
return numPrims;
}
PrimIdGroupMap groupMap;
groupGeo.destroyEmptyGroups( GA_ATTRIB_PRIMITIVE );
size_t numNewGroups = regroup( &groupGeo, groupMap );
if ( numNewGroups < 2 )
{
result = doPrimitiveConversion( &groupGeo );
return numPrims;
}
GroupPtr groupResult = new Group();
if ( !group->getInternal() )
{
groupResult->blindData()->member<StringData>( "name", false, true )->writable() = group->getName().toStdString();
}
for ( PrimIdGroupMapIterator it = groupMap.begin(); it != groupMap.end(); it++ )
{
VisibleRenderablePtr renderable = 0;
GU_Detail childGeo( &groupGeo, it->second );
for ( GA_GroupTable::iterator<GA_ElementGroup> it=childGeo.primitiveGroups().beginTraverse(); !it.atEnd(); ++it )
{
childGeo.destroyGroup( it.group() );
}
PrimitivePtr child = doPrimitiveConversion( &childGeo );
if ( child )
{
groupResult->addChild( child );
}
}
result = groupResult;
return numPrims;
}
size_t FromHoudiniGroupConverter::regroup( GU_Detail *geo, PrimIdGroupMap &groupMap ) const
{
PrimIdGroupMapIterator it;
const GA_PrimitiveList &primitives = geo->getPrimitiveList();
for ( GA_Iterator pIt=geo->getPrimitiveRange().begin(); !pIt.atEnd(); ++pIt )
{
GA_Primitive *prim = primitives.get( pIt.getOffset() );
unsigned primType = prim->getTypeId().get();
it = groupMap.find( primType );
if ( it == groupMap.end() )
{
PrimIdGroupPair pair( primType, static_cast<GA_PrimitiveGroup*>( geo->createInternalElementGroup( GA_ATTRIB_PRIMITIVE, ( boost::format( "FromHoudiniGroupConverter__typedPrimitives%d" ) % primType ).str().c_str() ) ) );
it = groupMap.insert( pair ).first;
}
it->second->add( prim );
}
return groupMap.size();
}
PrimitivePtr FromHoudiniGroupConverter::doPrimitiveConversion( const GU_Detail *geo ) const
{
GU_DetailHandle handle;
handle.allocateAndSet( (GU_Detail*)geo, false );
FromHoudiniGeometryConverterPtr converter = FromHoudiniGeometryConverter::create( handle );
if ( !converter || converter->isInstanceOf( FromHoudiniGroupConverter::staticTypeId() ) )
{
return 0;
}
return IECore::runTimeCast<Primitive>( converter->convert() );
}
<commit_msg>fix for houdini group converter. works with h 12.0.562 and 12.0.581<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "IECore/Group.h"
#include "IECoreHoudini/FromHoudiniGroupConverter.h"
using namespace IECore;
using namespace IECoreHoudini;
IE_CORE_DEFINERUNTIMETYPED( FromHoudiniGroupConverter );
FromHoudiniGeometryConverter::Description<FromHoudiniGroupConverter> FromHoudiniGroupConverter::m_description( GroupTypeId );
FromHoudiniGroupConverter::FromHoudiniGroupConverter( const GU_DetailHandle &handle ) :
FromHoudiniGeometryConverter( handle, "Converts a Houdini GU_Detail to an IECore::Group." )
{
}
FromHoudiniGroupConverter::FromHoudiniGroupConverter( const SOP_Node *sop ) :
FromHoudiniGeometryConverter( sop, "Converts a Houdini GU_Detail to an IECore::Group." )
{
}
FromHoudiniGroupConverter::~FromHoudiniGroupConverter()
{
}
FromHoudiniGeometryConverter::Convertability FromHoudiniGroupConverter::canConvert( const GU_Detail *geo )
{
const GA_PrimitiveList &primitives = geo->getPrimitiveList();
// are there multiple primitives?
size_t numPrims = geo->getNumPrimitives();
if ( numPrims < 2 )
{
return Admissible;
}
// are there mixed primitive types?
GA_Iterator firstPrim = geo->getPrimitiveRange().begin();
GA_PrimitiveTypeId firstPrimId = primitives.get( firstPrim.getOffset() )->getTypeId();
for ( GA_Iterator it=firstPrim; !it.atEnd(); ++it )
{
if ( primitives.get( it.getOffset() )->getTypeId() != firstPrimId )
{
return Ideal;
}
}
// are the primitives split into groups?
UT_PtrArray<const GA_ElementGroup*> primGroups;
geo->getElementGroupList( GA_ATTRIB_PRIMITIVE, primGroups );
if ( primGroups.isEmpty() || primGroups[0]->entries() == numPrims )
{
return Admissible;
}
return Ideal;
}
ObjectPtr FromHoudiniGroupConverter::doConversion( ConstCompoundObjectPtr operands ) const
{
GU_DetailHandleAutoReadLock readHandle( handle() );
const GU_Detail *geo = readHandle.getGdp();
if ( !geo )
{
return 0;
}
size_t numResultPrims = 0;
size_t numOrigPrims = geo->getNumPrimitives();
GroupPtr result = new Group();
for ( GA_GroupTable::iterator<GA_ElementGroup> it=geo->primitiveGroups().beginTraverse(); !it.atEnd(); ++it )
{
GA_PrimitiveGroup *group = static_cast<GA_PrimitiveGroup*>( it.group() );
if ( group->getInternal() || group->isEmpty() )
{
continue;
}
VisibleRenderablePtr renderable = 0;
numResultPrims += doGroupConversion( geo, group, renderable );
if( !renderable )
{
continue;
}
result->addChild( renderable );
}
if ( numOrigPrims == numResultPrims )
{
return result;
}
GU_Detail ungroupedGeo( (GU_Detail*)geo );
GA_PrimitiveGroup *ungrouped = static_cast<GA_PrimitiveGroup*>( ungroupedGeo.createInternalElementGroup( GA_ATTRIB_PRIMITIVE, "FromHoudiniGroupConverter__ungroupedPrimitives" ) );
for ( GA_GroupTable::iterator<GA_ElementGroup> it=geo->primitiveGroups().beginTraverse(); !it.atEnd(); ++it )
{
*ungrouped |= *static_cast<GA_PrimitiveGroup*>( it.group() );
}
ungrouped->toggleRange( ungroupedGeo.getPrimitiveRange() );
if ( ungrouped->isEmpty() )
{
return result;
}
VisibleRenderablePtr renderable = 0;
doGroupConversion( &ungroupedGeo, ungrouped, renderable );
if ( renderable )
{
result->addChild( renderable );
}
return result;
}
size_t FromHoudiniGroupConverter::doGroupConversion( const GU_Detail *geo, GA_PrimitiveGroup *group, VisibleRenderablePtr &result ) const
{
GU_Detail groupGeo( (GU_Detail*)geo, group );
if ( !groupGeo.getNumPoints() )
{
return 0;
}
size_t numPrims = groupGeo.getNumPrimitives();
if ( numPrims < 2 )
{
result = doPrimitiveConversion( &groupGeo );
return numPrims;
}
PrimIdGroupMap groupMap;
groupGeo.destroyEmptyGroups( GA_ATTRIB_PRIMITIVE );
size_t numNewGroups = regroup( &groupGeo, groupMap );
if ( numNewGroups < 2 )
{
result = doPrimitiveConversion( &groupGeo );
return numPrims;
}
GroupPtr groupResult = new Group();
if ( !group->getInternal() )
{
groupResult->blindData()->member<StringData>( "name", false, true )->writable() = group->getName().toStdString();
}
for ( PrimIdGroupMapIterator it = groupMap.begin(); it != groupMap.end(); it++ )
{
VisibleRenderablePtr renderable = 0;
GU_Detail childGeo( &groupGeo, it->second );
for ( GA_GroupTable::iterator<GA_ElementGroup> it=childGeo.primitiveGroups().beginTraverse(); !it.atEnd(); ++it )
{
it.group()->clear();
}
childGeo.destroyAllEmptyGroups();
PrimitivePtr child = doPrimitiveConversion( &childGeo );
if ( child )
{
groupResult->addChild( child );
}
}
result = groupResult;
return numPrims;
}
size_t FromHoudiniGroupConverter::regroup( GU_Detail *geo, PrimIdGroupMap &groupMap ) const
{
PrimIdGroupMapIterator it;
const GA_PrimitiveList &primitives = geo->getPrimitiveList();
for ( GA_Iterator pIt=geo->getPrimitiveRange().begin(); !pIt.atEnd(); ++pIt )
{
GA_Primitive *prim = primitives.get( pIt.getOffset() );
unsigned primType = prim->getTypeId().get();
it = groupMap.find( primType );
if ( it == groupMap.end() )
{
PrimIdGroupPair pair( primType, static_cast<GA_PrimitiveGroup*>( geo->createInternalElementGroup( GA_ATTRIB_PRIMITIVE, ( boost::format( "FromHoudiniGroupConverter__typedPrimitives%d" ) % primType ).str().c_str() ) ) );
it = groupMap.insert( pair ).first;
}
it->second->add( prim );
}
return groupMap.size();
}
PrimitivePtr FromHoudiniGroupConverter::doPrimitiveConversion( const GU_Detail *geo ) const
{
GU_DetailHandle handle;
handle.allocateAndSet( (GU_Detail*)geo, false );
FromHoudiniGeometryConverterPtr converter = FromHoudiniGeometryConverter::create( handle );
if ( !converter || converter->isInstanceOf( FromHoudiniGroupConverter::staticTypeId() ) )
{
return 0;
}
return IECore::runTimeCast<Primitive>( converter->convert() );
}
<|endoftext|> |
<commit_before>
#include "include/config.h"
#include "include/error.h"
#include "common/Timer.h"
#include "common/Mutex.h"
#include "MPIMessenger.h"
#include "CheesySerializer.h"
#include "Message.h"
#include <iostream>
#include <cassert>
using namespace std;
#include <ext/hash_map>
using namespace __gnu_cxx;
#include <unistd.h>
#include <mpi.h>
/*
* We make a directory, so that we can have multiple Messengers in the
* same process (rank). This is useful for benchmarking and creating lots of
* simulated clients, e.g.
*/
hash_map<int, MPIMessenger*> directory;
list<Message*> outgoing;
/* this process */
int mpi_world;
int mpi_rank;
bool mpi_done = false; // set this flag to stop the event loop
// lame way
#define TAG_ENV 0
#define TAG_PAYLOAD 1
#define TAG_ACK 2
// chris' multithreaded way
#define TAG_UNSOLICITED 0
#define TAG_PAYLOAD 1
// the key used to fetch the tag for the current thread.
pthread_key_t tag_key;
pthread_t thread_id = 0; // thread id of the event loop. init value == nobody
Mutex sender_lock;
// our lock for any common data; it's okay to have only the one global mutex
// because our common data isn't a whole lot.
static pthread_mutex_t mutex;
// the number of distinct threads we've seen so far; used to generate
// a unique tag for each thread.
static int nthreads = 10;
//#define TAG_UNSOLICITED 0
// debug
#undef dout
#define dout(l) if (l<=g_conf.debug) cout << "[MPI " << mpi_rank << "/" << mpi_world << " " << getpid() << "." << pthread_self() << "] "
/*****
* MPI global methods for process-wide setup, shutdown.
*/
int mpimessenger_init(int& argc, char**& argv)
{
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &mpi_world);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
char hostname[100];
gethostname(hostname,100);
int pid = getpid();
dout(12) << "init: i am " << hostname << " pid " << pid << endl;
assert(mpi_world > g_conf.num_osd+g_conf.num_mds);
return mpi_rank;
}
int mpimessenger_shutdown()
{
MPI_Finalize();
}
int mpimessenger_world()
{
return mpi_world;
}
/***
* internal send/recv
*/
MPI_Request recv_env_req;
Message *mpi_recv(int tag)
{
MPI_Status status;
dout(10) << "mpi_recv waiting for message tag " << tag << endl;
// get message size
ASSERT(MPI_Probe(MPI_ANY_SOURCE,
tag,
MPI_COMM_WORLD,
&status) == MPI_SUCCESS);
dout(10) << "mpi_recv probe sees " << status.count << " bytes incoming" << endl;
// make sure it's the size of an envelope!
assert(status.count <= MSG_ENVELOPE_LEN);
msg_envelope_t env;
dout(10) << "mpi_recv Irecv envelope" << endl;
ASSERT(MPI_Recv((void*)&env,
sizeof(env),
MPI_CHAR,
status.MPI_SOURCE,//MPI_ANY_SOURCE,
tag,
MPI_COMM_WORLD,
&status/*,
&recv_env_req*/) == MPI_SUCCESS);
/*
dout(10) << "mpi_recv wait" << endl;
if (MPI_Wait(&recv_env_req, &status) != MPI_SUCCESS) {
dout(10) << "mpi_recv MPI_Wait not success" << endl;
return 0;
}
*/
if (status.count < MSG_ENVELOPE_LEN) {
dout(10) << "mpi_recv got short recv " << status.count << " bytes" << endl;
return 0;
}
if (env.type == 0) {
dout(10) << "mpi_recv got type 0 message, kicked!" << endl;
return 0;
}
dout(10) << "mpi_recv got envelope " << status.count << ", type=" << env.type << " src " << env.source << " dst " << env.dest << " nchunks=" << env.nchunks << " from " << status.MPI_SOURCE << endl;
// get the rest of the message
bufferlist blist;
for (int i=0; i<env.nchunks; i++) {
MPI_Status fragstatus;
ASSERT(MPI_Probe(status.MPI_SOURCE,
tag, //TAG_PAYLOAD,
MPI_COMM_WORLD,
&fragstatus) == MPI_SUCCESS);
dout(10) << "mpi_recv frag " << i << " of " << env.nchunks << " is len " << fragstatus.count << endl;
bufferptr bp = new buffer(fragstatus.count);
ASSERT(MPI_Recv(bp.c_str(),
fragstatus.count,
MPI_CHAR,
status.MPI_SOURCE,
tag, //TAG_PAYLOAD,
MPI_COMM_WORLD,
&fragstatus) == MPI_SUCCESS);
bp.set_length(fragstatus.count);
blist.push_back(bp);
dout(10) << "mpi_recv got frag " << i << " of " << env.nchunks << " len " << fragstatus.count << endl;
}
dout(10) << "mpi_recv got " << blist.length() << " byte message tag " << status.MPI_TAG << endl;
// unmarshall message
Message *m = decode_message(env, blist);
return m;
}
int mpi_send(Message *m, int tag)
{
int rank = MPI_DEST_TO_RANK(m->get_dest(), mpi_world);
if (rank == mpi_rank) {
dout(1) << "local delivery not implemented" << endl;
assert(0);
}
// marshall
m->encode_payload();
msg_envelope_t *env = &m->get_envelope();
bufferlist blist = m->get_payload();
env->nchunks = blist.buffers().size();
dout(10) << "mpi_sending " << blist.length() << " size message on tag " << tag << " type " << env->type << " src " << env->source << " dst " << env->dest << " to rank " << rank << " nchunks=" << env->nchunks << endl;
sender_lock.Lock();
// send envelope
MPI_Request req;
ASSERT(MPI_Isend((void*)env,
sizeof(*env),
MPI_CHAR,
rank,
tag,
MPI_COMM_WORLD,
&req) == MPI_SUCCESS);
int i = 0;
vector<MPI_Request> chunk_reqs(env->nchunks);
for (list<bufferptr>::iterator it = blist.buffers().begin();
it != blist.buffers().end();
it++) {
dout(10) << "mpi_sending frag " << i << " len " << (*it).length() << endl;
ASSERT(MPI_Isend((void*)(*it).c_str(),
(*it).length(),
MPI_CHAR,
rank,
tag,//TAG_PAYLOAD,
MPI_COMM_WORLD,
&chunk_reqs[i]) == MPI_SUCCESS);
i++;
}
dout(10) << "mpi_send done" << endl;
sender_lock.Unlock();
}
// get the tag for this thread
static int get_thread_tag()
{
int tag = (int)pthread_getspecific(tag_key);
if (tag == 0) {
// first time this thread has performed MPI messaging
if (pthread_mutex_lock(&mutex) < 0)
SYSERROR();
tag = ++nthreads;
if (pthread_mutex_unlock(&mutex) < 0)
SYSERROR();
if (pthread_setspecific(tag_key, (void*)tag) < 0)
SYSERROR();
}
return tag;
}
// recv event loop, for unsolicited messages.
void* mpimessenger_loop(void*)
{
dout(1) << "mpimessenger_loop start pid " << getpid() << endl;
while (!mpi_done) {
// check outgoing queue
/*
sender_lock.Lock();
for (list<Message*>::iterator it = outgoing.begin();
it != outgoing.end();
it++) {
mpi_send(*it);
}
outgoing.clear();
sender_lock.Unlock();
*/
// check mpi
dout(12) << "mpimessenger_loop waiting for incoming messages" << endl;
// get message
Message *m = mpi_recv(TAG_UNSOLICITED);
if (!m) continue; // no message?
int dest = m->get_dest();
if (directory.count(dest)) {
Messenger *who = directory[ dest ];
dout(3) << "---- mpimessenger_loop dispatching '" << m->get_type_name() <<
"' from " << MSG_ADDR_NICE(m->get_source()) << ':' << m->get_source_port() <<
" to " << MSG_ADDR_NICE(m->get_dest()) << ':' << m->get_dest_port() << " ---- " << m
<< endl;
who->dispatch(m);
} else {
dout (1) << "---- i don't know who " << dest << " is." << endl;
assert(0);
break;
}
}
dout(5) << "mpimessenger_loop finish, waiting for all to finish" << endl;
MPI_Barrier (MPI_COMM_WORLD);
dout(5) << "mpimessenger_loop everybody done, exiting loop" << endl;
}
// start/stop mpi receiver thread (for unsolicited messages)
int mpimessenger_start()
{
dout(5) << "mpimessenger_start starting thread" << endl;
// start a thread
pthread_create(&thread_id,
NULL,
mpimessenger_loop,
0);
}
MPI_Request kick_req;
void mpimessenger_kick_loop()
{
/*
dout(10) << "kicking" << endl;
MPI_Cancel(&recv_env_req);
dout(10) << "kicked" << endl;
return;
*/
// wake up the event loop with a bad "message"
//char stop = 0; // a byte will do
msg_envelope_t env;
env.type = 0;
dout(10) << "kicking" << endl;
ASSERT(MPI_Isend(&env,
sizeof(env),
MPI_CHAR,
mpi_rank,
TAG_ENV,
MPI_COMM_WORLD,
&kick_req) == MPI_SUCCESS);
dout(10) << "kicked" << endl;
}
void mpimessenger_stop()
{
dout(5) << "mpimessenger_stop stopping thread" << endl;
if (mpi_done) {
dout(1) << "mpimessenger_stop called, but already done!" << endl;
assert(!mpi_done);
}
// set finish flag
mpi_done = true;
mpimessenger_kick_loop();
// wait for thread to stop
mpimessenger_wait();
}
void mpimessenger_wait()
{
void *returnval;
pthread_join(thread_id, &returnval);
dout(10) << "mpimessenger_wait thread finished." << endl;
}
/***********
* MPIMessenger implementation
*/
MPIMessenger::MPIMessenger(msg_addr_t myaddr) : Messenger()
{
// my address
this->myaddr = myaddr;
// register myself in the messenger directory
directory[myaddr] = this;
// logger
/*
string name;
name = "m.";
name += MSG_ADDR_TYPE(whoami);
int w = MSG_ADDR_NUM(whoami);
if (w >= 1000) name += ('0' + ((w/1000)%10));
if (w >= 100) name += ('0' + ((w/100)%10));
if (w >= 10) name += ('0' + ((w/10)%10));
name += ('0' + ((w/1)%10));
logger = new Logger(name, (LogType*)&mpimsg_logtype);
loggers[ whoami ] = logger;
*/
}
MPIMessenger::~MPIMessenger()
{
//delete logger;
}
int MPIMessenger::shutdown()
{
// remove me from the directory
directory.erase(myaddr);
// last one?
if (directory.empty()) {
dout(10) << "last mpimessenger on rank " << mpi_rank << " shut down" << endl;
pthread_t whoami = pthread_self();
dout(15) << "whoami = " << whoami << ", thread = " << thread_id << endl;
if (whoami == thread_id) {
// i am the event loop thread, just set flag!
dout(15) << " set mpi_done=true" << endl;
mpi_done = true;
} else {
// i am a different thread, tell the event loop to stop.
dout(15) << " calling mpimessenger_stop()" << endl;
mpimessenger_stop();
}
}
}
/*** events
*/
void MPIMessenger::trigger_timer(Timer *t)
{
assert(0); //implement me
}
/***
* public messaging interface
*/
int MPIMessenger::send_message(Message *m, msg_addr_t dest, int port, int fromport)
{
// set envelope
m->set_source(myaddr, fromport);
m->set_dest(dest, port);
if (1) {
// send in this thread
mpi_send(m, m->get_pcid());
} else {
// queue up
sender_lock.Lock();
dout(10) << "send_message queueing up outgoing message " << *m << endl;
outgoing.push_back(m);
mpimessenger_kick_loop();
sender_lock.Unlock();
}
}
Message *MPIMessenger::sendrecv(Message *m, msg_addr_t dest, int port)
{
int fromport = 0;
// set envelope
m->set_source(myaddr, fromport);
m->set_dest(dest, port);
int rank = MPI_DEST_TO_RANK(dest, mpi_world);
// get a tag to uniquely identify this procedure call
int my_tag = get_thread_tag();
m->set_pcid(my_tag);
mpi_send(m, TAG_UNSOLICITED);
return mpi_recv(my_tag);
}
<commit_msg>*** empty log message ***<commit_after>
#include "include/config.h"
#include "include/error.h"
#include "common/Timer.h"
#include "common/Mutex.h"
#include "MPIMessenger.h"
#include "CheesySerializer.h"
#include "Message.h"
#include <iostream>
#include <cassert>
using namespace std;
#include <ext/hash_map>
using namespace __gnu_cxx;
#include <unistd.h>
#include <mpi.h>
/*
* We make a directory, so that we can have multiple Messengers in the
* same process (rank). This is useful for benchmarking and creating lots of
* simulated clients, e.g.
*/
hash_map<int, MPIMessenger*> directory;
list<Message*> outgoing;
/* this process */
int mpi_world;
int mpi_rank;
bool mpi_done = false; // set this flag to stop the event loop
// lame way
#define TAG_ENV 0
#define TAG_PAYLOAD 1
#define TAG_ACK 2
// chris' multithreaded way
#define TAG_UNSOLICITED 0
#define TAG_PAYLOAD 1
// the key used to fetch the tag for the current thread.
pthread_key_t tag_key;
pthread_t thread_id = 0; // thread id of the event loop. init value == nobody
Mutex sender_lock;
// our lock for any common data; it's okay to have only the one global mutex
// because our common data isn't a whole lot.
static pthread_mutex_t mutex;
// the number of distinct threads we've seen so far; used to generate
// a unique tag for each thread.
static int nthreads = 10;
//#define TAG_UNSOLICITED 0
// debug
#undef dout
#define dout(l) if (l<=g_conf.debug) cout << "[MPI " << mpi_rank << "/" << mpi_world << " " << getpid() << "." << pthread_self() << "] "
/*****
* MPI global methods for process-wide setup, shutdown.
*/
int mpimessenger_init(int& argc, char**& argv)
{
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &mpi_world);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
char hostname[100];
gethostname(hostname,100);
int pid = getpid();
dout(12) << "init: i am " << hostname << " pid " << pid << endl;
assert(mpi_world > g_conf.num_osd+g_conf.num_mds);
return mpi_rank;
}
int mpimessenger_shutdown()
{
MPI_Finalize();
}
int mpimessenger_world()
{
return mpi_world;
}
/***
* internal send/recv
*/
MPI_Request recv_env_req;
Message *mpi_recv(int tag)
{
MPI_Status status;
dout(10) << "mpi_recv waiting for message tag " << tag << endl;
/*
// get message size
ASSERT(MPI_Probe(MPI_ANY_SOURCE,
tag,
MPI_COMM_WORLD,
&status) == MPI_SUCCESS);
dout(10) << "mpi_recv probe sees " << status.count << " bytes incoming" << endl;
// make sure it's the size of an envelope!
assert(status.count <= MSG_ENVELOPE_LEN);
*/
msg_envelope_t env;
dout(10) << "mpi_recv Irecv envelope" << endl;
ASSERT(MPI_Recv((void*)&env,
sizeof(env),
MPI_CHAR,
MPI_ANY_SOURCE,// status.MPI_SOURCE,//MPI_ANY_SOURCE,
tag,
MPI_COMM_WORLD,
&status/*,
&recv_env_req*/) == MPI_SUCCESS);
/*
dout(10) << "mpi_recv wait" << endl;
if (MPI_Wait(&recv_env_req, &status) != MPI_SUCCESS) {
dout(10) << "mpi_recv MPI_Wait not success" << endl;
return 0;
}
*/
if (status.count < MSG_ENVELOPE_LEN) {
dout(10) << "mpi_recv got short recv " << status.count << " bytes" << endl;
return 0;
}
if (env.type == 0) {
dout(10) << "mpi_recv got type 0 message, kicked!" << endl;
return 0;
}
dout(10) << "mpi_recv got envelope " << status.count << ", type=" << env.type << " src " << env.source << " dst " << env.dest << " nchunks=" << env.nchunks << " from " << status.MPI_SOURCE << endl;
// get the rest of the message
bufferlist blist;
for (int i=0; i<env.nchunks; i++) {
MPI_Status fragstatus;
ASSERT(MPI_Probe(status.MPI_SOURCE,
tag, //TAG_PAYLOAD,
MPI_COMM_WORLD,
&fragstatus) == MPI_SUCCESS);
dout(10) << "mpi_recv frag " << i << " of " << env.nchunks << " is len " << fragstatus.count << endl;
bufferptr bp = new buffer(fragstatus.count);
ASSERT(MPI_Recv(bp.c_str(),
fragstatus.count,
MPI_CHAR,
status.MPI_SOURCE,
tag, //TAG_PAYLOAD,
MPI_COMM_WORLD,
&fragstatus) == MPI_SUCCESS);
bp.set_length(fragstatus.count);
blist.push_back(bp);
dout(10) << "mpi_recv got frag " << i << " of " << env.nchunks << " len " << fragstatus.count << endl;
}
dout(10) << "mpi_recv got " << blist.length() << " byte message tag " << status.MPI_TAG << endl;
// unmarshall message
Message *m = decode_message(env, blist);
return m;
}
int mpi_send(Message *m, int tag)
{
int rank = MPI_DEST_TO_RANK(m->get_dest(), mpi_world);
if (rank == mpi_rank) {
dout(1) << "local delivery not implemented" << endl;
assert(0);
}
// marshall
m->encode_payload();
msg_envelope_t *env = &m->get_envelope();
bufferlist blist = m->get_payload();
env->nchunks = blist.buffers().size();
dout(10) << "mpi_sending " << blist.length() << " size message on tag " << tag << " type " << env->type << " src " << env->source << " dst " << env->dest << " to rank " << rank << " nchunks=" << env->nchunks << endl;
//sender_lock.Lock();
// send envelope
MPI_Request req;
ASSERT(MPI_Isend((void*)env,
sizeof(*env),
MPI_CHAR,
rank,
tag,
MPI_COMM_WORLD,
&req) == MPI_SUCCESS);
int i = 0;
vector<MPI_Request> chunk_reqs(env->nchunks);
for (list<bufferptr>::iterator it = blist.buffers().begin();
it != blist.buffers().end();
it++) {
dout(10) << "mpi_sending frag " << i << " len " << (*it).length() << endl;
ASSERT(MPI_Isend((void*)(*it).c_str(),
(*it).length(),
MPI_CHAR,
rank,
tag,//TAG_PAYLOAD,
MPI_COMM_WORLD,
&chunk_reqs[i]) == MPI_SUCCESS);
i++;
}
dout(10) << "mpi_send done" << endl;
//sender_lock.Unlock();
}
// get the tag for this thread
static int get_thread_tag()
{
int tag = (int)pthread_getspecific(tag_key);
if (tag == 0) {
// first time this thread has performed MPI messaging
if (pthread_mutex_lock(&mutex) < 0)
SYSERROR();
tag = ++nthreads;
if (pthread_mutex_unlock(&mutex) < 0)
SYSERROR();
if (pthread_setspecific(tag_key, (void*)tag) < 0)
SYSERROR();
}
return tag;
}
// recv event loop, for unsolicited messages.
void* mpimessenger_loop(void*)
{
dout(1) << "mpimessenger_loop start pid " << getpid() << endl;
while (!mpi_done) {
// check outgoing queue
sender_lock.Lock();
for (list<Message*>::iterator it = outgoing.begin();
it != outgoing.end();
it++) {
mpi_send(*it, TAG_UNSOLICITED);
}
outgoing.clear();
sender_lock.Unlock();
// check mpi
dout(12) << "mpimessenger_loop waiting for incoming messages" << endl;
// get message
Message *m = mpi_recv(TAG_UNSOLICITED);
if (!m) continue; // no message?
int dest = m->get_dest();
if (directory.count(dest)) {
Messenger *who = directory[ dest ];
dout(3) << "---- mpimessenger_loop dispatching '" << m->get_type_name() <<
"' from " << MSG_ADDR_NICE(m->get_source()) << ':' << m->get_source_port() <<
" to " << MSG_ADDR_NICE(m->get_dest()) << ':' << m->get_dest_port() << " ---- " << m
<< endl;
who->dispatch(m);
} else {
dout (1) << "---- i don't know who " << dest << " is." << endl;
assert(0);
break;
}
}
dout(5) << "mpimessenger_loop finish, waiting for all to finish" << endl;
MPI_Barrier (MPI_COMM_WORLD);
dout(5) << "mpimessenger_loop everybody done, exiting loop" << endl;
}
// start/stop mpi receiver thread (for unsolicited messages)
int mpimessenger_start()
{
dout(5) << "mpimessenger_start starting thread" << endl;
// start a thread
pthread_create(&thread_id,
NULL,
mpimessenger_loop,
0);
}
MPI_Request kick_req;
void mpimessenger_kick_loop()
{
/*
dout(10) << "kicking" << endl;
MPI_Cancel(&recv_env_req);
dout(10) << "kicked" << endl;
return;
*/
// wake up the event loop with a bad "message"
//char stop = 0; // a byte will do
msg_envelope_t env;
env.type = 0;
dout(10) << "kicking" << endl;
ASSERT(MPI_Send(&env,
sizeof(env),
MPI_CHAR,
mpi_rank,
TAG_UNSOLICITED,
MPI_COMM_WORLD/*,
&kick_req*/) == MPI_SUCCESS);
dout(10) << "kicked" << endl;
}
void mpimessenger_stop()
{
dout(5) << "mpimessenger_stop stopping thread" << endl;
if (mpi_done) {
dout(1) << "mpimessenger_stop called, but already done!" << endl;
assert(!mpi_done);
}
// set finish flag
mpi_done = true;
mpimessenger_kick_loop();
// wait for thread to stop
mpimessenger_wait();
}
void mpimessenger_wait()
{
void *returnval;
pthread_join(thread_id, &returnval);
dout(10) << "mpimessenger_wait thread finished." << endl;
}
/***********
* MPIMessenger implementation
*/
MPIMessenger::MPIMessenger(msg_addr_t myaddr) : Messenger()
{
// my address
this->myaddr = myaddr;
// register myself in the messenger directory
directory[myaddr] = this;
// logger
/*
string name;
name = "m.";
name += MSG_ADDR_TYPE(whoami);
int w = MSG_ADDR_NUM(whoami);
if (w >= 1000) name += ('0' + ((w/1000)%10));
if (w >= 100) name += ('0' + ((w/100)%10));
if (w >= 10) name += ('0' + ((w/10)%10));
name += ('0' + ((w/1)%10));
logger = new Logger(name, (LogType*)&mpimsg_logtype);
loggers[ whoami ] = logger;
*/
}
MPIMessenger::~MPIMessenger()
{
//delete logger;
}
int MPIMessenger::shutdown()
{
// remove me from the directory
directory.erase(myaddr);
// last one?
if (directory.empty()) {
dout(10) << "last mpimessenger on rank " << mpi_rank << " shut down" << endl;
pthread_t whoami = pthread_self();
dout(15) << "whoami = " << whoami << ", thread = " << thread_id << endl;
if (whoami == thread_id) {
// i am the event loop thread, just set flag!
dout(15) << " set mpi_done=true" << endl;
mpi_done = true;
} else {
// i am a different thread, tell the event loop to stop.
dout(15) << " calling mpimessenger_stop()" << endl;
mpimessenger_stop();
}
}
}
/*** events
*/
void MPIMessenger::trigger_timer(Timer *t)
{
assert(0); //implement me
}
/***
* public messaging interface
*/
int MPIMessenger::send_message(Message *m, msg_addr_t dest, int port, int fromport)
{
// set envelope
m->set_source(myaddr, fromport);
m->set_dest(dest, port);
if (0) {
// send in this thread
mpi_send(m, m->get_pcid());
} else {
// queue up
sender_lock.Lock();
dout(10) << "send_message queueing up outgoing message " << *m << endl;
outgoing.push_back(m);
mpimessenger_kick_loop();
sender_lock.Unlock();
}
}
Message *MPIMessenger::sendrecv(Message *m, msg_addr_t dest, int port)
{
int fromport = 0;
// set envelope
m->set_source(myaddr, fromport);
m->set_dest(dest, port);
int rank = MPI_DEST_TO_RANK(dest, mpi_world);
// get a tag to uniquely identify this procedure call
int my_tag = get_thread_tag();
m->set_pcid(my_tag);
mpi_send(m, TAG_UNSOLICITED);
return mpi_recv(my_tag);
}
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include <iostream>
#include "GL/glew.h"
#include "pbge/gfx/VBO.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/ShaderUniform.h"
#include "pbge/gfx/UniformSet.h"
#include "OpenGLAPI/gfx/GLGraphic.h"
#include "OpenGLAPI/gfx/GLDrawController.h"
using namespace pbge;
GLDrawController::GLDrawController(GLGraphic * _ogl):ogl(_ogl), coreSupported(false), arbSupported(false), extSupported(false) {
}
void GLDrawController::initialize() {
if(GLEW_VERSION_3_1 || GLEW_VERSION_3_2 || GLEW_VERSION_3_3 || GLEW_VERSION_4_0) {
coreSupported = true;
}
if(GLEW_ARB_draw_instanced) {
arbSupported = true;
}
if(GLEW_EXT_draw_instanced) {
extSupported = true;
}
}
void GLDrawController::draw(Model * model) {
model->beforeRender(ogl);
callRender(model);
model->afterRender(ogl);
}
void GLDrawController::draw(Model * model, int times) {
model->beforeRender(ogl);
UniformSet uniforms;
ogl->pushUniforms(&uniforms);
// FIXME: replace by getInt
UniformFloat * instanceID = uniforms.getFloat("instanceID");
for(int i = 0; i < times; i++) {
instanceID->setValue((float)i);
callRender(model);
}
ogl->popUniforms();
model->afterRender(ogl);
}
void GLDrawController::drawVBOModel(VBOModel *model) {
bindVBO(model->getVBO());
glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
unbindVBO(model->getVBO());
}
// Instanced Rendering optimization if possible
void GLDrawController::drawVBOModel(VBOModel *model, int times) {
bindVBO(model->getVBO());
if(coreSupported) {
glDrawArraysInstanced(model->getPrimitive(), 0, model->getVBO()->getNVertices(), times);
} else if(arbSupported) {
glDrawArraysInstancedARB(model->getPrimitive(), 0, model->getVBO()->getNVertices(), times);
} else if(extSupported) {
// ......
} else {
for(int i = 0; i < times; i++) {
glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
}
}
unbindVBO(model->getVBO());
}
void GLDrawController::callRender(Model * model) {
model->render(ogl);
}
#define ATTRIB_POINTER_OFFSET(offset) ((GLbyte *)NULL + (offset))
void GLDrawController::bindVBO(VertexBuffer * buffer) {
glEnable(GL_VERTEX_ARRAY);
buffer->getBuffer()->bindOn(Buffer::VertexBuffer);
std::vector<VertexAttrib>::iterator attr;
std::vector<VertexAttrib> & attribs = buffer->getAttribs();
for(attr = attribs.begin(); attr != attribs.end(); attr++) {
if(attr->getType() == VertexAttrib::VERTEX) {
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
}
else if (attr->getType() == VertexAttrib::NORMAL) {
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
} else if(attr->getType() == VertexAttrib::COLOR) {
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
} else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
glEnableClientState(GL_SECONDARY_COLOR_ARRAY);
glSecondaryColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
} else if(attr->getType() == VertexAttrib::TEXCOORD) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
}
}
}
#undef ATTRIB_POINTER_OFFSET
void GLDrawController::unbindVBO(VertexBuffer * buffer) {
std::vector<VertexAttrib>::iterator attr;
std::vector<VertexAttrib> & attribs = buffer->getAttribs();
for(attr = attribs.begin(); attr != attribs.end(); attr++) {
if(attr->getType() == VertexAttrib::VERTEX) {
glDisableClientState(GL_VERTEX_ARRAY);
}
else if (attr->getType() == VertexAttrib::NORMAL) {
glDisableClientState(GL_NORMAL_ARRAY);
} else if(attr->getType() == VertexAttrib::COLOR) {
glDisableClientState(GL_COLOR_ARRAY);
} else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
} else if(attr->getType() == VertexAttrib::TEXCOORD) {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
}
buffer->getBuffer()->unbind();
glDisable(GL_VERTEX_ARRAY);
}
<commit_msg>some more refactoring<commit_after>#include <GL/glew.h>
#include <iostream>
#include "GL/glew.h"
#include "pbge/gfx/VBO.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/ShaderUniform.h"
#include "pbge/gfx/UniformSet.h"
#include "OpenGLAPI/gfx/GLGraphic.h"
#include "OpenGLAPI/gfx/GLDrawController.h"
using namespace pbge;
GLDrawController::GLDrawController(GLGraphic * _ogl):ogl(_ogl), coreSupported(false), arbSupported(false), extSupported(false) {
}
void GLDrawController::initialize() {
if((ogl->getMajorVersion() == 3 && !GLEW_VERSION_3_0) || ogl->getMajorVersion() >= 4) {
coreSupported = true;
}
if(GLEW_ARB_draw_instanced) {
arbSupported = true;
}
if(GLEW_EXT_draw_instanced) {
extSupported = true;
}
}
void GLDrawController::draw(Model * model) {
model->beforeRender(ogl);
callRender(model);
model->afterRender(ogl);
}
void GLDrawController::draw(Model * model, int times) {
model->beforeRender(ogl);
UniformSet uniforms;
ogl->pushUniforms(&uniforms);
// FIXME: replace by getInt
UniformFloat * instanceID = uniforms.getFloat("instanceID");
for(int i = 0; i < times; i++) {
instanceID->setValue((float)i);
callRender(model);
}
ogl->popUniforms();
model->afterRender(ogl);
}
void GLDrawController::drawVBOModel(VBOModel *model) {
bindVBO(model->getVBO());
glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
unbindVBO(model->getVBO());
}
// Instanced Rendering optimization if possible
void GLDrawController::drawVBOModel(VBOModel *model, int times) {
bindVBO(model->getVBO());
if(coreSupported) {
glDrawArraysInstanced(model->getPrimitive(), 0, model->getVBO()->getNVertices(), times);
} else if(arbSupported) {
glDrawArraysInstancedARB(model->getPrimitive(), 0, model->getVBO()->getNVertices(), times);
} else if(extSupported) {
// ......
} else {
for(int i = 0; i < times; i++) {
glDrawArrays(model->getPrimitive(), 0, model->getVBO()->getNVertices());
}
}
unbindVBO(model->getVBO());
}
void GLDrawController::callRender(Model * model) {
model->render(ogl);
}
#define ATTRIB_POINTER_OFFSET(offset) ((GLbyte *)NULL + (offset))
void GLDrawController::bindVBO(VertexBuffer * buffer) {
glEnable(GL_VERTEX_ARRAY);
buffer->getBuffer()->bindOn(Buffer::VertexBuffer);
std::vector<VertexAttrib>::iterator attr;
std::vector<VertexAttrib> & attribs = buffer->getAttribs();
for(attr = attribs.begin(); attr != attribs.end(); attr++) {
if(attr->getType() == VertexAttrib::VERTEX) {
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
}
else if (attr->getType() == VertexAttrib::NORMAL) {
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
} else if(attr->getType() == VertexAttrib::COLOR) {
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
} else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
glEnableClientState(GL_SECONDARY_COLOR_ARRAY);
glSecondaryColorPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
} else if(attr->getType() == VertexAttrib::TEXCOORD) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(attr->getNCoord(), GL_FLOAT, attr->getStride(), ATTRIB_POINTER_OFFSET(attr->getOffset()));
}
}
}
#undef ATTRIB_POINTER_OFFSET
void GLDrawController::unbindVBO(VertexBuffer * buffer) {
std::vector<VertexAttrib>::iterator attr;
std::vector<VertexAttrib> & attribs = buffer->getAttribs();
for(attr = attribs.begin(); attr != attribs.end(); attr++) {
if(attr->getType() == VertexAttrib::VERTEX) {
glDisableClientState(GL_VERTEX_ARRAY);
}
else if (attr->getType() == VertexAttrib::NORMAL) {
glDisableClientState(GL_NORMAL_ARRAY);
} else if(attr->getType() == VertexAttrib::COLOR) {
glDisableClientState(GL_COLOR_ARRAY);
} else if(attr->getType() == VertexAttrib::SECONDARY_COLOR) {
glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
} else if(attr->getType() == VertexAttrib::TEXCOORD) {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
}
buffer->getBuffer()->unbind();
glDisable(GL_VERTEX_ARRAY);
}
<|endoftext|> |
<commit_before>/**
* @name Diogo Dantas
* date 14-10-2016
*/
#ifndef MOCHILA_BINARIA_HPP
#define MOCHILA_BINARIA_HPP
#include <vector>
namespace dinamica {
/**
* @brief { Função que calcula o valor máximo que é possivel colocar na mochila
* de capacidade weight}
*
* @param[in] weight Capacidade da mochila
* @param weight_vector Vetor que armazena o peso dos itens
* @param values_vector The que armazena o valor dos itens
* @param[in] num_itens Número de itens
*
*/
int mochila_binaria(const int weight, std::vector<int> & weight_vector, std::vector<int> & values_vector, const int num_itens);
}
#endif // MOCHILA_BINARIA_HPP
<commit_msg>Atualização na documentação do problema da Mochila Binária<commit_after>/**
* @name Diogo Dantas
* date 14-10-2016
*/
#ifndef MOCHILA_BINARIA_HPP
#define MOCHILA_BINARIA_HPP
#include <vector>
namespace dinamica {
/**
* @brief { Função que calcula o valor máximo que é possivel colocar na mochila
* de capacidade weight}
*
* @param[in] weight Capacidade da mochila
* @param weight_vector Vetor que armazena o peso dos itens
* @param values_vector Vetor que armazena o valor dos itens
* @param[in] num_itens Número de itens
*
*/
int mochila_binaria(const int weight, std::vector<int> & weight_vector, std::vector<int> & values_vector, const int num_itens);
}
#endif // MOCHILA_BINARIA_HPP
<|endoftext|> |
<commit_before>#include<stdlib.h>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<time.h>
#pragma comment(lib,"opencv_world320.lib")
static const int N = 256;//文字列の長さ
int main(void) {
char full_command[N];
char front_command[] = "sudo raspistill -o ";//command
char full_path[N];
char directry_path[] = "/home/pi/object";//pathの先頭
char name_path[N];//時間を文字列に変換するときに代入する変数
char file_extention[] = ".jpg";//拡張子
time_t timer;//時刻を受け取る変数
struct tm *timeptr;//日時を集めた構造体ポインタ
time(&timer);//現在時刻の取得
timeptr = localtime(&timer);//ポインタ
strftime(name_path, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入
sprintf(full_path, "%s%s%s",directry_path, name_path, file_extention);
sprintf(full_command, "%s%s", front_command, full_path);//コマンドの文字列をつなげる。
system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。
cv::Mat src,dst,dst_filtered;
dst_filtered = cv::Scalar(0, 0, 0);//画像の初期化
double count = 0; //赤色を認識したピクセルの数
double percentage = 0; //割合
double Area = dst.rows*dst.cols;//全ピクセル数
src =cv::imread(full_path);
cv::cvtColor(src, dst, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(dst, cv::Scalar(160, 150, 0), cv::Scalar(190, 255, 255), dst_filtered);
count = cv::countNonZero(dst_filtered);//赤色部分の面積を計算
percentage = count / Area;//割合を計算
printf("赤色の面積の割合は%f\n", percentage);
}
<commit_msg>debug<commit_after>#include<stdlib.h>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<time.h>
#pragma comment(lib,"opencv_world320.lib")
static const int N = 256;//文字列の長さ
int main(void) {
char full_command[N];
char front_command[] = "sudo raspistill -o ";//command
char full_path[N];
char directry_path[] = "/home/pi/object";//pathの先頭
char name_path[N];//時間を文字列に変換するときに代入する変数
char file_extention[] = ".jpg";//拡張子
time_t timer;//時刻を受け取る変数
struct tm *timeptr;//日時を集めた構造体ポインタ
time(&timer);//現在時刻の取得
timeptr = localtime(&timer);//ポインタ
strftime(name_path, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入
sprintf(full_path, "%s%s%s",directry_path, name_path, file_extention);
sprintf(full_command, "%s%s", front_command, full_path);//コマンドの文字列をつなげる。
system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。
cv::Mat src,dst,dst_filtered;
dst_filtered = cv::Scalar(0, 0, 0);//画像の初期化
double count = 0; //赤色を認識したピクセルの数
double percentage = 0; //割合
src =cv::imread(full_path);
cv::cvtColor(src, dst, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(dst, cv::Scalar(160, 150, 0), cv::Scalar(190, 255, 255), dst_filtered);
count = cv::countNonZero(dst_filtered);//赤色部分の面積を計算
double Area = dst.rows*dst.cols;//全ピクセル数の計算
percentage = count / Area;//割合を計算
printf("赤色の面積の割合は%f\n", percentage);
}
<|endoftext|> |
<commit_before>#include "GraphToolsGTest.h"
#include "../Graph.h"
#include "../GraphTools.h"
namespace NetworKit {
TEST_F(GraphToolsGTest, testGetContinuousOnContinuous) {
Graph G(10);
auto nodeIds = GraphTools::getContinuousNodeIds(G);
std::unordered_map<node,node> reference = {{0,0},{1,1},{2,2},{3,3},{4,4},{5,5},{6,6},{7,7},{8,8},{9,9}};
EXPECT_EQ(reference,nodeIds);
}
TEST_F(GraphToolsGTest, testGetContinuousOnDeletedNodes1) {
Graph G(10);
G.removeNode(0);
G.removeNode(1);
G.removeNode(2);
G.removeNode(3);
G.removeNode(4);
auto nodeIds = GraphTools::getContinuousNodeIds(G);
std::unordered_map<node,node> reference = {{5,0},{6,1},{7,2},{8,3},{9,4}};
EXPECT_EQ(reference,nodeIds);
}
TEST_F(GraphToolsGTest, testGetContinuousOnDeletedNodes2) {
Graph G(10);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
auto nodeIds = GraphTools::getContinuousNodeIds(G);
std::unordered_map<node,node> reference = {{1,0},{3,1},{5,2},{7,3},{9,4}};
EXPECT_EQ(reference,nodeIds);
}
TEST_F(GraphToolsGTest, testGetCompactedGraphUndirectedUnweighted1) {
Graph G(10,false,false);
G.addEdge(0,1);
G.addEdge(2,1);
G.addEdge(0,3);
G.addEdge(2,4);
G.addEdge(3,6);
G.addEdge(4,8);
G.addEdge(5,9);
G.addEdge(3,7);
G.addEdge(5,7);
auto Gcompact = GraphTools::getCompactedGraph(G);
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphUndirectedUnweighted2) {
Graph G(10,false,false);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3);
G.addEdge(5,3);
G.addEdge(7,5);
G.addEdge(7,9);
G.addEdge(1,9);
auto Gcompact = GraphTools::getCompactedGraph(G);
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphUndirectedWeighted1) {
Graph G(10,true,false);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3,0.2);
G.addEdge(5,3,2132.351);
G.addEdge(7,5,3.14);
G.addEdge(7,9,2.7);
G.addEdge(1,9,0.12345);
auto Gcompact = GraphTools::getCompactedGraph(G);
EXPECT_EQ(G.totalEdgeWeight(),Gcompact.totalEdgeWeight());
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphDirectedWeighted1) {
Graph G(10,true,true);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3,0.2);
G.addEdge(5,3,2132.351);
G.addEdge(7,5,3.14);
G.addEdge(7,9,2.7);
G.addEdge(1,9,0.12345);
auto Gcompact = GraphTools::getCompactedGraph(G);
EXPECT_EQ(G.totalEdgeWeight(),Gcompact.totalEdgeWeight());
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphDirectedUnweighted1) {
Graph G(10,false,true);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3);
G.addEdge(5,3);
G.addEdge(7,5);
G.addEdge(7,9);
G.addEdge(1,9);
auto Gcompact = GraphTools::getCompactedGraph(G);
EXPECT_EQ(G.totalEdgeWeight(),Gcompact.totalEdgeWeight());
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
}<commit_msg>fixed broken test cases<commit_after>#include "GraphToolsGTest.h"
#include "../Graph.h"
#include "../GraphTools.h"
namespace NetworKit {
TEST_F(GraphToolsGTest, testGetContinuousOnContinuous) {
Graph G(10);
auto nodeIds = GraphTools::getContinuousNodeIds(G);
std::unordered_map<node,node> reference = {{0,0},{1,1},{2,2},{3,3},{4,4},{5,5},{6,6},{7,7},{8,8},{9,9}};
EXPECT_EQ(reference,nodeIds);
}
TEST_F(GraphToolsGTest, testGetContinuousOnDeletedNodes1) {
Graph G(10);
G.removeNode(0);
G.removeNode(1);
G.removeNode(2);
G.removeNode(3);
G.removeNode(4);
auto nodeIds = GraphTools::getContinuousNodeIds(G);
std::unordered_map<node,node> reference = {{5,0},{6,1},{7,2},{8,3},{9,4}};
EXPECT_EQ(reference,nodeIds);
}
TEST_F(GraphToolsGTest, testGetContinuousOnDeletedNodes2) {
Graph G(10);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
auto nodeIds = GraphTools::getContinuousNodeIds(G);
std::unordered_map<node,node> reference = {{1,0},{3,1},{5,2},{7,3},{9,4}};
EXPECT_EQ(reference,nodeIds);
}
TEST_F(GraphToolsGTest, testGetCompactedGraphUndirectedUnweighted1) {
Graph G(10,false,false);
G.addEdge(0,1);
G.addEdge(2,1);
G.addEdge(0,3);
G.addEdge(2,4);
G.addEdge(3,6);
G.addEdge(4,8);
G.addEdge(5,9);
G.addEdge(3,7);
G.addEdge(5,7);
auto nodeMap = GraphTools::getContinuousNodeIds(G);
auto Gcompact = GraphTools::getCompactedGraph(G,nodeMap);
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphUndirectedUnweighted2) {
Graph G(10,false,false);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3);
G.addEdge(5,3);
G.addEdge(7,5);
G.addEdge(7,9);
G.addEdge(1,9);
auto nodeMap = GraphTools::getContinuousNodeIds(G);
auto Gcompact = GraphTools::getCompactedGraph(G,nodeMap);
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphUndirectedWeighted1) {
Graph G(10,true,false);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3,0.2);
G.addEdge(5,3,2132.351);
G.addEdge(7,5,3.14);
G.addEdge(7,9,2.7);
G.addEdge(1,9,0.12345);
auto nodeMap = GraphTools::getContinuousNodeIds(G);
auto Gcompact = GraphTools::getCompactedGraph(G,nodeMap);
EXPECT_EQ(G.totalEdgeWeight(),Gcompact.totalEdgeWeight());
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphDirectedWeighted1) {
Graph G(10,true,true);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3,0.2);
G.addEdge(5,3,2132.351);
G.addEdge(7,5,3.14);
G.addEdge(7,9,2.7);
G.addEdge(1,9,0.12345);
auto nodeMap = GraphTools::getContinuousNodeIds(G);
auto Gcompact = GraphTools::getCompactedGraph(G,nodeMap);
EXPECT_EQ(G.totalEdgeWeight(),Gcompact.totalEdgeWeight());
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
TEST_F(GraphToolsGTest, testGetCompactedGraphDirectedUnweighted1) {
Graph G(10,false,true);
G.removeNode(0);
G.removeNode(2);
G.removeNode(4);
G.removeNode(6);
G.removeNode(8);
G.addEdge(1,3);
G.addEdge(5,3);
G.addEdge(7,5);
G.addEdge(7,9);
G.addEdge(1,9);
auto nodeMap = GraphTools::getContinuousNodeIds(G);
auto Gcompact = GraphTools::getCompactedGraph(G,nodeMap);
EXPECT_EQ(G.totalEdgeWeight(),Gcompact.totalEdgeWeight());
EXPECT_NE(G.upperNodeIdBound(),Gcompact.upperNodeIdBound());
EXPECT_EQ(G.numberOfNodes(),Gcompact.numberOfNodes());
EXPECT_EQ(G.numberOfEdges(),Gcompact.numberOfEdges());
EXPECT_EQ(G.isDirected(),Gcompact.isDirected());
EXPECT_EQ(G.isWeighted(),Gcompact.isWeighted());
// TODOish: find a deeper test to check if the structure of the graphs are the same,
// probably compare results of some algorithms or compare each edge with a reference node id map.
}
}<|endoftext|> |
<commit_before>#include "ExeBox.h"
#include <Entry.h>
#include <FindDirectory.h>
#include <Directory.h>
#include <storage/Node.h>
#include <OS.h>
#include <File.h>
#include <storage/Path.h>
#include <Locker.h>
#include "ObjectList.h"
#include <Volume.h>
#include <VolumeRoster.h>
#include <Query.h>
static BObjectList<entry_ref> *sPathData = NULL;
BLocker sPathDataLock;
thread_id sThreadID = -1;
void PrintList(const char* s)
{
sPathDataLock.Lock();
int len = sPathData->CountItems();
printf("Count: %i\nsPathData (%s) :\n", len, s);
for ( int i = 0; i < len ; i += 3 )
{
printf("%i: %-13.13s\t", i, sPathData->ItemAt(i)->name);
if ( i+1 < len )
printf("%i: %-13.13s\t", i+1, sPathData->ItemAt(i+1)->name);
if ( i+2 < len )
printf("%i: %-13.13s\t", i+2, sPathData->ItemAt(i+2)->name);
printf("\n");
}
sPathDataLock.Unlock();
}
ExeBoxFilter::ExeBoxFilter(ExeBox *box)
: AutoTextControlFilter(box)
{
}
filter_result
ExeBoxFilter::KeyFilter(const int32 &key, const int32 &mod)
{
if (key < 32 || ( (mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) &&
!(mod & B_OPTION_KEY) && !(mod & B_CONTROL_KEY)) )
return B_DISPATCH_MESSAGE;
int32 start, end;
TextControl()->TextView()->GetSelection(&start,&end);
if (end == (int32)strlen(TextControl()->Text()))
{
TextControl()->TextView()->Delete(start,end);
BString string;
if( GetCurrentMessage()->FindString("bytes",&string) != B_OK)
string = "";
string.Prepend(TextControl()->Text());
entry_ref *match = NULL, *data;;
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
data = sPathData->ItemAt(i);
BString namestr(data->name);
if (!data->name)
continue;
if (namestr.IFindFirst(string) == 0)
{
match = data;
break;
}
}
sPathDataLock.Unlock();
if(match)
{
BMessage automsg(M_EXE_AUTOCOMPLETE);
automsg.AddInt32("start",strlen(TextControl()->Text())+1);
automsg.AddString("string",match->name);
BMessenger msgr((BHandler*)TextControl()->Window());
msgr.SendMessage(&automsg);
}
}
return B_DISPATCH_MESSAGE;
}
ExeBox::ExeBox(const BRect &frame, const char *name, const char *label,
const char *text, BMessage *msg, uint32 resize, uint32 flags)
: AutoTextControl(frame,name,label,text,msg,resize,flags)
{
if (!sPathData)
InitializeAutocompletion();
SetFilter(new ExeBoxFilter(this));
SetCharacterLimit(32);
}
ExeBox::~ExeBox(void)
{
int32 value;
sPathDataLock.Lock();
if (sThreadID >= 0)
{
sPathDataLock.Unlock();
wait_for_thread(sThreadID,&value);
}
else
sPathDataLock.Unlock();
}
entry_ref *
ExeBox::FindMatch(const char *name)
{
// Handle the autocompletion
if (!name)
return NULL;
entry_ref *match = NULL;
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *data = sPathData->ItemAt(i);
if (!data->name)
continue;
BString refstr(data->name);
if (refstr.IFindFirst(name) == 0)
{
match = data;
break;
}
}
sPathDataLock.Unlock();
return match;
}
void
ExeBox::InitializeAutocompletion(void)
{
sPathData = new BObjectList<entry_ref>(20,true);
// Set up autocomplete
BEntry entry("/boot/home/config/settings/Run Program");
BPath path;
entry_ref ref;
if (entry.Exists())
{
BFile settingsFile("/boot/home/config/settings/Run Program",B_READ_ONLY);
BMessage settings;
if (settings.Unflatten(&settingsFile) == B_OK)
{
int32 index = 0;
while (settings.FindRef("refs",index,&ref) == B_OK)
{
index++;
entry_ref *listref = new entry_ref(ref);
sPathData->AddItem(listref);
}
sThreadID = spawn_thread(UpdateThread,
"updatethread", B_NORMAL_PRIORITY, NULL);
if (sThreadID >= 0)
resume_thread(sThreadID);
return;
}
}
BDirectory dir;
find_directory(B_BEOS_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref,true);
entry.GetRef(&ref);
entry_ref *match = NULL;
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *listref = sPathData->ItemAt(i);
if (*listref == ref)
{
match = listref;
break;
}
}
if (!match)
sPathData->AddItem(new entry_ref(ref));
}
find_directory(B_SYSTEM_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref, true);
entry.GetRef(&ref);
entry_ref *match = NULL;
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *listref = sPathData->ItemAt(i);
if (*listref == ref)
{
match = listref;
break;
}
}
if (!match)
sPathData->AddItem(new entry_ref(ref));
}
sThreadID = spawn_thread(QueryThread, "querythread", B_NORMAL_PRIORITY, NULL);
if (sThreadID >= 0)
resume_thread(sThreadID);
}
static
int
CompareRefs(const entry_ref *ref1, const entry_ref *ref2)
{
if (!ref1)
return -1;
else if (!ref2)
return 1;
return strcmp(ref1->name,ref2->name);
}
int32
ExeBox::QueryThread(void *data)
{
BVolumeRoster roster;
BVolume vol;
BQuery query;
entry_ref ref;
roster.GetBootVolume(&vol);
query.SetVolume(&vol);
query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&"
"(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))");
query.Fetch();
while (query.GetNextRef(&ref) == B_OK)
{
if ( ref.directory == B_USER_ADDONS_DIRECTORY
|| ref.directory == B_BEOS_ADDONS_DIRECTORY
|| ref.directory == B_SYSTEM_ADDONS_DIRECTORY)
continue;
if (ref.directory == -1)
{
fprintf(stderr, "FATAL : Query returned invalid ref!\n");
return -1;
}
sPathDataLock.Lock();
sPathData->AddItem(new entry_ref(ref));
sPathDataLock.Unlock();
}
BMessage settings;
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
settings.AddRef("refs", sPathData->ItemAt(i));
sPathDataLock.Unlock();
BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE |
B_ERASE_FILE |
B_CREATE_FILE);
settings.Flatten(&settingsFile);
sPathDataLock.Lock();
sThreadID = -1;
sPathDataLock.Unlock();
return 0;
}
int32
ExeBox::UpdateThread(void *data)
{
// This takes longer, but it's not really time-critical. Most of the time there
// will only be minor differences between run sessions.
// In order to save as much time as possible:
// 1) Get a new ref list via scanning the usual places. This won't take long, thanks
// to the file cache. :)
// 2) For each item in the official list
// - if entry doesn't exist, remove it
// - if entry does exist, remove it from the temporary list
// 3) Add any remaining entries in the temporary list to the official one
// 4) Update the disk version of the settings file
BObjectList<entry_ref> queryList(20,true);
BDirectory dir;
BPath path;
entry_ref ref, *pref;
BEntry entry;
BVolumeRoster roster;
BVolume vol;
BQuery query;
find_directory(B_BEOS_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref, true);
entry.GetRef(&ref);
entry.Unset();
queryList.AddItem(new entry_ref(ref));
}
find_directory(B_SYSTEM_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref,true);
entry.GetRef(&ref);
entry.Unset();
queryList.AddItem(new entry_ref(ref));
}
roster.GetBootVolume(&vol);
query.SetVolume(&vol);
query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&"
"(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))");
query.Fetch();
while (query.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref,true);
entry.GetPath(&path);
entry.GetRef(&ref);
entry.Unset();
if (strstr(path.Path(),"add-ons") || strstr(path.Path(),"beos/servers") ||
!ref.name)
continue;
queryList.AddItem(new entry_ref(ref));
}
// Scan is finished, so start culling
sPathDataLock.Lock();
int32 count = sPathData->CountItems();
sPathDataLock.Unlock();
for (int32 i = 0; i < count; i++)
{
sPathDataLock.Lock();
pref = sPathData->ItemAt(i);
entry.SetTo(pref);
if (! entry.Exists() )
sPathData->RemoveItemAt( i );
else
{
for (int32 j = 0; j < queryList.CountItems(); j++)
{
if (*pref == *queryList.ItemAt(j))
{
queryList.RemoveItemAt(j);
break;
}
}
}
entry.Unset();
sPathDataLock.Unlock();
}
// Remaining items in queryList are new entries
sPathDataLock.Lock();
for (int32 j = 0; j < queryList.CountItems(); j++)
{
entry_ref *qref = queryList.RemoveItemAt(j);
if (qref && qref->directory >= 0)
sPathData->AddItem(qref);
}
sPathDataLock.Unlock();
BMessage settings;
sPathDataLock.Lock();
sPathData->SortItems(CompareRefs);
sPathDataLock.Unlock();
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *listref = sPathData->ItemAt(i);
settings.AddRef("refs",listref);
}
sPathDataLock.Unlock();
BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE |
B_ERASE_FILE |
B_CREATE_FILE);
settings.Flatten(&settingsFile);
sPathDataLock.Lock();
sThreadID = -1;
sPathDataLock.Unlock();
return 0;
}
<commit_msg>Fix includes for building with gcc4<commit_after>#include "ExeBox.h"
#include <Entry.h>
#include <FindDirectory.h>
#include <Directory.h>
#include <storage/Node.h>
#include <OS.h>
#include <File.h>
#include <storage/Path.h>
#include <Locker.h>
#include "ObjectList.h"
#include <Volume.h>
#include <VolumeRoster.h>
#include <Query.h>
#include <stdio.h>
static BObjectList<entry_ref> *sPathData = NULL;
BLocker sPathDataLock;
thread_id sThreadID = -1;
void PrintList(const char* s)
{
sPathDataLock.Lock();
int len = sPathData->CountItems();
printf("Count: %i\nsPathData (%s) :\n", len, s);
for ( int i = 0; i < len ; i += 3 )
{
printf("%i: %-13.13s\t", i, sPathData->ItemAt(i)->name);
if ( i+1 < len )
printf("%i: %-13.13s\t", i+1, sPathData->ItemAt(i+1)->name);
if ( i+2 < len )
printf("%i: %-13.13s\t", i+2, sPathData->ItemAt(i+2)->name);
printf("\n");
}
sPathDataLock.Unlock();
}
ExeBoxFilter::ExeBoxFilter(ExeBox *box)
: AutoTextControlFilter(box)
{
}
filter_result
ExeBoxFilter::KeyFilter(const int32 &key, const int32 &mod)
{
if (key < 32 || ( (mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) &&
!(mod & B_OPTION_KEY) && !(mod & B_CONTROL_KEY)) )
return B_DISPATCH_MESSAGE;
int32 start, end;
TextControl()->TextView()->GetSelection(&start,&end);
if (end == (int32)strlen(TextControl()->Text()))
{
TextControl()->TextView()->Delete(start,end);
BString string;
if( GetCurrentMessage()->FindString("bytes",&string) != B_OK)
string = "";
string.Prepend(TextControl()->Text());
entry_ref *match = NULL, *data;;
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
data = sPathData->ItemAt(i);
BString namestr(data->name);
if (!data->name)
continue;
if (namestr.IFindFirst(string) == 0)
{
match = data;
break;
}
}
sPathDataLock.Unlock();
if(match)
{
BMessage automsg(M_EXE_AUTOCOMPLETE);
automsg.AddInt32("start",strlen(TextControl()->Text())+1);
automsg.AddString("string",match->name);
BMessenger msgr((BHandler*)TextControl()->Window());
msgr.SendMessage(&automsg);
}
}
return B_DISPATCH_MESSAGE;
}
ExeBox::ExeBox(const BRect &frame, const char *name, const char *label,
const char *text, BMessage *msg, uint32 resize, uint32 flags)
: AutoTextControl(frame,name,label,text,msg,resize,flags)
{
if (!sPathData)
InitializeAutocompletion();
SetFilter(new ExeBoxFilter(this));
SetCharacterLimit(32);
}
ExeBox::~ExeBox(void)
{
int32 value;
sPathDataLock.Lock();
if (sThreadID >= 0)
{
sPathDataLock.Unlock();
wait_for_thread(sThreadID,&value);
}
else
sPathDataLock.Unlock();
}
entry_ref *
ExeBox::FindMatch(const char *name)
{
// Handle the autocompletion
if (!name)
return NULL;
entry_ref *match = NULL;
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *data = sPathData->ItemAt(i);
if (!data->name)
continue;
BString refstr(data->name);
if (refstr.IFindFirst(name) == 0)
{
match = data;
break;
}
}
sPathDataLock.Unlock();
return match;
}
void
ExeBox::InitializeAutocompletion(void)
{
sPathData = new BObjectList<entry_ref>(20,true);
// Set up autocomplete
BEntry entry("/boot/home/config/settings/Run Program");
BPath path;
entry_ref ref;
if (entry.Exists())
{
BFile settingsFile("/boot/home/config/settings/Run Program",B_READ_ONLY);
BMessage settings;
if (settings.Unflatten(&settingsFile) == B_OK)
{
int32 index = 0;
while (settings.FindRef("refs",index,&ref) == B_OK)
{
index++;
entry_ref *listref = new entry_ref(ref);
sPathData->AddItem(listref);
}
sThreadID = spawn_thread(UpdateThread,
"updatethread", B_NORMAL_PRIORITY, NULL);
if (sThreadID >= 0)
resume_thread(sThreadID);
return;
}
}
BDirectory dir;
find_directory(B_BEOS_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref,true);
entry.GetRef(&ref);
entry_ref *match = NULL;
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *listref = sPathData->ItemAt(i);
if (*listref == ref)
{
match = listref;
break;
}
}
if (!match)
sPathData->AddItem(new entry_ref(ref));
}
find_directory(B_SYSTEM_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref, true);
entry.GetRef(&ref);
entry_ref *match = NULL;
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *listref = sPathData->ItemAt(i);
if (*listref == ref)
{
match = listref;
break;
}
}
if (!match)
sPathData->AddItem(new entry_ref(ref));
}
sThreadID = spawn_thread(QueryThread, "querythread", B_NORMAL_PRIORITY, NULL);
if (sThreadID >= 0)
resume_thread(sThreadID);
}
static
int
CompareRefs(const entry_ref *ref1, const entry_ref *ref2)
{
if (!ref1)
return -1;
else if (!ref2)
return 1;
return strcmp(ref1->name,ref2->name);
}
int32
ExeBox::QueryThread(void *data)
{
BVolumeRoster roster;
BVolume vol;
BQuery query;
entry_ref ref;
roster.GetBootVolume(&vol);
query.SetVolume(&vol);
query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&"
"(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))");
query.Fetch();
while (query.GetNextRef(&ref) == B_OK)
{
if ( ref.directory == B_USER_ADDONS_DIRECTORY
|| ref.directory == B_BEOS_ADDONS_DIRECTORY
|| ref.directory == B_SYSTEM_ADDONS_DIRECTORY)
continue;
if (ref.directory == -1)
{
fprintf(stderr, "FATAL : Query returned invalid ref!\n");
return -1;
}
sPathDataLock.Lock();
sPathData->AddItem(new entry_ref(ref));
sPathDataLock.Unlock();
}
BMessage settings;
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
settings.AddRef("refs", sPathData->ItemAt(i));
sPathDataLock.Unlock();
BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE |
B_ERASE_FILE |
B_CREATE_FILE);
settings.Flatten(&settingsFile);
sPathDataLock.Lock();
sThreadID = -1;
sPathDataLock.Unlock();
return 0;
}
int32
ExeBox::UpdateThread(void *data)
{
// This takes longer, but it's not really time-critical. Most of the time there
// will only be minor differences between run sessions.
// In order to save as much time as possible:
// 1) Get a new ref list via scanning the usual places. This won't take long, thanks
// to the file cache. :)
// 2) For each item in the official list
// - if entry doesn't exist, remove it
// - if entry does exist, remove it from the temporary list
// 3) Add any remaining entries in the temporary list to the official one
// 4) Update the disk version of the settings file
BObjectList<entry_ref> queryList(20,true);
BDirectory dir;
BPath path;
entry_ref ref, *pref;
BEntry entry;
BVolumeRoster roster;
BVolume vol;
BQuery query;
find_directory(B_BEOS_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref, true);
entry.GetRef(&ref);
entry.Unset();
queryList.AddItem(new entry_ref(ref));
}
find_directory(B_SYSTEM_BIN_DIRECTORY,&path);
dir.SetTo(path.Path());
dir.Rewind();
while (dir.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref,true);
entry.GetRef(&ref);
entry.Unset();
queryList.AddItem(new entry_ref(ref));
}
roster.GetBootVolume(&vol);
query.SetVolume(&vol);
query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&"
"(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))");
query.Fetch();
while (query.GetNextRef(&ref) == B_OK)
{
entry.SetTo(&ref,true);
entry.GetPath(&path);
entry.GetRef(&ref);
entry.Unset();
if (strstr(path.Path(),"add-ons") || strstr(path.Path(),"beos/servers") ||
!ref.name)
continue;
queryList.AddItem(new entry_ref(ref));
}
// Scan is finished, so start culling
sPathDataLock.Lock();
int32 count = sPathData->CountItems();
sPathDataLock.Unlock();
for (int32 i = 0; i < count; i++)
{
sPathDataLock.Lock();
pref = sPathData->ItemAt(i);
entry.SetTo(pref);
if (! entry.Exists() )
sPathData->RemoveItemAt( i );
else
{
for (int32 j = 0; j < queryList.CountItems(); j++)
{
if (*pref == *queryList.ItemAt(j))
{
queryList.RemoveItemAt(j);
break;
}
}
}
entry.Unset();
sPathDataLock.Unlock();
}
// Remaining items in queryList are new entries
sPathDataLock.Lock();
for (int32 j = 0; j < queryList.CountItems(); j++)
{
entry_ref *qref = queryList.RemoveItemAt(j);
if (qref && qref->directory >= 0)
sPathData->AddItem(qref);
}
sPathDataLock.Unlock();
BMessage settings;
sPathDataLock.Lock();
sPathData->SortItems(CompareRefs);
sPathDataLock.Unlock();
sPathDataLock.Lock();
for (int32 i = 0; i < sPathData->CountItems(); i++)
{
entry_ref *listref = sPathData->ItemAt(i);
settings.AddRef("refs",listref);
}
sPathDataLock.Unlock();
BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE |
B_ERASE_FILE |
B_CREATE_FILE);
settings.Flatten(&settingsFile);
sPathDataLock.Lock();
sThreadID = -1;
sPathDataLock.Unlock();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>impress210: #i106378# use datetime to get current date<commit_after><|endoftext|> |
<commit_before>#include "fence.hpp"
#include <stdexcept>
// Max timeout before killing program
const int criticalWaitTime = 5000000000;
Fence::Fence(Fence&& fence) : sync{fence.sync}
{
fence.sync = 0;
}
Fence &Fence::operator=(Fence && fence)
{
if (sync && fence.sync != sync) glDeleteSync(sync);
sync = fence.sync;
fence.sync = 0;
return *this;
}
Fence::~Fence()
{
if (sync) glDeleteSync(sync);
}
void Fence::wait()
{
if (!sync) return;
glWaitSync(sync, 0, GL_TIMEOUT_IGNORED);
}
bool Fence::waitClient(int64_t timeout)
{
if (!sync) return true;
const GLenum ret = glClientWaitSync(sync, 0, (timeout == -1)?criticalWaitTime:timeout);
if (ret == GL_CONDITION_SATISFIED ||
ret == GL_ALREADY_SIGNALED) return true;
if (ret == GL_TIMEOUT_EXPIRED)
{
if (timeout == -1) throw std::runtime_error("Waited too long on fence");
return false;
}
if (ret == GL_WAIT_FAILED)
{
throw std::runtime_error("Fence wait failed");
}
}
void Fence::lock()
{
if (sync) glDeleteSync(sync);
sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
<commit_msg>Fix wrong type<commit_after>#include "fence.hpp"
#include <stdexcept>
// Max timeout before killing program
const int64_t criticalWaitTime = 5000000000;
Fence::Fence(Fence&& fence) : sync{fence.sync}
{
fence.sync = 0;
}
Fence &Fence::operator=(Fence && fence)
{
if (sync && fence.sync != sync) glDeleteSync(sync);
sync = fence.sync;
fence.sync = 0;
return *this;
}
Fence::~Fence()
{
if (sync) glDeleteSync(sync);
}
void Fence::wait()
{
if (!sync) return;
glWaitSync(sync, 0, GL_TIMEOUT_IGNORED);
}
bool Fence::waitClient(int64_t timeout)
{
if (!sync) return true;
const GLenum ret = glClientWaitSync(sync, 0, (timeout == -1)?criticalWaitTime:timeout);
if (ret == GL_CONDITION_SATISFIED ||
ret == GL_ALREADY_SIGNALED) return true;
if (ret == GL_TIMEOUT_EXPIRED)
{
if (timeout == -1) throw std::runtime_error("Waited too long on fence");
return false;
}
if (ret == GL_WAIT_FAILED)
{
throw std::runtime_error("Fence wait failed");
}
}
void Fence::lock()
{
if (sync) glDeleteSync(sync);
sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: PathPoint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Peter Loan *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "PathPoint.h"
#include "BodySet.h"
#include "Model.h"
#include "GeometryPath.h"
#include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h>
#include <OpenSim/Simulation/Wrap/WrapObject.h>
#include <OpenSim/Simulation/Model/Geometry.h>
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
using SimTK::Vec3;
using SimTK::Transform;
void PathPoint::
changeBodyPreserveLocation(const SimTK::State& s, const PhysicalFrame& body)
{
if (!hasParent()) {
throw Exception("PathPoint::changeBodyPreserveLocation attempted to "
" change the body on PathPoint which was not assigned to a body.");
}
// if it is already assigned to aBody, do nothing
const PhysicalFrame& currentFrame = getParentFrame();
if (currentFrame == body)
return;
// Preserve location means to switch bodies without changing
// the location of the point in the inertial reference frame.
upd_location() = currentFrame.findLocationInAnotherFrame(s, get_location(), body);
// now assign this point's body to point to aBody
setParentFrame(body);
}
void PathPoint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
int documentVersion = versionNumber;
if (documentVersion < XMLDocument::getLatestVersion()) {
if (documentVersion < 30505) {
// replace old properties with latest use of Connectors
SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body");
std::string bodyName("");
if (bodyElement != aNode.element_end()) {
bodyElement->getValueAs<std::string>(bodyName);
XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_",
"parent_frame", bodyName);
}
}
}
Super::updateFromXMLNode(aNode, versionNumber);
}
<commit_msg>Update comment<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: PathPoint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Peter Loan *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "PathPoint.h"
#include "BodySet.h"
#include "Model.h"
#include "GeometryPath.h"
#include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h>
#include <OpenSim/Simulation/Wrap/WrapObject.h>
#include <OpenSim/Simulation/Model/Geometry.h>
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
using SimTK::Vec3;
using SimTK::Transform;
void PathPoint::
changeBodyPreserveLocation(const SimTK::State& s, const PhysicalFrame& body)
{
if (!hasParent()) {
throw Exception("PathPoint::changeBodyPreserveLocation attempted to "
" change the body on PathPoint which was not assigned to a body.");
}
// if it is already assigned to aBody, do nothing
const PhysicalFrame& currentFrame = getParentFrame();
if (currentFrame == body)
return;
// Preserve location means to switch bodies without changing
// the location of the point in the inertial reference frame.
upd_location() = currentFrame.findLocationInAnotherFrame(s, get_location(), body);
// now make "body" this PathPoint's parent Frame
setParentFrame(body);
}
void PathPoint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
int documentVersion = versionNumber;
if (documentVersion < XMLDocument::getLatestVersion()) {
if (documentVersion < 30505) {
// replace old properties with latest use of Connectors
SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body");
std::string bodyName("");
if (bodyElement != aNode.element_end()) {
bodyElement->getValueAs<std::string>(bodyName);
XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_",
"parent_frame", bodyName);
}
}
}
Super::updateFromXMLNode(aNode, versionNumber);
}
<|endoftext|> |
<commit_before>///
/// @file FactorTable.hpp
/// @brief The FactorTable class is used to save memory. It combines
/// the lpf[n] (least prime factor) and mu[n] (Möbius function)
/// lookup tables into a single factor_table[n] which
/// furthermore only contains entries for numbers which are
/// not divisible by 2, 3, 5 and 7.
/// The factor table concept has first been devised and
/// implemented by Christian Bau in 2003.
///
/// FactorTable.lpf(index) is equal to (n = get_number(index)):
///
/// * 0 if moebius(n) = 0
/// * lpf if !is_prime(n) && moebius(n) = -1
/// * lpf-1 if !is_prime(n) && moebius(n) = 1
/// * n if is_prime(n) && n < T_MAX
/// * T_MAX if is_prime(n) && n > T_MAX
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP
#include <primecount.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <cassert>
#include <limits>
#include <stdint.h>
#include <vector>
namespace primecount {
namespace sft {
/// Convert a wheel index to a wheel number
extern const uint8_t to_number[48];
/// Convert a wheel number to a wheel index
extern const int8_t to_index[210];
}
template <typename T>
class FactorTable
{
public:
FactorTable(int64_t max) :
max_(std::max(max, (int64_t) 8))
{
T T_MAX = std::numeric_limits<T>::max();
if (isqrt(max_) >= T_MAX)
throw primecount_error("FactorTable: sqrt(max) must be < T_MAX.");
init_factors(T_MAX);
}
void init_factors(T T_MAX)
{
factors_.resize(get_index(max_) + 1, T_MAX);
// mu(1) = 1 -> factors_[0] = lpf - 1
factors_[0] = T_MAX - 1;
for (size_t i = 1; i < factors_.size(); i++)
{
if (factors_[i] == T_MAX)
{
int64_t prime = get_number(i);
int64_t multiple = prime * get_number(1);
int64_t j = 2;
if (prime < T_MAX)
factors_[i] = (T) prime;
for (; multiple <= max_; multiple = prime * get_number(j++))
{
int64_t index = get_index(multiple);
// prime is the smallest factor
if (factors_[index] == T_MAX)
factors_[index] = (T) prime;
// the least significant bit indicates whether multiple has
// an even (0) or odd (1) number of prime factors
else if (factors_[index] > 0)
factors_[index] ^= 1;
}
// Moebius function is 0 if n has a squared prime factor
multiple = prime * prime * get_number(0);
for (j = 1; multiple <= max_; multiple = prime * prime * get_number(j++))
factors_[get_index(multiple)] = 0;
}
}
}
/// @pre number > 0
static void to_index(int64_t* number)
{
assert(*number > 0);
*number = get_index(*number);
}
/// @pre number > 0
static int64_t get_index(int64_t number)
{
assert(number > 0);
int64_t quotient = number / 210;
int64_t remainder = number % 210;
return 48 * quotient + sft::to_index[remainder];
}
static int64_t get_number(int64_t index)
{
int64_t quotient = index / 48;
int64_t remainder = index % 48;
return 210 * quotient + sft::to_number[remainder];
}
/// Get the least prime factor (lpf) of the number get_number(index).
/// The result is different from lpf in some situations:
/// 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.
/// 2) lpf(index) returns lpf minus one if mu(index) == 1.
/// 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.
///
int64_t lpf(int64_t index) const
{
return factors_[index];
}
/// Get the Möbius function value of the number get_number(index).
/// For performance reasons mu(index) == 0 is not supported.
/// @pre mu(index) != 0 (i.e. lpf(index) != 0)
///
int64_t mu(int64_t index) const
{
assert(lpf(index) != 0);
return (factors_[index] & 1) ? -1 : 1;
}
private:
static const uint8_t numbers_[48];
static const int8_t indexes_[210];
std::vector<T> factors_;
int64_t max_;
};
} // namespace
#endif
<commit_msg>Update FactorTable.hpp<commit_after>///
/// @file FactorTable.hpp
/// @brief The FactorTable class is used to save memory. It combines
/// the lpf[n] (least prime factor) and mu[n] (Möbius function)
/// lookup tables into a single factor_table[n] which
/// furthermore only contains entries for numbers which are
/// not divisible by 2, 3, 5 and 7.
/// The factor table concept has first been devised and
/// implemented by Christian Bau in 2003.
///
/// FactorTable.lpf(index) is equal to (n = get_number(index)):
///
/// * 0 if moebius(n) = 0
/// * lpf if !is_prime(n) && moebius(n) = -1
/// * lpf-1 if !is_prime(n) && moebius(n) = 1
/// * n if is_prime(n) && n < T_MAX
/// * T_MAX if is_prime(n) && n > T_MAX
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP
#include <primecount.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <cassert>
#include <limits>
#include <stdint.h>
#include <vector>
namespace primecount {
namespace sft {
/// Convert a wheel index to a wheel number
extern const uint8_t to_number[48];
/// Convert a wheel number to a wheel index
extern const int8_t to_index[210];
}
template <typename T>
class FactorTable
{
public:
FactorTable(int64_t max) :
max_(std::max(max, (int64_t) 8))
{
T T_MAX = std::numeric_limits<T>::max();
if (isqrt(max_) >= T_MAX)
throw primecount_error("FactorTable: sqrt(max) must be < T_MAX.");
init_factors(T_MAX);
}
void init_factors(T T_MAX)
{
factors_.resize(get_index(max_) + 1, T_MAX);
// mu(1) = 1 -> factors_[0] = lpf - 1
factors_[0] = T_MAX - 1;
for (size_t i = 1; i < factors_.size(); i++)
{
if (factors_[i] == T_MAX)
{
int64_t prime = get_number(i);
int64_t multiple = prime * get_number(1);
int64_t j = 2;
if (prime < T_MAX)
factors_[i] = (T) prime;
for (; multiple <= max_; multiple = prime * get_number(j++))
{
int64_t index = get_index(multiple);
// prime is the smallest factor
if (factors_[index] == T_MAX)
factors_[index] = (T) prime;
// the least significant bit indicates whether multiple has
// an even (0) or odd (1) number of prime factors
else if (factors_[index] > 0)
factors_[index] ^= 1;
}
// Moebius function is 0 if n has a squared prime factor
multiple = prime * prime * get_number(0);
for (j = 1; multiple <= max_; multiple = prime * prime * get_number(j++))
factors_[get_index(multiple)] = 0;
}
}
}
/// @pre number > 0
static void to_index(int64_t* number)
{
assert(*number > 0);
*number = get_index(*number);
}
/// @pre number > 0
static int64_t get_index(int64_t number)
{
assert(number > 0);
int64_t quotient = number / 210;
int64_t remainder = number % 210;
return 48 * quotient + sft::to_index[remainder];
}
static int64_t get_number(int64_t index)
{
int64_t quotient = index / 48;
int64_t remainder = index % 48;
return 210 * quotient + sft::to_number[remainder];
}
/// Get the least prime factor (lpf) of the number get_number(index).
/// The result is different from lpf in some situations:
/// 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.
/// 2) lpf(index) returns lpf minus one if mu(index) == 1.
/// 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.
///
int64_t lpf(int64_t index) const
{
return factors_[index];
}
/// Get the Möbius function value of the number get_number(index).
/// For performance reasons mu(index) == 0 is not supported.
/// @pre mu(index) != 0 (i.e. lpf(index) != 0)
///
int64_t mu(int64_t index) const
{
assert(lpf(index) != 0);
return (factors_[index] & 1) ? -1 : 1;
}
private:
static const uint8_t numbers_[48];
static const int8_t indexes_[210];
std::vector<T> factors_;
int64_t max_;
};
} // namespace
#endif
<|endoftext|> |
<commit_before>#ifndef WATCHDOGD_H
#define WATCHDOGD_H
#define _XOPEN_SOURCE 700
#define _FILE_OFFSET_BITS 64
#define PREFER_PORTABLE_SNPRINTF
#define HAVE_SNPRINTF
#include <atomic>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <cinttypes>
#include <climits>
#include <clocale>
#include <config.h>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <grp.h>
#include <libconfig.h>
#include <libgen.h>
#include <oping.h>
#include <pthread.h>
#include <pwd.h>
#include <sched.h>
#include <syslog.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <zlib.h>
#include "snprintf.hpp"
#include "watchdog.hpp"
#include "linux.hpp"
#include "watchdog.hpp"
#ifndef NSIG
#if defined(_NSIG)
#define NSIG _NSIG /* For BSD/SysV */
#elif defined(_SIGMAX)
#define NSIG (_SIGMAX + 1) /* For QNX */
#elif defined(SIGMAX)
#define NSIG (SIGMAX + 1) /* For djgpp */
#else
#define NSIG 64 /* Use a reasonable default value */
#endif
#endif
#include "list.hpp"
#if defined __cplusplus
#define restrict
#endif
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
#define SOFTBOOT 0x1
#define SYNC 0x2
#define USEPIDFILE 0x4
#define ENABLEPING 0x8
#define KEXEC 0x10
#define DAEMONIZE 0x20
#define ENABLEPIDCHECKER 0x40
#define FORCE 0x80
#define NOACTION 0x100
#define REALTIME 0x200
#define VERBOSE 0x400
#define IDENTIFY 0x800
#define BUSYBOXDEVOPTCOMPAT 0x1000
#define LOGLVLSETCMDLN 0x2000
#define SCRIPTFAILED 0x1
#define FORKFAILED 0x2
#define OUTOFMEMORY 0x4
#define LOADAVGTOOHIGH 0x8
#define UNKNOWNPIDFILERROR 0x10
#define PIDFILERROR 0x20
#define PINGFAILED 0x40
#define NETWORKDOWN 0x80
//TODO: Split this struct into an options struct(values read in from config file) and a runtime struct.
struct cfgoptions {
cfgoptions() {
};
config_t cfg = {0};
double maxLoadFifteen = 0.0;
double maxLoadOne = 0.0;
double maxLoadFive = 0.0;
double retryLimit = 0.0;
const config_setting_t *ipAddresses = NULL;
const config_setting_t *networkInterfaces = NULL;
pingobj_t *pingObj = NULL;
const config_setting_t *pidFiles = NULL;
const char *devicepath = NULL;
const char *pidfileName = NULL;
const char *testexepath = "/etc/watchdog.d";
const char *exepathname = NULL;
const char *testexepathname = NULL;
const char *confile = "/etc/watchdogd.conf";
unsigned long options = 0;
const char *logTarget = NULL;
const char *logUpto = NULL;
time_t sleeptime = -1;
unsigned long minfreepages = 0;
const char *randomSeedPath = NULL;
int testBinTimeout = 60;
int repairBinTimeout = 60;
int sigtermDelay = 0;
int priority;
int watchdogTimeout = -1;
int testExeReturnValue = 0;
long loopExit = -1;
int allocatableMemory = 0;
volatile std::atomic_uint error = {0};
bool haveConfigFile = false;
};
struct ProcessList {
struct list head;
};
typedef struct ProcessList ProcessList;
struct spawnattr_t {
char *workingDirectory;
const char *repairFilePathname;
char *execStart;
char *user;
char *group;
int timeout;
int nice;
mode_t umask;
bool noNewPrivileges;
bool hasUmask;
};
struct repaircmd_t {
spawnattr_t spawnattr;
struct list entry;
const char *path;
char retString[8];
int ret;
std::atomic_bool mode;
bool legacy;
};
struct dbusinfo
{
cfgoptions **config;
Watchdog **wdt;
int fd;
};
struct identinfo {
char name[128];
char deviceName[128];
char daemonVersion[8];
long unsigned flags;
long timeout;
long firmwareVersion;
};
struct dev {
char name[64];
unsigned long minor;
unsigned long major;
};
extern ProcessList processes;
enum logTarget_t {
INVALID_LOG_TARGET,
STANDARD_ERROR,
SYSTEM_LOG,
FILE_APPEND,
FILE_NEW,
};
#endif
<commit_msg>initialize member<commit_after>#ifndef WATCHDOGD_H
#define WATCHDOGD_H
#ifdef __COVERITY__
#define __INCLUDE_LEVEL__ 22 //XXX: This is nessary for cov-build to work
#endif
#define _XOPEN_SOURCE 700
#define _FILE_OFFSET_BITS 64
#define PREFER_PORTABLE_SNPRINTF
#define HAVE_SNPRINTF
#include <atomic>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <cinttypes>
#include <climits>
#include <clocale>
#include <config.h>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <grp.h>
#include <libconfig.h>
#include <libgen.h>
#include <oping.h>
#include <pthread.h>
#include <pwd.h>
#include <sched.h>
#include <syslog.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <zlib.h>
#include "snprintf.hpp"
#include "watchdog.hpp"
#include "linux.hpp"
#include "watchdog.hpp"
#ifndef NSIG
#if defined(_NSIG)
#define NSIG _NSIG /* For BSD/SysV */
#elif defined(_SIGMAX)
#define NSIG (_SIGMAX + 1) /* For QNX */
#elif defined(SIGMAX)
#define NSIG (SIGMAX + 1) /* For djgpp */
#else
#define NSIG 64 /* Use a reasonable default value */
#endif
#endif
#include "list.hpp"
#if defined __cplusplus
#define restrict
#endif
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
#define SOFTBOOT 0x1
#define SYNC 0x2
#define USEPIDFILE 0x4
#define ENABLEPING 0x8
#define KEXEC 0x10
#define DAEMONIZE 0x20
#define ENABLEPIDCHECKER 0x40
#define FORCE 0x80
#define NOACTION 0x100
#define REALTIME 0x200
#define VERBOSE 0x400
#define IDENTIFY 0x800
#define BUSYBOXDEVOPTCOMPAT 0x1000
#define LOGLVLSETCMDLN 0x2000
#define SCRIPTFAILED 0x1
#define FORKFAILED 0x2
#define OUTOFMEMORY 0x4
#define LOADAVGTOOHIGH 0x8
#define UNKNOWNPIDFILERROR 0x10
#define PIDFILERROR 0x20
#define PINGFAILED 0x40
#define NETWORKDOWN 0x80
//TODO: Split this struct into an options struct(values read in from config file) and a runtime struct.
struct cfgoptions {
cfgoptions() {
};
config_t cfg = {0};
double maxLoadFifteen = 0.0;
double maxLoadOne = 0.0;
double maxLoadFive = 0.0;
double retryLimit = 0.0;
const config_setting_t *ipAddresses = NULL;
const config_setting_t *networkInterfaces = NULL;
pingobj_t *pingObj = NULL;
const config_setting_t *pidFiles = NULL;
const char *devicepath = NULL;
const char *pidfileName = NULL;
const char *testexepath = "/etc/watchdog.d";
const char *exepathname = NULL;
const char *testexepathname = NULL;
const char *confile = "/etc/watchdogd.conf";
unsigned long options = 0;
const char *logTarget = NULL;
const char *logUpto = NULL;
time_t sleeptime = -1;
unsigned long minfreepages = 0;
const char *randomSeedPath = NULL;
int testBinTimeout = 60;
int repairBinTimeout = 60;
int sigtermDelay = 0;
int priority = 0;
int watchdogTimeout = -1;
int testExeReturnValue = 0;
long loopExit = -1;
int allocatableMemory = 0;
volatile std::atomic_uint error = {0};
bool haveConfigFile = false;
};
struct ProcessList {
struct list head;
};
typedef struct ProcessList ProcessList;
struct spawnattr_t {
char *workingDirectory;
const char *repairFilePathname;
char *execStart;
char *user;
char *group;
int timeout;
int nice;
mode_t umask;
bool noNewPrivileges;
bool hasUmask;
};
struct repaircmd_t {
spawnattr_t spawnattr;
struct list entry;
const char *path;
char retString[8];
int ret;
std::atomic_bool mode;
bool legacy;
};
struct dbusinfo
{
cfgoptions **config;
Watchdog **wdt;
int fd;
};
struct identinfo {
char name[128];
char deviceName[128];
char daemonVersion[8];
long unsigned flags;
long timeout;
long firmwareVersion;
};
struct dev {
char name[64];
unsigned long minor;
unsigned long major;
};
extern ProcessList processes;
enum logTarget_t {
INVALID_LOG_TARGET,
STANDARD_ERROR,
SYSTEM_LOG,
FILE_APPEND,
FILE_NEW,
};
#endif
<|endoftext|> |
<commit_before>/* Calf DSP Library
* Example audio modules - wavetable synthesizer
*
* Copyright (C) 2009 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <config.h>
#if ENABLE_EXPERIMENTAL
#include <assert.h>
#include <memory.h>
#include <complex>
#if USE_JACK
#include <jack/jack.h>
#endif
#include <calf/giface.h>
#include <calf/modules_synths.h>
#include <iostream>
using namespace dsp;
using namespace calf_plugins;
wavetable_voice::wavetable_voice()
{
sample_rate = -1;
}
void wavetable_voice::set_params_ptr(wavetable_audio_module *_parent, int _srate)
{
parent = _parent;
params = parent->params;
sample_rate = _srate;
}
void wavetable_voice::reset()
{
note = -1;
}
void wavetable_voice::note_on(int note, int vel)
{
this->note = note;
velocity = vel / 127.0;
amp.set(1.0);
for (int i = 0; i < OscCount; i++) {
oscs[i].tables = parent->tables;
oscs[i].reset();
oscs[i].set_freq(note_to_hz(note, 0), sample_rate);
}
int cr = sample_rate / BlockSize;
for (int i = 0; i < EnvCount; i++) {
envs[i].set(0.01, 0.1, 0.5, 1, cr);
envs[i].note_on();
}
}
void wavetable_voice::note_off(int vel)
{
for (int i = 0; i < EnvCount; i++)
envs[i].note_off();
}
void wavetable_voice::steal()
{
}
void wavetable_voice::render_block()
{
int spc = wavetable_metadata::par_o2level - wavetable_metadata::par_o1level;
for (int j = 0; j < OscCount; j++)
oscs[j].set_freq(note_to_hz(note, *params[wavetable_metadata::par_o1transpose + j * spc] * 100+ *params[wavetable_metadata::par_o1detune + j * spc]), sample_rate);
float prev_value = envs[0].value;
for (int i = 0; i < EnvCount; i++)
envs[i].advance();
float cur_value = envs[0].value;
for (int i = 0; i < BlockSize; i++) {
float value = 0.f;
float env = velocity * (prev_value + (cur_value - prev_value) * i * (1.0 / BlockSize));
for (int j = 0; j < OscCount; j++)
value += oscs[j].get(dsp::clip(fastf2i_drm((env + *params[wavetable_metadata::par_o1offset + j * spc]) * 127.0), 0, 127)) * *params[wavetable_metadata::par_o1level + j * spc];
output_buffer[i][0] = output_buffer[i][1] = value * env * env;
}
if (envs[0].stopped())
released = true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
wavetable_audio_module::wavetable_audio_module()
{
panic_flag = false;
for (int i = 0; i < 128; i++)
{
for (int j = 0; j < 256; j++)
{
//tables[i][j] = i < j ? -32767 : 32767;
float ph = j * 2 * M_PI / 256;
float ii = i / 128.0;
float peak = (32 * ii);
float rezo = lerp(sin(floor(peak) * ph), sin(floor(peak+1) * ph), peak - floor(peak));
tables[i][j] = 32767 * sin (ph + 2 * ii * sin(2 * ph) + 2 * ii * ii * sin(4 * ph) + ii * ii * rezo);
}
}
}
#endif
<commit_msg>+ Wavetable: smoother wavetable<commit_after>/* Calf DSP Library
* Example audio modules - wavetable synthesizer
*
* Copyright (C) 2009 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <config.h>
#if ENABLE_EXPERIMENTAL
#include <assert.h>
#include <memory.h>
#include <complex>
#if USE_JACK
#include <jack/jack.h>
#endif
#include <calf/giface.h>
#include <calf/modules_synths.h>
#include <iostream>
using namespace dsp;
using namespace calf_plugins;
wavetable_voice::wavetable_voice()
{
sample_rate = -1;
}
void wavetable_voice::set_params_ptr(wavetable_audio_module *_parent, int _srate)
{
parent = _parent;
params = parent->params;
sample_rate = _srate;
}
void wavetable_voice::reset()
{
note = -1;
}
void wavetable_voice::note_on(int note, int vel)
{
this->note = note;
velocity = vel / 127.0;
amp.set(1.0);
for (int i = 0; i < OscCount; i++) {
oscs[i].tables = parent->tables;
oscs[i].reset();
oscs[i].set_freq(note_to_hz(note, 0), sample_rate);
}
int cr = sample_rate / BlockSize;
for (int i = 0; i < EnvCount; i++) {
envs[i].set(0.01, 0.1, 0.5, 1, cr);
envs[i].note_on();
}
}
void wavetable_voice::note_off(int vel)
{
for (int i = 0; i < EnvCount; i++)
envs[i].note_off();
}
void wavetable_voice::steal()
{
}
void wavetable_voice::render_block()
{
int spc = wavetable_metadata::par_o2level - wavetable_metadata::par_o1level;
for (int j = 0; j < OscCount; j++)
oscs[j].set_freq(note_to_hz(note, *params[wavetable_metadata::par_o1transpose + j * spc] * 100+ *params[wavetable_metadata::par_o1detune + j * spc]), sample_rate);
float prev_value = envs[0].value;
for (int i = 0; i < EnvCount; i++)
envs[i].advance();
float cur_value = envs[0].value;
for (int i = 0; i < BlockSize; i++) {
float value = 0.f;
float env = velocity * (prev_value + (cur_value - prev_value) * i * (1.0 / BlockSize));
for (int j = 0; j < OscCount; j++)
value += oscs[j].get(dsp::clip(fastf2i_drm((env + *params[wavetable_metadata::par_o1offset + j * spc]) * 127.0), 0, 127)) * *params[wavetable_metadata::par_o1level + j * spc];
output_buffer[i][0] = output_buffer[i][1] = value * env * env;
}
if (envs[0].stopped())
released = true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
wavetable_audio_module::wavetable_audio_module()
{
panic_flag = false;
for (int i = 0; i < 128; i++)
{
for (int j = 0; j < 256; j++)
{
//tables[i][j] = i < j ? -32767 : 32767;
float ph = j * 2 * M_PI / 256;
float ii = i / 128.0;
float peak = (32 * ii);
float rezo1 = sin(floor(peak) * ph);
float rezo2 = sin(floor(peak + 1) * ph);
float v1 = sin (ph + 2 * ii * sin(2 * ph) + 2 * ii * ii * sin(4 * ph) + ii * ii * rezo1);
float v2 = sin (ph + 2 * ii * sin(2 * ph) + 2 * ii * ii * sin(4 * ph) + ii * ii * rezo2);
tables[i][j] = 32767 * lerp(v1, v2, peak - floor(peak));
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "priv/websocket.h"
#include "httpserverrequest.h"
#include "headers.h"
#include <QtCore/QCryptographicHash>
#include <QtCore/QtEndian>
#include <QtCore/QDataStream>
#include <QtNetwork/QHostAddress>
// Writes a string without the '\0' char using function \p func
#define WRITE_STRING(func, chunk) (func)(chunk, sizeof(chunk) - 1)
static const char crlf[] = "\r\n";
#define CRLF crlf, sizeof(crlf) - 1
namespace Tufao {
WebSocket::WebSocket(DeliveryType deliveryType, QObject *parent) :
AbstractMessageNode(parent),
priv(new Priv::WebSocket(deliveryType))
{
}
WebSocket::~WebSocket()
{
delete priv;
}
bool WebSocket::startClientHandshake(QAbstractSocket *socket,
const QByteArray &host,
const QByteArray &resource,
const Headers &headers)
{
if (!socket->isOpen())
return false;
priv->socket = socket;
priv->sentMessagesAreMasked = true;
priv->state = Priv::CONNECTING;
connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
WRITE_STRING(socket->write, "GET ");
socket->write(resource);
WRITE_STRING(socket->write, " HTTP/1.1\r\n");
for (Headers::const_iterator i = headers.begin();i != headers.end();++i) {
socket->write(i.key());
socket->write(": ", 2);
socket->write(i.value());
socket->write(CRLF);
}
WRITE_STRING(socket->write, "Host: ");
socket->write(host);
WRITE_STRING(socket->write, "\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: ");
{
static const int SUBSTR_SIZE = int(sizeof(int));
union
{
int i;
char str[sizeof(int)];
} chunk;
QByteArray headerValue;
headerValue.reserve(16);
for (int i = 0;i < 16;i += SUBSTR_SIZE) {
chunk.i = qrand();
headerValue.append(chunk.str, qMin(SUBSTR_SIZE, 16 - i));
}
socket->write(headerValue.toBase64());
}
WRITE_STRING(socket->write, "\r\n\r\n");
return true;
}
bool WebSocket::startClientHandshake(QAbstractSocket *socket,
const QByteArray &resource,
const Headers &headers)
{
return startClientHandshake(socket, (socket->peerAddress().toString() + ':'
+ socket->peerPort()).toUtf8(),
resource, headers);
}
bool WebSocket::startServerHandshake(const HttpServerRequest *request,
const QByteArray &head,
const Headers &extraHeaders)
{
QAbstractSocket *socket = request->socket();
Headers headers = request->headers();
if (!headers.contains("Upgrade", "websocket")) {
WRITE_STRING(socket->write,
"HTTP/1.1 400 Bad Request\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n"
"\r\n");
return false;
}
if (!headers.contains("Sec-WebSocket-Version", "13")) {
WRITE_STRING(socket->write,
"HTTP/1.1 426 Upgrade Required\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n");
return false;
}
QByteArray key = headers.value("Sec-WebSocket-Key");
if (key.size() != 24)
return false;
priv->socket = socket;
priv->sentMessagesAreMasked = false;
priv->state = Priv::OPEN;
WRITE_STRING(socket->write,
"HTTP/1.1 101 Switching Protocols\r\n"
"Connection: Upgrade\r\n"
"Upgrade: websocket\r\n");
for (Headers::const_iterator i = extraHeaders.begin()
;i != extraHeaders.end();++i) {
socket->write(i.key());
WRITE_STRING(socket->write, ": ");
socket->write(i.value());
socket->write(CRLF);
}
WRITE_STRING(socket->write, "Sec-WebSocket-Accept: ");
WRITE_STRING(key.append, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
socket->write(QCryptographicHash::hash(key, QCryptographicHash::Sha1)
.toBase64());
WRITE_STRING(socket->write, "\r\n\r\n");
connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
if (head.size())
readData(head);
return true;
}
bool WebSocket::sendMessage(const QByteArray &msg)
{
if (priv->state != Priv::OPEN)
return false;
Priv::Frame frame = standardFrame();
frame.setFinTrue();
frame.setOpcode(Priv::FrameType::BINARY);
writePayload(frame, msg);
return true;
}
bool WebSocket::sendMessage(const QString &utf8Msg)
{
if (priv->state != Priv::OPEN)
return false;
Priv::Frame frame = standardFrame();
frame.setFinTrue();
frame.setOpcode(Priv::FrameType::TEXT);
writePayload(frame, utf8Msg.toUtf8());
return true;
}
void WebSocket::onReadyRead()
{
readData(priv->socket->readAll());
}
void WebSocket::close()
{
close(Priv::StatusCode::NORMAL);
}
inline Priv::Frame WebSocket::standardFrame() const
{
Priv::Frame frame;
frame.bytes[0] = 0;
frame.bytes[1] = 0;
if (priv->sentMessagesAreMasked)
frame.setMaskedTrue();
else
frame.setMaskedFalse();
return frame;
}
inline Priv::Frame WebSocket::controlFrame() const
{
Priv::Frame frame = standardFrame();
frame.setFinTrue();
return frame;
}
inline void WebSocket::writePayload(Priv::Frame frame, const QByteArray &data)
{
int size = data.size();
if (size < 126)
frame.setPayloadLength(size);
else if (size <= 65535)
frame.setPayloadLength(126);
else
frame.setPayloadLength(127);
priv->socket->write(frame.bytes, 2);
if (size >= 126 && size <= 65535) {
uchar chunk[2];
qToBigEndian(quint16(size), chunk);
priv->socket->write(reinterpret_cast<char*>(chunk), sizeof(chunk));
} else if (size > 65535) {
uchar chunk[8];
qToBigEndian(quint64(size), chunk);
priv->socket->write(reinterpret_cast<char*>(chunk), sizeof(chunk));
}
if (priv->sentMessagesAreMasked) {
union
{
quint32 key;
uchar pieces[4];
} mask;
mask.key = qrand();
qToBigEndian(mask.key, mask.pieces);
for (int i = 0;i != size;++i) {
uchar byte = mask.pieces[i % 4] ^ data[i];
priv->socket->write(reinterpret_cast<char*>(&byte), 1);
}
} else {
priv->socket->write(data);
}
}
inline void WebSocket::close(quint16 code)
{
QByteArray data;
QDataStream stream(priv->socket);
stream.setByteOrder(QDataStream::BigEndian);
stream << code;
Priv::Frame frame = controlFrame();
frame.setOpcode(Priv::FrameType::CONNECTION_CLOSE);
writePayload(frame, data);
}
inline void WebSocket::readData(const QByteArray &data)
{
priv->buffer += data;
switch (priv->state) {
case Priv::CONNECTING:
// TODO: this is used soon after startClientHandshake
break;
case Priv::OPEN:
parseBuffer();
break;
case Priv::CLOSING:
// TODO
break;
case Priv::CLOSED:
default:
qWarning("WebSocket: data received while in closed state");
}
}
inline void WebSocket::parseBuffer()
{
while (true) {
switch (priv->parsingState) {
case Priv::PARSING_FRAME:
if (!parseFrame()) return;
break;
case Priv::PARSING_SIZE_16BIT:
if (!parseSize16()) return;
break;
case Priv::PARSING_SIZE_64BIT:
if (!parseSize64()) return;
break;
case Priv::PARSING_MASKING_KEY:
if (!parseMaskingKey()) return;
break;
case Priv::PARSING_PAYLOAD_DATA:
if (!parsePayloadData()) return;
}
}
}
inline bool WebSocket::parseFrame()
{
if (priv->buffer.size() < int(sizeof(Priv::Frame)))
return false;
for (uint i = 0;i != 2;++i)
priv->frame.bytes[i] = priv->buffer[i];
priv->buffer.remove(0, 2);
if (priv->frame.payloadLength() == 126) {
priv->parsingState = Priv::PARSING_SIZE_16BIT;
} else if (priv->frame.payloadLength() == 127) {
priv->parsingState = Priv::PARSING_SIZE_64BIT;
} else {
priv->remainingPayloadSize = priv->frame.payloadLength();
if (!priv->sentMessagesAreMasked)
priv->parsingState = Priv::PARSING_MASKING_KEY;
else
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
}
return true;
}
inline bool WebSocket::parseSize16()
{
if (priv->buffer.size() < int(sizeof(quint16)))
return false;
uchar size[2];
for (uint i = 0;i != uint(sizeof(quint16));++i)
size[i] = priv->buffer[i];
priv->buffer.remove(0, sizeof(quint16));
priv->remainingPayloadSize = qFromBigEndian<quint16>(size);
if (!priv->sentMessagesAreMasked)
priv->parsingState = Priv::PARSING_MASKING_KEY;
else
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
return true;
}
inline bool WebSocket::parseSize64()
{
if (priv->buffer.size() < int(sizeof(quint64)))
return false;
uchar size[8];
for (uint i = 0;i != uint(sizeof(quint64));++i)
size[i] = priv->buffer[i];
priv->buffer.remove(0, sizeof(quint64));
priv->remainingPayloadSize = qFromBigEndian<quint64>(size);
if (!priv->sentMessagesAreMasked)
priv->parsingState = Priv::PARSING_MASKING_KEY;
else
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
return true;
}
inline bool WebSocket::parseMaskingKey()
{
if (priv->buffer.size() < int(sizeof(quint32)))
return false;
priv->maskingIndex = 0;
for (int i = 0;i != 4;++i)
*(reinterpret_cast<char *>(priv->maskingKey + i)) = priv->buffer[i];
priv->buffer.remove(0, sizeof(quint32));
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
return true;
}
inline bool WebSocket::parsePayloadData()
{
if (!priv->buffer.size())
return false;
QByteArray chunk = priv->buffer.left(priv->remainingPayloadSize);
priv->buffer.remove(0, chunk.size());
priv->remainingPayloadSize -= chunk.size();
if (priv->deliveryType == DELIVER_PARTIAL_FRAMES) {
decodeFragment(chunk);
emit newMessage(chunk);
} else
priv->fragment += chunk;
if (priv->remainingPayloadSize)
return false;
if (priv->frame.fin()
&& priv->deliveryType == DELIVER_FULL_FRAMES) {
decodeFragment(priv->fragment);
emit newMessage(priv->fragment);
priv->fragment.clear();
}
priv->parsingState = Priv::PARSING_FRAME;
return true;
}
inline void WebSocket::decodeFragment(QByteArray &fragment)
{
if (priv->sentMessagesAreMasked)
return;
for (int i = 0;i != fragment.size();++i) {
fragment[i] = fragment[i] ^ priv->maskingKey[priv->maskingIndex % 4];
priv->maskingIndex += 1;
}
}
} // namespace Tufao
<commit_msg>fixed WebSocket::close and removed QDataStream dependency<commit_after>#include "priv/websocket.h"
#include "httpserverrequest.h"
#include "headers.h"
#include <QtCore/QCryptographicHash>
#include <QtCore/QtEndian>
#include <QtNetwork/QHostAddress>
// Writes a string without the '\0' char using function \p func
#define WRITE_STRING(func, chunk) (func)(chunk, sizeof(chunk) - 1)
static const char crlf[] = "\r\n";
#define CRLF crlf, sizeof(crlf) - 1
namespace Tufao {
WebSocket::WebSocket(DeliveryType deliveryType, QObject *parent) :
AbstractMessageNode(parent),
priv(new Priv::WebSocket(deliveryType))
{
}
WebSocket::~WebSocket()
{
delete priv;
}
bool WebSocket::startClientHandshake(QAbstractSocket *socket,
const QByteArray &host,
const QByteArray &resource,
const Headers &headers)
{
if (!socket->isOpen())
return false;
priv->socket = socket;
priv->sentMessagesAreMasked = true;
priv->state = Priv::CONNECTING;
connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
WRITE_STRING(socket->write, "GET ");
socket->write(resource);
WRITE_STRING(socket->write, " HTTP/1.1\r\n");
for (Headers::const_iterator i = headers.begin();i != headers.end();++i) {
socket->write(i.key());
socket->write(": ", 2);
socket->write(i.value());
socket->write(CRLF);
}
WRITE_STRING(socket->write, "Host: ");
socket->write(host);
WRITE_STRING(socket->write, "\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: ");
{
static const int SUBSTR_SIZE = int(sizeof(int));
union
{
int i;
char str[sizeof(int)];
} chunk;
QByteArray headerValue;
headerValue.reserve(16);
for (int i = 0;i < 16;i += SUBSTR_SIZE) {
chunk.i = qrand();
headerValue.append(chunk.str, qMin(SUBSTR_SIZE, 16 - i));
}
socket->write(headerValue.toBase64());
}
WRITE_STRING(socket->write, "\r\n\r\n");
return true;
}
bool WebSocket::startClientHandshake(QAbstractSocket *socket,
const QByteArray &resource,
const Headers &headers)
{
return startClientHandshake(socket, (socket->peerAddress().toString() + ':'
+ socket->peerPort()).toUtf8(),
resource, headers);
}
bool WebSocket::startServerHandshake(const HttpServerRequest *request,
const QByteArray &head,
const Headers &extraHeaders)
{
QAbstractSocket *socket = request->socket();
Headers headers = request->headers();
if (!headers.contains("Upgrade", "websocket")) {
WRITE_STRING(socket->write,
"HTTP/1.1 400 Bad Request\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n"
"\r\n");
return false;
}
if (!headers.contains("Sec-WebSocket-Version", "13")) {
WRITE_STRING(socket->write,
"HTTP/1.1 426 Upgrade Required\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n");
return false;
}
QByteArray key = headers.value("Sec-WebSocket-Key");
if (key.size() != 24)
return false;
priv->socket = socket;
priv->sentMessagesAreMasked = false;
priv->state = Priv::OPEN;
WRITE_STRING(socket->write,
"HTTP/1.1 101 Switching Protocols\r\n"
"Connection: Upgrade\r\n"
"Upgrade: websocket\r\n");
for (Headers::const_iterator i = extraHeaders.begin()
;i != extraHeaders.end();++i) {
socket->write(i.key());
WRITE_STRING(socket->write, ": ");
socket->write(i.value());
socket->write(CRLF);
}
WRITE_STRING(socket->write, "Sec-WebSocket-Accept: ");
WRITE_STRING(key.append, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
socket->write(QCryptographicHash::hash(key, QCryptographicHash::Sha1)
.toBase64());
WRITE_STRING(socket->write, "\r\n\r\n");
connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
if (head.size())
readData(head);
return true;
}
bool WebSocket::sendMessage(const QByteArray &msg)
{
if (priv->state != Priv::OPEN)
return false;
Priv::Frame frame = standardFrame();
frame.setFinTrue();
frame.setOpcode(Priv::FrameType::BINARY);
writePayload(frame, msg);
return true;
}
bool WebSocket::sendMessage(const QString &utf8Msg)
{
if (priv->state != Priv::OPEN)
return false;
Priv::Frame frame = standardFrame();
frame.setFinTrue();
frame.setOpcode(Priv::FrameType::TEXT);
writePayload(frame, utf8Msg.toUtf8());
return true;
}
void WebSocket::onReadyRead()
{
readData(priv->socket->readAll());
}
void WebSocket::close()
{
close(Priv::StatusCode::NORMAL);
}
inline Priv::Frame WebSocket::standardFrame() const
{
Priv::Frame frame;
frame.bytes[0] = 0;
frame.bytes[1] = 0;
if (priv->sentMessagesAreMasked)
frame.setMaskedTrue();
else
frame.setMaskedFalse();
return frame;
}
inline Priv::Frame WebSocket::controlFrame() const
{
Priv::Frame frame = standardFrame();
frame.setFinTrue();
return frame;
}
inline void WebSocket::writePayload(Priv::Frame frame, const QByteArray &data)
{
int size = data.size();
if (size < 126)
frame.setPayloadLength(size);
else if (size <= 65535)
frame.setPayloadLength(126);
else
frame.setPayloadLength(127);
priv->socket->write(frame.bytes, 2);
if (size >= 126 && size <= 65535) {
uchar chunk[2];
qToBigEndian(quint16(size), chunk);
priv->socket->write(reinterpret_cast<char*>(chunk), sizeof(chunk));
} else if (size > 65535) {
uchar chunk[8];
qToBigEndian(quint64(size), chunk);
priv->socket->write(reinterpret_cast<char*>(chunk), sizeof(chunk));
}
if (priv->sentMessagesAreMasked) {
union
{
quint32 key;
uchar pieces[4];
} mask;
mask.key = qrand();
qToBigEndian(mask.key, mask.pieces);
for (int i = 0;i != size;++i) {
uchar byte = mask.pieces[i % 4] ^ data[i];
priv->socket->write(reinterpret_cast<char*>(&byte), 1);
}
} else {
priv->socket->write(data);
}
}
inline void WebSocket::close(quint16 code)
{
uchar chunk[2];
qToBigEndian(code, chunk);
QByteArray data(reinterpret_cast<char*>(chunk), 2);
Priv::Frame frame = controlFrame();
frame.setOpcode(Priv::FrameType::CONNECTION_CLOSE);
writePayload(frame, data);
}
inline void WebSocket::readData(const QByteArray &data)
{
priv->buffer += data;
switch (priv->state) {
case Priv::CONNECTING:
// TODO: this is used soon after startClientHandshake
break;
case Priv::OPEN:
parseBuffer();
break;
case Priv::CLOSING:
// TODO
break;
case Priv::CLOSED:
default:
qWarning("WebSocket: data received while in closed state");
}
}
inline void WebSocket::parseBuffer()
{
while (true) {
switch (priv->parsingState) {
case Priv::PARSING_FRAME:
if (!parseFrame()) return;
break;
case Priv::PARSING_SIZE_16BIT:
if (!parseSize16()) return;
break;
case Priv::PARSING_SIZE_64BIT:
if (!parseSize64()) return;
break;
case Priv::PARSING_MASKING_KEY:
if (!parseMaskingKey()) return;
break;
case Priv::PARSING_PAYLOAD_DATA:
if (!parsePayloadData()) return;
}
}
}
inline bool WebSocket::parseFrame()
{
if (priv->buffer.size() < int(sizeof(Priv::Frame)))
return false;
for (uint i = 0;i != 2;++i)
priv->frame.bytes[i] = priv->buffer[i];
priv->buffer.remove(0, 2);
if (priv->frame.payloadLength() == 126) {
priv->parsingState = Priv::PARSING_SIZE_16BIT;
} else if (priv->frame.payloadLength() == 127) {
priv->parsingState = Priv::PARSING_SIZE_64BIT;
} else {
priv->remainingPayloadSize = priv->frame.payloadLength();
if (!priv->sentMessagesAreMasked)
priv->parsingState = Priv::PARSING_MASKING_KEY;
else
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
}
return true;
}
inline bool WebSocket::parseSize16()
{
if (priv->buffer.size() < int(sizeof(quint16)))
return false;
uchar size[2];
for (uint i = 0;i != uint(sizeof(quint16));++i)
size[i] = priv->buffer[i];
priv->buffer.remove(0, sizeof(quint16));
priv->remainingPayloadSize = qFromBigEndian<quint16>(size);
if (!priv->sentMessagesAreMasked)
priv->parsingState = Priv::PARSING_MASKING_KEY;
else
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
return true;
}
inline bool WebSocket::parseSize64()
{
if (priv->buffer.size() < int(sizeof(quint64)))
return false;
uchar size[8];
for (uint i = 0;i != uint(sizeof(quint64));++i)
size[i] = priv->buffer[i];
priv->buffer.remove(0, sizeof(quint64));
priv->remainingPayloadSize = qFromBigEndian<quint64>(size);
if (!priv->sentMessagesAreMasked)
priv->parsingState = Priv::PARSING_MASKING_KEY;
else
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
return true;
}
inline bool WebSocket::parseMaskingKey()
{
if (priv->buffer.size() < int(sizeof(quint32)))
return false;
priv->maskingIndex = 0;
for (int i = 0;i != 4;++i)
*(reinterpret_cast<char *>(priv->maskingKey + i)) = priv->buffer[i];
priv->buffer.remove(0, sizeof(quint32));
priv->parsingState = Priv::PARSING_PAYLOAD_DATA;
return true;
}
inline bool WebSocket::parsePayloadData()
{
if (!priv->buffer.size())
return false;
QByteArray chunk = priv->buffer.left(priv->remainingPayloadSize);
priv->buffer.remove(0, chunk.size());
priv->remainingPayloadSize -= chunk.size();
if (priv->deliveryType == DELIVER_PARTIAL_FRAMES) {
decodeFragment(chunk);
emit newMessage(chunk);
} else
priv->fragment += chunk;
if (priv->remainingPayloadSize)
return false;
if (priv->frame.fin()
&& priv->deliveryType == DELIVER_FULL_FRAMES) {
decodeFragment(priv->fragment);
emit newMessage(priv->fragment);
priv->fragment.clear();
}
priv->parsingState = Priv::PARSING_FRAME;
return true;
}
inline void WebSocket::decodeFragment(QByteArray &fragment)
{
if (priv->sentMessagesAreMasked)
return;
for (int i = 0;i != fragment.size();++i) {
fragment[i] = fragment[i] ^ priv->maskingKey[priv->maskingIndex % 4];
priv->maskingIndex += 1;
}
}
} // namespace Tufao
<|endoftext|> |
<commit_before>#include <pcap_cpp/device.hpp>
#include <pcap_cpp/pcap.hpp>
#include <thread>
namespace libpcap {
device::device(const std::string device_name)
: device_name_{ device_name }, device_{ create(device_name) } {
libpcap::set_promiscuous_mode(device_, false);
libpcap::set_timeout(device_, std::chrono::seconds{10});
libpcap::set_buffer_size(device_, BUFSIZ);
}
device::device(pcap_if_t *pcap_device) : device{ pcap_device->name } {}
device::~device() {
break_loop();
pcap_close(device_);
}
void device::set_promiscuous_mode(const bool flag) {
libpcap::set_promiscuous_mode(device_, flag);
}
void device::set_monitor_mode(const bool flag) {
libpcap::set_monitor_mode(device_, flag);
}
bool device::can_set_monitor_mode() {
return libpcap::can_set_monitor_mode(device_);
}
void device::set_snapshot_length(const int snapshot_length) {
libpcap::set_snapshot_length(device_, snapshot_length);
}
void device::set_timeout(const std::chrono::milliseconds time) {
libpcap::set_timeout(device_, time);
}
void device::set_buffer_size(const int bytes) {
libpcap::set_buffer_size(device_, bytes);
}
void device::set_time_stamp(const time_stamp &tstamp) {
libpcap::set_time_stamp(device_, tstamp);
}
void device::set_capture_direction(const capture_direction &direction) {
libpcap::set_capture_direction(device_, direction);
}
void device::set_filter(filter_program filter) {
filter_ = filter;
libpcap::set_filter(device_, filter_.get());
}
void device::loop(pcap_handler handler, const int count, unsigned char *user_arguments) {
auto loop_thread = std::thread{[=]() -> void {
libpcap::loop(device_, handler, count, user_arguments);
}};
loop_thread.detach();
}
void device::break_loop() {
pcap_breakloop(device_);
}
std::vector<device::device> device::find_all_devices() {
const auto all_devices = libpcap::find_all_devices();
auto devices = std::vector<device>{};
for (const auto &device : all_devices) {
devices.emplace_back(device);
}
return devices;
}
}
<commit_msg>call activate before loop<commit_after>#include <pcap_cpp/device.hpp>
#include <pcap_cpp/pcap.hpp>
#include <thread>
namespace libpcap {
device::device(const std::string device_name)
: device_name_{ device_name }, device_{ create(device_name) } {
libpcap::set_promiscuous_mode(device_, false);
libpcap::set_timeout(device_, std::chrono::seconds{10});
libpcap::set_buffer_size(device_, BUFSIZ);
}
device::device(pcap_if_t *pcap_device) : device{ pcap_device->name } {}
device::~device() {
break_loop();
pcap_close(device_);
}
void device::set_promiscuous_mode(const bool flag) {
libpcap::set_promiscuous_mode(device_, flag);
}
void device::set_monitor_mode(const bool flag) {
libpcap::set_monitor_mode(device_, flag);
}
bool device::can_set_monitor_mode() {
return libpcap::can_set_monitor_mode(device_);
}
void device::set_snapshot_length(const int snapshot_length) {
libpcap::set_snapshot_length(device_, snapshot_length);
}
void device::set_timeout(const std::chrono::milliseconds time) {
libpcap::set_timeout(device_, time);
}
void device::set_buffer_size(const int bytes) {
libpcap::set_buffer_size(device_, bytes);
}
void device::set_time_stamp(const time_stamp &tstamp) {
libpcap::set_time_stamp(device_, tstamp);
}
void device::set_capture_direction(const capture_direction &direction) {
libpcap::set_capture_direction(device_, direction);
}
void device::set_filter(filter_program filter) {
filter_ = filter;
libpcap::set_filter(device_, filter_.get());
}
void device::loop(pcap_handler handler, const int count, unsigned char *user_arguments) {
libpcap::activate(device_);
auto loop_thread = std::thread{[=]() -> void {
libpcap::loop(device_, handler, count, user_arguments);
}};
loop_thread.detach();
}
void device::break_loop() {
pcap_breakloop(device_);
}
std::vector<device::device> device::find_all_devices() {
const auto all_devices = libpcap::find_all_devices();
auto devices = std::vector<device>{};
for (const auto &device : all_devices) {
devices.emplace_back(device);
}
return devices;
}
}
<|endoftext|> |
<commit_before>#include <possumwood_sdk/node_implementation.h>
#include "possumwood_sdk/datatypes/enum.h"
#include "datatypes/meshes.h"
#include <CGAL/Polygon_mesh_processing/stitch_borders.h>
namespace {
using possumwood::Meshes;
using possumwood::CGALPolyhedron;
typedef possumwood::CGALPolyhedron Mesh;
dependency_graph::InAttr<Meshes> a_inMesh;
dependency_graph::OutAttr<Meshes> a_outMesh;
dependency_graph::State compute(dependency_graph::Values& data) {
const Meshes inMeshes = data.get(a_inMesh);
Meshes result;
for(auto& inMesh : inMeshes) {
std::unique_ptr<Mesh> mesh(new Mesh(inMesh.polyhedron()));
CGAL::Polygon_mesh_processing::stitch_borders(*mesh);
result.addMesh(inMesh.name(), std::move(mesh));
}
data.set(a_outMesh, result);
return dependency_graph::State();
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_inMesh, "input");
meta.addAttribute(a_outMesh, "output");
meta.addInfluence(a_inMesh, a_outMesh);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("cgal/topology/stitch_borders", init);
}
<commit_msg>Stitch Borders node now works in-place, because the properties exist in place<commit_after>#include <possumwood_sdk/node_implementation.h>
#include "possumwood_sdk/datatypes/enum.h"
#include "datatypes/meshes.h"
#include <CGAL/Polygon_mesh_processing/stitch_borders.h>
namespace {
using possumwood::Meshes;
using possumwood::CGALPolyhedron;
typedef possumwood::CGALPolyhedron Mesh;
dependency_graph::InAttr<Meshes> a_inMesh;
dependency_graph::OutAttr<Meshes> a_outMesh;
dependency_graph::State compute(dependency_graph::Values& data) {
Meshes result = data.get(a_inMesh);
for(auto& mesh : result)
CGAL::Polygon_mesh_processing::stitch_borders(mesh.polyhedron());
data.set(a_outMesh, result);
return dependency_graph::State();
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_inMesh, "input");
meta.addAttribute(a_outMesh, "output");
meta.addInfluence(a_inMesh, a_outMesh);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("cgal/topology/stitch_borders", init);
}
<|endoftext|> |
<commit_before>#include <array>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <ros/ros.h>
#include <controller_manager/controller_manager.h>
#include <geometry_msgs/Twist.h>
#include <hardware_interface/joint_command_interface.h>
#include <hardware_interface/joint_state_interface.h>
#include <hardware_interface/robot_hw.h>
#include <nav_msgs/Odometry.h>
#include <ics3/ics>
struct JointData
{
std::string name_;
double cmd_;
double pos_;
double vel_;
double eff_;
};
template<class JntCmdIF>
struct JointControlBuildData
{
std::string joint_name_;
hardware_interface::JointStateInterface& jnt_stat_;
JntCmdIF& jnt_cmd_;
};
class JointControlInterface
{
public:
virtual void fetch() = 0;
virtual void move() = 0;
virtual ~JointControlInterface() noexcept {}
};
class ICSControl
: public JointControlInterface
{
public:
using JntCmdType = hardware_interface::PositionJointInterface;
using BuildDataType = JointControlBuildData<JntCmdType>;
ICSControl(BuildDataType&, ics::ICS3&, const ics::ID&);
void fetch() override;
void move() override;
private:
JointData data_;
ics::ICS3& driver_;
ics::ID id_;
double last_pos_;
};
class SimpleVelocityControl
: public JointControlInterface
{
public:
using JntCmdType = hardware_interface::VelocityJointInterface;
using BuildDataType = JointControlBuildData<JntCmdType>;
SimpleVelocityControl(BuildDataType&);
void fetch() override;
void move() override;
void odomCb(const nav_msgs::OdometryConstPtr&);
private:
JointData data_;
double last_pos_;
double last_vel_;
ros::NodeHandle nh_;
ros::Publisher pub_;
ros::Subscriber sub_;
};
template<class JntCmdIF>
class DammyControl
: public JointControlInterface
{
public:
using JntCmdType = JntCmdIF;
using BuildDataType = JointControlBuildData<JntCmdType>;
DammyControl(BuildDataType&);
void fetch() override;
void move() override;
private:
JointData data_;
};
using DammyPositionControl = DammyControl<hardware_interface::PositionJointInterface>;
using DammyVelocityControl = DammyControl<hardware_interface::VelocityJointInterface>;
class Arcsys2HW
: public hardware_interface::RobotHW
{
public:
static constexpr std::size_t JOINT_COUNT {6};
using JointControlContainer = std::array<JointControlInterface*, JOINT_COUNT>;
Arcsys2HW(hardware_interface::JointStateInterface*);
void registerControl(JointControlInterface*);
void read();
void write();
ros::Time getTime();
ros::Duration getPeriod();
private:
JointControlContainer controls;
};
template<class JntCmdIF>
void registerJoint(
JointData&,
hardware_interface::JointStateInterface&,
JntCmdIF&);
template<class JntCmdIF>
void registerJoint(
JointData&,
JointControlBuildData<JntCmdIF>&);
int main(int argc, char *argv[])
{
ros::init(argc, argv, "arcsys2_control_node");
ros::NodeHandle pnh {"~"};
std::string ics_device_path {"/dev/ttyUSB0"};
pnh.param<std::string>("ics_device_path", ics_device_path, ics_device_path);
ics::ICS3 ics_driver {std::move(ics_device_path)};
std::vector<int> ics_id_vec {};
pnh.getParam("ics_id_vec", ics_id_vec);
if (ics_id_vec.empty()) throw std::invalid_argument {"ics_id_vec parameter is not found"};
std::vector<ics::ID> ics_ids(ics_id_vec.cbegin(), ics_id_vec.cend());
hardware_interface::JointStateInterface joint_state_interface {};
hardware_interface::PositionJointInterface position_joint_interface {};
hardware_interface::VelocityJointInterface velocity_joint_interface {};
DammyVelocityControl::BuildDataType shaft_builder {"rail_to_shaft_joint", joint_state_interface, velocity_joint_interface};
DammyVelocityControl shaft_control {shaft_builder};
DammyVelocityControl::BuildDataType arm0_builder {"shaft_to_arm0_joint", joint_state_interface, velocity_joint_interface};
DammyVelocityControl arm0_control {arm0_builder};
auto ics_id_it = ics_ids.cbegin();
ICSControl::BuildDataType arm1_builder {"arm0_to_arm1_joint", joint_state_interface, position_joint_interface};
ICSControl arm1_control {arm1_builder, ics_driver, *ics_id_it++};
ICSControl::BuildDataType arm2_builder {"arm1_to_arm2_joint", joint_state_interface, position_joint_interface};
ICSControl arm2_control {arm2_builder, ics_driver, *ics_id_it++};
ICSControl::BuildDataType effector_base_builder {"arm2_to_effector_base_joint", joint_state_interface, position_joint_interface};
ICSControl effector_base_control {effector_base_builder, ics_driver, *ics_id_it++};
DammyPositionControl::BuildDataType effector_end_builder {"effector_base_to_effector_end_joint", joint_state_interface, position_joint_interface};
DammyPositionControl effector_end_control {effector_end_builder};
Arcsys2HW robot {&joint_state_interface};
robot.registerInterface(&position_joint_interface);
robot.registerInterface(&velocity_joint_interface);
robot.registerControl(&shaft_control);
robot.registerControl(&arm0_control);
robot.registerControl(&arm1_control);
robot.registerControl(&arm2_control);
robot.registerControl(&effector_base_control);
robot.registerControl(&effector_end_control);
controller_manager::ControllerManager cm {&robot};
ros::Rate rate(1.0 / robot.getPeriod().toSec());
ros::AsyncSpinner spinner {1};
spinner.start();
while(ros::ok())
{
robot.read();
cm.update(robot.getTime(), robot.getPeriod());
robot.write();
rate.sleep();
}
spinner.stop();
return 0;
}
inline ICSControl::ICSControl(BuildDataType& build_data, ics::ICS3& driver, const ics::ID& id)
: data_ {build_data.joint_name_},
driver_(driver), // for ubuntu 14.04
id_ {id},
last_pos_ {0}
{
registerJoint(data_, build_data);
}
inline void ICSControl::fetch()
{
data_.pos_ = last_pos_;
}
inline void ICSControl::move()
{
last_pos_ = driver_.move(id_, ics::Angle::newRadian(data_.cmd_)) / 2 + last_pos_ / 2;
}
inline SimpleVelocityControl::SimpleVelocityControl(BuildDataType& build_data)
: data_ {build_data.joint_name_},
last_pos_ {},
last_vel_ {},
nh_ {build_data.joint_name_},
pub_ {nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1)},
sub_ {nh_.subscribe("odom", 1, &SimpleVelocityControl::odomCb, this)}
{
}
inline void SimpleVelocityControl::fetch()
{
data_.pos_ = last_pos_;
data_.vel_ = last_vel_;
}
inline void SimpleVelocityControl::move()
{
geometry_msgs::Twist msg {};
msg.linear.x = data_.cmd_;
pub_.publish(std::move(msg));
}
inline void SimpleVelocityControl::odomCb(const nav_msgs::OdometryConstPtr& odom)
{
last_pos_ = odom->pose.pose.position.x;
last_vel_ = odom->twist.twist.linear.x;
}
template<class JntCmdIF>
inline DammyControl<JntCmdIF>::DammyControl(BuildDataType& build_data)
: data_ {build_data.joint_name_}
{
registerJoint(data_, build_data);
}
template<>
inline void DammyPositionControl::fetch()
{
data_.pos_ = data_.cmd_;
}
template<>
inline void DammyVelocityControl::fetch()
{
data_.pos_ += data_.cmd_ * 0.01; // FIXME: test code
data_.vel_ = data_.cmd_;
}
template<class JntCmdIF>
inline void DammyControl<JntCmdIF>::move()
{
}
inline Arcsys2HW::Arcsys2HW(hardware_interface::JointStateInterface* jnt_stat)
: controls {}
{
registerInterface(jnt_stat);
}
inline void Arcsys2HW::registerControl(JointControlInterface* jnt_cntr)
{
static auto inserter = controls.begin();
if (inserter == controls.cend()) throw std::out_of_range {"Too many JointControl"};
*inserter = jnt_cntr;
++inserter;
}
inline void Arcsys2HW::read()
{
for (auto control : controls) control->fetch();
}
inline void Arcsys2HW::write()
{
for (auto control : controls) control->move();
}
inline ros::Time Arcsys2HW::getTime()
{
return ros::Time::now();
}
inline ros::Duration Arcsys2HW::getPeriod()
{
return ros::Duration {0.01};
}
template<class JntCmdIF>
inline void registerJoint(
JointData& joint,
hardware_interface::JointStateInterface& jnt_stat,
JntCmdIF& jnt_cmd)
{
jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_});
jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_});
}
template<class JntCmdIF>
inline void registerJoint(
JointData& joint,
JointControlBuildData<JntCmdIF>& build_data)
{
registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_);
}
<commit_msg>Add SimpleControl and SimplePositionControl<commit_after>#include <array>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <ros/ros.h>
#include <controller_manager/controller_manager.h>
#include <geometry_msgs/Twist.h>
#include <hardware_interface/joint_command_interface.h>
#include <hardware_interface/joint_state_interface.h>
#include <hardware_interface/robot_hw.h>
#include <nav_msgs/Odometry.h>
#include <ics3/ics>
struct JointData
{
std::string name_;
double cmd_;
double pos_;
double vel_;
double eff_;
};
template<class JntCmdIF>
struct JointControlBuildData
{
std::string joint_name_;
hardware_interface::JointStateInterface& jnt_stat_;
JntCmdIF& jnt_cmd_;
};
class JointControlInterface
{
public:
virtual void fetch() = 0;
virtual void move() = 0;
virtual ~JointControlInterface() noexcept {}
};
class ICSControl
: public JointControlInterface
{
public:
using JntCmdType = hardware_interface::PositionJointInterface;
using BuildDataType = JointControlBuildData<JntCmdType>;
ICSControl(BuildDataType&, ics::ICS3&, const ics::ID&);
void fetch() override;
void move() override;
private:
JointData data_;
ics::ICS3& driver_;
ics::ID id_;
double last_pos_;
};
template<class JntCmdIF>
class SimpleControl
: public JointControlInterface
{
public:
using JntCmdType = JntCmdIF;
using BuildDataType = JointControlBuildData<JntCmdType>;
SimpleControl(BuildDataType&);
void fetch() override;
void move() override;
void odomCb(const nav_msgs::OdometryConstPtr&);
private:
JointData data_;
double last_pos_;
double last_vel_;
ros::NodeHandle nh_;
ros::Publisher pub_;
ros::Subscriber sub_;
};
using SimplePositionControl = SimpleControl<hardware_interface::PositionJointInterface>;
class SimpleVelocityControl
: public JointControlInterface
{
public:
using JntCmdType = hardware_interface::VelocityJointInterface;
using BuildDataType = JointControlBuildData<JntCmdType>;
SimpleVelocityControl(BuildDataType&);
void fetch() override;
void move() override;
void odomCb(const nav_msgs::OdometryConstPtr&);
private:
JointData data_;
double last_pos_;
double last_vel_;
ros::NodeHandle nh_;
ros::Publisher pub_;
ros::Subscriber sub_;
};
template<class JntCmdIF>
class DammyControl
: public JointControlInterface
{
public:
using JntCmdType = JntCmdIF;
using BuildDataType = JointControlBuildData<JntCmdType>;
DammyControl(BuildDataType&);
void fetch() override;
void move() override;
private:
JointData data_;
};
using DammyPositionControl = DammyControl<hardware_interface::PositionJointInterface>;
using DammyVelocityControl = DammyControl<hardware_interface::VelocityJointInterface>;
class Arcsys2HW
: public hardware_interface::RobotHW
{
public:
static constexpr std::size_t JOINT_COUNT {6};
using JointControlContainer = std::array<JointControlInterface*, JOINT_COUNT>;
Arcsys2HW(hardware_interface::JointStateInterface*);
void registerControl(JointControlInterface*);
void read();
void write();
ros::Time getTime();
ros::Duration getPeriod();
private:
JointControlContainer controls;
};
template<class JntCmdIF>
void registerJoint(
JointData&,
hardware_interface::JointStateInterface&,
JntCmdIF&);
template<class JntCmdIF>
void registerJoint(
JointData&,
JointControlBuildData<JntCmdIF>&);
int main(int argc, char *argv[])
{
ros::init(argc, argv, "arcsys2_control_node");
ros::NodeHandle pnh {"~"};
std::string ics_device_path {"/dev/ttyUSB0"};
pnh.param<std::string>("ics_device_path", ics_device_path, ics_device_path);
ics::ICS3 ics_driver {std::move(ics_device_path)};
std::vector<int> ics_id_vec {};
pnh.getParam("ics_id_vec", ics_id_vec);
if (ics_id_vec.empty()) throw std::invalid_argument {"ics_id_vec parameter is not found"};
std::vector<ics::ID> ics_ids(ics_id_vec.cbegin(), ics_id_vec.cend());
hardware_interface::JointStateInterface joint_state_interface {};
hardware_interface::PositionJointInterface position_joint_interface {};
hardware_interface::VelocityJointInterface velocity_joint_interface {};
DammyVelocityControl::BuildDataType shaft_builder {"rail_to_shaft_joint", joint_state_interface, velocity_joint_interface};
DammyVelocityControl shaft_control {shaft_builder};
DammyVelocityControl::BuildDataType arm0_builder {"shaft_to_arm0_joint", joint_state_interface, velocity_joint_interface};
DammyVelocityControl arm0_control {arm0_builder};
auto ics_id_it = ics_ids.cbegin();
ICSControl::BuildDataType arm1_builder {"arm0_to_arm1_joint", joint_state_interface, position_joint_interface};
ICSControl arm1_control {arm1_builder, ics_driver, *ics_id_it++};
ICSControl::BuildDataType arm2_builder {"arm1_to_arm2_joint", joint_state_interface, position_joint_interface};
ICSControl arm2_control {arm2_builder, ics_driver, *ics_id_it++};
ICSControl::BuildDataType effector_base_builder {"arm2_to_effector_base_joint", joint_state_interface, position_joint_interface};
ICSControl effector_base_control {effector_base_builder, ics_driver, *ics_id_it++};
DammyPositionControl::BuildDataType effector_end_builder {"effector_base_to_effector_end_joint", joint_state_interface, position_joint_interface};
DammyPositionControl effector_end_control {effector_end_builder};
Arcsys2HW robot {&joint_state_interface};
robot.registerInterface(&position_joint_interface);
robot.registerInterface(&velocity_joint_interface);
robot.registerControl(&shaft_control);
robot.registerControl(&arm0_control);
robot.registerControl(&arm1_control);
robot.registerControl(&arm2_control);
robot.registerControl(&effector_base_control);
robot.registerControl(&effector_end_control);
controller_manager::ControllerManager cm {&robot};
ros::Rate rate(1.0 / robot.getPeriod().toSec());
ros::AsyncSpinner spinner {1};
spinner.start();
while(ros::ok())
{
robot.read();
cm.update(robot.getTime(), robot.getPeriod());
robot.write();
rate.sleep();
}
spinner.stop();
return 0;
}
inline ICSControl::ICSControl(BuildDataType& build_data, ics::ICS3& driver, const ics::ID& id)
: data_ {build_data.joint_name_},
driver_(driver), // for ubuntu 14.04
id_ {id},
last_pos_ {0}
{
registerJoint(data_, build_data);
}
inline void ICSControl::fetch()
{
data_.pos_ = last_pos_;
}
inline void ICSControl::move()
{
last_pos_ = driver_.move(id_, ics::Angle::newRadian(data_.cmd_)) / 2 + last_pos_ / 2;
}
template<class JntCmdIF>
inline SimpleControl<JntCmdIF>::SimpleControl(BuildDataType& build_data)
: data_ {build_data.joint_name_},
last_pos_ {},
last_vel_ {},
nh_ {build_data.joint_name_},
pub_ {nh_.advertise<geometry_msgs::Twist>("cmd_pos", 1)},
sub_ {nh_.subscribe("odom", 1, &SimpleControl<JntCmdIF>::odomCb, this)}
{
}
template<class JntCmdIF>
inline void SimpleControl<JntCmdIF>::fetch()
{
data_.pos_ = last_pos_;
data_.pos_ = last_pos_;
}
template<class JntCmdIF>
inline void SimpleControl<JntCmdIF>::odomCb(const nav_msgs::OdometryConstPtr& odom)
{
last_pos_ = odom->pose.pose.position.x;
last_vel_ = odom->twist.twist.linear.x;
}
template<>
inline void SimplePositionControl::move()
{
geometry_msgs::Point msg {};
msg.x = data_.cmd_;
pub_.publish(std::move(msg));
}
inline SimpleVelocityControl::SimpleVelocityControl(BuildDataType& build_data)
: data_ {build_data.joint_name_},
last_pos_ {},
last_vel_ {},
nh_ {build_data.joint_name_},
pub_ {nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1)},
sub_ {nh_.subscribe("odom", 1, &SimpleVelocityControl::odomCb, this)}
{
}
inline void SimpleVelocityControl::fetch()
{
data_.pos_ = last_pos_;
data_.vel_ = last_vel_;
}
inline void SimpleVelocityControl::move()
{
geometry_msgs::Twist msg {};
msg.linear.x = data_.cmd_;
pub_.publish(std::move(msg));
}
inline void SimpleVelocityControl::odomCb(const nav_msgs::OdometryConstPtr& odom)
{
last_pos_ = odom->pose.pose.position.x;
last_vel_ = odom->twist.twist.linear.x;
}
template<class JntCmdIF>
inline DammyControl<JntCmdIF>::DammyControl(BuildDataType& build_data)
: data_ {build_data.joint_name_}
{
registerJoint(data_, build_data);
}
template<>
inline void DammyPositionControl::fetch()
{
data_.pos_ = data_.cmd_;
}
template<>
inline void DammyVelocityControl::fetch()
{
data_.pos_ += data_.cmd_ * 0.01; // FIXME: test code
data_.vel_ = data_.cmd_;
}
template<class JntCmdIF>
inline void DammyControl<JntCmdIF>::move()
{
}
inline Arcsys2HW::Arcsys2HW(hardware_interface::JointStateInterface* jnt_stat)
: controls {}
{
registerInterface(jnt_stat);
}
inline void Arcsys2HW::registerControl(JointControlInterface* jnt_cntr)
{
static auto inserter = controls.begin();
if (inserter == controls.cend()) throw std::out_of_range {"Too many JointControl"};
*inserter = jnt_cntr;
++inserter;
}
inline void Arcsys2HW::read()
{
for (auto control : controls) control->fetch();
}
inline void Arcsys2HW::write()
{
for (auto control : controls) control->move();
}
inline ros::Time Arcsys2HW::getTime()
{
return ros::Time::now();
}
inline ros::Duration Arcsys2HW::getPeriod()
{
return ros::Duration {0.01};
}
template<class JntCmdIF>
inline void registerJoint(
JointData& joint,
hardware_interface::JointStateInterface& jnt_stat,
JntCmdIF& jnt_cmd)
{
jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_});
jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_});
}
template<class JntCmdIF>
inline void registerJoint(
JointData& joint,
JointControlBuildData<JntCmdIF>& build_data)
{
registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_);
}
<|endoftext|> |
<commit_before>#ifndef basic_types_hpp
#define basic_types_hpp
// I think this has to come before STL?
#include <boost/config.hpp>
// ===========================================
// All the STL support we need
// ===========================================
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <unordered_map> // for C++11 unordered_map and unordered_multimap
#include <unordered_set>
// ===========================================
// My STL container extensions (ie sorted_vector)
#include "STLContainers.h"
// ===========================================
// Basic boost support
// ===========================================
// for boost::split(), replace_all()
#include <boost/algorithm/string.hpp>
// boost assign
// used for:
// std::vector<int> v = boost::assign::list_of(1)(2)(3);
// REPLACE once c++11 is available:
// std::vector<int> v = {1,2,3};
#include <boost/assign.hpp>
// for checksum functions
#include <boost/crc.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time; // for ptime
using namespace boost::gregorian; // for date
// ranged for loops with an index:
// for (const auto& element : boost::adaptors::index(my_container))
// cout << element.value() << element.index();
#include <boost/range/adaptor/indexed.hpp>
// ===========================================
// ===========================================
// 32 vs 64 bit ENVIRONMENT CHECK
// ===========================================
// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif
// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif
// ===========================================
// ===========================================
// cross-platform threading and i/o
// ===========================================
#ifdef WIN32
// we need to define the target system
#define _WIN32_WINNT 0x0501
// we also need a compiled lib:
// libboost_system-vc100-mt-1_53.lib
//
// to get it, first build boost:
//
// cd boost
// bootstrap.bat
// .\b2
//
// then add the lib path to the project:
// C:\Software Development\boost_1_53_0\stage\lib
#endif
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/date_time.hpp>
// ===========================================
// ===========================================
// https (taken from boost docs)
// ===========================================
#include <boost/asio/ssl.hpp>
using boost::asio::ip::tcp;
namespace ssl = boost::asio::ssl;
// NOTE that we use the form that requires an existing socket.
// See: http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/overview/ssl.html
typedef ssl::stream<tcp::socket&> ssl_socket;
typedef ssl::stream<tcp::socket> ssl_embedded_socket;
// ===========================================
// ===========================================
// UUIDs
// ===========================================
// When using this in windows...
// You need to define following macro under Project Properties--> yourapp Properties--> ALL CONFIGS -> C/C++-->Command Connector-->Additional Options
//
// -D_SCL_SECURE_NO_WARNINGS
//
// so VS doesn't spew "checked iterators" warnings.
// ===========================================
// NOTE in boost 1.69 you get some erroneous dumb deprecated warning, here is a workaround that can come out once we have 1.70.
#define BOOST_PENDING_INTEGER_LOG2_HPP
#include <boost/integer/integer_log2.hpp>
// ===========================================
#include <boost/uuid/uuid.hpp> // uuid class
#include <boost/uuid/random_generator.hpp> // uuid generators
#include <boost/uuid/uuid_io.hpp> // streaming operators etc.
// ===========================================
// ===========================================
// graph library (BGL) support
// ===========================================
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/undirected_dfs.hpp>
#include <boost/graph/graphviz.hpp>
// ===========================================
// ===========================================
// writing to and reading from files
// ===========================================
#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
// ===========================================
using namespace std;
using namespace boost;
// ===========================================
// COMMON CUSTOM TYPES
// ===========================================
typedef vector<string> Strings;
typedef Strings::iterator StringsIt;
typedef vector<int> Ints;
typedef vector<int>::iterator IntsIt;
typedef vector<int>::const_iterator IntsConstIt;
// our hashmaps
typedef std::unordered_map<std::string, int> hashmap;
typedef std::unordered_multimap<std::string, int> hashmmap;
// RESTful http action verbs
// Used by http_client and http_server
// Search for this on changes:
// assert(http_action_count == 5);
typedef enum
{
ha_get, // for RETRIEVE
ha_post, // for CREATE (when using server-generated ID)
ha_put, // for UPDATE (also for create when client provides ID)
ha_patch, // for UPDATE of a subset of fields (PUT technically requires all)
ha_delete, // for DELETE
http_action_count
} http_action;
// NOTE that for many of our JSON objects, we don't need to permanently store all the data that is extracted.
// Strategy:
// use a memory object inside a JSON object
// extract the JSON
// use the JSON data as needed
// discard the JSON object and just keep the in-memory object
class JSONableObject
{
public:
virtual ~JSONableObject() {}
virtual bool from_JSON(const string& in) = 0;
virtual string to_JSON() const = 0;
virtual void log() const {}
};
#endif
<commit_msg>Comments<commit_after>#ifndef basic_types_hpp
#define basic_types_hpp
// I think this has to come before STL?
#include <boost/config.hpp>
// ===========================================
// All the STL support we need
// ===========================================
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <unordered_map> // for C++11 unordered_map and unordered_multimap
#include <unordered_set>
// #include <format> // C++20, not implemented by any compiler as of 2020-11
// ===========================================
// My STL container extensions (ie sorted_vector)
#include "STLContainers.h"
// ===========================================
// Basic boost support
// ===========================================
// for boost::split(), replace_all()
#include <boost/algorithm/string.hpp>
// boost assign
// used for:
// std::vector<int> v = boost::assign::list_of(1)(2)(3);
// REPLACE once c++11 is available:
// std::vector<int> v = {1,2,3};
#include <boost/assign.hpp>
// for checksum functions
#include <boost/crc.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time; // for ptime
using namespace boost::gregorian; // for date
// ranged for loops with an index:
// for (const auto& element : boost::adaptors::index(my_container))
// cout << element.value() << element.index();
#include <boost/range/adaptor/indexed.hpp>
// ===========================================
// ===========================================
// 32 vs 64 bit ENVIRONMENT CHECK
// ===========================================
// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif
// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif
// ===========================================
// ===========================================
// cross-platform threading and i/o
// ===========================================
#ifdef WIN32
// we need to define the target system
#define _WIN32_WINNT 0x0501
// we also need a compiled lib:
// libboost_system-vc100-mt-1_53.lib
//
// to get it, first build boost:
//
// cd boost
// bootstrap.bat
// .\b2
//
// then add the lib path to the project:
// C:\Software Development\boost_1_53_0\stage\lib
#endif
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/date_time.hpp>
// ===========================================
// ===========================================
// https (taken from boost docs)
// ===========================================
#include <boost/asio/ssl.hpp>
using boost::asio::ip::tcp;
namespace ssl = boost::asio::ssl;
// NOTE that we use the form that requires an existing socket.
// See: http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/overview/ssl.html
typedef ssl::stream<tcp::socket&> ssl_socket;
typedef ssl::stream<tcp::socket> ssl_embedded_socket;
// ===========================================
// ===========================================
// UUIDs
// ===========================================
// When using this in windows...
// You need to define following macro under Project Properties--> yourapp Properties--> ALL CONFIGS -> C/C++-->Command Connector-->Additional Options
//
// -D_SCL_SECURE_NO_WARNINGS
//
// so VS doesn't spew "checked iterators" warnings.
// ===========================================
// NOTE in boost 1.69 you get some erroneous dumb deprecated warning, here is a workaround that can come out once we have 1.70.
#define BOOST_PENDING_INTEGER_LOG2_HPP
#include <boost/integer/integer_log2.hpp>
// ===========================================
#include <boost/uuid/uuid.hpp> // uuid class
#include <boost/uuid/random_generator.hpp> // uuid generators
#include <boost/uuid/uuid_io.hpp> // streaming operators etc.
// ===========================================
// ===========================================
// graph library (BGL) support
// ===========================================
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/undirected_dfs.hpp>
#include <boost/graph/graphviz.hpp>
// ===========================================
// ===========================================
// writing to and reading from files
// ===========================================
#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
// ===========================================
using namespace std;
using namespace boost;
// ===========================================
// COMMON CUSTOM TYPES
// ===========================================
typedef vector<string> Strings;
typedef Strings::iterator StringsIt;
typedef vector<int> Ints;
typedef vector<int>::iterator IntsIt;
typedef vector<int>::const_iterator IntsConstIt;
// our hashmaps
typedef std::unordered_map<std::string, int> hashmap;
typedef std::unordered_multimap<std::string, int> hashmmap;
// RESTful http action verbs
// Used by http_client and http_server
// Search for this on changes:
// assert(http_action_count == 5);
typedef enum
{
ha_get, // for RETRIEVE
ha_post, // for CREATE (when using server-generated ID)
ha_put, // for UPDATE (also for create when client provides ID)
ha_patch, // for UPDATE of a subset of fields (PUT technically requires all)
ha_delete, // for DELETE
http_action_count
} http_action;
// NOTE that for many of our JSON objects, we don't need to permanently store all the data that is extracted.
// Strategy:
// use a memory object inside a JSON object
// extract the JSON
// use the JSON data as needed
// discard the JSON object and just keep the in-memory object
class JSONableObject
{
public:
virtual ~JSONableObject() {}
virtual bool from_JSON(const string& in) = 0;
virtual string to_JSON() const = 0;
virtual void log() const {}
};
#endif
<|endoftext|> |
<commit_before>/**
* @file omxcv_jpeg.cpp
* @brief OpenMAX JPEG encoder for OpenCV.
*/
#include "omxcv.h"
#include "omxcv-impl.h"
#include <vector>
using namespace omxcv;
OmxCvJpegImpl::OmxCvJpegImpl(int width, int height, int quality)
: m_width(width)
, m_height(height)
, m_stride(((width + 31) & ~31) * 3)
, m_quality(quality)
, m_stop{false}
{
int ret;
bcm_host_init();
//Initialise OpenMAX and the IL client.
CHECKED(OMX_Init() != OMX_ErrorNone, "OMX_Init failed.");
m_ilclient = ilclient_init();
CHECKED(m_ilclient == NULL, "ILClient initialisation failed.");
ret = ilclient_create_component(m_ilclient, &m_encoder_component,
(char*)"image_encode",
(ILCLIENT_CREATE_FLAGS_T)(ILCLIENT_DISABLE_ALL_PORTS |
ILCLIENT_ENABLE_INPUT_BUFFERS | ILCLIENT_ENABLE_OUTPUT_BUFFERS));
CHECKED(ret != 0, "ILCient image_encode component creation failed.");
//Set input definition to the encoder
OMX_PARAM_PORTDEFINITIONTYPE def = {0};
def.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
def.nVersion.nVersion = OMX_VERSION;
def.nPortIndex = OMX_JPEG_PORT_IN;
ret = OMX_GetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamPortDefinition, &def);
CHECKED(ret != OMX_ErrorNone, "OMX_GetParameter failed for encode port in.");
//We allocate 3 input buffers.
def.nBufferCountActual = 3;
def.format.image.nFrameWidth = m_width;
def.format.image.nFrameHeight = m_height;
//16 byte alignment. I don't know if these also hold for image encoding.
def.format.image.nSliceHeight = (m_height + 15) & ~15;
//Must be manually defined to ensure sufficient size if stride needs to be rounded up to multiple of 32.
def.nBufferSize = def.format.image.nStride * def.format.image.nSliceHeight;
def.format.image.nStride = m_stride;
def.format.image.bFlagErrorConcealment = OMX_FALSE;
def.format.image.eColorFormat = OMX_COLOR_Format24bitBGR888; //OMX_COLOR_Format32bitABGR8888;//OMX_COLOR_FormatYUV420PackedPlanar;
ret = OMX_SetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamPortDefinition, &def);
CHECKED(ret != OMX_ErrorNone, "OMX_SetParameter failed for input format definition.");
//Set the output format of the encoder
OMX_IMAGE_PARAM_PORTFORMATTYPE format = {0};
format.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
format.nVersion.nVersion = OMX_VERSION;
format.nPortIndex = OMX_JPEG_PORT_OUT;
format.eCompressionFormat = OMX_IMAGE_CodingJPEG;
ret = OMX_SetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamImagePortFormat, &format);
CHECKED(ret != OMX_ErrorNone, "OMX_SetParameter failed for setting encoder output format.");
//Set the encoder quality
OMX_IMAGE_PARAM_QFACTORTYPE qfactor = {0};
qfactor.nSize = sizeof(OMX_IMAGE_PARAM_QFACTORTYPE);
qfactor.nVersion.nVersion = OMX_VERSION;
qfactor.nPortIndex = OMX_JPEG_PORT_OUT;
qfactor.nQFactor = m_quality;
ret = OMX_SetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamQFactor, &qfactor);
CHECKED(ret != OMX_ErrorNone, "OMX_SetParameter failed for setting encoder quality.");
ret = ilclient_change_component_state(m_encoder_component, OMX_StateIdle);
CHECKED(ret != 0, "ILClient failed to change encoder to idle state.");
ret = ilclient_enable_port_buffers(m_encoder_component, OMX_JPEG_PORT_IN, NULL, NULL, NULL);
CHECKED(ret != 0, "ILClient failed to enable input buffers.");
ret = ilclient_enable_port_buffers(m_encoder_component, OMX_JPEG_PORT_OUT, NULL, NULL, NULL);
CHECKED(ret != 0, "ILClient failed to enable output buffers.");
ret = ilclient_change_component_state(m_encoder_component, OMX_StateExecuting);
CHECKED(ret != 0, "ILClient failed to change encoder to executing stage.");
//Start the worker thread for dumping the encoded data
m_input_worker = std::thread(&OmxCvJpegImpl::input_worker, this);
}
OmxCvJpegImpl::~OmxCvJpegImpl() {
m_stop = true;
m_input_signaller.notify_one();
m_input_worker.join();
//Teardown similar to hello_encode
ilclient_change_component_state(m_encoder_component, OMX_StateIdle);
ilclient_disable_port_buffers(m_encoder_component, OMX_JPEG_PORT_IN, NULL, NULL, NULL);
ilclient_disable_port_buffers(m_encoder_component, OMX_JPEG_PORT_OUT, NULL, NULL, NULL);
//ilclient_change_component_state(m_encoder_component, OMX_StateIdle);
ilclient_change_component_state(m_encoder_component, OMX_StateLoaded);
COMPONENT_T *list[] = {m_encoder_component, NULL};
ilclient_cleanup_components(list);
ilclient_destroy(m_ilclient);
}
void OmxCvJpegImpl::input_worker() {
std::unique_lock<std::mutex> lock(m_input_mutex);
OMX_BUFFERHEADERTYPE *out = ilclient_get_output_buffer(m_encoder_component, OMX_JPEG_PORT_OUT, 1);
while (true) {
m_input_signaller.wait(lock, [this]{return m_stop || m_input_queue.size() > 0;});
if (m_stop) {
if (m_input_queue.size() > 0) {
printf("Stop acknowledged but need to flush the input buffer (%d)...\n", m_input_queue.size());
} else {
break;
}
}
std::pair<OMX_BUFFERHEADERTYPE *, std::string> frame = m_input_queue.front();
m_input_queue.pop_front();
lock.unlock();
FILE *fp = fopen(frame.second.c_str(), "wb");
if (!fp) {
perror(frame.second.c_str());
}
OMX_EmptyThisBuffer(ILC_GET_HANDLE(m_encoder_component), frame.first);
do {
OMX_FillThisBuffer(ILC_GET_HANDLE(m_encoder_component), out);
out = ilclient_get_output_buffer(m_encoder_component, OMX_JPEG_PORT_OUT, 1);
if (fp) {
fwrite(out->pBuffer, 1, out->nFilledLen, fp);
}
} while (!(out->nFlags & OMX_BUFFERFLAG_ENDOFFRAME));
fclose(fp);
lock.lock();
}
//Needed because we call ilclient_get_output_buffer last.
//Otherwise ilclient waits forever for the buffer to be filled.
OMX_FillThisBuffer(ILC_GET_HANDLE(m_encoder_component), out);
}
bool OmxCvJpegImpl::process(const char *filename, const cv::Mat &mat) {
//static const std::vector<int> saveparams = {CV_IMWRITE_JPEG_QUALITY, 75};
//cv::imwrite(filename, mat, saveparams);
OMX_BUFFERHEADERTYPE *in = ilclient_get_input_buffer(
m_encoder_component, OMX_JPEG_PORT_IN, 0);
if (in == NULL) { //No free buffer.
return false;
}
assert(mat.cols == m_width && mat.rows == m_height);
BGR2RGB(mat, in->pBuffer, m_stride);
in->nFilledLen = in->nAllocLen;
std::unique_lock<std::mutex> lock(m_input_mutex);
m_input_queue.push_back(std::pair<OMX_BUFFERHEADERTYPE *, std::string>(
in, std::string(filename)));
lock.unlock();
m_input_signaller.notify_one();
return true;
}
/**
* Constructor for our wrapper.
* @param [in] name The file to save to.
* @param [in] width The video width.
* @param [in] height The video height.
* @param [in] bitrate The bitrate, in Kbps.
* @param [in] fpsnum The FPS numerator.
* @param [in] fpsden The FPS denominator.
*/
OmxCvJpeg::OmxCvJpeg(int width, int height, int quality)
: m_width(width)
, m_height(height)
, m_quality(quality)
{
m_impl = new OmxCvJpegImpl(width, height, quality);
}
/**
* Wrapper destructor.
*/
OmxCvJpeg::~OmxCvJpeg() {
delete m_impl;
}
/**
* Encode image.
* @param [in] filename The path to save the image to.
* @param [in] in Image to be encoded.
* @param [in] fallback If set to true and there is no available buffer for
* encoding, fallback to using OpenCV to write out the image.
* @return true iff the file was encoded.
*/
bool OmxCvJpeg::Encode(const char *filename, const cv::Mat &in, bool fallback) {
if (in.cols != m_width || in.rows != m_height || in.type() != CV_8UC3) {
std::vector<int> params {CV_IMWRITE_JPEG_QUALITY, m_quality};
return cv::imwrite(filename, in, params);
}
bool ret = m_impl->process(filename, in);
if (!ret && fallback) {
std::vector<int> params {CV_IMWRITE_JPEG_QUALITY, m_quality};
return cv::imwrite(filename, in, params);
}
return ret;
}
<commit_msg>JPEG: Add commentry + fp check for fclose.<commit_after>/**
* @file omxcv_jpeg.cpp
* @brief OpenMAX JPEG encoder for OpenCV.
*/
#include "omxcv.h"
#include "omxcv-impl.h"
#include <vector>
using namespace omxcv;
/**
* Constructor.
* @param [in] width The width of the image to encode.
* @param [in] height The height of the image to encode.
* @param [in] quality The JPEG quality factor (1-100). 100 is best quality.
* @throws std::invalid_argument on error.
*/
OmxCvJpegImpl::OmxCvJpegImpl(int width, int height, int quality)
: m_width(width)
, m_height(height)
, m_stride(((width + 31) & ~31) * 3)
, m_quality(quality)
, m_stop{false}
{
int ret;
bcm_host_init();
//Initialise OpenMAX and the IL client.
CHECKED(OMX_Init() != OMX_ErrorNone, "OMX_Init failed.");
m_ilclient = ilclient_init();
CHECKED(m_ilclient == NULL, "ILClient initialisation failed.");
ret = ilclient_create_component(m_ilclient, &m_encoder_component,
(char*)"image_encode",
(ILCLIENT_CREATE_FLAGS_T)(ILCLIENT_DISABLE_ALL_PORTS |
ILCLIENT_ENABLE_INPUT_BUFFERS | ILCLIENT_ENABLE_OUTPUT_BUFFERS));
CHECKED(ret != 0, "ILCient image_encode component creation failed.");
//Set input definition to the encoder
OMX_PARAM_PORTDEFINITIONTYPE def = {0};
def.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
def.nVersion.nVersion = OMX_VERSION;
def.nPortIndex = OMX_JPEG_PORT_IN;
ret = OMX_GetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamPortDefinition, &def);
CHECKED(ret != OMX_ErrorNone, "OMX_GetParameter failed for encode port in.");
//We allocate 3 input buffers.
def.nBufferCountActual = 3;
def.format.image.nFrameWidth = m_width;
def.format.image.nFrameHeight = m_height;
//16 byte alignment. I don't know if these also hold for image encoding.
def.format.image.nSliceHeight = (m_height + 15) & ~15;
//Must be manually defined to ensure sufficient size if stride needs to be rounded up to multiple of 32.
def.nBufferSize = def.format.image.nStride * def.format.image.nSliceHeight;
def.format.image.nStride = m_stride;
def.format.image.bFlagErrorConcealment = OMX_FALSE;
def.format.image.eColorFormat = OMX_COLOR_Format24bitBGR888; //OMX_COLOR_Format32bitABGR8888;//OMX_COLOR_FormatYUV420PackedPlanar;
ret = OMX_SetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamPortDefinition, &def);
CHECKED(ret != OMX_ErrorNone, "OMX_SetParameter failed for input format definition.");
//Set the output format of the encoder
OMX_IMAGE_PARAM_PORTFORMATTYPE format = {0};
format.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
format.nVersion.nVersion = OMX_VERSION;
format.nPortIndex = OMX_JPEG_PORT_OUT;
format.eCompressionFormat = OMX_IMAGE_CodingJPEG;
ret = OMX_SetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamImagePortFormat, &format);
CHECKED(ret != OMX_ErrorNone, "OMX_SetParameter failed for setting encoder output format.");
//Set the encoder quality
OMX_IMAGE_PARAM_QFACTORTYPE qfactor = {0};
qfactor.nSize = sizeof(OMX_IMAGE_PARAM_QFACTORTYPE);
qfactor.nVersion.nVersion = OMX_VERSION;
qfactor.nPortIndex = OMX_JPEG_PORT_OUT;
qfactor.nQFactor = m_quality;
ret = OMX_SetParameter(ILC_GET_HANDLE(m_encoder_component),
OMX_IndexParamQFactor, &qfactor);
CHECKED(ret != OMX_ErrorNone, "OMX_SetParameter failed for setting encoder quality.");
ret = ilclient_change_component_state(m_encoder_component, OMX_StateIdle);
CHECKED(ret != 0, "ILClient failed to change encoder to idle state.");
ret = ilclient_enable_port_buffers(m_encoder_component, OMX_JPEG_PORT_IN, NULL, NULL, NULL);
CHECKED(ret != 0, "ILClient failed to enable input buffers.");
ret = ilclient_enable_port_buffers(m_encoder_component, OMX_JPEG_PORT_OUT, NULL, NULL, NULL);
CHECKED(ret != 0, "ILClient failed to enable output buffers.");
ret = ilclient_change_component_state(m_encoder_component, OMX_StateExecuting);
CHECKED(ret != 0, "ILClient failed to change encoder to executing stage.");
//Start the worker thread for dumping the encoded data
m_input_worker = std::thread(&OmxCvJpegImpl::input_worker, this);
}
/**
* Destructor.
*/
OmxCvJpegImpl::~OmxCvJpegImpl() {
m_stop = true;
m_input_signaller.notify_one();
m_input_worker.join();
//Teardown similar to hello_encode
ilclient_change_component_state(m_encoder_component, OMX_StateIdle);
ilclient_disable_port_buffers(m_encoder_component, OMX_JPEG_PORT_IN, NULL, NULL, NULL);
ilclient_disable_port_buffers(m_encoder_component, OMX_JPEG_PORT_OUT, NULL, NULL, NULL);
//ilclient_change_component_state(m_encoder_component, OMX_StateIdle);
ilclient_change_component_state(m_encoder_component, OMX_StateLoaded);
COMPONENT_T *list[] = {m_encoder_component, NULL};
ilclient_cleanup_components(list);
ilclient_destroy(m_ilclient);
}
/**
* Worker thread. Encodes the images.
*/
void OmxCvJpegImpl::input_worker() {
std::unique_lock<std::mutex> lock(m_input_mutex);
OMX_BUFFERHEADERTYPE *out = ilclient_get_output_buffer(m_encoder_component, OMX_JPEG_PORT_OUT, 1);
while (true) {
m_input_signaller.wait(lock, [this]{return m_stop || m_input_queue.size() > 0;});
if (m_stop) {
if (m_input_queue.size() > 0) {
printf("Stop acknowledged but need to flush the input buffer (%d)...\n", m_input_queue.size());
} else {
break;
}
}
std::pair<OMX_BUFFERHEADERTYPE *, std::string> frame = m_input_queue.front();
m_input_queue.pop_front();
lock.unlock();
FILE *fp = fopen(frame.second.c_str(), "wb");
if (!fp) {
perror(frame.second.c_str());
}
OMX_EmptyThisBuffer(ILC_GET_HANDLE(m_encoder_component), frame.first);
do {
OMX_FillThisBuffer(ILC_GET_HANDLE(m_encoder_component), out);
out = ilclient_get_output_buffer(m_encoder_component, OMX_JPEG_PORT_OUT, 1);
if (fp) {
fwrite(out->pBuffer, 1, out->nFilledLen, fp);
}
} while (!(out->nFlags & OMX_BUFFERFLAG_ENDOFFRAME));
if (fp) {
fclose(fp);
}
lock.lock();
}
//Needed because we call ilclient_get_output_buffer last.
//Otherwise ilclient waits forever for the buffer to be filled.
OMX_FillThisBuffer(ILC_GET_HANDLE(m_encoder_component), out);
}
/**
* Process a frame.
* @param [in] filename The filename to save to.
* @param [in] mat The image data to save.
* @return true iff the image will be saved. Will return false if there's no
* free input buffer.
*/
bool OmxCvJpegImpl::process(const char *filename, const cv::Mat &mat) {
//static const std::vector<int> saveparams = {CV_IMWRITE_JPEG_QUALITY, 75};
//cv::imwrite(filename, mat, saveparams);
OMX_BUFFERHEADERTYPE *in = ilclient_get_input_buffer(
m_encoder_component, OMX_JPEG_PORT_IN, 0);
if (in == NULL) { //No free buffer.
return false;
}
assert(mat.cols == m_width && mat.rows == m_height);
BGR2RGB(mat, in->pBuffer, m_stride);
in->nFilledLen = in->nAllocLen;
std::unique_lock<std::mutex> lock(m_input_mutex);
m_input_queue.push_back(std::pair<OMX_BUFFERHEADERTYPE *, std::string>(
in, std::string(filename)));
lock.unlock();
m_input_signaller.notify_one();
return true;
}
/**
* Constructor for our wrapper.
* @param [in] name The file to save to.
* @param [in] width The video width.
* @param [in] height The video height.
* @param [in] bitrate The bitrate, in Kbps.
* @param [in] fpsnum The FPS numerator.
* @param [in] fpsden The FPS denominator.
*/
OmxCvJpeg::OmxCvJpeg(int width, int height, int quality)
: m_width(width)
, m_height(height)
, m_quality(quality)
{
m_impl = new OmxCvJpegImpl(width, height, quality);
}
/**
* Wrapper destructor.
*/
OmxCvJpeg::~OmxCvJpeg() {
delete m_impl;
}
/**
* Encode image.
* @param [in] filename The path to save the image to.
* @param [in] in Image to be encoded. If the width and height of this
* image does not match what was set in the constructor,
* this function will fallback to using OpenCV's imwrite.
* @param [in] fallback If set to true and there is no available buffer for
* encoding, fallback to using OpenCV to write out the image.
* @return true iff the file was encoded.
*/
bool OmxCvJpeg::Encode(const char *filename, const cv::Mat &in, bool fallback) {
if (in.cols != m_width || in.rows != m_height || in.type() != CV_8UC3) {
std::vector<int> params {CV_IMWRITE_JPEG_QUALITY, m_quality};
return cv::imwrite(filename, in, params);
}
bool ret = m_impl->process(filename, in);
if (!ret && fallback) {
std::vector<int> params {CV_IMWRITE_JPEG_QUALITY, m_quality};
return cv::imwrite(filename, in, params);
}
return ret;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vpp/vpp.hh>
using namespace vpp;
int main()
{
vuchar3 p;
//vint3 x = cast<vint3>(p);
vint1 xxx; xxx[0] = (20);
float y = cast<float>(xxx);
assert(y == 20);
vint1 vi = cast<vint1>(float(3.f));
assert(vi[0] == 3);
}
<commit_msg>Fix cast.<commit_after>#include <iostream>
#include <vpp/vpp.hh>
using namespace vpp;
int main()
{
vuchar3 p;
vint3 x = cast<vint3>(p);
vint1 xxx; xxx[0] = (20);
float y = cast<float>(xxx);
assert(y == 20);
vint1 vi = cast<vint1>(float(3.f));
assert(vi[0] == 3);
}
<|endoftext|> |
<commit_before>/*
HCSR04 - Library for arduino, for HC-SR04 ultrasonic distance sensor.
Created by Martin Sosic, June 11, 2016.
*/
#include "Arduino.h"
#include "HCSR04.h"
UltraSonicDistanceSensor::UltraSonicDistanceSensor(
int triggerPin, int echoPin) {
this->triggerPin = triggerPin;
this->echoPin = echoPin;
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
double UltraSonicDistanceSensor::measureDistanceCm() {
//Using the approximate formula 19.307°C results in roughly 343m/s which is the commonly used value for air.
return measureDistanceCm(19.307);
}
double UltraSonicDistanceSensor::measureDistanceCm(float temperature) {
// Make sure that trigger pin is LOW.
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Hold trigger for 10 microseconds, which is signal for sensor to measure distance.
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Measure the length of echo signal, which is equal to the time needed for sound to go there and back.
unsigned long durationMicroSec = pulseIn(echoPin, HIGH);
double speedOfSoundInCmPerMs = 0.03313 + 0.0000606 * temperature // Cair ≈ (331.3 + 0.606 ⋅ ϑ) m/s
double distanceCm = durationMicroSec / 2.0 * speedOfSoundInCmPerMs;
if (distanceCm == 0 || distanceCm > 400) {
return -1.0 ;
} else {
return distanceCm;
}
}
<commit_msg>Fix build error - missing semicolon<commit_after>/*
HCSR04 - Library for arduino, for HC-SR04 ultrasonic distance sensor.
Created by Martin Sosic, June 11, 2016.
*/
#include "Arduino.h"
#include "HCSR04.h"
UltraSonicDistanceSensor::UltraSonicDistanceSensor(
int triggerPin, int echoPin) {
this->triggerPin = triggerPin;
this->echoPin = echoPin;
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
double UltraSonicDistanceSensor::measureDistanceCm() {
//Using the approximate formula 19.307°C results in roughly 343m/s which is the commonly used value for air.
return measureDistanceCm(19.307);
}
double UltraSonicDistanceSensor::measureDistanceCm(float temperature) {
// Make sure that trigger pin is LOW.
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Hold trigger for 10 microseconds, which is signal for sensor to measure distance.
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Measure the length of echo signal, which is equal to the time needed for sound to go there and back.
unsigned long durationMicroSec = pulseIn(echoPin, HIGH);
double speedOfSoundInCmPerMs = 0.03313 + 0.0000606 * temperature; // Cair ≈ (331.3 + 0.606 ⋅ ϑ) m/s
double distanceCm = durationMicroSec / 2.0 * speedOfSoundInCmPerMs;
if (distanceCm == 0 || distanceCm > 400) {
return -1.0 ;
} else {
return distanceCm;
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <sstream>
#include <map>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <Context.h>
#include <Filter.h>
#include <Lexer.h>
#include <ViewTask.h>
#include <i18n.h>
#include <text.h>
#include <main.h>
#include <CmdCustom.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdCustom::CmdCustom (
const std::string& k,
const std::string& u,
const std::string& d)
{
_keyword = k;
_usage = u;
_description = d;
_read_only = true;
_displays_id = true;
}
////////////////////////////////////////////////////////////////////////////////
int CmdCustom::execute (std::string& output)
{
int rc = 0;
// Load report configuration.
std::string reportColumns = context.config.get ("report." + _keyword + ".columns");
std::string reportLabels = context.config.get ("report." + _keyword + ".labels");
std::string reportSort = context.config.get ("report." + _keyword + ".sort");
std::string reportFilter = context.config.get ("report." + _keyword + ".filter");
if (reportFilter != "")
reportFilter = "( " + reportFilter + " )";
std::vector <std::string> columns;
split (columns, reportColumns, ',');
validateReportColumns (columns);
std::vector <std::string> labels;
split (labels, reportLabels, ',');
if (columns.size () != labels.size () && labels.size () != 0)
throw format (STRING_CMD_CUSTOM_MISMATCH, _keyword);
std::vector <std::string> sortOrder;
split (sortOrder, reportSort, ',');
validateSortColumns (sortOrder);
// Prepend the argument list with those from the report filter.
std::string lexeme;
Lexer::Type type;
Lexer lex (reportFilter);
lex.ambiguity (false);
std::vector <std::string> filterArgs;
while (lex.token (lexeme, type))
{
filterArgs.push_back (lexeme);
context.cli.add (lexeme);
}
std::vector <std::string>::reverse_iterator arg;
for (arg = filterArgs.rbegin (); arg != filterArgs.rend (); ++ arg)
context.parser.captureFirst (*arg);
// Reparse after tree change.
context.parser.parse ();
context.cli.analyze ();
// Apply filter.
handleRecurrence ();
Filter filter;
std::vector <Task> filtered;
filter.subset (filtered);
// Sort the tasks.
std::vector <int> sequence;
for (unsigned int i = 0; i < filtered.size (); ++i)
sequence.push_back (i);
sort_tasks (filtered, sequence, reportSort);
// Configure the view.
ViewTask view;
view.width (context.getWidth ());
view.leftMargin (context.config.getInteger ("indent.report"));
view.extraPadding (context.config.getInteger ("row.padding"));
view.intraPadding (context.config.getInteger ("column.padding"));
Color label (context.config.get ("color.label"));
view.colorHeader (label);
Color label_sort (context.config.get ("color.label.sort"));
view.colorSortHeader (label_sort);
Color alternate (context.config.get ("color.alternate"));
view.colorOdd (alternate);
view.intraColorOdd (alternate);
// Capture columns that are sorted.
std::vector <std::string> sortColumns;
// Add the break columns, if any.
std::vector <std::string>::iterator so;
for (so = sortOrder.begin (); so != sortOrder.end (); ++so)
{
std::string name;
bool ascending;
bool breakIndicator;
context.decomposeSortField (*so, name, ascending, breakIndicator);
if (breakIndicator)
view.addBreak (name);
sortColumns.push_back (name);
}
// Add the columns and labels.
for (unsigned int i = 0; i < columns.size (); ++i)
{
Column* c = Column::factory (columns[i], _keyword);
if (i < labels.size ())
c->setLabel (labels[i]);
bool sort = std::find (sortColumns.begin (), sortColumns.end (), c->name ()) != sortColumns.end ()
? true
: false;
view.add (c, sort);
}
// How many lines taken up by table header?
int table_header = 0;
if (context.verbose ("label"))
{
if (context.color () && context.config.getBoolean ("fontunderline"))
table_header = 1; // Underlining doesn't use extra line.
else
table_header = 2; // Dashes use an extra line.
}
// Report output can be limited by rows or lines.
int maxrows = 0;
int maxlines = 0;
context.getLimits (maxrows, maxlines);
// Adjust for fluff in the output.
if (maxlines)
maxlines -= table_header
+ (context.verbose ("blank") ? 1 : 0)
+ (context.verbose ("footnote") ? context.footnotes.size () : 0)
+ (context.verbose ("affected") ? 1 : 0)
+ context.config.getInteger ("reserved.lines"); // For prompt, etc.
// Render.
std::stringstream out;
if (filtered.size ())
{
view.truncateRows (maxrows);
view.truncateLines (maxlines);
out << optionalBlankLine ()
<< view.render (filtered, sequence)
<< optionalBlankLine ();
// Print the number of rendered tasks
if (context.verbose ("affected"))
{
out << (filtered.size () == 1
? STRING_CMD_CUSTOM_COUNT
: format (STRING_CMD_CUSTOM_COUNTN, filtered.size ()));
if (maxrows && maxrows < (int)filtered.size ())
out << ", " << format (STRING_CMD_CUSTOM_SHOWN, maxrows);
if (maxlines && maxlines < (int)filtered.size ())
out << ", "
<< format (STRING_CMD_CUSTOM_TRUNCATED, maxlines - table_header);
out << "\n";
}
}
else
{
context.footnote (STRING_FEEDBACK_NO_MATCH);
rc = 1;
}
feedback_backlog ();
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
void CmdCustom::validateReportColumns (std::vector <std::string>& columns)
{
std::vector <std::string>::iterator i;
for (i = columns.begin (); i != columns.end (); ++i)
legacyColumnMap (*i);
}
////////////////////////////////////////////////////////////////////////////////
void CmdCustom::validateSortColumns (std::vector <std::string>& columns)
{
std::vector <std::string>::iterator i;
for (i = columns.begin (); i != columns.end (); ++i)
legacySortColumnMap (*i);
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdCustom<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <sstream>
#include <map>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <Context.h>
#include <Filter.h>
#include <Lexer.h>
#include <ViewTask.h>
#include <i18n.h>
#include <text.h>
#include <main.h>
#include <CmdCustom.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdCustom::CmdCustom (
const std::string& k,
const std::string& u,
const std::string& d)
{
_keyword = k;
_usage = u;
_description = d;
_read_only = true;
_displays_id = true;
}
////////////////////////////////////////////////////////////////////////////////
int CmdCustom::execute (std::string& output)
{
int rc = 0;
// Load report configuration.
std::string reportColumns = context.config.get ("report." + _keyword + ".columns");
std::string reportLabels = context.config.get ("report." + _keyword + ".labels");
std::string reportSort = context.config.get ("report." + _keyword + ".sort");
std::string reportFilter = context.config.get ("report." + _keyword + ".filter");
if (reportFilter != "")
reportFilter = "( " + reportFilter + " )";
std::vector <std::string> columns;
split (columns, reportColumns, ',');
validateReportColumns (columns);
std::vector <std::string> labels;
split (labels, reportLabels, ',');
if (columns.size () != labels.size () && labels.size () != 0)
throw format (STRING_CMD_CUSTOM_MISMATCH, _keyword);
std::vector <std::string> sortOrder;
split (sortOrder, reportSort, ',');
validateSortColumns (sortOrder);
// Prepend the argument list with those from the report filter.
std::string lexeme;
Lexer::Type type;
Lexer lex (reportFilter);
lex.ambiguity (false);
while (lex.token (lexeme, type))
context.cli.add (lexeme);
// Reparse after tree change.
context.cli.analyze ();
// Apply filter.
handleRecurrence ();
Filter filter;
std::vector <Task> filtered;
filter.subset (filtered);
// Sort the tasks.
std::vector <int> sequence;
for (unsigned int i = 0; i < filtered.size (); ++i)
sequence.push_back (i);
sort_tasks (filtered, sequence, reportSort);
// Configure the view.
ViewTask view;
view.width (context.getWidth ());
view.leftMargin (context.config.getInteger ("indent.report"));
view.extraPadding (context.config.getInteger ("row.padding"));
view.intraPadding (context.config.getInteger ("column.padding"));
Color label (context.config.get ("color.label"));
view.colorHeader (label);
Color label_sort (context.config.get ("color.label.sort"));
view.colorSortHeader (label_sort);
Color alternate (context.config.get ("color.alternate"));
view.colorOdd (alternate);
view.intraColorOdd (alternate);
// Capture columns that are sorted.
std::vector <std::string> sortColumns;
// Add the break columns, if any.
std::vector <std::string>::iterator so;
for (so = sortOrder.begin (); so != sortOrder.end (); ++so)
{
std::string name;
bool ascending;
bool breakIndicator;
context.decomposeSortField (*so, name, ascending, breakIndicator);
if (breakIndicator)
view.addBreak (name);
sortColumns.push_back (name);
}
// Add the columns and labels.
for (unsigned int i = 0; i < columns.size (); ++i)
{
Column* c = Column::factory (columns[i], _keyword);
if (i < labels.size ())
c->setLabel (labels[i]);
bool sort = std::find (sortColumns.begin (), sortColumns.end (), c->name ()) != sortColumns.end ()
? true
: false;
view.add (c, sort);
}
// How many lines taken up by table header?
int table_header = 0;
if (context.verbose ("label"))
{
if (context.color () && context.config.getBoolean ("fontunderline"))
table_header = 1; // Underlining doesn't use extra line.
else
table_header = 2; // Dashes use an extra line.
}
// Report output can be limited by rows or lines.
int maxrows = 0;
int maxlines = 0;
context.getLimits (maxrows, maxlines);
// Adjust for fluff in the output.
if (maxlines)
maxlines -= table_header
+ (context.verbose ("blank") ? 1 : 0)
+ (context.verbose ("footnote") ? context.footnotes.size () : 0)
+ (context.verbose ("affected") ? 1 : 0)
+ context.config.getInteger ("reserved.lines"); // For prompt, etc.
// Render.
std::stringstream out;
if (filtered.size ())
{
view.truncateRows (maxrows);
view.truncateLines (maxlines);
out << optionalBlankLine ()
<< view.render (filtered, sequence)
<< optionalBlankLine ();
// Print the number of rendered tasks
if (context.verbose ("affected"))
{
out << (filtered.size () == 1
? STRING_CMD_CUSTOM_COUNT
: format (STRING_CMD_CUSTOM_COUNTN, filtered.size ()));
if (maxrows && maxrows < (int)filtered.size ())
out << ", " << format (STRING_CMD_CUSTOM_SHOWN, maxrows);
if (maxlines && maxlines < (int)filtered.size ())
out << ", "
<< format (STRING_CMD_CUSTOM_TRUNCATED, maxlines - table_header);
out << "\n";
}
}
else
{
context.footnote (STRING_FEEDBACK_NO_MATCH);
rc = 1;
}
feedback_backlog ();
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
void CmdCustom::validateReportColumns (std::vector <std::string>& columns)
{
std::vector <std::string>::iterator i;
for (i = columns.begin (); i != columns.end (); ++i)
legacyColumnMap (*i);
}
////////////////////////////////////////////////////////////////////////////////
void CmdCustom::validateSortColumns (std::vector <std::string>& columns)
{
std::vector <std::string>::iterator i;
for (i = columns.begin (); i != columns.end (); ++i)
legacySortColumnMap (*i);
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "InGame.h"
#include <sstream>
InGame::InGame(Configuration& newConfig, std::unique_ptr<StartInfo> startInfo) :
config(newConfig)
{
loadGame(startInfo);
}
InGame::~InGame()
{
delete interfacePtr;
delete networkPtr;
delete systemPtr;
}
void InGame::run()
{
sf::RenderWindow& window = config.window;
window.setFramerateLimit(60);
while (window.isOpen())
{
//input & update phase
systemPtr->updateQuadTree();
networkPtr->update();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if(event.type == sf::Event::KeyPressed)
{
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
systemPtr->interact();
}
interfacePtr->updateGUI(event);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::left);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "left";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::right);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "right";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::down);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "down";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::up);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "up";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
config.cursor.update();
//rendering phase
window.clear();
interfacePtr->draw();
//window.draw(config.cursor);
window.display();
}
}
void InGame::loadGame(std::unique_ptr<StartInfo>& startInfo)
{
//graphics in loading screen
sf::RenderWindow& window = config.window;
tgui::Gui gui;
gui.setWindow(window);
gui.setFont(tgui::Font(config.fontMan.get("Carlito-Bold.ttf")));
tgui::Picture::Ptr background = std::make_shared<tgui::Picture>();
background->setTexture(config.texMan.get("Book.png"));
background->setSize(gui.getSize());
gui.add(background);
tgui::ProgressBar::Ptr progressBar = std::make_shared<tgui::ProgressBar>();
gui.add(progressBar);
progressBar->setPosition(50, 700);
progressBar->setSize(930, 20);
progressBar->setMinimum(0);
progressBar->setMaximum(100);
progressBar->setText("loading...0%");
unsigned int percent = 0;
tgui::Panel::Ptr panel = std::make_shared<tgui::Panel>();
gui.add(panel);
panel->setSize(820, 200);
panel->setPosition(100, 450);
panel->setBackgroundColor(tgui::Color(192, 192, 192, 150));
tgui::Label::Ptr tips = std::make_shared<tgui::Label>();
panel->add(tips);
tips->setPosition(20, 20);
tips->setTextSize(24);
tips->setText("This is testing. Click cross button to leave.");
//*************************************************************************
//the render loop
bool loading_complete = false; //leave the loop when loading completed
Connection* temp_networkPtr = new Connection;
if (!temp_networkPtr)
{
throw "Failed to create network module!";
}
while (window.isOpen() && !loading_complete)
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
gui.handleEvent(event);
}
config.cursor.update();
//if still loading, update percent
if (percent < 99)
{
if (clock.getElapsedTime() > sf::seconds(0.05))
{
percent++;
std::stringstream ss;
ss << percent;
progressBar->setText(sf::String("loading...") + sf::String(ss.str()) + sf::String("%"));
progressBar->setValue(percent);
clock.restart();
}
}
else //else, client: send "ready" signal to server for every 5s; server: start anyway
{
progressBar->setText(sf::String("waiting for server..."));
loading_complete = waitForStart(startInfo, temp_networkPtr);
}
window.clear();
gui.draw();
window.draw(config.cursor);
window.display();
}
delete temp_networkPtr;
//*************************************************************************
//if it is server, start server system...TBD
systemPtr = new Gameplay::GameSystem(config, startInfo);
if (startInfo->type == StartInfo::TYPE::Server)
{
//systemPtr = new Gameplay::ServerSystem(config);
}
else //else it is client, start client system
{
//systemPtr = new Gameplay::ClientSystem();
}
//create network and interface which is pointing to the game system
networkPtr = new Gameplay::GameNetwork(systemPtr, startInfo);
systemPtr->setNetworkPtr(networkPtr);
interfacePtr = new Gameplay::GameInterface(systemPtr);
systemPtr->setInterfacePtr(interfacePtr);
if (startInfo->type == StartInfo::TYPE::Server)
{
//send ready signal to every player
//...
}
else //if it is a client
{
//wait for server's signal
}
}
bool InGame::waitForStart(std::unique_ptr<StartInfo>& startInfoPtr, Connection * connectionPtr)
{
if (startInfoPtr->type == StartInfo::TYPE::Server)
{
return true;
}
else
{
//if recevied somthing, if that's from server and the signal if "start", return true
if (!connectionPtr->empty())
{
Package& package = connectionPtr->front();
std::string signal;
package.packet >> signal;
if (package.ip == startInfoPtr->serverIP && signal == "start")
{
connectionPtr->pop();
return true;
}
}
else //else, send "ready" signal to server for every 2s
{
if (clock.getElapsedTime() > sf::seconds(2))
{
sf::Packet packet;
packet << "ready";
connectionPtr->send(startInfoPtr->serverIP, packet);
}
}
}
return false;
}
<commit_msg>comment the loading bar code for smoother testing<commit_after>#include "InGame.h"
#include <sstream>
InGame::InGame(Configuration& newConfig, std::unique_ptr<StartInfo> startInfo) :
config(newConfig)
{
loadGame(startInfo);
}
InGame::~InGame()
{
delete interfacePtr;
delete networkPtr;
delete systemPtr;
}
void InGame::run()
{
sf::RenderWindow& window = config.window;
window.setFramerateLimit(60);
while (window.isOpen())
{
//input & update phase
systemPtr->updateQuadTree();
networkPtr->update();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if(event.type == sf::Event::KeyPressed)
{
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
systemPtr->interact();
}
interfacePtr->updateGUI(event);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::left);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "left";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::right);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "right";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::down);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "down";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up))
{
systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::up);
if (networkPtr->getServerIP() != sf::IpAddress::None)
{
sf::Packet packet;
packet << "move";
packet << "up";
networkPtr->send(networkPtr->getServerIP(), packet);
}
}
config.cursor.update();
//rendering phase
window.clear();
interfacePtr->draw();
//window.draw(config.cursor);
window.display();
}
}
void InGame::loadGame(std::unique_ptr<StartInfo>& startInfo)
{
//graphics in loading screen
sf::RenderWindow& window = config.window;
tgui::Gui gui;
gui.setWindow(window);
gui.setFont(tgui::Font(config.fontMan.get("Carlito-Bold.ttf")));
tgui::Picture::Ptr background = std::make_shared<tgui::Picture>();
background->setTexture(config.texMan.get("Book.png"));
background->setSize(gui.getSize());
gui.add(background);
tgui::ProgressBar::Ptr progressBar = std::make_shared<tgui::ProgressBar>();
gui.add(progressBar);
progressBar->setPosition(50, 700);
progressBar->setSize(930, 20);
progressBar->setMinimum(0);
progressBar->setMaximum(100);
progressBar->setText("loading...0%");
unsigned int percent = 0;
tgui::Panel::Ptr panel = std::make_shared<tgui::Panel>();
gui.add(panel);
panel->setSize(820, 200);
panel->setPosition(100, 450);
panel->setBackgroundColor(tgui::Color(192, 192, 192, 150));
tgui::Label::Ptr tips = std::make_shared<tgui::Label>();
panel->add(tips);
tips->setPosition(20, 20);
tips->setTextSize(24);
tips->setText("This is testing. Click cross button to leave.");
//*************************************************************************
//the render loop
bool loading_complete = false; //leave the loop when loading completed
Connection* temp_networkPtr = new Connection;
if (!temp_networkPtr)
{
throw "Failed to create network module!";
}
while (window.isOpen() && !loading_complete)
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
gui.handleEvent(event);
}
config.cursor.update();
//if still loading, update percent
if (percent < 99)
{
/* Uncomment if the game is finished
if (clock.getElapsedTime() > sf::seconds(0.05))
{
percent++;
std::stringstream ss;
ss << percent;
progressBar->setText(sf::String("loading...") + sf::String(ss.str()) + sf::String("%"));
progressBar->setValue(percent);
clock.restart();
}
*/
}
else //else, client: send "ready" signal to server for every 5s; server: start anyway
{
progressBar->setText(sf::String("waiting for server..."));
loading_complete = waitForStart(startInfo, temp_networkPtr);
}
window.clear();
gui.draw();
window.draw(config.cursor);
window.display();
}
delete temp_networkPtr;
//*************************************************************************
//if it is server, start server system...TBD
systemPtr = new Gameplay::GameSystem(config, startInfo);
if (startInfo->type == StartInfo::TYPE::Server)
{
//systemPtr = new Gameplay::ServerSystem(config);
}
else //else it is client, start client system
{
//systemPtr = new Gameplay::ClientSystem();
}
//create network and interface which is pointing to the game system
networkPtr = new Gameplay::GameNetwork(systemPtr, startInfo);
systemPtr->setNetworkPtr(networkPtr);
interfacePtr = new Gameplay::GameInterface(systemPtr);
systemPtr->setInterfacePtr(interfacePtr);
if (startInfo->type == StartInfo::TYPE::Server)
{
//send ready signal to every player
//...
}
else //if it is a client
{
//wait for server's signal
}
}
bool InGame::waitForStart(std::unique_ptr<StartInfo>& startInfoPtr, Connection * connectionPtr)
{
if (startInfoPtr->type == StartInfo::TYPE::Server)
{
return true;
}
else
{
//if recevied somthing, if that's from server and the signal if "start", return true
if (!connectionPtr->empty())
{
Package& package = connectionPtr->front();
std::string signal;
package.packet >> signal;
if (package.ip == startInfoPtr->serverIP && signal == "start")
{
connectionPtr->pop();
return true;
}
}
else //else, send "ready" signal to server for every 2s
{
if (clock.getElapsedTime() > sf::seconds(2))
{
sf::Packet packet;
packet << "ready";
connectionPtr->send(startInfoPtr->serverIP, packet);
}
}
}
return false;
}
<|endoftext|> |
<commit_before>#include <docset.hpp>
#include <utility>
namespace docset
{
// Error
error::error(const char *text) throw()
: std::runtime_error(text)
{}
// Docset
doc_set::doc_set(const char *dirname)
: basedir_(dirname)
{
init(dirname);
}
doc_set::doc_set(std::string dirname)
: basedir_(std::move(dirname))
{
init(dirname.c_str());
}
std::size_t doc_set::count() const
{
return ::docset_count(docset_.get());
}
const char *doc_set::name() const
{
return ::docset_name(docset_.get());
}
iterator doc_set::begin() const
{
return iterator(::docset_list_entries(docset_.get()));
}
entry_range doc_set::find(const char *query) const
{
return entry_range(docset_.get(), query);
}
entry_range doc_set::find(std::string query) const
{
return entry_range(docset_.get(), std::move(query));
}
void doc_set::init(const char *dirname)
{
::DocSet *ds;
::DocSetError err = ::docset_try_open(&ds, dirname);
if (err != ::DOCSET_OK) {
throw error(::docset_error_string(err));
}
docset_ = std::shared_ptr<::DocSet>(ds, ::docset_close);
}
// Entry
bool entry::operator==(const entry &rhs) const
{
return name_ == rhs.name_
&& path_ == rhs.path_
&& canonical_type_ == rhs.canonical_type_;
}
void entry::assign_raw_entry(::DocSetEntry *e)
{
id_ = ::docset_entry_id(e);
name_.assign(::docset_entry_name(e));
path_.assign(::docset_entry_path(e));
canonical_type_ = ::docset_entry_type(e);
}
// Iterator
iterator::iterator(DocSetCursor *cursor)
: cursor_(cursor, ::docset_cursor_dispose)
{
++(*this);
}
iterator &iterator::operator++()
{
if (::docset_cursor_step(cursor_.get())) {
::DocSetEntry *e = docset_cursor_entry(cursor_.get());
entry_.assign_raw_entry(e);
} else {
cursor_.reset();
}
return *this;
}
bool iterator::operator==(const iterator &rhs) const
{
if (rhs.cursor_.get() == nullptr) {
return cursor_.get() == nullptr;
}
return cursor_ == rhs.cursor_
&& entry_ == rhs.entry_;
}
// Entry range
entry_range::entry_range(::DocSet *docset, std::string query)
: docset_(docset)
, query_(std::move(query))
{}
iterator entry_range::begin() const
{
return iterator(::docset_find(docset_, query_.c_str()));
}
}
<commit_msg>Fix bug in doc_set constructor<commit_after>#include <docset.hpp>
#include <utility>
namespace docset
{
// Error
error::error(const char *text) throw()
: std::runtime_error(text)
{}
// Docset
doc_set::doc_set(const char *dirname)
: doc_set(std::string(dirname))
{}
doc_set::doc_set(std::string dirname)
: basedir_(std::move(dirname))
{
init(basedir_.c_str());
}
std::size_t doc_set::count() const
{
return ::docset_count(docset_.get());
}
const char *doc_set::name() const
{
return ::docset_name(docset_.get());
}
iterator doc_set::begin() const
{
return iterator(::docset_list_entries(docset_.get()));
}
entry_range doc_set::find(const char *query) const
{
return entry_range(docset_.get(), query);
}
entry_range doc_set::find(std::string query) const
{
return entry_range(docset_.get(), std::move(query));
}
void doc_set::init(const char *dirname)
{
::DocSet *ds;
::DocSetError err = ::docset_try_open(&ds, dirname);
if (err != ::DOCSET_OK) {
throw error(::docset_error_string(err));
}
docset_ = std::shared_ptr<::DocSet>(ds, ::docset_close);
}
// Entry
bool entry::operator==(const entry &rhs) const
{
return name_ == rhs.name_
&& path_ == rhs.path_
&& canonical_type_ == rhs.canonical_type_;
}
void entry::assign_raw_entry(::DocSetEntry *e)
{
id_ = ::docset_entry_id(e);
name_.assign(::docset_entry_name(e));
path_.assign(::docset_entry_path(e));
canonical_type_ = ::docset_entry_type(e);
}
// Iterator
iterator::iterator(DocSetCursor *cursor)
: cursor_(cursor, ::docset_cursor_dispose)
{
++(*this);
}
iterator &iterator::operator++()
{
if (::docset_cursor_step(cursor_.get())) {
::DocSetEntry *e = docset_cursor_entry(cursor_.get());
entry_.assign_raw_entry(e);
} else {
cursor_.reset();
}
return *this;
}
bool iterator::operator==(const iterator &rhs) const
{
if (rhs.cursor_.get() == nullptr) {
return cursor_.get() == nullptr;
}
return cursor_ == rhs.cursor_
&& entry_ == rhs.entry_;
}
// Entry range
entry_range::entry_range(::DocSet *docset, std::string query)
: docset_(docset)
, query_(std::move(query))
{}
iterator entry_range::begin() const
{
return iterator(::docset_find(docset_, query_.c_str()));
}
}
<|endoftext|> |
<commit_before>#ifndef TMVA_SOFIE_ROPERATOR_BatchNormalization
#define TMVA_SOFIE_ROPERATOR_BatchNormalization
#include "SOFIE_common.hxx"
#include "ROperator.hxx"
#include "RModel.hxx"
#include <cmath>
#include <sstream>
namespace TMVA{
namespace Experimental{
namespace SOFIE{
template <typename T>
class ROperator_BatchNormalization final : public ROperator
{
private:
/* Attributes */
float fepsilon = 1e-05;
float fmomentum = 0.9;
std::size_t ftraining_mode = 0;
std::string fNX;
std::string fNScale;
std::string fNB;
std::string fNMean;
std::string fNVar;
std::string fNY;
std::vector<size_t> fShapeX;
std::vector<size_t> fShapeScale;
std::vector<size_t> fShapeB;
std::vector<size_t> fShapeMean;
std::vector<size_t> fShapeVar;
std::vector<size_t> fShapeY;
std::string fType;
public:
ROperator_BatchNormalization() = delete;
/* Constructor */
ROperator_BatchNormalization( float epsilon, float momentum, std::size_t training_mode,
std::string nameX, std::string nameScale, std::string nameB,
std::string nameMean, std::string nameVar, std::string nameY):
fepsilon(epsilon), fmomentum(momentum), ftraining_mode(training_mode),
fNX(UTILITY::Clean_name(nameX)), fNScale(UTILITY::Clean_name(nameScale)),
fNB(UTILITY::Clean_name(nameB)), fNMean(UTILITY::Clean_name(nameMean)),
fNVar(UTILITY::Clean_name(nameVar)), fNY(UTILITY::Clean_name(nameY))
{
if(std::is_same<T, float>::value){
fType = "float";
}
else{
throw
std::runtime_error("TMVA SOFIE Encountered unsupported type parsing a BatchNormalization operator");
}
}
std::vector<ETensorType> TypeInference(std::vector<ETensorType> input) {
ETensorType out = input[0];
return {out};
}
std::vector<std::vector<size_t>> ShapeInference(std::vector<std::vector<size_t>> input) {
if (input.size() != 5 ) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization Op Shape inference need 5 input tensors");
}
for(size_t i = 0; i < input.size(); i++) {
if (input[i].size() != 4) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization Op Shape inference only accept tensor with 4 dimensions");
}
}
auto ret = input;
return ret;
}
void Initialize(RModel& model){
if (!model.CheckIfTensorAlreadyExist(fNX)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNX + " fnx is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNScale)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNScale + " fns is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNB)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNB + " fnb is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNMean)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNMean + " fnm is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNVar)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNVar + " fnv is not found in model");
}
fShapeX = model.GetTensorShape(fNX);
if (fShapeX.size() != 4) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization Op input tensor " + fNX + " fnx is not of 4 dimensions");
}
fShapeScale = model.GetTensorShape(fNScale);
fShapeB = model.GetTensorShape(fNB);
fShapeMean = model.GetTensorShape(fNMean);
fShapeVar = model.GetTensorShape(fNVar);
fShapeY = fShapeX;
model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShapeY);
if (fShapeB.size() == 1) {
// Broadcast scale, bias, input_mean and input_var to shape_X
auto original_B = model.GetInitializedTensorData(fNB);
auto original_S = model.GetInitializedTensorData(fNScale);
auto original_M = model.GetInitializedTensorData(fNMean);
auto original_V = model.GetInitializedTensorData(fNVar);
size_t batchSize = fShapeX[0], channels = fShapeX[1], height = fShapeX[2], width = fShapeX[3];
size_t n = batchSize * channels * height * width;
if (fType == "float") {
float *original_bias = static_cast<float*>(original_B.get());
float *original_scale = static_cast<float*>(original_S.get());
float *original_mean = static_cast<float*>(original_M.get());
float *original_var = static_cast<float*>(original_V.get());
float *new_bias = new float[n];
float *new_scale = new float[n];
float *new_mean = new float[n];
float *new_var = new float[n];
size_t bs = 0, ch = 0, h = 0, w = 0;
for(ch=0; ch<channels; ch++){
for(h=0; h<height; h++){
for(w=0; w<width; w++){
new_bias[bs*channels*height*width + ch*height*width + h*width + w] = original_bias[ch];
new_scale[bs*channels*height*width + ch*height*width + h*width + w] = original_scale[ch];
new_mean[bs*channels*height*width + ch*height*width + h*width + w] = original_mean[ch];
new_var[bs*channels*height*width + ch*height*width + h*width + w] = original_var[ch];
}
}
}
size_t Batchoffset = channels*height*width;
for(bs = 1; bs<batchSize; bs++){
std::copy(new_bias, new_bias+Batchoffset, new_bias+(bs*Batchoffset));
std::copy(new_scale, new_scale+Batchoffset, new_scale+(bs*Batchoffset));
std::copy(new_mean, new_mean+Batchoffset, new_mean+(bs*Batchoffset));
std::copy(new_var, new_var+Batchoffset, new_var+(bs*Batchoffset));
}
//// new_var =1. / sqrt(input_var + fepsilon)
for(size_t i=0; i<n; i++){
new_var[i] = 1./sqrt(new_var[i] + fepsilon);
}
std::vector<size_t> new_bias_shape = {batchSize,channels,height,width};
std::shared_ptr<void> new_bias_ptr(new_bias, std::default_delete<float[]>());
std::shared_ptr<void> new_scale_ptr(new_scale, std::default_delete<float[]>());
std::shared_ptr<void> new_mean_ptr(new_mean, std::default_delete<float[]>());
std::shared_ptr<void> new_var_ptr(new_var, std::default_delete<float[]>());
model.UpdateInitializedTensor(fNB, model.GetTensorType(fNB), new_bias_shape, new_bias_ptr);
model.UpdateInitializedTensor(fNScale, model.GetTensorType(fNScale), new_bias_shape, new_scale_ptr);
model.UpdateInitializedTensor(fNMean, model.GetTensorType(fNMean), new_bias_shape, new_mean_ptr);
model.UpdateInitializedTensor(fNVar, model.GetTensorType(fNVar), new_bias_shape, new_var_ptr);
fShapeB = model.GetTensorShape(fNB);
fShapeScale = model.GetTensorShape(fNScale);
fShapeMean = model.GetTensorShape(fNMean);
fShapeVar = model.GetTensorShape(fNVar);
}
}
}
std::string Generate(std::string OpName){
OpName = "op_" + OpName;
if (fShapeX.empty()){
throw std::runtime_error("TMVA SOFIE Batch Normalization called to Generate without being initialized first");
}
std::stringstream out;
int length = 1;
for(auto& i: fShapeX){
length *= i;
}
//// Batch Norm op
size_t batchSize = fShapeX[0], channels = fShapeX[1], height = fShapeX[2], width = fShapeX[3];
size_t n = batchSize * channels * height * width;
//// copy X into Y
out << "\t" << "const int N ="<<batchSize * channels * height * width<<";\n";
out << "\t" << "const int "<<OpName<< "_incx = 1;\n";
out << "\t" << "const int "<<OpName<< "_incy = 1;\n";
out << "\t" << "BLAS::scopy_(&N, " << "tensor_" << fNX <<", &" << OpName << "_incx," << "tensor_" << fNY <<", &" << OpName << "_incy);\n\n";
//// blas saxpy (Y = -Bmean + Y)
out << "\t" << "float "<<OpName<< "_alpha = -1;\n";
out << "\t" << "BLAS::saxpy_(&N, &" << OpName << "_alpha, " << "tensor_" << fNMean << ", &" << OpName << "_incx," << "tensor_" << fNY <<", &" << OpName << "_incy);\n\n";
//// Y *= scale*var
out << "\t" << "for (size_t i = 0; i < " << n << "; i++) {\n";
out << "\t" << "\t" << "tensor_" << fNY << "[i] *= tensor_" << fNScale << "[i] * tensor_" << fNVar << "[i]; \n";
out << "\t" << "}\n";
//// blas saxpy (Y = Bbias + Y)
out << "\t" <<OpName<< "_alpha = 1;\n";
out << "\t" << "BLAS::saxpy_(&N, &" << OpName << "_alpha, " << "tensor_" << fNB << ", &" << OpName << "_incx, " << "tensor_" << fNY <<", &" << OpName << "_incy);\n\n";
// std::cout<<out;
return out.str();
}
};
}//SOFIE
}//Experimental
}//TMVA
#endif //TMVA_SOFIE_ROPERATOR_BatchNormalization<commit_msg>[TMVA][SOFIE] Add support for batch normalization with input tensor dimensions less than 4. For example this is the case when using models created with torch BatchNorm1d (Batch normalization for dense layers)<commit_after>#ifndef TMVA_SOFIE_ROPERATOR_BatchNormalization
#define TMVA_SOFIE_ROPERATOR_BatchNormalization
#include "SOFIE_common.hxx"
#include "ROperator.hxx"
#include "RModel.hxx"
#include <cmath>
#include <sstream>
namespace TMVA{
namespace Experimental{
namespace SOFIE{
template <typename T>
class ROperator_BatchNormalization final : public ROperator
{
private:
/* Attributes */
float fepsilon = 1e-05;
float fmomentum = 0.9;
std::size_t ftraining_mode = 0;
std::string fNX;
std::string fNScale;
std::string fNB;
std::string fNMean;
std::string fNVar;
std::string fNY;
std::vector<size_t> fShapeX;
std::vector<size_t> fShapeScale;
std::vector<size_t> fShapeB;
std::vector<size_t> fShapeMean;
std::vector<size_t> fShapeVar;
std::vector<size_t> fShapeY;
std::string fType;
public:
ROperator_BatchNormalization() = delete;
/* Constructor */
ROperator_BatchNormalization( float epsilon, float momentum, std::size_t training_mode,
std::string nameX, std::string nameScale, std::string nameB,
std::string nameMean, std::string nameVar, std::string nameY):
fepsilon(epsilon), fmomentum(momentum), ftraining_mode(training_mode),
fNX(UTILITY::Clean_name(nameX)), fNScale(UTILITY::Clean_name(nameScale)),
fNB(UTILITY::Clean_name(nameB)), fNMean(UTILITY::Clean_name(nameMean)),
fNVar(UTILITY::Clean_name(nameVar)), fNY(UTILITY::Clean_name(nameY))
{
if(std::is_same<T, float>::value){
fType = "float";
}
else{
throw
std::runtime_error("TMVA SOFIE Encountered unsupported type parsing a BatchNormalization operator");
}
}
std::vector<ETensorType> TypeInference(std::vector<ETensorType> input) {
ETensorType out = input[0];
return {out};
}
std::vector<std::vector<size_t>> ShapeInference(std::vector<std::vector<size_t>> input) {
if (input.size() != 5 ) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization Op Shape inference need 5 input tensors");
}
for(size_t i = 0; i < input.size(); i++) {
if (input[i].size() != 4) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization Op Shape inference only accept tensor with 4 dimensions");
}
}
auto ret = input;
return ret;
}
void Initialize(RModel& model){
if (!model.CheckIfTensorAlreadyExist(fNX)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNX + " fnx is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNScale)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNScale + " fns is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNB)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNB + " fnb is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNMean)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNMean + " fnm is not found in model");
}
if (!model.CheckIfTensorAlreadyExist(fNVar)) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization op Input Tensor " + fNVar + " fnv is not found in model");
}
fShapeX = model.GetTensorShape(fNX);
if (fShapeX.size() < 4)
fShapeX.resize(4, 1);
if (fShapeX.size() != 4) {
throw
std::runtime_error("TMVA SOFIE BatchNormalization Op input tensor " + fNX + " fnx is not of 4 dimensions");
}
fShapeScale = model.GetTensorShape(fNScale);
fShapeB = model.GetTensorShape(fNB);
fShapeMean = model.GetTensorShape(fNMean);
fShapeVar = model.GetTensorShape(fNVar);
fShapeY = fShapeX;
model.AddIntermediateTensor(fNY, model.GetTensorType(fNX), fShapeY);
if (fShapeB.size() == 1) {
// Broadcast scale, bias, input_mean and input_var to shape_X
auto original_B = model.GetInitializedTensorData(fNB);
auto original_S = model.GetInitializedTensorData(fNScale);
auto original_M = model.GetInitializedTensorData(fNMean);
auto original_V = model.GetInitializedTensorData(fNVar);
size_t batchSize = fShapeX[0], channels = fShapeX[1], height = fShapeX[2], width = fShapeX[3];
size_t n = batchSize * channels * height * width;
if (fType == "float") {
float *original_bias = static_cast<float*>(original_B.get());
float *original_scale = static_cast<float*>(original_S.get());
float *original_mean = static_cast<float*>(original_M.get());
float *original_var = static_cast<float*>(original_V.get());
float *new_bias = new float[n];
float *new_scale = new float[n];
float *new_mean = new float[n];
float *new_var = new float[n];
size_t bs = 0, ch = 0, h = 0, w = 0;
for(ch=0; ch<channels; ch++){
for(h=0; h<height; h++){
for(w=0; w<width; w++){
new_bias[bs*channels*height*width + ch*height*width + h*width + w] = original_bias[ch];
new_scale[bs*channels*height*width + ch*height*width + h*width + w] = original_scale[ch];
new_mean[bs*channels*height*width + ch*height*width + h*width + w] = original_mean[ch];
new_var[bs*channels*height*width + ch*height*width + h*width + w] = original_var[ch];
}
}
}
size_t Batchoffset = channels*height*width;
for(bs = 1; bs<batchSize; bs++){
std::copy(new_bias, new_bias+Batchoffset, new_bias+(bs*Batchoffset));
std::copy(new_scale, new_scale+Batchoffset, new_scale+(bs*Batchoffset));
std::copy(new_mean, new_mean+Batchoffset, new_mean+(bs*Batchoffset));
std::copy(new_var, new_var+Batchoffset, new_var+(bs*Batchoffset));
}
//// new_var =1. / sqrt(input_var + fepsilon)
for(size_t i=0; i<n; i++){
new_var[i] = 1./sqrt(new_var[i] + fepsilon);
}
std::vector<size_t> new_bias_shape = {batchSize,channels,height,width};
std::shared_ptr<void> new_bias_ptr(new_bias, std::default_delete<float[]>());
std::shared_ptr<void> new_scale_ptr(new_scale, std::default_delete<float[]>());
std::shared_ptr<void> new_mean_ptr(new_mean, std::default_delete<float[]>());
std::shared_ptr<void> new_var_ptr(new_var, std::default_delete<float[]>());
model.UpdateInitializedTensor(fNB, model.GetTensorType(fNB), new_bias_shape, new_bias_ptr);
model.UpdateInitializedTensor(fNScale, model.GetTensorType(fNScale), new_bias_shape, new_scale_ptr);
model.UpdateInitializedTensor(fNMean, model.GetTensorType(fNMean), new_bias_shape, new_mean_ptr);
model.UpdateInitializedTensor(fNVar, model.GetTensorType(fNVar), new_bias_shape, new_var_ptr);
fShapeB = model.GetTensorShape(fNB);
fShapeScale = model.GetTensorShape(fNScale);
fShapeMean = model.GetTensorShape(fNMean);
fShapeVar = model.GetTensorShape(fNVar);
}
}
}
std::string Generate(std::string OpName){
OpName = "op_" + OpName;
if (fShapeX.empty()){
throw std::runtime_error("TMVA SOFIE Batch Normalization called to Generate without being initialized first");
}
std::stringstream out;
int length = 1;
for(auto& i: fShapeX){
length *= i;
}
//// Batch Norm op
size_t batchSize = fShapeX[0], channels = fShapeX[1], height = fShapeX[2], width = fShapeX[3];
size_t n = batchSize * channels * height * width;
//// copy X into Y
out << "\t" << "const int N ="<<batchSize * channels * height * width<<";\n";
out << "\t" << "const int "<<OpName<< "_incx = 1;\n";
out << "\t" << "const int "<<OpName<< "_incy = 1;\n";
out << "\t" << "BLAS::scopy_(&N, " << "tensor_" << fNX <<", &" << OpName << "_incx," << "tensor_" << fNY <<", &" << OpName << "_incy);\n\n";
//// blas saxpy (Y = -Bmean + Y)
out << "\t" << "float "<<OpName<< "_alpha = -1;\n";
out << "\t" << "BLAS::saxpy_(&N, &" << OpName << "_alpha, " << "tensor_" << fNMean << ", &" << OpName << "_incx," << "tensor_" << fNY <<", &" << OpName << "_incy);\n\n";
//// Y *= scale*var
out << "\t" << "for (size_t i = 0; i < " << n << "; i++) {\n";
out << "\t" << "\t" << "tensor_" << fNY << "[i] *= tensor_" << fNScale << "[i] * tensor_" << fNVar << "[i]; \n";
out << "\t" << "}\n";
//// blas saxpy (Y = Bbias + Y)
out << "\t" <<OpName<< "_alpha = 1;\n";
out << "\t" << "BLAS::saxpy_(&N, &" << OpName << "_alpha, " << "tensor_" << fNB << ", &" << OpName << "_incx, " << "tensor_" << fNY <<", &" << OpName << "_incy);\n\n";
// std::cout<<out;
return out.str();
}
};
}//SOFIE
}//Experimental
}//TMVA
#endif //TMVA_SOFIE_ROPERATOR_BatchNormalization<|endoftext|> |
<commit_before>/*******************************************************************
This file is part of KNotes.
Copyright (c) 2004, Bo Thorsen <bo@klaralvdalens-datakonsult.se>
2004, Michael Brade <brade@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*******************************************************************/
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <libkcal/icalformat.h>
#include "knotes/resourcelocal.h"
#include "knotes/resourcemanager.h"
ResourceLocal::ResourceLocal( const KConfig* config )
: ResourceNotes( config )
{
if ( !config )
setType( "file" );
}
ResourceLocal::~ResourceLocal()
{
}
bool ResourceLocal::load()
{
mCalendar.load( KGlobal::dirs()->saveLocation( "data" ) + "knotes/notes.ics" );
KCal::Journal::List notes = mCalendar.journals();
KCal::Journal::List::ConstIterator it;
for ( it = notes.begin(); it != notes.end(); ++it )
manager()->registerNote( this, *it );
return true;
}
bool ResourceLocal::save()
{
QString file = KGlobal::dirs()->saveLocation( "data" ) + "knotes/notes.ics";
if ( !mCalendar.save( file, new KCal::ICalFormat() ) )
{
KMessageBox::error( 0,
i18n("<qt>Unable to save the notes to <b>%1</b>. "
"Check that there is sufficient disk space."
"<br>There should be a backup in the same directory "
"though.</qt>").arg( file ) );
return false;
}
return true;
}
bool ResourceLocal::addNote( KCal::Journal* journal )
{
mCalendar.addJournal( journal );
return true;
}
bool ResourceLocal::deleteNote( KCal::Journal* journal )
{
mCalendar.deleteJournal( journal );
return true;
}
<commit_msg>Make sure that $KDEHOME/share/apps/knotes gets created when saving a note.<commit_after>/*******************************************************************
This file is part of KNotes.
Copyright (c) 2004, Bo Thorsen <bo@klaralvdalens-datakonsult.se>
2004, Michael Brade <brade@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*******************************************************************/
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <libkcal/icalformat.h>
#include "knotes/resourcelocal.h"
#include "knotes/resourcemanager.h"
ResourceLocal::ResourceLocal( const KConfig* config )
: ResourceNotes( config )
{
if ( !config )
setType( "file" );
}
ResourceLocal::~ResourceLocal()
{
}
bool ResourceLocal::load()
{
mCalendar.load( KGlobal::dirs()->saveLocation( "data" ) + "knotes/notes.ics" );
KCal::Journal::List notes = mCalendar.journals();
KCal::Journal::List::ConstIterator it;
for ( it = notes.begin(); it != notes.end(); ++it )
manager()->registerNote( this, *it );
return true;
}
bool ResourceLocal::save()
{
QString file = KGlobal::dirs()->saveLocation( "data", "knotes" ) + "notes.ics";
if ( !mCalendar.save( file, new KCal::ICalFormat() ) )
{
KMessageBox::error( 0,
i18n("<qt>Unable to save the notes to <b>%1</b>. "
"Check that there is sufficient disk space."
"<br>There should be a backup in the same directory "
"though.</qt>").arg( file ) );
return false;
}
return true;
}
bool ResourceLocal::addNote( KCal::Journal* journal )
{
mCalendar.addJournal( journal );
return true;
}
bool ResourceLocal::deleteNote( KCal::Journal* journal )
{
mCalendar.deleteJournal( journal );
return true;
}
<|endoftext|> |
<commit_before>#include "bart_builder.h"
#include <unordered_map>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_raviart_thomas.h>
template <int dim>
BARTBuilder<dim>::BARTBuilder (dealii::ParameterHandler &prm) {
SetParams (prm);
}
template <int dim>
BARTBuilder<dim>::~BARTBuilder () {
}
template <int dim>
void BARTBuilder<dim>::SetParams (dealii::ParameterHandler &prm) {
do_nda_ = prm.get_bool ("do nda");
p_order_ = prm.get_integer("finite element polynomial degree");
ho_discretization_ = prm.get ("ho spatial discretization");
nda_discretization_ = prm.get ("nda spatial discretization");
}
template <int dim>
void BARTBuilder<dim>::BuildFESpaces (
std::vector<dealii::FiniteElement<dim, dim>*> &fe_ptrs) {
fe_ptrs.resize (do_nda_ ? 2 : 1);
std::unordered_map<std::string, unsigned int> discretization_ind = {
{"cfem", 0}, {"dfem", 1}, {"cmfd", 2}, {"rtk", 3}};
switch (discretization_ind[ho_discretization_]) {
case 0:
fe_ptrs.front () = new dealii::FE_Q<dim> (p_order_);
break;
case 1:
fe_ptrs.front () = new dealii::FE_DGQ<dim> (p_order_);
break;
default:
AssertThrow (false,
dealii::ExcMessage("Invalid HO discretization name"));
break;
}
if (do_nda_) {
switch (discretization_ind[nda_discretization_]) {
case 0:
fe_ptrs.back () = new dealii::FE_Q<dim> (p_order_);
break;
case 1:
fe_ptrs.back () = new dealii::FE_DGQ<dim> (p_order_);
break;
case 2:
fe_ptrs.back () = new dealii::FE_DGQ<dim> (0);
break;
case 3:
fe_ptrs.back () = new dealii::FE_RaviartThomas<dim> (p_order_);
break;
default:
AssertThrow (false,
dealii::ExcMessage("Invalid NDA discretization name"));
break;
}
}
}
template class BARTBuilder<1>;
template class BARTBuilder<2>;
template class BARTBuilder<3>;
<commit_msg>Style addressed #63<commit_after>#include "bart_builder.h"
#include <unordered_map>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_raviart_thomas.h>
template <int dim>
BARTBuilder<dim>::BARTBuilder (dealii::ParameterHandler &prm) {
SetParams (prm);
}
template <int dim>
BARTBuilder<dim>::~BARTBuilder () {}
template <int dim>
void BARTBuilder<dim>::SetParams (dealii::ParameterHandler &prm) {
do_nda_ = prm.get_bool ("do nda");
p_order_ = prm.get_integer("finite element polynomial degree");
ho_discretization_ = prm.get ("ho spatial discretization");
nda_discretization_ = prm.get ("nda spatial discretization");
}
template <int dim>
void BARTBuilder<dim>::BuildFESpaces (
std::vector<dealii::FiniteElement<dim, dim>*> &fe_ptrs) {
fe_ptrs.resize (do_nda_ ? 2 : 1);
std::unordered_map<std::string, unsigned int> discretization_ind = {
{"cfem", 0}, {"dfem", 1}, {"cmfd", 2}, {"rtk", 3}};
switch (discretization_ind[ho_discretization_]) {
case 0:
fe_ptrs.front () = new dealii::FE_Q<dim> (p_order_);
break;
case 1:
fe_ptrs.front () = new dealii::FE_DGQ<dim> (p_order_);
break;
default:
AssertThrow (false,
dealii::ExcMessage("Invalid HO discretization name"));
break;
}
if (do_nda_) {
switch (discretization_ind[nda_discretization_]) {
case 0:
fe_ptrs.back () = new dealii::FE_Q<dim> (p_order_);
break;
case 1:
fe_ptrs.back () = new dealii::FE_DGQ<dim> (p_order_);
break;
case 2:
fe_ptrs.back () = new dealii::FE_DGQ<dim> (0);
break;
case 3:
fe_ptrs.back () = new dealii::FE_RaviartThomas<dim> (p_order_);
break;
default:
AssertThrow (false,
dealii::ExcMessage("Invalid NDA discretization name"));
break;
}
}
}
template class BARTBuilder<1>;
template class BARTBuilder<2>;
template class BARTBuilder<3>;
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: unocontrolcontainer.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2003-03-27 17:02:55 $
*
* 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 _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
#define _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XUNOCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XUnoControlContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#include <toolkit/controls/unocontrol.hxx>
#include <toolkit/controls/unocontrolbase.hxx>
#include <toolkit/helper/macros.hxx>
#include <toolkit/helper/servicenames.hxx>
class UnoControlHolderList;
// ----------------------------------------------------
// class UnoControlContainer
// ----------------------------------------------------
class UnoControlContainer : public ::com::sun::star::awt::XUnoControlContainer,
public ::com::sun::star::awt::XControlContainer,
public ::com::sun::star::container::XContainer,
public UnoControlBase
{
private:
UnoControlHolderList* mpControls;
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > > maTabControllers;
ContainerListenerMultiplexer maCListeners;
protected:
void ImplActivateTabControllers();
public:
UnoControlContainer();
UnoControlContainer( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xPeer );
~UnoControlContainer();
::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { return UnoControl::queryInterface(rType); }
void SAL_CALL acquire() throw() { OWeakAggObject::acquire(); }
void SAL_CALL release() throw() { OWeakAggObject::release(); }
::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XTypeProvider
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XComponent
void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XEventListener
void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::container::XContainer
void SAL_CALL addContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL removeContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XControlContainer
void SAL_CALL setStatusText( const ::rtl::OUString& StatusText ) throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > > SAL_CALL getControls( ) throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > SAL_CALL getControl( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL addControl( const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL removeControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XUnoControlContainer
void SAL_CALL setTabControllers( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > >& TabControllers ) throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > > SAL_CALL getTabControllers( ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL addTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL removeTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XControl
void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& Toolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& Parent ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XWindow
void SAL_CALL setVisible( sal_Bool Visible ) throw(::com::sun::star::uno::RuntimeException);
DECLIMPL_SERVICEINFO_DERIVED( UnoControlContainer, UnoControlBase, szServiceName2_UnoControlContainer )
protected:
virtual void removingControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl );
virtual void addingControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl );
};
#endif // _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.336); FILE MERGED 2005/09/05 16:57:45 rt 1.7.336.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unocontrolcontainer.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:52:15 $
*
* 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 _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
#define _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XUNOCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XUnoControlContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#include <toolkit/controls/unocontrol.hxx>
#include <toolkit/controls/unocontrolbase.hxx>
#include <toolkit/helper/macros.hxx>
#include <toolkit/helper/servicenames.hxx>
class UnoControlHolderList;
// ----------------------------------------------------
// class UnoControlContainer
// ----------------------------------------------------
class UnoControlContainer : public ::com::sun::star::awt::XUnoControlContainer,
public ::com::sun::star::awt::XControlContainer,
public ::com::sun::star::container::XContainer,
public UnoControlBase
{
private:
UnoControlHolderList* mpControls;
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > > maTabControllers;
ContainerListenerMultiplexer maCListeners;
protected:
void ImplActivateTabControllers();
public:
UnoControlContainer();
UnoControlContainer( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xPeer );
~UnoControlContainer();
::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { return UnoControl::queryInterface(rType); }
void SAL_CALL acquire() throw() { OWeakAggObject::acquire(); }
void SAL_CALL release() throw() { OWeakAggObject::release(); }
::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XTypeProvider
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XComponent
void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XEventListener
void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::container::XContainer
void SAL_CALL addContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL removeContainerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XControlContainer
void SAL_CALL setStatusText( const ::rtl::OUString& StatusText ) throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > > SAL_CALL getControls( ) throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > SAL_CALL getControl( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL addControl( const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL removeControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& Control ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XUnoControlContainer
void SAL_CALL setTabControllers( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > >& TabControllers ) throw(::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController > > SAL_CALL getTabControllers( ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL addTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);
void SAL_CALL removeTabController( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTabController >& TabController ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XControl
void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& Toolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& Parent ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::awt::XWindow
void SAL_CALL setVisible( sal_Bool Visible ) throw(::com::sun::star::uno::RuntimeException);
DECLIMPL_SERVICEINFO_DERIVED( UnoControlContainer, UnoControlBase, szServiceName2_UnoControlContainer )
protected:
virtual void removingControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl );
virtual void addingControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl );
};
#endif // _TOOLKIT_CONTROLS_UNOCONTROLCONTAINER_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fileidentifierconverter.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:19:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucbhelper.hxx"
#ifndef _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
#include <ucbhelper/fileidentifierconverter.hxx>
#endif
#ifndef _COM_SUN_STAR_UCB_CONTENTPROVIDERINFO_HPP_
#include <com/sun/star/ucb/ContentProviderInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDERMANAGER_HPP_
#include <com/sun/star/ucb/XContentProviderManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XFILEIDENTIFIERCONVERTER_HPP_
#include <com/sun/star/ucb/XFileIdentifierConverter.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
using namespace com::sun;
using namespace com::sun::star;
namespace ucb {
//============================================================================
//
// getLocalFileURL
//
//============================================================================
rtl::OUString
getLocalFileURL(
uno::Reference< star::ucb::XContentProviderManager > const &)
SAL_THROW((com::sun::star::uno::RuntimeException))
{
// If there were more file systems than just "file:///" (e.g., the obsolete
// "vnd.sun.star.wfs:///"), this code should query all relevant UCPs for
// their com.sun.star.ucb.XFileIdentifierConverter.getFileProviderLocality
// and return the most local one:
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("file:///"));
}
//============================================================================
//
// getFileURLFromSystemPath
//
//============================================================================
rtl::OUString
getFileURLFromSystemPath(
uno::Reference< star::ucb::XContentProviderManager > const & rManager,
rtl::OUString const & rBaseURL,
rtl::OUString const & rSystemPath)
SAL_THROW((com::sun::star::uno::RuntimeException))
{
OSL_ASSERT(rManager.is());
uno::Reference< star::ucb::XFileIdentifierConverter >
xConverter(rManager->queryContentProvider(rBaseURL), uno::UNO_QUERY);
if (xConverter.is())
return xConverter->getFileURLFromSystemPath(rBaseURL, rSystemPath);
else
return rtl::OUString();
}
//============================================================================
//
// getSystemPathFromFileURL
//
//============================================================================
rtl::OUString
getSystemPathFromFileURL(
uno::Reference< star::ucb::XContentProviderManager > const & rManager,
rtl::OUString const & rURL)
SAL_THROW((com::sun::star::uno::RuntimeException))
{
OSL_ASSERT(rManager.is());
uno::Reference< star::ucb::XFileIdentifierConverter >
xConverter(rManager->queryContentProvider(rURL), uno::UNO_QUERY);
if (xConverter.is())
return xConverter->getSystemPathFromFileURL(rURL);
else
return rtl::OUString();
}
}
<commit_msg>INTEGRATION: CWS bgdlremove (1.7.28); FILE MERGED 2007/05/18 11:38:07 kso 1.7.28.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fileidentifierconverter.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:52:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucbhelper.hxx"
#ifndef _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
#include <ucbhelper/fileidentifierconverter.hxx>
#endif
#ifndef _COM_SUN_STAR_UCB_CONTENTPROVIDERINFO_HPP_
#include <com/sun/star/ucb/ContentProviderInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDERMANAGER_HPP_
#include <com/sun/star/ucb/XContentProviderManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XFILEIDENTIFIERCONVERTER_HPP_
#include <com/sun/star/ucb/XFileIdentifierConverter.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
using namespace com::sun::star;
namespace ucbhelper {
//============================================================================
//
// getLocalFileURL
//
//============================================================================
rtl::OUString
getLocalFileURL(
uno::Reference< ucb::XContentProviderManager > const &)
SAL_THROW((uno::RuntimeException))
{
// If there were more file systems than just "file:///" (e.g., the obsolete
// "vnd.sun.star.wfs:///"), this code should query all relevant UCPs for
// their com.sun.star.ucb.XFileIdentifierConverter.getFileProviderLocality
// and return the most local one:
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("file:///"));
}
//============================================================================
//
// getFileURLFromSystemPath
//
//============================================================================
rtl::OUString
getFileURLFromSystemPath(
uno::Reference< ucb::XContentProviderManager > const & rManager,
rtl::OUString const & rBaseURL,
rtl::OUString const & rSystemPath)
SAL_THROW((uno::RuntimeException))
{
OSL_ASSERT(rManager.is());
uno::Reference< ucb::XFileIdentifierConverter >
xConverter(rManager->queryContentProvider(rBaseURL), uno::UNO_QUERY);
if (xConverter.is())
return xConverter->getFileURLFromSystemPath(rBaseURL, rSystemPath);
else
return rtl::OUString();
}
//============================================================================
//
// getSystemPathFromFileURL
//
//============================================================================
rtl::OUString
getSystemPathFromFileURL(
uno::Reference< ucb::XContentProviderManager > const & rManager,
rtl::OUString const & rURL)
SAL_THROW((uno::RuntimeException))
{
OSL_ASSERT(rManager.is());
uno::Reference< ucb::XFileIdentifierConverter >
xConverter(rManager->queryContentProvider(rURL), uno::UNO_QUERY);
if (xConverter.is())
return xConverter->getSystemPathFromFileURL(rURL);
else
return rtl::OUString();
}
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// class interface header
#include "cURLManager.h"
// common implementation headers
#include "bzfio.h"
bool cURLManager::inited = false;
CURLM *cURLManager::multiHandle = NULL;
std::list<cURLManager*> cURLManager::cURLList;
cURLManager::cURLManager()
{
CURLcode result;
theData = NULL;
theLen = 0;
errorCode = CURLE_OK;
added = false;
if (!inited)
setup();
easyHandle = curl_easy_init();
if (!easyHandle) {
DEBUG1("Something wrong with CURL\n");
return;
}
#if LIBCURL_VERSION_NUM >= 0x070a00
result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_NOSIGNAL error: %d\n", result);
}
#endif
result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,
cURLManager::writeFunction);
if (result != CURLE_OK)
DEBUG1("CURLOPT_WRITEFUNCTION error: %d\n", result);
result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);
if (result != CURLE_OK)
DEBUG1("CURLOPT_FILE error: %d\n", result);
}
cURLManager::~cURLManager()
{
if (added)
removeHandle();
curl_easy_cleanup(easyHandle);
free(theData);
}
void cURLManager::setup()
{
CURLcode result;
DEBUG1("LIBCURL: %s\n", curl_version());
#if LIBCURL_VERSION_NUM >= 0x070a00
if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
#endif
multiHandle = curl_multi_init();
if (!multiHandle)
DEBUG1("Unexpected error creating multi handle from libcurl \n");
inited = true;
}
size_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,
void *stream)
{
int len = size * nmemb;
((cURLManager*)stream)->collectData((char*)ptr, len);
return len;
}
void cURLManager::setTimeout(long timeout)
{
CURLcode result;
result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_TIMEOUT error: %d\n", result);
}
}
void cURLManager::setNoBody(bool nobody)
{
CURLcode result;
result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_NOBODY error: %d\n", result);
}
}
void cURLManager::setURL(std::string url)
{
CURLcode result;
if (url == "")
result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);
else
result = curl_easy_setopt(easyHandle, CURLOPT_URL, url.c_str());
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_URL error: %d\n", result);
}
}
void cURLManager::addHandle()
{
CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);
if (result != CURLM_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
cURLList.push_back(this);
added = true;
}
void cURLManager::removeHandle()
{
if (!added)
return;
for (std::list<cURLManager*>::iterator i = cURLList.begin();
i != cURLList.end(); i++)
if (*i == this) {
cURLList.erase(i);
break;
}
CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);
if (result != CURLM_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
added = false;
}
void cURLManager::collectData(char* ptr, int &len)
{
unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);
if (!newData) {
DEBUG1("memory exhausted\n");
} else {
memcpy(newData + theLen, ptr, len);
theLen += len;
theData = newData;
}
}
int cURLManager::perform()
{
if (!inited)
setup();
int activeTransfers = 0;
CURLMcode result;
while (true) {
result = curl_multi_perform(multiHandle, &activeTransfers);
if (result != CURLM_CALL_MULTI_PERFORM)
break;
}
if (result != CURLM_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
int msgs_in_queue;
CURLMsg *pendingMsg;
CURL *easy;
while (true) {
pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);
if (!pendingMsg)
break;
easy = pendingMsg->easy_handle;
for (std::list<cURLManager*>::iterator i = cURLList.begin();
i != cURLList.end(); i++)
if ((*i)->easyHandle == easy) {
(*i)->infoComplete(pendingMsg->data.result);
break;
}
if (msgs_in_queue <= 0)
break;
}
return activeTransfers;
}
void cURLManager::infoComplete(CURLcode result)
{
if (result != CURLE_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
finalization((char *)theData, theLen, result == CURLE_OK);
free(theData);
removeHandle();
}
bool cURLManager::getFileTime(time_t &t)
{
long filetime;
CURLcode result;
result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);
if (result) {
DEBUG1("CURLINFO_FILETIME error: %d\n", result);
return false;
}
t = (time_t)filetime;
return true;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Avoid double free<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// class interface header
#include "cURLManager.h"
// common implementation headers
#include "bzfio.h"
bool cURLManager::inited = false;
CURLM *cURLManager::multiHandle = NULL;
std::list<cURLManager*> cURLManager::cURLList;
cURLManager::cURLManager()
{
CURLcode result;
theData = NULL;
theLen = 0;
errorCode = CURLE_OK;
added = false;
if (!inited)
setup();
easyHandle = curl_easy_init();
if (!easyHandle) {
DEBUG1("Something wrong with CURL\n");
return;
}
#if LIBCURL_VERSION_NUM >= 0x070a00
result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_NOSIGNAL error: %d\n", result);
}
#endif
result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,
cURLManager::writeFunction);
if (result != CURLE_OK)
DEBUG1("CURLOPT_WRITEFUNCTION error: %d\n", result);
result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);
if (result != CURLE_OK)
DEBUG1("CURLOPT_FILE error: %d\n", result);
}
cURLManager::~cURLManager()
{
if (added)
removeHandle();
curl_easy_cleanup(easyHandle);
free(theData);
}
void cURLManager::setup()
{
CURLcode result;
DEBUG1("LIBCURL: %s\n", curl_version());
#if LIBCURL_VERSION_NUM >= 0x070a00
if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
#endif
multiHandle = curl_multi_init();
if (!multiHandle)
DEBUG1("Unexpected error creating multi handle from libcurl \n");
inited = true;
}
size_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,
void *stream)
{
int len = size * nmemb;
((cURLManager*)stream)->collectData((char*)ptr, len);
return len;
}
void cURLManager::setTimeout(long timeout)
{
CURLcode result;
result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_TIMEOUT error: %d\n", result);
}
}
void cURLManager::setNoBody(bool nobody)
{
CURLcode result;
result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_NOBODY error: %d\n", result);
}
}
void cURLManager::setURL(std::string url)
{
CURLcode result;
if (url == "")
result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);
else
result = curl_easy_setopt(easyHandle, CURLOPT_URL, url.c_str());
if (result != CURLE_OK) {
errorCode = result;
DEBUG1("CURLOPT_URL error: %d\n", result);
}
}
void cURLManager::addHandle()
{
CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);
if (result != CURLM_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
cURLList.push_back(this);
added = true;
}
void cURLManager::removeHandle()
{
if (!added)
return;
for (std::list<cURLManager*>::iterator i = cURLList.begin();
i != cURLList.end(); i++)
if (*i == this) {
cURLList.erase(i);
break;
}
CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);
if (result != CURLM_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
added = false;
}
void cURLManager::collectData(char* ptr, int &len)
{
unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);
if (!newData) {
DEBUG1("memory exhausted\n");
} else {
memcpy(newData + theLen, ptr, len);
theLen += len;
theData = newData;
}
}
int cURLManager::perform()
{
if (!inited)
setup();
int activeTransfers = 0;
CURLMcode result;
while (true) {
result = curl_multi_perform(multiHandle, &activeTransfers);
if (result != CURLM_CALL_MULTI_PERFORM)
break;
}
if (result != CURLM_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
int msgs_in_queue;
CURLMsg *pendingMsg;
CURL *easy;
while (true) {
pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);
if (!pendingMsg)
break;
easy = pendingMsg->easy_handle;
for (std::list<cURLManager*>::iterator i = cURLList.begin();
i != cURLList.end(); i++)
if ((*i)->easyHandle == easy) {
(*i)->infoComplete(pendingMsg->data.result);
break;
}
if (msgs_in_queue <= 0)
break;
}
return activeTransfers;
}
void cURLManager::infoComplete(CURLcode result)
{
if (result != CURLE_OK)
DEBUG1("Unexpected error from libcurl; Error: %d\n", result);
finalization((char *)theData, theLen, result == CURLE_OK);
free(theData);
removeHandle();
theData = NULL;
theLen = 0;
}
bool cURLManager::getFileTime(time_t &t)
{
long filetime;
CURLcode result;
result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);
if (result) {
DEBUG1("CURLINFO_FILETIME error: %d\n", result);
return false;
}
t = (time_t)filetime;
return true;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/modelselection/ParameterCombination.h>
#include <shogun/base/Parameter.h>
#include <shogun/machine/Machine.h>
using namespace shogun;
CParameterCombination::CParameterCombination()
{
init();
}
CParameterCombination::CParameterCombination(Parameter* param)
{
init();
m_param=param;
}
void CParameterCombination::init()
{
m_param=NULL;
m_child_nodes=new CDynamicObjectArray<CParameterCombination> ();
SG_REF(m_child_nodes);
m_parameters->add((CSGObject**)m_child_nodes, "child nodes",
"children of this node");
}
CParameterCombination::~CParameterCombination()
{
delete m_param;
SG_UNREF(m_child_nodes);
}
void CParameterCombination::append_child(CParameterCombination* child)
{
m_child_nodes->append_element(child);
}
void CParameterCombination::print_tree(int prefix_num) const
{
/* prefix is enlarged */
char* prefix=SG_MALLOC(char, prefix_num+1);
for (index_t i=0; i<prefix_num; ++i)
prefix[i]='\t';
prefix[prefix_num]='\0';
/* cases:
* -node with a Parameter instance and a possible children
* -root node with children
*/
if (m_param)
{
SG_SPRINT("%s", prefix);
for (index_t i=0; i<m_param->get_num_parameters(); ++i)
{
/* distinction between sgobject and values */
if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_SGOBJECT)
{
TParameter* param=m_param->get_parameter(i);
CSGObject* current_sgobject=*((CSGObject**) param->m_parameter);
SG_SPRINT("\"%s\":%s at %p ", param->m_name,
current_sgobject->get_name(), current_sgobject);
}
else
{
SG_SPRINT("\"%s\"=%f ", m_param->get_parameter(i)->m_name,
*((float64_t*)m_param->get_parameter(i)->m_parameter));
}
}
}
else
SG_SPRINT("%sroot", prefix);
SG_SPRINT("\n");
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
child->print_tree(prefix_num+1);
SG_UNREF(child);
}
SG_FREE(prefix);
}
DynArray<Parameter*>* CParameterCombination::parameter_set_multiplication(
const DynArray<Parameter*>& set_1, const DynArray<Parameter*>& set_2)
{
DynArray<Parameter*>* result=new DynArray<Parameter*>();
for (index_t i=0; i<set_1.get_num_elements(); ++i)
{
for (index_t j=0; j<set_2.get_num_elements(); ++j)
{
Parameter* p=new Parameter();
p->add_parameters(set_1[i]);
p->add_parameters(set_2[j]);
result->append_element(p);
}
}
return result;
}
CDynamicObjectArray<CParameterCombination>* CParameterCombination::leaf_sets_multiplication(
const CDynamicObjectArray<CDynamicObjectArray<CParameterCombination> >& sets,
const CParameterCombination* new_root)
{
CDynamicObjectArray<CParameterCombination>* result=new CDynamicObjectArray<
CParameterCombination>();
/* check marginal cases */
if (sets.get_num_elements()==1)
{
CDynamicObjectArray<CParameterCombination>* current_set=
sets.get_element(0);
/* just use the only element into result array.
* put root node before all combinations*/
*result=*current_set;
SG_UNREF(current_set);
for (index_t i=0; i<result->get_num_elements(); ++i)
{
/* put new root as root into the tree and replace tree */
CParameterCombination* current=result->get_element(i);
CParameterCombination* root=new_root->copy_tree();
root->append_child(current);
result->set_element(root, i);
SG_UNREF(current);
}
}
else if (sets.get_num_elements()>1)
{
/* now the case where at least two sets are given */
/* first, extract Parameter instances of given sets */
DynArray<DynArray<Parameter*>*> param_sets;
for (index_t set_nr=0; set_nr<sets.get_num_elements(); ++set_nr)
{
CDynamicObjectArray<CParameterCombination>* current_set=
sets.get_element(set_nr);
DynArray<Parameter*>* new_param_set=new DynArray<Parameter*> ();
param_sets.append_element(new_param_set);
for (index_t i=0; i<current_set->get_num_elements(); ++i)
{
CParameterCombination* current_node=current_set->get_element(i);
if (current_node->m_child_nodes->get_num_elements())
{
SG_SERROR("leaf sets multiplication only possible if all "
"trees are leafs");
}
Parameter* current_param=current_node->m_param;
if (current_param)
new_param_set->append_element(current_param);
else
{
SG_SERROR("leaf sets multiplication only possible if all "
"leafs have non-NULL Parameter instances\n");
}
SG_UNREF(current_node);
}
SG_UNREF(current_set);
}
/* second, build products of all parameter sets */
DynArray<Parameter*>* param_product=parameter_set_multiplication(
*param_sets[0], *param_sets[1]);
delete param_sets[0];
delete param_sets[1];
/* build product of all remaining sets and collect results. delete all
* parameter instances of interim products*/
for (index_t i=2; i<param_sets.get_num_elements(); ++i)
{
DynArray<Parameter*>* old_temp_result=param_product;
param_product=parameter_set_multiplication(*param_product,
*param_sets[i]);
/* delete interim result parameter instances */
for (index_t j=0; j<old_temp_result->get_num_elements(); ++j)
delete old_temp_result->get_element(j);
/* and dyn arrays of interim result and of param_sets */
delete old_temp_result;
delete param_sets[i];
}
/* at this point there is only one DynArray instance remaining:
* param_product. contains all combinations of parameters of all given
* sets */
/* third, build tree sets with the given root and the parameter product
* elements */
for (index_t i=0; i<param_product->get_num_elements(); ++i)
{
/* build parameter node from parameter product to append to root */
CParameterCombination* param_node=new CParameterCombination(
param_product->get_element(i));
/* copy new root node, has to be a new one each time */
CParameterCombination* root=new_root->copy_tree();
/* append both and add them to result set */
root->append_child(param_node);
result->append_element(root);
}
/* this is not needed anymore, because the Parameter instances are now
* in the resulting tree sets */
delete param_product;
}
return result;
}
CParameterCombination* CParameterCombination::copy_tree() const
{
CParameterCombination* copy=new CParameterCombination();
/* but build new Parameter instance */
/* only call add_parameters() argument is non-null */
if (m_param)
{
copy->m_param=new Parameter();
copy->m_param->add_parameters(m_param);
} else
copy->m_param=NULL;
/* recursively copy all children */
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
copy->m_child_nodes->append_element(child->copy_tree());
SG_UNREF(child);
}
return copy;
}
void CParameterCombination::apply_to_machine(CMachine* machine) const
{
apply_to_parameter(machine->m_parameters);
}
void CParameterCombination::apply_to_parameter(Parameter* parameter) const
{
/* case root node or name node */
if (!m_param)
{
/* iterate over all children and recursively set parameters from
* their values to the current parameter input (its just handed one
* recursion level downwards) */
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
child->apply_to_parameter(parameter);
SG_UNREF(child);
}
}
/* case parameter node */
else if (m_param)
{
/* does this node has sub parameters? */
if (has_children())
{
/* if a parameter node has children, it has to have ONE CSGObject as
* parameter */
if (m_param->get_num_parameters()>1 ||
m_param->get_parameter(0)->m_datatype.m_ptype!=PT_SGOBJECT)
{
SG_SERROR("invalid CParameterCombination node type, has children"
" and more than one parameter or is not a "
"CSGObject.\n");
}
/* cast is now safe */
CSGObject* current_sgobject=
*((CSGObject**)(m_param->get_parameter(0)->m_parameter));
/* set parameters */
parameter->set_from_parameters(m_param);
/* iterate over all children and recursively set parameters from
* their values */
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
child->apply_to_parameter(current_sgobject->m_parameters);
SG_UNREF(child);
}
}
else
parameter->set_from_parameters(m_param);
}
else
SG_SERROR("CParameterCombination node has illegal type.\n");
}
<commit_msg>print method now handles different data types<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/modelselection/ParameterCombination.h>
#include <shogun/base/Parameter.h>
#include <shogun/machine/Machine.h>
using namespace shogun;
CParameterCombination::CParameterCombination()
{
init();
}
CParameterCombination::CParameterCombination(Parameter* param)
{
init();
m_param=param;
}
void CParameterCombination::init()
{
m_param=NULL;
m_child_nodes=new CDynamicObjectArray<CParameterCombination> ();
SG_REF(m_child_nodes);
m_parameters->add((CSGObject**)m_child_nodes, "child nodes",
"children of this node");
}
CParameterCombination::~CParameterCombination()
{
delete m_param;
SG_UNREF(m_child_nodes);
}
void CParameterCombination::append_child(CParameterCombination* child)
{
m_child_nodes->append_element(child);
}
void CParameterCombination::print_tree(int prefix_num) const
{
/* prefix is enlarged */
char* prefix=SG_MALLOC(char, prefix_num+1);
for (index_t i=0; i<prefix_num; ++i)
prefix[i]='\t';
prefix[prefix_num]='\0';
/* cases:
* -node with a Parameter instance and a possible children
* -root node with children
*/
if (m_param)
{
SG_SPRINT("%s", prefix);
for (index_t i=0; i<m_param->get_num_parameters(); ++i)
{
/* distinction between sgobject and values */
if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_SGOBJECT)
{
TParameter* param=m_param->get_parameter(i);
CSGObject* current_sgobject=*((CSGObject**) param->m_parameter);
SG_SPRINT("\"%s\":%s at %p ", param->m_name,
current_sgobject->get_name(), current_sgobject);
}
else
{
SG_SPRINT("\"%s\"=", m_param->get_parameter(i)->m_name);
void* param=m_param->get_parameter(i)->m_parameter;
if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_FLOAT64)
SG_SPRINT("%f ", *((float64_t*)param));
else if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_INT32)
SG_SPRINT("%i ", *((int32_t*)param));
else if (m_param->get_parameter(i)->m_datatype.m_ptype==PT_BOOL)
SG_SPRINT("%s ", *((bool*)param ? "true" : "false"));
else
SG_NOTIMPLEMENTED;
}
}
}
else
SG_SPRINT("%sroot", prefix);
SG_SPRINT("\n");
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
child->print_tree(prefix_num+1);
SG_UNREF(child);
}
SG_FREE(prefix);
}
DynArray<Parameter*>* CParameterCombination::parameter_set_multiplication(
const DynArray<Parameter*>& set_1, const DynArray<Parameter*>& set_2)
{
DynArray<Parameter*>* result=new DynArray<Parameter*>();
for (index_t i=0; i<set_1.get_num_elements(); ++i)
{
for (index_t j=0; j<set_2.get_num_elements(); ++j)
{
Parameter* p=new Parameter();
p->add_parameters(set_1[i]);
p->add_parameters(set_2[j]);
result->append_element(p);
}
}
return result;
}
CDynamicObjectArray<CParameterCombination>* CParameterCombination::leaf_sets_multiplication(
const CDynamicObjectArray<CDynamicObjectArray<CParameterCombination> >& sets,
const CParameterCombination* new_root)
{
CDynamicObjectArray<CParameterCombination>* result=new CDynamicObjectArray<
CParameterCombination>();
/* check marginal cases */
if (sets.get_num_elements()==1)
{
CDynamicObjectArray<CParameterCombination>* current_set=
sets.get_element(0);
/* just use the only element into result array.
* put root node before all combinations*/
*result=*current_set;
SG_UNREF(current_set);
for (index_t i=0; i<result->get_num_elements(); ++i)
{
/* put new root as root into the tree and replace tree */
CParameterCombination* current=result->get_element(i);
CParameterCombination* root=new_root->copy_tree();
root->append_child(current);
result->set_element(root, i);
SG_UNREF(current);
}
}
else if (sets.get_num_elements()>1)
{
/* now the case where at least two sets are given */
/* first, extract Parameter instances of given sets */
DynArray<DynArray<Parameter*>*> param_sets;
for (index_t set_nr=0; set_nr<sets.get_num_elements(); ++set_nr)
{
CDynamicObjectArray<CParameterCombination>* current_set=
sets.get_element(set_nr);
DynArray<Parameter*>* new_param_set=new DynArray<Parameter*> ();
param_sets.append_element(new_param_set);
for (index_t i=0; i<current_set->get_num_elements(); ++i)
{
CParameterCombination* current_node=current_set->get_element(i);
if (current_node->m_child_nodes->get_num_elements())
{
SG_SERROR("leaf sets multiplication only possible if all "
"trees are leafs");
}
Parameter* current_param=current_node->m_param;
if (current_param)
new_param_set->append_element(current_param);
else
{
SG_SERROR("leaf sets multiplication only possible if all "
"leafs have non-NULL Parameter instances\n");
}
SG_UNREF(current_node);
}
SG_UNREF(current_set);
}
/* second, build products of all parameter sets */
DynArray<Parameter*>* param_product=parameter_set_multiplication(
*param_sets[0], *param_sets[1]);
delete param_sets[0];
delete param_sets[1];
/* build product of all remaining sets and collect results. delete all
* parameter instances of interim products*/
for (index_t i=2; i<param_sets.get_num_elements(); ++i)
{
DynArray<Parameter*>* old_temp_result=param_product;
param_product=parameter_set_multiplication(*param_product,
*param_sets[i]);
/* delete interim result parameter instances */
for (index_t j=0; j<old_temp_result->get_num_elements(); ++j)
delete old_temp_result->get_element(j);
/* and dyn arrays of interim result and of param_sets */
delete old_temp_result;
delete param_sets[i];
}
/* at this point there is only one DynArray instance remaining:
* param_product. contains all combinations of parameters of all given
* sets */
/* third, build tree sets with the given root and the parameter product
* elements */
for (index_t i=0; i<param_product->get_num_elements(); ++i)
{
/* build parameter node from parameter product to append to root */
CParameterCombination* param_node=new CParameterCombination(
param_product->get_element(i));
/* copy new root node, has to be a new one each time */
CParameterCombination* root=new_root->copy_tree();
/* append both and add them to result set */
root->append_child(param_node);
result->append_element(root);
}
/* this is not needed anymore, because the Parameter instances are now
* in the resulting tree sets */
delete param_product;
}
return result;
}
CParameterCombination* CParameterCombination::copy_tree() const
{
CParameterCombination* copy=new CParameterCombination();
/* but build new Parameter instance */
/* only call add_parameters() argument is non-null */
if (m_param)
{
copy->m_param=new Parameter();
copy->m_param->add_parameters(m_param);
} else
copy->m_param=NULL;
/* recursively copy all children */
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
copy->m_child_nodes->append_element(child->copy_tree());
SG_UNREF(child);
}
return copy;
}
void CParameterCombination::apply_to_machine(CMachine* machine) const
{
apply_to_parameter(machine->m_parameters);
}
void CParameterCombination::apply_to_parameter(Parameter* parameter) const
{
/* case root node or name node */
if (!m_param)
{
/* iterate over all children and recursively set parameters from
* their values to the current parameter input (its just handed one
* recursion level downwards) */
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
child->apply_to_parameter(parameter);
SG_UNREF(child);
}
}
/* case parameter node */
else if (m_param)
{
/* does this node has sub parameters? */
if (has_children())
{
/* if a parameter node has children, it has to have ONE CSGObject as
* parameter */
if (m_param->get_num_parameters()>1 ||
m_param->get_parameter(0)->m_datatype.m_ptype!=PT_SGOBJECT)
{
SG_SERROR("invalid CParameterCombination node type, has children"
" and more than one parameter or is not a "
"CSGObject.\n");
}
/* cast is now safe */
CSGObject* current_sgobject=
*((CSGObject**)(m_param->get_parameter(0)->m_parameter));
/* set parameters */
parameter->set_from_parameters(m_param);
/* iterate over all children and recursively set parameters from
* their values */
for (index_t i=0; i<m_child_nodes->get_num_elements(); ++i)
{
CParameterCombination* child=m_child_nodes->get_element(i);
child->apply_to_parameter(current_sgobject->m_parameters);
SG_UNREF(child);
}
}
else
parameter->set_from_parameters(m_param);
}
else
SG_SERROR("CParameterCombination node has illegal type.\n");
}
<|endoftext|> |
<commit_before>#ifndef NANOCV_CONVOLUTION_H
#define NANOCV_CONVOLUTION_H
#include <eigen3/Eigen/Core>
namespace ncv
{
namespace math
{
///
/// 2D convolution: odata += idata @ kdata (using Eigen 2D blocks)
///
template
<
typename tmatrixi,
typename tmatrixk = tmatrixi,
typename tmatrixo = tmatrixi,
typename tscalar = typename tmatrixi::Scalar
>
void conv(const tmatrixi& idata, const tmatrixk& kdata, tmatrixo& odata)
{
for (auto r = 0; r < odata.rows(); r ++)
{
for (auto c = 0; c < odata.cols(); c ++)
{
odata(r, c) +=
kdata.cwiseProduct(idata.block(r, c, kdata.rows(), kdata.cols())).sum();
}
}
}
///
/// 2D convolution: odata += weight * idata @ kdata (using Eigen 2D blocks)
///
template
<
typename tmatrixi,
typename tmatrixk = tmatrixi,
typename tmatrixo = tmatrixi,
typename tscalar = typename tmatrixi::Scalar
>
void wconv(const tmatrixi& idata, const tmatrixk& kdata, tscalar weight, tmatrixo& odata)
{
for (auto r = 0; r < odata.rows(); r ++)
{
for (auto c = 0; c < odata.cols(); c ++)
{
odata(r, c) += weight *
kdata.cwiseProduct(idata.block(r, c, kdata.rows(), kdata.cols())).sum();
}
}
}
}
}
#endif // NANOCV_CONVOLUTION_H
<commit_msg>conv & conv_sum implementations<commit_after>#ifndef NANOCV_CONVOLUTION_H
#define NANOCV_CONVOLUTION_H
#include <eigen3/Eigen/Core>
namespace ncv
{
namespace math
{
///
/// 2D convolution: odata += idata @ kdata (using Eigen 2D blocks)
///
template
<
typename tmatrixi,
typename tmatrixk = tmatrixi,
typename tmatrixo = tmatrixi,
typename tscalar = typename tmatrixi::Scalar
>
void conv_sum(const tmatrixi& idata, const tmatrixk& kdata, tmatrixo& odata)
{
for (auto r = 0; r < odata.rows(); r ++)
{
for (auto c = 0; c < odata.cols(); c ++)
{
odata(r, c) +=
kdata.cwiseProduct(idata.block(r, c, kdata.rows(), kdata.cols())).sum();
}
}
}
///
/// 2D convolution: odata = idata @ kdata (using Eigen 2D blocks)
///
template
<
typename tmatrixi,
typename tmatrixk = tmatrixi,
typename tmatrixo = tmatrixi,
typename tscalar = typename tmatrixi::Scalar
>
void conv(const tmatrixi& idata, const tmatrixk& kdata, tmatrixo& odata)
{
for (auto r = 0; r < odata.rows(); r ++)
{
for (auto c = 0; c < odata.cols(); c ++)
{
odata(r, c) =
kdata.cwiseProduct(idata.block(r, c, kdata.rows(), kdata.cols())).sum();
}
}
}
///
/// 2D convolution: odata += weight * idata @ kdata (using Eigen 2D blocks)
///
template
<
typename tmatrixi,
typename tmatrixk = tmatrixi,
typename tmatrixo = tmatrixi,
typename tscalar = typename tmatrixi::Scalar
>
void wconv_sum(const tmatrixi& idata, const tmatrixk& kdata, tscalar weight, tmatrixo& odata)
{
for (auto r = 0; r < odata.rows(); r ++)
{
for (auto c = 0; c < odata.cols(); c ++)
{
odata(r, c) += weight *
kdata.cwiseProduct(idata.block(r, c, kdata.rows(), kdata.cols())).sum();
}
}
}
///
/// 2D convolution: odata = weight * idata @ kdata (using Eigen 2D blocks)
///
template
<
typename tmatrixi,
typename tmatrixk = tmatrixi,
typename tmatrixo = tmatrixi,
typename tscalar = typename tmatrixi::Scalar
>
void wconv(const tmatrixi& idata, const tmatrixk& kdata, tscalar weight, tmatrixo& odata)
{
for (auto r = 0; r < odata.rows(); r ++)
{
for (auto c = 0; c < odata.cols(); c ++)
{
odata(r, c) = weight *
kdata.cwiseProduct(idata.block(r, c, kdata.rows(), kdata.cols())).sum();
}
}
}
}
}
#endif // NANOCV_CONVOLUTION_H
<|endoftext|> |
<commit_before>/**
* Created by Jian Chen
* @since 2016.12.14
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
*/
#if !defined(__linux__) && !defined(_WIN32)
#include <socket/core/reactor.hpp>
#include <chen/sys/sys.hpp>
#include <unordered_map>
#include <vector>
#include <memory>
// -----------------------------------------------------------------------------
// reactor
const int chen::reactor::FlagEdge = EV_CLEAR;
const int chen::reactor::FlagOnce = EV_ONESHOT;
chen::reactor::reactor(int count) : _count(count)
{
// create kqueue file descriptor
if ((this->_kqueue = ::kqueue()) < 0)
throw std::system_error(sys::error(), "kqueue: failed to create kqueue");
// register custom filter to receive wake message
// ident's value is not important here, so use zero is ok
if (this->alter(0, EVFILT_USER, EV_ADD | EV_CLEAR, 0, nullptr) < 0)
{
::close(this->_kqueue);
throw std::system_error(chen::sys::error(), "kqueue: failed to create custom filter");
}
}
chen::reactor::~reactor()
{
::close(this->_kqueue);
}
// modify
void chen::reactor::set(handle_t fd, callback *cb, int mode, int flag)
{
// register read or delete
if ((this->alter(fd, EVFILT_READ, (mode & ModeRead) ? EV_ADD | flag : EV_DELETE, 0, cb) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to set event");
// register write or delete
if ((this->alter(fd, EVFILT_WRITE, (mode & ModeWrite) ? EV_ADD | flag : EV_DELETE, 0, cb) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to set event");
}
void chen::reactor::del(handle_t fd)
{
// delete read
if ((this->alter(fd, EVFILT_READ, EV_DELETE, 0, nullptr) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to delete event");
// delete write
if ((this->alter(fd, EVFILT_WRITE, EV_DELETE, 0, nullptr) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to delete event");
}
// run
void chen::reactor::run()
{
for (std::error_code code; !code || (code == std::errc::interrupted); code = this->once())
;
}
std::error_code chen::reactor::once(double timeout)
{
// poll events
struct ::kevent events[this->_count]; // VLA
std::unique_ptr<::timespec> val;
if (timeout >= 0)
{
val.reset(new ::timespec);
val->tv_sec = static_cast<time_t>(timeout);
val->tv_nsec = static_cast<time_t>((timeout - val->tv_sec) * 1000000000);
}
int result = 0;
if ((result = ::kevent(this->_kqueue, nullptr, 0, events, this->_count, val.get())) <= 0)
{
if (!result)
return std::make_error_code(std::errc::timed_out); // timeout if result is zero
else if (errno == EINTR)
return std::make_error_code(std::errc::interrupted); // EINTR maybe triggered by debugger
else
throw std::system_error(sys::error(), "kqueue: failed to poll event");
}
// merge events, events on the same fd will be notified only once
typedef std::vector<std::pair<callback*, Type>> merge_t; // keep events' original order
typedef std::unordered_map<callback*, merge_t::iterator> cache_t;
merge_t merge;
cache_t cache;
for (int i = 0; i < result; ++i)
{
auto &item = events[i];
auto *call = static_cast<callback*>(item.udata);
// user request to stop
if (item.filter == EVFILT_USER)
return std::make_error_code(std::errc::operation_canceled);
if (!call)
continue;
// find exist event
auto find = cache.find(call);
auto type = this->type(item.filter, item.flags);
if (find != cache.end())
find->second->second |= type;
else
cache[call] = merge.insert(merge.end(), std::make_pair(call, type));
}
// invoke callback
std::for_each(merge.begin(), merge.end(), [] (merge_t::value_type &item) {
(*item.first)(item.second);
});
return {};
}
void chen::reactor::stop()
{
// notify wake message via custom filter
if (this->alter(0, EVFILT_USER, EV_ENABLE, NOTE_TRIGGER, nullptr) < 0)
throw std::system_error(sys::error(), "kqueue: failed to stop the kqueue");
}
// misc
chen::reactor::Type chen::reactor::type(int filter, int flags)
{
if ((flags & EV_EOF) || (flags & EV_ERROR))
return Closed;
switch (filter)
{
case EVFILT_READ:
return Readable;
case EVFILT_WRITE:
return Writable;
default:
throw std::runtime_error("kqueue: unknown event detect");
}
}
int chen::reactor::alter(handle_t fd, int filter, int flags, int fflags, void *data)
{
struct ::kevent event{};
EV_SET(&event, fd, filter, flags, fflags, 0, data);
return ::kevent(this->_kqueue, &event, 1, nullptr, 0, nullptr);
}
#endif<commit_msg>reactor: stop message should be handled in later block, not in merge block<commit_after>/**
* Created by Jian Chen
* @since 2016.12.14
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
*/
#if !defined(__linux__) && !defined(_WIN32)
#include <socket/core/reactor.hpp>
#include <chen/sys/sys.hpp>
#include <unordered_map>
#include <vector>
#include <memory>
// -----------------------------------------------------------------------------
// reactor
const int chen::reactor::FlagEdge = EV_CLEAR;
const int chen::reactor::FlagOnce = EV_ONESHOT;
chen::reactor::reactor(int count) : _count(count)
{
// create kqueue file descriptor
if ((this->_kqueue = ::kqueue()) < 0)
throw std::system_error(sys::error(), "kqueue: failed to create kqueue");
// register custom filter to receive wake message
// ident's value is not important here, so use zero is ok
if (this->alter(0, EVFILT_USER, EV_ADD | EV_CLEAR, 0, nullptr) < 0)
{
::close(this->_kqueue);
throw std::system_error(chen::sys::error(), "kqueue: failed to create custom filter");
}
}
chen::reactor::~reactor()
{
::close(this->_kqueue);
}
// modify
void chen::reactor::set(handle_t fd, callback *cb, int mode, int flag)
{
// register read or delete
if ((this->alter(fd, EVFILT_READ, (mode & ModeRead) ? EV_ADD | flag : EV_DELETE, 0, cb) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to set event");
// register write or delete
if ((this->alter(fd, EVFILT_WRITE, (mode & ModeWrite) ? EV_ADD | flag : EV_DELETE, 0, cb) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to set event");
}
void chen::reactor::del(handle_t fd)
{
// delete read
if ((this->alter(fd, EVFILT_READ, EV_DELETE, 0, nullptr) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to delete event");
// delete write
if ((this->alter(fd, EVFILT_WRITE, EV_DELETE, 0, nullptr) < 0) && (errno != ENOENT))
throw std::system_error(chen::sys::error(), "kqueue: failed to delete event");
}
// run
void chen::reactor::run()
{
for (std::error_code code; !code || (code == std::errc::interrupted); code = this->once())
;
}
std::error_code chen::reactor::once(double timeout)
{
// poll events
struct ::kevent events[this->_count]; // VLA
std::unique_ptr<::timespec> val;
if (timeout >= 0)
{
val.reset(new ::timespec);
val->tv_sec = static_cast<time_t>(timeout);
val->tv_nsec = static_cast<time_t>((timeout - val->tv_sec) * 1000000000);
}
int result = 0;
if ((result = ::kevent(this->_kqueue, nullptr, 0, events, this->_count, val.get())) <= 0)
{
if (!result)
return std::make_error_code(std::errc::timed_out); // timeout if result is zero
else if (errno == EINTR)
return std::make_error_code(std::errc::interrupted); // EINTR maybe triggered by debugger
else
throw std::system_error(sys::error(), "kqueue: failed to poll event");
}
// merge events, events on the same fd will be notified only once
typedef std::vector<std::pair<callback*, Type>> merge_t; // keep events' original order
typedef std::unordered_map<callback*, merge_t::iterator> cache_t;
merge_t merge;
cache_t cache;
for (int i = 0; i < result; ++i)
{
auto &item = events[i];
auto *call = static_cast<callback*>(item.udata);
// user request to stop
if (item.filter == EVFILT_USER)
{
// store for later use
merge.emplace_back(std::make_pair(nullptr, 0));
continue;
}
if (!call)
continue;
// find exist event
auto find = cache.find(call);
auto type = this->type(item.filter, item.flags);
if (find != cache.end())
find->second->second |= type;
else
cache[call] = merge.insert(merge.end(), std::make_pair(call, type));
}
// invoke callback
for (auto it = merge.begin(); it != merge.end(); ++it)
{
// user request to stop
if (!it->first)
return std::make_error_code(std::errc::operation_canceled);
(*it->first)(it->second);
}
return {};
}
void chen::reactor::stop()
{
// notify wake message via custom filter
if (this->alter(0, EVFILT_USER, EV_ENABLE, NOTE_TRIGGER, nullptr) < 0)
throw std::system_error(sys::error(), "kqueue: failed to stop the kqueue");
}
// misc
chen::reactor::Type chen::reactor::type(int filter, int flags)
{
if ((flags & EV_EOF) || (flags & EV_ERROR))
return Closed;
switch (filter)
{
case EVFILT_READ:
return Readable;
case EVFILT_WRITE:
return Writable;
default:
throw std::runtime_error("kqueue: unknown event detect");
}
}
int chen::reactor::alter(handle_t fd, int filter, int flags, int fflags, void *data)
{
struct ::kevent event{};
EV_SET(&event, fd, filter, flags, fflags, 0, data);
return ::kevent(this->_kqueue, &event, 1, nullptr, 0, nullptr);
}
#endif<|endoftext|> |
<commit_before>// Rubiks2x2x3.cpp
#include "Application.h"
#include "Rubiks2x2x3.h"
#include <Surface.h>
#include <Plane.h>
wxIMPLEMENT_DYNAMIC_CLASS( Rubiks2x2x3, TwistyPuzzle );
Rubiks2x2x3::Rubiks2x2x3( void )
{
}
/*virtual*/ Rubiks2x2x3::~Rubiks2x2x3( void )
{
}
/*virtual*/ void Rubiks2x2x3::Reset( void )
{
Clear();
SetupStandardDynamicFaceTurningBoxLabels();
MakeBox( 10.0 * ( 2.0 / 3.0 ), 10.0, 10.0 * ( 2.0 / 3.0 ) );
CutShape* cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( 1.0, 0.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( 1.0, 0.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 1, 31 );
cutShape->ccwPermutation.DefineCycle( 2, 28 );
cutShape->ccwPermutation.DefineCycle( 4, 7 );
cutShape->ccwPermutation.DefineCycle( 6, 9 );
cutShape->ccwPermutation.DefineCycle( 5, 8 );
cutShape->ccwPermutation.DefineCycle( 11, 23 );
cutShape->ccwPermutation.DefineCycle( 12, 24 );
cutShape->ccwPermutation.DefineCycle( 13, 15 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( -1.0, 0.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( -1.0, 0.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 0, 30 );
cutShape->ccwPermutation.DefineCycle( 3, 29 );
cutShape->ccwPermutation.DefineCycle( 10, 22 );
cutShape->ccwPermutation.DefineCycle( 15, 27 );
cutShape->ccwPermutation.DefineCycle( 14, 26 );
cutShape->ccwPermutation.DefineCycle( 21, 18 );
cutShape->ccwPermutation.DefineCycle( 20, 27 );
cutShape->ccwPermutation.DefineCycle( 19, 16 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( 0.0, 0.0, 1.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( 0.0, 0.0, 1.0 );
cutShape->ccwPermutation.DefineCycle( 0, 28 );
cutShape->ccwPermutation.DefineCycle( 1, 29 );
cutShape->ccwPermutation.DefineCycle( 26, 23 );
cutShape->ccwPermutation.DefineCycle( 27, 24 );
cutShape->ccwPermutation.DefineCycle( 22, 25 );
cutShape->ccwPermutation.DefineCycle( 6, 18 );
cutShape->ccwPermutation.DefineCycle( 5, 17 );
cutShape->ccwPermutation.DefineCycle( 4, 16 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( 0.0, 0.0, -1.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( 0.0, 0.0, -1.0 );
cutShape->ccwPermutation.DefineCycle( 2, 30 );
cutShape->ccwPermutation.DefineCycle( 3, 31 );
cutShape->ccwPermutation.DefineCycle( 9, 21 );
cutShape->ccwPermutation.DefineCycle( 8, 20 );
cutShape->ccwPermutation.DefineCycle( 7, 19 );
cutShape->ccwPermutation.DefineCycle( 11, 14 );
cutShape->ccwPermutation.DefineCycle( 15, 12 );
cutShape->ccwPermutation.DefineCycle( 10, 13 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 5.0 - 10.0 / 3.0, 0.0 ), _3DMath::Vector( 0.0, 1.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI / 2.0;
cutShape->axisOfRotation.normal.Set( 0.0, 1.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 0, 1, 2, 3 );
cutShape->ccwPermutation.DefineCycle( 4, 11, 19, 26 );
cutShape->ccwPermutation.DefineCycle( 9, 10, 18, 25 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, -5.0 + 10 / 3.0, 0.0 ), _3DMath::Vector( 0.0, -1.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI / 2.0;
cutShape->axisOfRotation.normal.Set( 0.0, -1.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 28, 29, 30, 31 );
cutShape->ccwPermutation.DefineCycle( 6, 22, 21, 13 );
cutShape->ccwPermutation.DefineCycle( 7, 23, 16, 14 );
cutShapeList.push_back( cutShape );
}
/*virtual*/ wxString Rubiks2x2x3::LocateStabChainFile( void ) const
{
return wxGetApp().ResolveRelativeResourcePath( "Data/StabChains/Rubiks2x2x3.txt" );
}
// Rubiks2x2x3.cpp<commit_msg>fix mistakes<commit_after>// Rubiks2x2x3.cpp
#include "Application.h"
#include "Rubiks2x2x3.h"
#include <Surface.h>
#include <Plane.h>
wxIMPLEMENT_DYNAMIC_CLASS( Rubiks2x2x3, TwistyPuzzle );
Rubiks2x2x3::Rubiks2x2x3( void )
{
}
/*virtual*/ Rubiks2x2x3::~Rubiks2x2x3( void )
{
}
/*virtual*/ void Rubiks2x2x3::Reset( void )
{
Clear();
SetupStandardDynamicFaceTurningBoxLabels();
MakeBox( 10.0 * ( 2.0 / 3.0 ), 10.0, 10.0 * ( 2.0 / 3.0 ) );
CutShape* cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( 1.0, 0.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( 1.0, 0.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 1, 31 );
cutShape->ccwPermutation.DefineCycle( 2, 28 );
cutShape->ccwPermutation.DefineCycle( 4, 7 );
cutShape->ccwPermutation.DefineCycle( 6, 9 );
cutShape->ccwPermutation.DefineCycle( 5, 8 );
cutShape->ccwPermutation.DefineCycle( 11, 23 );
cutShape->ccwPermutation.DefineCycle( 12, 24 );
cutShape->ccwPermutation.DefineCycle( 13, 25 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( -1.0, 0.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( -1.0, 0.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 0, 30 );
cutShape->ccwPermutation.DefineCycle( 3, 29 );
cutShape->ccwPermutation.DefineCycle( 10, 22 );
cutShape->ccwPermutation.DefineCycle( 15, 27 );
cutShape->ccwPermutation.DefineCycle( 14, 26 );
cutShape->ccwPermutation.DefineCycle( 21, 18 );
cutShape->ccwPermutation.DefineCycle( 20, 17 );
cutShape->ccwPermutation.DefineCycle( 19, 16 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( 0.0, 0.0, 1.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( 0.0, 0.0, 1.0 );
cutShape->ccwPermutation.DefineCycle( 0, 28 );
cutShape->ccwPermutation.DefineCycle( 1, 29 );
cutShape->ccwPermutation.DefineCycle( 26, 23 );
cutShape->ccwPermutation.DefineCycle( 27, 24 );
cutShape->ccwPermutation.DefineCycle( 22, 25 );
cutShape->ccwPermutation.DefineCycle( 6, 18 );
cutShape->ccwPermutation.DefineCycle( 5, 17 );
cutShape->ccwPermutation.DefineCycle( 4, 16 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 0.0, 0.0 ), _3DMath::Vector( 0.0, 0.0, -1.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI;
cutShape->axisOfRotation.normal.Set( 0.0, 0.0, -1.0 );
cutShape->ccwPermutation.DefineCycle( 2, 30 );
cutShape->ccwPermutation.DefineCycle( 3, 31 );
cutShape->ccwPermutation.DefineCycle( 9, 21 );
cutShape->ccwPermutation.DefineCycle( 8, 20 );
cutShape->ccwPermutation.DefineCycle( 7, 19 );
cutShape->ccwPermutation.DefineCycle( 11, 14 );
cutShape->ccwPermutation.DefineCycle( 15, 12 );
cutShape->ccwPermutation.DefineCycle( 10, 13 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, 5.0 - 10.0 / 3.0, 0.0 ), _3DMath::Vector( 0.0, 1.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI / 2.0;
cutShape->axisOfRotation.normal.Set( 0.0, 1.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 0, 1, 2, 3 );
cutShape->ccwPermutation.DefineCycle( 4, 11, 19, 26 );
cutShape->ccwPermutation.DefineCycle( 9, 10, 18, 25 );
cutShapeList.push_back( cutShape );
cutShape = new CutShape();
cutShape->surface = new _3DMath::PlaneSurface( _3DMath::Plane( _3DMath::Vector( 0.0, -5.0 + 10 / 3.0, 0.0 ), _3DMath::Vector( 0.0, -1.0, 0.0 ) ) );
cutShape->rotationAngleForSingleTurn = M_PI / 2.0;
cutShape->axisOfRotation.normal.Set( 0.0, -1.0, 0.0 );
cutShape->ccwPermutation.DefineCycle( 28, 29, 30, 31 );
cutShape->ccwPermutation.DefineCycle( 6, 22, 21, 13 );
cutShape->ccwPermutation.DefineCycle( 7, 23, 16, 14 );
cutShapeList.push_back( cutShape );
}
/*virtual*/ wxString Rubiks2x2x3::LocateStabChainFile( void ) const
{
return wxGetApp().ResolveRelativeResourcePath( "Data/StabChains/Rubiks2x2x3.txt" );
}
// Rubiks2x2x3.cpp<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include "loader.h"
#include "hdd.h"
#include "cpu.h"
using namespace std;
int main(int argc, char const *argv[])
{
HDD *hdd = new HDD();
Loader *l = new Loader("/Users/jonathan/Development/os/spec/Program-File.txt", hdd);
CPU *cpu = new CPU();
File * file = hdd->findFile(1);
WORD * programData = (WORD *)&(*(file+1));
for (unsigned i = 0; i < file->programSize; i++)
{
cpu->fetch(programData++);
cpu->decode();
}
return 0;
}
<commit_msg>Driver using chrono timing to measure execution time<commit_after>#include <iostream>
#include <fstream>
#include <chrono>
#include "loader.h"
#include "hdd.h"
#include "cpu.h"
using namespace std;
int main(int argc, char const *argv[])
{
HDD *hdd = new HDD();
Loader *l = new Loader("..\\OSProj\\spec\\Program-File.txt", hdd);
CPU *cpu = new CPU();
File * file = hdd->findFile(1);
WORD * programData = (WORD *)&(*(file+1));
std::chrono::steady_clock::time_point start;
std::chrono::steady_clock::time_point end;
for (unsigned i = 0; i < file->programSize; i++)
{
start = std::chrono::steady_clock::now();
cpu->fetch(programData++);
cpu->decode();
end = std::chrono::steady_clock::now();
std::cout << "Execution Time " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()<<'\n';
}
system("pause");
return 0;
}<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/GLTestContext.h"
#define GL_GLEXT_PROTOTYPES
#include <GLES2/gl2.h>
#define EGL_EGLEXT_PROTOTYPES
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "gl/GrGLDefines.h"
#include "gl/GrGLUtil.h"
namespace {
// TODO: Share this class with ANGLE if/when it gets support for EGL_KHR_fence_sync.
class EGLFenceSync : public sk_gpu_test::FenceSync {
public:
static std::unique_ptr<EGLFenceSync> MakeIfSupported(EGLDisplay);
sk_gpu_test::PlatformFence SK_WARN_UNUSED_RESULT insertFence() const override;
bool waitFence(sk_gpu_test::PlatformFence fence) const override;
void deleteFence(sk_gpu_test::PlatformFence fence) const override;
private:
EGLFenceSync(EGLDisplay display) : fDisplay(display) {}
EGLDisplay fDisplay;
typedef sk_gpu_test::FenceSync INHERITED;
};
class EGLGLTestContext : public sk_gpu_test::GLTestContext {
public:
EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext);
~EGLGLTestContext() override;
GrEGLImage texture2DToEGLImage(GrGLuint texID) const override;
void destroyEGLImage(GrEGLImage) const override;
GrGLuint eglImageToExternalTexture(GrEGLImage) const override;
std::unique_ptr<sk_gpu_test::GLTestContext> makeNew() const override;
private:
void destroyGLContext();
void onPlatformMakeCurrent() const override;
void onPlatformSwapBuffers() const override;
GrGLFuncPtr onPlatformGetProcAddress(const char*) const override;
EGLContext fContext;
EGLDisplay fDisplay;
EGLSurface fSurface;
};
EGLGLTestContext::EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext)
: fContext(EGL_NO_CONTEXT)
, fDisplay(EGL_NO_DISPLAY)
, fSurface(EGL_NO_SURFACE) {
EGLContext eglShareContext = shareContext ? shareContext->fContext : nullptr;
static const EGLint kEGLContextAttribsForOpenGL[] = {
EGL_NONE
};
static const EGLint kEGLContextAttribsForOpenGLES[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
static const struct {
const EGLint* fContextAttribs;
EGLenum fAPI;
EGLint fRenderableTypeBit;
GrGLStandard fStandard;
} kAPIs[] = {
{ // OpenGL
kEGLContextAttribsForOpenGL,
EGL_OPENGL_API,
EGL_OPENGL_BIT,
kGL_GrGLStandard
},
{ // OpenGL ES. This seems to work for both ES2 and 3 (when available).
kEGLContextAttribsForOpenGLES,
EGL_OPENGL_ES_API,
EGL_OPENGL_ES2_BIT,
kGLES_GrGLStandard
},
};
size_t apiLimit = SK_ARRAY_COUNT(kAPIs);
size_t api = 0;
if (forcedGpuAPI == kGL_GrGLStandard) {
apiLimit = 1;
} else if (forcedGpuAPI == kGLES_GrGLStandard) {
api = 1;
}
SkASSERT(forcedGpuAPI == kNone_GrGLStandard || kAPIs[api].fStandard == forcedGpuAPI);
sk_sp<const GrGLInterface> gl;
for (; nullptr == gl.get() && api < apiLimit; ++api) {
fDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint majorVersion;
EGLint minorVersion;
eglInitialize(fDisplay, &majorVersion, &minorVersion);
#if 0
SkDebugf("VENDOR: %s\n", eglQueryString(fDisplay, EGL_VENDOR));
SkDebugf("APIS: %s\n", eglQueryString(fDisplay, EGL_CLIENT_APIS));
SkDebugf("VERSION: %s\n", eglQueryString(fDisplay, EGL_VERSION));
SkDebugf("EXTENSIONS %s\n", eglQueryString(fDisplay, EGL_EXTENSIONS));
#endif
if (!eglBindAPI(kAPIs[api].fAPI)) {
continue;
}
EGLint numConfigs = 0;
const EGLint configAttribs[] = {
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, kAPIs[api].fRenderableTypeBit,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_NONE
};
EGLConfig surfaceConfig;
if (!eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs)) {
SkDebugf("eglChooseConfig failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
if (0 == numConfigs) {
SkDebugf("No suitable EGL config found.\n");
continue;
}
fContext = eglCreateContext(fDisplay, surfaceConfig, eglShareContext,
kAPIs[api].fContextAttribs);
if (EGL_NO_CONTEXT == fContext) {
SkDebugf("eglCreateContext failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
static const EGLint kSurfaceAttribs[] = {
EGL_WIDTH, 1,
EGL_HEIGHT, 1,
EGL_NONE
};
fSurface = eglCreatePbufferSurface(fDisplay, surfaceConfig, kSurfaceAttribs);
if (EGL_NO_SURFACE == fSurface) {
SkDebugf("eglCreatePbufferSurface failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("eglMakeCurrent failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
gl.reset(GrGLCreateNativeInterface());
if (nullptr == gl.get()) {
SkDebugf("Failed to create gl interface.\n");
this->destroyGLContext();
continue;
}
if (!gl->validate()) {
SkDebugf("Failed to validate gl interface.\n");
this->destroyGLContext();
continue;
}
this->init(gl.release(), EGLFenceSync::MakeIfSupported(fDisplay));
break;
}
}
EGLGLTestContext::~EGLGLTestContext() {
this->teardown();
this->destroyGLContext();
}
void EGLGLTestContext::destroyGLContext() {
if (fDisplay) {
eglMakeCurrent(fDisplay, 0, 0, 0);
if (fContext) {
eglDestroyContext(fDisplay, fContext);
fContext = EGL_NO_CONTEXT;
}
if (fSurface) {
eglDestroySurface(fDisplay, fSurface);
fSurface = EGL_NO_SURFACE;
}
//TODO should we close the display?
fDisplay = EGL_NO_DISPLAY;
}
}
GrEGLImage EGLGLTestContext::texture2DToEGLImage(GrGLuint texID) const {
if (!this->gl()->hasExtension("EGL_KHR_gl_texture_2D_image")) {
return GR_EGL_NO_IMAGE;
}
GrEGLImage img;
GrEGLint attribs[] = { GR_EGL_GL_TEXTURE_LEVEL, 0, GR_EGL_NONE };
GrEGLClientBuffer clientBuffer = reinterpret_cast<GrEGLClientBuffer>(texID);
GR_GL_CALL_RET(this->gl(), img,
EGLCreateImage(fDisplay, fContext, GR_EGL_GL_TEXTURE_2D, clientBuffer, attribs));
return img;
}
void EGLGLTestContext::destroyEGLImage(GrEGLImage image) const {
GR_GL_CALL(this->gl(), EGLDestroyImage(fDisplay, image));
}
GrGLuint EGLGLTestContext::eglImageToExternalTexture(GrEGLImage image) const {
GrGLClearErr(this->gl());
if (!this->gl()->hasExtension("GL_OES_EGL_image_external")) {
return 0;
}
typedef GrGLvoid (*EGLImageTargetTexture2DProc)(GrGLenum, GrGLeglImage);
EGLImageTargetTexture2DProc glEGLImageTargetTexture2D =
(EGLImageTargetTexture2DProc) eglGetProcAddress("glEGLImageTargetTexture2DOES");
if (!glEGLImageTargetTexture2D) {
return 0;
}
GrGLuint texID;
glGenTextures(1, &texID);
if (!texID) {
return 0;
}
glBindTexture(GR_GL_TEXTURE_EXTERNAL, texID);
if (glGetError() != GR_GL_NO_ERROR) {
glDeleteTextures(1, &texID);
return 0;
}
glEGLImageTargetTexture2D(GR_GL_TEXTURE_EXTERNAL, image);
if (glGetError() != GR_GL_NO_ERROR) {
glDeleteTextures(1, &texID);
return 0;
}
return texID;
}
std::unique_ptr<sk_gpu_test::GLTestContext> EGLGLTestContext::makeNew() const {
std::unique_ptr<sk_gpu_test::GLTestContext> ctx(new EGLGLTestContext(this->gl()->fStandard,
nullptr));
if (ctx) {
ctx->makeCurrent();
}
return ctx;
}
void EGLGLTestContext::onPlatformMakeCurrent() const {
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("Could not set the context.\n");
}
}
void EGLGLTestContext::onPlatformSwapBuffers() const {
if (!eglSwapBuffers(fDisplay, fSurface)) {
SkDebugf("Could not complete eglSwapBuffers.\n");
}
}
GrGLFuncPtr EGLGLTestContext::onPlatformGetProcAddress(const char* procName) const {
return eglGetProcAddress(procName);
}
static bool supports_egl_extension(EGLDisplay display, const char* extension) {
size_t extensionLength = strlen(extension);
const char* extensionsStr = eglQueryString(display, EGL_EXTENSIONS);
while (const char* match = strstr(extensionsStr, extension)) {
// Ensure the string we found is its own extension, not a substring of a larger extension
// (e.g. GL_ARB_occlusion_query / GL_ARB_occlusion_query2).
if ((match == extensionsStr || match[-1] == ' ') &&
(match[extensionLength] == ' ' || match[extensionLength] == '\0')) {
return true;
}
extensionsStr = match + extensionLength;
}
return false;
}
std::unique_ptr<EGLFenceSync> EGLFenceSync::MakeIfSupported(EGLDisplay display) {
if (!display || !supports_egl_extension(display, "EGL_KHR_fence_sync")) {
return nullptr;
}
return std::unique_ptr<EGLFenceSync>(new EGLFenceSync(display));
}
sk_gpu_test::PlatformFence EGLFenceSync::insertFence() const {
EGLSyncKHR eglsync = eglCreateSyncKHR(fDisplay, EGL_SYNC_FENCE_KHR, nullptr);
return reinterpret_cast<sk_gpu_test::PlatformFence>(eglsync);
}
bool EGLFenceSync::waitFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
return EGL_CONDITION_SATISFIED_KHR ==
eglClientWaitSyncKHR(fDisplay,
eglsync,
EGL_SYNC_FLUSH_COMMANDS_BIT_KHR,
EGL_FOREVER_KHR);
}
void EGLFenceSync::deleteFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
eglDestroySyncKHR(fDisplay, eglsync);
}
GR_STATIC_ASSERT(sizeof(EGLSyncKHR) <= sizeof(sk_gpu_test::PlatformFence));
} // anonymous namespace
namespace sk_gpu_test {
GLTestContext *CreatePlatformGLTestContext(GrGLStandard forcedGpuAPI,
GLTestContext *shareContext) {
EGLGLTestContext* eglShareContext = reinterpret_cast<EGLGLTestContext*>(shareContext);
EGLGLTestContext *ctx = new EGLGLTestContext(forcedGpuAPI, eglShareContext);
if (!ctx->isValid()) {
delete ctx;
return nullptr;
}
return ctx;
}
} // namespace sk_gpu_test
<commit_msg>Access EGL_KHR_fence_sync via eglGetProcAddress<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/GLTestContext.h"
#define GL_GLEXT_PROTOTYPES
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "gl/GrGLDefines.h"
#include "gl/GrGLUtil.h"
namespace {
// TODO: Share this class with ANGLE if/when it gets support for EGL_KHR_fence_sync.
class EGLFenceSync : public sk_gpu_test::FenceSync {
public:
static std::unique_ptr<EGLFenceSync> MakeIfSupported(EGLDisplay);
sk_gpu_test::PlatformFence SK_WARN_UNUSED_RESULT insertFence() const override;
bool waitFence(sk_gpu_test::PlatformFence fence) const override;
void deleteFence(sk_gpu_test::PlatformFence fence) const override;
private:
EGLFenceSync(EGLDisplay display);
PFNEGLCREATESYNCKHRPROC fEGLCreateSyncKHR;
PFNEGLCLIENTWAITSYNCKHRPROC fEGLClientWaitSyncKHR;
PFNEGLDESTROYSYNCKHRPROC fEGLDestroySyncKHR;
EGLDisplay fDisplay;
typedef sk_gpu_test::FenceSync INHERITED;
};
class EGLGLTestContext : public sk_gpu_test::GLTestContext {
public:
EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext);
~EGLGLTestContext() override;
GrEGLImage texture2DToEGLImage(GrGLuint texID) const override;
void destroyEGLImage(GrEGLImage) const override;
GrGLuint eglImageToExternalTexture(GrEGLImage) const override;
std::unique_ptr<sk_gpu_test::GLTestContext> makeNew() const override;
private:
void destroyGLContext();
void onPlatformMakeCurrent() const override;
void onPlatformSwapBuffers() const override;
GrGLFuncPtr onPlatformGetProcAddress(const char*) const override;
EGLContext fContext;
EGLDisplay fDisplay;
EGLSurface fSurface;
};
EGLGLTestContext::EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext)
: fContext(EGL_NO_CONTEXT)
, fDisplay(EGL_NO_DISPLAY)
, fSurface(EGL_NO_SURFACE) {
EGLContext eglShareContext = shareContext ? shareContext->fContext : nullptr;
static const EGLint kEGLContextAttribsForOpenGL[] = {
EGL_NONE
};
static const EGLint kEGLContextAttribsForOpenGLES[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
static const struct {
const EGLint* fContextAttribs;
EGLenum fAPI;
EGLint fRenderableTypeBit;
GrGLStandard fStandard;
} kAPIs[] = {
{ // OpenGL
kEGLContextAttribsForOpenGL,
EGL_OPENGL_API,
EGL_OPENGL_BIT,
kGL_GrGLStandard
},
{ // OpenGL ES. This seems to work for both ES2 and 3 (when available).
kEGLContextAttribsForOpenGLES,
EGL_OPENGL_ES_API,
EGL_OPENGL_ES2_BIT,
kGLES_GrGLStandard
},
};
size_t apiLimit = SK_ARRAY_COUNT(kAPIs);
size_t api = 0;
if (forcedGpuAPI == kGL_GrGLStandard) {
apiLimit = 1;
} else if (forcedGpuAPI == kGLES_GrGLStandard) {
api = 1;
}
SkASSERT(forcedGpuAPI == kNone_GrGLStandard || kAPIs[api].fStandard == forcedGpuAPI);
sk_sp<const GrGLInterface> gl;
for (; nullptr == gl.get() && api < apiLimit; ++api) {
fDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint majorVersion;
EGLint minorVersion;
eglInitialize(fDisplay, &majorVersion, &minorVersion);
#if 0
SkDebugf("VENDOR: %s\n", eglQueryString(fDisplay, EGL_VENDOR));
SkDebugf("APIS: %s\n", eglQueryString(fDisplay, EGL_CLIENT_APIS));
SkDebugf("VERSION: %s\n", eglQueryString(fDisplay, EGL_VERSION));
SkDebugf("EXTENSIONS %s\n", eglQueryString(fDisplay, EGL_EXTENSIONS));
#endif
if (!eglBindAPI(kAPIs[api].fAPI)) {
continue;
}
EGLint numConfigs = 0;
const EGLint configAttribs[] = {
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, kAPIs[api].fRenderableTypeBit,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_NONE
};
EGLConfig surfaceConfig;
if (!eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs)) {
SkDebugf("eglChooseConfig failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
if (0 == numConfigs) {
SkDebugf("No suitable EGL config found.\n");
continue;
}
fContext = eglCreateContext(fDisplay, surfaceConfig, eglShareContext,
kAPIs[api].fContextAttribs);
if (EGL_NO_CONTEXT == fContext) {
SkDebugf("eglCreateContext failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
static const EGLint kSurfaceAttribs[] = {
EGL_WIDTH, 1,
EGL_HEIGHT, 1,
EGL_NONE
};
fSurface = eglCreatePbufferSurface(fDisplay, surfaceConfig, kSurfaceAttribs);
if (EGL_NO_SURFACE == fSurface) {
SkDebugf("eglCreatePbufferSurface failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("eglMakeCurrent failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
gl.reset(GrGLCreateNativeInterface());
if (nullptr == gl.get()) {
SkDebugf("Failed to create gl interface.\n");
this->destroyGLContext();
continue;
}
if (!gl->validate()) {
SkDebugf("Failed to validate gl interface.\n");
this->destroyGLContext();
continue;
}
this->init(gl.release(), EGLFenceSync::MakeIfSupported(fDisplay));
break;
}
}
EGLGLTestContext::~EGLGLTestContext() {
this->teardown();
this->destroyGLContext();
}
void EGLGLTestContext::destroyGLContext() {
if (fDisplay) {
eglMakeCurrent(fDisplay, 0, 0, 0);
if (fContext) {
eglDestroyContext(fDisplay, fContext);
fContext = EGL_NO_CONTEXT;
}
if (fSurface) {
eglDestroySurface(fDisplay, fSurface);
fSurface = EGL_NO_SURFACE;
}
//TODO should we close the display?
fDisplay = EGL_NO_DISPLAY;
}
}
GrEGLImage EGLGLTestContext::texture2DToEGLImage(GrGLuint texID) const {
if (!this->gl()->hasExtension("EGL_KHR_gl_texture_2D_image")) {
return GR_EGL_NO_IMAGE;
}
GrEGLImage img;
GrEGLint attribs[] = { GR_EGL_GL_TEXTURE_LEVEL, 0, GR_EGL_NONE };
GrEGLClientBuffer clientBuffer = reinterpret_cast<GrEGLClientBuffer>(texID);
GR_GL_CALL_RET(this->gl(), img,
EGLCreateImage(fDisplay, fContext, GR_EGL_GL_TEXTURE_2D, clientBuffer, attribs));
return img;
}
void EGLGLTestContext::destroyEGLImage(GrEGLImage image) const {
GR_GL_CALL(this->gl(), EGLDestroyImage(fDisplay, image));
}
GrGLuint EGLGLTestContext::eglImageToExternalTexture(GrEGLImage image) const {
GrGLClearErr(this->gl());
if (!this->gl()->hasExtension("GL_OES_EGL_image_external")) {
return 0;
}
typedef GrGLvoid (*EGLImageTargetTexture2DProc)(GrGLenum, GrGLeglImage);
EGLImageTargetTexture2DProc glEGLImageTargetTexture2D =
(EGLImageTargetTexture2DProc) eglGetProcAddress("glEGLImageTargetTexture2DOES");
if (!glEGLImageTargetTexture2D) {
return 0;
}
GrGLuint texID;
glGenTextures(1, &texID);
if (!texID) {
return 0;
}
glBindTexture(GR_GL_TEXTURE_EXTERNAL, texID);
if (glGetError() != GR_GL_NO_ERROR) {
glDeleteTextures(1, &texID);
return 0;
}
glEGLImageTargetTexture2D(GR_GL_TEXTURE_EXTERNAL, image);
if (glGetError() != GR_GL_NO_ERROR) {
glDeleteTextures(1, &texID);
return 0;
}
return texID;
}
std::unique_ptr<sk_gpu_test::GLTestContext> EGLGLTestContext::makeNew() const {
std::unique_ptr<sk_gpu_test::GLTestContext> ctx(new EGLGLTestContext(this->gl()->fStandard,
nullptr));
if (ctx) {
ctx->makeCurrent();
}
return ctx;
}
void EGLGLTestContext::onPlatformMakeCurrent() const {
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("Could not set the context.\n");
}
}
void EGLGLTestContext::onPlatformSwapBuffers() const {
if (!eglSwapBuffers(fDisplay, fSurface)) {
SkDebugf("Could not complete eglSwapBuffers.\n");
}
}
GrGLFuncPtr EGLGLTestContext::onPlatformGetProcAddress(const char* procName) const {
return eglGetProcAddress(procName);
}
static bool supports_egl_extension(EGLDisplay display, const char* extension) {
size_t extensionLength = strlen(extension);
const char* extensionsStr = eglQueryString(display, EGL_EXTENSIONS);
while (const char* match = strstr(extensionsStr, extension)) {
// Ensure the string we found is its own extension, not a substring of a larger extension
// (e.g. GL_ARB_occlusion_query / GL_ARB_occlusion_query2).
if ((match == extensionsStr || match[-1] == ' ') &&
(match[extensionLength] == ' ' || match[extensionLength] == '\0')) {
return true;
}
extensionsStr = match + extensionLength;
}
return false;
}
std::unique_ptr<EGLFenceSync> EGLFenceSync::MakeIfSupported(EGLDisplay display) {
if (!display || !supports_egl_extension(display, "EGL_KHR_fence_sync")) {
return nullptr;
}
return std::unique_ptr<EGLFenceSync>(new EGLFenceSync(display));
}
EGLFenceSync::EGLFenceSync(EGLDisplay display)
: fDisplay(display) {
fEGLCreateSyncKHR = (PFNEGLCREATESYNCKHRPROC) eglGetProcAddress("eglCreateSyncKHR");
fEGLClientWaitSyncKHR = (PFNEGLCLIENTWAITSYNCKHRPROC) eglGetProcAddress("eglClientWaitSyncKHR");
fEGLDestroySyncKHR = (PFNEGLDESTROYSYNCKHRPROC) eglGetProcAddress("eglDestroySyncKHR");
SkASSERT(fEGLCreateSyncKHR && fEGLClientWaitSyncKHR && fEGLDestroySyncKHR);
}
sk_gpu_test::PlatformFence EGLFenceSync::insertFence() const {
EGLSyncKHR eglsync = fEGLCreateSyncKHR(fDisplay, EGL_SYNC_FENCE_KHR, nullptr);
return reinterpret_cast<sk_gpu_test::PlatformFence>(eglsync);
}
bool EGLFenceSync::waitFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
return EGL_CONDITION_SATISFIED_KHR ==
fEGLClientWaitSyncKHR(fDisplay,
eglsync,
EGL_SYNC_FLUSH_COMMANDS_BIT_KHR,
EGL_FOREVER_KHR);
}
void EGLFenceSync::deleteFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
fEGLDestroySyncKHR(fDisplay, eglsync);
}
GR_STATIC_ASSERT(sizeof(EGLSyncKHR) <= sizeof(sk_gpu_test::PlatformFence));
} // anonymous namespace
namespace sk_gpu_test {
GLTestContext *CreatePlatformGLTestContext(GrGLStandard forcedGpuAPI,
GLTestContext *shareContext) {
EGLGLTestContext* eglShareContext = reinterpret_cast<EGLGLTestContext*>(shareContext);
EGLGLTestContext *ctx = new EGLGLTestContext(forcedGpuAPI, eglShareContext);
if (!ctx->isValid()) {
delete ctx;
return nullptr;
}
return ctx;
}
} // namespace sk_gpu_test
<|endoftext|> |
<commit_before>#pragma once
/**
@file
@brief unit test class
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#include <stdio.h>
#include <string.h>
#include <string>
#include <list>
#include <iostream>
#include <utility>
#include <cybozu/exception.hpp>
namespace cybozu { namespace test {
class AutoRun {
typedef void (*Func)();
typedef std::list<std::pair<const char*, Func> > UnitTestList;
public:
AutoRun()
: init_(0)
, term_(0)
, okCount_(0)
, ngCount_(0)
, exceptionCount_(0)
{
}
void setup(Func init, Func term)
{
init_ = init;
term_ = term;
}
void append(const char *name, Func func)
{
list_.push_back(std::make_pair(name, func));
}
void set(bool isOK)
{
if (isOK) {
okCount_++;
} else {
ngCount_++;
}
}
std::string getBaseName(const std::string& name) const
{
#ifdef _WIN32
const char sep = '\\';
#else
const char sep = '/';
#endif
size_t pos = name.find_last_of(sep);
std::string ret = name.substr(pos + 1);
pos = ret.find('.');
return ret.substr(0, pos);
}
int run(int, char *argv[])
{
std::string msg;
try {
if (init_) init_();
for (UnitTestList::const_iterator i = list_.begin(), ie = list_.end(); i != ie; ++i) {
std::cout << "ctest:module=" << i->first << std::endl;
try {
(i->second)();
} catch (cybozu::Exception& e) {
exceptionCount_++;
std::cout << "ctest: " << i->first << " is stopped by cybozu::Exception " << e.toString() << std::endl;
} catch (std::exception& e) {
exceptionCount_++;
std::cout << "ctest: " << i->first << " is stopped by std::exception " << e.what() << std::endl;
} catch (...) {
exceptionCount_++;
std::cout << "ctest: " << i->first << " is stopped by an exception" << std::endl;
}
}
if (term_) term_();
} catch (cybozu::Exception& e) {
msg = "ctest:err:" + e.toString();
} catch (...) {
msg = "ctest:err: catch unexpected exception";
}
fflush(stdout);
if (msg.empty()) {
std::cout << "ctest:name=" << getBaseName(*argv)
<< ", module=" << list_.size()
<< ", total=" << (okCount_ + ngCount_ + exceptionCount_)
<< ", ok=" << okCount_
<< ", ng=" << ngCount_
<< ", exception=" << exceptionCount_ << std::endl;
return 0;
} else {
std::cout << msg << std::endl;
return 1;
}
}
private:
Func init_;
Func term_;
int okCount_;
int ngCount_;
int exceptionCount_;
UnitTestList list_;
};
AutoRun autoRun;
void test(bool ret, const std::string& msg, const std::string& param, const char *file, int line)
{
autoRun.set(ret);
if (!ret) {
std::cout << file << "(" << line << "):" << "ctest:" << msg << "(" << param << ");" << std::endl;
}
}
template<typename T, typename U>
bool isEqual(const T& lhs, const U& rhs)
{
return lhs == rhs;
}
bool isEqual(const char *lhs, const char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
bool isEqual(char *lhs, const char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
bool isEqual(const char *lhs, char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
bool isEqual(char *lhs, char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
// avoid to compare float directly
bool isEqual(float lhs, float rhs)
{
union fi {
float f;
uint32_t i;
} lfi, rfi;
lfi.f = lhs;
rfi.f = rhs;
return lfi.i == rfi.i;
}
// avoid to compare double directly
bool isEqual(double lhs, double rhs)
{
union di {
double d;
uint64_t i;
} ldi, rdi;
ldi.d = lhs;
rdi.d = rhs;
return ldi.i == rdi.i;
}
} } // cybozu::test
#ifndef CYBOZU_TEST_DISABLE_AUTO_RUN
int main(int argc, char *argv[])
{
return cybozu::test::autoRun.run(argc, argv);
}
#endif
/**
alert if !x
@param x [in]
*/
#define CYBOZU_TEST_ASSERT(x) cybozu::test::test(!!(x), "CYBOZU_TEST_ASSERT", #x, __FILE__, __LINE__)
/**
alert if x != y
@param x [in]
@param y [in]
*/
#define CYBOZU_TEST_EQUAL(x, y) { \
bool eq = cybozu::test::isEqual(x, y); \
cybozu::test::test(eq, "CYBOZU_TEST_EQUAL", #x ", " #y, __FILE__, __LINE__); \
if (!eq) { \
std::cout << "ctest: lhs=" << (x) << std::endl; \
std::cout << "ctest: rhs=" << (y) << std::endl; \
} \
}
/**
alert if fabs(x, y) >= eps
@param x [in]
@param y [in]
*/
#define CYBOZU_TEST_NEAR(x, y, eps) { \
bool isNear = fabs((x) - (y)) < eps; \
cybozu::test::test(isNear, "CYBOZU_TEST_NEAR", #x ", " #y, __FILE__, __LINE__); \
if (!isNear) { \
std::cout << "ctest: lhs=" << (x) << std::endl; \
std::cout << "ctest: rhs=" << (y) << std::endl; \
} \
}
#define CYBOZU_TEST_EQUAL_POINTER(x, y) { \
bool eq = x == y; \
cybozu::test::test(eq, "CYBOZU_TEST_EQUAL_POINTER", #x ", " #y, __FILE__, __LINE__); \
if (!eq) { \
std::cout << "ctest: lhs=" << (const void*)(x) << std::endl; \
std::cout << "ctest: rhs=" << (const void*)(y) << std::endl; \
} \
}
/**
always alert
@param msg [in]
*/
#define CYBOZU_TEST_FAIL(msg) cybozu::test::test(false, "CYBOZU_TEST_FAIL", msg, __FILE__, __LINE__)
/**
verify message in exception
*/
#define CYBOZU_TEST_EXCEPTION_MESSAGE(statement, Exception, msg) \
{ \
int ret = 0; \
std::string errMsg; \
try { \
statement; \
ret = 1; \
} catch (const Exception& e) { \
errMsg = e.what(); \
if (errMsg.find(msg) == std::string::npos) { \
ret = 2; \
} \
} catch (...) { \
ret = 3; \
} \
if (ret) { \
cybozu::test::autoRun.set(false); \
cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION_MESSAGE", #statement ", " #Exception ", " #msg, __FILE__, __LINE__); \
if (ret == 1) { \
std::cout << "ctest: no exception" << std::endl; \
} else if (ret == 2) { \
std::cout << "ctest: bad exception msg:" << errMsg << std::endl; \
} else { \
std::cout << "ctest: unexpected exception" << std::endl; \
} \
} else { \
cybozu::test::autoRun.set(true); \
} \
}
#define CYBOZU_TEST_EXCEPTION(statement, Exception) \
{ \
int ret = 0; \
try { \
statement; \
ret = 1; \
} catch (const Exception&) { \
} catch (...) { \
ret = 2; \
} \
if (ret) { \
cybozu::test::autoRun.set(false); \
cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION", #statement ", " #Exception, __FILE__, __LINE__); \
if (ret == 1) { \
std::cout << "ctest: no exception" << std::endl; \
} else { \
std::cout << "ctest: unexpected exception" << std::endl; \
} \
} else { \
cybozu::test::autoRun.set(true); \
} \
}
/**
verify statement does not throw
*/
#define CYBOZU_TEST_NO_EXCEPTION(statement) \
try { \
statement; \
cybozu::test::autoRun.set(true); \
} catch (...) { \
cybozu::test::test(false, "CYBOZU_TEST_NO_EXCEPTION", #statement, __FILE__, __LINE__); \
}
/**
append auto unit test
@param name [in] module name
*/
#define CYBOZU_TEST_AUTO(name) \
void cybozu_test_ ## name(); \
struct cybozu_test_local_ ## name { \
cybozu_test_local_ ## name() \
{ \
cybozu::test::autoRun.append(#name, cybozu_test_ ## name); \
} \
} cybozu_test_local_instance_ ## name; \
void cybozu_test_ ## name()
/**
append auto unit test with fixture
@param name [in] module name
*/
#define CYBOZU_TEST_AUTO_WITH_FIXTURE(name, Fixture) \
void cybozu_test_ ## name(); \
void cybozu_test_real_ ## name() \
{ \
Fixture f; \
cybozu_test_ ## name(); \
} \
struct cybozu_test_local_ ## name { \
cybozu_test_local_ ## name() \
{ \
cybozu::test::autoRun.append(#name, cybozu_test_real_ ## name); \
} \
} cybozu_test_local_instance_ ## name; \
void cybozu_test_ ## name()
/**
setup fixture
@param Fixture [in] class name of fixture
@note cstr of Fixture is called before test and dstr of Fixture is called after test
*/
#define CYBOZU_TEST_SETUP_FIXTURE(Fixture) \
Fixture *cybozu_test_local_fixture; \
void cybozu_test_local_init() \
{ \
cybozu_test_local_fixture = new Fixture(); \
} \
void cybozu_test_local_term() \
{ \
delete cybozu_test_local_fixture; \
} \
struct cybozu_test_local_fixture_setup_ { \
cybozu_test_local_fixture_setup_() \
{ \
cybozu::test::autoRun.setup(cybozu_test_local_init, cybozu_test_local_term); \
} \
} cybozu_test_local_fixture_setup_instance_;
<commit_msg>avoid duplicate instance of autoRun for many cpp files<commit_after>#pragma once
/**
@file
@brief unit test class
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#include <stdio.h>
#include <string.h>
#include <string>
#include <list>
#include <iostream>
#include <utility>
#include <cybozu/exception.hpp>
namespace cybozu { namespace test {
class AutoRun {
typedef void (*Func)();
typedef std::list<std::pair<const char*, Func> > UnitTestList;
public:
AutoRun()
: init_(0)
, term_(0)
, okCount_(0)
, ngCount_(0)
, exceptionCount_(0)
{
}
void setup(Func init, Func term)
{
init_ = init;
term_ = term;
}
void append(const char *name, Func func)
{
list_.push_back(std::make_pair(name, func));
}
void set(bool isOK)
{
if (isOK) {
okCount_++;
} else {
ngCount_++;
}
}
std::string getBaseName(const std::string& name) const
{
#ifdef _WIN32
const char sep = '\\';
#else
const char sep = '/';
#endif
size_t pos = name.find_last_of(sep);
std::string ret = name.substr(pos + 1);
pos = ret.find('.');
return ret.substr(0, pos);
}
int run(int, char *argv[])
{
std::string msg;
try {
if (init_) init_();
for (UnitTestList::const_iterator i = list_.begin(), ie = list_.end(); i != ie; ++i) {
std::cout << "ctest:module=" << i->first << std::endl;
try {
(i->second)();
} catch (cybozu::Exception& e) {
exceptionCount_++;
std::cout << "ctest: " << i->first << " is stopped by cybozu::Exception " << e.toString() << std::endl;
} catch (std::exception& e) {
exceptionCount_++;
std::cout << "ctest: " << i->first << " is stopped by std::exception " << e.what() << std::endl;
} catch (...) {
exceptionCount_++;
std::cout << "ctest: " << i->first << " is stopped by an exception" << std::endl;
}
}
if (term_) term_();
} catch (cybozu::Exception& e) {
msg = "ctest:err:" + e.toString();
} catch (...) {
msg = "ctest:err: catch unexpected exception";
}
fflush(stdout);
if (msg.empty()) {
std::cout << "ctest:name=" << getBaseName(*argv)
<< ", module=" << list_.size()
<< ", total=" << (okCount_ + ngCount_ + exceptionCount_)
<< ", ok=" << okCount_
<< ", ng=" << ngCount_
<< ", exception=" << exceptionCount_ << std::endl;
return 0;
} else {
std::cout << msg << std::endl;
return 1;
}
}
static inline AutoRun& getInstance()
{
static AutoRun instance;
return instance;
}
private:
Func init_;
Func term_;
int okCount_;
int ngCount_;
int exceptionCount_;
UnitTestList list_;
};
static AutoRun& autoRun = AutoRun::getInstance();
inline void test(bool ret, const std::string& msg, const std::string& param, const char *file, int line)
{
autoRun.set(ret);
if (!ret) {
std::cout << file << "(" << line << "):" << "ctest:" << msg << "(" << param << ");" << std::endl;
}
}
template<typename T, typename U>
bool isEqual(const T& lhs, const U& rhs)
{
return lhs == rhs;
}
inline bool isEqual(const char *lhs, const char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
inline bool isEqual(char *lhs, const char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
inline bool isEqual(const char *lhs, char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
inline bool isEqual(char *lhs, char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
// avoid to compare float directly
inline bool isEqual(float lhs, float rhs)
{
union fi {
float f;
uint32_t i;
} lfi, rfi;
lfi.f = lhs;
rfi.f = rhs;
return lfi.i == rfi.i;
}
// avoid to compare double directly
inline bool isEqual(double lhs, double rhs)
{
union di {
double d;
uint64_t i;
} ldi, rdi;
ldi.d = lhs;
rdi.d = rhs;
return ldi.i == rdi.i;
}
} } // cybozu::test
#ifndef CYBOZU_TEST_DISABLE_AUTO_RUN
int main(int argc, char *argv[])
{
return cybozu::test::autoRun.run(argc, argv);
}
#endif
/**
alert if !x
@param x [in]
*/
#define CYBOZU_TEST_ASSERT(x) cybozu::test::test(!!(x), "CYBOZU_TEST_ASSERT", #x, __FILE__, __LINE__)
/**
alert if x != y
@param x [in]
@param y [in]
*/
#define CYBOZU_TEST_EQUAL(x, y) { \
bool eq = cybozu::test::isEqual(x, y); \
cybozu::test::test(eq, "CYBOZU_TEST_EQUAL", #x ", " #y, __FILE__, __LINE__); \
if (!eq) { \
std::cout << "ctest: lhs=" << (x) << std::endl; \
std::cout << "ctest: rhs=" << (y) << std::endl; \
} \
}
/**
alert if fabs(x, y) >= eps
@param x [in]
@param y [in]
*/
#define CYBOZU_TEST_NEAR(x, y, eps) { \
bool isNear = fabs((x) - (y)) < eps; \
cybozu::test::test(isNear, "CYBOZU_TEST_NEAR", #x ", " #y, __FILE__, __LINE__); \
if (!isNear) { \
std::cout << "ctest: lhs=" << (x) << std::endl; \
std::cout << "ctest: rhs=" << (y) << std::endl; \
} \
}
#define CYBOZU_TEST_EQUAL_POINTER(x, y) { \
bool eq = x == y; \
cybozu::test::test(eq, "CYBOZU_TEST_EQUAL_POINTER", #x ", " #y, __FILE__, __LINE__); \
if (!eq) { \
std::cout << "ctest: lhs=" << (const void*)(x) << std::endl; \
std::cout << "ctest: rhs=" << (const void*)(y) << std::endl; \
} \
}
/**
always alert
@param msg [in]
*/
#define CYBOZU_TEST_FAIL(msg) cybozu::test::test(false, "CYBOZU_TEST_FAIL", msg, __FILE__, __LINE__)
/**
verify message in exception
*/
#define CYBOZU_TEST_EXCEPTION_MESSAGE(statement, Exception, msg) \
{ \
int ret = 0; \
std::string errMsg; \
try { \
statement; \
ret = 1; \
} catch (const Exception& e) { \
errMsg = e.what(); \
if (errMsg.find(msg) == std::string::npos) { \
ret = 2; \
} \
} catch (...) { \
ret = 3; \
} \
if (ret) { \
cybozu::test::autoRun.set(false); \
cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION_MESSAGE", #statement ", " #Exception ", " #msg, __FILE__, __LINE__); \
if (ret == 1) { \
std::cout << "ctest: no exception" << std::endl; \
} else if (ret == 2) { \
std::cout << "ctest: bad exception msg:" << errMsg << std::endl; \
} else { \
std::cout << "ctest: unexpected exception" << std::endl; \
} \
} else { \
cybozu::test::autoRun.set(true); \
} \
}
#define CYBOZU_TEST_EXCEPTION(statement, Exception) \
{ \
int ret = 0; \
try { \
statement; \
ret = 1; \
} catch (const Exception&) { \
} catch (...) { \
ret = 2; \
} \
if (ret) { \
cybozu::test::autoRun.set(false); \
cybozu::test::test(false, "CYBOZU_TEST_EXCEPTION", #statement ", " #Exception, __FILE__, __LINE__); \
if (ret == 1) { \
std::cout << "ctest: no exception" << std::endl; \
} else { \
std::cout << "ctest: unexpected exception" << std::endl; \
} \
} else { \
cybozu::test::autoRun.set(true); \
} \
}
/**
verify statement does not throw
*/
#define CYBOZU_TEST_NO_EXCEPTION(statement) \
try { \
statement; \
cybozu::test::autoRun.set(true); \
} catch (...) { \
cybozu::test::test(false, "CYBOZU_TEST_NO_EXCEPTION", #statement, __FILE__, __LINE__); \
}
/**
append auto unit test
@param name [in] module name
*/
#define CYBOZU_TEST_AUTO(name) \
void cybozu_test_ ## name(); \
struct cybozu_test_local_ ## name { \
cybozu_test_local_ ## name() \
{ \
cybozu::test::autoRun.append(#name, cybozu_test_ ## name); \
} \
} cybozu_test_local_instance_ ## name; \
void cybozu_test_ ## name()
/**
append auto unit test with fixture
@param name [in] module name
*/
#define CYBOZU_TEST_AUTO_WITH_FIXTURE(name, Fixture) \
void cybozu_test_ ## name(); \
void cybozu_test_real_ ## name() \
{ \
Fixture f; \
cybozu_test_ ## name(); \
} \
struct cybozu_test_local_ ## name { \
cybozu_test_local_ ## name() \
{ \
cybozu::test::autoRun.append(#name, cybozu_test_real_ ## name); \
} \
} cybozu_test_local_instance_ ## name; \
void cybozu_test_ ## name()
/**
setup fixture
@param Fixture [in] class name of fixture
@note cstr of Fixture is called before test and dstr of Fixture is called after test
*/
#define CYBOZU_TEST_SETUP_FIXTURE(Fixture) \
Fixture *cybozu_test_local_fixture; \
void cybozu_test_local_init() \
{ \
cybozu_test_local_fixture = new Fixture(); \
} \
void cybozu_test_local_term() \
{ \
delete cybozu_test_local_fixture; \
} \
struct cybozu_test_local_fixture_setup_ { \
cybozu_test_local_fixture_setup_() \
{ \
cybozu::test::autoRun.setup(cybozu_test_local_init, cybozu_test_local_term); \
} \
} cybozu_test_local_fixture_setup_instance_;
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <common/config.h>
#include <cstring> // memcpy
#include <stdexcept>
#include <unordered_map>
#if VSNRAY_COMMON_HAVE_PBRTPARSER
#include <pbrtParser/Scene.h>
#endif
#include <visionaray/detail/spd/blackbody.h>
#include <visionaray/math/forward.h>
#include <visionaray/math/matrix.h>
#include <visionaray/math/vector.h>
#include "model.h"
#include "sg.h"
namespace visionaray
{
#if VSNRAY_COMMON_HAVE_PBRTPARSER
using namespace pbrt;
mat4 make_mat4(affine3f const& aff)
{
mat4 result = mat4::identity();
result(0, 0) = aff.l.vx.x;
result(1, 0) = aff.l.vx.y;
result(2, 0) = aff.l.vx.z;
result(0, 1) = aff.l.vy.x;
result(1, 1) = aff.l.vy.y;
result(2, 1) = aff.l.vy.z;
result(0, 2) = aff.l.vz.x;
result(1, 2) = aff.l.vz.y;
result(2, 2) = aff.l.vz.z;
result(0, 3) = aff.p.x;
result(1, 3) = aff.p.y;
result(2, 3) = aff.p.z;
return result;
}
std::shared_ptr<sg::material> make_material_node(Shape::SP shape)
{
if (shape->areaLight != nullptr)
{
// TODO: don't misuse obj for emissive
auto obj = std::make_shared<sg::obj_material>();
if (auto l = std::dynamic_pointer_cast<DiffuseAreaLightRGB>(shape->areaLight))
{
obj->ce = vec3(l->L.x, l->L.y, l->L.z);
}
else if (auto l = std::dynamic_pointer_cast<DiffuseAreaLightBB>(shape->areaLight))
{
blackbody bb(l->temperature);
obj->ce = spd_to_rgb(bb) * l->scale; //?
}
return obj;
}
auto mat = shape->material;
if (auto m = std::dynamic_pointer_cast<MetalMaterial>(mat))
{
}
else if (auto m = std::dynamic_pointer_cast<PlasticMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
obj->cs = vec3(m->ks.x, m->ks.y, m->ks.z);
// TODO
obj->specular_exp = m->roughness;
return obj;
}
else if (auto m = std::dynamic_pointer_cast<SubstrateMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
obj->cs = vec3(m->ks.x, m->ks.y, m->ks.z);
// TODO
obj->specular_exp = m->uRoughness;
return obj;
}
else if (auto m = std::dynamic_pointer_cast<MirrorMaterial>(mat))
{
}
else if (auto m = std::dynamic_pointer_cast<MatteMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
return obj;
}
else if (auto m = std::dynamic_pointer_cast<GlassMaterial>(mat))
{
auto glass = std::make_shared<sg::glass_material>();
glass->ct = vec3(m->kt.x, m->kt.y, m->kt.z);
glass->cr = vec3(m->kr.x, m->kr.y, m->kr.z);
glass->ior = vec3(m->index);
return glass;
}
else if (auto m = std::dynamic_pointer_cast<UberMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
obj->cs = vec3(m->ks.x, m->ks.y, m->ks.z);
return obj;
}
return std::make_shared<sg::obj_material>();
}
void make_scene_graph(
Object::SP object,
sg::node& parent,
std::unordered_map<Shape::SP, std::shared_ptr<sg::indexed_triangle_mesh>>& shape2itm,
std::unordered_map<Material::SP, std::shared_ptr<sg::surface_properties>>& mat2prop
)
{
for (auto shape : object->shapes)
{
if (auto sphere = std::dynamic_pointer_cast<Sphere>(shape))
{
mat4 m = mat4::identity();
m = scale(m, vec3(sphere->radius));
m = translate(m, vec3(sphere->transform.p.x, sphere->transform.p.y, sphere->transform.p.z));
auto trans = std::make_shared<sg::transform>();
trans->matrix() = m;
trans->add_child(std::make_shared<sg::sphere>());
// TODO: dedup!!
std::shared_ptr<sg::surface_properties> sp = nullptr;
auto it = mat2prop.find(sphere->material);
if (it != mat2prop.end())
{
sp = it->second;
}
else
{
sp = std::make_shared<sg::surface_properties>();
// TODO
auto mat = make_material_node(sphere);
sp->material() = mat;
mat2prop.insert({ sphere->material, sp });
parent.add_child(sp);
}
bool insert_dummy = true;
if (insert_dummy)
{
// Add a dummy texture
vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);
auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();
tex->resize(1, 1);
tex->set_address_mode(Wrap);
tex->set_filter_mode(Nearest);
tex->reset(&dummy_texel);
sp->add_texture(tex, "diffuse");
}
sp->add_child(trans);
}
if (auto mesh = std::dynamic_pointer_cast<TriangleMesh>(shape))
{
std::shared_ptr<sg::indexed_triangle_mesh> itm = nullptr;
auto itm_it = shape2itm.find(shape);
if (itm_it != shape2itm.end())
{
itm = itm_it->second;
}
else
{
itm = std::make_shared<sg::indexed_triangle_mesh>();
itm->vertices = std::make_shared<aligned_vector<vec3>>(mesh->vertex.size());
if (mesh->normal.size() > 0)
{
itm->normals = std::make_shared<aligned_vector<vec3>>(mesh->normal.size());
}
itm->vertex_indices.resize(mesh->index.size() * 3);
itm->normal_indices.resize(mesh->index.size() * 3);
for (size_t i = 0; i < mesh->vertex.size(); ++i)
{
auto v = mesh->vertex[i];
(*itm->vertices)[i] = vec3(v.x, v.y, v.z);
}
for (size_t i = 0; i < mesh->normal.size(); ++i)
{
auto n = mesh->normal[i];
(*itm->normals)[i] = vec3(n.x, n.y, n.z);
}
for (size_t i = 0; i < mesh->index.size(); ++i)
{
auto i3 = mesh->index[i];
memcpy(itm->vertex_indices.data() + i * 3, &i3.x, sizeof(int) * 3);
memcpy(itm->normal_indices.data() + i * 3, &i3.x, sizeof(int) * 3);
}
// If model has no shading normals, use geometric normals instead
if (itm->normals == nullptr)
{
itm->normals = std::make_shared<aligned_vector<vec3>>(itm->vertex_indices.size());
for (size_t i = 0; i < itm->vertex_indices.size(); i += 3)
{
int i1 = itm->vertex_indices[i];
int i2 = itm->vertex_indices[i + 1];
int i3 = itm->vertex_indices[i + 2];
vec3 v1 = (*itm->vertices)[i1];
vec3 v2 = (*itm->vertices)[i2];
vec3 v3 = (*itm->vertices)[i3];
vec3 n = normalize(cross(v2 - v1, v3 - v1));
(*itm->normals)[i1] = n;
(*itm->normals)[i2] = n;
(*itm->normals)[i3] = n;
}
}
shape2itm.insert({ shape, itm });
}
std::shared_ptr<sg::surface_properties> sp = nullptr;
auto it = mat2prop.find(mesh->material);
if (it != mat2prop.end())
{
sp = it->second;
}
else
{
sp = std::make_shared<sg::surface_properties>();
// TODO
auto mat = make_material_node(mesh);
sp->material() = mat;
mat2prop.insert({ mesh->material, sp });
parent.add_child(sp);
}
bool insert_dummy = true;
if (insert_dummy)
{
// Add a dummy texture
vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);
auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();
tex->resize(1, 1);
tex->set_address_mode(Wrap);
tex->set_filter_mode(Nearest);
tex->reset(&dummy_texel);
sp->add_texture(tex, "diffuse");
}
sp->add_child(itm);
}
}
for (auto inst : object->instances)
{
auto trans = std::make_shared<sg::transform>();
trans->matrix() = make_mat4(inst->xfm);
make_scene_graph(inst->object, *trans, shape2itm, mat2prop);
parent.add_child(trans);
}
}
#endif // VSNRAY_COMMON_HAVE_PBRTPARSER
void load_pbrt(std::string const& filename, model& mod)
{
#if VSNRAY_COMMON_HAVE_PBRTPARSER
auto root = std::make_shared<sg::node>();
// If we find a material that is already in use, we just hang
// the triangle mesh underneath its surface_properties node
// NOTE: this only works because pbrtParser doesn't expose
// transforms
std::unordered_map<Material::SP, std::shared_ptr<sg::surface_properties>> mat2prop;
// List with all shapes that are stored and their corresponding
// triangle mesh nodes, so that instances can refer to them
std::unordered_map<Shape::SP, std::shared_ptr<sg::indexed_triangle_mesh>> shape2itm;
std::shared_ptr<Scene> scene;
try
{
auto scene = importPBRT(filename);
make_scene_graph(scene->world, *root, shape2itm, mat2prop);
}
catch (std::runtime_error e)
{
// TODO
throw e;
}
if (mod.scene_graph == nullptr)
{
mod.scene_graph = root;
}
else
{
mod.scene_graph->add_child(root);
}
#else
VSNRAY_UNUSED(filename, mod);
#endif
}
void load_pbrt(std::vector<std::string> const& filenames, model& mod)
{
// TODO!
for (auto filename : filenames)
{
load_pbrt(filename, mod);
}
}
} // visionaray
<commit_msg>Translate and scale in the right order<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <common/config.h>
#include <cstring> // memcpy
#include <stdexcept>
#include <unordered_map>
#if VSNRAY_COMMON_HAVE_PBRTPARSER
#include <pbrtParser/Scene.h>
#endif
#include <visionaray/detail/spd/blackbody.h>
#include <visionaray/math/forward.h>
#include <visionaray/math/matrix.h>
#include <visionaray/math/vector.h>
#include "model.h"
#include "sg.h"
namespace visionaray
{
#if VSNRAY_COMMON_HAVE_PBRTPARSER
using namespace pbrt;
mat4 make_mat4(affine3f const& aff)
{
mat4 result = mat4::identity();
result(0, 0) = aff.l.vx.x;
result(1, 0) = aff.l.vx.y;
result(2, 0) = aff.l.vx.z;
result(0, 1) = aff.l.vy.x;
result(1, 1) = aff.l.vy.y;
result(2, 1) = aff.l.vy.z;
result(0, 2) = aff.l.vz.x;
result(1, 2) = aff.l.vz.y;
result(2, 2) = aff.l.vz.z;
result(0, 3) = aff.p.x;
result(1, 3) = aff.p.y;
result(2, 3) = aff.p.z;
return result;
}
std::shared_ptr<sg::material> make_material_node(Shape::SP shape)
{
if (shape->areaLight != nullptr)
{
// TODO: don't misuse obj for emissive
auto obj = std::make_shared<sg::obj_material>();
if (auto l = std::dynamic_pointer_cast<DiffuseAreaLightRGB>(shape->areaLight))
{
obj->ce = vec3(l->L.x, l->L.y, l->L.z);
}
else if (auto l = std::dynamic_pointer_cast<DiffuseAreaLightBB>(shape->areaLight))
{
blackbody bb(l->temperature);
obj->ce = spd_to_rgb(bb) * l->scale; //?
}
return obj;
}
auto mat = shape->material;
if (auto m = std::dynamic_pointer_cast<MetalMaterial>(mat))
{
}
else if (auto m = std::dynamic_pointer_cast<PlasticMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
obj->cs = vec3(m->ks.x, m->ks.y, m->ks.z);
// TODO
obj->specular_exp = m->roughness;
return obj;
}
else if (auto m = std::dynamic_pointer_cast<SubstrateMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
obj->cs = vec3(m->ks.x, m->ks.y, m->ks.z);
// TODO
obj->specular_exp = m->uRoughness;
return obj;
}
else if (auto m = std::dynamic_pointer_cast<MirrorMaterial>(mat))
{
}
else if (auto m = std::dynamic_pointer_cast<MatteMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
return obj;
}
else if (auto m = std::dynamic_pointer_cast<GlassMaterial>(mat))
{
auto glass = std::make_shared<sg::glass_material>();
glass->ct = vec3(m->kt.x, m->kt.y, m->kt.z);
glass->cr = vec3(m->kr.x, m->kr.y, m->kr.z);
glass->ior = vec3(m->index);
return glass;
}
else if (auto m = std::dynamic_pointer_cast<UberMaterial>(mat))
{
auto obj = std::make_shared<sg::obj_material>();
obj->cd = vec3(m->kd.x, m->kd.y, m->kd.z);
obj->cs = vec3(m->ks.x, m->ks.y, m->ks.z);
return obj;
}
return std::make_shared<sg::obj_material>();
}
void make_scene_graph(
Object::SP object,
sg::node& parent,
std::unordered_map<Shape::SP, std::shared_ptr<sg::indexed_triangle_mesh>>& shape2itm,
std::unordered_map<Material::SP, std::shared_ptr<sg::surface_properties>>& mat2prop
)
{
for (auto shape : object->shapes)
{
if (auto sphere = std::dynamic_pointer_cast<Sphere>(shape))
{
mat4 m = mat4::identity();
m = translate(m, vec3(sphere->transform.p.x, sphere->transform.p.y, sphere->transform.p.z));
m = scale(m, vec3(sphere->radius));
auto trans = std::make_shared<sg::transform>();
trans->matrix() = m;
trans->add_child(std::make_shared<sg::sphere>());
// TODO: dedup!!
std::shared_ptr<sg::surface_properties> sp = nullptr;
auto it = mat2prop.find(sphere->material);
if (it != mat2prop.end())
{
sp = it->second;
}
else
{
sp = std::make_shared<sg::surface_properties>();
// TODO
auto mat = make_material_node(sphere);
sp->material() = mat;
mat2prop.insert({ sphere->material, sp });
parent.add_child(sp);
}
bool insert_dummy = true;
if (insert_dummy)
{
// Add a dummy texture
vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);
auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();
tex->resize(1, 1);
tex->set_address_mode(Wrap);
tex->set_filter_mode(Nearest);
tex->reset(&dummy_texel);
sp->add_texture(tex, "diffuse");
}
sp->add_child(trans);
}
if (auto mesh = std::dynamic_pointer_cast<TriangleMesh>(shape))
{
std::shared_ptr<sg::indexed_triangle_mesh> itm = nullptr;
auto itm_it = shape2itm.find(shape);
if (itm_it != shape2itm.end())
{
itm = itm_it->second;
}
else
{
itm = std::make_shared<sg::indexed_triangle_mesh>();
itm->vertices = std::make_shared<aligned_vector<vec3>>(mesh->vertex.size());
if (mesh->normal.size() > 0)
{
itm->normals = std::make_shared<aligned_vector<vec3>>(mesh->normal.size());
}
itm->vertex_indices.resize(mesh->index.size() * 3);
itm->normal_indices.resize(mesh->index.size() * 3);
for (size_t i = 0; i < mesh->vertex.size(); ++i)
{
auto v = mesh->vertex[i];
(*itm->vertices)[i] = vec3(v.x, v.y, v.z);
}
for (size_t i = 0; i < mesh->normal.size(); ++i)
{
auto n = mesh->normal[i];
(*itm->normals)[i] = vec3(n.x, n.y, n.z);
}
for (size_t i = 0; i < mesh->index.size(); ++i)
{
auto i3 = mesh->index[i];
memcpy(itm->vertex_indices.data() + i * 3, &i3.x, sizeof(int) * 3);
memcpy(itm->normal_indices.data() + i * 3, &i3.x, sizeof(int) * 3);
}
// If model has no shading normals, use geometric normals instead
if (itm->normals == nullptr)
{
itm->normals = std::make_shared<aligned_vector<vec3>>(itm->vertex_indices.size());
for (size_t i = 0; i < itm->vertex_indices.size(); i += 3)
{
int i1 = itm->vertex_indices[i];
int i2 = itm->vertex_indices[i + 1];
int i3 = itm->vertex_indices[i + 2];
vec3 v1 = (*itm->vertices)[i1];
vec3 v2 = (*itm->vertices)[i2];
vec3 v3 = (*itm->vertices)[i3];
vec3 n = normalize(cross(v2 - v1, v3 - v1));
(*itm->normals)[i1] = n;
(*itm->normals)[i2] = n;
(*itm->normals)[i3] = n;
}
}
shape2itm.insert({ shape, itm });
}
std::shared_ptr<sg::surface_properties> sp = nullptr;
auto it = mat2prop.find(mesh->material);
if (it != mat2prop.end())
{
sp = it->second;
}
else
{
sp = std::make_shared<sg::surface_properties>();
// TODO
auto mat = make_material_node(mesh);
sp->material() = mat;
mat2prop.insert({ mesh->material, sp });
parent.add_child(sp);
}
bool insert_dummy = true;
if (insert_dummy)
{
// Add a dummy texture
vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);
auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();
tex->resize(1, 1);
tex->set_address_mode(Wrap);
tex->set_filter_mode(Nearest);
tex->reset(&dummy_texel);
sp->add_texture(tex, "diffuse");
}
sp->add_child(itm);
}
}
for (auto inst : object->instances)
{
auto trans = std::make_shared<sg::transform>();
trans->matrix() = make_mat4(inst->xfm);
make_scene_graph(inst->object, *trans, shape2itm, mat2prop);
parent.add_child(trans);
}
}
#endif // VSNRAY_COMMON_HAVE_PBRTPARSER
void load_pbrt(std::string const& filename, model& mod)
{
#if VSNRAY_COMMON_HAVE_PBRTPARSER
auto root = std::make_shared<sg::node>();
// If we find a material that is already in use, we just hang
// the triangle mesh underneath its surface_properties node
// NOTE: this only works because pbrtParser doesn't expose
// transforms
std::unordered_map<Material::SP, std::shared_ptr<sg::surface_properties>> mat2prop;
// List with all shapes that are stored and their corresponding
// triangle mesh nodes, so that instances can refer to them
std::unordered_map<Shape::SP, std::shared_ptr<sg::indexed_triangle_mesh>> shape2itm;
std::shared_ptr<Scene> scene;
try
{
auto scene = importPBRT(filename);
make_scene_graph(scene->world, *root, shape2itm, mat2prop);
}
catch (std::runtime_error e)
{
// TODO
throw e;
}
if (mod.scene_graph == nullptr)
{
mod.scene_graph = root;
}
else
{
mod.scene_graph->add_child(root);
}
#else
VSNRAY_UNUSED(filename, mod);
#endif
}
void load_pbrt(std::vector<std::string> const& filenames, model& mod)
{
// TODO!
for (auto filename : filenames)
{
load_pbrt(filename, mod);
}
}
} // visionaray
<|endoftext|> |
<commit_before>//===--- Statistic.cpp - Swift unified stats reporting --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Statistic.h"
#include "swift/Driver/DependencyGraph.h"
#include "llvm/Config/config.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
#include <chrono>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
namespace swift {
using namespace llvm;
using namespace llvm::sys;
static size_t
getChildrenMaxResidentSetSize() {
#if defined(HAVE_GETRUSAGE) && !defined(__HAIKU__)
struct rusage RU;
::getrusage(RUSAGE_CHILDREN, &RU);
return RU.ru_maxrss;
#else
return 0;
#endif
}
static std::string
makeFileName(StringRef Prefix,
StringRef ProgramName,
StringRef AuxName,
StringRef Suffix) {
std::string tmp;
raw_string_ostream stream(tmp);
auto now = std::chrono::system_clock::now();
stream << Prefix
<< "-" << now.time_since_epoch().count()
<< "-" << ProgramName
<< "-" << AuxName
<< "-" << Process::GetRandomNumber()
<< "." << Suffix;
return stream.str();
}
static std::string
makeStatsFileName(StringRef ProgramName,
StringRef AuxName) {
return makeFileName("stats", ProgramName, AuxName, "json");
}
static std::string
makeTraceFileName(StringRef ProgramName,
StringRef AuxName) {
return makeFileName("trace", ProgramName, AuxName, "csv");
}
// LLVM's statistics-reporting machinery is sensitive to filenames containing
// YAML-quote-requiring characters, which occur surprisingly often in the wild;
// we only need a recognizable and likely-unique name for a target here, not an
// exact filename, so we go with a crude approximation. Furthermore, to avoid
// parse ambiguities when "demangling" counters and filenames we exclude hyphens
// and slashes.
static std::string
cleanName(StringRef n) {
std::string tmp;
for (auto c : n) {
if (('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
('0' <= c && c <= '9') ||
(c == '.'))
tmp += c;
else
tmp += '_';
}
return tmp;
}
static std::string
auxName(StringRef ModuleName,
StringRef InputName,
StringRef TripleName,
StringRef OutputType,
StringRef OptType) {
if (InputName.empty()) {
InputName = "all";
}
if (OptType.empty()) {
InputName = "Onone";
}
if (!OutputType.empty() && OutputType.front() == '.') {
OutputType = OutputType.substr(1);
}
if (!OptType.empty() && OptType.front() == '-') {
OptType = OptType.substr(1);
}
return (cleanName(ModuleName)
+ "-" + cleanName(InputName)
+ "-" + cleanName(TripleName)
+ "-" + cleanName(OutputType)
+ "-" + cleanName(OptType));
}
UnifiedStatsReporter::UnifiedStatsReporter(StringRef ProgramName,
StringRef ModuleName,
StringRef InputName,
StringRef TripleName,
StringRef OutputType,
StringRef OptType,
StringRef Directory,
SourceManager *SM,
bool TraceEvents)
: UnifiedStatsReporter(ProgramName,
auxName(ModuleName,
InputName,
TripleName,
OutputType,
OptType),
Directory,
SM, TraceEvents)
{
}
UnifiedStatsReporter::UnifiedStatsReporter(StringRef ProgramName,
StringRef AuxName,
StringRef Directory,
SourceManager *SM,
bool TraceEvents)
: StatsFilename(Directory),
TraceFilename(Directory),
StartedTime(llvm::TimeRecord::getCurrentTime()),
Timer(make_unique<NamedRegionTimer>(AuxName,
"Building Target",
ProgramName, "Running Program")),
SourceMgr(SM)
{
path::append(StatsFilename, makeStatsFileName(ProgramName, AuxName));
path::append(TraceFilename, makeTraceFileName(ProgramName, AuxName));
EnableStatistics(/*PrintOnExit=*/false);
SharedTimer::enableCompilationTimers();
if (TraceEvents)
LastTracedFrontendCounters = make_unique<AlwaysOnFrontendCounters>();
}
UnifiedStatsReporter::AlwaysOnDriverCounters &
UnifiedStatsReporter::getDriverCounters()
{
if (!DriverCounters)
DriverCounters = make_unique<AlwaysOnDriverCounters>();
return *DriverCounters;
}
UnifiedStatsReporter::AlwaysOnFrontendCounters &
UnifiedStatsReporter::getFrontendCounters()
{
if (!FrontendCounters)
FrontendCounters = make_unique<AlwaysOnFrontendCounters>();
return *FrontendCounters;
}
UnifiedStatsReporter::AlwaysOnFrontendRecursiveSharedTimers &
UnifiedStatsReporter::getFrontendRecursiveSharedTimers() {
if (!FrontendRecursiveSharedTimers)
FrontendRecursiveSharedTimers =
make_unique<AlwaysOnFrontendRecursiveSharedTimers>();
return *FrontendRecursiveSharedTimers;
}
void
UnifiedStatsReporter::publishAlwaysOnStatsToLLVM() {
if (FrontendCounters) {
auto &C = getFrontendCounters();
#define FRONTEND_STATISTIC(TY, NAME) \
do { \
static Statistic Stat = {#TY, #NAME, #NAME, {0}, false}; \
Stat += (C).NAME; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef FRONTEND_STATISTIC
}
if (DriverCounters) {
auto &C = getDriverCounters();
#define DRIVER_STATISTIC(NAME) \
do { \
static Statistic Stat = {"Driver", #NAME, #NAME, {0}, false}; \
Stat += (C).NAME; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef DRIVER_STATISTIC
}
}
void
UnifiedStatsReporter::printAlwaysOnStatsAndTimers(raw_ostream &OS) {
// Adapted from llvm::PrintStatisticsJSON
OS << "{\n";
const char *delim = "";
if (FrontendCounters) {
auto &C = getFrontendCounters();
#define FRONTEND_STATISTIC(TY, NAME) \
do { \
OS << delim << "\t\"" #TY "." #NAME "\": " << C.NAME; \
delim = ",\n"; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef FRONTEND_STATISTIC
}
if (DriverCounters) {
auto &C = getDriverCounters();
#define DRIVER_STATISTIC(NAME) \
do { \
OS << delim << "\t\"Driver." #NAME "\": " << C.NAME; \
delim = ",\n"; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef DRIVER_STATISTIC
}
// Print timers.
TimerGroup::printAllJSONValues(OS, delim);
OS << "\n}\n";
OS.flush();
}
UnifiedStatsReporter::FrontendStatsTracer::FrontendStatsTracer(
StringRef Name,
SourceRange const &Range,
UnifiedStatsReporter *Reporter)
: Reporter(Reporter),
SavedTime(llvm::TimeRecord::getCurrentTime()),
Name(Name),
Range(Range)
{
if (Reporter)
Reporter->saveAnyFrontendStatsEvents(*this, true);
}
UnifiedStatsReporter::FrontendStatsTracer::FrontendStatsTracer()
: Reporter(nullptr)
{
}
UnifiedStatsReporter::FrontendStatsTracer&
UnifiedStatsReporter::FrontendStatsTracer::operator=(
FrontendStatsTracer&& other)
{
Reporter = other.Reporter;
SavedTime = other.SavedTime;
Name = other.Name;
Range = other.Range;
other.Reporter = nullptr;
return *this;
}
UnifiedStatsReporter::FrontendStatsTracer::FrontendStatsTracer(
FrontendStatsTracer&& other)
: Reporter(other.Reporter),
SavedTime(other.SavedTime),
Name(other.Name),
Range(other.Range)
{
other.Reporter = nullptr;
}
UnifiedStatsReporter::FrontendStatsTracer::~FrontendStatsTracer()
{
if (Reporter)
Reporter->saveAnyFrontendStatsEvents(*this, false);
}
UnifiedStatsReporter::FrontendStatsTracer
UnifiedStatsReporter::getStatsTracer(StringRef N,
SourceRange const &R)
{
if (LastTracedFrontendCounters)
// Return live tracer object.
return FrontendStatsTracer(N, R, this);
else
// Return inert tracer object.
return FrontendStatsTracer();
}
void
UnifiedStatsReporter::saveAnyFrontendStatsEvents(
FrontendStatsTracer const& T,
bool IsEntry)
{
if (!LastTracedFrontendCounters)
return;
auto Now = llvm::TimeRecord::getCurrentTime();
auto StartUS = uint64_t(1000000.0 * T.SavedTime.getProcessTime());
auto NowUS = uint64_t(1000000.0 * Now.getProcessTime());
auto LiveUS = IsEntry ? 0 : NowUS - StartUS;
auto &C = getFrontendCounters();
#define FRONTEND_STATISTIC(TY, NAME) \
do { \
auto delta = C.NAME - LastTracedFrontendCounters->NAME; \
static char const *name = #TY "." #NAME; \
if (delta != 0) { \
LastTracedFrontendCounters->NAME = C.NAME; \
FrontendStatsEvents.emplace_back(FrontendStatsEvent { \
NowUS, LiveUS, IsEntry, T.Name, name, \
delta, C.NAME, T.Range}); \
} \
} while (0);
#include "swift/Basic/Statistics.def"
#undef FRONTEND_STATISTIC
}
UnifiedStatsReporter::AlwaysOnFrontendRecursiveSharedTimers::
AlwaysOnFrontendRecursiveSharedTimers()
:
#define FRONTEND_RECURSIVE_SHARED_TIMER(ID) ID(#ID),
#include "swift/Basic/Statistics.def"
#undef FRONTEND_RECURSIVE_SHARED_TIMER
dummyInstanceVariableToGetConstructorToParse(0) {
}
UnifiedStatsReporter::~UnifiedStatsReporter()
{
// NB: Timer needs to be Optional<> because it needs to be destructed early;
// LLVM will complain about double-stopping a timer if you tear down a
// NamedRegionTimer after printing all timers. The printing routines were
// designed with more of a global-scope, run-at-process-exit in mind, which
// we're repurposing a bit here.
Timer.reset();
// We currently do this by manual TimeRecord keeping because LLVM has decided
// not to allow access to the Timers inside NamedRegionTimers.
auto ElapsedTime = llvm::TimeRecord::getCurrentTime();
ElapsedTime -= StartedTime;
if (DriverCounters) {
auto &C = getDriverCounters();
C.ChildrenMaxRSS = getChildrenMaxResidentSetSize();
}
if (FrontendCounters) {
auto &C = getFrontendCounters();
// Convenience calculation for crude top-level "absolute speed".
if (C.NumSourceLines != 0 && ElapsedTime.getProcessTime() != 0.0)
C.NumSourceLinesPerSecond = (size_t) (((double)C.NumSourceLines) /
ElapsedTime.getProcessTime());
}
std::error_code EC;
raw_fd_ostream ostream(StatsFilename, EC, fs::F_Append | fs::F_Text);
if (EC)
return;
// We change behavior here depending on whether -DLLVM_ENABLE_STATS and/or
// assertions were on in this build; this is somewhat subtle, but turning on
// all stats for all of LLVM and clang is a bit more expensive and intrusive
// than we want to be in release builds.
//
// - If enabled: we copy all of our "always-on" local stats into LLVM's
// global statistics list, and ask LLVM to manage the printing of them.
//
// - If disabled: we still have our "always-on" local stats to write, and
// LLVM's global _timers_ were still enabled (they're runtime-enabled, not
// compile-time) so we sequence printing our own stats and LLVM's timers
// manually.
#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
publishAlwaysOnStatsToLLVM();
PrintStatisticsJSON(ostream);
#else
printAlwaysOnStatsAndTimers(ostream);
#endif
if (LastTracedFrontendCounters && SourceMgr) {
std::error_code EC;
raw_fd_ostream tstream(TraceFilename, EC, fs::F_Append | fs::F_Text);
if (EC)
return;
tstream << "Time,Live,IsEntry,EventName,CounterName,"
<< "CounterDelta,CounterValue,SourceRange\n";
for (auto const &E : FrontendStatsEvents) {
tstream << E.TimeUSec << ','
<< E.LiveUSec << ','
<< (E.IsEntry ? "\"entry\"," : "\"exit\",")
<< '"' << E.EventName << '"' << ','
<< '"' << E.CounterName << '"' << ','
<< E.CounterDelta << ','
<< E.CounterValue << ',';
tstream << '"';
E.SourceRange.print(tstream, *SourceMgr, false);
tstream << '"' << '\n';
}
}
}
} // namespace swift
<commit_msg>[Stats] Fix typo.<commit_after>//===--- Statistic.cpp - Swift unified stats reporting --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Statistic.h"
#include "swift/Driver/DependencyGraph.h"
#include "llvm/Config/config.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
#include <chrono>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
namespace swift {
using namespace llvm;
using namespace llvm::sys;
static size_t
getChildrenMaxResidentSetSize() {
#if defined(HAVE_GETRUSAGE) && !defined(__HAIKU__)
struct rusage RU;
::getrusage(RUSAGE_CHILDREN, &RU);
return RU.ru_maxrss;
#else
return 0;
#endif
}
static std::string
makeFileName(StringRef Prefix,
StringRef ProgramName,
StringRef AuxName,
StringRef Suffix) {
std::string tmp;
raw_string_ostream stream(tmp);
auto now = std::chrono::system_clock::now();
stream << Prefix
<< "-" << now.time_since_epoch().count()
<< "-" << ProgramName
<< "-" << AuxName
<< "-" << Process::GetRandomNumber()
<< "." << Suffix;
return stream.str();
}
static std::string
makeStatsFileName(StringRef ProgramName,
StringRef AuxName) {
return makeFileName("stats", ProgramName, AuxName, "json");
}
static std::string
makeTraceFileName(StringRef ProgramName,
StringRef AuxName) {
return makeFileName("trace", ProgramName, AuxName, "csv");
}
// LLVM's statistics-reporting machinery is sensitive to filenames containing
// YAML-quote-requiring characters, which occur surprisingly often in the wild;
// we only need a recognizable and likely-unique name for a target here, not an
// exact filename, so we go with a crude approximation. Furthermore, to avoid
// parse ambiguities when "demangling" counters and filenames we exclude hyphens
// and slashes.
static std::string
cleanName(StringRef n) {
std::string tmp;
for (auto c : n) {
if (('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
('0' <= c && c <= '9') ||
(c == '.'))
tmp += c;
else
tmp += '_';
}
return tmp;
}
static std::string
auxName(StringRef ModuleName,
StringRef InputName,
StringRef TripleName,
StringRef OutputType,
StringRef OptType) {
if (InputName.empty()) {
InputName = "all";
}
if (OptType.empty()) {
OptType = "Onone";
}
if (!OutputType.empty() && OutputType.front() == '.') {
OutputType = OutputType.substr(1);
}
if (!OptType.empty() && OptType.front() == '-') {
OptType = OptType.substr(1);
}
return (cleanName(ModuleName)
+ "-" + cleanName(InputName)
+ "-" + cleanName(TripleName)
+ "-" + cleanName(OutputType)
+ "-" + cleanName(OptType));
}
UnifiedStatsReporter::UnifiedStatsReporter(StringRef ProgramName,
StringRef ModuleName,
StringRef InputName,
StringRef TripleName,
StringRef OutputType,
StringRef OptType,
StringRef Directory,
SourceManager *SM,
bool TraceEvents)
: UnifiedStatsReporter(ProgramName,
auxName(ModuleName,
InputName,
TripleName,
OutputType,
OptType),
Directory,
SM, TraceEvents)
{
}
UnifiedStatsReporter::UnifiedStatsReporter(StringRef ProgramName,
StringRef AuxName,
StringRef Directory,
SourceManager *SM,
bool TraceEvents)
: StatsFilename(Directory),
TraceFilename(Directory),
StartedTime(llvm::TimeRecord::getCurrentTime()),
Timer(make_unique<NamedRegionTimer>(AuxName,
"Building Target",
ProgramName, "Running Program")),
SourceMgr(SM)
{
path::append(StatsFilename, makeStatsFileName(ProgramName, AuxName));
path::append(TraceFilename, makeTraceFileName(ProgramName, AuxName));
EnableStatistics(/*PrintOnExit=*/false);
SharedTimer::enableCompilationTimers();
if (TraceEvents)
LastTracedFrontendCounters = make_unique<AlwaysOnFrontendCounters>();
}
UnifiedStatsReporter::AlwaysOnDriverCounters &
UnifiedStatsReporter::getDriverCounters()
{
if (!DriverCounters)
DriverCounters = make_unique<AlwaysOnDriverCounters>();
return *DriverCounters;
}
UnifiedStatsReporter::AlwaysOnFrontendCounters &
UnifiedStatsReporter::getFrontendCounters()
{
if (!FrontendCounters)
FrontendCounters = make_unique<AlwaysOnFrontendCounters>();
return *FrontendCounters;
}
UnifiedStatsReporter::AlwaysOnFrontendRecursiveSharedTimers &
UnifiedStatsReporter::getFrontendRecursiveSharedTimers() {
if (!FrontendRecursiveSharedTimers)
FrontendRecursiveSharedTimers =
make_unique<AlwaysOnFrontendRecursiveSharedTimers>();
return *FrontendRecursiveSharedTimers;
}
void
UnifiedStatsReporter::publishAlwaysOnStatsToLLVM() {
if (FrontendCounters) {
auto &C = getFrontendCounters();
#define FRONTEND_STATISTIC(TY, NAME) \
do { \
static Statistic Stat = {#TY, #NAME, #NAME, {0}, false}; \
Stat += (C).NAME; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef FRONTEND_STATISTIC
}
if (DriverCounters) {
auto &C = getDriverCounters();
#define DRIVER_STATISTIC(NAME) \
do { \
static Statistic Stat = {"Driver", #NAME, #NAME, {0}, false}; \
Stat += (C).NAME; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef DRIVER_STATISTIC
}
}
void
UnifiedStatsReporter::printAlwaysOnStatsAndTimers(raw_ostream &OS) {
// Adapted from llvm::PrintStatisticsJSON
OS << "{\n";
const char *delim = "";
if (FrontendCounters) {
auto &C = getFrontendCounters();
#define FRONTEND_STATISTIC(TY, NAME) \
do { \
OS << delim << "\t\"" #TY "." #NAME "\": " << C.NAME; \
delim = ",\n"; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef FRONTEND_STATISTIC
}
if (DriverCounters) {
auto &C = getDriverCounters();
#define DRIVER_STATISTIC(NAME) \
do { \
OS << delim << "\t\"Driver." #NAME "\": " << C.NAME; \
delim = ",\n"; \
} while (0);
#include "swift/Basic/Statistics.def"
#undef DRIVER_STATISTIC
}
// Print timers.
TimerGroup::printAllJSONValues(OS, delim);
OS << "\n}\n";
OS.flush();
}
UnifiedStatsReporter::FrontendStatsTracer::FrontendStatsTracer(
StringRef Name,
SourceRange const &Range,
UnifiedStatsReporter *Reporter)
: Reporter(Reporter),
SavedTime(llvm::TimeRecord::getCurrentTime()),
Name(Name),
Range(Range)
{
if (Reporter)
Reporter->saveAnyFrontendStatsEvents(*this, true);
}
UnifiedStatsReporter::FrontendStatsTracer::FrontendStatsTracer()
: Reporter(nullptr)
{
}
UnifiedStatsReporter::FrontendStatsTracer&
UnifiedStatsReporter::FrontendStatsTracer::operator=(
FrontendStatsTracer&& other)
{
Reporter = other.Reporter;
SavedTime = other.SavedTime;
Name = other.Name;
Range = other.Range;
other.Reporter = nullptr;
return *this;
}
UnifiedStatsReporter::FrontendStatsTracer::FrontendStatsTracer(
FrontendStatsTracer&& other)
: Reporter(other.Reporter),
SavedTime(other.SavedTime),
Name(other.Name),
Range(other.Range)
{
other.Reporter = nullptr;
}
UnifiedStatsReporter::FrontendStatsTracer::~FrontendStatsTracer()
{
if (Reporter)
Reporter->saveAnyFrontendStatsEvents(*this, false);
}
UnifiedStatsReporter::FrontendStatsTracer
UnifiedStatsReporter::getStatsTracer(StringRef N,
SourceRange const &R)
{
if (LastTracedFrontendCounters)
// Return live tracer object.
return FrontendStatsTracer(N, R, this);
else
// Return inert tracer object.
return FrontendStatsTracer();
}
void
UnifiedStatsReporter::saveAnyFrontendStatsEvents(
FrontendStatsTracer const& T,
bool IsEntry)
{
if (!LastTracedFrontendCounters)
return;
auto Now = llvm::TimeRecord::getCurrentTime();
auto StartUS = uint64_t(1000000.0 * T.SavedTime.getProcessTime());
auto NowUS = uint64_t(1000000.0 * Now.getProcessTime());
auto LiveUS = IsEntry ? 0 : NowUS - StartUS;
auto &C = getFrontendCounters();
#define FRONTEND_STATISTIC(TY, NAME) \
do { \
auto delta = C.NAME - LastTracedFrontendCounters->NAME; \
static char const *name = #TY "." #NAME; \
if (delta != 0) { \
LastTracedFrontendCounters->NAME = C.NAME; \
FrontendStatsEvents.emplace_back(FrontendStatsEvent { \
NowUS, LiveUS, IsEntry, T.Name, name, \
delta, C.NAME, T.Range}); \
} \
} while (0);
#include "swift/Basic/Statistics.def"
#undef FRONTEND_STATISTIC
}
UnifiedStatsReporter::AlwaysOnFrontendRecursiveSharedTimers::
AlwaysOnFrontendRecursiveSharedTimers()
:
#define FRONTEND_RECURSIVE_SHARED_TIMER(ID) ID(#ID),
#include "swift/Basic/Statistics.def"
#undef FRONTEND_RECURSIVE_SHARED_TIMER
dummyInstanceVariableToGetConstructorToParse(0) {
}
UnifiedStatsReporter::~UnifiedStatsReporter()
{
// NB: Timer needs to be Optional<> because it needs to be destructed early;
// LLVM will complain about double-stopping a timer if you tear down a
// NamedRegionTimer after printing all timers. The printing routines were
// designed with more of a global-scope, run-at-process-exit in mind, which
// we're repurposing a bit here.
Timer.reset();
// We currently do this by manual TimeRecord keeping because LLVM has decided
// not to allow access to the Timers inside NamedRegionTimers.
auto ElapsedTime = llvm::TimeRecord::getCurrentTime();
ElapsedTime -= StartedTime;
if (DriverCounters) {
auto &C = getDriverCounters();
C.ChildrenMaxRSS = getChildrenMaxResidentSetSize();
}
if (FrontendCounters) {
auto &C = getFrontendCounters();
// Convenience calculation for crude top-level "absolute speed".
if (C.NumSourceLines != 0 && ElapsedTime.getProcessTime() != 0.0)
C.NumSourceLinesPerSecond = (size_t) (((double)C.NumSourceLines) /
ElapsedTime.getProcessTime());
}
std::error_code EC;
raw_fd_ostream ostream(StatsFilename, EC, fs::F_Append | fs::F_Text);
if (EC)
return;
// We change behavior here depending on whether -DLLVM_ENABLE_STATS and/or
// assertions were on in this build; this is somewhat subtle, but turning on
// all stats for all of LLVM and clang is a bit more expensive and intrusive
// than we want to be in release builds.
//
// - If enabled: we copy all of our "always-on" local stats into LLVM's
// global statistics list, and ask LLVM to manage the printing of them.
//
// - If disabled: we still have our "always-on" local stats to write, and
// LLVM's global _timers_ were still enabled (they're runtime-enabled, not
// compile-time) so we sequence printing our own stats and LLVM's timers
// manually.
#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
publishAlwaysOnStatsToLLVM();
PrintStatisticsJSON(ostream);
#else
printAlwaysOnStatsAndTimers(ostream);
#endif
if (LastTracedFrontendCounters && SourceMgr) {
std::error_code EC;
raw_fd_ostream tstream(TraceFilename, EC, fs::F_Append | fs::F_Text);
if (EC)
return;
tstream << "Time,Live,IsEntry,EventName,CounterName,"
<< "CounterDelta,CounterValue,SourceRange\n";
for (auto const &E : FrontendStatsEvents) {
tstream << E.TimeUSec << ','
<< E.LiveUSec << ','
<< (E.IsEntry ? "\"entry\"," : "\"exit\",")
<< '"' << E.EventName << '"' << ','
<< '"' << E.CounterName << '"' << ','
<< E.CounterDelta << ','
<< E.CounterValue << ',';
tstream << '"';
E.SourceRange.print(tstream, *SourceMgr, false);
tstream << '"' << '\n';
}
}
}
} // namespace swift
<|endoftext|> |
<commit_before>/**
@file Logger.cpp
@author Lime Microsystems
@brief API for reporting error codes and error messages.
*/
#include "Logger.h"
#include <cstdio>
#include <cstring> //strerror
#ifdef _MSC_VER
#define thread_local __declspec( thread )
#include <Windows.h>
#endif
#ifdef __APPLE__
#define thread_local __thread
#endif
#define MAX_MSG_LEN 1024
thread_local int _reportedErrorCode;
thread_local char _reportedErrorMessage[MAX_MSG_LEN];
static const char *errToStr(const int errnum)
{
thread_local static char buff[MAX_MSG_LEN];
#ifdef _MSC_VER
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buff, sizeof(buff), NULL);
return buff;
#else
//http://linux.die.net/man/3/strerror_r
#if ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE) || __APPLE__
strerror_r(errnum, buff, sizeof(buff));
#else
//this version may decide to use its own internal string
return strerror_r(errnum, buff, sizeof(buff));
#endif
return buff;
#endif
}
const char *lime::GetLastErrorMessage(void)
{
return _reportedErrorMessage;
}
int lime::ReportError(const int errnum)
{
return lime::ReportError(errnum, errToStr(errnum));
}
int lime::ReportError(const int errnum, const char *format, va_list argList)
{
_reportedErrorCode = errnum;
vsnprintf(_reportedErrorMessage, MAX_MSG_LEN, format, argList);
lime::log(LOG_LEVEL_ERROR, _reportedErrorMessage);
return errnum;
}
static void defaultLogHandler(const lime::LogLevel level, const char *message)
{
#ifdef NDEBUG
if (level == lime::LOG_LEVEL_DEBUG)
return;
#endif
fprintf(stderr, "%s\n", message);
}
static lime::LogHandler logHandler(&defaultLogHandler);
void lime::log(const LogLevel level, const char *format, va_list argList)
{
char buff[4096];
int ret = vsnprintf(buff, sizeof(buff), format, argList);
if (ret > 0) logHandler(level, buff);
}
void lime::registerLogHandler(const LogHandler handler)
{
logHandler = handler;
}
const char *lime::logLevelToName(const LogLevel level)
{
switch(level)
{
case lime::LOG_LEVEL_CRITICAL: return "CRITICAL";
case lime::LOG_LEVEL_ERROR: return "ERROR";
case lime::LOG_LEVEL_WARNING: return "WARNING";
case lime::LOG_LEVEL_INFO: return "INFO";
case lime::LOG_LEVEL_DEBUG: return "DEBUG";
}
return "";
}
<commit_msg>instead of catching all non-compliant cases, use a !catch all<commit_after>/**
@file Logger.cpp
@author Lime Microsystems
@brief API for reporting error codes and error messages.
*/
#include "Logger.h"
#include <cstdio>
#include <cstring> //strerror
#ifdef _MSC_VER
#define thread_local __declspec( thread )
#include <Windows.h>
#endif
#ifdef __APPLE__
#define thread_local __thread
#endif
#define MAX_MSG_LEN 1024
thread_local int _reportedErrorCode;
thread_local char _reportedErrorMessage[MAX_MSG_LEN];
static const char *errToStr(const int errnum)
{
thread_local static char buff[MAX_MSG_LEN];
#ifdef _MSC_VER
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buff, sizeof(buff), NULL);
return buff;
#else
//http://linux.die.net/man/3/strerror_r
#if !(defined(__GLIBC__) && defined(__GNU_SOURCE))
strerror_r(errnum, buff, sizeof(buff));
#else
//this version may decide to use its own internal string
return strerror_r(errnum, buff, sizeof(buff));
#endif
return buff;
#endif
}
const char *lime::GetLastErrorMessage(void)
{
return _reportedErrorMessage;
}
int lime::ReportError(const int errnum)
{
return lime::ReportError(errnum, errToStr(errnum));
}
int lime::ReportError(const int errnum, const char *format, va_list argList)
{
_reportedErrorCode = errnum;
vsnprintf(_reportedErrorMessage, MAX_MSG_LEN, format, argList);
lime::log(LOG_LEVEL_ERROR, _reportedErrorMessage);
return errnum;
}
static void defaultLogHandler(const lime::LogLevel level, const char *message)
{
#ifdef NDEBUG
if (level == lime::LOG_LEVEL_DEBUG)
return;
#endif
fprintf(stderr, "%s\n", message);
}
static lime::LogHandler logHandler(&defaultLogHandler);
void lime::log(const LogLevel level, const char *format, va_list argList)
{
char buff[4096];
int ret = vsnprintf(buff, sizeof(buff), format, argList);
if (ret > 0) logHandler(level, buff);
}
void lime::registerLogHandler(const LogHandler handler)
{
logHandler = handler;
}
const char *lime::logLevelToName(const LogLevel level)
{
switch(level)
{
case lime::LOG_LEVEL_CRITICAL: return "CRITICAL";
case lime::LOG_LEVEL_ERROR: return "ERROR";
case lime::LOG_LEVEL_WARNING: return "WARNING";
case lime::LOG_LEVEL_INFO: return "INFO";
case lime::LOG_LEVEL_DEBUG: return "DEBUG";
}
return "";
}
<|endoftext|> |
<commit_before>#pragma once
#include <samplog/samplog.hpp>
#include "Singleton.hpp"
#include "Error.hpp"
#include <fmt/format.h>
using samplog::PluginLogger_t;
using samplog::LogLevel;
using samplog::AmxFuncCallInfo;
class DebugInfoManager : public Singleton<DebugInfoManager>
{
friend class Singleton<DebugInfoManager>;
friend class ScopedDebugInfo;
private:
DebugInfoManager() = default;
~DebugInfoManager() = default;
private:
bool m_Available = false;
AMX *m_Amx = nullptr;
std::vector<AmxFuncCallInfo> m_Info;
const char *m_NativeName = nullptr;
private:
void Update(AMX * const amx, const char *func);
void Clear();
public:
inline AMX * const GetCurrentAmx()
{
return m_Amx;
}
inline const decltype(m_Info) &GetCurrentInfo()
{
return m_Info;
}
inline bool IsInfoAvailable()
{
return m_Available;
}
inline const char *GetCurrentNativeName()
{
return m_NativeName;
}
};
class Logger : public Singleton<Logger>
{
friend class Singleton<Logger>;
friend class ScopedDebugInfo;
private:
Logger() :
m_Logger("discord-connector")
{ }
~Logger() = default;
public:
inline bool IsLogLevel(LogLevel level)
{
return m_Logger.IsLogLevel(level);
}
template<typename... Args>
inline void Log(LogLevel level, const char *format, Args &&...args)
{
if (!IsLogLevel(level))
return;
string str = format;
if (sizeof...(args) != 0)
str = fmt::format(format, std::forward<Args>(args)...);
m_Logger.Log(level, str.c_str());
}
template<typename... Args>
inline void Log(LogLevel level, std::vector<AmxFuncCallInfo> const &callinfo,
const char *format, Args &&...args)
{
if (!IsLogLevel(level))
return;
string str = format;
if (sizeof...(args) != 0)
str = fmt::format(format, std::forward<Args>(args)...);
m_Logger.Log(level, str.c_str(), callinfo);
}
// should only be called in native functions
template<typename... Args>
void LogNative(LogLevel level, const char *fmt, Args &&...args)
{
if (!IsLogLevel(level))
return;
if (DebugInfoManager::Get()->GetCurrentAmx() == nullptr)
return; //do nothing, since we're not called from within a native func
string msg = fmt::format("{}: {}",
DebugInfoManager::Get()->GetCurrentNativeName(),
fmt::format(fmt, std::forward<Args>(args)...));
if (DebugInfoManager::Get()->IsInfoAvailable())
Log(level, DebugInfoManager::Get()->GetCurrentInfo(), msg.c_str());
else
Log(level, msg.c_str());
}
template<typename T>
inline void LogNative(const Error<T> &error)
{
LogNative(LogLevel::ERROR, "{} error: {}",
error.module(), error.msg());
}
private:
PluginLogger_t m_Logger;
};
class ScopedDebugInfo
{
public:
ScopedDebugInfo(AMX * const amx, const char *func,
cell * const params, const char *params_format = "");
~ScopedDebugInfo()
{
DebugInfoManager::Get()->Clear();
}
ScopedDebugInfo(const ScopedDebugInfo &rhs) = delete;
};
<commit_msg>minor improvements<commit_after>#pragma once
#include <samplog/samplog.hpp>
#include "Singleton.hpp"
#include "Error.hpp"
#include <fmt/format.h>
using samplog::PluginLogger_t;
using samplog::LogLevel;
using samplog::AmxFuncCallInfo;
class DebugInfoManager : public Singleton<DebugInfoManager>
{
friend class Singleton<DebugInfoManager>;
friend class ScopedDebugInfo;
private:
DebugInfoManager() = default;
~DebugInfoManager() = default;
private:
bool m_Available = false;
AMX *m_Amx = nullptr;
std::vector<AmxFuncCallInfo> m_Info;
const char *m_NativeName = nullptr;
private:
void Update(AMX * const amx, const char *func);
void Clear();
public:
inline AMX * const GetCurrentAmx()
{
return m_Amx;
}
inline const decltype(m_Info) &GetCurrentInfo()
{
return m_Info;
}
inline bool IsInfoAvailable()
{
return m_Available;
}
inline const char *GetCurrentNativeName()
{
return m_NativeName;
}
};
class Logger : public Singleton<Logger>
{
friend class Singleton<Logger>;
friend class ScopedDebugInfo;
private:
Logger() :
m_Logger("discord-connector")
{ }
~Logger() = default;
public:
inline bool IsLogLevel(LogLevel level)
{
return m_Logger.IsLogLevel(level);
}
template<typename... Args>
inline void Log(LogLevel level, const char *msg)
{
m_Logger.Log(level, msg);
}
template<typename... Args>
inline void Log(LogLevel level, const char *format, Args &&...args)
{
auto str = fmt::format(format, std::forward<Args>(args)...);
m_Logger.Log(level, str.c_str());
}
template<typename... Args>
inline void Log(LogLevel level, std::vector<AmxFuncCallInfo> const &callinfo,
const char *msg)
{
m_Logger.Log(level, msg, callinfo);
}
template<typename... Args>
inline void Log(LogLevel level, std::vector<AmxFuncCallInfo> const &callinfo,
const char *format, Args &&...args)
{
auto str = fmt::format(format, std::forward<Args>(args)...);
m_Logger.Log(level, str.c_str(), callinfo);
}
// should only be called in native functions
template<typename... Args>
void LogNative(LogLevel level, const char *fmt, Args &&...args)
{
if (!IsLogLevel(level))
return;
if (DebugInfoManager::Get()->GetCurrentAmx() == nullptr)
return; //do nothing, since we're not called from within a native func
auto msg = fmt::format("{:s}: {:s}",
DebugInfoManager::Get()->GetCurrentNativeName(),
fmt::format(fmt, std::forward<Args>(args)...));
if (DebugInfoManager::Get()->IsInfoAvailable())
Log(level, DebugInfoManager::Get()->GetCurrentInfo(), msg.c_str());
else
Log(level, msg.c_str());
}
template<typename T>
inline void LogNative(const Error<T> &error)
{
LogNative(LogLevel::ERROR, "{} error: {}", error.module(), error.msg());
}
private:
PluginLogger_t m_Logger;
};
class ScopedDebugInfo
{
public:
ScopedDebugInfo(AMX * const amx, const char *func,
cell * const params, const char *params_format = "");
~ScopedDebugInfo()
{
DebugInfoManager::Get()->Clear();
}
ScopedDebugInfo(const ScopedDebugInfo &rhs) = delete;
};
<|endoftext|> |
<commit_before>
#include "neighborhoods.h"
// apply valid and feasable move to the current solution (this)
void Neighborhoods::applyMove(const Move& m) {
switch (m.getmtype()) {
case Move::Ins:
{
// Get a copy of the node we are going to remove
// remove if from v1
Vehicle& v1 = fleet[m.getvid1()];
Trashnode n1 = v1[m.getpos1()]; // TODO can be ref?
v1.remove(m.getpos1());
// Get a reference to vid2
Vehicle& v2 = fleet[m.getvid2()];
// and insert n1 at the appropriate location
v2.insert(n1, m.getpos2());
}
break;
case Move::IntraSw:
{
Vehicle& v1 = fleet[m.getvid1()];
v1.swap(m.getpos1(), m.getpos2());
}
break;
case Move::InterSw:
{
Vehicle& v1 = fleet[m.getvid1()];
Vehicle& v2 = fleet[m.getvid2()];
v1.swap(v2, m.getpos1(), m.getpos2());
}
break;
}
}
// make or simulate making the move and check if the modified
// route(s) are feasable
bool Neighborhoods::isNotFeasible(const Move& m) {
switch (m.getmtype()) {
case Move::Ins:
{
// remove a node will not make the path infeasible
// so we only need to check on inserting it
// copy the vehicle and the node
// so we can change it and then throw it away
assert( m.getvid2()<fleet.size() );
Vehicle v2 = fleet[m.getvid2()];
assert( m.getpos1()<v2.size() );
Trashnode n1 = v2[m.getpos1()];
if (not v2.insert(n1, m.getpos2())) return true;
if (not v2.feasable()) return true;
}
break;
case Move::IntraSw:
{
Vehicle v1 = fleet[m.getvid1()];
if (not v1.swap(m.getpos1(), m.getpos2())) return true;
if (not v1.feasable()) return true;
}
break;
case Move::InterSw:
{
Vehicle v1 = fleet[m.getvid1()];
Vehicle v2 = fleet[m.getvid2()];
if (not v1.swap(v2, m.getpos1(), m.getpos2())) return true;
if (not v1.feasable() or not v2.feasable()) return true;
}
break;
default:
return true;
}
return false;
}
// make or simulate making the move and return the savings
// that it will generate. This would be equivalent to
// savings = oldsolution.getcost() - newsolution.getcost()
double Neighborhoods::getMoveSavings(const Move& m) {
// TODO: improve this, this is probably very inefficient
// for example IF we combined the savings calc with isNotFeasible()
// we can get the savings from the new paths we made.
// we would want to v1.remove(m.getpos1) to get that cost
double oldCost = getCost();
// make a copy of the current solution
// we dont what to modify this as we are const
Neighborhoods newsol = *this;
newsol.applyMove(m);
double newCost = newsol.getCost();
return oldCost - newCost;
}
// this should be dumb and fast as it is called a HUGE number of times
// The Ins move is defined as follows:
// mtype = Move::Ins
// vid1 - vehicle from
// nid1 - node id in vehicle 1
// pos1 - postion of nid1 in vid1
// vid2 - destination vehicle
// nid2 = -1 unused
// pos2 - position to insert nid1 in vid2
//
// Algorithm
// for every pickup node in every vehicle
// create Move objects for moving that node to every position
// in every other route if the Move would be feasable
//
void Neighborhoods::getInsNeighborhood(std::vector<Move>& moves) {
moves.clear();
// iterate through the vechicles (vi, vj)
for (int vi=0; vi<fleet.size(); vi++) {
for (int vj=0; vj<fleet.size(); vj++) {
if (vi==vj) continue;
// iterate through the positions of each path (pi, pj)
// dont exchange the depot in position 0
for (int pi=1; pi<fleet[vi].size(); pi++) {
// dont try to move the dump
if(fleet[vi][pi].isdump()) continue;
for (int pj=1; pj<fleet[vj].size(); pj++) {
// we can't break because we might have multiple dumps
// if we could get the position of the next dump
// we could jump pj forward to it
if (fleet[vj].deltaCargoGeneratesCV(fleet[vi][pi], pj))
continue;
// if we check TWC we can break out if pj/->pi
if (fleet[vj].deltaTimeGeneratesTV(fleet[vi][pi], pj))
break;
// create a move with a dummy savings value
Move m(Move::Ins,
fleet[vi][pi].getnid(), // nid1
-1, // nid2
vi, // vid1
vj, // vid2
pi, // pos1
pj, // pos2
0.0); // dummy savings
// we check two feasable conditions above but
// isNotFeasible tests if the move is possible
// or rejected by the lower level move methods
// TODO see if removing this changes the results
if (isNotFeasible(m)) continue;
// compute the savings and set it in the move
m.setsavings(getMoveSavings(m));
moves.push_back(m);
}
}
}
}
}
// this should be dumb and fast as it is called a HUGE number of times
// IntraSw move is defined as follows:
// mtype = Move::IntraSw
// vid1 - vehicle we are changing
// nid1 - node id 1 that we are swapping
// pos1 - position of nid1 in vid1
// vid2 = -1 unused
// nid2 - node id 2 that will get swapped with node id 1
// pos2 - position of nid2 in vid1
//
// Algorithm
// for every vehicle
// for every pickup node
// try to swap that node to every other position
// within its original vehicle
//
void Neighborhoods::getIntraSwNeighborhood(std::vector<Move>& moves) {
moves.clear();
// iterate through each vehicle (vi)
for (int vi=0; vi<fleet.size(); vi++) {
// iterate through the nodes in the path (pi, pj)
// dont exchange the depot in position 0
for (int pi=1; pi<fleet[vi].size(); pi++) {
// dont try to move the dump
if(fleet[vi][pi].isdump()) continue;
// since we are swapping node, swap(i,j) == swap(j,i)
// we only need to search forward
for (int pj=pi+1; pj<fleet[vi].size(); pj++) {
// dont try to move the dump
if(fleet[vi][pj].isdump()) continue;
// create a move with a dummy savings value
Move m(Move::IntraSw,
fleet[vi][pi].getnid(), // nid1
fleet[vi][pj].getnid(), // nid2
vi, // vid1
-1, // vid2
pi, // pos1
pj, // pos2
0.0); // dummy savings
if (isNotFeasible(m)) continue;
m.setsavings(getMoveSavings(m));
moves.push_back(m);
}
}
}
}
// this should be dumb and fast as it is called a HUGE number of times
// The InterSw move is defined as follows:
// mtype = Move::InterSw
// vid1 - vehicle 1
// nid1 - node id in vehicle 1
// pos1 - postion of nid1 in vid1
// vid2 - vehicle 2
// nid2 = node id in vehicle 2
// pos2 - position od nid2 in vid2
//
void Neighborhoods::getInterSwNeighborhood(std::vector<Move>& moves) {
moves.clear();
// iterate through the vechicles (vi, vj)
for (int vi=0; vi<fleet.size(); vi++) {
for (int vj=0; vj<fleet.size(); vj++) {
if (vi==vj) continue;
// iterate through the positions of each path (pi, pj)
// dont exchange the depot in position 0
for (int pi=1; pi<fleet[vi].size(); pi++) {
// dont try to move the dump
if(fleet[vi][pi].isdump()) continue;
for (int pj=1; pj<fleet[vj].size(); pj++) {
// dont try to move the dump
if(fleet[vj][pj].isdump()) continue;
// create a move with a dummy savings value
Move m(Move::Ins,
fleet[vi][pi].getnid(), // nid1
fleet[vj][pj].getnid(), // nid2
vi, // vid1
vj, // vid2
pi, // pos1
pj, // pos2
0.0); // dummy savings
if (isNotFeasible(m)) continue;
double savings = getMoveSavings(m);
m.setsavings(savings);
moves.push_back(m);
}
}
}
}
}
<commit_msg>Fixed bug after merge.<commit_after>
#include "neighborhoods.h"
// apply valid and feasable move to the current solution (this)
void Neighborhoods::applyMove(const Move& m) {
switch (m.getmtype()) {
case Move::Ins:
{
// Get a copy of the node we are going to remove
// remove if from v1
Vehicle& v1 = fleet[m.getvid1()];
Trashnode n1 = v1[m.getpos1()]; // TODO can be ref?
v1.remove(m.getpos1());
// Get a reference to vid2
Vehicle& v2 = fleet[m.getvid2()];
// and insert n1 at the appropriate location
v2.insert(n1, m.getpos2());
}
break;
case Move::IntraSw:
{
Vehicle& v1 = fleet[m.getvid1()];
v1.swap(m.getpos1(), m.getpos2());
}
break;
case Move::InterSw:
{
Vehicle& v1 = fleet[m.getvid1()];
Vehicle& v2 = fleet[m.getvid2()];
v1.swap(v2, m.getpos1(), m.getpos2());
}
break;
}
}
// make or simulate making the move and check if the modified
// route(s) are feasable
bool Neighborhoods::isNotFeasible(const Move& m) {
switch (m.getmtype()) {
case Move::Ins:
{
// remove a node will not make the path infeasible
// so we only need to check on inserting it
// copy the vehicle and the node
// so we can change it and then throw it away
Vehicle v1 = fleet[m.getvid1()];
assert( m.getvid2()<fleet.size() );
Vehicle v2 = fleet[m.getvid2()];
assert( m.getpos1()<v1.size() );
Trashnode n1 = v1[m.getpos1()];
if (not v2.insert(n1, m.getpos2())) return true;
if (not v2.feasable()) return true;
}
break;
case Move::IntraSw:
{
Vehicle v1 = fleet[m.getvid1()];
if (not v1.swap(m.getpos1(), m.getpos2())) return true;
if (not v1.feasable()) return true;
}
break;
case Move::InterSw:
{
Vehicle v1 = fleet[m.getvid1()];
Vehicle v2 = fleet[m.getvid2()];
if (not v1.swap(v2, m.getpos1(), m.getpos2())) return true;
if (not v1.feasable() or not v2.feasable()) return true;
}
break;
default:
return true;
}
return false;
}
// make or simulate making the move and return the savings
// that it will generate. This would be equivalent to
// savings = oldsolution.getcost() - newsolution.getcost()
double Neighborhoods::getMoveSavings(const Move& m) {
// TODO: improve this, this is probably very inefficient
// for example IF we combined the savings calc with isNotFeasible()
// we can get the savings from the new paths we made.
// we would want to v1.remove(m.getpos1) to get that cost
double oldCost = getCost();
// make a copy of the current solution
// we dont what to modify this as we are const
Neighborhoods newsol = *this;
newsol.applyMove(m);
double newCost = newsol.getCost();
return oldCost - newCost;
}
// this should be dumb and fast as it is called a HUGE number of times
// The Ins move is defined as follows:
// mtype = Move::Ins
// vid1 - vehicle from
// nid1 - node id in vehicle 1
// pos1 - postion of nid1 in vid1
// vid2 - destination vehicle
// nid2 = -1 unused
// pos2 - position to insert nid1 in vid2
//
// Algorithm
// for every pickup node in every vehicle
// create Move objects for moving that node to every position
// in every other route if the Move would be feasable
//
void Neighborhoods::getInsNeighborhood(std::vector<Move>& moves) {
moves.clear();
// iterate through the vechicles (vi, vj)
for (int vi=0; vi<fleet.size(); vi++) {
for (int vj=0; vj<fleet.size(); vj++) {
if (vi==vj) continue;
// iterate through the positions of each path (pi, pj)
// dont exchange the depot in position 0
for (int pi=1; pi<fleet[vi].size(); pi++) {
// dont try to move the dump
if(fleet[vi][pi].isdump()) continue;
for (int pj=1; pj<fleet[vj].size(); pj++) {
// we can't break because we might have multiple dumps
// if we could get the position of the next dump
// we could jump pj forward to it
if (fleet[vj].deltaCargoGeneratesCV(fleet[vi][pi], pj))
continue;
// if we check TWC we can break out if pj/->pi
if (fleet[vj].deltaTimeGeneratesTV(fleet[vi][pi], pj))
break;
// create a move with a dummy savings value
Move m(Move::Ins,
fleet[vi][pi].getnid(), // nid1
-1, // nid2
vi, // vid1
vj, // vid2
pi, // pos1
pj, // pos2
0.0); // dummy savings
// we check two feasable conditions above but
// isNotFeasible tests if the move is possible
// or rejected by the lower level move methods
// TODO see if removing this changes the results
if (isNotFeasible(m)) continue;
// compute the savings and set it in the move
m.setsavings(getMoveSavings(m));
moves.push_back(m);
}
}
}
}
}
// this should be dumb and fast as it is called a HUGE number of times
// IntraSw move is defined as follows:
// mtype = Move::IntraSw
// vid1 - vehicle we are changing
// nid1 - node id 1 that we are swapping
// pos1 - position of nid1 in vid1
// vid2 = -1 unused
// nid2 - node id 2 that will get swapped with node id 1
// pos2 - position of nid2 in vid1
//
// Algorithm
// for every vehicle
// for every pickup node
// try to swap that node to every other position
// within its original vehicle
//
void Neighborhoods::getIntraSwNeighborhood(std::vector<Move>& moves) {
moves.clear();
// iterate through each vehicle (vi)
for (int vi=0; vi<fleet.size(); vi++) {
// iterate through the nodes in the path (pi, pj)
// dont exchange the depot in position 0
for (int pi=1; pi<fleet[vi].size(); pi++) {
// dont try to move the dump
if(fleet[vi][pi].isdump()) continue;
// since we are swapping node, swap(i,j) == swap(j,i)
// we only need to search forward
for (int pj=pi+1; pj<fleet[vi].size(); pj++) {
// dont try to move the dump
if(fleet[vi][pj].isdump()) continue;
// create a move with a dummy savings value
Move m(Move::IntraSw,
fleet[vi][pi].getnid(), // nid1
fleet[vi][pj].getnid(), // nid2
vi, // vid1
-1, // vid2
pi, // pos1
pj, // pos2
0.0); // dummy savings
if (isNotFeasible(m)) continue;
m.setsavings(getMoveSavings(m));
moves.push_back(m);
}
}
}
}
// this should be dumb and fast as it is called a HUGE number of times
// The InterSw move is defined as follows:
// mtype = Move::InterSw
// vid1 - vehicle 1
// nid1 - node id in vehicle 1
// pos1 - postion of nid1 in vid1
// vid2 - vehicle 2
// nid2 = node id in vehicle 2
// pos2 - position od nid2 in vid2
//
void Neighborhoods::getInterSwNeighborhood(std::vector<Move>& moves) {
moves.clear();
// iterate through the vechicles (vi, vj)
for (int vi=0; vi<fleet.size(); vi++) {
for (int vj=0; vj<fleet.size(); vj++) {
if (vi==vj) continue;
// iterate through the positions of each path (pi, pj)
// dont exchange the depot in position 0
for (int pi=1; pi<fleet[vi].size(); pi++) {
// dont try to move the dump
if(fleet[vi][pi].isdump()) continue;
for (int pj=1; pj<fleet[vj].size(); pj++) {
// dont try to move the dump
if(fleet[vj][pj].isdump()) continue;
// create a move with a dummy savings value
Move m(Move::Ins,
fleet[vi][pi].getnid(), // nid1
fleet[vj][pj].getnid(), // nid2
vi, // vid1
vj, // vid2
pi, // pos1
pj, // pos2
0.0); // dummy savings
if (isNotFeasible(m)) continue;
double savings = getMoveSavings(m);
m.setsavings(savings);
moves.push_back(m);
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) 2022 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _TDI_FIXED_TABLE_DATA_IMPL_HPP
#define _TDI_FIXED_TABLE_DATA_IMPL_HPP
#include <tdi/common/tdi_table.hpp>
#include <tdi/common/tdi_table_data.hpp>
#include <tdi_common/tdi_context_info.hpp>
namespace tdi {
namespace pna {
namespace rt {
// FixedFunctionConfigTable ******************
class FixedFunctionTableDataSpec {
public:
FixedFunctionTableDataSpec() {}
FixedFunctionTableDataSpec(const size_t &data_sz) {
std::memset(&fixed_spec_data, 0, sizeof(fixed_spec_data));
data_bytes.reset(new uint8_t[data_sz]());
fixed_spec_data.data_bytes = data_bytes.get();
fixed_spec_data.num_data_bytes = data_sz;
};
tdi_status_t setFixedFunctionData(const tdi::DataFieldInfo &field,
const uint64_t &value,
const uint8_t *value_ptr,
const std::string &value_str,
pipe_data_spec_t *fixed_spec_data);
void getFixedFunctionData(fixed_function_data_spec_t *value,
pipe_data_spec_t *spec_data) const;
void getFixedFunctionDataBytes(const tdi::DataFieldInfo &field,
const size_t size,
uint8_t *value,
pipe_data_spec_t *fixed_spec_data) const;
void getFixedFunctionDataSpec(pipe_data_spec_t *value,
pipe_data_spec_t *fixed_spec_data) const;
pipe_data_spec_t *getFixedFunctionDataSpec() {
return &fixed_spec_data;
}
const pipe_data_spec_t *getFixedFunctionDataSpec() const {
return &fixed_spec_data;
}
void reset() {
std::memset(&fixed_spec_data, 0, sizeof(fixed_spec_data));
}
~FixedFunctionTableDataSpec() {}
pipe_data_spec_t fixed_spec_data {0};
std::unique_ptr<uint8_t[]> data_bytes{nullptr};
};
class FixedFunctionTableData : public tdi::TableData {
public:
FixedFunctionTableData(const tdi::Table *table,
tdi_id_t act_id,
const std::vector<tdi_id_t> &fields)
: tdi::TableData(table, act_id, fields) {
size_t data_sz = 0;
data_sz = static_cast<const RtTableContextInfo *>(
this->table_->tableInfoGet()->tableContextInfoGet())
->maxDataSzGet();
fixed_spec_data_ = new FixedFunctionTableDataSpec(data_sz);
}
~FixedFunctionTableData() {
if (fixed_spec_data_)
delete(fixed_spec_data_);
}
FixedFunctionTableData(const tdi::Table *tbl_obj,
const std::vector<tdi_id_t> &fields)
: FixedFunctionTableData(tbl_obj, 0, fields) {}
tdi_status_t setValue(const tdi_id_t &field_id,
const std::string &value) override;
tdi_status_t setValue(const tdi_id_t &field_id,
const uint64_t &value) override;
tdi_status_t setValue(const tdi_id_t &field_id,
const uint8_t *value,
const size_t &size) override;
tdi_status_t setValue(const tdi_id_t &field_id, const float &value) override;
tdi_status_t getValue(const tdi_id_t &field_id,
uint64_t *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id,
const size_t &size,
uint8_t *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id,
std::string *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id, float *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id,
std::vector<uint64_t> *value) const override;
tdi_status_t resetDerived();
tdi_status_t reset(const tdi_id_t &action_id,
const tdi_id_t &/*container_id*/,
const std::vector<tdi_id_t> &fields);
const uint32_t &numActionOnlyFieldsGet() const {
return num_action_only_fields;
}
pipe_act_fn_hdl_t getActFnHdl() const;
// Functions not exposed
const FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj() const {
return *fixed_spec_data_;
}
FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj() {
return *fixed_spec_data_;
}
const FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj_() const {
return *(spec_data_wraper.get());
}
FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj_() {
return *(spec_data_wraper.get());
}
FixedFunctionTableDataSpec *fixed_spec_data_;
protected:
std::unique_ptr<FixedFunctionTableDataSpec> spec_data_wraper;
private:
tdi_status_t setValueInternal(const tdi_id_t &field_id,
const uint64_t &value,
const uint8_t *value_ptr,
const size_t &s,
const std::string &str_value);
tdi_status_t getValueInternal(const tdi_id_t &field_id,
uint64_t *value,
uint8_t *value_ptr,
const size_t &size) const;
void initializeDataFields();
uint32_t num_action_only_fields = 0;
};
} // namespace rt
} // namespace pna
} // namespace tdi
#endif // _TDI_FIXED_TABLE_DATA_IMPL_HPP
<commit_msg>KW FIX | Fixed function TDI support<commit_after>/*
* Copyright(c) 2022 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _TDI_FIXED_TABLE_DATA_IMPL_HPP
#define _TDI_FIXED_TABLE_DATA_IMPL_HPP
#include <tdi/common/tdi_table.hpp>
#include <tdi/common/tdi_table_data.hpp>
#include <tdi_common/tdi_context_info.hpp>
namespace tdi {
namespace pna {
namespace rt {
// FixedFunctionConfigTable ******************
class FixedFunctionTableDataSpec {
public:
FixedFunctionTableDataSpec() {}
FixedFunctionTableDataSpec(const size_t &data_sz) {
std::memset(&fixed_spec_data, 0, sizeof(fixed_spec_data));
data_bytes.reset(new uint8_t[data_sz]());
fixed_spec_data.data_bytes = data_bytes.get();
fixed_spec_data.num_data_bytes = data_sz;
};
tdi_status_t setFixedFunctionData(const tdi::DataFieldInfo &field,
const uint64_t &value,
const uint8_t *value_ptr,
const std::string &value_str,
pipe_data_spec_t *fixed_spec_data);
void getFixedFunctionData(fixed_function_data_spec_t *value,
pipe_data_spec_t *spec_data) const;
void getFixedFunctionDataBytes(const tdi::DataFieldInfo &field,
const size_t size,
uint8_t *value,
pipe_data_spec_t *fixed_spec_data) const;
void getFixedFunctionDataSpec(pipe_data_spec_t *value,
pipe_data_spec_t *fixed_spec_data) const;
pipe_data_spec_t *getFixedFunctionDataSpec() {
return &fixed_spec_data;
}
const pipe_data_spec_t *getFixedFunctionDataSpec() const {
return &fixed_spec_data;
}
void reset() {
std::memset(&fixed_spec_data, 0, sizeof(fixed_spec_data));
}
~FixedFunctionTableDataSpec() {}
pipe_data_spec_t fixed_spec_data {0};
std::unique_ptr<uint8_t[]> data_bytes{nullptr};
};
class FixedFunctionTableData : public tdi::TableData {
public:
FixedFunctionTableData(const tdi::Table *table,
tdi_id_t act_id,
const std::vector<tdi_id_t> &fields)
: tdi::TableData(table, act_id, fields) {
size_t data_sz = 0;
data_sz = static_cast<const RtTableContextInfo *>(
this->table_->tableInfoGet()->tableContextInfoGet())
->maxDataSzGet();
fixed_spec_data_ = new FixedFunctionTableDataSpec(data_sz);
}
~FixedFunctionTableData() {
if (fixed_spec_data_)
delete(fixed_spec_data_);
}
FixedFunctionTableData(FixedFunctionTableData const &) = delete;
FixedFunctionTableData &operator=(const FixedFunctionTableData&) = delete;
FixedFunctionTableData(const tdi::Table *tbl_obj,
const std::vector<tdi_id_t> &fields)
: FixedFunctionTableData(tbl_obj, 0, fields) {}
tdi_status_t setValue(const tdi_id_t &field_id,
const std::string &value) override;
tdi_status_t setValue(const tdi_id_t &field_id,
const uint64_t &value) override;
tdi_status_t setValue(const tdi_id_t &field_id,
const uint8_t *value,
const size_t &size) override;
tdi_status_t setValue(const tdi_id_t &field_id, const float &value) override;
tdi_status_t getValue(const tdi_id_t &field_id,
uint64_t *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id,
const size_t &size,
uint8_t *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id,
std::string *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id, float *value) const override;
tdi_status_t getValue(const tdi_id_t &field_id,
std::vector<uint64_t> *value) const override;
tdi_status_t resetDerived();
tdi_status_t reset(const tdi_id_t &action_id,
const tdi_id_t &/*container_id*/,
const std::vector<tdi_id_t> &fields);
const uint32_t &numActionOnlyFieldsGet() const {
return num_action_only_fields;
}
pipe_act_fn_hdl_t getActFnHdl() const;
// Functions not exposed
const FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj() const {
return *fixed_spec_data_;
}
FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj() {
return *fixed_spec_data_;
}
const FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj_() const {
return *(spec_data_wraper.get());
}
FixedFunctionTableDataSpec &getFixedFunctionTableDataSpecObj_() {
return *(spec_data_wraper.get());
}
FixedFunctionTableDataSpec *fixed_spec_data_;
protected:
std::unique_ptr<FixedFunctionTableDataSpec> spec_data_wraper;
private:
tdi_status_t setValueInternal(const tdi_id_t &field_id,
const uint64_t &value,
const uint8_t *value_ptr,
const size_t &s,
const std::string &str_value);
tdi_status_t getValueInternal(const tdi_id_t &field_id,
uint64_t *value,
uint8_t *value_ptr,
const size_t &size) const;
void initializeDataFields();
uint32_t num_action_only_fields = 0;
};
} // namespace rt
} // namespace pna
} // namespace tdi
#endif // _TDI_FIXED_TABLE_DATA_IMPL_HPP
<|endoftext|> |
<commit_before>/*!
* \file File componentAnimation.cpp
* \brief Implementation of CompAnim class
*
* This file has the implementation of CompAnim class
*
* \sa componentAnimation.hpp
*/
#include <componentAnimation.hpp>
#include <gameObject.hpp>
#include <camera.hpp>
#include <complib.hpp>
#include <game.hpp>
#include <stateStage.hpp>
#include <txtFuncs.hpp>
#include <assert.h>
// #include <inputManager.hpp>
//! A constructor.
/*!
This is a constructor method of CompAnim class
*/
// Constructor method with no params
CompAnim::CompAnim() {
LOG_METHOD_START("CompAnim::CompAnim (blank)");
}
//! A constructor.
/*!
This is a constructor method of CompAnim class
*/
CompAnim::CompAnim(string filename, CompCollider* temporary_collider) {
LOG_METHOD_START("CompAnim::CompAnim");
LOG_VARIABLE("filename", filename);
LOG_VARIABLE("temporary_collider", temporary_collider.to_string);
assert(filename != "");
assert(temporary_collider != NULL);
string name = "";
string img_file = "";
string function_name = "";
string animFile = "";
string type = "";
int f_count = 0;
int f_counter_x = 0;
int f_counter_y = 0;
int collider_counter = 0;
int function_counter = 0;
float f_timex_axis = 0f;
float y_axis = 0f;
float width = 0f;
float height = 0f;
float r = 0f;
ifstream in(ANIMATION_PATH + filename + ".txt");
// Treats possible file opening error
if (!in.is_open()) {
cerr << "Erro ao abrir arquivo de animação '" << filename << "'" << endl;
}
else {
in >> img_file >> f_count >> f_counter_x >> f_counter_y >> f_time;
sp.Open(img_file, f_counter_x, f_counter_y, f_time, f_count);
colliders.resize(f_count, nullptr);
FOR(i, f_count) {
in >> collider_counter;
if (collider_counter) {
colliders[i] = new CompCollider{};
colliders[i]->entity = entity;
FOR(j, collider_counter) {
//TODO: use rotation
//TODO: different collider types for each coll
in >> x_axis >> y_axis >> width >> height >> r;
colliders[i]->colls.emplace_back(entity,
temporary_collider->colls[0].cType,
Rect{x_axis, y_axis, width, height});
colliders[i]->colls[j].useDefault = temporary_collider->colls[0].useDefault;
colliders[i]->colls[j].active = temporary_collider->colls[0].active;
}
}
else {
// Do nothing
}
in >> function_counter;
FOR(funcI, funcCount) {
in >> function_name;
if (txtFuncsF.count(function_name)) {
frameFunc[i].push_back(txtFuncsF[function_name](in));
}
else {
// Do nothing
}
}
}
in.close();
}
// Changes called value to false if frameFunc has no elements in it
if (frameFunc.count(0)) {
called = false;
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::CompAnim", "constructor");
}
//! A destructor.
/*!
This is a destructor method of CompAnim class
*/
CompAnim::~CompAnim() {
LOG_METHOD_START("CompAnim::~CompAnim");
// Iterates through coliders
assert(colliders != NULL);
FOR(i, colliders.size()) {
// Ignores deletion if current collider equals current frame
if (i == GetCurFrame()) {
continue;
}
else {
// Do nothing
}
delete colliders[i];
}
LOG_METHOD_CLOSE("CompAnim::~CompAnim", "destructor");
}
/*!
@fn int CompAnim::get_frame_count()const
@brief Returns current frame count as a integer
@param none
@return int value of frame count
@warning none
*/
int CompAnim::get_frame_count()const {
LOG_METHOD_START("CompAnim::get_frame_count");
assert(sp != NULL);
LOG_METHOD_CLOSE("CompAnim::get_frame_count", sp.get_frame_count());
return sp.get_frame_count();
}
/*!
@fn int CompAnim::get_current_frame()const
@brief Returns current frame as a integer
@param none
@return int with the number of the current frame
@warning none
*/
int CompAnim::get_current_frame()const {
LOG_METHOD_START("CompAnim::get_current_frame");
assert(sp != NULL);
LOG_METHOD_CLOSE("CompAnim::get_current_frame", sp.get_current_frame());
return sp.get_current_frame();
}
/*!
@fn void CompAnim::set_current_frame(int frame, bool force)
@brief Sets the current frame
@param int frame, bool force
@return void
@warning none
*/
void CompAnim::set_current_frame(int frame, // range: unknown
bool force) {// true to force current frame
LOG_METHOD_START("CompAnim::set_current_frame");
LOG_VARIABLE("frame", frame);
LOG_VARIABLE("force", force);
assert(sp != NULL);
// Set frame as current if it isn't already
if (frame != get_current_frame()) {
sp.SetFrame(frame);
for (auto &foo:frameFunc[frame]) {
foo(GO(entity));
}
called = true;
force = true;
}
else {
// Do nothing
}
// Sets current frame by force
set_current_frame_by_force(frame, force);
LOG_METHOD_CLOSE("CompAnim::set_current_frame", sp.set_current_frame());
}
/*!
@fn void CompAnim::set_current_frame_by_force(int frame, bool force)
@brief Sets the current frame by force
@param int frame, bool force
@return void
@warning none
*/
void CompAnim::set_current_frame_by_force(int frame,
bool force) {
LOG_METHOD_START("CompAnim::set_current_frame_by_force");
LOG_VARIABLE("frame", frame);
LOG_VARIABLE("force", force);
assert(sp != NULL);
// Sets current frame by force
if (force == true) {
// proceeds if frame exists or sets as null
if (colliders[frame] != nullptr) {
GO(entity)->SetComponent(Component::type::t_collider, colliders[frame]);
}
else if (GO(entity)->HasComponent(Component::type::t_collider)) {
GO(entity)->components[Component::type::t_collider] = nullptr;
}
else {
// Do nothing
}
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::set_current_frame_by_force", "void");
}
/*!
@fn bool CompAnim::Looped()const
@brief Returns if the animation is looped (true) or not (false)
@param none
@return bool velue defining if animation is looped or not
@warning none
*/
bool CompAnim::Looped()const {
LOG_METHOD_START("CompAnim::Looped");
assert(sp != NULL);
LOG_METHOD_CLOSE("CompAnim::Looped", sp.Looped());
return sp.Looped();
}
/*!
@fn void CompAnim::Update(float time)
@brief Updates the animation
@param float time
@return void
@warning none
*/
void CompAnim::Update(float time) {
LOG_METHOD_START("CompAnim::Update");
LOG_VARIABLE("time", time);
assert(sp != NULL);
int frame1 = get_current_frame(); //!< Used later for comparrison with next frame
int frame2 = get_current_frame(); //!< Assigns the new frame to this variable for
//!< comparing with the previous one
LOG_VARIABLE("frame1", frame1);
LOG_VARIABLE("frame2", frame2);
// Checks if the animation has not been called and calls it
checks_animation_call(frame1);
sp.Update(time);
set_new_frame(frame1, frame2);
LOG_METHOD_CLOSE("CompAnim::Update", "void");
}
/*!
@fn void CompAnim::checks_animation_call(int frame)
@brief checks if the animation has been called
@param int frame
@return void
@warning none
*/
void CompAnim::checks_animation_call(int frame) {
LOG_METHOD_START("CompAnim::checks_animation_call");
LOG_VARIABLE("frame", frame);
LOG_VARIABLE("called", called);
assert(sp != NULL);
assert(frame > 0);
if (!called) {
// Iterates through frame
for (auto &foo : frameFunc[frame]) {
foo(GO(entity));
}
called = true;
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::checks_animation_call", "void");
}
/*!
@fn void CompAnim::compare_frames(int frame1, int frame2)
@brief compares the frames
@param int frame1, int frame2
@return bool
@warning none
*/
bool CompAnim::compare_frames(int frame1, int frame2) {
LOG_METHOD_START("CompAnim::compare_frames");
LOG_VARIABLE("frame1", frame1);
LOG_VARIABLE("frame2", frame2);
assert(frame1 < 0 or frame2 < 0);
if (frame1 != frame2) {
LOG_METHOD_CLOSE("CompAnim::compare_frames", 'true');
return true;
}
else {
LOG_METHOD_CLOSE("CompAnim::compare_frames", 'false');
return false;
}
}
/*!
@fn void CompAnim::set_new_frame(int frame1, int frame2)
@brief sets the new frame if it is not already set
@param int frame1, int frame2
@return void
@warning none
*/
void set_new_frame(int frame1, int frame2) {
LOG_METHOD_START("CompAnim::set_new_frame");
LOG_VARIABLE("frame1", frame1);
LOG_VARIABLE("frame2", frame2);
assert(frame1 < 0 or frame2 < 0);
// Checks if current frames is the same as the next one, if they're not the
// next frame is set
if (compare_frames(frame1, frame2)) {
called = false;
set_current_frame(frame2, true);
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::set_new_frame", "void");
}
/*!
@fn void CompAnim::Render()
@brief Renders current animation
@param none
@return void
@warning none
*/
void CompAnim::Render() {
LOG_METHOD_START("CompAnim::Render");
assert(sp != NULL);
Vec2 pos = GO(entity)->FullBox().corner().renderPos(); //!< Used to save the
LOG_VARIABLE("pos", pos.to_string());
//!< position to render
assert(pos != NULL);
sp.SetFlipH(GO(entity)->flipped);
sp.Render(pos, GO(entity)->rotation, Camera::zoom);
LOG_METHOD_CLOSE("CompAnim::Render", "void");
}
/*!
@fn void CompAnim::own(GameObject* go)
@brief Sets ownage of a animation to a game object
@param GameObject* go
@return void
@warning none
*/
void CompAnim::own(GameObject* go) {
LOG_METHOD_START("CompAnim::own");
assert(go != NULL);
LOG_VARIABLE("go", go.to_string());
entity = go->uid;
// Iterates through the colliders and defines its ownage if they're not null
for (CompCollider *coll:colliders) {
if (coll != nullptr) {
coll->own(go);
}
else {
// Do nothing
}
}
int frame = get_current_frame();
set_current_frame(frame, true);
LOG_METHOD_CLOSE("CompAnim::own", "void");
}
/*!
@fn Component::type CompAnim::GetType()const
@brief Returns type of the animation as a constant value
@param none
@return Component::type type of the animation
@warning none
*/
Component::type CompAnim::GetType()const {
LOG_METHOD_START("CompAnim::GetType");
LOG_METHOD_CLOSE("CompAnim::GetType", Component::type::t_animation);
return Component::type::t_animation;
}
<commit_msg>[LATE DECLARATION] applies technique to componentAnimation.cpp<commit_after>/*!
* \file File componentAnimation.cpp
* \brief Implementation of CompAnim class
*
* This file has the implementation of CompAnim class
*
* \sa componentAnimation.hpp
*/
#include <componentAnimation.hpp>
#include <gameObject.hpp>
#include <camera.hpp>
#include <complib.hpp>
#include <game.hpp>
#include <stateStage.hpp>
#include <txtFuncs.hpp>
#include <assert.h>
// #include <inputManager.hpp>
//! A constructor.
/*!
This is a constructor method of CompAnim class
*/
// Constructor method with no params
CompAnim::CompAnim() {
LOG_METHOD_START("CompAnim::CompAnim (blank)");
LOG_METHOD_CLOSE("CompAnim::CompAnim (blank)", "constructor");
}
//! A constructor.
/*!
This is a constructor method of CompAnim class
*/
CompAnim::CompAnim(string filename, CompCollider* temporary_collider) {
LOG_METHOD_START("CompAnim::CompAnim");
LOG_VARIABLE("filename", filename);
LOG_VARIABLE("temporary_collider", temporary_collider.to_string);
assert(filename != "");
assert(temporary_collider != NULL);
ifstream in(ANIMATION_PATH + filename + ".txt");
// Treats possible file opening error
if (!in.is_open()) {
cerr << "Erro ao abrir arquivo de animação '" << filename << "'" << endl;
}
else {
string name = "";
string img_file = "";
string animation_file = "";
string type = "";
int f_count = 0;
int f_counter_x = 0;
int f_counter_y = 0;
int collider_counter = 0;
float f_timex_axis = 0f;
float y_axis = 0f;
float width = 0f;
float height = 0f;
float r = 0f;
in >> img_file >> f_count >> f_counter_x >> f_counter_y >> f_time;
sp.Open(img_file, f_counter_x, f_counter_y, f_time, f_count);
colliders.resize(f_count, nullptr);
FOR(i, f_count) {
in >> collider_counter;
if (collider_counter) {
colliders[i] = new CompCollider{};
colliders[i]->entity = entity;
FOR(j, collider_counter) {
in >> x_axis;
in >> y_axis;
in >> width;
in >> height;
in >> r;
colliders[i]->colls.emplace_back(entity,
temporary_collider->colls[0].cType,
Rect{x_axis, y_axis, width, height});
colliders[i]->colls[j].useDefault = temporary_collider->colls[0].useDefault;
colliders[i]->colls[j].active = temporary_collider->colls[0].active;
}
}
else {
// Do nothing
}
int function_counter = 0;
in >> function_counter;
string function_name = "";
FOR(funcI, funcCount) {
in >> function_name;
if (txtFuncsF.count(function_name)) {
frameFunc[i].push_back(txtFuncsF[function_name](in));
}
else {
// Do nothing
}
}
}
in.close();
}
// Changes called value to false if frameFunc has no elements in it
if (frameFunc.count(0)) {
called = false;
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::CompAnim", "constructor");
}
//! A destructor.
/*!
This is a destructor method of CompAnim class
*/
CompAnim::~CompAnim() {
LOG_METHOD_START("CompAnim::~CompAnim");
// Iterates through coliders
assert(colliders != NULL);
FOR(i, colliders.size()) {
// Ignores deletion if current collider equals current frame
if (i == GetCurFrame()) {
continue;
}
else {
// Do nothing
}
delete colliders[i];
}
LOG_METHOD_CLOSE("CompAnim::~CompAnim", "destructor");
}
/*!
@fn int CompAnim::get_frame_count()const
@brief Returns current frame count as a integer
@param none
@return int value of frame count
@warning none
*/
int CompAnim::get_frame_count()const {
LOG_METHOD_START("CompAnim::get_frame_count");
assert(sp != NULL);
LOG_METHOD_CLOSE("CompAnim::get_frame_count", sp.get_frame_count());
return sp.get_frame_count();
}
/*!
@fn int CompAnim::get_current_frame()const
@brief Returns current frame as a integer
@param none
@return int with the number of the current frame
@warning none
*/
int CompAnim::get_current_frame()const {
LOG_METHOD_START("CompAnim::get_current_frame");
assert(sp != NULL);
LOG_METHOD_CLOSE("CompAnim::get_current_frame", sp.get_current_frame());
return sp.get_current_frame();
}
/*!
@fn void CompAnim::set_current_frame(int frame, bool force)
@brief Sets the current frame
@param int frame, bool force
@return void
@warning none
*/
void CompAnim::set_current_frame(int frame, // range: unknown
bool force) {// true to force current frame
LOG_METHOD_START("CompAnim::set_current_frame");
LOG_VARIABLE("frame", frame);
LOG_VARIABLE("force", force);
assert(sp != NULL);
// Set frame as current if it isn't already
if (frame != get_current_frame()) {
sp.SetFrame(frame);
for (auto &foo:frameFunc[frame]) {
foo(GO(entity));
}
called = true;
force = true;
}
else {
// Do nothing
}
// Sets current frame by force
set_current_frame_by_force(frame, force);
LOG_METHOD_CLOSE("CompAnim::set_current_frame", sp.set_current_frame());
}
/*!
@fn void CompAnim::set_current_frame_by_force(int frame, bool force)
@brief Sets the current frame by force
@param int frame, bool force
@return void
@warning none
*/
void CompAnim::set_current_frame_by_force(int frame,
bool force) {
LOG_METHOD_START("CompAnim::set_current_frame_by_force");
LOG_VARIABLE("frame", frame);
LOG_VARIABLE("force", force);
assert(sp != NULL);
// Sets current frame by force
if (force == true) {
// proceeds if frame exists or sets as null
if (colliders[frame] != nullptr) {
GO(entity)->SetComponent(Component::type::t_collider, colliders[frame]);
}
else if (GO(entity)->HasComponent(Component::type::t_collider)) {
GO(entity)->components[Component::type::t_collider] = nullptr;
}
else {
// Do nothing
}
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::set_current_frame_by_force", "void");
}
/*!
@fn bool CompAnim::Looped()const
@brief Returns if the animation is looped (true) or not (false)
@param none
@return bool velue defining if animation is looped or not
@warning none
*/
bool CompAnim::Looped()const {
LOG_METHOD_START("CompAnim::Looped");
assert(sp != NULL);
LOG_METHOD_CLOSE("CompAnim::Looped", sp.Looped());
return sp.Looped();
}
/*!
@fn void CompAnim::Update(float time)
@brief Updates the animation
@param float time
@return void
@warning none
*/
void CompAnim::Update(float time) {
LOG_METHOD_START("CompAnim::Update");
LOG_VARIABLE("time", time);
assert(sp != NULL);
int frame1 = get_current_frame(); //!< Used later for comparrison with next frame
int frame2 = get_current_frame(); //!< Assigns the new frame to this variable for
//!< comparing with the previous one
LOG_VARIABLE("frame1", frame1);
LOG_VARIABLE("frame2", frame2);
// Checks if the animation has not been called and calls it
checks_animation_call(frame1);
sp.Update(time);
set_new_frame(frame1, frame2);
LOG_METHOD_CLOSE("CompAnim::Update", "void");
}
/*!
@fn void CompAnim::checks_animation_call(int frame)
@brief checks if the animation has been called
@param int frame
@return void
@warning none
*/
void CompAnim::checks_animation_call(int frame) {
LOG_METHOD_START("CompAnim::checks_animation_call");
LOG_VARIABLE("frame", frame);
LOG_VARIABLE("called", called);
assert(sp != NULL);
assert(frame > 0);
if (!called) {
// Iterates through frame
for (auto &foo : frameFunc[frame]) {
foo(GO(entity));
}
called = true;
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::checks_animation_call", "void");
}
/*!
@fn void CompAnim::compare_frames(int frame1, int frame2)
@brief compares the frames
@param int frame1, int frame2
@return bool
@warning none
*/
bool CompAnim::compare_frames(int frame1, int frame2) {
LOG_METHOD_START("CompAnim::compare_frames");
LOG_VARIABLE("frame1", frame1);
LOG_VARIABLE("frame2", frame2);
assert(frame1 < 0 or frame2 < 0);
if (frame1 != frame2) {
LOG_METHOD_CLOSE("CompAnim::compare_frames", 'true');
return true;
}
else {
LOG_METHOD_CLOSE("CompAnim::compare_frames", 'false');
return false;
}
}
/*!
@fn void CompAnim::set_new_frame(int frame1, int frame2)
@brief sets the new frame if it is not already set
@param int frame1, int frame2
@return void
@warning none
*/
void set_new_frame(int frame1, int frame2) {
LOG_METHOD_START("CompAnim::set_new_frame");
LOG_VARIABLE("frame1", frame1);
LOG_VARIABLE("frame2", frame2);
assert(frame1 < 0 or frame2 < 0);
// Checks if current frames is the same as the next one, if they're not the
// next frame is set
if (compare_frames(frame1, frame2)) {
called = false;
set_current_frame(frame2, true);
}
else {
// Do nothing
}
LOG_METHOD_CLOSE("CompAnim::set_new_frame", "void");
}
/*!
@fn void CompAnim::Render()
@brief Renders current animation
@param none
@return void
@warning none
*/
void CompAnim::Render() {
LOG_METHOD_START("CompAnim::Render");
assert(sp != NULL);
Vec2 full_box = GO(entity)->FullBox(); //!< Used to save the
//!< position to render
Vec2 corner = full_box.corner();
Vec2 render_pos = corner.renderPos();
LOG_VARIABLE("pos", pos.to_string());
assert(pos != NULL);
sp.SetFlipH(GO(entity)->flipped);
sp.Render(pos, GO(entity)->rotation, Camera::zoom);
LOG_METHOD_CLOSE("CompAnim::Render", "void");
}
/*!
@fn void CompAnim::own(GameObject* go)
@brief Sets ownage of a animation to a game object
@param GameObject* go
@return void
@warning none
*/
void CompAnim::own(GameObject* go) {
LOG_METHOD_START("CompAnim::own");
LOG_VARIABLE("go", go.to_string());
assert(go != NULL);
entity = go->uid;
// Iterates through the colliders and defines its ownage if they're not null
for (CompCollider *coll:colliders) {
if (coll != nullptr) {
coll->own(go);
}
else {
// Do nothing
}
}
int frame = get_current_frame();
set_current_frame(frame, true);
LOG_METHOD_CLOSE("CompAnim::own", "void");
}
/*!
@fn Component::type CompAnim::GetType()const
@brief Returns type of the animation as a constant value
@param none
@return Component::type type of the animation
@warning none
*/
Component::type CompAnim::GetType()const {
LOG_METHOD_START("CompAnim::GetType");
LOG_METHOD_CLOSE("CompAnim::GetType", Component::type::t_animation);
return Component::type::t_animation;
}
<|endoftext|> |
<commit_before>#include <openlane/component_provider.h>
#include <openlane/module.h>
#include <iostream>
typedef uint32_t (*LoadComponentType)(void *ctx);
LoadComponentType LCT;
namespace openlane {
ComponentProvider::ComponentProvider() :
xml_parser()
{
}
ComponentProvider::~ComponentProvider() {
}
ErrorCode ComponentProvider::LoadComponent(const char* filename) {
if (!filename)
return InvalidArgument;
ErrorCode result = parser.Parse(filename);
if (result != Ok)
return result;
DynamicLibrary module;
ErrorCode res = module.Load("./libcomponent1.so");
res = module.GetSymbol("LoadComponent", LCT);
if (Ok == res)
LCT(this);
std::cout << "ComponentProvider::LoadComponent\tfilename=" << filename << std::endl;
return Ok;
}
ErrorCode ComponentProvider::RegisterComponent(uint32_t id, IComponent* c) {
std::cout << "ComponentProvider::RegisterComponent\tfilename=" << id << std::endl;
return Ok;
}
ErrorCode ComponentProvider::UnregisterComponent(uint32_t id, IComponent* c) {
std::cout << "ComponentProvider::UnregisterComponent\tid=" << id << std::endl;
return Ok;
}
} /* openlane */
<commit_msg>Fix component_provider<commit_after>#include <openlane/component_provider.h>
#include <openlane/module.h>
#include <iostream>
typedef uint32_t (*LoadComponentType)(void *ctx);
LoadComponentType LCT;
namespace openlane {
ComponentProvider::ComponentProvider() :
xml_parser()
{
}
ComponentProvider::~ComponentProvider() {
}
ErrorCode ComponentProvider::LoadComponent(const char* filename) {
if (!filename)
return InvalidArgument;
ErrorCode result = xml_parser.Parse(filename);
if (result != Ok)
return result;
DynamicLibrary module;
ErrorCode res = module.Load("./libcomponent1.so");
res = module.GetSymbol("LoadComponent", LCT);
if (Ok == res)
LCT(this);
std::cout << "ComponentProvider::LoadComponent\tfilename=" << filename << std::endl;
return Ok;
}
ErrorCode ComponentProvider::RegisterComponent(uint32_t id, IComponent* c) {
std::cout << "ComponentProvider::RegisterComponent\tfilename=" << id << std::endl;
return Ok;
}
ErrorCode ComponentProvider::UnregisterComponent(uint32_t id, IComponent* c) {
std::cout << "ComponentProvider::UnregisterComponent\tid=" << id << std::endl;
return Ok;
}
} /* openlane */
<|endoftext|> |
<commit_before>#include "support.hpp"
#include <Tchar.h>
// Глобальные переменные:
HINSTANCE hInst; // Указатель приложения
LPCTSTR szWindowClass = _T("Kostyuk");
LPCTSTR szTitle = _T("lab3: input");
const SIZE wndDefaultSize{ 600, 400 };
HGDIOBJ defaultFont = GetStockObject( SYSTEM_FIXED_FONT );
// Основная программа
int APIENTRY WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd )
{
MSG msg;
// Регистрация класса окна
MyRegisterClass( hInstance );
// Создание окна приложения
if ( !InitInstance( hInstance, nShowCmd ) )
{
return FALSE;
}
// Цикл обработки сообщений
while ( GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
return (int) msg.wParam;
}
// FUNCTION: MyRegisterClass()
// Регистрирует класс окна
ATOM MyRegisterClass( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW; // стиль окна
wcex.lpfnWndProc = (WNDPROC)WndProc; // оконная процедура
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance; // указатель приложения
wcex.hIcon = LoadIcon( NULL, IDI_INFORMATION ); // определение иконки
wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); // определение курсора
wcex.hbrBackground = GetSysColorBrush( COLOR_WINDOW ); // установка фона
wcex.lpszMenuName = NULL; // определение меню
wcex.lpszClassName = szWindowClass; // имя класса
wcex.hIconSm = NULL;
return RegisterClassEx( &wcex ); // регистрация класса окна
}
// FUNCTION: InitInstance(HANDLE, int)
// Создает окно приложения и сохраняет указатель приложения в переменной hInst
BOOL InitInstance( HINSTANCE hInstance, int nCmdShow )
{
HWND hWnd;
hInst = hInstance; // сохраняет указатель приложения в переменной hInst
const RECT screenField{
0, 0,
GetSystemMetrics( SM_CXSCREEN ),
GetSystemMetrics( SM_CYSCREEN )
};
const POINT wndPos = GetCenternedPosition( wndDefaultSize, screenField );
hWnd = CreateWindow( szWindowClass, // имя класса окна
szTitle, // имя приложения
WS_MINIMIZEBOX | WS_TILED | WS_SIZEBOX | WS_SYSMENU, // стиль окна
wndPos.x, // положение по Х
wndPos.y, // положение по Y
wndDefaultSize.cx, // размер по Х
wndDefaultSize.cy, // размер по Y
NULL, // описатель родительского окна
NULL, // описатель меню окна
hInstance, // указатель приложения
NULL ); // параметры создания.
if ( !hWnd ) // Если окно не создалось, функция возвращает FALSE
return FALSE;
ShowWindow( hWnd, nCmdShow ); // Показать окно
UpdateWindow( hWnd ); // Обновить окно
return TRUE; //Успешное завершение функции
}
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
// Оконная процедура. Принимает и обрабатывает все сообщения, приходящие в приложение
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
PAINTSTRUCT ps;
HDC hdc;
static TEXTMETRIC tm;
static SIZE charSize;
static RECT clientRect;
static StdStringType buffer;
static int currCharPosition = 0;
static std::vector< StringInfo > preparedText;
int xPadding = 10;
static int maxCharsInLine;
static POINT caretPosition{ 0, 0 };
static Direction caretMoveDirection;
TCHAR debug[ 30 ];
switch ( message )
{
// Сообщение приходит при создании окна
case WM_CREATE:
hdc = GetDC( hWnd );
SelectObject( hdc, defaultFont );
GetTextMetrics( hdc, &tm );
charSize.cx = tm.tmAveCharWidth;
charSize.cy = tm.tmHeight;
ReleaseDC( hWnd, hdc );
break;
// Изменение размеров окна
case WM_SIZE:
GetClientRect( hWnd, &clientRect );
maxCharsInLine = (int)( (clientRect.right - clientRect.left - (xPadding << 1)) / charSize.cx );
break;
// Перерисовать окно
case WM_PAINT:
// Ставим каретку на место
CaretWinPosSetter( caretPosition, charSize, xPadding );
// Начать графический вывод
hdc = BeginPaint( hWnd, &ps );
// Выбираем моноширинный шрифт
SelectObject( hdc, defaultFont );
// Вывод информации
DrawSavedText( hdc, preparedText, charSize, xPadding );
//TODO: Удалить строку ниже, нужна для дебага
TextOut( hdc, xPadding, clientRect.bottom - 10, debug, wsprintf( debug, _T("%d %d %d"), currCharPosition, buffer.size(), preparedText.size() ) );
// Закончить графический вывод
EndPaint( hWnd, &ps );
break;
// Нажатие ЛКМ - фиксирование позиции курсора
//case WM_LBUTTONUP:
//break;
case WM_SETFOCUS:
// Широкая каретка (rewrite mode)
//CreateCaret( hWnd, NULL, xPadding, charSize.cy );
// Каретка-палка (insert mode)
CreateCaret( hWnd, (HBITMAP)0, 0, charSize.cy );
CaretWinPosSetter( caretPosition, charSize, xPadding );
ShowCaret( hWnd );
break;
case WM_KILLFOCUS:
HideCaret( hWnd );
DestroyCaret();
break;
// Обработка нажатия системных клавиш
case WM_KEYDOWN:
switch ( wParam ) {
case VK_DELETE:
if ( currCharPosition < buffer.size() )
buffer.erase( currCharPosition, 1 );
PrepareText( buffer, preparedText, charSize, maxCharsInLine );
InvalidateRect( hWnd, NULL, TRUE );
break;
case VK_LEFT:
if ( currCharPosition > 0 ) {
MoveCaret( caretPosition, Direction::LEFT, preparedText );
//--currCharPosition;
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
}
break;
case VK_RIGHT:
if ( currCharPosition < buffer.size() ) {
MoveCaret( caretPosition, Direction::RIGHT, preparedText );
//++currCharPosition;
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
}
break;
case VK_UP:
MoveCaret( caretPosition, Direction::UP, preparedText );
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
break;
case VK_DOWN:
MoveCaret( caretPosition, Direction::DOWN, preparedText );
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
break;
default:
break;
}
CaretWinPosSetter( caretPosition, charSize, xPadding );
// TODO: Убрать строку ниже, она нужна для дебага
InvalidateRect( hWnd, NULL, TRUE );
break;
case WM_CHAR:
switch ( wParam )
{
// New line
case '\r':
buffer.insert( currCharPosition, 1, '\n' );
//++ currCharPosition;
caretMoveDirection = Direction::RIGHT;
break;
// Backspace
case '\b':
if ( currCharPosition > 0 ) {
//-- currCharPosition;
buffer.erase( currCharPosition - 1, 1 );
caretMoveDirection = Direction::LEFT;
}
break;
// Escape
/*case '\x1B':
break;
*/
// Other symbols
default:
buffer.insert( currCharPosition, 1, (TCHAR) wParam );
//++ currCharPosition;
caretMoveDirection = Direction::RIGHT;
break;
}
PrepareText( buffer, preparedText, charSize, maxCharsInLine );
MoveCaret( caretPosition, caretMoveDirection, preparedText );
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
InvalidateRect( hWnd, NULL, TRUE );
break;
case WM_DESTROY: // Завершение работы
PostQuitMessage( 0 );
break;
default:
// Обработка сообщений, которые не обработаны пользователем
return DefWindowProc( hWnd, message, wParam, lParam );
}
return 0;
}<commit_msg>Removed debug info<commit_after>#include "support.hpp"
#include <Tchar.h>
// Глобальные переменные:
HINSTANCE hInst; // Указатель приложения
LPCTSTR szWindowClass = _T("Kostyuk");
LPCTSTR szTitle = _T("lab3: input");
const SIZE wndDefaultSize{ 600, 400 };
HGDIOBJ defaultFont = GetStockObject( SYSTEM_FIXED_FONT );
// Основная программа
int APIENTRY WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd )
{
MSG msg;
// Регистрация класса окна
MyRegisterClass( hInstance );
// Создание окна приложения
if ( !InitInstance( hInstance, nShowCmd ) )
{
return FALSE;
}
// Цикл обработки сообщений
while ( GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
return (int) msg.wParam;
}
// FUNCTION: MyRegisterClass()
// Регистрирует класс окна
ATOM MyRegisterClass( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW; // стиль окна
wcex.lpfnWndProc = (WNDPROC)WndProc; // оконная процедура
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance; // указатель приложения
wcex.hIcon = LoadIcon( NULL, IDI_INFORMATION ); // определение иконки
wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); // определение курсора
wcex.hbrBackground = GetSysColorBrush( COLOR_WINDOW ); // установка фона
wcex.lpszMenuName = NULL; // определение меню
wcex.lpszClassName = szWindowClass; // имя класса
wcex.hIconSm = NULL;
return RegisterClassEx( &wcex ); // регистрация класса окна
}
// FUNCTION: InitInstance(HANDLE, int)
// Создает окно приложения и сохраняет указатель приложения в переменной hInst
BOOL InitInstance( HINSTANCE hInstance, int nCmdShow )
{
HWND hWnd;
hInst = hInstance; // сохраняет указатель приложения в переменной hInst
const RECT screenField{
0, 0,
GetSystemMetrics( SM_CXSCREEN ),
GetSystemMetrics( SM_CYSCREEN )
};
const POINT wndPos = GetCenternedPosition( wndDefaultSize, screenField );
hWnd = CreateWindow( szWindowClass, // имя класса окна
szTitle, // имя приложения
WS_MINIMIZEBOX | WS_TILED | WS_SIZEBOX | WS_SYSMENU, // стиль окна
wndPos.x, // положение по Х
wndPos.y, // положение по Y
wndDefaultSize.cx, // размер по Х
wndDefaultSize.cy, // размер по Y
NULL, // описатель родительского окна
NULL, // описатель меню окна
hInstance, // указатель приложения
NULL ); // параметры создания.
if ( !hWnd ) // Если окно не создалось, функция возвращает FALSE
return FALSE;
ShowWindow( hWnd, nCmdShow ); // Показать окно
UpdateWindow( hWnd ); // Обновить окно
return TRUE; //Успешное завершение функции
}
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
// Оконная процедура. Принимает и обрабатывает все сообщения, приходящие в приложение
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
PAINTSTRUCT ps;
HDC hdc;
static TEXTMETRIC tm;
static SIZE charSize;
static RECT clientRect;
static StdStringType buffer;
static int currCharPosition = 0;
static std::vector< StringInfo > preparedText;
int xPadding = 10;
static int maxCharsInLine;
static POINT caretPosition{ 0, 0 };
static Direction caretMoveDirection;
//TCHAR debug[ 30 ];
switch ( message )
{
// Сообщение приходит при создании окна
case WM_CREATE:
hdc = GetDC( hWnd );
SelectObject( hdc, defaultFont );
GetTextMetrics( hdc, &tm );
charSize.cx = tm.tmAveCharWidth;
charSize.cy = tm.tmHeight;
ReleaseDC( hWnd, hdc );
break;
// Изменение размеров окна
case WM_SIZE:
GetClientRect( hWnd, &clientRect );
maxCharsInLine = (int)( (clientRect.right - clientRect.left - (xPadding << 1)) / charSize.cx );
break;
// Перерисовать окно
case WM_PAINT:
// Ставим каретку на место
CaretWinPosSetter( caretPosition, charSize, xPadding );
// Начать графический вывод
hdc = BeginPaint( hWnd, &ps );
// Выбираем моноширинный шрифт
SelectObject( hdc, defaultFont );
// Вывод информации
DrawSavedText( hdc, preparedText, charSize, xPadding );
//TODO: Удалить строку ниже, нужна для дебага
//TextOut( hdc, xPadding, clientRect.bottom - 10, debug, wsprintf( debug, _T("%d %d %d"), currCharPosition, buffer.size(), preparedText.size() ) );
// Закончить графический вывод
EndPaint( hWnd, &ps );
break;
// Нажатие ЛКМ - фиксирование позиции курсора
//case WM_LBUTTONUP:
//break;
case WM_SETFOCUS:
// Широкая каретка (rewrite mode)
//CreateCaret( hWnd, NULL, xPadding, charSize.cy );
// Каретка-палка (insert mode)
CreateCaret( hWnd, (HBITMAP)0, 0, charSize.cy );
CaretWinPosSetter( caretPosition, charSize, xPadding );
ShowCaret( hWnd );
break;
case WM_KILLFOCUS:
HideCaret( hWnd );
DestroyCaret();
break;
// Обработка нажатия системных клавиш
case WM_KEYDOWN:
switch ( wParam ) {
case VK_DELETE:
if ( currCharPosition < buffer.size() )
buffer.erase( currCharPosition, 1 );
PrepareText( buffer, preparedText, charSize, maxCharsInLine );
InvalidateRect( hWnd, NULL, TRUE );
break;
case VK_LEFT:
if ( currCharPosition > 0 ) {
MoveCaret( caretPosition, Direction::LEFT, preparedText );
//--currCharPosition;
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
}
break;
case VK_RIGHT:
if ( currCharPosition < buffer.size() ) {
MoveCaret( caretPosition, Direction::RIGHT, preparedText );
//++currCharPosition;
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
}
break;
case VK_UP:
MoveCaret( caretPosition, Direction::UP, preparedText );
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
break;
case VK_DOWN:
MoveCaret( caretPosition, Direction::DOWN, preparedText );
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
break;
default:
break;
}
CaretWinPosSetter( caretPosition, charSize, xPadding );
// TODO: Убрать строку ниже, она нужна для дебага
//InvalidateRect( hWnd, NULL, TRUE );
break;
case WM_CHAR:
switch ( wParam )
{
// New line
case '\r':
buffer.insert( currCharPosition, 1, '\n' );
//++ currCharPosition;
caretMoveDirection = Direction::RIGHT;
break;
// Backspace
case '\b':
if ( currCharPosition > 0 ) {
//-- currCharPosition;
buffer.erase( currCharPosition - 1, 1 );
caretMoveDirection = Direction::LEFT;
}
break;
// Escape
/*case '\x1B':
break;
*/
// Other symbols
default:
buffer.insert( currCharPosition, 1, (TCHAR) wParam );
//++ currCharPosition;
caretMoveDirection = Direction::RIGHT;
break;
}
PrepareText( buffer, preparedText, charSize, maxCharsInLine );
MoveCaret( caretPosition, caretMoveDirection, preparedText );
currCharPosition = GetCharNumberByPos( caretPosition, preparedText );
InvalidateRect( hWnd, NULL, TRUE );
break;
case WM_DESTROY: // Завершение работы
PostQuitMessage( 0 );
break;
default:
// Обработка сообщений, которые не обработаны пользователем
return DefWindowProc( hWnd, message, wParam, lParam );
}
return 0;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, Vsevolod Stakhov
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR ''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 AUTHOR 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 <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <arpa/inet.h>
#include "encrypt.h"
#include "nonce.h"
#include "aead.h"
#include "util.h"
#include "kdf.h"
#include "thread_pool.h"
#include "aligned_alloc.h"
namespace hpenc
{
class HPEncEncrypt::impl {
public:
std::unique_ptr<HPEncKDF> kdf;
std::vector <std::shared_ptr<HPencAead> > ciphers;
std::unique_ptr<HPEncNonce> nonce;
int fd_in, fd_out;
unsigned block_size;
std::vector<std::shared_ptr<aligned_vector> > io_bufs;
HPEncHeader hdr;
bool encode;
bool random_mode;
std::unique_ptr<ThreadPool> pool;
impl(std::unique_ptr<HPEncKDF> &&_kdf,
const std::string &in,
const std::string &out,
AeadAlgorithm alg,
unsigned _block_size,
unsigned nthreads = 0,
bool _rmode = false) : kdf(std::move(_kdf)), block_size(_block_size),
hdr(alg, _block_size), random_mode(_rmode)
{
if (!in.empty()) {
fd_in = open(in.c_str(), O_RDONLY);
if (fd_in == -1) {
std::cerr << "Cannot open input file '" << in << "': "
<< ::strerror(errno) << std::endl;
}
}
else {
fd_in = STDIN_FILENO;
}
if (!out.empty()) {
fd_out = open(out.c_str(), O_WRONLY | O_TRUNC);
if (fd_out == -1) {
std::cerr << "Cannot open output file '" << out << "': "
<< ::strerror(errno) << std::endl;
}
}
else {
fd_out = STDOUT_FILENO;
}
encode = false;
pool.reset(new ThreadPool(nthreads));
io_bufs.resize(pool->size());
hdr.nonce = kdf->initialNonce();
auto klen = AeadKeyLengths[static_cast<int>(alg)];
auto key = kdf->genKey(klen);
for (auto i = 0U; i < pool->size(); i ++) {
auto cipher = std::make_shared<HPencAead>(alg, _rmode);
cipher->setKey(key);
if (!nonce) {
nonce.reset(new HPEncNonce(cipher->noncelen()));
}
ciphers.push_back(cipher);
io_bufs[i] = std::make_shared<aligned_vector>();
io_bufs[i]->resize(block_size + ciphers[0]->taglen());
}
}
virtual ~impl()
{
if (fd_in != -1) close(fd_in);
if (fd_out != -1) close(fd_out);
}
bool writeHeader()
{
return hdr.toFd(fd_out, encode);
}
ssize_t writeBlock(ssize_t rd, aligned_vector *io_buf,
const std::vector<byte> &n, std::shared_ptr<HPencAead> const &cipher)
{
if (rd > 0) {
auto bs = htonl(rd);
auto tag = cipher->encrypt(reinterpret_cast<byte *>(&bs), sizeof(bs),
n.data(), n.size(), io_buf->data(), rd, io_buf->data());
if (!random_mode) {
if (!tag) {
return -1;
}
auto mac_pos = io_buf->data() + rd;
std::copy(tag->data, tag->data + tag->datalen, mac_pos);
return rd + tag->datalen;
}
return rd;
}
return -1;
}
size_t readBlock(aligned_vector *io_buf)
{
return util::atomicRead(fd_in, io_buf->data(), block_size);
}
};
HPEncEncrypt::HPEncEncrypt(std::unique_ptr<HPEncKDF> &&kdf,
const std::string &in,
const std::string &out,
AeadAlgorithm alg,
unsigned block_size,
unsigned nthreads,
bool random_mode) :
pimpl(new impl(std::move(kdf), in, out, alg, block_size, nthreads, random_mode))
{
}
HPEncEncrypt::~HPEncEncrypt()
{
}
void HPEncEncrypt::encrypt(bool encode, unsigned count)
{
pimpl->encode = encode;
bool last = false;
auto remain = count;
if (pimpl->random_mode || pimpl->writeHeader()) {
auto nblocks = 0U;
for (;;) {
auto blocks_read = 0;
std::vector< std::future<ssize_t> > results;
auto i = 0U;
for (auto &buf : pimpl->io_bufs) {
if (count > 0) {
if (remain == 0) {
last = true;
break;
}
remain --;
}
auto rd = pimpl->block_size;
if (!pimpl->random_mode) {
// For random mode we skip reading
rd = pimpl->readBlock(buf.get());
}
if (rd > 0) {
auto n = pimpl->nonce->incAndGet();
results.emplace_back(
pimpl->pool->enqueue(
&impl::writeBlock, pimpl.get(), rd, buf.get(),
n, pimpl->ciphers[i]
));
blocks_read ++;
}
else {
last = true;
break;
}
i ++;
}
i = 0;
for(auto && result: results) {
result.wait();
auto rd = result.get();
if (rd == -1) {
throw std::runtime_error("Cannot encrypt block");
}
else {
if (rd > 0) {
const auto &io_buf = pimpl->io_bufs[i].get();
if (encode) {
auto b64_out = util::base64Encode(io_buf->data(), rd);
if (util::atomicWrite(pimpl->fd_out,
reinterpret_cast<const byte *>(b64_out.data()),
b64_out.size()) == 0) {
throw std::runtime_error("Cannot write encrypted block");
}
}
else {
if (util::atomicWrite(pimpl->fd_out, io_buf->data(),
rd) == 0) {
throw std::runtime_error("Cannot write encrypted block");
}
}
}
if (rd < pimpl->block_size) {
// We are done
return;
}
}
i++;
}
if (last) {
return;
}
if (++nblocks % rekey_blocks == 0) {
// Rekey all cipers
auto nkey = pimpl->kdf->genKey(pimpl->ciphers[0]->keylen());
for (auto const &cipher : pimpl->ciphers) {
cipher->setKey(nkey);
}
}
}
}
}
} /* namespace hpenc */
<commit_msg>Do not throw exception on write errors in random mode.<commit_after>/*
* Copyright (c) 2014, Vsevolod Stakhov
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR ''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 AUTHOR 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 <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <arpa/inet.h>
#include "encrypt.h"
#include "nonce.h"
#include "aead.h"
#include "util.h"
#include "kdf.h"
#include "thread_pool.h"
#include "aligned_alloc.h"
namespace hpenc
{
class HPEncEncrypt::impl {
public:
std::unique_ptr<HPEncKDF> kdf;
std::vector <std::shared_ptr<HPencAead> > ciphers;
std::unique_ptr<HPEncNonce> nonce;
int fd_in, fd_out;
unsigned block_size;
std::vector<std::shared_ptr<aligned_vector> > io_bufs;
HPEncHeader hdr;
bool encode;
bool random_mode;
std::unique_ptr<ThreadPool> pool;
impl(std::unique_ptr<HPEncKDF> &&_kdf,
const std::string &in,
const std::string &out,
AeadAlgorithm alg,
unsigned _block_size,
unsigned nthreads = 0,
bool _rmode = false) : kdf(std::move(_kdf)), block_size(_block_size),
hdr(alg, _block_size), random_mode(_rmode)
{
if (!in.empty()) {
fd_in = open(in.c_str(), O_RDONLY);
if (fd_in == -1) {
std::cerr << "Cannot open input file '" << in << "': "
<< ::strerror(errno) << std::endl;
}
}
else {
fd_in = STDIN_FILENO;
}
if (!out.empty()) {
fd_out = open(out.c_str(), O_WRONLY | O_TRUNC);
if (fd_out == -1) {
std::cerr << "Cannot open output file '" << out << "': "
<< ::strerror(errno) << std::endl;
}
}
else {
fd_out = STDOUT_FILENO;
}
encode = false;
pool.reset(new ThreadPool(nthreads));
io_bufs.resize(pool->size());
hdr.nonce = kdf->initialNonce();
auto klen = AeadKeyLengths[static_cast<int>(alg)];
auto key = kdf->genKey(klen);
for (auto i = 0U; i < pool->size(); i ++) {
auto cipher = std::make_shared<HPencAead>(alg, _rmode);
cipher->setKey(key);
if (!nonce) {
nonce.reset(new HPEncNonce(cipher->noncelen()));
}
ciphers.push_back(cipher);
io_bufs[i] = std::make_shared<aligned_vector>();
io_bufs[i]->resize(block_size + ciphers[0]->taglen());
}
}
virtual ~impl()
{
if (fd_in != -1) close(fd_in);
if (fd_out != -1) close(fd_out);
}
bool writeHeader()
{
return hdr.toFd(fd_out, encode);
}
ssize_t writeBlock(ssize_t rd, aligned_vector *io_buf,
const std::vector<byte> &n, std::shared_ptr<HPencAead> const &cipher)
{
if (rd > 0) {
auto bs = htonl(rd);
auto tag = cipher->encrypt(reinterpret_cast<byte *>(&bs), sizeof(bs),
n.data(), n.size(), io_buf->data(), rd, io_buf->data());
if (!random_mode) {
if (!tag) {
return -1;
}
auto mac_pos = io_buf->data() + rd;
std::copy(tag->data, tag->data + tag->datalen, mac_pos);
return rd + tag->datalen;
}
return rd;
}
return -1;
}
size_t readBlock(aligned_vector *io_buf)
{
return util::atomicRead(fd_in, io_buf->data(), block_size);
}
};
HPEncEncrypt::HPEncEncrypt(std::unique_ptr<HPEncKDF> &&kdf,
const std::string &in,
const std::string &out,
AeadAlgorithm alg,
unsigned block_size,
unsigned nthreads,
bool random_mode) :
pimpl(new impl(std::move(kdf), in, out, alg, block_size, nthreads, random_mode))
{
}
HPEncEncrypt::~HPEncEncrypt()
{
}
void HPEncEncrypt::encrypt(bool encode, unsigned count)
{
pimpl->encode = encode;
bool last = false;
auto remain = count;
if (pimpl->random_mode || pimpl->writeHeader()) {
auto nblocks = 0U;
for (;;) {
auto blocks_read = 0;
std::vector< std::future<ssize_t> > results;
auto i = 0U;
for (auto &buf : pimpl->io_bufs) {
if (count > 0) {
if (remain == 0) {
last = true;
break;
}
remain --;
}
auto rd = pimpl->block_size;
if (!pimpl->random_mode) {
// For random mode we skip reading
rd = pimpl->readBlock(buf.get());
}
if (rd > 0) {
auto n = pimpl->nonce->incAndGet();
results.emplace_back(
pimpl->pool->enqueue(
&impl::writeBlock, pimpl.get(), rd, buf.get(),
n, pimpl->ciphers[i]
));
blocks_read ++;
}
else {
last = true;
break;
}
i ++;
}
i = 0;
for(auto && result: results) {
result.wait();
auto rd = result.get();
if (rd == -1) {
throw std::runtime_error("Cannot encrypt block");
}
else {
if (rd > 0) {
const auto &io_buf = pimpl->io_bufs[i].get();
if (encode) {
auto b64_out = util::base64Encode(io_buf->data(), rd);
if (util::atomicWrite(pimpl->fd_out,
reinterpret_cast<const byte *>(b64_out.data()),
b64_out.size()) == 0) {
if (pimpl->random_mode) {
// Assume that we are done
std::cerr << "Cannot write output: " <<
strerror(errno);
return;
}
else {
throw std::runtime_error("Cannot write "
"encrypted block");
}
}
}
else {
if (util::atomicWrite(pimpl->fd_out, io_buf->data(),
rd) == 0) {
if (pimpl->random_mode) {
// Assume that we are done
std::cerr << "Cannot write output: " <<
strerror(errno);
return;
}
else {
throw std::runtime_error("Cannot write "
"encrypted block");
}
}
}
}
if (rd < pimpl->block_size) {
// We are done
return;
}
}
i++;
}
if (last) {
return;
}
if (++nblocks % rekey_blocks == 0) {
// Rekey all cipers
auto nkey = pimpl->kdf->genKey(pimpl->ciphers[0]->keylen());
for (auto const &cipher : pimpl->ciphers) {
cipher->setKey(nkey);
}
}
}
}
}
} /* namespace hpenc */
<|endoftext|> |
<commit_before>#include "entity.hpp"
void entity_t::move(position_t offset){
position.x += offset.x;
position.y += offset.y;
position.z += offset.z;
}
void entity_t::accelerate(velocity_t ammount){
velocity.x += ammount.x;
velocity.y += ammount.y;
velocity.z += ammount.z;
}
void entity_t::update(){
}
<commit_msg>Delete entity.cpp<commit_after><|endoftext|> |
<commit_before>#include "expand.hpp"
#include "ast.hpp"
#include "bind.hpp"
#include "eval.hpp"
#include "contextualize.hpp"
#include "to_string.hpp"
#include <iostream>
#include <typeinfo>
#ifndef SASS_CONTEXT
#include "context.hpp"
#endif
namespace Sass {
Expand::Expand(Context& ctx, Eval* eval, Contextualize* contextualize, Env* env)
: ctx(ctx),
eval(eval),
contextualize(contextualize),
env(env),
block_stack(vector<Block*>()),
content_stack(vector<Block*>()),
property_stack(vector<String*>()),
selector_stack(vector<Selector*>())
{ selector_stack.push_back(0); }
Statement* Expand::operator()(Block* b)
{
Env new_env;
new_env.link(*env);
env = &new_env;
Block* bb = new (ctx.mem) Block(b->path(), b->line(), b->length(), b->is_root());
block_stack.push_back(bb);
append_block(b);
block_stack.pop_back();
env = env->parent();
return bb;
}
Statement* Expand::operator()(Ruleset* r)
{
To_String to_string;
Selector* sel_ctx = r->selector()->perform(contextualize->with(selector_stack.back(), env));
selector_stack.push_back(sel_ctx);
Ruleset* rr = new (ctx.mem) Ruleset(r->path(),
r->line(),
sel_ctx,
r->block()->perform(this)->block());
selector_stack.pop_back();
return rr;
}
Statement* Expand::operator()(Propset* p)
{
Block* current_block = block_stack.back();
String_Schema* combined_prop = new (ctx.mem) String_Schema(p->path(), p->line());
if (!property_stack.empty()) {
*combined_prop << property_stack.back()
<< new (ctx.mem) String_Constant(p->path(), p->line(), "-")
<< p->property_fragment(); // TODO: eval the prop into a string constant
}
else {
*combined_prop << p->property_fragment();
}
for (size_t i = 0, S = p->declarations().size(); i < S; ++i) {
Declaration* dec = static_cast<Declaration*>(p->declarations()[i]->perform(this));
String_Schema* final_prop = new (ctx.mem) String_Schema(dec->path(), dec->line());
*final_prop += combined_prop;
*final_prop << new (ctx.mem) String_Constant(dec->path(), dec->line(), "-");
*final_prop << dec->property();
dec->property(static_cast<String*>(final_prop->perform(eval->with(env))));
*current_block << dec;
}
for (size_t i = 0, S = p->propsets().size(); i < S; ++i) {
property_stack.push_back(combined_prop);
p->propsets()[i]->perform(this);
property_stack.pop_back();
}
return 0;
}
Statement* Expand::operator()(Media_Block* m)
{
Expression* media_queries = m->media_queries()->perform(eval->with(env));
return new (ctx.mem) Media_Block(m->path(),
m->line(),
static_cast<List*>(media_queries),
m->block()->perform(this)->block());
}
Statement* Expand::operator()(At_Rule* a)
{
Block* ab = a->block();
Block* bb = ab ? ab->perform(this)->block() : 0;
return new (ctx.mem) At_Rule(a->path(),
a->line(),
a->keyword(),
a->selector(),
bb);
}
Statement* Expand::operator()(Declaration* d)
{
String* old_p = d->property();
String* new_p = static_cast<String*>(old_p->perform(eval->with(env)));
return new (ctx.mem) Declaration(d->path(),
d->line(),
new_p,
d->value()->perform(eval->with(env)));
}
Statement* Expand::operator()(Assignment* a)
{
string var(a->variable());
if (env->has(var)) {
if(!a->is_guarded()) (*env)[var] = a->value()->perform(eval->with(env));
}
else {
env->current_frame()[var] = a->value()->perform(eval->with(env));
}
return 0;
}
Statement* Expand::operator()(Import* i)
{
return i; // TODO: eval i->urls()
}
Statement* Expand::operator()(Import_Stub* i)
{
append_block(ctx.style_sheets[i->file_name()]);
return 0;
}
Statement* Expand::operator()(Warning* w)
{
// eval handles this too, because warnings may occur in functions
w->perform(eval->with(env));
return 0;
}
Statement* Expand::operator()(Comment* c)
{
// TODO: eval the text, once we're parsing/storing it as a String_Schema
return c;
}
Statement* Expand::operator()(If* i)
{
if (*i->predicate()->perform(eval->with(env))) {
append_block(i->consequent());
}
else {
Block* alt = i->alternative();
if (alt) append_block(alt);
}
return 0;
}
Statement* Expand::operator()(For* f)
{
string variable(f->variable());
Expression* low = f->lower_bound()->perform(eval->with(env));
if (low->concrete_type() != Expression::NUMBER) {
error("lower bound of `@for` directive must be numeric", low->path(), low->line());
}
Expression* high = f->upper_bound()->perform(eval->with(env));
if (high->concrete_type() != Expression::NUMBER) {
error("upper bound of `@for` directive must be numeric", high->path(), high->line());
}
double lo = static_cast<Number*>(low)->value();
double hi = static_cast<Number*>(high)->value();
if (f->is_inclusive()) ++hi;
Env new_env;
new_env[variable] = new (ctx.mem) Number(low->path(), low->line(), lo);
new_env.link(env);
env = &new_env;
Block* body = f->block();
for (size_t i = lo;
i < hi;
(*env)[variable] = new (ctx.mem) Number(low->path(), low->line(), ++i)) {
append_block(body);
}
env = new_env.parent();
return 0;
}
Statement* Expand::operator()(Each* e)
{
string variable(e->variable());
Expression* expr = e->list()->perform(eval->with(env));
List* list = 0;
if (expr->concrete_type() != Expression::LIST) {
list = new (ctx.mem) List(expr->path(), expr->line(), 1, List::COMMA);
*list << expr;
}
else {
list = static_cast<List*>(expr);
}
Env new_env;
new_env[variable] = 0;
new_env.link(env);
env = &new_env;
Block* body = e->block();
for (size_t i = 0, L = list->length(); i < L; ++i) {
(*env)[variable] = (*list)[i];
append_block(body);
}
env = new_env.parent();
return 0;
}
Statement* Expand::operator()(While* w)
{
Expression* pred = w->predicate();
Block* body = w->block();
while (*pred->perform(eval->with(env))) {
append_block(body);
}
return 0;
}
Statement* Expand::operator()(Return* r)
{
error("@return may only be used within a function", r->path(), r->line());
return 0;
}
Statement* Expand::operator()(Extend* e)
{
// TODO: implement this, obviously
return 0;
}
Statement* Expand::operator()(Definition* d)
{
env->current_frame()[d->name() +
(d->type() == Definition::MIXIN ? "[m]" : "[f]")] = d;
// evaluate the default args
Parameters* params = d->parameters();
for (size_t i = 0, L = params->length(); i < L; ++i) {
Parameter* param = (*params)[i];
Expression* dflt = param->default_value();
if (dflt) param->default_value(dflt->perform(eval->with(env)));
}
// set the static link so we can have lexical scoping
d->environment(env);
return 0;
}
Statement* Expand::operator()(Mixin_Call* c)
{
string full_name(c->name() + "[m]");
if (!env->has(full_name)) {
error("no mixin named " + c->name(), c->path(), c->line());
}
Definition* def = static_cast<Definition*>((*env)[full_name]);
Block* body = def->block();
if (c->block()) {
content_stack.push_back(static_cast<Block*>(c->block()->perform(this)));
}
Block* current_block = block_stack.back();
Parameters* params = def->parameters();
Arguments* args = static_cast<Arguments*>(c->arguments()
->perform(eval->with(env)));
Env new_env;
bind("mixin " + c->name(), params, args, ctx, &new_env);
new_env.link(def->environment());
Env* old_env = env;
env = &new_env;
append_block(body);
env = old_env;
if (c->block()) {
content_stack.pop_back();
}
return 0;
}
Statement* Expand::operator()(Content* c)
{
if (content_stack.empty()) return 0;
Block* current_block = block_stack.back();
Block* content = content_stack.back();
for (size_t i = 0, L = content->length(); i < L; ++i) {
Statement* ith = (*content)[i];
if (ith) *current_block << ith;
}
return 0;
}
inline Statement* Expand::fallback_impl(AST_Node* n)
{
error("internal error; please contact the LibSass maintainers", n->path(), n->line());
String_Constant* msg = new (ctx.mem) String_Constant("", 0, string("`Expand` doesn't handle ") + typeid(*n).name());
return new (ctx.mem) Warning("", 0, msg);
}
inline void Expand::append_block(Block* b)
{
Block* current_block = block_stack.back();
for (size_t i = 0, L = b->length(); i < L; ++i) {
Statement* ith = (*b)[i]->perform(this);
if (ith) *current_block << ith;
}
}
}<commit_msg>Selectors directly under at-rules shouldn't be expanded.<commit_after>#include "expand.hpp"
#include "ast.hpp"
#include "bind.hpp"
#include "eval.hpp"
#include "contextualize.hpp"
#include "to_string.hpp"
#include <iostream>
#include <typeinfo>
#ifndef SASS_CONTEXT
#include "context.hpp"
#endif
namespace Sass {
Expand::Expand(Context& ctx, Eval* eval, Contextualize* contextualize, Env* env)
: ctx(ctx),
eval(eval),
contextualize(contextualize),
env(env),
block_stack(vector<Block*>()),
content_stack(vector<Block*>()),
property_stack(vector<String*>()),
selector_stack(vector<Selector*>())
{ selector_stack.push_back(0); }
Statement* Expand::operator()(Block* b)
{
Env new_env;
new_env.link(*env);
env = &new_env;
Block* bb = new (ctx.mem) Block(b->path(), b->line(), b->length(), b->is_root());
block_stack.push_back(bb);
append_block(b);
block_stack.pop_back();
env = env->parent();
return bb;
}
Statement* Expand::operator()(Ruleset* r)
{
To_String to_string;
Selector* sel_ctx = r->selector()->perform(contextualize->with(selector_stack.back(), env));
selector_stack.push_back(sel_ctx);
Ruleset* rr = new (ctx.mem) Ruleset(r->path(),
r->line(),
sel_ctx,
r->block()->perform(this)->block());
selector_stack.pop_back();
return rr;
}
Statement* Expand::operator()(Propset* p)
{
Block* current_block = block_stack.back();
String_Schema* combined_prop = new (ctx.mem) String_Schema(p->path(), p->line());
if (!property_stack.empty()) {
*combined_prop << property_stack.back()
<< new (ctx.mem) String_Constant(p->path(), p->line(), "-")
<< p->property_fragment(); // TODO: eval the prop into a string constant
}
else {
*combined_prop << p->property_fragment();
}
for (size_t i = 0, S = p->declarations().size(); i < S; ++i) {
Declaration* dec = static_cast<Declaration*>(p->declarations()[i]->perform(this));
String_Schema* final_prop = new (ctx.mem) String_Schema(dec->path(), dec->line());
*final_prop += combined_prop;
*final_prop << new (ctx.mem) String_Constant(dec->path(), dec->line(), "-");
*final_prop << dec->property();
dec->property(static_cast<String*>(final_prop->perform(eval->with(env))));
*current_block << dec;
}
for (size_t i = 0, S = p->propsets().size(); i < S; ++i) {
property_stack.push_back(combined_prop);
p->propsets()[i]->perform(this);
property_stack.pop_back();
}
return 0;
}
Statement* Expand::operator()(Media_Block* m)
{
Expression* media_queries = m->media_queries()->perform(eval->with(env));
return new (ctx.mem) Media_Block(m->path(),
m->line(),
static_cast<List*>(media_queries),
m->block()->perform(this)->block());
}
Statement* Expand::operator()(At_Rule* a)
{
Block* ab = a->block();
selector_stack.push_back(0);
Block* bb = ab ? ab->perform(this)->block() : 0;
At_Rule* aa = new (ctx.mem) At_Rule(a->path(),
a->line(),
a->keyword(),
a->selector(),
bb);
selector_stack.pop_back();
return aa;
}
Statement* Expand::operator()(Declaration* d)
{
String* old_p = d->property();
String* new_p = static_cast<String*>(old_p->perform(eval->with(env)));
return new (ctx.mem) Declaration(d->path(),
d->line(),
new_p,
d->value()->perform(eval->with(env)));
}
Statement* Expand::operator()(Assignment* a)
{
string var(a->variable());
if (env->has(var)) {
if(!a->is_guarded()) (*env)[var] = a->value()->perform(eval->with(env));
}
else {
env->current_frame()[var] = a->value()->perform(eval->with(env));
}
return 0;
}
Statement* Expand::operator()(Import* i)
{
return i; // TODO: eval i->urls()
}
Statement* Expand::operator()(Import_Stub* i)
{
append_block(ctx.style_sheets[i->file_name()]);
return 0;
}
Statement* Expand::operator()(Warning* w)
{
// eval handles this too, because warnings may occur in functions
w->perform(eval->with(env));
return 0;
}
Statement* Expand::operator()(Comment* c)
{
// TODO: eval the text, once we're parsing/storing it as a String_Schema
return c;
}
Statement* Expand::operator()(If* i)
{
if (*i->predicate()->perform(eval->with(env))) {
append_block(i->consequent());
}
else {
Block* alt = i->alternative();
if (alt) append_block(alt);
}
return 0;
}
Statement* Expand::operator()(For* f)
{
string variable(f->variable());
Expression* low = f->lower_bound()->perform(eval->with(env));
if (low->concrete_type() != Expression::NUMBER) {
error("lower bound of `@for` directive must be numeric", low->path(), low->line());
}
Expression* high = f->upper_bound()->perform(eval->with(env));
if (high->concrete_type() != Expression::NUMBER) {
error("upper bound of `@for` directive must be numeric", high->path(), high->line());
}
double lo = static_cast<Number*>(low)->value();
double hi = static_cast<Number*>(high)->value();
if (f->is_inclusive()) ++hi;
Env new_env;
new_env[variable] = new (ctx.mem) Number(low->path(), low->line(), lo);
new_env.link(env);
env = &new_env;
Block* body = f->block();
for (size_t i = lo;
i < hi;
(*env)[variable] = new (ctx.mem) Number(low->path(), low->line(), ++i)) {
append_block(body);
}
env = new_env.parent();
return 0;
}
Statement* Expand::operator()(Each* e)
{
string variable(e->variable());
Expression* expr = e->list()->perform(eval->with(env));
List* list = 0;
if (expr->concrete_type() != Expression::LIST) {
list = new (ctx.mem) List(expr->path(), expr->line(), 1, List::COMMA);
*list << expr;
}
else {
list = static_cast<List*>(expr);
}
Env new_env;
new_env[variable] = 0;
new_env.link(env);
env = &new_env;
Block* body = e->block();
for (size_t i = 0, L = list->length(); i < L; ++i) {
(*env)[variable] = (*list)[i];
append_block(body);
}
env = new_env.parent();
return 0;
}
Statement* Expand::operator()(While* w)
{
Expression* pred = w->predicate();
Block* body = w->block();
while (*pred->perform(eval->with(env))) {
append_block(body);
}
return 0;
}
Statement* Expand::operator()(Return* r)
{
error("@return may only be used within a function", r->path(), r->line());
return 0;
}
Statement* Expand::operator()(Extend* e)
{
// TODO: implement this, obviously
return 0;
}
Statement* Expand::operator()(Definition* d)
{
env->current_frame()[d->name() +
(d->type() == Definition::MIXIN ? "[m]" : "[f]")] = d;
// evaluate the default args
Parameters* params = d->parameters();
for (size_t i = 0, L = params->length(); i < L; ++i) {
Parameter* param = (*params)[i];
Expression* dflt = param->default_value();
if (dflt) param->default_value(dflt->perform(eval->with(env)));
}
// set the static link so we can have lexical scoping
d->environment(env);
return 0;
}
Statement* Expand::operator()(Mixin_Call* c)
{
string full_name(c->name() + "[m]");
if (!env->has(full_name)) {
error("no mixin named " + c->name(), c->path(), c->line());
}
Definition* def = static_cast<Definition*>((*env)[full_name]);
Block* body = def->block();
if (c->block()) {
content_stack.push_back(static_cast<Block*>(c->block()->perform(this)));
}
Block* current_block = block_stack.back();
Parameters* params = def->parameters();
Arguments* args = static_cast<Arguments*>(c->arguments()
->perform(eval->with(env)));
Env new_env;
bind("mixin " + c->name(), params, args, ctx, &new_env);
new_env.link(def->environment());
Env* old_env = env;
env = &new_env;
append_block(body);
env = old_env;
if (c->block()) {
content_stack.pop_back();
}
return 0;
}
Statement* Expand::operator()(Content* c)
{
if (content_stack.empty()) return 0;
Block* current_block = block_stack.back();
Block* content = content_stack.back();
for (size_t i = 0, L = content->length(); i < L; ++i) {
Statement* ith = (*content)[i];
if (ith) *current_block << ith;
}
return 0;
}
inline Statement* Expand::fallback_impl(AST_Node* n)
{
error("internal error; please contact the LibSass maintainers", n->path(), n->line());
String_Constant* msg = new (ctx.mem) String_Constant("", 0, string("`Expand` doesn't handle ") + typeid(*n).name());
return new (ctx.mem) Warning("", 0, msg);
}
inline void Expand::append_block(Block* b)
{
Block* current_block = block_stack.back();
for (size_t i = 0, L = b->length(); i < L; ++i) {
Statement* ith = (*b)[i]->perform(this);
if (ith) *current_block << ith;
}
}
}<|endoftext|> |
<commit_before>// $Id: fourth_error_estimators.C,v 1.12 2006-09-19 17:50:52 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm> // for std::fill
#include <math.h> // for sqrt
// Local Includes
#include "libmesh_common.h"
#include "fourth_error_estimators.h"
#include "dof_map.h"
#include "error_vector.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "mesh.h"
#include "system.h"
//-----------------------------------------------------------------
// ErrorEstimator implementations
#ifndef ENABLE_SECOND_DERIVATIVES
void LaplacianErrorEstimator::estimate_error (const System&,
ErrorVector&,
bool)
{
std::cerr << "ERROR: This functionalitry requires second-derivative support!"
<< std::endl;
error();
}
#else // defined (ENABLE_SECOND_DERIVATIVES)
void LaplacianErrorEstimator::estimate_error (const System& system,
ErrorVector& error_per_cell,
bool)
{
START_LOG("laplacian_jump()", "LaplacianErrorEstimator");
/*
- e & f are global element ids
Case (1.) Elements are at the same level, e<f
Compute the laplacian jump on the face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | |
| | f |
| | |
| e |---> n |
| | |
| | |
----------------------
Case (2.) The neighbor is at a higher level.
Compute the laplacian jump on e's face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | | |
| | e |---> n |
| | | |
|-----------| f |
| | | |
| | | |
| | | |
----------------------
*/
// The current mesh
const Mesh& mesh = system.get_mesh();
// The dimensionality of the mesh
const unsigned int dim = mesh.mesh_dimension();
// The number of variables in the system
const unsigned int n_vars = system.n_vars();
// The DofMap for this system
const DofMap& dof_map = system.get_dof_map();
// Resize the error_per_cell vector to be
// the number of elements, initialize it to 0.
error_per_cell.resize (mesh.n_elem());
std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);
// Check for the use of component_mask
this->convert_component_mask_to_scale();
// Check for a valid component_scale
if (!component_scale.empty())
{
if (component_scale.size() != n_vars)
{
std::cerr << "ERROR: component_scale is the wrong size:"
<< std::endl
<< " component_scale.size()=" << component_scale.size()
<< std::endl
<< " n_vars=" << n_vars
<< std::endl;
error();
}
}
else
{
// No specified scaling. Scale all variables by one.
component_scale.resize (n_vars);
std::fill (component_scale.begin(), component_scale.end(), 1.0);
}
// Loop over all the variables in the system
for (unsigned int var=0; var<n_vars; var++)
{
// Possibly skip this variable
if (!component_scale.empty())
if (component_scale[var] == 0.0) continue;
// The type of finite element to use for this variable
const FEType& fe_type = dof_map.variable_type (var);
// Finite element objects for the same face from
// different sides
AutoPtr<FEBase> fe_e (FEBase::build (dim, fe_type));
AutoPtr<FEBase> fe_f (FEBase::build (dim, fe_type));
// Build an appropriate quadrature rule
AutoPtr<QBase> qrule(fe_type.default_quadrature_rule(dim-1));
// Tell the finite element for element e about the quadrature
// rule. The finite element for element f need not know about it
fe_e->attach_quadrature_rule (qrule.get());
// By convention we will always do the integration
// on the face of element e. Get its Jacobian values, etc..
const std::vector<Real>& JxW_face = fe_e->get_JxW();
const std::vector<Point>& qface_point = fe_e->get_xyz();
// const std::vector<Point>& face_normals = fe_e->get_normals();
// The quadrature points on element f. These will be computed
// from the quadrature points on element e.
std::vector<Point> qp_f;
// The shape function second derivatives on elements e & f
const std::vector<std::vector<RealTensor> > & d2phi_e =
fe_e->get_d2phi();
const std::vector<std::vector<RealTensor> > & d2phi_f =
fe_f->get_d2phi();
// The global DOF indices for elements e & f
std::vector<unsigned int> dof_indices_e;
std::vector<unsigned int> dof_indices_f;
// Iterate over all the active elements in the mesh
// that live on this processor.
MeshBase::const_element_iterator elem_it =
mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end =
mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
// e is necessarily an active element on the local processor
const Elem* e = *elem_it;
const unsigned int e_id = e->id();
// Loop over the neighbors of element e
for (unsigned int n_e=0; n_e<e->n_neighbors(); n_e++)
if (e->neighbor(n_e) != NULL) // e is not on the boundary
{
const Elem* f = e->neighbor(n_e);
const unsigned int f_id = f->id();
if ( //-------------------------------------
((f->active()) &&
(f->level() == e->level()) &&
(e_id < f_id)) // Case 1.
|| //-------------------------------------
(f->level() < e->level()) // Case 2.
) //-------------------------------------
{
// Update the shape functions on side s_e of
// element e
fe_e->reinit (e, n_e);
// Build the side
AutoPtr<Elem> side (e->build_side(n_e));
// Get the maximum h for this side
const Real h = side->hmax();
// Get the DOF indices for the two elements
dof_map.dof_indices (e, dof_indices_e, var);
dof_map.dof_indices (f, dof_indices_f, var);
// The number of DOFS on each element
const unsigned int n_dofs_e = dof_indices_e.size();
const unsigned int n_dofs_f = dof_indices_f.size();
// The number of quadrature points
const unsigned int n_qp = qrule->n_points();
// Find the location of the quadrature points
// on element f
FEInterface::inverse_map (dim, fe_type, f,
qface_point, qp_f);
// Compute the shape functions on element f
// at the quadrature points of element e
fe_f->reinit (f, &qp_f);
// The error contribution from this face
Real error = 1.e-10;
// loop over the integration points on the face
for (unsigned int qp=0; qp<n_qp; qp++)
{
// The solution laplacian from each element
Number lap_e = 0., lap_f = 0.;
// Compute the solution laplacian on element e
for (unsigned int i=0; i<n_dofs_e; i++)
{
lap_e += d2phi_e[i][qp](0,0) *
system.current_solution(dof_indices_e[i]);
if (dim > 1)
{
lap_e += d2phi_e[i][qp](1,1) *
system.current_solution(dof_indices_e[i]);
}
if (dim > 2)
{
lap_e += d2phi_e[i][qp](2,2) *
system.current_solution(dof_indices_e[i]);
}
}
// Compute the solution gradient on element f
for (unsigned int i=0; i<n_dofs_f; i++)
{
lap_f += d2phi_f[i][qp](0,0) *
system.current_solution(dof_indices_f[i]);
if (dim > 1)
{
lap_f += d2phi_f[i][qp](1,1) *
system.current_solution(dof_indices_f[i]);
}
if (dim > 2)
{
lap_f += d2phi_f[i][qp](2,2) *
system.current_solution(dof_indices_f[i]);
}
}
// The flux jump at the face
const Number jump = lap_e - lap_f;
// The flux jump squared
#ifndef USE_COMPLEX_NUMBERS
const Real jump2 = jump*jump;
#else
const Real jump2 = std::norm(jump);
#endif
// Integrate the error on the face
error += JxW_face[qp]*h*jump2;
} // End quadrature point loop
// Add the error contribution to elements e & f
error_per_cell[e_id] += error;
error_per_cell[f_id] += error;
}
} // if (e->neigbor(n_e) != NULL)
} // End loop over active local elements
} // End loop over variables
// Each processor has now computed the error contribuions
// for its local elements. We need to sum the vector
// and then take the square-root of each component. Note
// that we only need to sum if we are running on multiple
// processors, and we only need to take the square-root
// if the value is nonzero. There will in general be many
// zeros for the inactive elements.
// First sum the vector
this->reduce_error(error_per_cell);
// Compute the square-root of each component.
for (unsigned int i=0; i<error_per_cell.size(); i++)
if (error_per_cell[i] != 0.)
error_per_cell[i] = sqrt(error_per_cell[i]);
STOP_LOG("laplacian_jump()", "LaplacianErrorEstimator");
}
#endif // defined (ENABLE_SECOND_DERIVATIVES)
<commit_msg>Fixed to handle 1D meshes, use component_scale terms<commit_after>// $Id: fourth_error_estimators.C,v 1.13 2006-10-20 20:31:22 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm> // for std::fill
#include <math.h> // for sqrt
// Local Includes
#include "libmesh_common.h"
#include "fourth_error_estimators.h"
#include "dof_map.h"
#include "error_vector.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "mesh.h"
#include "system.h"
//-----------------------------------------------------------------
// ErrorEstimator implementations
#ifndef ENABLE_SECOND_DERIVATIVES
void LaplacianErrorEstimator::estimate_error (const System&,
ErrorVector&,
bool)
{
std::cerr << "ERROR: This functionalitry requires second-derivative support!"
<< std::endl;
error();
}
#else // defined (ENABLE_SECOND_DERIVATIVES)
void LaplacianErrorEstimator::estimate_error (const System& system,
ErrorVector& error_per_cell,
bool)
{
START_LOG("laplacian_jump()", "LaplacianErrorEstimator");
/*
- e & f are global element ids
Case (1.) Elements are at the same level, e<f
Compute the laplacian jump on the face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | |
| | f |
| | |
| e |---> n |
| | |
| | |
----------------------
Case (2.) The neighbor is at a higher level.
Compute the laplacian jump on e's face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | | |
| | e |---> n |
| | | |
|-----------| f |
| | | |
| | | |
| | | |
----------------------
*/
// The current mesh
const Mesh& mesh = system.get_mesh();
// The dimensionality of the mesh
const unsigned int dim = mesh.mesh_dimension();
// The number of variables in the system
const unsigned int n_vars = system.n_vars();
// The DofMap for this system
const DofMap& dof_map = system.get_dof_map();
// Resize the error_per_cell vector to be
// the number of elements, initialize it to 0.
error_per_cell.resize (mesh.n_elem());
std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);
// Check for the use of component_mask
this->convert_component_mask_to_scale();
// Check for a valid component_scale
if (!component_scale.empty())
{
if (component_scale.size() != n_vars)
{
std::cerr << "ERROR: component_scale is the wrong size:"
<< std::endl
<< " component_scale.size()=" << component_scale.size()
<< std::endl
<< " n_vars=" << n_vars
<< std::endl;
error();
}
}
else
{
// No specified scaling. Scale all variables by one.
component_scale.resize (n_vars);
std::fill (component_scale.begin(), component_scale.end(), 1.0);
}
// Loop over all the variables in the system
for (unsigned int var=0; var<n_vars; var++)
{
// Possibly skip this variable
if (!component_scale.empty())
if (component_scale[var] == 0.0) continue;
// The type of finite element to use for this variable
const FEType& fe_type = dof_map.variable_type (var);
// Finite element objects for the same face from
// different sides
AutoPtr<FEBase> fe_e (FEBase::build (dim, fe_type));
AutoPtr<FEBase> fe_f (FEBase::build (dim, fe_type));
// Build an appropriate quadrature rule
AutoPtr<QBase> qrule(fe_type.default_quadrature_rule(dim-1));
// Tell the finite element for element e about the quadrature
// rule. The finite element for element f need not know about it
fe_e->attach_quadrature_rule (qrule.get());
// By convention we will always do the integration
// on the face of element e. Get its Jacobian values, etc..
const std::vector<Real>& JxW_face = fe_e->get_JxW();
const std::vector<Point>& qface_point = fe_e->get_xyz();
// const std::vector<Point>& face_normals = fe_e->get_normals();
// The quadrature points on element f. These will be computed
// from the quadrature points on element e.
std::vector<Point> qp_f;
// The shape function second derivatives on elements e & f
const std::vector<std::vector<RealTensor> > & d2phi_e =
fe_e->get_d2phi();
const std::vector<std::vector<RealTensor> > & d2phi_f =
fe_f->get_d2phi();
// The global DOF indices for elements e & f
std::vector<unsigned int> dof_indices_e;
std::vector<unsigned int> dof_indices_f;
// Iterate over all the active elements in the mesh
// that live on this processor.
MeshBase::const_element_iterator elem_it =
mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end =
mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
// e is necessarily an active element on the local processor
const Elem* e = *elem_it;
const unsigned int e_id = e->id();
// Loop over the neighbors of element e
for (unsigned int n_e=0; n_e<e->n_neighbors(); n_e++)
if (e->neighbor(n_e) != NULL) // e is not on the boundary
{
const Elem* f = e->neighbor(n_e);
const unsigned int f_id = f->id();
if ( //-------------------------------------
((f->active()) &&
(f->level() == e->level()) &&
(e_id < f_id)) // Case 1.
|| //-------------------------------------
(f->level() < e->level()) // Case 2.
) //-------------------------------------
{
// Update the shape functions on side s_e of
// element e
fe_e->reinit (e, n_e);
// Build the side
AutoPtr<Elem> side (e->build_side(n_e));
// Get the maximum h for this side
Real h_e, h_f;
if (dim == 1)
{
h_e = e->hmax();
h_f = f->hmax();
}
else
h_e = h_f = side->hmax();
// Get the DOF indices for the two elements
dof_map.dof_indices (e, dof_indices_e, var);
dof_map.dof_indices (f, dof_indices_f, var);
// The number of DOFS on each element
const unsigned int n_dofs_e = dof_indices_e.size();
const unsigned int n_dofs_f = dof_indices_f.size();
// The number of quadrature points
const unsigned int n_qp = qrule->n_points();
// Find the location of the quadrature points
// on element f
FEInterface::inverse_map (dim, fe_type, f,
qface_point, qp_f);
// Compute the shape functions on element f
// at the quadrature points of element e
fe_f->reinit (f, &qp_f);
// The error contribution from this face
Real error = 1.e-10;
// loop over the integration points on the face
for (unsigned int qp=0; qp<n_qp; qp++)
{
// The solution laplacian from each element
Number lap_e = 0., lap_f = 0.;
// Compute the solution laplacian on element e
for (unsigned int i=0; i<n_dofs_e; i++)
{
lap_e += d2phi_e[i][qp](0,0) *
system.current_solution(dof_indices_e[i]);
if (dim > 1)
{
lap_e += d2phi_e[i][qp](1,1) *
system.current_solution(dof_indices_e[i]);
}
if (dim > 2)
{
lap_e += d2phi_e[i][qp](2,2) *
system.current_solution(dof_indices_e[i]);
}
}
// Compute the solution gradient on element f
for (unsigned int i=0; i<n_dofs_f; i++)
{
lap_f += d2phi_f[i][qp](0,0) *
system.current_solution(dof_indices_f[i]);
if (dim > 1)
{
lap_f += d2phi_f[i][qp](1,1) *
system.current_solution(dof_indices_f[i]);
}
if (dim > 2)
{
lap_f += d2phi_f[i][qp](2,2) *
system.current_solution(dof_indices_f[i]);
}
}
// The flux jump at the face
const Number jump = lap_e - lap_f;
// The flux jump squared
#ifndef USE_COMPLEX_NUMBERS
const Real jump2 = jump*jump;
#else
const Real jump2 = std::norm(jump);
#endif
// Integrate the error on the face
error += JxW_face[qp]*jump2;
} // End quadrature point loop
// Add the error contribution to elements e & f
error_per_cell[e_id] += error*h_e*component_scale[var];
error_per_cell[f_id] += error*h_f*component_scale[var];
}
} // if (e->neigbor(n_e) != NULL)
} // End loop over active local elements
} // End loop over variables
// Each processor has now computed the error contribuions
// for its local elements. We need to sum the vector
// and then take the square-root of each component. Note
// that we only need to sum if we are running on multiple
// processors, and we only need to take the square-root
// if the value is nonzero. There will in general be many
// zeros for the inactive elements.
// First sum the vector
this->reduce_error(error_per_cell);
// Compute the square-root of each component.
for (unsigned int i=0; i<error_per_cell.size(); i++)
if (error_per_cell[i] != 0.)
error_per_cell[i] = sqrt(error_per_cell[i]);
STOP_LOG("laplacian_jump()", "LaplacianErrorEstimator");
}
#endif // defined (ENABLE_SECOND_DERIVATIVES)
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_META_OPERANDS_AND_PARTIALS_HPP
#define STAN_MATH_PRIM_SCAL_META_OPERANDS_AND_PARTIALS_HPP
#include <stan/math/prim/scal/meta/broadcast_array.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
namespace stan {
namespace math {
template <typename Op1 = double, typename Op2 = double, typename Op3 = double,
typename Op4 = double, typename Op5 = double,
typename T_return_type =
typename return_type<Op1, Op2, Op3, Op4, Op5>::type>
class operands_and_partials; // Forward declaration
namespace internal {
/**
* An edge holds both the operands and its associated
* partial derivatives. They're held together in the
* same class because then we can keep the templating logic that
* specializes on type of operand in one place.
*
* This is the base template class that ends up getting instantiated
* for arithmetic primitives (doubles and ints).
*
* @tparam ViewElt the type we expect to be at partials_[i]
* @tparam Op the type of the operand
*/
template <typename ViewElt, typename Op>
class ops_partials_edge {
public:
typedef empty_broadcast_array<ViewElt, Op> partials_t;
partials_t partials_;
ops_partials_edge() {}
explicit ops_partials_edge(const Op&) {}
private:
template <typename, typename, typename, typename, typename, typename>
friend class stan::math::operands_and_partials;
void dump_partials(ViewElt* /* partials */) const {} // reverse mode
void dump_operands(void* /* operands */) const {} // reverse mode
ViewElt dx() const { return 0; } // used for fvars
int size() const { return 0; } // reverse mode
};
} // namespace internal
/**
* This template builds partial derivatives with respect to a
* set of
* operands. There are two reason for the generality of this
* class. The first is to handle vector and scalar arguments
* without needing to write additional code. The second is to use
* this class for writing probability distributions that handle
* primitives, reverse mode, and forward mode variables
* seamlessly.
*
* Conceptually, this class is used when we want to manually calculate
* the derivative of a function and store this manual result on the
* autodiff stack in a sort of "compressed" form. Think of it like an
* easy-to-use interface to rev/core/precomputed_gradients.
*
* This class supports nested container ("multivariate") use-cases
* as well by exposing a partials_vec_ member on edges of the
* appropriate type.
*
* This base template is instantiated when all operands are
* primitives and we don't want to calculate derivatives at
* all. So all Op1 - Op5 must be arithmetic primitives
* like int or double. This is controlled with the
* T_return_type type parameter.
*
* @tparam Op1 type of the first operand
* @tparam Op2 type of the second operand
* @tparam Op3 type of the third operand
* @tparam Op4 type of the fourth operand
* @tparam Op5 type of the fifth operand
* @tparam T_return_type return type of the expression. This defaults
* to calling a template metaprogram that calculates the scalar
* promotion of Op1..Op4
*/
template <typename Op1, typename Op2, typename Op3, typename Op4, typename Op5,
typename T_return_type>
class operands_and_partials {
public:
explicit operands_and_partials(const Op1& op1) {}
operands_and_partials(const Op1& op1, const Op2& op2) {}
operands_and_partials(const Op1& op1, const Op2& op2, const Op3& op3) {}
operands_and_partials(const Op1& op1, const Op2& op2, const Op3& op3,
const Op4& op4) {}
operands_and_partials(const Op1& op1, const Op2& op2, const Op3& op3,
const Op4& op4, const Op5& op5) {}
/**
* Build the node to be stored on the autodiff graph.
* This should contain both the value and the tangent.
*
* For scalars (this implementation), we don't calculate any derivatives.
* For reverse mode, we end up returning a type of var that will calculate
* the appropriate adjoint using the stored operands and partials.
* Forward mode just calculates the tangent on the spot and returns it in
* a vanilla fvar.
*
* @param value the return value of the function we are compressing
* @return the value with its derivative
*/
T_return_type build(double value) { return value; }
// These will always be 0 size base template instantiations (above).
internal::ops_partials_edge<double, Op1> edge1_;
internal::ops_partials_edge<double, Op2> edge2_;
internal::ops_partials_edge<double, Op3> edge3_;
internal::ops_partials_edge<double, Op4> edge4_;
internal::ops_partials_edge<double, Op5> edge5_;
};
} // namespace math
} // namespace stan
#endif
<commit_msg>Restore prim/scal operands_and_partials to state on develop<commit_after>#ifndef STAN_MATH_PRIM_SCAL_META_OPERANDS_AND_PARTIALS_HPP
#define STAN_MATH_PRIM_SCAL_META_OPERANDS_AND_PARTIALS_HPP
#include <stan/math/prim/scal/meta/broadcast_array.hpp>
#include <stan/math/prim/scal/meta/return_type.hpp>
namespace stan {
namespace math {
template <typename Op1 = double, typename Op2 = double, typename Op3 = double,
typename Op4 = double, typename Op5 = double,
typename T_return_type =
typename return_type<Op1, Op2, Op3, Op4, Op5>::type>
class operands_and_partials; // Forward declaration
namespace internal {
/**
* An edge holds both the operands and its associated
* partial derivatives. They're held together in the
* same class because then we can keep the templating logic that
* specializes on type of operand in one place.
*
* This is the base template class that ends up getting instantiated
* for arithmetic primitives (doubles and ints).
*
* @tparam ViewElt the type we expect to be at partials_[i]
* @tparam Op the type of the operand
*/
template <typename ViewElt, typename Op>
class ops_partials_edge {
public:
empty_broadcast_array<ViewElt, Op> partials_;
ops_partials_edge() {}
explicit ops_partials_edge(const Op& /* op */) {}
private:
template <typename, typename, typename, typename, typename, typename>
friend class stan::math::operands_and_partials;
void dump_partials(ViewElt* /* partials */) const {} // reverse mode
void dump_operands(void* /* operands */) const {} // reverse mode
ViewElt dx() const { return 0; } // used for fvars
int size() const { return 0; } // reverse mode
};
} // namespace internal
/**
* This template builds partial derivatives with respect to a
* set of
* operands. There are two reason for the generality of this
* class. The first is to handle vector and scalar arguments
* without needing to write additional code. The second is to use
* this class for writing probability distributions that handle
* primitives, reverse mode, and forward mode variables
* seamlessly.
*
* Conceptually, this class is used when we want to manually calculate
* the derivative of a function and store this manual result on the
* autodiff stack in a sort of "compressed" form. Think of it like an
* easy-to-use interface to rev/core/precomputed_gradients.
*
* This class supports nested container ("multivariate") use-cases
* as well by exposing a partials_vec_ member on edges of the
* appropriate type.
*
* This base template is instantiated when all operands are
* primitives and we don't want to calculate derivatives at
* all. So all Op1 - Op5 must be arithmetic primitives
* like int or double. This is controlled with the
* T_return_type type parameter.
*
* @tparam Op1 type of the first operand
* @tparam Op2 type of the second operand
* @tparam Op3 type of the third operand
* @tparam Op4 type of the fourth operand
* @tparam Op5 type of the fifth operand
* @tparam T_return_type return type of the expression. This defaults
* to calling a template metaprogram that calculates the scalar
* promotion of Op1..Op4
*/
template <typename Op1, typename Op2, typename Op3, typename Op4, typename Op5,
typename T_return_type>
class operands_and_partials {
public:
explicit operands_and_partials(const Op1& op1) {}
operands_and_partials(const Op1& op1, const Op2& op2) {}
operands_and_partials(const Op1& op1, const Op2& op2, const Op3& op3) {}
operands_and_partials(const Op1& op1, const Op2& op2, const Op3& op3,
const Op4& op4) {}
operands_and_partials(const Op1& op1, const Op2& op2, const Op3& op3,
const Op4& op4, const Op5& op5) {}
/**
* Build the node to be stored on the autodiff graph.
* This should contain both the value and the tangent.
*
* For scalars (this implementation), we don't calculate any derivatives.
* For reverse mode, we end up returning a type of var that will calculate
* the appropriate adjoint using the stored operands and partials.
* Forward mode just calculates the tangent on the spot and returns it in
* a vanilla fvar.
*
* @param value the return value of the function we are compressing
* @return the value with its derivative
*/
T_return_type build(double value) { return value; }
// These will always be 0 size base template instantiations (above).
internal::ops_partials_edge<double, Op1> edge1_;
internal::ops_partials_edge<double, Op2> edge2_;
internal::ops_partials_edge<double, Op3> edge3_;
internal::ops_partials_edge<double, Op4> edge4_;
internal::ops_partials_edge<double, Op5> edge5_;
};
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*
* opencog/atoms/execution/Eager.cc
*
* Copyright (C) 2009, 2013, 2015, 2016 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atomspace/AtomSpace.h>
#include "Eager.h"
#include "Instantiator.h"
using namespace opencog;
/// Utility -- Perform eager execution of black-box arguments.
///
/// Perform eager execution of the arguments. We have to do this,
/// because the user-defined functions are black-boxes, and cannot be
/// trusted to do lazy execution correctly. Right now, this is the
/// policy. I guess we could add "scm-lazy:" and "py-lazy:" URI's
/// for user-defined functions smart enough to do lazy evaluation.
///
/// When executing, if the results are different, add the new
/// results to the atomspace. We need to do this, because scheme,
/// and python expects to find thier arguments in the atomspace.
/// This is arguably broken, as it pollutes the atomspace with
/// junk that is never cleaned up. We punt for now, but something
/// should be done about this. XXX FIXME ... Well ... except that
/// all callers of this method are invited to create a temporary
/// scratch atomspace, and use that. This presumably avoids the
/// pollution concerns.
///
Handle eager_execute(AtomSpace* as, const Handle& cargs)
{
Instantiator inst(as);
Handle args(cargs);
if (LIST_LINK == cargs->getType())
{
std::vector<Handle> new_oset;
bool changed = false;
for (const Handle& ho : cargs->getOutgoingSet())
{
Handle nh(inst.execute(ho));
// nh might be NULL if ho was a DeleteLink
if (nullptr == nh)
{
changed = true;
continue;
}
// Unwrap the top-most DontExecLink's. Lower ones are left
// untouched. We do this as a sop for issue opencog/atomspace#704
// but maybe we should not?
if (DONT_EXEC_LINK == nh->getType())
{
nh = nh->getOutgoingAtom(0);
}
new_oset.emplace_back(nh);
if (nh != ho) changed = true;
}
if (changed)
args = as->add_link(LIST_LINK, new_oset);
}
return args;
}
<commit_msg>Add correct namespace<commit_after>/*
* opencog/atoms/execution/Eager.cc
*
* Copyright (C) 2009, 2013, 2015, 2016 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atomspace/AtomSpace.h>
#include "Eager.h"
#include "Instantiator.h"
using namespace opencog;
/// Utility -- Perform eager execution of black-box arguments.
///
/// Perform eager execution of the arguments. We have to do this,
/// because the user-defined functions are black-boxes, and cannot be
/// trusted to do lazy execution correctly. Right now, this is the
/// policy. I guess we could add "scm-lazy:" and "py-lazy:" URI's
/// for user-defined functions smart enough to do lazy evaluation.
///
/// When executing, if the results are different, add the new
/// results to the atomspace. We need to do this, because scheme,
/// and python expects to find thier arguments in the atomspace.
/// This is arguably broken, as it pollutes the atomspace with
/// junk that is never cleaned up. We punt for now, but something
/// should be done about this. XXX FIXME ... Well ... except that
/// all callers of this method are invited to create a temporary
/// scratch atomspace, and use that. This presumably avoids the
/// pollution concerns.
///
Handle opencog::eager_execute(AtomSpace* as, const Handle& cargs)
{
Instantiator inst(as);
Handle args(cargs);
if (LIST_LINK == cargs->getType())
{
std::vector<Handle> new_oset;
bool changed = false;
for (const Handle& ho : cargs->getOutgoingSet())
{
Handle nh(inst.execute(ho));
// nh might be NULL if ho was a DeleteLink
if (nullptr == nh)
{
changed = true;
continue;
}
// Unwrap the top-most DontExecLink's. Lower ones are left
// untouched. We do this as a sop for issue opencog/atomspace#704
// but maybe we should not?
if (DONT_EXEC_LINK == nh->getType())
{
nh = nh->getOutgoingAtom(0);
}
new_oset.emplace_back(nh);
if (nh != ho) changed = true;
}
if (changed)
args = as->add_link(LIST_LINK, new_oset);
}
return args;
}
<|endoftext|> |
<commit_before>//===--- OptTable.cpp - Option Table Implementation -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cctype>
#include <map>
using namespace llvm;
using namespace llvm::opt;
namespace llvm {
namespace opt {
// Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
// with an exceptions. '\0' comes at the end of the alphabet instead of the
// beginning (thus options precede any other options which prefix them).
static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
const char *X = A, *Y = B;
char a = tolower(*A), b = tolower(*B);
while (a == b) {
if (a == '\0')
return 0;
a = tolower(*++X);
b = tolower(*++Y);
}
if (a == '\0') // A is a prefix of B.
return 1;
if (b == '\0') // B is a prefix of A.
return -1;
// Otherwise lexicographic.
return (a < b) ? -1 : 1;
}
#ifndef NDEBUG
static int StrCmpOptionName(const char *A, const char *B) {
if (int N = StrCmpOptionNameIgnoreCase(A, B))
return N;
return strcmp(A, B);
}
static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
if (&A == &B)
return false;
if (int N = StrCmpOptionName(A.Name, B.Name))
return N < 0;
for (const char * const *APre = A.Prefixes,
* const *BPre = B.Prefixes;
*APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
if (int N = StrCmpOptionName(*APre, *BPre))
return N < 0;
}
// Names are the same, check that classes are in order; exactly one
// should be joined, and it should succeed the other.
assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
"Unexpected classes for options with same name.");
return B.Kind == Option::JoinedClass;
}
#endif
// Support lower_bound between info and an option name.
static inline bool operator<(const OptTable::Info &I, const char *Name) {
return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
}
}
}
OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
bool _IgnoreCase)
: OptionInfos(_OptionInfos),
NumOptionInfos(_NumOptionInfos),
IgnoreCase(_IgnoreCase),
TheInputOptionID(0),
TheUnknownOptionID(0),
FirstSearchableIndex(0)
{
// Explicitly zero initialize the error to work around a bug in array
// value-initialization on MinGW with gcc 4.3.5.
// Find start of normal options.
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Kind = getInfo(i + 1).Kind;
if (Kind == Option::InputClass) {
assert(!TheInputOptionID && "Cannot have multiple input options!");
TheInputOptionID = getInfo(i + 1).ID;
} else if (Kind == Option::UnknownClass) {
assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
TheUnknownOptionID = getInfo(i + 1).ID;
} else if (Kind != Option::GroupClass) {
FirstSearchableIndex = i;
break;
}
}
assert(FirstSearchableIndex != 0 && "No searchable options?");
#ifndef NDEBUG
// Check that everything after the first searchable option is a
// regular option class.
for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
Kind != Option::GroupClass) &&
"Special options should be defined first!");
}
// Check that options are in order.
for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
if (!(getInfo(i) < getInfo(i + 1))) {
getOption(i).dump();
getOption(i + 1).dump();
llvm_unreachable("Options are not in order!");
}
}
#endif
// Build prefixes.
for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
i != e; ++i) {
if (const char *const *P = getInfo(i).Prefixes) {
for (; *P != nullptr; ++P) {
PrefixesUnion.insert(*P);
}
}
}
// Build prefix chars.
for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
E = PrefixesUnion.end(); I != E; ++I) {
StringRef Prefix = I->getKey();
for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
C != CE; ++C)
if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
== PrefixChars.end())
PrefixChars.push_back(*C);
}
}
OptTable::~OptTable() {
}
const Option OptTable::getOption(OptSpecifier Opt) const {
unsigned id = Opt.getID();
if (id == 0)
return Option(nullptr, nullptr);
assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
return Option(&getInfo(id), this);
}
static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
if (Arg == "-")
return true;
for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
E = Prefixes.end(); I != E; ++I)
if (Arg.startswith(I->getKey()))
return false;
return true;
}
/// \returns Matched size. 0 means no match.
static unsigned matchOption(const OptTable::Info *I, StringRef Str,
bool IgnoreCase) {
for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
StringRef Prefix(*Pre);
if (Str.startswith(Prefix)) {
StringRef Rest = Str.substr(Prefix.size());
bool Matched = IgnoreCase
? Rest.startswith_lower(I->Name)
: Rest.startswith(I->Name);
if (Matched)
return Prefix.size() + StringRef(I->Name).size();
}
}
return 0;
}
Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
unsigned Prev = Index;
const char *Str = Args.getArgString(Index);
// Anything that doesn't start with PrefixesUnion is an input, as is '-'
// itself.
if (isInput(PrefixesUnion, Str))
return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
const Info *Start = OptionInfos + FirstSearchableIndex;
const Info *End = OptionInfos + getNumOptions();
StringRef Name = StringRef(Str).ltrim(PrefixChars);
// Search for the first next option which could be a prefix.
Start = std::lower_bound(Start, End, Name.data());
// Options are stored in sorted order, with '\0' at the end of the
// alphabet. Since the only options which can accept a string must
// prefix it, we iteratively search for the next option which could
// be a prefix.
//
// FIXME: This is searching much more than necessary, but I am
// blanking on the simplest way to make it fast. We can solve this
// problem when we move to TableGen.
for (; Start != End; ++Start) {
unsigned ArgSize = 0;
// Scan for first option which is a proper prefix.
for (; Start != End; ++Start)
if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
break;
if (Start == End)
break;
Option Opt(Start, this);
if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
continue;
if (Opt.hasFlag(FlagsToExclude))
continue;
// See if this option matches.
if (Arg *A = Opt.accept(Args, Index, ArgSize))
return A;
// Otherwise, see if this argument was missing values.
if (Prev != Index)
return nullptr;
}
// If we failed to find an option and this arg started with /, then it's
// probably an input path.
if (Str[0] == '/')
return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
}
InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
const char *const *ArgEnd,
unsigned &MissingArgIndex,
unsigned &MissingArgCount,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
// FIXME: Handle '@' args (or at least error on them).
MissingArgIndex = MissingArgCount = 0;
unsigned Index = 0, End = ArgEnd - ArgBegin;
while (Index < End) {
// Ignore empty arguments (other things may still take them as arguments).
StringRef Str = Args->getArgString(Index);
if (Str == "") {
++Index;
continue;
}
unsigned Prev = Index;
Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
assert(Index > Prev && "Parser failed to consume argument.");
// Check for missing argument error.
if (!A) {
assert(Index >= End && "Unexpected parser error.");
assert(Index - Prev - 1 && "No missing arguments!");
MissingArgIndex = Prev;
MissingArgCount = Index - Prev - 1;
break;
}
Args->append(A);
}
return Args;
}
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
const Option O = Opts.getOption(Id);
std::string Name = O.getPrefixedName();
// Add metavar, if used.
switch (O.getKind()) {
case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
llvm_unreachable("Invalid option with help text.");
case Option::MultiArgClass:
llvm_unreachable("Cannot print metavar for this kind of option.");
case Option::FlagClass:
break;
case Option::SeparateClass: case Option::JoinedOrSeparateClass:
case Option::RemainingArgsClass:
Name += ' ';
// FALLTHROUGH
case Option::JoinedClass: case Option::CommaJoinedClass:
case Option::JoinedAndSeparateClass:
if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
Name += MetaVarName;
else
Name += "<value>";
break;
}
return Name;
}
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
std::vector<std::pair<std::string,
const char*> > &OptionHelp) {
OS << Title << ":\n";
// Find the maximum option length.
unsigned OptionFieldWidth = 0;
for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
// Skip titles.
if (!OptionHelp[i].second)
continue;
// Limit the amount of padding we are willing to give up for alignment.
unsigned Length = OptionHelp[i].first.size();
if (Length <= 23)
OptionFieldWidth = std::max(OptionFieldWidth, Length);
}
const unsigned InitialPad = 2;
for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
const std::string &Option = OptionHelp[i].first;
int Pad = OptionFieldWidth - int(Option.size());
OS.indent(InitialPad) << Option;
// Break on long option names.
if (Pad < 0) {
OS << "\n";
Pad = OptionFieldWidth + InitialPad;
}
OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
}
}
static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
unsigned GroupID = Opts.getOptionGroupID(Id);
// If not in a group, return the default help group.
if (!GroupID)
return "OPTIONS";
// Abuse the help text of the option groups to store the "help group"
// name.
//
// FIXME: Split out option groups.
if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
return GroupHelp;
// Otherwise keep looking.
return getOptionHelpGroup(Opts, GroupID);
}
void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
bool ShowHidden) const {
PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
(ShowHidden ? 0 : HelpHidden));
}
void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
OS << "OVERVIEW: " << Title << "\n";
OS << '\n';
OS << "USAGE: " << Name << " [options] <inputs>\n";
OS << '\n';
// Render help text into a map of group-name to a list of (option, help)
// pairs.
typedef std::map<std::string,
std::vector<std::pair<std::string, const char*> > > helpmap_ty;
helpmap_ty GroupedOptionHelp;
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Id = i + 1;
// FIXME: Split out option groups.
if (getOptionKind(Id) == Option::GroupClass)
continue;
unsigned Flags = getInfo(Id).Flags;
if (FlagsToInclude && !(Flags & FlagsToInclude))
continue;
if (Flags & FlagsToExclude)
continue;
if (const char *Text = getOptionHelpText(Id)) {
const char *HelpGroup = getOptionHelpGroup(*this, Id);
const std::string &OptName = getOptionHelpName(*this, Id);
GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
}
}
for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
ie = GroupedOptionHelp.end(); it != ie; ++it) {
if (it != GroupedOptionHelp .begin())
OS << "\n";
PrintHelpOptionList(OS, it->first, it->second);
}
OS.flush();
}
<commit_msg>[Option] Support MultiArg in --help<commit_after>//===--- OptTable.cpp - Option Table Implementation -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cctype>
#include <map>
using namespace llvm;
using namespace llvm::opt;
namespace llvm {
namespace opt {
// Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
// with an exceptions. '\0' comes at the end of the alphabet instead of the
// beginning (thus options precede any other options which prefix them).
static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
const char *X = A, *Y = B;
char a = tolower(*A), b = tolower(*B);
while (a == b) {
if (a == '\0')
return 0;
a = tolower(*++X);
b = tolower(*++Y);
}
if (a == '\0') // A is a prefix of B.
return 1;
if (b == '\0') // B is a prefix of A.
return -1;
// Otherwise lexicographic.
return (a < b) ? -1 : 1;
}
#ifndef NDEBUG
static int StrCmpOptionName(const char *A, const char *B) {
if (int N = StrCmpOptionNameIgnoreCase(A, B))
return N;
return strcmp(A, B);
}
static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
if (&A == &B)
return false;
if (int N = StrCmpOptionName(A.Name, B.Name))
return N < 0;
for (const char * const *APre = A.Prefixes,
* const *BPre = B.Prefixes;
*APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
if (int N = StrCmpOptionName(*APre, *BPre))
return N < 0;
}
// Names are the same, check that classes are in order; exactly one
// should be joined, and it should succeed the other.
assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
"Unexpected classes for options with same name.");
return B.Kind == Option::JoinedClass;
}
#endif
// Support lower_bound between info and an option name.
static inline bool operator<(const OptTable::Info &I, const char *Name) {
return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
}
}
}
OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos,
bool _IgnoreCase)
: OptionInfos(_OptionInfos),
NumOptionInfos(_NumOptionInfos),
IgnoreCase(_IgnoreCase),
TheInputOptionID(0),
TheUnknownOptionID(0),
FirstSearchableIndex(0)
{
// Explicitly zero initialize the error to work around a bug in array
// value-initialization on MinGW with gcc 4.3.5.
// Find start of normal options.
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Kind = getInfo(i + 1).Kind;
if (Kind == Option::InputClass) {
assert(!TheInputOptionID && "Cannot have multiple input options!");
TheInputOptionID = getInfo(i + 1).ID;
} else if (Kind == Option::UnknownClass) {
assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
TheUnknownOptionID = getInfo(i + 1).ID;
} else if (Kind != Option::GroupClass) {
FirstSearchableIndex = i;
break;
}
}
assert(FirstSearchableIndex != 0 && "No searchable options?");
#ifndef NDEBUG
// Check that everything after the first searchable option is a
// regular option class.
for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
Kind != Option::GroupClass) &&
"Special options should be defined first!");
}
// Check that options are in order.
for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
if (!(getInfo(i) < getInfo(i + 1))) {
getOption(i).dump();
getOption(i + 1).dump();
llvm_unreachable("Options are not in order!");
}
}
#endif
// Build prefixes.
for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
i != e; ++i) {
if (const char *const *P = getInfo(i).Prefixes) {
for (; *P != nullptr; ++P) {
PrefixesUnion.insert(*P);
}
}
}
// Build prefix chars.
for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(),
E = PrefixesUnion.end(); I != E; ++I) {
StringRef Prefix = I->getKey();
for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
C != CE; ++C)
if (std::find(PrefixChars.begin(), PrefixChars.end(), *C)
== PrefixChars.end())
PrefixChars.push_back(*C);
}
}
OptTable::~OptTable() {
}
const Option OptTable::getOption(OptSpecifier Opt) const {
unsigned id = Opt.getID();
if (id == 0)
return Option(nullptr, nullptr);
assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
return Option(&getInfo(id), this);
}
static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) {
if (Arg == "-")
return true;
for (llvm::StringSet<>::const_iterator I = Prefixes.begin(),
E = Prefixes.end(); I != E; ++I)
if (Arg.startswith(I->getKey()))
return false;
return true;
}
/// \returns Matched size. 0 means no match.
static unsigned matchOption(const OptTable::Info *I, StringRef Str,
bool IgnoreCase) {
for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
StringRef Prefix(*Pre);
if (Str.startswith(Prefix)) {
StringRef Rest = Str.substr(Prefix.size());
bool Matched = IgnoreCase
? Rest.startswith_lower(I->Name)
: Rest.startswith(I->Name);
if (Matched)
return Prefix.size() + StringRef(I->Name).size();
}
}
return 0;
}
Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
unsigned Prev = Index;
const char *Str = Args.getArgString(Index);
// Anything that doesn't start with PrefixesUnion is an input, as is '-'
// itself.
if (isInput(PrefixesUnion, Str))
return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
const Info *Start = OptionInfos + FirstSearchableIndex;
const Info *End = OptionInfos + getNumOptions();
StringRef Name = StringRef(Str).ltrim(PrefixChars);
// Search for the first next option which could be a prefix.
Start = std::lower_bound(Start, End, Name.data());
// Options are stored in sorted order, with '\0' at the end of the
// alphabet. Since the only options which can accept a string must
// prefix it, we iteratively search for the next option which could
// be a prefix.
//
// FIXME: This is searching much more than necessary, but I am
// blanking on the simplest way to make it fast. We can solve this
// problem when we move to TableGen.
for (; Start != End; ++Start) {
unsigned ArgSize = 0;
// Scan for first option which is a proper prefix.
for (; Start != End; ++Start)
if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
break;
if (Start == End)
break;
Option Opt(Start, this);
if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
continue;
if (Opt.hasFlag(FlagsToExclude))
continue;
// See if this option matches.
if (Arg *A = Opt.accept(Args, Index, ArgSize))
return A;
// Otherwise, see if this argument was missing values.
if (Prev != Index)
return nullptr;
}
// If we failed to find an option and this arg started with /, then it's
// probably an input path.
if (Str[0] == '/')
return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
}
InputArgList *OptTable::ParseArgs(const char *const *ArgBegin,
const char *const *ArgEnd,
unsigned &MissingArgIndex,
unsigned &MissingArgCount,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
// FIXME: Handle '@' args (or at least error on them).
MissingArgIndex = MissingArgCount = 0;
unsigned Index = 0, End = ArgEnd - ArgBegin;
while (Index < End) {
// Ignore empty arguments (other things may still take them as arguments).
StringRef Str = Args->getArgString(Index);
if (Str == "") {
++Index;
continue;
}
unsigned Prev = Index;
Arg *A = ParseOneArg(*Args, Index, FlagsToInclude, FlagsToExclude);
assert(Index > Prev && "Parser failed to consume argument.");
// Check for missing argument error.
if (!A) {
assert(Index >= End && "Unexpected parser error.");
assert(Index - Prev - 1 && "No missing arguments!");
MissingArgIndex = Prev;
MissingArgCount = Index - Prev - 1;
break;
}
Args->append(A);
}
return Args;
}
static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
const Option O = Opts.getOption(Id);
std::string Name = O.getPrefixedName();
// Add metavar, if used.
switch (O.getKind()) {
case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
llvm_unreachable("Invalid option with help text.");
case Option::MultiArgClass:
if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
// For MultiArgs, metavar is full list of all argument names.
Name += ' ';
Name += MetaVarName;
}
else {
// For MultiArgs<N>, if metavar not supplied, print <value> N times.
for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
Name += " <value>";
}
}
break;
case Option::FlagClass:
break;
case Option::SeparateClass: case Option::JoinedOrSeparateClass:
case Option::RemainingArgsClass:
Name += ' ';
// FALLTHROUGH
case Option::JoinedClass: case Option::CommaJoinedClass:
case Option::JoinedAndSeparateClass:
if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
Name += MetaVarName;
else
Name += "<value>";
break;
}
return Name;
}
static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
std::vector<std::pair<std::string,
const char*> > &OptionHelp) {
OS << Title << ":\n";
// Find the maximum option length.
unsigned OptionFieldWidth = 0;
for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
// Skip titles.
if (!OptionHelp[i].second)
continue;
// Limit the amount of padding we are willing to give up for alignment.
unsigned Length = OptionHelp[i].first.size();
if (Length <= 23)
OptionFieldWidth = std::max(OptionFieldWidth, Length);
}
const unsigned InitialPad = 2;
for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
const std::string &Option = OptionHelp[i].first;
int Pad = OptionFieldWidth - int(Option.size());
OS.indent(InitialPad) << Option;
// Break on long option names.
if (Pad < 0) {
OS << "\n";
Pad = OptionFieldWidth + InitialPad;
}
OS.indent(Pad + 1) << OptionHelp[i].second << '\n';
}
}
static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
unsigned GroupID = Opts.getOptionGroupID(Id);
// If not in a group, return the default help group.
if (!GroupID)
return "OPTIONS";
// Abuse the help text of the option groups to store the "help group"
// name.
//
// FIXME: Split out option groups.
if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
return GroupHelp;
// Otherwise keep looking.
return getOptionHelpGroup(Opts, GroupID);
}
void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
bool ShowHidden) const {
PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
(ShowHidden ? 0 : HelpHidden));
}
void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
unsigned FlagsToInclude,
unsigned FlagsToExclude) const {
OS << "OVERVIEW: " << Title << "\n";
OS << '\n';
OS << "USAGE: " << Name << " [options] <inputs>\n";
OS << '\n';
// Render help text into a map of group-name to a list of (option, help)
// pairs.
typedef std::map<std::string,
std::vector<std::pair<std::string, const char*> > > helpmap_ty;
helpmap_ty GroupedOptionHelp;
for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
unsigned Id = i + 1;
// FIXME: Split out option groups.
if (getOptionKind(Id) == Option::GroupClass)
continue;
unsigned Flags = getInfo(Id).Flags;
if (FlagsToInclude && !(Flags & FlagsToInclude))
continue;
if (Flags & FlagsToExclude)
continue;
if (const char *Text = getOptionHelpText(Id)) {
const char *HelpGroup = getOptionHelpGroup(*this, Id);
const std::string &OptName = getOptionHelpName(*this, Id);
GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text));
}
}
for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
ie = GroupedOptionHelp.end(); it != ie; ++it) {
if (it != GroupedOptionHelp .begin())
OS << "\n";
PrintHelpOptionList(OS, it->first, it->second);
}
OS.flush();
}
<|endoftext|> |
<commit_before>/*
* HypothesisColl.cpp
*
* Created on: 26 Feb 2016
* Author: hieu
*/
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"
using namespace std;
namespace Moses2
{
HypothesisColl::HypothesisColl(const ManagerBase &mgr)
:m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{
//m_bestScore = -std::numeric_limits<float>::infinity();
//m_minBeamScore = -std::numeric_limits<float>::infinity();
m_worseScore = std::numeric_limits<float>::infinity();
}
const HypothesisBase *HypothesisColl::GetBestHypo() const
{
if (GetSize() == 0) {
return NULL;
}
if (m_sortedHypos) {
return (*m_sortedHypos)[0];
}
SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
const HypothesisBase *bestHypo;
BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
if (hypo->GetFutureScore() > bestScore) {
bestScore = hypo->GetFutureScore();
bestHypo = hypo;
}
}
return bestHypo;
}
void HypothesisColl::Add(
const ManagerBase &mgr,
HypothesisBase *hypo,
Recycler<HypothesisBase*> &hypoRecycle,
ArcLists &arcLists)
{
size_t maxStackSize = mgr.system.options.search.stack_size;
if (GetSize() > maxStackSize * 2) {
//cerr << "maxStackSize=" << maxStackSize << " " << GetSize() << endl;
PruneHypos(mgr, mgr.arcLists);
}
SCORE futureScore = hypo->GetFutureScore();
/*
cerr << "scores:"
<< futureScore << " "
<< m_bestScore << " "
<< m_minBeamScore << " "
<< GetSize() << " "
<< endl;
*/
if (GetSize() >= maxStackSize && futureScore < m_worseScore) {
// beam threshold or really bad hypo that won't make the pruning cut
// as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
//cerr << "Discard, really bad score:" << hypo->Debug(system) << endl;
hypoRecycle.Recycle(hypo);
return;
}
/*
if (futureScore < m_minBeamScore) {
// beam threshold or really bad hypo that won't make the pruning cut
// as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
//cerr << "Discard, below beam:" << hypo->Debug(system) << endl;
hypoRecycle.Recycle(hypo);
return;
}
if (futureScore > m_bestScore) {
m_bestScore = hypo->GetFutureScore();
// this may also affect the worst score
SCORE beamWidth = system.options.search.beam_width;
//cerr << "beamWidth=" << beamWidth << endl;
if ( m_bestScore + beamWidth > m_minBeamScore ) {
m_minBeamScore = m_bestScore + beamWidth;
}
}
//cerr << "OK:" << hypo->Debug(system) << endl;
*/
StackAdd added = Add(hypo);
size_t nbestSize = mgr.system.options.nbest.nbest_size;
if (nbestSize) {
arcLists.AddArc(added.added, hypo, added.other);
}
else {
if (!added.added) {
hypoRecycle.Recycle(hypo);
}
else {
if (added.other) {
hypoRecycle.Recycle(added.other);
}
if (GetSize() <= maxStackSize && hypo->GetFutureScore() < m_worseScore) {
m_worseScore = futureScore;
}
}
}
}
StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);
// CHECK RECOMBINATION
if (addRet.second) {
// equiv hypo doesn't exists
return StackAdd(true, NULL);
}
else {
HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
// incoming hypo is better than the one we have
const HypothesisBase * const &hypoExisting1 = *addRet.first;
const HypothesisBase *&hypoExisting2 =
const_cast<const HypothesisBase *&>(hypoExisting1);
hypoExisting2 = hypo;
return StackAdd(true, hypoExisting);
}
else {
// already storing the best hypo. discard incoming hypo
return StackAdd(false, hypoExisting);
}
}
//assert(false);
}
const Hypotheses &HypothesisColl::GetSortedAndPruneHypos(
const ManagerBase &mgr,
ArcLists &arcLists) const
{
if (m_sortedHypos == NULL) {
// create sortedHypos first
MemPool &pool = mgr.GetPool();
m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
m_coll.size());
size_t ind = 0;
BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
(*m_sortedHypos)[ind] = hypo;
++ind;
}
SortAndPruneHypos(mgr, arcLists);
}
return *m_sortedHypos;
}
const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos() const
{
UTIL_THROW_IF2(m_sortedHypos == NULL, "m_sortedHypos must be sorted beforehand");
return *m_sortedHypos;
}
void HypothesisColl::SortAndPruneHypos(const ManagerBase &mgr,
ArcLists &arcLists) const
{
size_t stackSize = mgr.system.options.search.stack_size;
Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();
/*
cerr << "UNSORTED hypos: ";
BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
}
cerr << endl;
*/
Hypotheses::iterator iterMiddle;
iterMiddle =
(stackSize == 0 || m_sortedHypos->size() < stackSize) ?
m_sortedHypos->end() : m_sortedHypos->begin() + stackSize;
std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
HypothesisFutureScoreOrderer());
// prune
if (stackSize && m_sortedHypos->size() > stackSize) {
for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
recycler.Recycle(hypo);
// delete from arclist
if (mgr.system.options.nbest.nbest_size) {
arcLists.Delete(hypo);
}
}
m_sortedHypos->resize(stackSize);
}
/*
cerr << "sorted hypos: ";
for (size_t i = 0; i < m_sortedHypos->size(); ++i) {
const HypothesisBase *hypo = (*m_sortedHypos)[i];
cerr << hypo << " ";
}
cerr << endl;
*/
}
void HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)
{
size_t maxStackSize = mgr.system.options.search.stack_size;
Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();
/*
cerr << "UNSORTED hypos: ";
BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
}
cerr << endl;
*/
vector<const HypothesisBase*> sortedHypos(GetSize());
size_t ind = 0;
BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
sortedHypos[ind] = hypo;
++ind;
}
vector<const HypothesisBase*>::iterator iterMiddle;
iterMiddle =
(maxStackSize == 0 || sortedHypos.size() < maxStackSize) ?
sortedHypos.end() : sortedHypos.begin() + maxStackSize;
std::partial_sort(sortedHypos.begin(), iterMiddle, sortedHypos.end(),
HypothesisFutureScoreOrderer());
// prune
if (maxStackSize && sortedHypos.size() > maxStackSize) {
for (size_t i = maxStackSize; i < sortedHypos.size(); ++i) {
HypothesisBase *hypo = const_cast<HypothesisBase*>((sortedHypos)[i]);
// delete from arclist
if (mgr.system.options.nbest.nbest_size) {
arcLists.Delete(hypo);
}
// delete from collection
Delete(hypo);
//recycler.Recycle(hypo);
}
}
/*
cerr << "sorted hypos: ";
for (size_t i = 0; i < sortedHypos.size(); ++i) {
const HypothesisBase *hypo = sortedHypos[i];
cerr << hypo << " ";
}
cerr << endl;
*/
}
void HypothesisColl::Delete(const HypothesisBase *hypo)
{
cerr << "hypo=" << hypo << " " << m_coll.size() << endl;
_HCType::const_iterator iter = m_coll.find(hypo);
UTIL_THROW_IF2(iter == m_coll.end(), "Can't find hypo");
m_coll.erase(iter);
}
void HypothesisColl::Clear()
{
m_sortedHypos = NULL;
m_coll.clear();
//m_bestScore = -std::numeric_limits<float>::infinity();
//m_minBeamScore = -std::numeric_limits<float>::infinity();
m_worseScore = std::numeric_limits<float>::infinity();
}
std::string HypothesisColl::Debug(const System &system) const
{
stringstream out;
BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
out << hypo->Debug(system);
out << std::endl << std::endl;
}
return out.str();
}
} /* namespace Moses2 */
<commit_msg>debug<commit_after>/*
* HypothesisColl.cpp
*
* Created on: 26 Feb 2016
* Author: hieu
*/
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"
using namespace std;
namespace Moses2
{
HypothesisColl::HypothesisColl(const ManagerBase &mgr)
:m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{
//m_bestScore = -std::numeric_limits<float>::infinity();
//m_minBeamScore = -std::numeric_limits<float>::infinity();
m_worseScore = std::numeric_limits<float>::infinity();
}
const HypothesisBase *HypothesisColl::GetBestHypo() const
{
if (GetSize() == 0) {
return NULL;
}
if (m_sortedHypos) {
return (*m_sortedHypos)[0];
}
SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
const HypothesisBase *bestHypo;
BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
if (hypo->GetFutureScore() > bestScore) {
bestScore = hypo->GetFutureScore();
bestHypo = hypo;
}
}
return bestHypo;
}
void HypothesisColl::Add(
const ManagerBase &mgr,
HypothesisBase *hypo,
Recycler<HypothesisBase*> &hypoRecycle,
ArcLists &arcLists)
{
size_t maxStackSize = mgr.system.options.search.stack_size;
if (GetSize() > maxStackSize * 2) {
//cerr << "maxStackSize=" << maxStackSize << " " << GetSize() << endl;
PruneHypos(mgr, mgr.arcLists);
}
SCORE futureScore = hypo->GetFutureScore();
/*
cerr << "scores:"
<< futureScore << " "
<< m_bestScore << " "
<< m_minBeamScore << " "
<< GetSize() << " "
<< endl;
*/
if (GetSize() >= maxStackSize && futureScore < m_worseScore) {
// beam threshold or really bad hypo that won't make the pruning cut
// as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
//cerr << "Discard, really bad score:" << hypo->Debug(system) << endl;
hypoRecycle.Recycle(hypo);
return;
}
/*
if (futureScore < m_minBeamScore) {
// beam threshold or really bad hypo that won't make the pruning cut
// as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
//cerr << "Discard, below beam:" << hypo->Debug(system) << endl;
hypoRecycle.Recycle(hypo);
return;
}
if (futureScore > m_bestScore) {
m_bestScore = hypo->GetFutureScore();
// this may also affect the worst score
SCORE beamWidth = system.options.search.beam_width;
//cerr << "beamWidth=" << beamWidth << endl;
if ( m_bestScore + beamWidth > m_minBeamScore ) {
m_minBeamScore = m_bestScore + beamWidth;
}
}
//cerr << "OK:" << hypo->Debug(system) << endl;
*/
StackAdd added = Add(hypo);
size_t nbestSize = mgr.system.options.nbest.nbest_size;
if (nbestSize) {
arcLists.AddArc(added.added, hypo, added.other);
}
else {
if (!added.added) {
hypoRecycle.Recycle(hypo);
}
else {
if (added.other) {
hypoRecycle.Recycle(added.other);
}
if (GetSize() <= maxStackSize && hypo->GetFutureScore() < m_worseScore) {
m_worseScore = futureScore;
}
}
}
}
StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);
// CHECK RECOMBINATION
if (addRet.second) {
// equiv hypo doesn't exists
return StackAdd(true, NULL);
}
else {
HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
// incoming hypo is better than the one we have
const HypothesisBase * const &hypoExisting1 = *addRet.first;
const HypothesisBase *&hypoExisting2 =
const_cast<const HypothesisBase *&>(hypoExisting1);
hypoExisting2 = hypo;
return StackAdd(true, hypoExisting);
}
else {
// already storing the best hypo. discard incoming hypo
return StackAdd(false, hypoExisting);
}
}
//assert(false);
}
const Hypotheses &HypothesisColl::GetSortedAndPruneHypos(
const ManagerBase &mgr,
ArcLists &arcLists) const
{
if (m_sortedHypos == NULL) {
// create sortedHypos first
MemPool &pool = mgr.GetPool();
m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
m_coll.size());
size_t ind = 0;
BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
(*m_sortedHypos)[ind] = hypo;
++ind;
}
SortAndPruneHypos(mgr, arcLists);
}
return *m_sortedHypos;
}
const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos() const
{
UTIL_THROW_IF2(m_sortedHypos == NULL, "m_sortedHypos must be sorted beforehand");
return *m_sortedHypos;
}
void HypothesisColl::SortAndPruneHypos(const ManagerBase &mgr,
ArcLists &arcLists) const
{
size_t stackSize = mgr.system.options.search.stack_size;
Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();
/*
cerr << "UNSORTED hypos: ";
BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
}
cerr << endl;
*/
Hypotheses::iterator iterMiddle;
iterMiddle =
(stackSize == 0 || m_sortedHypos->size() < stackSize) ?
m_sortedHypos->end() : m_sortedHypos->begin() + stackSize;
std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
HypothesisFutureScoreOrderer());
// prune
if (stackSize && m_sortedHypos->size() > stackSize) {
for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
recycler.Recycle(hypo);
// delete from arclist
if (mgr.system.options.nbest.nbest_size) {
arcLists.Delete(hypo);
}
}
m_sortedHypos->resize(stackSize);
}
/*
cerr << "sorted hypos: ";
for (size_t i = 0; i < m_sortedHypos->size(); ++i) {
const HypothesisBase *hypo = (*m_sortedHypos)[i];
cerr << hypo << " ";
}
cerr << endl;
*/
}
void HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)
{
size_t maxStackSize = mgr.system.options.search.stack_size;
Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();
/*
cerr << "UNSORTED hypos: ";
BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
}
cerr << endl;
*/
vector<const HypothesisBase*> sortedHypos(GetSize());
size_t ind = 0;
BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
sortedHypos[ind] = hypo;
++ind;
}
vector<const HypothesisBase*>::iterator iterMiddle;
iterMiddle =
(maxStackSize == 0 || sortedHypos.size() < maxStackSize) ?
sortedHypos.end() : sortedHypos.begin() + maxStackSize;
std::partial_sort(sortedHypos.begin(), iterMiddle, sortedHypos.end(),
HypothesisFutureScoreOrderer());
// prune
if (maxStackSize && sortedHypos.size() > maxStackSize) {
for (size_t i = maxStackSize; i < sortedHypos.size(); ++i) {
HypothesisBase *hypo = const_cast<HypothesisBase*>((sortedHypos)[i]);
// delete from arclist
if (mgr.system.options.nbest.nbest_size) {
arcLists.Delete(hypo);
}
// delete from collection
Delete(hypo);
recycler.Recycle(hypo);
}
}
/*
cerr << "sorted hypos: ";
for (size_t i = 0; i < sortedHypos.size(); ++i) {
const HypothesisBase *hypo = sortedHypos[i];
cerr << hypo << " ";
}
cerr << endl;
*/
}
void HypothesisColl::Delete(const HypothesisBase *hypo)
{
//cerr << "hypo=" << hypo << " " << m_coll.size() << endl;
_HCType::const_iterator iter = m_coll.find(hypo);
UTIL_THROW_IF2(iter == m_coll.end(), "Can't find hypo");
m_coll.erase(iter);
}
void HypothesisColl::Clear()
{
m_sortedHypos = NULL;
m_coll.clear();
//m_bestScore = -std::numeric_limits<float>::infinity();
//m_minBeamScore = -std::numeric_limits<float>::infinity();
m_worseScore = std::numeric_limits<float>::infinity();
}
std::string HypothesisColl::Debug(const System &system) const
{
stringstream out;
BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
out << hypo->Debug(system);
out << std::endl << std::endl;
}
return out.str();
}
} /* namespace Moses2 */
<|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 <stdint.h>
#include <sys/stat.h>
#include <ostream>
#include <thread>
#include <unistd.h>
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/proto_desc.h"
#include "paddle/fluid/framework/threadpool.h"
#include "paddle/fluid/operators/detail/grpc_server.h"
#include "paddle/fluid/operators/detail/sendrecvop_utils.h"
#include "paddle/fluid/operators/detail/simple_block_queue.h"
#include "paddle/fluid/string/printf.h"
namespace paddle {
namespace operators {
constexpr char kOptimizeBlock[] = "OptimizeBlock";
void RunServer(std::shared_ptr<detail::AsyncGRPCServer> service) {
service->RunSyncUpdate();
VLOG(4) << "RunServer thread end";
}
static void CreateTensorFromMessageType(framework::Variable *var,
sendrecv::VarType var_type) {
if (var_type == sendrecv::VarType::LOD_TENSOR) {
var->GetMutable<framework::LoDTensor>();
} else if (var_type == sendrecv::VarType::SELECTED_ROWS) {
var->GetMutable<framework::SelectedRows>();
} else {
PADDLE_THROW(
"VariableMessage type %d is not in "
"[LoDTensor, SelectedRows]",
var_type);
}
}
class ListenAndServOp : public framework::OperatorBase {
public:
ListenAndServOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {
if (!rpc_service_) {
std::string endpoint = Attr<std::string>("endpoint");
rpc_service_.reset(new detail::AsyncGRPCServer(endpoint));
server_thread_.reset(new std::thread(RunServer, rpc_service_));
}
}
void Stop() override {
detail::MessageWithName term_msg;
term_msg.first = LISTEN_TERMINATE_MESSAGE;
rpc_service_->Push(term_msg);
rpc_service_->ShutDown();
server_thread_->join();
}
void RunImpl(const framework::Scope &scope,
const platform::Place &dev_place) const override {
platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
auto &dev_ctx = *pool.Get(dev_place);
framework::Scope &recv_scope = scope.NewScope();
// FIXME(Yancey1989): initialize rpc server with lazy mode.
rpc_service_->SetScope(&recv_scope);
rpc_service_->SetDevCtx(&dev_ctx);
auto ins = Inputs("X");
auto fan_in = Attr<int>("Fanin");
auto *block = Attr<framework::BlockDesc *>(kOptimizeBlock);
auto *program = block->Program();
int num_blocks = program->Size();
PADDLE_ENFORCE_GE(num_blocks, 2,
"server program should have at least 2 blocks");
framework::Executor executor(dev_place);
// TODO(typhoonzero): change this to a while_op for every cluster-batch.
bool exit_flag = false;
// Record received sparse variables, so that
// we could reset those after execute optimize program
std::vector<framework::Variable *> sparse_vars;
while (!exit_flag) {
// Get from multiple trainers, we don't care about the order in which
// the gradients arrives, just add suffix 0~n and merge the gradient.
rpc_service_->SetCond(0);
size_t recv_var_cnt = 0;
int batch_barrier = 0;
while (batch_barrier != fan_in) {
const detail::MessageWithName &v = rpc_service_->Get();
auto recv_var_name = v.first;
if (recv_var_name == LISTEN_TERMINATE_MESSAGE) {
LOG(INFO) << "received terminate message and exit";
exit_flag = true;
break;
} else if (recv_var_name == BATCH_BARRIER_MESSAGE) {
VLOG(3) << "recv batch barrier message";
batch_barrier++;
continue;
} else {
VLOG(3) << "received grad: " << recv_var_name;
recv_var_cnt++;
auto *var = recv_scope.FindVar(recv_var_name);
if (var == nullptr) {
LOG(ERROR) << "Can not find server side var: " << recv_var_name;
PADDLE_THROW("Can not find server side var");
}
detail::DeserializeFromMessage(v.second, dev_ctx, var);
if (var->IsType<framework::SelectedRows>()) {
sparse_vars.push_back(var);
}
}
}
if (exit_flag) {
rpc_service_->SetCond(1);
rpc_service_->ShutDown();
break;
}
// put optimize blocks in the thread pool to start run, the last block
// should be global ops.
// NOTE: if is_gpu_place, CUDA kernels are laugched by multiple threads
// and this will still work.
std::vector<std::future<void>> fs;
// block0 contains only listen_and_serv op, start run from block1.
for (int blkid = 1; blkid < num_blocks - 1; ++blkid) {
fs.push_back(framework::Async([&executor, &program, &recv_scope,
blkid]() {
int run_block = blkid; // thread local
try {
executor.Run(*program, &recv_scope, run_block,
false /*create_local_scope*/, false /*create_vars*/);
} catch (std::exception &e) {
LOG(ERROR) << "run sub program error " << e.what();
}
}));
}
for (int i = 0; i < num_blocks - 2; ++i) fs[i].wait();
// Run global block at final step
if (num_blocks > 2) {
try {
executor.Run(*program, &recv_scope, num_blocks - 1,
false /*create_local_scope*/, false /*create_vars*/);
} catch (std::exception &e) {
LOG(ERROR) << "run sub program error " << e.what();
}
}
// Reset the received sparse variables, the sum operator would not
// sum the input sparse variables which rows is empty at the next
// mini-batch.
// TODO(Yancey1989): move the reset action into an operator, we couldn't
// have any hide logic in the operator.
for (auto &var : sparse_vars) {
var->GetMutable<framework::SelectedRows>()->mutable_rows()->clear();
}
rpc_service_->SetCond(1);
// FIXME(typhoonzero): use another condition to sync wait clients get.
rpc_service_->WaitClientGet(fan_in);
sparse_vars.clear();
} // while(true)
}
protected:
std::shared_ptr<detail::AsyncGRPCServer> rpc_service_;
std::shared_ptr<std::thread> server_thread_;
};
class ListenAndServOpMaker : public framework::OpProtoAndCheckerMaker {
public:
ListenAndServOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("X", "(Tensor) Variables that server recv.").AsDuplicable();
AddComment(R"DOC(
ListenAndServ operator
This operator will start a RPC server which can receive variables
from send_op and send back variables to recv_op.
)DOC");
AddAttr<std::string>("endpoint",
"(string, default 127.0.0.1:6164)"
"IP address to listen on.")
.SetDefault("127.0.0.1:6164")
.AddCustomChecker([](const std::string &ip) { return !ip.empty(); });
AddAttr<framework::BlockDesc *>(kOptimizeBlock,
"BlockID to run on server side.");
AddAttr<int>("Fanin", "How many clients send to this server.")
.SetDefault(1);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(listen_and_serv, ops::ListenAndServOp,
ops::ListenAndServOpMaker);
<commit_msg>fix num_blocks==2<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 <stdint.h>
#include <sys/stat.h>
#include <ostream>
#include <thread>
#include <unistd.h>
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/proto_desc.h"
#include "paddle/fluid/framework/threadpool.h"
#include "paddle/fluid/operators/detail/grpc_server.h"
#include "paddle/fluid/operators/detail/sendrecvop_utils.h"
#include "paddle/fluid/operators/detail/simple_block_queue.h"
#include "paddle/fluid/string/printf.h"
namespace paddle {
namespace operators {
constexpr char kOptimizeBlock[] = "OptimizeBlock";
void RunServer(std::shared_ptr<detail::AsyncGRPCServer> service) {
service->RunSyncUpdate();
VLOG(4) << "RunServer thread end";
}
static void CreateTensorFromMessageType(framework::Variable *var,
sendrecv::VarType var_type) {
if (var_type == sendrecv::VarType::LOD_TENSOR) {
var->GetMutable<framework::LoDTensor>();
} else if (var_type == sendrecv::VarType::SELECTED_ROWS) {
var->GetMutable<framework::SelectedRows>();
} else {
PADDLE_THROW(
"VariableMessage type %d is not in "
"[LoDTensor, SelectedRows]",
var_type);
}
}
class ListenAndServOp : public framework::OperatorBase {
public:
ListenAndServOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {
if (!rpc_service_) {
std::string endpoint = Attr<std::string>("endpoint");
rpc_service_.reset(new detail::AsyncGRPCServer(endpoint));
server_thread_.reset(new std::thread(RunServer, rpc_service_));
}
}
void Stop() override {
detail::MessageWithName term_msg;
term_msg.first = LISTEN_TERMINATE_MESSAGE;
rpc_service_->Push(term_msg);
rpc_service_->ShutDown();
server_thread_->join();
}
void RunImpl(const framework::Scope &scope,
const platform::Place &dev_place) const override {
platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
auto &dev_ctx = *pool.Get(dev_place);
framework::Scope &recv_scope = scope.NewScope();
// FIXME(Yancey1989): initialize rpc server with lazy mode.
rpc_service_->SetScope(&recv_scope);
rpc_service_->SetDevCtx(&dev_ctx);
auto ins = Inputs("X");
auto fan_in = Attr<int>("Fanin");
auto *block = Attr<framework::BlockDesc *>(kOptimizeBlock);
auto *program = block->Program();
int num_blocks = program->Size();
PADDLE_ENFORCE_GE(num_blocks, 2,
"server program should have at least 2 blocks");
framework::Executor executor(dev_place);
// TODO(typhoonzero): change this to a while_op for every cluster-batch.
bool exit_flag = false;
// Record received sparse variables, so that
// we could reset those after execute optimize program
std::vector<framework::Variable *> sparse_vars;
while (!exit_flag) {
// Get from multiple trainers, we don't care about the order in which
// the gradients arrives, just add suffix 0~n and merge the gradient.
rpc_service_->SetCond(0);
size_t recv_var_cnt = 0;
int batch_barrier = 0;
while (batch_barrier != fan_in) {
const detail::MessageWithName &v = rpc_service_->Get();
auto recv_var_name = v.first;
if (recv_var_name == LISTEN_TERMINATE_MESSAGE) {
LOG(INFO) << "received terminate message and exit";
exit_flag = true;
break;
} else if (recv_var_name == BATCH_BARRIER_MESSAGE) {
VLOG(3) << "recv batch barrier message";
batch_barrier++;
continue;
} else {
VLOG(3) << "received grad: " << recv_var_name;
recv_var_cnt++;
auto *var = recv_scope.FindVar(recv_var_name);
if (var == nullptr) {
LOG(ERROR) << "Can not find server side var: " << recv_var_name;
PADDLE_THROW("Can not find server side var");
}
detail::DeserializeFromMessage(v.second, dev_ctx, var);
if (var->IsType<framework::SelectedRows>()) {
sparse_vars.push_back(var);
}
}
}
if (exit_flag) {
rpc_service_->SetCond(1);
rpc_service_->ShutDown();
break;
}
// put optimize blocks in the thread pool to start run, the last block
// should be global ops.
// NOTE: if is_gpu_place, CUDA kernels are laugched by multiple threads
// and this will still work.
std::vector<std::future<void>> fs;
// block0 contains only listen_and_serv op, start run from block1.
for (int blkid = 1; blkid < num_blocks - 1; ++blkid) {
fs.push_back(framework::Async([&executor, &program, &recv_scope,
blkid]() {
int run_block = blkid; // thread local
try {
executor.Run(*program, &recv_scope, run_block,
false /*create_local_scope*/, false /*create_vars*/);
} catch (std::exception &e) {
LOG(ERROR) << "run sub program error " << e.what();
}
}));
}
for (int i = 0; i < num_blocks - 2; ++i) fs[i].wait();
// Run global block at final step, or block1 if there are only 2 blocks
if (num_blocks >= 2) {
try {
executor.Run(*program, &recv_scope, num_blocks - 1,
false /*create_local_scope*/, false /*create_vars*/);
} catch (std::exception &e) {
LOG(ERROR) << "run sub program error " << e.what();
}
}
// Reset the received sparse variables, the sum operator would not
// sum the input sparse variables which rows is empty at the next
// mini-batch.
// TODO(Yancey1989): move the reset action into an operator, we couldn't
// have any hide logic in the operator.
for (auto &var : sparse_vars) {
var->GetMutable<framework::SelectedRows>()->mutable_rows()->clear();
}
rpc_service_->SetCond(1);
// FIXME(typhoonzero): use another condition to sync wait clients get.
rpc_service_->WaitClientGet(fan_in);
sparse_vars.clear();
} // while(true)
}
protected:
std::shared_ptr<detail::AsyncGRPCServer> rpc_service_;
std::shared_ptr<std::thread> server_thread_;
};
class ListenAndServOpMaker : public framework::OpProtoAndCheckerMaker {
public:
ListenAndServOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("X", "(Tensor) Variables that server recv.").AsDuplicable();
AddComment(R"DOC(
ListenAndServ operator
This operator will start a RPC server which can receive variables
from send_op and send back variables to recv_op.
)DOC");
AddAttr<std::string>("endpoint",
"(string, default 127.0.0.1:6164)"
"IP address to listen on.")
.SetDefault("127.0.0.1:6164")
.AddCustomChecker([](const std::string &ip) { return !ip.empty(); });
AddAttr<framework::BlockDesc *>(kOptimizeBlock,
"BlockID to run on server side.");
AddAttr<int>("Fanin", "How many clients send to this server.")
.SetDefault(1);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(listen_and_serv, ops::ListenAndServOp,
ops::ListenAndServOpMaker);
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.