text
stringlengths 54
60.6k
|
---|
<commit_before>#pragma once
#include <bts/blockchain/config.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/time.hpp>
#ifdef BTS_TEST_NETWORK
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 0
#else
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 4
#endif
#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE 512 // just a random assumption used to calibrate TRX per SEC
/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )
namespace bts { namespace blockchain {
struct delegate_config
{
uint32_t network_min_connection_count = NETWORK_MIN_CONNECTION_COUNT_DEFAULT;
uint32_t block_max_transaction_count = -1;
uint32_t block_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
fc::microseconds block_max_production_time = fc::seconds( 3 );
uint32_t transaction_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
bool transaction_canonical_signatures_required = false;
share_type transaction_min_fee = BTS_BLOCKCHAIN_PRECISION / 10;
set<transaction_id_type> transaction_blacklist;
set<operation_type_enum> operation_blacklist;
void validate()const
{ try {
FC_ASSERT( block_max_size <= BTS_BLOCKCHAIN_MAX_BLOCK_SIZE );
FC_ASSERT( block_max_production_time.count() >= 0 );
FC_ASSERT( block_max_production_time.to_seconds() <= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC );
FC_ASSERT( transaction_max_size <= block_max_size );
FC_ASSERT( transaction_min_fee >= 0 );
FC_ASSERT( transaction_min_fee <= BTS_BLOCKCHAIN_MAX_SHARES );
} FC_CAPTURE_AND_RETHROW() }
};
} } // bts::blockchain
FC_REFLECT( bts::blockchain::delegate_config,
(network_min_connection_count)
(block_max_transaction_count)
(block_max_size)
(block_max_production_time)
(transaction_max_size)
(transaction_canonical_signatures_required)
(transaction_min_fee)
(transaction_blacklist)
(operation_blacklist)
)
<commit_msg>update min net count for dev to 1<commit_after>#pragma once
#include <bts/blockchain/config.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/time.hpp>
#ifdef BTS_TEST_NETWORK
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 0
#else
#define NETWORK_MIN_CONNECTION_COUNT_DEFAULT 1
#endif
#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE 512 // just a random assumption used to calibrate TRX per SEC
/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )
namespace bts { namespace blockchain {
struct delegate_config
{
uint32_t network_min_connection_count = NETWORK_MIN_CONNECTION_COUNT_DEFAULT;
uint32_t block_max_transaction_count = -1;
uint32_t block_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
fc::microseconds block_max_production_time = fc::seconds( 3 );
uint32_t transaction_max_size = BTS_BLOCKCHAIN_MAX_BLOCK_SIZE;
bool transaction_canonical_signatures_required = false;
share_type transaction_min_fee = BTS_BLOCKCHAIN_PRECISION / 10;
set<transaction_id_type> transaction_blacklist;
set<operation_type_enum> operation_blacklist;
void validate()const
{ try {
FC_ASSERT( block_max_size <= BTS_BLOCKCHAIN_MAX_BLOCK_SIZE );
FC_ASSERT( block_max_production_time.count() >= 0 );
FC_ASSERT( block_max_production_time.to_seconds() <= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC );
FC_ASSERT( transaction_max_size <= block_max_size );
FC_ASSERT( transaction_min_fee >= 0 );
FC_ASSERT( transaction_min_fee <= BTS_BLOCKCHAIN_MAX_SHARES );
} FC_CAPTURE_AND_RETHROW() }
};
} } // bts::blockchain
FC_REFLECT( bts::blockchain::delegate_config,
(network_min_connection_count)
(block_max_transaction_count)
(block_max_size)
(block_max_production_time)
(transaction_max_size)
(transaction_canonical_signatures_required)
(transaction_min_fee)
(transaction_blacklist)
(operation_blacklist)
)
<|endoftext|> |
<commit_before>// (c) Mathias Panzenböck
// http://github.com/panzi/mathfun/blob/master/examples/portable_endian.h
//
#pragma once
#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)
# define __WINDOWS__
#endif
// use standard posix style headers for apple emscripten builds as well since emscripten sdk now ships its own
// libc headers
#if defined(__linux__) || defined(__CYGWIN__) || defined(__EMSCRIPTEN__)
# include <endian.h>
#elif defined(__APPLE__)
# include <machine/endian.h>
# include <libkern/OSByteOrder.h>
# define htobe16 OSSwapHostToBigInt16
# define htole16 OSSwapHostToLittleInt16
# define be16toh OSSwapBigToHostInt16
# define le16toh OSSwapLittleToHostInt16
# define htobe32 OSSwapHostToBigInt32
# define htole32 OSSwapHostToLittleInt32
# define be32toh OSSwapBigToHostInt32
# define le32toh OSSwapLittleToHostInt32
# define htobe64 OSSwapHostToBigInt64
# define htole64 OSSwapHostToLittleInt64
# define be64toh OSSwapBigToHostInt64
# define le64toh OSSwapLittleToHostInt64
/**
# define __BYTE_ORDER BYTE_ORDER
# define __BIG_ENDIAN BIG_ENDIAN
# define __LITTLE_ENDIAN LITTLE_ENDIAN
# define __PDP_ENDIAN PDP_ENDIAN
**/
#elif defined(__OpenBSD__)|| defined(__FreeBSD__)
# include <sys/endian.h>
#elif defined(__NetBSD__) || defined(__DragonFly__)
# define be16toh betoh16
# define le16toh letoh16
# define be32toh betoh32
# define le32toh letoh32
# define be64toh betoh64
# define le64toh letoh64
#elif defined(__WINDOWS__)
# include <winsock2.h>
# if BYTE_ORDER == LITTLE_ENDIAN
# define htobe16 htons
# define htole16(x) (x)
# define be16toh ntohs
# define le16toh(x) (x)
# define htobe32 htonl
# define htole32(x) (x)
# define be32toh ntohl
# define le32toh(x) (x)
# define htole64(x) (x)
# define le64toh(x) (x)
# ifndef __MINGW32__
# define be64toh ntohll
# define htobe64 htonll
# else
# define be64toh(x) ((((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))
# define htobe64(x) ((((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))
# endif
# elif BYTE_ORDER == BIG_ENDIAN
/* that would be xbox 360 */
# define htobe16(x) (x)
# define htole16(x) __builtin_bswap16(x)
# define be16toh(x) (x)
# define le16toh(x) __builtin_bswap16(x)
# define htobe32(x) (x)
# define htole32(x) __builtin_bswap32(x)
# define be32toh(x) (x)
# define le32toh(x) __builtin_bswap32(x)
# define htobe64(x) (x)
# define htole64(x) __builtin_bswap64(x)
# define be64toh(x) (x)
# define le64toh(x) __builtin_bswap64(x)
# else
# error byte order not supported
# endif
# define __BYTE_ORDER BYTE_ORDER
# define __BIG_ENDIAN BIG_ENDIAN
# define __LITTLE_ENDIAN LITTLE_ENDIAN
# define __PDP_ENDIAN PDP_ENDIAN
#else
# error platform not supported
#endif
<commit_msg>More flexible endian.h handling for *BSD platforms (#119)<commit_after>// (c) Mathias Panzenböck
// http://github.com/panzi/mathfun/blob/master/examples/portable_endian.h
//
#pragma once
#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)
# define __WINDOWS__
#endif
// use standard posix style headers for apple emscripten builds as well since emscripten sdk now ships its own
// libc headers
#if defined(__linux__) || defined(__CYGWIN__) || defined(__EMSCRIPTEN__)
# include <endian.h>
#elif defined(__APPLE__)
# include <machine/endian.h>
# include <libkern/OSByteOrder.h>
# define htobe16 OSSwapHostToBigInt16
# define htole16 OSSwapHostToLittleInt16
# define be16toh OSSwapBigToHostInt16
# define le16toh OSSwapLittleToHostInt16
# define htobe32 OSSwapHostToBigInt32
# define htole32 OSSwapHostToLittleInt32
# define be32toh OSSwapBigToHostInt32
# define le32toh OSSwapLittleToHostInt32
# define htobe64 OSSwapHostToBigInt64
# define htole64 OSSwapHostToLittleInt64
# define be64toh OSSwapBigToHostInt64
# define le64toh OSSwapLittleToHostInt64
/**
# define __BYTE_ORDER BYTE_ORDER
# define __BIG_ENDIAN BIG_ENDIAN
# define __LITTLE_ENDIAN LITTLE_ENDIAN
# define __PDP_ENDIAN PDP_ENDIAN
**/
#elif defined(__OpenBSD__)|| defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
# if defined __has_include && __has_include (<sys/endian.h>)
# include <sys/endian.h>
# elif defined __has_include && __has_include (<endian.h>)
# include <endian.h>
# else
# define be16toh betoh16
# define le16toh letoh16
# define be32toh betoh32
# define le32toh letoh32
# define be64toh betoh64
# define le64toh letoh64
# endif
#elif defined(__WINDOWS__)
# include <winsock2.h>
# if BYTE_ORDER == LITTLE_ENDIAN
# define htobe16 htons
# define htole16(x) (x)
# define be16toh ntohs
# define le16toh(x) (x)
# define htobe32 htonl
# define htole32(x) (x)
# define be32toh ntohl
# define le32toh(x) (x)
# define htole64(x) (x)
# define le64toh(x) (x)
# ifndef __MINGW32__
# define be64toh ntohll
# define htobe64 htonll
# else
# define be64toh(x) ((((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))
# define htobe64(x) ((((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))
# endif
# elif BYTE_ORDER == BIG_ENDIAN
/* that would be xbox 360 */
# define htobe16(x) (x)
# define htole16(x) __builtin_bswap16(x)
# define be16toh(x) (x)
# define le16toh(x) __builtin_bswap16(x)
# define htobe32(x) (x)
# define htole32(x) __builtin_bswap32(x)
# define be32toh(x) (x)
# define le32toh(x) __builtin_bswap32(x)
# define htobe64(x) (x)
# define htole64(x) __builtin_bswap64(x)
# define be64toh(x) (x)
# define le64toh(x) __builtin_bswap64(x)
# else
# error byte order not supported
# endif
# define __BYTE_ORDER BYTE_ORDER
# define __BIG_ENDIAN BIG_ENDIAN
# define __LITTLE_ENDIAN LITTLE_ENDIAN
# define __PDP_ENDIAN PDP_ENDIAN
#else
# error platform not supported
#endif
<|endoftext|> |
<commit_before>// dllmain.cpp : Defines the entry point for the DLL application.
#include <cstdio>
#include <memory>
#include <string>
#include <locale>
#include "stdafx.h"
#include "supp/timer.h"
#include "core/armor_up.h"
#include "utils/query.h"
using namespace monster_avengers;
std::unique_ptr<int> a;
std::string result;
Timer timer;
extern "C"
{
__declspec(dllexport) const char *DisplayHelloFromDLL()
{
result = std::to_string(timer.Toc());
return result.c_str();
}
__declspec(dllexport) void DoSearch(const wchar_t* text) {
std::wstring query_text = text;
setlocale(LC_ALL, "en_US.UTF-8");
Query query;
wprintf(L"sizeof(wchar_t): %d\n", sizeof(wchar_t));
wprintf(L"Get %lc\n", a);
// ArmorUp armor_up("d:/pf/projects/monster-avengers/dataset/MH4GU");
// armor_up.Search<SCREEN>("(:weaopn-type ");
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
timer.Tic();
a.reset(new int(24));
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
a.release();
break;
}
return TRUE;
}
<commit_msg>working version, preliminary.<commit_after>// dllmain.cpp : Defines the entry point for the DLL application.
#include <cstdio>
#include <memory>
#include <string>
#include <locale>
#include "stdafx.h"
#include "supp/timer.h"
#include "core/armor_up.h"
#include "utils/query.h"
using namespace monster_avengers;
std::unique_ptr<int> a;
std::string result;
Timer timer;
extern "C"
{
__declspec(dllexport) const char *DisplayHelloFromDLL()
{
result = std::to_string(timer.Toc());
return result.c_str();
}
__declspec(dllexport) void DoSearch(const wchar_t* text) {
std::wstring query_text = text;
Query query;
CHECK_SUCCESS(Query::Parse(query_text, &query));
query.DebugPrint();
ArmorUp armor_up("d:/pf/projects/monster-avengers/dataset/MH4GU");
armor_up.Summarize();
armor_up.Search<SCREEN>(query);
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
setlocale(LC_ALL, "en_US.UTF-8");
timer.Tic();
a.reset(new int(24));
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
a.release();
break;
}
return TRUE;
}
<|endoftext|> |
<commit_before>/// \file TFormulaGradientTests.cxx
///
/// \brief The file contain unit tests which test the clad-based gradient
/// computations.
///
/// \author Vassil Vassilev <[email protected]>
///
/// \date Oct, 2018
///
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOTUnitTestSupport.h"
#include <Math/MinimizerOptions.h>
#include <TFormula.h>
#include <TF1.h>
#include <TFitResult.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
TEST(TFormulaGradientPar, Sanity)
{
TFormula f("f", "x*std::sin([0]) - y*std::cos([1])");
double p[] = {30, 60};
f.SetParameters(p);
double x[] = {1, 2};
TFormula::CladStorage result(2);
f.GradientPar(x, result);
ASSERT_FLOAT_EQ(x[0] * std::cos(30), result[0]);
ASSERT_FLOAT_EQ(-x[1] * -std::sin(60), result[1]);
}
TEST(TFormulaGradientPar, ResultUpsize)
{
TFormula f("f", "std::sin([1]) - std::cos([0])");
double p[] = {60, 30};
f.SetParameters(p);
TFormula::CladStorage result;
double x[] = {2, 1};
ASSERT_TRUE(0 == result.size());
ROOT_EXPECT_WARNING(f.GradientPar(x, result),
"TFormula::GradientPar",
"The size of gradient result is 0 but 2 is required. Resizing."
);
ASSERT_FLOAT_EQ(std::cos(30), result[1]);
ASSERT_FLOAT_EQ(std::sin(60), result[0]);
ASSERT_TRUE(2 == result.size());
}
TEST(TFormulaGradientPar, ResultDownsize)
{
TFormula f("f", "std::sin([0])");
double p[] = {60};
f.SetParameters(p);
TFormula::CladStorage result(2);
double x[] = {1};
ASSERT_TRUE(2 == result.size());
ROOT_EXPECT_NODIAG(f.GradientPar(x, result));
ASSERT_FLOAT_EQ(std::cos(60), result[0]);
ASSERT_TRUE(2 == result.size());
}
TEST(TFormulaGradientPar, GausCrossCheck)
{
auto h = new TF1("f1", "gaus");
// auto h = new TF1("f1", "landau"); -- inheritently does not work. See DIFLAN
//crystalball, breitwigner, cheb3, bigaus,
//auto h = new TF1("f1", "");
double p[] = {3, 1, 2};
h->SetParameters(p);
double x[] = {0};
TFormula::CladStorage result_clad(3);
h->GetFormula()->GradientPar(x, result_clad);
TFormula::CladStorage result_num(3);
h->GradientPar(x, result_num.data());
ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}
TEST(TFormulaGradientPar, BreitWignerCrossCheck)
{
auto h = new TF1("f1", "breitwigner");
double p[] = {3, 1, 2.1};
h->SetParameters(p);
double x[] = {0};
TFormula::CladStorage result_clad(3);
TFormula* formula = h->GetFormula();
formula->GradientPar(x, result_clad);
TFormula::CladStorage result_num(3);
h->GradientPar(x, result_num.data());
ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}
TEST(TFormulaGradientPar, BreitWignerCrossCheckAccuracyDemo)
{
auto h = new TF1("f1", "breitwigner");
double p[] = {3, 1, 2};
h->SetParameters(p);
double x[] = {0};
TFormula::CladStorage result_clad(3);
TFormula* formula = h->GetFormula();
formula->GradientPar(x, result_clad);
TFormula::CladStorage result_num(3);
h->GradientPar(x, result_num.data());
// This is a classical example why clad is better.
// The gradient with respect to gamma leads to a cancellation when gamma is
// set to 2. This is not a problem for clad yielding the correct result of 0
ASSERT_FLOAT_EQ(0, result_clad[2]);
// However, that is not the case for the numerical approach where we give
// a small but non-zero result.
EXPECT_NEAR(0, result_num[2], /*abs_error*/1e-13);
}
// FIXME: Add more: crystalball, cheb3, bigaus?
TEST(TFormulaGradientPar, GetGradFormula)
{
TFormula f("f", "gaus");
double p[] = {3, 1, 2};
f.SetParameters(p);
ASSERT_TRUE(f.GenerateGradientPar());
std::string s = f.GetGradientFormula().Data();
// Windows does not support posix regex which are necessary here.
#ifndef R__WIN32
ASSERT_THAT(s, testing::ContainsRegex("void TFormula____id[0-9]*_grad_1"));
#endif // R__WIN32
}
<commit_msg>[clad] Extend test coverage with bigaus function.<commit_after>/// \file TFormulaGradientTests.cxx
///
/// \brief The file contain unit tests which test the clad-based gradient
/// computations.
///
/// \author Vassil Vassilev <[email protected]>
///
/// \date Oct, 2018
///
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOTUnitTestSupport.h"
#include <Math/MinimizerOptions.h>
#include <TFormula.h>
#include <TF1.h>
#include <TF2.h>
#include <TFitResult.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
TEST(TFormulaGradientPar, Sanity)
{
TFormula f("f", "x*std::sin([0]) - y*std::cos([1])");
double p[] = {30, 60};
f.SetParameters(p);
double x[] = {1, 2};
TFormula::CladStorage result(2);
f.GradientPar(x, result);
ASSERT_FLOAT_EQ(x[0] * std::cos(30), result[0]);
ASSERT_FLOAT_EQ(-x[1] * -std::sin(60), result[1]);
}
TEST(TFormulaGradientPar, ResultUpsize)
{
TFormula f("f", "std::sin([1]) - std::cos([0])");
double p[] = {60, 30};
f.SetParameters(p);
TFormula::CladStorage result;
double x[] = {2, 1};
ASSERT_TRUE(0 == result.size());
ROOT_EXPECT_WARNING(f.GradientPar(x, result),
"TFormula::GradientPar",
"The size of gradient result is 0 but 2 is required. Resizing."
);
ASSERT_FLOAT_EQ(std::cos(30), result[1]);
ASSERT_FLOAT_EQ(std::sin(60), result[0]);
ASSERT_TRUE(2 == result.size());
}
TEST(TFormulaGradientPar, ResultDownsize)
{
TFormula f("f", "std::sin([0])");
double p[] = {60};
f.SetParameters(p);
TFormula::CladStorage result(2);
double x[] = {1};
ASSERT_TRUE(2 == result.size());
ROOT_EXPECT_NODIAG(f.GradientPar(x, result));
ASSERT_FLOAT_EQ(std::cos(60), result[0]);
ASSERT_TRUE(2 == result.size());
}
TEST(TFormulaGradientPar, GausCrossCheck)
{
auto h = new TF1("f1", "gaus");
// auto h = new TF1("f1", "landau"); -- inheritently does not work. See DIFLAN
//crystalball, breitwigner, cheb3, bigaus,
//auto h = new TF1("f1", "");
double p[] = {3, 1, 2};
h->SetParameters(p);
double x[] = {0};
TFormula::CladStorage result_clad(3);
h->GetFormula()->GradientPar(x, result_clad);
TFormula::CladStorage result_num(3);
h->GradientPar(x, result_num.data());
ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}
TEST(TFormulaGradientPar, BreitWignerCrossCheck)
{
auto h = new TF1("f1", "breitwigner");
double p[] = {3, 1, 2.1};
h->SetParameters(p);
double x[] = {0};
TFormula::CladStorage result_clad(3);
TFormula* formula = h->GetFormula();
formula->GradientPar(x, result_clad);
TFormula::CladStorage result_num(3);
h->GradientPar(x, result_num.data());
ASSERT_FLOAT_EQ(result_num[0], result_clad[0]);
ASSERT_FLOAT_EQ(result_num[1], result_clad[1]);
ASSERT_FLOAT_EQ(result_num[2], result_clad[2]);
}
TEST(TFormulaGradientPar, BreitWignerCrossCheckAccuracyDemo)
{
auto h = new TF1("f1", "breitwigner");
double p[] = {3, 1, 2};
h->SetParameters(p);
double x[] = {0};
TFormula::CladStorage result_clad(3);
TFormula* formula = h->GetFormula();
formula->GradientPar(x, result_clad);
TFormula::CladStorage result_num(3);
h->GradientPar(x, result_num.data());
// This is a classical example why clad is better.
// The gradient with respect to gamma leads to a cancellation when gamma is
// set to 2. This is not a problem for clad yielding the correct result of 0
ASSERT_FLOAT_EQ(0, result_clad[2]);
// However, that is not the case for the numerical approach where we give
// a small but non-zero result.
EXPECT_NEAR(0, result_num[2], /*abs_error*/1e-13);
}
TEST(TFormulaGradientPar, BigausCrossCheck)
{
auto h = new TF2("f1", "bigaus");
const unsigned len = 6;
double p[] = {/*Constant=*/1,/*MeanX=*/0,/*SigmaX=*/1,/*MeanY=*/1,/*SigmaY=*/2,/*Rho=*/0.};
h->SetParameters(p);
double x[] = {0};
TFormula::CladStorage result_clad(len);
TFormula* formula = h->GetFormula();
formula->GradientPar(x, result_clad);
TFormula::CladStorage result_num(len);
h->GradientPar(x, result_num.data());
for (unsigned i = 0; i < len; ++i)
ASSERT_FLOAT_EQ(result_num[i], result_clad[i]);
}
// FIXME: Add more: crystalball, cheb3?
TEST(TFormulaGradientPar, GetGradFormula)
{
TFormula f("f", "gaus");
double p[] = {3, 1, 2};
f.SetParameters(p);
ASSERT_TRUE(f.GenerateGradientPar());
std::string s = f.GetGradientFormula().Data();
// Windows does not support posix regex which are necessary here.
#ifndef R__WIN32
ASSERT_THAT(s, testing::ContainsRegex("void TFormula____id[0-9]*_grad_1"));
#endif // R__WIN32
}
<|endoftext|> |
<commit_before>// 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.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <addrman.h>
#include <blockencodings.h>
#include <chain.h>
#include <coins.h>
#include <compressor.h>
#include <consensus/merkle.h>
#include <net.h>
#include <primitives/block.h>
#include <protocol.h>
#include <pubkey.h>
#include <script/script.h>
#include <streams.h>
#include <undo.h>
#include <version.h>
#include <stdint.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
#include <vector>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
enum TEST_ID {
CBLOCK_DESERIALIZE=0,
CTRANSACTION_DESERIALIZE,
CBLOCKLOCATOR_DESERIALIZE,
CBLOCKMERKLEROOT,
CADDRMAN_DESERIALIZE,
CBLOCKHEADER_DESERIALIZE,
CBANENTRY_DESERIALIZE,
CTXUNDO_DESERIALIZE,
CBLOCKUNDO_DESERIALIZE,
CCOINS_DESERIALIZE,
CNETADDR_DESERIALIZE,
CSERVICE_DESERIALIZE,
CMESSAGEHEADER_DESERIALIZE,
CADDRESS_DESERIALIZE,
CINV_DESERIALIZE,
CBLOOMFILTER_DESERIALIZE,
CDISKBLOCKINDEX_DESERIALIZE,
CTXOUTCOMPRESSOR_DESERIALIZE,
BLOCKTRANSACTIONS_DESERIALIZE,
BLOCKTRANSACTIONSREQUEST_DESERIALIZE,
TEST_ID_END
};
static bool read_stdin(std::vector<uint8_t> &data) {
uint8_t buffer[1024];
ssize_t length=0;
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer+length);
if (data.size() > (1<<20)) return false;
}
return length==0;
}
static int test_one_input(std::vector<uint8_t> buffer) {
if (buffer.size() < sizeof(uint32_t)) return 0;
uint32_t test_id = 0xffffffff;
memcpy(&test_id, buffer.data(), sizeof(uint32_t));
buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));
if (test_id >= TEST_ID_END) return 0;
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure& e) {
return 0;
}
switch(test_id) {
case CBLOCK_DESERIALIZE:
{
try
{
CBlock block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTRANSACTION_DESERIALIZE:
{
try
{
CTransaction tx(deserialize, ds);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKLOCATOR_DESERIALIZE:
{
try
{
CBlockLocator bl;
ds >> bl;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKMERKLEROOT:
{
try
{
CBlock block;
ds >> block;
bool mutated;
BlockMerkleRoot(block, &mutated);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRMAN_DESERIALIZE:
{
try
{
CAddrMan am;
ds >> am;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKHEADER_DESERIALIZE:
{
try
{
CBlockHeader bh;
ds >> bh;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBANENTRY_DESERIALIZE:
{
try
{
CBanEntry be;
ds >> be;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXUNDO_DESERIALIZE:
{
try
{
CTxUndo tu;
ds >> tu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKUNDO_DESERIALIZE:
{
try
{
CBlockUndo bu;
ds >> bu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CCOINS_DESERIALIZE:
{
try
{
Coin coin;
ds >> coin;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CNETADDR_DESERIALIZE:
{
try
{
CNetAddr na;
ds >> na;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CSERVICE_DESERIALIZE:
{
try
{
CService s;
ds >> s;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CMESSAGEHEADER_DESERIALIZE:
{
CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
try
{
CMessageHeader mh(pchMessageStart);
ds >> mh;
if (!mh.IsValid(pchMessageStart)) {return 0;}
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRESS_DESERIALIZE:
{
try
{
CAddress a;
ds >> a;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CINV_DESERIALIZE:
{
try
{
CInv i;
ds >> i;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOOMFILTER_DESERIALIZE:
{
try
{
CBloomFilter bf;
ds >> bf;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CDISKBLOCKINDEX_DESERIALIZE:
{
try
{
CDiskBlockIndex dbi;
ds >> dbi;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXOUTCOMPRESSOR_DESERIALIZE:
{
CTxOut to;
CTxOutCompressor toc(to);
try
{
ds >> toc;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case BLOCKTRANSACTIONS_DESERIALIZE:
{
try
{
BlockTransactions bt;
ds >> bt;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case BLOCKTRANSACTIONSREQUEST_DESERIALIZE:
{
try
{
BlockTransactionsRequest btr;
ds >> btr;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
default:
return 0;
}
return 0;
}
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
void initialize() {
globalVerifyHandle = MakeUnique<ECCVerifyHandle>();
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
test_one_input(std::vector<uint8_t>(data, data + size));
return 0;
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
initialize();
return 0;
}
// Disabled under WIN32 due to clash with Cygwin's WinMain.
#ifndef WIN32
// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides
// the main(...) function.
__attribute__((weak))
#endif
int main(int argc, char **argv)
{
initialize();
#ifdef __AFL_INIT
// Enable AFL deferred forkserver mode. Requires compilation using
// afl-clang-fast++. See fuzzing.md for details.
__AFL_INIT();
#endif
#ifdef __AFL_LOOP
// Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
// See fuzzing.md for details.
int ret = 0;
while (__AFL_LOOP(1000)) {
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
continue;
}
ret = test_one_input(buffer);
}
return ret;
#else
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
return 0;
}
return test_one_input(buffer);
#endif
}
<commit_msg>[test] fuzz: make test_one_input return void<commit_after>// 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.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <addrman.h>
#include <blockencodings.h>
#include <chain.h>
#include <coins.h>
#include <compressor.h>
#include <consensus/merkle.h>
#include <net.h>
#include <primitives/block.h>
#include <protocol.h>
#include <pubkey.h>
#include <script/script.h>
#include <streams.h>
#include <undo.h>
#include <version.h>
#include <stdint.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
#include <vector>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
enum TEST_ID {
CBLOCK_DESERIALIZE=0,
CTRANSACTION_DESERIALIZE,
CBLOCKLOCATOR_DESERIALIZE,
CBLOCKMERKLEROOT,
CADDRMAN_DESERIALIZE,
CBLOCKHEADER_DESERIALIZE,
CBANENTRY_DESERIALIZE,
CTXUNDO_DESERIALIZE,
CBLOCKUNDO_DESERIALIZE,
CCOINS_DESERIALIZE,
CNETADDR_DESERIALIZE,
CSERVICE_DESERIALIZE,
CMESSAGEHEADER_DESERIALIZE,
CADDRESS_DESERIALIZE,
CINV_DESERIALIZE,
CBLOOMFILTER_DESERIALIZE,
CDISKBLOCKINDEX_DESERIALIZE,
CTXOUTCOMPRESSOR_DESERIALIZE,
BLOCKTRANSACTIONS_DESERIALIZE,
BLOCKTRANSACTIONSREQUEST_DESERIALIZE,
TEST_ID_END
};
static bool read_stdin(std::vector<uint8_t>& data)
{
uint8_t buffer[1024];
ssize_t length = 0;
while ((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer + length);
if (data.size() > (1 << 20)) return false;
}
return length == 0;
}
void test_one_input(std::vector<uint8_t> buffer)
{
if (buffer.size() < sizeof(uint32_t)) return;
uint32_t test_id = 0xffffffff;
memcpy(&test_id, buffer.data(), sizeof(uint32_t));
buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));
if (test_id >= TEST_ID_END) return;
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure& e) {
return;
}
switch(test_id) {
case CBLOCK_DESERIALIZE:
{
try
{
CBlock block;
ds >> block;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CTRANSACTION_DESERIALIZE:
{
try
{
CTransaction tx(deserialize, ds);
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CBLOCKLOCATOR_DESERIALIZE:
{
try
{
CBlockLocator bl;
ds >> bl;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CBLOCKMERKLEROOT:
{
try
{
CBlock block;
ds >> block;
bool mutated;
BlockMerkleRoot(block, &mutated);
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CADDRMAN_DESERIALIZE:
{
try
{
CAddrMan am;
ds >> am;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CBLOCKHEADER_DESERIALIZE:
{
try
{
CBlockHeader bh;
ds >> bh;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CBANENTRY_DESERIALIZE:
{
try
{
CBanEntry be;
ds >> be;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CTXUNDO_DESERIALIZE:
{
try
{
CTxUndo tu;
ds >> tu;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CBLOCKUNDO_DESERIALIZE:
{
try
{
CBlockUndo bu;
ds >> bu;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CCOINS_DESERIALIZE:
{
try
{
Coin coin;
ds >> coin;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CNETADDR_DESERIALIZE:
{
try
{
CNetAddr na;
ds >> na;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CSERVICE_DESERIALIZE:
{
try
{
CService s;
ds >> s;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CMESSAGEHEADER_DESERIALIZE:
{
CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
try
{
CMessageHeader mh(pchMessageStart);
ds >> mh;
if (!mh.IsValid(pchMessageStart)) {return;}
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CADDRESS_DESERIALIZE:
{
try
{
CAddress a;
ds >> a;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CINV_DESERIALIZE:
{
try
{
CInv i;
ds >> i;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CBLOOMFILTER_DESERIALIZE:
{
try
{
CBloomFilter bf;
ds >> bf;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CDISKBLOCKINDEX_DESERIALIZE:
{
try
{
CDiskBlockIndex dbi;
ds >> dbi;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case CTXOUTCOMPRESSOR_DESERIALIZE:
{
CTxOut to;
CTxOutCompressor toc(to);
try
{
ds >> toc;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case BLOCKTRANSACTIONS_DESERIALIZE:
{
try
{
BlockTransactions bt;
ds >> bt;
} catch (const std::ios_base::failure& e) {return;}
break;
}
case BLOCKTRANSACTIONSREQUEST_DESERIALIZE:
{
try
{
BlockTransactionsRequest btr;
ds >> btr;
} catch (const std::ios_base::failure& e) {return;}
break;
}
default:
return;
}
return;
}
void initialize()
{
const static auto verify_handle = MakeUnique<ECCVerifyHandle>();
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
test_one_input(std::vector<uint8_t>(data, data + size));
return 0;
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv)
{
initialize();
return 0;
}
// Disabled under WIN32 due to clash with Cygwin's WinMain.
#ifndef WIN32
// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides
// the main(...) function.
__attribute__((weak))
#endif
int main(int argc, char **argv)
{
initialize();
#ifdef __AFL_INIT
// Enable AFL deferred forkserver mode. Requires compilation using
// afl-clang-fast++. See fuzzing.md for details.
__AFL_INIT();
#endif
#ifdef __AFL_LOOP
// Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
// See fuzzing.md for details.
while (__AFL_LOOP(1000)) {
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
continue;
}
test_one_input(buffer);
}
#else
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
return 0;
}
test_one_input(buffer);
#endif
}
<|endoftext|> |
<commit_before>/*
This file is part of tgl-library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright Vitaly Valtman 2014-2015
Copyright Topology LP 2016
*/
#include "tgl.h"
#include "crypto/rsa_pem.h"
#include "crypto/sha.h"
#include "tools.h"
#include "mtproto-client.h"
#include "structures.h"
#include "tgl_transfer_manager.h"
#include "tgl-timer.h"
#include "tgl-queries.h"
#include "tools.h"
#include "types/tgl_online_status_observer.h"
#include "types/tgl_update_callback.h"
#include "types/tgl_rsa_key.h"
#include "types/tgl_secret_chat.h"
#include "queries.h"
#include <assert.h>
#include <stdlib.h>
constexpr int MAX_DC_ID = 10;
constexpr int32_t TG_APP_ID = 10534;
constexpr const char* TG_APP_HASH = "844584f2b1fd2daecee726166dcc1ef8";
std::unique_ptr<tgl_state> tgl_state::s_instance;
tgl_state::tgl_state()
: locks(0)
, ev_login(NULL)
, m_is_started(false)
, m_online_status(tgl_online_status::not_online)
, m_app_id(0)
, m_error_code(0)
, m_temp_key_expire_time(0)
, m_pts(0)
, m_qts(0)
, m_date(0)
, m_seq(0)
, m_test_mode(0)
, m_our_id()
, m_enable_pfs(false)
, m_ipv6_enabled(false)
, m_bn_ctx(TGLC_bn_ctx_new())
, m_online_status_observers()
{
}
tgl_state* tgl_state::instance()
{
if (!s_instance) {
s_instance.reset(new tgl_state);
}
return s_instance.get();
}
void tgl_state::reset()
{
s_instance.reset();
}
void tgl_state::set_auth_key(int num, const char* buf)
{
assert(num > 0 && num <= MAX_DC_ID);
assert(m_dcs[num]);
if (buf) {
memcpy(m_dcs[num]->auth_key, buf, 256);
}
unsigned char sha1_buffer[20];
memset(sha1_buffer, 0, sizeof(sha1_buffer));
TGLC_sha1((unsigned char *)m_dcs[num]->auth_key, 256, sha1_buffer);
memcpy(&m_dcs[num]->auth_key_id, sha1_buffer + 12, 8);
m_dcs[num]->set_authorized();
m_callback->dc_update(m_dcs[num]);
}
void tgl_state::set_our_id(int id)
{
if (m_our_id.peer_id == id) {
return;
}
m_our_id.peer_id = id;
m_our_id.peer_type = tgl_peer_type::user;
assert(our_id().peer_id > 0);
m_callback->our_id(our_id().peer_id);
}
void tgl_state::set_dc_option(bool is_v6, int id, const std::string& ip, int port)
{
if (id < 0) {
return;
}
if (static_cast<size_t>(id) >= m_dcs.size()) {
m_dcs.resize(id+1, nullptr);
}
if (!m_dcs[id]) {
m_dcs[id] = tgl_state::instance()->allocate_dc(id);
if (tgl_state::instance()->pfs_enabled()) {
//dc->ev = tgl_state::instance()->timer_factory()->create_timer(std::bind(®en_temp_key_gw, DC));
//dc->ev->start(0);
}
}
if (is_v6) {
m_dcs[id]->ipv6_options.option_list.push_back(std::make_pair(ip, port));
} else {
m_dcs[id]->ipv4_options.option_list.push_back(std::make_pair(ip, port));
}
}
void tgl_state::set_dc_logged_in(int num)
{
TGL_DEBUG2("set signed " << num);
assert(num > 0 && num <= MAX_DC_ID);
assert(m_dcs[num]);
m_dcs[num]->set_logged_in();
m_callback->dc_update(m_dcs[num]);
}
void tgl_state::set_working_dc(int num)
{
if (m_working_dc && m_working_dc->id == num) {
return;
}
TGL_DEBUG2("change working DC to " << num);
assert(num > 0 && num <= MAX_DC_ID);
m_working_dc = m_dcs[num];
m_callback->change_active_dc(num);
}
void tgl_state::set_qts(int32_t qts, bool force)
{
if (locks & TGL_LOCK_DIFF) {
return;
}
if (qts <= m_qts && !force) {
return;
}
m_qts = qts;
m_callback->qts_changed(qts);
}
void tgl_state::set_pts(int32_t pts, bool force)
{
if (locks & TGL_LOCK_DIFF && !force) {
return;
}
if (pts <= m_pts && !force) {
return;
}
m_pts = pts;
m_callback->pts_changed(pts);
}
void tgl_state::set_date(int64_t date, bool force)
{
if (locks & TGL_LOCK_DIFF && !force) {
return;
}
if (date <= m_date && !force) {
return;
}
m_date = date;
m_callback->date_changed(date);
}
void tgl_state::set_seq(int32_t seq)
{
if (locks & TGL_LOCK_DIFF) {
return;
}
if (seq <= m_seq) {
return;
}
m_seq = seq;
}
void tgl_state::reset_server_state()
{
m_qts = 0;
m_pts = 0;
m_date = 0;
m_seq = 0;
}
void tgl_state::add_rsa_key(const std::string& key)
{
m_rsa_key_list.push_back(std::unique_ptr<tgl_rsa_key>(new tgl_rsa_key(key)));
}
int tgl_state::init(const std::string& download_dir, int app_id, const std::string& app_hash, const std::string& app_version)
{
m_transfer_manager = std::make_shared<tgl_transfer_manager>(download_dir);
m_app_id = app_id;
m_app_hash = app_hash;
m_app_version = app_version;
assert(m_timer_factory);
assert(m_connection_factory);
if (!m_temp_key_expire_time) {
m_temp_key_expire_time = 7200; // seconds
}
if (tglmp_on_start() < 0) {
return -1;
}
if (!m_app_id) {
m_app_id = TG_APP_ID;
m_app_hash = TG_APP_HASH;
}
m_state_lookup_timer = m_timer_factory->create_timer(std::bind(&tgl_state::state_lookup_timeout, this));
m_state_lookup_timer->start(3600);
return 0;
}
void tgl_state::set_enable_pfs(bool val)
{
m_enable_pfs = val;
}
void tgl_state::set_test_mode(bool val)
{
m_test_mode = val;
}
void tgl_state::set_enable_ipv6(bool val)
{
m_ipv6_enabled = val;
}
void tgl_state::set_error(const std::string& error, int error_code)
{
m_error = error;
m_error_code = error_code;
}
int32_t tgl_state::create_secret_chat_id()
{
int chat_id = tgl_random<int>();
while (tgl_state::instance()->secret_chat_for_id(chat_id)) {
chat_id = tgl_random<int>();
}
return chat_id;
}
std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(int32_t id)
{
int chat_id;
if (id) {
chat_id = id;
} else {
chat_id = create_secret_chat_id();
}
auto secret_chat = std::make_shared<tgl_secret_chat>();
secret_chat->id = tgl_input_peer_t(tgl_peer_type::enc_chat, chat_id, 0);
m_secret_chats[chat_id] = secret_chat;
return secret_chat;
}
std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(const tgl_input_peer_t& chat_id)
{
if (m_secret_chats.find(chat_id.peer_id) != m_secret_chats.end()) {
return nullptr;
}
auto secret_chat = std::make_shared<tgl_secret_chat>();
secret_chat->id = chat_id;
m_secret_chats[chat_id.peer_id] = secret_chat;
return secret_chat;
}
std::shared_ptr<tgl_secret_chat> tgl_state::secret_chat_for_id(int chat_id) const
{
auto secret_chat_it = m_secret_chats.find(chat_id);
if (secret_chat_it == m_secret_chats.end()) {
return nullptr;
}
return secret_chat_it->second;
}
void tgl_state::add_secret_chat(const std::shared_ptr<tgl_secret_chat>& secret_chat)
{
m_secret_chats[secret_chat->id.peer_id] = secret_chat;
}
void tgl_state::add_query(const std::shared_ptr<query>& q)
{
auto id = q->msg_id();
assert(id);
auto inserted_iterator_pair = m_active_queries.emplace(id, q);
if (inserted_iterator_pair.second) {
q->dc()->increase_active_queries();
} else {
inserted_iterator_pair.first->second = q;
}
}
std::shared_ptr<query> tgl_state::get_query(int64_t id) const
{
assert(id);
auto it = m_active_queries.find(id);
if (it == m_active_queries.end()) {
return nullptr;
}
return it->second;
}
void tgl_state::remove_query(const std::shared_ptr<query>& q)
{
auto id = q->msg_id();
assert(id);
auto it = m_active_queries.find(id);
if (it != m_active_queries.end()) {
m_active_queries.erase(it);
q->dc()->decrease_active_queries();
}
}
void tgl_state::remove_all_queries()
{
m_active_queries.clear();
}
std::shared_ptr<tgl_dc> tgl_state::dc_at(int id)
{
if (static_cast<size_t>(id) >= m_dcs.size()) {
return nullptr;
}
return m_dcs[id];
}
std::shared_ptr<tgl_dc> tgl_state::allocate_dc(int id)
{
if (static_cast<size_t>(id) >= m_dcs.size()) {
m_dcs.resize(id+1, nullptr);
}
assert(!m_dcs[id]);
std::shared_ptr<tgl_dc> dc = std::make_shared<tgl_dc>();
dc->id = id;
m_dcs[id] = dc;
return dc;
}
void tgl_state::state_lookup_timeout()
{
tgl_do_lookup_state();
if (m_state_lookup_timer) {
m_state_lookup_timer->start(3600);
}
}
void tgl_state::logout()
{
tgl_do_logout(nullptr);
}
void tgl_state::set_online_status(tgl_online_status status)
{
if (status == m_online_status) {
return;
}
m_online_status = status;
for (const auto& weak_observer: m_online_status_observers) {
if (auto observer = weak_observer.lock()) {
observer->on_online_status_changed(status);
}
}
}
<commit_msg>Add log message when changing online status<commit_after>/*
This file is part of tgl-library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright Vitaly Valtman 2014-2015
Copyright Topology LP 2016
*/
#include "tgl.h"
#include "crypto/rsa_pem.h"
#include "crypto/sha.h"
#include "tools.h"
#include "mtproto-client.h"
#include "structures.h"
#include "tgl_transfer_manager.h"
#include "tgl-timer.h"
#include "tgl-queries.h"
#include "tools.h"
#include "types/tgl_online_status_observer.h"
#include "types/tgl_update_callback.h"
#include "types/tgl_rsa_key.h"
#include "types/tgl_secret_chat.h"
#include "queries.h"
#include <assert.h>
#include <stdlib.h>
constexpr int MAX_DC_ID = 10;
constexpr int32_t TG_APP_ID = 10534;
constexpr const char* TG_APP_HASH = "844584f2b1fd2daecee726166dcc1ef8";
std::unique_ptr<tgl_state> tgl_state::s_instance;
tgl_state::tgl_state()
: locks(0)
, ev_login(NULL)
, m_is_started(false)
, m_online_status(tgl_online_status::not_online)
, m_app_id(0)
, m_error_code(0)
, m_temp_key_expire_time(0)
, m_pts(0)
, m_qts(0)
, m_date(0)
, m_seq(0)
, m_test_mode(0)
, m_our_id()
, m_enable_pfs(false)
, m_ipv6_enabled(false)
, m_bn_ctx(TGLC_bn_ctx_new())
, m_online_status_observers()
{
}
tgl_state* tgl_state::instance()
{
if (!s_instance) {
s_instance.reset(new tgl_state);
}
return s_instance.get();
}
void tgl_state::reset()
{
s_instance.reset();
}
void tgl_state::set_auth_key(int num, const char* buf)
{
assert(num > 0 && num <= MAX_DC_ID);
assert(m_dcs[num]);
if (buf) {
memcpy(m_dcs[num]->auth_key, buf, 256);
}
unsigned char sha1_buffer[20];
memset(sha1_buffer, 0, sizeof(sha1_buffer));
TGLC_sha1((unsigned char *)m_dcs[num]->auth_key, 256, sha1_buffer);
memcpy(&m_dcs[num]->auth_key_id, sha1_buffer + 12, 8);
m_dcs[num]->set_authorized();
m_callback->dc_update(m_dcs[num]);
}
void tgl_state::set_our_id(int id)
{
if (m_our_id.peer_id == id) {
return;
}
m_our_id.peer_id = id;
m_our_id.peer_type = tgl_peer_type::user;
assert(our_id().peer_id > 0);
m_callback->our_id(our_id().peer_id);
}
void tgl_state::set_dc_option(bool is_v6, int id, const std::string& ip, int port)
{
if (id < 0) {
return;
}
if (static_cast<size_t>(id) >= m_dcs.size()) {
m_dcs.resize(id+1, nullptr);
}
if (!m_dcs[id]) {
m_dcs[id] = tgl_state::instance()->allocate_dc(id);
if (tgl_state::instance()->pfs_enabled()) {
//dc->ev = tgl_state::instance()->timer_factory()->create_timer(std::bind(®en_temp_key_gw, DC));
//dc->ev->start(0);
}
}
if (is_v6) {
m_dcs[id]->ipv6_options.option_list.push_back(std::make_pair(ip, port));
} else {
m_dcs[id]->ipv4_options.option_list.push_back(std::make_pair(ip, port));
}
}
void tgl_state::set_dc_logged_in(int num)
{
TGL_DEBUG2("set signed " << num);
assert(num > 0 && num <= MAX_DC_ID);
assert(m_dcs[num]);
m_dcs[num]->set_logged_in();
m_callback->dc_update(m_dcs[num]);
}
void tgl_state::set_working_dc(int num)
{
if (m_working_dc && m_working_dc->id == num) {
return;
}
TGL_DEBUG2("change working DC to " << num);
assert(num > 0 && num <= MAX_DC_ID);
m_working_dc = m_dcs[num];
m_callback->change_active_dc(num);
}
void tgl_state::set_qts(int32_t qts, bool force)
{
if (locks & TGL_LOCK_DIFF) {
return;
}
if (qts <= m_qts && !force) {
return;
}
m_qts = qts;
m_callback->qts_changed(qts);
}
void tgl_state::set_pts(int32_t pts, bool force)
{
if (locks & TGL_LOCK_DIFF && !force) {
return;
}
if (pts <= m_pts && !force) {
return;
}
m_pts = pts;
m_callback->pts_changed(pts);
}
void tgl_state::set_date(int64_t date, bool force)
{
if (locks & TGL_LOCK_DIFF && !force) {
return;
}
if (date <= m_date && !force) {
return;
}
m_date = date;
m_callback->date_changed(date);
}
void tgl_state::set_seq(int32_t seq)
{
if (locks & TGL_LOCK_DIFF) {
return;
}
if (seq <= m_seq) {
return;
}
m_seq = seq;
}
void tgl_state::reset_server_state()
{
m_qts = 0;
m_pts = 0;
m_date = 0;
m_seq = 0;
}
void tgl_state::add_rsa_key(const std::string& key)
{
m_rsa_key_list.push_back(std::unique_ptr<tgl_rsa_key>(new tgl_rsa_key(key)));
}
int tgl_state::init(const std::string& download_dir, int app_id, const std::string& app_hash, const std::string& app_version)
{
m_transfer_manager = std::make_shared<tgl_transfer_manager>(download_dir);
m_app_id = app_id;
m_app_hash = app_hash;
m_app_version = app_version;
assert(m_timer_factory);
assert(m_connection_factory);
if (!m_temp_key_expire_time) {
m_temp_key_expire_time = 7200; // seconds
}
if (tglmp_on_start() < 0) {
return -1;
}
if (!m_app_id) {
m_app_id = TG_APP_ID;
m_app_hash = TG_APP_HASH;
}
m_state_lookup_timer = m_timer_factory->create_timer(std::bind(&tgl_state::state_lookup_timeout, this));
m_state_lookup_timer->start(3600);
return 0;
}
void tgl_state::set_enable_pfs(bool val)
{
m_enable_pfs = val;
}
void tgl_state::set_test_mode(bool val)
{
m_test_mode = val;
}
void tgl_state::set_enable_ipv6(bool val)
{
m_ipv6_enabled = val;
}
void tgl_state::set_error(const std::string& error, int error_code)
{
m_error = error;
m_error_code = error_code;
}
int32_t tgl_state::create_secret_chat_id()
{
int chat_id = tgl_random<int>();
while (tgl_state::instance()->secret_chat_for_id(chat_id)) {
chat_id = tgl_random<int>();
}
return chat_id;
}
std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(int32_t id)
{
int chat_id;
if (id) {
chat_id = id;
} else {
chat_id = create_secret_chat_id();
}
auto secret_chat = std::make_shared<tgl_secret_chat>();
secret_chat->id = tgl_input_peer_t(tgl_peer_type::enc_chat, chat_id, 0);
m_secret_chats[chat_id] = secret_chat;
return secret_chat;
}
std::shared_ptr<tgl_secret_chat> tgl_state::create_secret_chat(const tgl_input_peer_t& chat_id)
{
if (m_secret_chats.find(chat_id.peer_id) != m_secret_chats.end()) {
return nullptr;
}
auto secret_chat = std::make_shared<tgl_secret_chat>();
secret_chat->id = chat_id;
m_secret_chats[chat_id.peer_id] = secret_chat;
return secret_chat;
}
std::shared_ptr<tgl_secret_chat> tgl_state::secret_chat_for_id(int chat_id) const
{
auto secret_chat_it = m_secret_chats.find(chat_id);
if (secret_chat_it == m_secret_chats.end()) {
return nullptr;
}
return secret_chat_it->second;
}
void tgl_state::add_secret_chat(const std::shared_ptr<tgl_secret_chat>& secret_chat)
{
m_secret_chats[secret_chat->id.peer_id] = secret_chat;
}
void tgl_state::add_query(const std::shared_ptr<query>& q)
{
auto id = q->msg_id();
assert(id);
auto inserted_iterator_pair = m_active_queries.emplace(id, q);
if (inserted_iterator_pair.second) {
q->dc()->increase_active_queries();
} else {
inserted_iterator_pair.first->second = q;
}
}
std::shared_ptr<query> tgl_state::get_query(int64_t id) const
{
assert(id);
auto it = m_active_queries.find(id);
if (it == m_active_queries.end()) {
return nullptr;
}
return it->second;
}
void tgl_state::remove_query(const std::shared_ptr<query>& q)
{
auto id = q->msg_id();
assert(id);
auto it = m_active_queries.find(id);
if (it != m_active_queries.end()) {
m_active_queries.erase(it);
q->dc()->decrease_active_queries();
}
}
void tgl_state::remove_all_queries()
{
m_active_queries.clear();
}
std::shared_ptr<tgl_dc> tgl_state::dc_at(int id)
{
if (static_cast<size_t>(id) >= m_dcs.size()) {
return nullptr;
}
return m_dcs[id];
}
std::shared_ptr<tgl_dc> tgl_state::allocate_dc(int id)
{
if (static_cast<size_t>(id) >= m_dcs.size()) {
m_dcs.resize(id+1, nullptr);
}
assert(!m_dcs[id]);
std::shared_ptr<tgl_dc> dc = std::make_shared<tgl_dc>();
dc->id = id;
m_dcs[id] = dc;
return dc;
}
void tgl_state::state_lookup_timeout()
{
tgl_do_lookup_state();
if (m_state_lookup_timer) {
m_state_lookup_timer->start(3600);
}
}
void tgl_state::logout()
{
tgl_do_logout(nullptr);
}
void tgl_state::set_online_status(tgl_online_status status)
{
if (status == m_online_status) {
return;
}
TGL_DEBUG("setting online status to " << static_cast<int>(status)
<< " (previous: " << static_cast<int>(m_online_status) << ")");
m_online_status = status;
for (const auto& weak_observer: m_online_status_observers) {
if (auto observer = weak_observer.lock()) {
observer->on_online_status_changed(status);
}
}
}
<|endoftext|> |
<commit_before>//
// Created by Harvey on 2017/1/4.
//
#include "strade_share_engine.h"
#define DEFAULT_CONFIG_PATH "./strade_share/stradeshare_config.xml"
strade_share::SSEngine* GetStradeShareEngine(void) {
return strade_share::SSEngineImpl::GetInstance();
}
namespace strade_share {
SSEngineImpl* SSEngineImpl::instance_ = NULL;
SSEngineImpl::SSEngineImpl() {
if (!Init()) {
LOG_ERROR("StradeShareEngineImpl Init error");
assert(0);
}
}
SSEngineImpl* SSEngineImpl::GetInstance() {
if (NULL == instance_) {
instance_ = new SSEngineImpl();
}
return instance_;
}
bool SSEngineImpl::Init() {
InitThreadrw(&lock_);
bool r = false;
std::string path = DEFAULT_CONFIG_PATH;
config::FileConfig* config = config::FileConfig::GetFileConfig();
if (config == NULL) {
return false;
}
r = config->LoadConfig(path);
if (!r) {
return false;
}
mysql_engine_ = new StradeShareDB(config);
LoadAllStockBasicInfo();
return true;
}
void SSEngineImpl::AttachObserver(strade_logic::Observer* observer) {
if(NULL != observer) {
base_logic::WLockGd lk(lock_);
this->Attach(observer);
}
}
void SSEngineImpl::DetachObserver(strade_logic::Observer* observer) {
if(NULL != observer) {
base_logic::WLockGd lk(lock_);
this->Detach(observer);
}
}
void SSEngineImpl::LoadAllStockBasicInfo() {
base_logic::WLockGd lk(lock_);
std::vector<strade_logic::StockTotalInfo> stock_vec;
mysql_engine_->FetchAllStockList(stock_vec);
std::vector<strade_logic::StockTotalInfo>::iterator iter(stock_vec.begin());
for (; iter != stock_vec.end(); ++iter) {
strade_logic::StockTotalInfo& stock_total_info = (*iter);
std::vector<strade_logic::StockHistInfo> stock_hist_vec;
mysql_engine_->FetchStockHistList(
stock_total_info.GetStockCode(), stock_hist_vec);
stock_total_info.AddStockHistVec(stock_hist_vec);
AddStockTotalInfoNonblock(stock_total_info);
}
}
void SSEngineImpl::UpdateStockRealMarketData(
REAL_MARKET_DATA_VEC& stocks_market_data) {
{
base_logic::WLockGd lk(lock_);
int total_count = 0;
REAL_MARKET_DATA_VEC::const_iterator iter(stocks_market_data.begin());
for (; iter != stocks_market_data.end(); ++iter) {
const strade_logic::StockRealInfo& stock_real_info = *iter;
const std::string& stock_code = stock_real_info.GetStockCode();
const time_t& trade_time = stock_real_info.GetTradeTime();
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
LOG_ERROR2("UpdateStockRealMarketData stock_code=%s, not exists!!!!",
stock_code.c_str());
continue;
}
stock_total_info->AddStockRealInfoByTime(trade_time, stock_real_info);
++total_count;
}
LOG_DEBUG2("UpdateStockRealMarketData total_count=%d, current_time=%d",
total_count, time(NULL));
}
// 通知所有需要实时行情数据的观察者
this->Notify(strade_logic::REALTIME_MARKET_VALUE_UPDATE);
}
bool SSEngineImpl::UpdateStockHistInfoByDate(const std::string& stock_code,
const std::string& date,
strade_logic::StockHistInfo& stock_hist_info) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL != stock_total_info) {
return stock_total_info->AddStockHistInfoByDate(date, stock_hist_info);
}
return false;
}
bool SSEngineImpl::ClearOldRealTradeMap() {
base_logic::WLockGd lk(lock_);
STOCKS_MAP::iterator iter(share_cache_.stocks_map_.begin());
for (; iter != share_cache_.stocks_map_.end(); ++iter) {
iter->second.ClearRealMap();
}
return true;
}
bool SSEngineImpl::UpdateStockHistDataVec(
const std::string& stock_code,
STOCK_HIST_DATA_VEC& stock_vec) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
return false;
}
stock_total_info->AddStockHistVec(stock_vec);
return true;
}
bool SSEngineImpl::AddStockTotalInfoNonblock(
const strade_logic::StockTotalInfo& stock_total_info) {
const std::string& stock_code = stock_total_info.GetStockCode();
share_cache_.stocks_map_[stock_code] = stock_total_info;
return true;
}
bool SSEngineImpl::AddStockTotalInfoBlock(
const strade_logic::StockTotalInfo& stock_total_info) {
base_logic::WLockGd lk(lock_);
AddStockTotalInfoNonblock(stock_total_info);
}
const STOCKS_MAP& SSEngineImpl::GetAllStockTotalMap() {
base_logic::RLockGd lk(lock_);
return share_cache_.stocks_map_;
}
const STOCK_HIST_MAP& SSEngineImpl::GetStockHistMap(
const std::string& stock_code) {
base_logic::RLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL != stock_total_info) {
return stock_total_info->GetStockHistMap();
}
return STOCK_HIST_MAP();
}
const STOCK_REAL_MAP& SSEngineImpl::GetStockRealInfoMap(
const std::string& stock_code) {
base_logic::RLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL != stock_total_info) {
return stock_total_info->GetStockRealMap();
}
return STOCK_REAL_MAP();
}
STOCKS_MAP SSEngineImpl::GetAllStockTotalMapCopy() {
base_logic::RLockGd lk(lock_);
return share_cache_.stocks_map_;
}
STOCK_HIST_MAP SSEngineImpl::GetStockHistMapByCodeCopy(
const std::string& stock_code) {
const STOCK_HIST_MAP& stock_hist_map =
GetStockHistMap(stock_code);
return stock_hist_map;
}
STOCK_REAL_MAP SSEngineImpl::GetStockRealInfoMapCopy(
const std::string& stock_code) {
const STOCK_REAL_MAP& stock_real_map =
GetStockRealInfoMap(stock_code);
return stock_real_map;
}
bool SSEngineImpl::GetStockTotalInfoByCode(
const std::string& stock_code,
strade_logic::StockTotalInfo* stock_total_info) {
base_logic::WLockGd lk(lock_);
GetStockTotalNonBlock(stock_code, &stock_total_info);
}
bool SSEngineImpl::GetStockHistInfoByDate(
const std::string& stock_code,
const std::string& date,
strade_logic::StockHistInfo* stock_hist_info) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info(NULL);
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
return false;
}
return stock_total_info->GetStockHistInfoByDate(date, &stock_hist_info);
}
bool SSEngineImpl::GetStockRealMarketDataByTime(
const std::string& stock_code,
const time_t& time,
strade_logic::StockRealInfo* stock_real_info) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info(NULL);
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
return false;
}
return stock_total_info->GetStockRealInfoByTradeTime(time, &stock_real_info);
}
} /* namespace strade_share */
<commit_msg>修改共享库返回map时为拷贝<commit_after>//
// Created by Harvey on 2017/1/4.
//
#include "strade_share_engine.h"
#define DEFAULT_CONFIG_PATH "./strade_share/stradeshare_config.xml"
strade_share::SSEngine* GetStradeShareEngine(void) {
return strade_share::SSEngineImpl::GetInstance();
}
namespace strade_share {
SSEngineImpl* SSEngineImpl::instance_ = NULL;
SSEngineImpl::SSEngineImpl() {
if (!Init()) {
LOG_ERROR("StradeShareEngineImpl Init error");
assert(0);
}
}
SSEngineImpl* SSEngineImpl::GetInstance() {
if (NULL == instance_) {
instance_ = new SSEngineImpl();
}
return instance_;
}
bool SSEngineImpl::Init() {
InitThreadrw(&lock_);
bool r = false;
std::string path = DEFAULT_CONFIG_PATH;
config::FileConfig* config = config::FileConfig::GetFileConfig();
if (config == NULL) {
return false;
}
r = config->LoadConfig(path);
if (!r) {
return false;
}
mysql_engine_ = new StradeShareDB(config);
LoadAllStockBasicInfo();
return true;
}
void SSEngineImpl::AttachObserver(strade_logic::Observer* observer) {
if(NULL != observer) {
base_logic::WLockGd lk(lock_);
this->Attach(observer);
}
}
void SSEngineImpl::DetachObserver(strade_logic::Observer* observer) {
if(NULL != observer) {
base_logic::WLockGd lk(lock_);
this->Detach(observer);
}
}
void SSEngineImpl::LoadAllStockBasicInfo() {
base_logic::WLockGd lk(lock_);
std::vector<strade_logic::StockTotalInfo> stock_vec;
mysql_engine_->FetchAllStockList(stock_vec);
std::vector<strade_logic::StockTotalInfo>::iterator iter(stock_vec.begin());
for (; iter != stock_vec.end(); ++iter) {
strade_logic::StockTotalInfo& stock_total_info = (*iter);
std::vector<strade_logic::StockHistInfo> stock_hist_vec;
mysql_engine_->FetchStockHistList(
stock_total_info.GetStockCode(), stock_hist_vec);
stock_total_info.AddStockHistVec(stock_hist_vec);
AddStockTotalInfoNonblock(stock_total_info);
}
}
void SSEngineImpl::UpdateStockRealMarketData(
REAL_MARKET_DATA_VEC& stocks_market_data) {
{
base_logic::WLockGd lk(lock_);
int total_count = 0;
REAL_MARKET_DATA_VEC::const_iterator iter(stocks_market_data.begin());
for (; iter != stocks_market_data.end(); ++iter) {
const strade_logic::StockRealInfo& stock_real_info = *iter;
const std::string& stock_code = stock_real_info.GetStockCode();
const time_t& trade_time = stock_real_info.GetTradeTime();
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
LOG_ERROR2("UpdateStockRealMarketData stock_code=%s, not exists!!!!",
stock_code.c_str());
continue;
}
stock_total_info->AddStockRealInfoByTime(trade_time, stock_real_info);
++total_count;
}
LOG_DEBUG2("UpdateStockRealMarketData total_count=%d, current_time=%d",
total_count, time(NULL));
}
// 通知所有需要实时行情数据的观察者
this->Notify(strade_logic::REALTIME_MARKET_VALUE_UPDATE);
}
bool SSEngineImpl::UpdateStockHistInfoByDate(const std::string& stock_code,
const std::string& date,
strade_logic::StockHistInfo& stock_hist_info) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL != stock_total_info) {
return stock_total_info->AddStockHistInfoByDate(date, stock_hist_info);
}
return false;
}
bool SSEngineImpl::ClearOldRealTradeMap() {
base_logic::WLockGd lk(lock_);
STOCKS_MAP::iterator iter(share_cache_.stocks_map_.begin());
for (; iter != share_cache_.stocks_map_.end(); ++iter) {
iter->second.ClearRealMap();
}
return true;
}
bool SSEngineImpl::UpdateStockHistDataVec(
const std::string& stock_code,
STOCK_HIST_DATA_VEC& stock_vec) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
return false;
}
stock_total_info->AddStockHistVec(stock_vec);
return true;
}
bool SSEngineImpl::AddStockTotalInfoNonblock(
const strade_logic::StockTotalInfo& stock_total_info) {
const std::string& stock_code = stock_total_info.GetStockCode();
share_cache_.stocks_map_[stock_code] = stock_total_info;
return true;
}
bool SSEngineImpl::AddStockTotalInfoBlock(
const strade_logic::StockTotalInfo& stock_total_info) {
base_logic::WLockGd lk(lock_);
AddStockTotalInfoNonblock(stock_total_info);
return true;
}
const STOCKS_MAP& SSEngineImpl::GetAllStockTotalMap() {
base_logic::RLockGd lk(lock_);
return share_cache_.stocks_map_;
}
const STOCK_HIST_MAP& SSEngineImpl::GetStockHistMap(
const std::string& stock_code) {
base_logic::RLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL != stock_total_info) {
return stock_total_info->GetStockHistMap();
}
return STOCK_HIST_MAP();
}
const STOCK_REAL_MAP& SSEngineImpl::GetStockRealInfoMap(
const std::string& stock_code) {
base_logic::RLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info = NULL;
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL != stock_total_info) {
return stock_total_info->GetStockRealMap();
}
return STOCK_REAL_MAP();
}
STOCKS_MAP SSEngineImpl::GetAllStockTotalMapCopy() {
base_logic::RLockGd lk(lock_);
return share_cache_.stocks_map_;
}
STOCK_HIST_MAP SSEngineImpl::GetStockHistMapByCodeCopy(
const std::string& stock_code) {
const STOCK_HIST_MAP& stock_hist_map =
GetStockHistMap(stock_code);
return stock_hist_map;
}
STOCK_REAL_MAP SSEngineImpl::GetStockRealInfoMapCopy(
const std::string& stock_code) {
const STOCK_REAL_MAP& stock_real_map =
GetStockRealInfoMap(stock_code);
return stock_real_map;
}
bool SSEngineImpl::GetStockTotalInfoByCode(
const std::string& stock_code,
strade_logic::StockTotalInfo* stock_total_info) {
base_logic::WLockGd lk(lock_);
GetStockTotalNonBlock(stock_code, &stock_total_info);
}
bool SSEngineImpl::GetStockHistInfoByDate(
const std::string& stock_code,
const std::string& date,
strade_logic::StockHistInfo* stock_hist_info) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info(NULL);
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
return false;
}
return stock_total_info->GetStockHistInfoByDate(date, &stock_hist_info);
}
bool SSEngineImpl::GetStockRealMarketDataByTime(
const std::string& stock_code,
const time_t& time,
strade_logic::StockRealInfo* stock_real_info) {
base_logic::WLockGd lk(lock_);
strade_logic::StockTotalInfo* stock_total_info(NULL);
GetStockTotalNonBlock(stock_code, &stock_total_info);
if (NULL == stock_total_info) {
return false;
}
return stock_total_info->GetStockRealInfoByTradeTime(time, &stock_real_info);
}
} /* namespace strade_share */
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2003-2012
\file app/rdo_studio_mfc/src/model/model_view.cpp
\author ([email protected])
\date 20.02.2003
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <QtGui/qevent.h>
#include <QtGui/qboxlayout.h>
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_mfc/src/model/model_view.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/resource.h"
#include "app/rdo_studio_mfc/src/main_frm.h"
// --------------------------------------------------------------------------------
using namespace rdoEditor;
// --------------------------------------------------------------------------------
// -------------------- RDOStudioModelView
// --------------------------------------------------------------------------------
// ON_UPDATE_COMMAND_UI
//! @todo qt
// RDOStudioEditBaseView -> QWidget
//BEGIN_MESSAGE_MAP(RDOStudioModelView, RDOStudioEditBaseView)
// ON_WM_CREATE()
// ON_WM_SETFOCUS()
// ON_WM_SIZE()
//END_MESSAGE_MAP()
RDOStudioModelView::RDOStudioModelView(PTR(QWidget) pParent)
: parent_type(pParent)
, m_pModel (NULL)
, m_pTabCtrl (NULL)
, m_pFindDialog(NULL)
{
m_pTabCtrl = new RDOEditorTabCtrl(this, this);
PTR(QVBoxLayout) pLayout = new QVBoxLayout(this);
pLayout->setSpacing(0);
pLayout->setContentsMargins(0, 0, 0, 0);
pLayout->addWidget(m_pTabCtrl);
RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
ASSERT(pMainWindow);
pMainWindow->actSearchFindInModel->setEnabled(true);
connect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}
RDOStudioModelView::~RDOStudioModelView()
{
RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
ASSERT(pMainWindow);
disconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}
void RDOStudioModelView::setModel(PTR(RDOStudioModel) pModel)
{
ASSERT(m_pModel != pModel);
m_pModel = pModel;
}
void RDOStudioModelView::closeEvent(PTR(QCloseEvent) event)
{
if (m_pModel)
{
if (m_pModel->closeModel())
{
event->accept();
}
else
{
event->ignore();
}
}
}
//! @todo qt
//BOOL RDOStudioModelView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
//{
// if ( m_pTabCtrl->getCurrentEdit()->OnCmdMsg( nID, nCode, pExtra, pHandlerInfo ) ) return TRUE;
// return RDOStudioEditBaseView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
//}
//
//void RDOStudioModelView::OnSetFocus(CWnd* pOldWnd)
//{
// RDOStudioEditBaseView::OnSetFocus( pOldWnd );
// m_pTabCtrl->SetFocus();
//}
//
REF(rdoEditor::RDOEditorTabCtrl) RDOStudioModelView::getTab()
{
return *m_pTabCtrl;
}
void RDOStudioModelView::onSearchFindInModel()
{
m_findSettings.what = m_pTabCtrl->getCurrentEdit()->getWordForFind();
if (!m_pFindDialog)
{
m_pFindDialog = new FindDialog(
this,
boost::bind(&RDOStudioModelView::onFindDlgFind, this, _1),
boost::bind(&RDOStudioModelView::onFindDlgClose, this)
);
}
m_pFindDialog->setSettings(m_findSettings);
m_pFindDialog->show();
m_pFindDialog->raise();
m_pFindDialog->activateWindow();
}
void RDOStudioModelView::onFindDlgFind(CREF(FindDialog::Settings) settings)
{
m_findSettings = settings;
onSearchFindAll();
}
void RDOStudioModelView::onFindDlgClose()
{
m_pFindDialog = NULL;
}
void RDOStudioModelView::onSearchFindAll()
{
studioApp.getIMainWnd()->getDockFind().clear();
studioApp.getIMainWnd()->getDockFind().raise();
tstring findStr = m_findSettings.what;
rbool bMatchCase = m_findSettings.matchCase;
rbool bMatchWholeWord = m_findSettings.matchWholeWord;
studioApp.getIMainWnd()->getDockFind().getContext().setKeyword(findStr, bMatchCase);
studioApp.getIMainWnd()->getDockFind().appendString(rdo::format(ID_FINDINMODEL_BEGINMSG, findStr.c_str()));
int count = 0;
for (int i = 0; i < m_pTabCtrl->count(); i++)
{
PTR(RDOEditorEdit) pEdit = m_pTabCtrl->getItemEdit(i);
int pos = 0;
int line = 0;
while (pos != -1)
{
pos = pEdit->findPos(findStr, line, bMatchCase, bMatchWholeWord);
if (pos != -1)
{
line = pEdit->getLineFromPosition(pos);
studioApp.getIMainWnd()->getDockFind().appendString(pEdit->getLine(line), m_pTabCtrl->indexToType(i), line, pos - pEdit->getPositionFromLine(line));
line++;
count++;
}
}
}
m_pFindDialog = NULL;
tstring s = count
? rdo::format(ID_FINDINMODEL_ENDMSG_COUNT, count)
: rdo::format(ID_FINDINMODEL_ENDMSG_NOTFOUND, findStr.c_str());
studioApp.getIMainWnd()->getDockFind().appendString(s);
}<commit_msg> - чистка кода<commit_after>/*!
\copyright (c) RDO-Team, 2003-2012
\file app/rdo_studio_mfc/src/model/model_view.cpp
\author ([email protected])
\date 20.02.2003
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <QtGui/qevent.h>
#include <QtGui/qboxlayout.h>
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_mfc/src/model/model_view.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/resource.h"
#include "app/rdo_studio_mfc/src/main_frm.h"
// --------------------------------------------------------------------------------
using namespace rdoEditor;
// --------------------------------------------------------------------------------
// -------------------- RDOStudioModelView
// --------------------------------------------------------------------------------
RDOStudioModelView::RDOStudioModelView(PTR(QWidget) pParent)
: parent_type(pParent)
, m_pModel (NULL)
, m_pTabCtrl (NULL)
, m_pFindDialog(NULL)
{
m_pTabCtrl = new RDOEditorTabCtrl(this, this);
PTR(QVBoxLayout) pLayout = new QVBoxLayout(this);
pLayout->setSpacing(0);
pLayout->setContentsMargins(0, 0, 0, 0);
pLayout->addWidget(m_pTabCtrl);
RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
ASSERT(pMainWindow);
pMainWindow->actSearchFindInModel->setEnabled(true);
connect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}
RDOStudioModelView::~RDOStudioModelView()
{
RDOStudioMainFrame* pMainWindow = studioApp.getMainWndUI();
ASSERT(pMainWindow);
disconnect(pMainWindow->actSearchFindInModel, SIGNAL(triggered(bool)), this, SLOT(onSearchFindInModel()));
}
void RDOStudioModelView::setModel(PTR(RDOStudioModel) pModel)
{
ASSERT(m_pModel != pModel);
m_pModel = pModel;
}
void RDOStudioModelView::closeEvent(PTR(QCloseEvent) event)
{
if (m_pModel)
{
if (m_pModel->closeModel())
{
event->accept();
}
else
{
event->ignore();
}
}
}
//! @todo qt
//BOOL RDOStudioModelView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
//{
// if ( m_pTabCtrl->getCurrentEdit()->OnCmdMsg( nID, nCode, pExtra, pHandlerInfo ) ) return TRUE;
// return RDOStudioEditBaseView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
//}
//
//void RDOStudioModelView::OnSetFocus(CWnd* pOldWnd)
//{
// RDOStudioEditBaseView::OnSetFocus( pOldWnd );
// m_pTabCtrl->SetFocus();
//}
//
REF(rdoEditor::RDOEditorTabCtrl) RDOStudioModelView::getTab()
{
return *m_pTabCtrl;
}
void RDOStudioModelView::onSearchFindInModel()
{
m_findSettings.what = m_pTabCtrl->getCurrentEdit()->getWordForFind();
if (!m_pFindDialog)
{
m_pFindDialog = new FindDialog(
this,
boost::bind(&RDOStudioModelView::onFindDlgFind, this, _1),
boost::bind(&RDOStudioModelView::onFindDlgClose, this)
);
}
m_pFindDialog->setSettings(m_findSettings);
m_pFindDialog->show();
m_pFindDialog->raise();
m_pFindDialog->activateWindow();
}
void RDOStudioModelView::onFindDlgFind(CREF(FindDialog::Settings) settings)
{
m_findSettings = settings;
onSearchFindAll();
}
void RDOStudioModelView::onFindDlgClose()
{
m_pFindDialog = NULL;
}
void RDOStudioModelView::onSearchFindAll()
{
studioApp.getIMainWnd()->getDockFind().clear();
studioApp.getIMainWnd()->getDockFind().raise();
tstring findStr = m_findSettings.what;
rbool bMatchCase = m_findSettings.matchCase;
rbool bMatchWholeWord = m_findSettings.matchWholeWord;
studioApp.getIMainWnd()->getDockFind().getContext().setKeyword(findStr, bMatchCase);
studioApp.getIMainWnd()->getDockFind().appendString(rdo::format(ID_FINDINMODEL_BEGINMSG, findStr.c_str()));
int count = 0;
for (int i = 0; i < m_pTabCtrl->count(); i++)
{
PTR(RDOEditorEdit) pEdit = m_pTabCtrl->getItemEdit(i);
int pos = 0;
int line = 0;
while (pos != -1)
{
pos = pEdit->findPos(findStr, line, bMatchCase, bMatchWholeWord);
if (pos != -1)
{
line = pEdit->getLineFromPosition(pos);
studioApp.getIMainWnd()->getDockFind().appendString(pEdit->getLine(line), m_pTabCtrl->indexToType(i), line, pos - pEdit->getPositionFromLine(line));
line++;
count++;
}
}
}
m_pFindDialog = NULL;
tstring s = count
? rdo::format(ID_FINDINMODEL_ENDMSG_COUNT, count)
: rdo::format(ID_FINDINMODEL_ENDMSG_NOTFOUND, findStr.c_str());
studioApp.getIMainWnd()->getDockFind().appendString(s);
}<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* 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
*
* "@(#) $Id: bulkDataNTReaderListener.cpp,v 1.34 2011/12/22 15:59:57 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2011-04-19 created
*/
#include "bulkDataNTReaderListener.h"
#include "ACS_BD_Errors.h"
#include <ACS_DDS_Errors.h>
#include <ACSErrTypeCommon.h>
#include <iostream>
#include <iterator>
using namespace ACS_BD_Errors;
using namespace ACS_DDS_Errors;
using namespace AcsBulkdata;
using namespace std;
#define BDNT_READER_LISTENER_USER_ERR(call) \
try { call; \
}catch(const ACSErr::ACSbaseExImpl &ex){ \
UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__); \
ucb.setCall("#call"); \
callback_mp->onError(ucb); \
}catch(const std::exception &stdex){ \
ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); \
ex.setWhat(stdex.what()); \
UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__); \
ucb.setCall("#call"); \
callback_mp->onError(ucb); \
}catch(...){ \
ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); \
UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__); \
ucb.setCall("#call"); \
callback_mp->onError(ucb); \
}
BulkDataNTReaderListener::BulkDataNTReaderListener(const char* name, BulkDataNTCallback* cb)
: BulkDataNTDDSLoggable("BulkDataNT:"+string(name)),
currentState_m(StartState),
topicName_m(name),
dataLength_m(0),
frameCounter_m(0),
totalFrames_m(0),
callback_mp (cb)
{
ACS_TRACE(__FUNCTION__);
nextFrame_m=0;
frameDataReader_mp=0;
conseqErrorCount_m=0;
maxConseqErrorCount_m = 4; //TBD now hardcoded, to be get from somewhere else
cbReceiveTimeoutSec_m = callback_mp->getCBReceiveProcessTimeout();
}//BulkDataNTReaderListener
BulkDataNTReaderListener::~BulkDataNTReaderListener ()
{
ACS_TRACE(__FUNCTION__);
}//~BulkDataNTReaderListener
void BulkDataNTReaderListener::on_data_available(DDS::DataReader* reader)
{
DDS::ReturnCode_t retCode;
DDS::SampleInfo si ;
ACSBulkData::BulkDataNTFrame message;
unsigned char tmpArray[ACSBulkData::FRAME_MAX_LEN];
initalizeLogging(); //force initialization of logging sys TBD changed
if (frameDataReader_mp==NULL)
{
frameDataReader_mp = ACSBulkData::BulkDataNTFrameDataReader::narrow(reader);
if ( frameDataReader_mp==NULL) {
ACS_DDS_Errors::DDSNarrowFailedCompletion nerr(__FILE__, __LINE__, __FUNCTION__);
nerr.setVariable("frameDataReader_mp");
nerr.setNarrowType("ACSBulkData::BulkDataNTFrameDataReader");
callback_mp->onError(nerr);
return;
}//if
}//if
message.data.maximum(ACSBulkData::FRAME_MAX_LEN); //TBD constant from
while ( (retCode = frameDataReader_mp->take_next_sample(message, si)) != DDS::RETCODE_NO_DATA )
{
if (retCode == DDS::RETCODE_OK)
{
if (si.valid_data == true)
{
switch(message.dataType)
{
case ACSBulkData::BD_PARAM:
{
cout << topicName_m << " startSend: parameter size: " << message.data.length() << endl;
if (currentState_m==StartState || currentState_m==StopState)
{
dataLength_m = 0;
frameCounter_m = 0;
currentState_m = DataRcvState;
message.data.to_array(tmpArray, message.data.length());
BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStart(tmpArray, message.data.length()) )
conseqErrorCount_m=0;
}
else //error
{
WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);
wfo.setDataType("BD_PARAM"); wfo.setState(currentState_m);
wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);
wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());
callback_mp->onError(wfo);
increasConseqErrorCount();
}//if-else
break;
}// case ACSBulkData::BD_PARAM:
case ACSBulkData::BD_DATA:
{
if (currentState_m==DataRcvState)
{
if (dataLength_m==0) // we get the first data frame
{
std::cout << " ************************* New sendData @ " << topicName_m << " *******************************" << std::endl;
start_time = ACE_OS::gettimeofday();
totalFrames_m = message.restDataLength+1;
frameCounter_m = 0;
}//if
dataLength_m += message.data.length();
frameCounter_m ++;
if ( message.restDataLength>0)
{
if (nextFrame_m!=0 && nextFrame_m!=message.restDataLength) // do we miss a frame ?
{
FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);
lde.setNextDataFrame(nextFrame_m);
lde.setFrameCount(frameCounter_m);
lde.setRestFrames(message.restDataLength);
lde.setFrameLength(message.data.length());
lde.setFlow(topicName_m.c_str());
callback_mp->onError(lde);
increasConseqErrorCount();
return; // ??
}
nextFrame_m = message.restDataLength-1;
}
else //message.restDataLength==0 what means we got the last frame
{
ACE_Time_Value elapsed_time = ACE_OS::gettimeofday() - start_time;
cout << topicName_m << " Received all data from sendData: " << dataLength_m << " Bytes in ";
cout <<(elapsed_time.sec()+( elapsed_time.usec() / 1000000.0 ));
cout << "secs. => Rate: ";
cout << ((dataLength_m/(1024.0*1024.0))/(elapsed_time.sec()+( elapsed_time.usec() / 1000000.0 ))) << "MBytes/sec" << endl;
DDS::SampleLostStatus s;
reader->get_sample_lost_status(s);
cerr << topicName_m << " LOST samples: \t\t total_count: " << s.total_count << " total_count_change: " << s.total_count_change << endl;
dataLength_m = 0;
}
cbReceiveStartTime_m = ACE_OS::gettimeofday();
message.data.to_array(tmpArray, message.data.length());
BDNT_READER_LISTENER_USER_ERR( callback_mp->cbReceive(tmpArray, message.data.length()) )
conseqErrorCount_m=0;
cbReceiveElapsedTime_m = ACE_OS::gettimeofday() - cbReceiveStartTime_m;
cbReceiveElapsedTimeSec_m = cbReceiveElapsedTime_m.sec() + (cbReceiveElapsedTime_m.usec() / 1000000.0);
if (cbReceiveElapsedTimeSec_m>cbReceiveTimeoutSec_m)
{
CBReceiveProcessTimeoutCompletion cbReceiveTO(__FILE__, __LINE__, __FUNCTION__);
cbReceiveTO.setProcessTimeoutSec(cbReceiveTimeoutSec_m);
cbReceiveTO.setActaullProcessTime(cbReceiveElapsedTimeSec_m);
callback_mp->onError(cbReceiveTO);
//TBD should we increase error counter here or not ?
}//if cbReceiveTimeoutSec_m
}
else //error
{
WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);
wfo.setDataType("BD_DATA"); wfo.setState(currentState_m);
wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);
wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());
callback_mp->onError(wfo);
increasConseqErrorCount();
}
break;
}//case ACSBulkData::BD_DATA
case ACSBulkData::BD_STOP:
{
if (currentState_m==DataRcvState)
{
currentState_m = StopState;
cout << topicName_m << " Received sendStop" << endl;
cout << "===============================================================" << endl;
if (frameCounter_m==0)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "On %s got stop (BD_STOP) before any data (sendData)!",
topicName_m.c_str()));
}else
{
if (frameCounter_m != totalFrames_m)
{
ACS_BD_Errors::FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);
lde.setNextDataFrame(nextFrame_m);
lde.setFrameCount(frameCounter_m);
lde.setRestFrames(message.restDataLength); // should be ??
lde.setFrameLength(message.data.length()); // should be 0
lde.setFlow(topicName_m.c_str());
callback_mp->onError(lde);
increasConseqErrorCount();
}//if
}//if-else
}else
{
if (currentState_m==StopState)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "On %s stop (BD_STOP) arrived in stop state - will be ignored!",
topicName_m.c_str()));
}
else //StartState
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "On %s stop (BD_STOP) arrived in start state: no parameter data (startSend) has arrived!",
topicName_m.c_str()));
}//if-else
}
// in all above warning/error case we call user's cbStop()
BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStop() )
conseqErrorCount_m=0;
break;
}//case ACSBulkData::BD_STOP
default:
conseqErrorCount_m++;
UnknownDataTypeCompletion udt(__FILE__, __LINE__, __FUNCTION__);
udt.setDataType(message.dataType);
udt.setFrameCount(frameCounter_m);
udt.setTotalFrameCount(totalFrames_m);
callback_mp->onError(udt);
}//switch
}//if(si.valid_data)
}
else
{
conseqErrorCount_m++;
DDSReturnErrorCompletion retErr(__FILE__, __LINE__, __FUNCTION__);
retErr.setRetCode(retCode); //would be good if we can give also string value
callback_mp->onError(retErr);
}//if(retCode)
}//while
}//on_data_available
void BulkDataNTReaderListener::on_requested_deadline_missed(DDS::DataReader*, const DDS::RequestedDeadlineMissedStatus& )
{
ACS_DDS_Errors::DDSDeadlineMissedCompletion dmerr(__FILE__, __LINE__, __FUNCTION__);
initalizeLogging(); //force initialization of logging sys TBD changed
callback_mp->onError(dmerr);
}//on_requested_deadline_missed
void BulkDataNTReaderListener::on_requested_incompatible_qos(DDS::DataReader*, const DDS::RequestedIncompatibleQosStatus&)
{
ACS_DDS_Errors::DDSIncompatibleQoSCompletion iqerr(__FILE__, __LINE__, __FUNCTION__);
initalizeLogging(); //force initialization of logging sys TBD changed
callback_mp->onError(iqerr);
}//on_requested_incompatible_qos
void BulkDataNTReaderListener::on_liveliness_changed(DDS::DataReader*, const DDS::LivelinessChangedStatus& lcs)
{
if (lcs.alive_count_change>0)
{
for(int i=0; i<lcs.alive_count_change; i++)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_INFO, "A new sender has connected to flow: %s of the stream: %s. Total alive connection(s): %d",
callback_mp->getFlowName(), callback_mp->getStreamName(),
lcs.alive_count));
BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderConnect() )
}//for
}else
{
for(int i=lcs.alive_count_change; i<0; i++)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_INFO, "A sender has disconnected to flow: %s of the stream: %s. Total alive connection(s): %d",
callback_mp->getFlowName(), callback_mp->getStreamName(),
lcs.alive_count));
BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderDisconnect() )
}//for
}//if-else
}//on_liveliness_changed
void BulkDataNTReaderListener::on_subscription_matched(DDS::DataReader*, const DDS::SubscriptionMatchedStatus&)
{
ACS_TRACE(__FUNCTION__);
}//on_subscription_matched
void BulkDataNTReaderListener::on_sample_rejected( DDS::DataReader*, const DDS::SampleRejectedStatus& srs)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "Sample Rejected: reason %d, change: %d, total: %d!",
srs.last_reason, srs.total_count_change, srs.total_count));
}//on_sample_rejected
void BulkDataNTReaderListener::on_sample_lost(DDS::DataReader*, const DDS::SampleLostStatus& s)
{
ACS_BD_Errors::SampleLostCompletion sle(__FILE__, __LINE__, __FUNCTION__);
sle.setLostSamples(s.total_count_change);
sle.setNextDataFrame(nextFrame_m);
sle.setFrameCount(frameCounter_m);
sle.setFlow(topicName_m.c_str());
initalizeLogging(); //force initialization of logging sys TBD changed
callback_mp->onError(sle);
}//on_sample_lost
void BulkDataNTReaderListener::increasConseqErrorCount()
{
conseqErrorCount_m++;
if (conseqErrorCount_m>=maxConseqErrorCount_m)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_ALERT, "Too many consequent errors: %d/%d on %s",
conseqErrorCount_m, maxConseqErrorCount_m, topicName_m.c_str()));
//TBD: disconnect
}
}//increasConseqErroCount
<commit_msg>set FlowName to CBReceiveProcessTimeoutCompletion<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* 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
*
* "@(#) $Id: bulkDataNTReaderListener.cpp,v 1.35 2011/12/22 16:05:45 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2011-04-19 created
*/
#include "bulkDataNTReaderListener.h"
#include "ACS_BD_Errors.h"
#include <ACS_DDS_Errors.h>
#include <ACSErrTypeCommon.h>
#include <iostream>
#include <iterator>
using namespace ACS_BD_Errors;
using namespace ACS_DDS_Errors;
using namespace AcsBulkdata;
using namespace std;
#define BDNT_READER_LISTENER_USER_ERR(call) \
try { call; \
}catch(const ACSErr::ACSbaseExImpl &ex){ \
UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__); \
ucb.setCall("#call"); \
callback_mp->onError(ucb); \
}catch(const std::exception &stdex){ \
ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); \
ex.setWhat(stdex.what()); \
UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__); \
ucb.setCall("#call"); \
callback_mp->onError(ucb); \
}catch(...){ \
ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); \
UserCallbackErrorCompletion ucb(ex, __FILE__, __LINE__, __FUNCTION__); \
ucb.setCall("#call"); \
callback_mp->onError(ucb); \
}
BulkDataNTReaderListener::BulkDataNTReaderListener(const char* name, BulkDataNTCallback* cb)
: BulkDataNTDDSLoggable("BulkDataNT:"+string(name)),
currentState_m(StartState),
topicName_m(name),
dataLength_m(0),
frameCounter_m(0),
totalFrames_m(0),
callback_mp (cb)
{
ACS_TRACE(__FUNCTION__);
nextFrame_m=0;
frameDataReader_mp=0;
conseqErrorCount_m=0;
maxConseqErrorCount_m = 4; //TBD now hardcoded, to be get from somewhere else
cbReceiveTimeoutSec_m = callback_mp->getCBReceiveProcessTimeout();
}//BulkDataNTReaderListener
BulkDataNTReaderListener::~BulkDataNTReaderListener ()
{
ACS_TRACE(__FUNCTION__);
}//~BulkDataNTReaderListener
void BulkDataNTReaderListener::on_data_available(DDS::DataReader* reader)
{
DDS::ReturnCode_t retCode;
DDS::SampleInfo si ;
ACSBulkData::BulkDataNTFrame message;
unsigned char tmpArray[ACSBulkData::FRAME_MAX_LEN];
initalizeLogging(); //force initialization of logging sys TBD changed
if (frameDataReader_mp==NULL)
{
frameDataReader_mp = ACSBulkData::BulkDataNTFrameDataReader::narrow(reader);
if ( frameDataReader_mp==NULL) {
ACS_DDS_Errors::DDSNarrowFailedCompletion nerr(__FILE__, __LINE__, __FUNCTION__);
nerr.setVariable("frameDataReader_mp");
nerr.setNarrowType("ACSBulkData::BulkDataNTFrameDataReader");
callback_mp->onError(nerr);
return;
}//if
}//if
message.data.maximum(ACSBulkData::FRAME_MAX_LEN); //TBD constant from
while ( (retCode = frameDataReader_mp->take_next_sample(message, si)) != DDS::RETCODE_NO_DATA )
{
if (retCode == DDS::RETCODE_OK)
{
if (si.valid_data == true)
{
switch(message.dataType)
{
case ACSBulkData::BD_PARAM:
{
cout << topicName_m << " startSend: parameter size: " << message.data.length() << endl;
if (currentState_m==StartState || currentState_m==StopState)
{
dataLength_m = 0;
frameCounter_m = 0;
currentState_m = DataRcvState;
message.data.to_array(tmpArray, message.data.length());
BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStart(tmpArray, message.data.length()) )
conseqErrorCount_m=0;
}
else //error
{
WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);
wfo.setDataType("BD_PARAM"); wfo.setState(currentState_m);
wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);
wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());
callback_mp->onError(wfo);
increasConseqErrorCount();
}//if-else
break;
}// case ACSBulkData::BD_PARAM:
case ACSBulkData::BD_DATA:
{
if (currentState_m==DataRcvState)
{
if (dataLength_m==0) // we get the first data frame
{
std::cout << " ************************* New sendData @ " << topicName_m << " *******************************" << std::endl;
start_time = ACE_OS::gettimeofday();
totalFrames_m = message.restDataLength+1;
frameCounter_m = 0;
}//if
dataLength_m += message.data.length();
frameCounter_m ++;
if ( message.restDataLength>0)
{
if (nextFrame_m!=0 && nextFrame_m!=message.restDataLength) // do we miss a frame ?
{
FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);
lde.setNextDataFrame(nextFrame_m);
lde.setFrameCount(frameCounter_m);
lde.setRestFrames(message.restDataLength);
lde.setFrameLength(message.data.length());
lde.setFlow(topicName_m.c_str());
callback_mp->onError(lde);
increasConseqErrorCount();
return; // ??
}
nextFrame_m = message.restDataLength-1;
}
else //message.restDataLength==0 what means we got the last frame
{
ACE_Time_Value elapsed_time = ACE_OS::gettimeofday() - start_time;
cout << topicName_m << " Received all data from sendData: " << dataLength_m << " Bytes in ";
cout <<(elapsed_time.sec()+( elapsed_time.usec() / 1000000.0 ));
cout << "secs. => Rate: ";
cout << ((dataLength_m/(1024.0*1024.0))/(elapsed_time.sec()+( elapsed_time.usec() / 1000000.0 ))) << "MBytes/sec" << endl;
DDS::SampleLostStatus s;
reader->get_sample_lost_status(s);
cerr << topicName_m << " LOST samples: \t\t total_count: " << s.total_count << " total_count_change: " << s.total_count_change << endl;
dataLength_m = 0;
}
cbReceiveStartTime_m = ACE_OS::gettimeofday();
message.data.to_array(tmpArray, message.data.length());
BDNT_READER_LISTENER_USER_ERR( callback_mp->cbReceive(tmpArray, message.data.length()) )
conseqErrorCount_m=0;
cbReceiveElapsedTime_m = ACE_OS::gettimeofday() - cbReceiveStartTime_m;
cbReceiveElapsedTimeSec_m = cbReceiveElapsedTime_m.sec() + (cbReceiveElapsedTime_m.usec() / 1000000.0);
if (cbReceiveElapsedTimeSec_m>cbReceiveTimeoutSec_m)
{
CBReceiveProcessTimeoutCompletion cbReceiveTO(__FILE__, __LINE__, __FUNCTION__);
cbReceiveTO.setFlowName(topicName_m.c_str());
cbReceiveTO.setProcessTimeoutSec(cbReceiveTimeoutSec_m);
cbReceiveTO.setActaullProcessTime(cbReceiveElapsedTimeSec_m);
callback_mp->onError(cbReceiveTO);
//TBD should we increase error counter here or not ?
}//if cbReceiveTimeoutSec_m
}
else //error
{
WrongFrameOrderCompletion wfo(__FILE__, __LINE__, __FUNCTION__);
wfo.setDataType("BD_DATA"); wfo.setState(currentState_m);
wfo.setFlow(topicName_m.c_str()); wfo.setFrameCount(frameCounter_m);
wfo.setTotalFrameCount(totalFrames_m); wfo.setFrameLength(message.data.length());
callback_mp->onError(wfo);
increasConseqErrorCount();
}
break;
}//case ACSBulkData::BD_DATA
case ACSBulkData::BD_STOP:
{
if (currentState_m==DataRcvState)
{
currentState_m = StopState;
cout << topicName_m << " Received sendStop" << endl;
cout << "===============================================================" << endl;
if (frameCounter_m==0)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "On %s got stop (BD_STOP) before any data (sendData)!",
topicName_m.c_str()));
}else
{
if (frameCounter_m != totalFrames_m)
{
ACS_BD_Errors::FrameLostCompletion lde(__FILE__, __LINE__, __FUNCTION__);
lde.setNextDataFrame(nextFrame_m);
lde.setFrameCount(frameCounter_m);
lde.setRestFrames(message.restDataLength); // should be ??
lde.setFrameLength(message.data.length()); // should be 0
lde.setFlow(topicName_m.c_str());
callback_mp->onError(lde);
increasConseqErrorCount();
}//if
}//if-else
}else
{
if (currentState_m==StopState)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "On %s stop (BD_STOP) arrived in stop state - will be ignored!",
topicName_m.c_str()));
}
else //StartState
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "On %s stop (BD_STOP) arrived in start state: no parameter data (startSend) has arrived!",
topicName_m.c_str()));
}//if-else
}
// in all above warning/error case we call user's cbStop()
BDNT_READER_LISTENER_USER_ERR( callback_mp->cbStop() )
conseqErrorCount_m=0;
break;
}//case ACSBulkData::BD_STOP
default:
conseqErrorCount_m++;
UnknownDataTypeCompletion udt(__FILE__, __LINE__, __FUNCTION__);
udt.setDataType(message.dataType);
udt.setFrameCount(frameCounter_m);
udt.setTotalFrameCount(totalFrames_m);
callback_mp->onError(udt);
}//switch
}//if(si.valid_data)
}
else
{
conseqErrorCount_m++;
DDSReturnErrorCompletion retErr(__FILE__, __LINE__, __FUNCTION__);
retErr.setRetCode(retCode); //would be good if we can give also string value
callback_mp->onError(retErr);
}//if(retCode)
}//while
}//on_data_available
void BulkDataNTReaderListener::on_requested_deadline_missed(DDS::DataReader*, const DDS::RequestedDeadlineMissedStatus& )
{
ACS_DDS_Errors::DDSDeadlineMissedCompletion dmerr(__FILE__, __LINE__, __FUNCTION__);
initalizeLogging(); //force initialization of logging sys TBD changed
callback_mp->onError(dmerr);
}//on_requested_deadline_missed
void BulkDataNTReaderListener::on_requested_incompatible_qos(DDS::DataReader*, const DDS::RequestedIncompatibleQosStatus&)
{
ACS_DDS_Errors::DDSIncompatibleQoSCompletion iqerr(__FILE__, __LINE__, __FUNCTION__);
initalizeLogging(); //force initialization of logging sys TBD changed
callback_mp->onError(iqerr);
}//on_requested_incompatible_qos
void BulkDataNTReaderListener::on_liveliness_changed(DDS::DataReader*, const DDS::LivelinessChangedStatus& lcs)
{
if (lcs.alive_count_change>0)
{
for(int i=0; i<lcs.alive_count_change; i++)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_INFO, "A new sender has connected to flow: %s of the stream: %s. Total alive connection(s): %d",
callback_mp->getFlowName(), callback_mp->getStreamName(),
lcs.alive_count));
BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderConnect() )
}//for
}else
{
for(int i=lcs.alive_count_change; i<0; i++)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_INFO, "A sender has disconnected to flow: %s of the stream: %s. Total alive connection(s): %d",
callback_mp->getFlowName(), callback_mp->getStreamName(),
lcs.alive_count));
BDNT_READER_LISTENER_USER_ERR( callback_mp->onSenderDisconnect() )
}//for
}//if-else
}//on_liveliness_changed
void BulkDataNTReaderListener::on_subscription_matched(DDS::DataReader*, const DDS::SubscriptionMatchedStatus&)
{
ACS_TRACE(__FUNCTION__);
}//on_subscription_matched
void BulkDataNTReaderListener::on_sample_rejected( DDS::DataReader*, const DDS::SampleRejectedStatus& srs)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_WARNING, "Sample Rejected: reason %d, change: %d, total: %d!",
srs.last_reason, srs.total_count_change, srs.total_count));
}//on_sample_rejected
void BulkDataNTReaderListener::on_sample_lost(DDS::DataReader*, const DDS::SampleLostStatus& s)
{
ACS_BD_Errors::SampleLostCompletion sle(__FILE__, __LINE__, __FUNCTION__);
sle.setLostSamples(s.total_count_change);
sle.setNextDataFrame(nextFrame_m);
sle.setFrameCount(frameCounter_m);
sle.setFlow(topicName_m.c_str());
initalizeLogging(); //force initialization of logging sys TBD changed
callback_mp->onError(sle);
}//on_sample_lost
void BulkDataNTReaderListener::increasConseqErrorCount()
{
conseqErrorCount_m++;
if (conseqErrorCount_m>=maxConseqErrorCount_m)
{
ACS_LOG(LM_RUNTIME_CONTEXT, __FUNCTION__,
(LM_ALERT, "Too many consequent errors: %d/%d on %s",
conseqErrorCount_m, maxConseqErrorCount_m, topicName_m.c_str()));
//TBD: disconnect
}
}//increasConseqErroCount
<|endoftext|> |
<commit_before><commit_msg>Update DepthBuffer.cpp<commit_after><|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../IO/FileAccessException.h"
#include "Exceptions.h"
#include "ErrNoException.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Execution;
using Debug::TraceContextBumper;
/*
********************************************************************************
***************************** errno_ErrorException *****************************
********************************************************************************
*/
errno_ErrorException::errno_ErrorException (Execution::errno_t e)
: StringException (SDKString2Wide (LookupMessage (e)))
, fError (e)
{
}
SDKString errno_ErrorException::LookupMessage (Execution::errno_t e)
{
SDKString justErrnoNumberMessage;
{
SDKChar justNumBuf[2048];
justNumBuf[0] = '\0';
#if qPlatform_Windows
(void)::_stprintf_s (justNumBuf, SDKSTR ("errno: %d"), e);
#else
(void)::snprintf (justNumBuf, NEltsOf (justNumBuf), SDKSTR ("errno: %d"), e);
#endif
justErrnoNumberMessage = justNumBuf;
}
SDKChar buf[2048];
buf[0] = '\0';
#if qPlatform_Windows
if (::_tcserror_s (buf, e) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#elif qPlatform_POSIX
/*
* A bit quirky - gcc and POSIX handle this API fairly differently.
* https://linux.die.net/man/3/strerror_r - in one case returns int and 0 means worked, and other case 0 means didnt work
*/
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
// The XSI-compliant strerror_r() function returns 0 on success
if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#else
// The strerror() and the GNU-specific strerror_r() functions return the appropriate error description string
(void)::strerror_r (e, buf, NEltsOf (buf));
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
#endif
#else
AssertNotImplemented ();
#endif
return justErrnoNumberMessage;
}
[[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error)
{
//REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29
switch (error) {
case ENOMEM: {
Execution::Throw (bad_alloc (), "errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc");
}
case ENOENT: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
case EACCES: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
// If I decide to pursue mapping, this maybe a good place to start
// http://aplawrence.com/Unixart/errors.html
// -- LGP 2009-01-02
#if 0
case EPERM: {
// not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception
// the mapping/unification would make sense.
// -- LGP 2009-01-02
DbgTrace ("errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED");
throw Win32Exception (ERROR_ACCESS_DENIED);
}
#endif
}
DbgTrace (L"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s'", error, SDKString2Wide (LookupMessage (error)).c_str ());
throw errno_ErrorException (error);
}
<commit_msg>fixed another bug with Execution/ErrNoException - using GNU verison of strerror_r<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../IO/FileAccessException.h"
#include "Exceptions.h"
#include "ErrNoException.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Execution;
using Debug::TraceContextBumper;
/*
********************************************************************************
***************************** errno_ErrorException *****************************
********************************************************************************
*/
errno_ErrorException::errno_ErrorException (Execution::errno_t e)
: StringException (SDKString2Wide (LookupMessage (e)))
, fError (e)
{
}
SDKString errno_ErrorException::LookupMessage (Execution::errno_t e)
{
SDKString justErrnoNumberMessage;
{
SDKChar justNumBuf[2048];
justNumBuf[0] = '\0';
#if qPlatform_Windows
(void)::_stprintf_s (justNumBuf, SDKSTR ("errno: %d"), e);
#else
(void)::snprintf (justNumBuf, NEltsOf (justNumBuf), SDKSTR ("errno: %d"), e);
#endif
justErrnoNumberMessage = justNumBuf;
}
SDKChar buf[2048];
buf[0] = '\0';
#if qPlatform_Windows
if (::_tcserror_s (buf, e) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#elif qPlatform_POSIX
/*
* A bit quirky - gcc and POSIX handle this API fairly differently.
* https://linux.die.net/man/3/strerror_r - in one case returns int and 0 means worked, and other case 0 means didnt work
*/
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
// The XSI-compliant strerror_r() function returns 0 on success
if (::strerror_r (e, buf, NEltsOf (buf)) == 0) {
return buf + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
}
#else
// the GNU-specific strerror_r() functions return the appropriate error description string
return ::strerror_r (e, buf, NEltsOf (buf)) + SDKString (SDKSTR (" (") + justErrnoNumberMessage + SDKSTR (")"));
#endif
#else
AssertNotImplemented ();
#endif
return justErrnoNumberMessage;
}
[[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error)
{
//REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29
switch (error) {
case ENOMEM: {
Execution::Throw (bad_alloc (), "errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc");
}
case ENOENT: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
case EACCES: {
Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name...
}
// If I decide to pursue mapping, this maybe a good place to start
// http://aplawrence.com/Unixart/errors.html
// -- LGP 2009-01-02
#if 0
case EPERM: {
// not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception
// the mapping/unification would make sense.
// -- LGP 2009-01-02
DbgTrace ("errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED");
throw Win32Exception (ERROR_ACCESS_DENIED);
}
#endif
}
DbgTrace (L"errno_ErrorException::Throw (%d) - throwing errno_ErrorException '%s'", error, SDKString2Wide (LookupMessage (error)).c_str ());
throw errno_ErrorException (error);
}
<|endoftext|> |
<commit_before>#include "stan/math/functions/fma.hpp"
#include <gtest/gtest.h>
TEST(MathFunctions, fma) {
using stan::math::fma;
EXPECT_FLOAT_EQ(5.0, fma(1.0,2.0,3.0));
EXPECT_FLOAT_EQ(10.0, fma(2.0,3.0,4.0));
}
<commit_msg>added NaN test for fma<commit_after>#include <stan/math/functions/fma.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions, fma) {
using stan::math::fma;
EXPECT_FLOAT_EQ(5.0, fma(1.0,2.0,3.0));
EXPECT_FLOAT_EQ(10.0, fma(2.0,3.0,4.0));
}
TEST(MathFunctions, fma_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::fma(1.0, 2.0, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::fma(1.0, nan, 3.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::fma(1.0, nan, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::fma(nan, 2.0, 3.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::fma(nan, 2.0, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::fma(nan, nan, 3.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::fma(nan, nan, nan));
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
// Author: Hadrien Courtecuisse
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/core/objectmodel/BaseContext.h>
#include <sofa/core/behavior/LinearSolver.h>
#include <sofa/component/linearsolver/ShewchukPCGLinearSolver.h>
#include <sofa/component/linearsolver/NewMatMatrix.h>
#include <sofa/component/linearsolver/FullMatrix.h>
#include <sofa/component/linearsolver/SparseMatrix.h>
#include <sofa/simulation/common/MechanicalVisitor.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/helper/AdvancedTimer.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace linearsolver
{
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
using namespace sofa::core::objectmodel;
using sofa::helper::system::thread::CTime;
using sofa::helper::system::thread::ctime_t;
using std::cerr;
using std::endl;
template<class TMatrix, class TVector>
ShewchukPCGLinearSolver<TMatrix,TVector>::ShewchukPCGLinearSolver()
: f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") )
, f_tolerance( initData(&f_tolerance,1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
, f_update_iteration( initData(&f_update_iteration,(unsigned)0,"update_iteration","Number of CG iterations before next refresh of precondtioner") )
, f_update_step( initData(&f_update_step,(unsigned)1,"update_step","Number of steps before the next refresh of precondtioners") )
, f_use_precond( initData(&f_use_precond,true,"use_precond","Use preconditioners") )
, f_preconditioners( initData(&f_preconditioners, "preconditioners", "If not empty: path to the solvers to use as preconditioners") )
, f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") )
{
f_graph.setWidget("graph");
// f_graph.setReadOnly(true);
usePrecond = true;
first = true;
}
template<class TMatrix, class TVector>
void ShewchukPCGLinearSolver<TMatrix,TVector>::init()
{
std::vector<sofa::core::behavior::LinearSolver*> solvers;
BaseContext * c = this->getContext();
const helper::vector<std::string>& precondNames = f_preconditioners.getValue();
if (precondNames.empty() && f_use_precond.getValue())
{
c->get<sofa::core::behavior::LinearSolver>(&solvers,BaseContext::SearchDown);
}
else
{
for (unsigned int i=0; i<precondNames.size(); ++i)
{
sofa::core::behavior::LinearSolver* s = NULL;
c->get(s, precondNames[i]);
if (s) solvers.push_back(s);
else serr << "Solver \"" << precondNames[i] << "\" not found." << sendl;
}
}
for (unsigned int i=0; i<solvers.size(); ++i)
{
if (solvers[i] && solvers[i] != this)
{
this->preconditioners.push_back(solvers[i]);
}
}
sout<<"Found " << this->preconditioners.size() << " preconditioners"<<sendl;
first = true;
}
template<class TMatrix, class TVector>
void ShewchukPCGLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(double mFact, double bFact, double kFact)
{
sofa::helper::AdvancedTimer::valSet("PCG::buildMBK", 1);
sofa::helper::AdvancedTimer::stepBegin("PCG::setSystemMBKMatrix");
Inherit::setSystemMBKMatrix(mFact,bFact,kFact);
sofa::helper::AdvancedTimer::stepEnd("PCG::setSystemMBKMatrix(Precond)");
if (preconditioners.size()==0) return;
if (first) //We initialize all the preconditioners for the first step
{
for (unsigned int i=0; i<this->preconditioners.size(); ++i)
{
preconditioners[i]->setSystemMBKMatrix(mFact,bFact,kFact);
}
first = false;
next_refresh_iteration = 1;
next_refresh_step = 1;
}
else if (f_use_precond.getValue()) // We use only the first precond in the list
{
sofa::helper::AdvancedTimer::valSet("PCG::PrecondBuildMBK", 1);
sofa::helper::AdvancedTimer::stepBegin("PCG::PrecondSetSystemMBKMatrix");
if (f_update_step.getValue()>0)
{
if (next_refresh_step>=f_update_step.getValue())
{
preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);
next_refresh_step=1;
}
else
{
next_refresh_step++;
}
}
else if (f_update_iteration.getValue()>0)
{
if (next_refresh_iteration>=f_update_iteration.getValue())
{
preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);
next_refresh_iteration=1;
}
}
sofa::helper::AdvancedTimer::stepEnd("PCG::PrecondSetSystemMBKMatrix");
}
}
template<>
inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_beta(Vector& p, Vector& r, double beta)
{
this->v_op(p,r,p,beta); // p = p*beta + r
}
template<>
inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_alpha(Vector& x, Vector& p, double alpha)
{
x.peq(p,alpha); // x = x + alpha p
}
template<class TMatrix, class TVector>
void ShewchukPCGLinearSolver<TMatrix,TVector>::solve (Matrix& M, Vector& x, Vector& b)
{
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve");
Vector& r = *this->createVector();
Vector& d = *this->createVector();
Vector& q = *this->createVector();
Vector& s = *this->createVector();
const bool verbose = f_verbose.getValue();
unsigned iter=1;
r = M*x;
cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i];
if (this->preconditioners.size()>0 && usePrecond)
{
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond");
preconditioners[0]->setSystemLHVector(d);
preconditioners[0]->setSystemRHVector(r);
preconditioners[0]->freezeSystemMatrix();
preconditioners[0]->solveSystem();
//Use freeze boolean to specify the preconditioner that's the fist solve of the step (for example if stepMBK is not call)
preconditioners[0]->updateSystemMatrix();
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve");
}
else
{
d = r;
}
double deltaNew = r.dot(d);
double delta0 = deltaNew;
double eps = f_tolerance.getValue() * f_tolerance.getValue() * delta0;
std::map < std::string, sofa::helper::vector<double> >& graph = * f_graph.beginEdit();
sofa::helper::vector<double>& graph_error = graph["Error"];
graph_error.clear();
while ((iter <= f_maxIter.getValue()) && (deltaNew > eps))
{
if (verbose) printf("CG iteration %d: current L2 error vs initial error=%G\n", iter, sqrt(deltaNew/delta0));
graph_error.push_back(deltaNew);
q = M * d;
double dtq = d.dot(q);
double alpha = deltaNew / dtq;
cgstep_alpha(x,d,alpha);//for(int i=0; i<n; i++) x[i] += alpha * d[i];
if (iter % 50 == 0) // periodically compute the exact residual
{
r = M * x;
cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i];
}
else
{
cgstep_alpha(r,q,-alpha);//for (int i=0; i<n; i++) r[i] = r[i] - alpha * q[i];
}
if (this->preconditioners.size()>0 && usePrecond)
{
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond");
preconditioners[0]->setSystemLHVector(s);
preconditioners[0]->setSystemRHVector(r);
preconditioners[0]->solveSystem();
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve");
}
else
{
s = r;
}
double deltaOld = deltaNew;
deltaNew = r.dot(s);
double beta = deltaNew / deltaOld;
cgstep_beta(d,s,beta);//for (int i=0; i<n; i++) d[i] = r[i] + beta * d[i];
iter++;
}
graph_error.push_back(deltaNew);
next_refresh_iteration=iter;
sofa::helper::AdvancedTimer::valSet("PCG iterations", iter);
f_graph.endEdit();
this->deleteVector(&r);
this->deleteVector(&q);
this->deleteVector(&d);
this->deleteVector(&s);
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve");
}
SOFA_DECL_CLASS(ShewchukPCGLinearSolver)
int ShewchukPCGLinearSolverClass = core::RegisterObject("Linear system solver using the conjugate gradient iterative algorithm")
.add< ShewchukPCGLinearSolver<GraphScatteredMatrix,GraphScatteredVector> >(true)
;
} // namespace linearsolver
} // namespace component
} // namespace sofa
<commit_msg>r7803/sofa-dev : Small changes in ShewchukPCGLinearSolver<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
// Author: Hadrien Courtecuisse
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/core/objectmodel/BaseContext.h>
#include <sofa/core/behavior/LinearSolver.h>
#include <sofa/component/linearsolver/ShewchukPCGLinearSolver.h>
#include <sofa/component/linearsolver/NewMatMatrix.h>
#include <sofa/component/linearsolver/FullMatrix.h>
#include <sofa/component/linearsolver/SparseMatrix.h>
#include <sofa/simulation/common/MechanicalVisitor.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/helper/AdvancedTimer.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace linearsolver
{
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
using namespace sofa::core::objectmodel;
using sofa::helper::system::thread::CTime;
using sofa::helper::system::thread::ctime_t;
using std::cerr;
using std::endl;
template<class TMatrix, class TVector>
ShewchukPCGLinearSolver<TMatrix,TVector>::ShewchukPCGLinearSolver()
: f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") )
, f_tolerance( initData(&f_tolerance,1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
, f_update_iteration( initData(&f_update_iteration,(unsigned)0,"update_iteration","Number of CG iterations before next refresh of precondtioner") )
, f_update_step( initData(&f_update_step,(unsigned)1,"update_step","Number of steps before the next refresh of precondtioners") )
, f_use_precond( initData(&f_use_precond,true,"use_precond","Use preconditioners") )
, f_preconditioners( initData(&f_preconditioners, "preconditioners", "If not empty: path to the solvers to use as preconditioners") )
, f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") )
{
f_graph.setWidget("graph");
// f_graph.setReadOnly(true);
usePrecond = true;
first = true;
}
template<class TMatrix, class TVector>
void ShewchukPCGLinearSolver<TMatrix,TVector>::init()
{
std::vector<sofa::core::behavior::LinearSolver*> solvers;
BaseContext * c = this->getContext();
const helper::vector<std::string>& precondNames = f_preconditioners.getValue();
if (precondNames.empty() && f_use_precond.getValue())
{
c->get<sofa::core::behavior::LinearSolver>(&solvers,BaseContext::SearchDown);
}
else
{
for (unsigned int i=0; i<precondNames.size(); ++i)
{
sofa::core::behavior::LinearSolver* s = NULL;
c->get(s, precondNames[i]);
if (s) solvers.push_back(s);
else serr << "Solver \"" << precondNames[i] << "\" not found." << sendl;
}
}
for (unsigned int i=0; i<solvers.size(); ++i)
{
if (solvers[i] && solvers[i] != this)
{
this->preconditioners.push_back(solvers[i]);
}
}
sout<<"Found " << this->preconditioners.size() << " preconditioners"<<sendl;
first = true;
}
template<class TMatrix, class TVector>
void ShewchukPCGLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(double mFact, double bFact, double kFact)
{
sofa::helper::AdvancedTimer::valSet("PCG::buildMBK", 1);
sofa::helper::AdvancedTimer::stepBegin("PCG::setSystemMBKMatrix");
Inherit::setSystemMBKMatrix(mFact,bFact,kFact);
sofa::helper::AdvancedTimer::stepEnd("PCG::setSystemMBKMatrix(Precond)");
if (preconditioners.size()==0) return;
if (first) //We initialize all the preconditioners for the first step
{
for (unsigned int i=0; i<this->preconditioners.size(); ++i)
{
preconditioners[i]->setSystemMBKMatrix(mFact,bFact,kFact);
}
first = false;
next_refresh_step = 1;
}
else if (f_use_precond.getValue()) // We use only the first precond in the list
{
sofa::helper::AdvancedTimer::valSet("PCG::PrecondBuildMBK", 1);
sofa::helper::AdvancedTimer::stepBegin("PCG::PrecondSetSystemMBKMatrix");
if ((f_update_step.getValue()>0) && (f_update_iteration.getValue()>0))
{
if ((next_refresh_step>=f_update_step.getValue()) && (next_refresh_iteration>=f_update_iteration.getValue()))
{
preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);
next_refresh_step=1;
}
else
{
next_refresh_step++;
}
}
else if (f_update_step.getValue()>0)
{
if (next_refresh_step>=f_update_step.getValue())
{
preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);
next_refresh_step=1;
}
else
{
next_refresh_step++;
}
}
else if (f_update_iteration.getValue()>0)
{
if (next_refresh_iteration>=f_update_iteration.getValue())
{
preconditioners[0]->setSystemMBKMatrix(mFact,bFact,kFact);
next_refresh_iteration=1;
}
}
sofa::helper::AdvancedTimer::stepEnd("PCG::PrecondSetSystemMBKMatrix");
}
next_refresh_iteration = 1;
}
template<>
inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_beta(Vector& p, Vector& r, double beta)
{
this->v_op(p,r,p,beta); // p = p*beta + r
}
template<>
inline void ShewchukPCGLinearSolver<component::linearsolver::GraphScatteredMatrix,component::linearsolver::GraphScatteredVector>::cgstep_alpha(Vector& x, Vector& p, double alpha)
{
x.peq(p,alpha); // x = x + alpha p
}
template<class TMatrix, class TVector>
void ShewchukPCGLinearSolver<TMatrix,TVector>::solve (Matrix& M, Vector& x, Vector& b)
{
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve");
Vector& r = *this->createVector();
Vector& d = *this->createVector();
Vector& q = *this->createVector();
Vector& s = *this->createVector();
const bool verbose = f_verbose.getValue();
unsigned iter=1;
r = M*x;
cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i];
if (this->preconditioners.size()>0 && usePrecond)
{
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond");
preconditioners[0]->setSystemLHVector(d);
preconditioners[0]->setSystemRHVector(r);
preconditioners[0]->freezeSystemMatrix();
preconditioners[0]->solveSystem();
//Use freeze boolean to specify the preconditioner that's the fist solve of the step (for example if stepMBK is not call)
preconditioners[0]->updateSystemMatrix();
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve");
}
else
{
d = r;
}
double deltaNew = r.dot(d);
double delta0 = deltaNew;
double eps = f_tolerance.getValue() * f_tolerance.getValue() * delta0;
std::map < std::string, sofa::helper::vector<double> >& graph = * f_graph.beginEdit();
sofa::helper::vector<double>& graph_error = graph["Error"];
graph_error.clear();
while ((iter <= f_maxIter.getValue()) && (deltaNew > eps))
{
if (verbose) printf("CG iteration %d: current L2 error vs initial error=%G\n", iter, sqrt(deltaNew/delta0));
graph_error.push_back(deltaNew);
q = M * d;
double dtq = d.dot(q);
double alpha = deltaNew / dtq;
cgstep_alpha(x,d,alpha);//for(int i=0; i<n; i++) x[i] += alpha * d[i];
if (iter % 50 == 0) // periodically compute the exact residual
{
r = M * x;
cgstep_beta(r,b,-1);//for (int i=0; i<n; i++) r[i] = b[i] - r[i];
}
else
{
cgstep_alpha(r,q,-alpha);//for (int i=0; i<n; i++) r[i] = r[i] - alpha * q[i];
}
if (this->preconditioners.size()>0 && usePrecond)
{
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::apply Precond");
preconditioners[0]->setSystemLHVector(s);
preconditioners[0]->setSystemRHVector(r);
preconditioners[0]->solveSystem();
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::apply Precond");
sofa::helper::AdvancedTimer::stepBegin("PCGLinearSolver::solve");
}
else
{
s = r;
}
double deltaOld = deltaNew;
deltaNew = r.dot(s);
double beta = deltaNew / deltaOld;
cgstep_beta(d,s,beta);//for (int i=0; i<n; i++) d[i] = r[i] + beta * d[i];
iter++;
}
graph_error.push_back(deltaNew);
next_refresh_iteration=iter;
sofa::helper::AdvancedTimer::valSet("PCG iterations", iter);
f_graph.endEdit();
this->deleteVector(&r);
this->deleteVector(&q);
this->deleteVector(&d);
this->deleteVector(&s);
sofa::helper::AdvancedTimer::stepEnd("PCGLinearSolver::solve");
}
SOFA_DECL_CLASS(ShewchukPCGLinearSolver)
int ShewchukPCGLinearSolverClass = core::RegisterObject("Linear system solver using the conjugate gradient iterative algorithm")
.add< ShewchukPCGLinearSolver<GraphScatteredMatrix,GraphScatteredVector> >(true)
;
} // namespace linearsolver
} // namespace component
} // namespace sofa
<|endoftext|> |
<commit_before>#ifndef REFL_INFORMATION_HPP
#define REFL_INFORMATION_HPP
#include "../meta_utils/meta_utils.hpp"
#include "variables/reflect_information_variable.hpp"
#include "functions/reflect_information_method.hpp"
namespace reflect {
/**
* @brief Namespace related to all reflection information(metadata, names, etc)
*/
namespace info {
/**
* @brief SFINAE check if class is generator
*/
template <class T>
struct is_generator {
template <class C, ::std::size_t... Indices> static constexpr ::std::true_type check(decltype (&C::template generate<::boost::hana::tuple<::boost::hana::size_t<Indices>...>>));
template <class> static constexpr ::std::false_type check(...);
static constexpr bool value = ::std::is_same<::std::true_type, decltype(check<T>(nullptr))>::value;
};
template <class T> constexpr bool is_generator_v = is_generator<T>::value;
/**
* @brief SFINAE check if class is reflected
*
*/
template <class T>
struct is_reflected {
/**
* @brief If is_reflected method exist
*
* @return ::std::true_type
*/
template <class C> static constexpr ::std::true_type check(decltype(&C::is_reflected));
/**
* @brief If is_reflected method doesn't exist
*
* @return ::std::false_type
*/
template <class> static constexpr ::std::false_type check(...);
static constexpr bool value = ::std::is_same<::std::true_type, decltype(check<T>(nullptr))>::value; /**< true true if reflected, othervise false */
};
template <class T> constexpr bool is_reflected_v = is_reflected<T>::value; /**< Helper variable template for is_reflected */
namespace detail {
/**
* @brief Concating all names in one tuple
*/
template <class Type, class MetaInfo_type, ::std::size_t... Indices>
constexpr decltype (auto) names_tuple (::std::index_sequence<Indices... >&&) {
return metautils::multiple_concat(names_state(metautils::counter<Indices>{},static_cast<const Type*>(nullptr),static_cast<const MetaInfo_type*>(nullptr))...);
}
/**
* @brief Concating all metadata in one tuple
*/
template <class Type, class MetaInfo_type, ::std::size_t... Indices>
constexpr decltype (auto) metadata_tuple (::std::index_sequence<Indices... >&&) {
return metautils::multiple_concat(metadata_state(metautils::counter<Indices>{},static_cast<const Type*>(nullptr),static_cast<const MetaInfo_type*>(nullptr))...);
}
}
/**
* @brief Class that stores meta-information about T
*
*/
template <class T>
struct MetaClass {
using Type = typename T::Type;
using MetaInfo_type = T;
static constexpr auto class_name {HANA_STR(class_name_detail(static_cast<const typename T::Type*>(nullptr),static_cast<const T*>(nullptr)))}; /**< compile-time string of class name */
static constexpr auto names {detail::names_tuple<Type, MetaInfo_type>(::std::make_index_sequence<decltype(counter(metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value>{})}; /**< tuple of all variable names */
static constexpr auto metadata {detail::metadata_tuple<Type, MetaInfo_type>(::std::make_index_sequence<decltype(counter(metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value>{})}; /**< tuple of all method names */
};
class EmptyGenerator;
/**
* @brief The DefaultIndexGenerator class - generate tuple of indices [0..N-1] where N - tuple size
*/
class DefaultIndexGenerator final {
public:
using reverse = EmptyGenerator;
/**
* @brief Generate tuple of indices
* @return ::boost::hana::tuple<0...N-1>
*/
template<class Tuple>
constexpr static decltype (auto) generate () {
return metautils::gen_inds_tup<decltype(::boost::hana::size(::std::declval<Tuple>()))>();
}
};
/**
* @brief Empty generator
*/
class EmptyGenerator final {
public:
using reverse = DefaultIndexGenerator;
template<class Tuple>
/**
* @brief Generate empty tuple
* @return ::boost::hana::tuple<>
*/
constexpr static ::boost::hana::tuple<> generate () {
return {};
}
};
/**
* @brief Class that stores meta-functions
*/
template <class... Args>
struct MetaInfo;
}
}
#define IN_METAINFO(TYPE) \
using Type = TYPE; \
using MetaInfo_type = TYPE; \
static constexpr auto is_reflected () {return std::true_type();} \
friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \
friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);
#define OUT_METAINFO(TYPE) \
friend struct reflect::info::MetaInfo<TYPE>; \
using MetaInfo_type = ::reflect::info::MetaInfo<TYPE>; \
static constexpr auto is_reflected () {return std::true_type();}
#define METAINFO(TYPE) \
namespace reflect { \
namespace info { \
template <> \
struct MetaInfo<TYPE> { \
using Type = TYPE; \
using MetaInfo_type = ::reflect::info::MetaInfo<Type>; \
friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \
friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);
#define TEMPLATE_METAINFO(TYPE,TEMPLATE_TYPE,TEMPLATE) \
namespace reflect { \
namespace info { \
template <TEMPLATE_TYPE> \
struct MetaInfo<TYPE<TEMPLATE>> { \
using Type = TYPE<TEMPLATE>; \
using MetaInfo_type = ::reflect::info::MetaInfo<Type>; \
friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \
friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);
#define TEMPLATE_METAINFO_SPETIALIZE(TYPE,TEMPLATE) \
namespace reflect { \
namespace info { \
struct MetaInfo<TYPE<TEMPLATE>> { \
using Type = TYPE<TEMPLATE>; \
using MetaInfo_type = ::reflect::info::MetaInfo<Type>; \
friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \
friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);
#define END_METAINFO \
}; \
} }
#define TUPLE_APPEND(STATE, COUNTER, ...) \
friend constexpr auto STATE(::reflect::metautils::counter<decltype(COUNTER(::reflect::metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value>, \
const Type*, const MetaInfo_type*) -> decltype (::boost::hana::make_tuple(__VA_ARGS__)) \
{ return ::boost::hana::make_tuple(__VA_ARGS__); }
#define INCREASE_COUNTER(COUNTER) \
friend constexpr ::reflect::metautils::counter<decltype(COUNTER(::reflect::metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value+1u> \
COUNTER (::reflect::metautils::counter<decltype(COUNTER(::reflect::metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value+1u>, const MetaInfo_type*);
#endif // META_INFORMATION_HPP
<commit_msg>Remove unnecessary macros<commit_after>#ifndef REFL_INFORMATION_HPP
#define REFL_INFORMATION_HPP
#include "../meta_utils/meta_utils.hpp"
#include "variables/reflect_information_variable.hpp"
#include "functions/reflect_information_method.hpp"
namespace reflect {
/**
* @brief Namespace related to all reflection information(metadata, names, etc)
*/
namespace info {
/**
* @brief SFINAE check if class is generator
*/
template <class T>
struct is_generator {
template <class C, ::std::size_t... Indices> static constexpr ::std::true_type check(decltype (&C::template generate<::boost::hana::tuple<::boost::hana::size_t<Indices>...>>));
template <class> static constexpr ::std::false_type check(...);
static constexpr bool value = ::std::is_same<::std::true_type, decltype(check<T>(nullptr))>::value;
};
template <class T> constexpr bool is_generator_v = is_generator<T>::value;
/**
* @brief SFINAE check if class is reflected
*
*/
template <class T>
struct is_reflected {
/**
* @brief If is_reflected method exist
*
* @return ::std::true_type
*/
template <class C> static constexpr ::std::true_type check(decltype(&C::is_reflected));
/**
* @brief If is_reflected method doesn't exist
*
* @return ::std::false_type
*/
template <class> static constexpr ::std::false_type check(...);
static constexpr bool value = ::std::is_same<::std::true_type, decltype(check<T>(nullptr))>::value; /**< true true if reflected, othervise false */
};
template <class T> constexpr bool is_reflected_v = is_reflected<T>::value; /**< Helper variable template for is_reflected */
namespace detail {
/**
* @brief Concating all names in one tuple
*/
template <class Type, class MetaInfo_type, ::std::size_t... Indices>
constexpr decltype (auto) names_tuple (::std::index_sequence<Indices... >&&) {
return metautils::multiple_concat(names_state(metautils::counter<Indices>{},static_cast<const Type*>(nullptr),static_cast<const MetaInfo_type*>(nullptr))...);
}
/**
* @brief Concating all metadata in one tuple
*/
template <class Type, class MetaInfo_type, ::std::size_t... Indices>
constexpr decltype (auto) metadata_tuple (::std::index_sequence<Indices... >&&) {
return metautils::multiple_concat(metadata_state(metautils::counter<Indices>{},static_cast<const Type*>(nullptr),static_cast<const MetaInfo_type*>(nullptr))...);
}
}
/**
* @brief Class that stores meta-information about T
*
*/
template <class T>
struct MetaClass {
using Type = typename T::Type;
using MetaInfo_type = T;
static constexpr auto class_name {HANA_STR(class_name_detail(static_cast<const typename T::Type*>(nullptr),static_cast<const T*>(nullptr)))}; /**< compile-time string of class name */
static constexpr auto names {detail::names_tuple<Type, MetaInfo_type>(::std::make_index_sequence<decltype(counter(metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value>{})}; /**< tuple of all variable names */
static constexpr auto metadata {detail::metadata_tuple<Type, MetaInfo_type>(::std::make_index_sequence<decltype(counter(metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value>{})}; /**< tuple of all method names */
};
class EmptyGenerator;
/**
* @brief The DefaultIndexGenerator class - generate tuple of indices [0..N-1] where N - tuple size
*/
class DefaultIndexGenerator final {
public:
using reverse = EmptyGenerator;
/**
* @brief Generate tuple of indices
* @return ::boost::hana::tuple<0...N-1>
*/
template<class Tuple>
constexpr static decltype (auto) generate () {
return metautils::gen_inds_tup<decltype(::boost::hana::size(::std::declval<Tuple>()))>();
}
};
/**
* @brief Empty generator
*/
class EmptyGenerator final {
public:
using reverse = DefaultIndexGenerator;
template<class Tuple>
/**
* @brief Generate empty tuple
* @return ::boost::hana::tuple<>
*/
constexpr static ::boost::hana::tuple<> generate () {
return {};
}
};
/**
* @brief Class that stores meta-functions
*/
template <class... Args>
struct MetaInfo;
}
}
#define IN_METAINFO(TYPE) \
using Type = TYPE; \
using MetaInfo_type = TYPE; \
static constexpr auto is_reflected () {return std::true_type();} \
friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \
friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);
#define OUT_METAINFO(TYPE) \
friend struct reflect::info::MetaInfo<TYPE>; \
using MetaInfo_type = ::reflect::info::MetaInfo<TYPE>; \
static constexpr auto is_reflected () {return std::true_type();}
#define METAINFO(TYPE) \
namespace reflect { \
namespace info { \
template <> \
struct MetaInfo<TYPE> { \
using Type = TYPE; \
using MetaInfo_type = ::reflect::info::MetaInfo<Type>; \
friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \
friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);
#define TEMPLATE_METAINFO(TYPE,TEMPLATE_TYPE,TEMPLATE) \
namespace reflect { \
namespace info { \
template <TEMPLATE_TYPE> \
struct MetaInfo<TYPE<TEMPLATE>> { \
using Type = TYPE<TEMPLATE>; \
using MetaInfo_type = ::reflect::info::MetaInfo<Type>; \
friend constexpr auto class_name_detail(const Type*, const MetaInfo_type*) -> decltype (#TYPE) { return #TYPE; } \
friend constexpr ::reflect::metautils::counter<0> counter (::reflect::metautils::counter<0>, const MetaInfo_type*);
#define END_METAINFO \
}; \
} }
#define TUPLE_APPEND(STATE, COUNTER, ...) \
friend constexpr auto STATE(::reflect::metautils::counter<decltype(COUNTER(::reflect::metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value>, \
const Type*, const MetaInfo_type*) -> decltype (::boost::hana::make_tuple(__VA_ARGS__)) \
{ return ::boost::hana::make_tuple(__VA_ARGS__); }
#define INCREASE_COUNTER(COUNTER) \
friend constexpr ::reflect::metautils::counter<decltype(COUNTER(::reflect::metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value+1u> \
COUNTER (::reflect::metautils::counter<decltype(COUNTER(::reflect::metautils::counter<>{},static_cast<const MetaInfo_type*>(nullptr)))::value+1u>, const MetaInfo_type*);
#endif // META_INFORMATION_HPP
<|endoftext|> |
<commit_before>// MOOSE includes
#include "FEProblemBase.h"
#include "MultiApp.h"
#include "PiecewiseBase.h"
// MASTODON includes
#include "PiecewiseFunctionTransfer.h"
registerMooseObject("MastodonApp", PiecewiseFunctionTransfer);
InputParameters
PiecewiseFunctionTransfer::validParams()
{
InputParameters params = MultiAppTransfer::validParams();
params.addClassDescription("Transfers from one Piecewise function to another.");
params.addRequiredParam<std::string>("to_function",
"The name of the function being transferred into.");
params.addRequiredParam<std::string>("from_function",
"The name of the function being transferred out of.");
return params;
}
PiecewiseFunctionTransfer::PiecewiseFunctionTransfer(const InputParameters & parameters)
: MultiAppTransfer(parameters)
{
}
void
PiecewiseFunctionTransfer::execute()
{
const std::string & from_name = getParam<std::string>("from_function");
const std::string & to_name = getParam<std::string>("to_function");
if (_direction == TO_MULTIAPP)
{
FEProblemBase & from_problem = _multi_app->problemBase();
PiecewiseBase & from_function =
dynamic_cast<PiecewiseBase &>(from_problem.getFunction(from_name));
for (unsigned int i = 0; i < _multi_app->numGlobalApps(); i++)
if (_multi_app->hasLocalApp(i))
{
FEProblemBase & to_problem = getMultiApp()->appProblemBase(i);
PiecewiseBase & to_function =
dynamic_cast<PiecewiseBase &>(to_problem.getFunction(to_name));
transfer(from_function, to_function);
}
}
else if (_direction == FROM_MULTIAPP)
{
FEProblemBase & to_problem = _multi_app->problemBase();
PiecewiseBase & to_function = dynamic_cast<PiecewiseBase &>(to_problem.getFunction(to_name));
for (unsigned int i = 0; i < _multi_app->numGlobalApps(); i++)
if (_multi_app->hasLocalApp(i))
{
FEProblemBase & from_problem = getMultiApp()->appProblemBase(i);
PiecewiseBase & from_function =
dynamic_cast<PiecewiseBase &>(from_problem.getFunction(from_name));
transfer(from_function, to_function);
}
}
}
void
PiecewiseFunctionTransfer::transfer(PiecewiseBase & from_function, PiecewiseBase & to_function)
{
std::size_t n = from_function.functionSize();
std::vector<Real> x(n), y(n);
for (std::size_t i = 0; i < n; ++i)
{
x[i] = from_function.domain(i);
y[i] = from_function.range(i);
}
to_function.setData(x, y);
}
<commit_msg>Adapt transfers for compatibility with moose sibling multiapp transfers, refs idaholab/moose#19451<commit_after>// MOOSE includes
#include "FEProblemBase.h"
#include "MultiApp.h"
#include "PiecewiseBase.h"
// MASTODON includes
#include "PiecewiseFunctionTransfer.h"
registerMooseObject("MastodonApp", PiecewiseFunctionTransfer);
InputParameters
PiecewiseFunctionTransfer::validParams()
{
InputParameters params = MultiAppTransfer::validParams();
params.addClassDescription("Transfers from one Piecewise function to another.");
params.addRequiredParam<std::string>("to_function",
"The name of the function being transferred into.");
params.addRequiredParam<std::string>("from_function",
"The name of the function being transferred out of.");
return params;
}
PiecewiseFunctionTransfer::PiecewiseFunctionTransfer(const InputParameters & parameters)
: MultiAppTransfer(parameters)
{
}
void
PiecewiseFunctionTransfer::execute()
{
const std::string & from_name = getParam<std::string>("from_function");
const std::string & to_name = getParam<std::string>("to_function");
if (_direction == TO_MULTIAPP)
{
FEProblemBase & from_problem = _to_multi_app->problemBase();
PiecewiseBase & from_function =
dynamic_cast<PiecewiseBase &>(from_problem.getFunction(from_name));
for (unsigned int i = 0; i < _to_multi_app->numGlobalApps(); i++)
if (_to_multi_app->hasLocalApp(i))
{
FEProblemBase & to_problem = getMultiApp()->appProblemBase(i);
PiecewiseBase & to_function =
dynamic_cast<PiecewiseBase &>(to_problem.getFunction(to_name));
transfer(from_function, to_function);
}
}
else if (_direction == FROM_MULTIAPP)
{
FEProblemBase & to_problem = _from_multi_app->problemBase();
PiecewiseBase & to_function = dynamic_cast<PiecewiseBase &>(to_problem.getFunction(to_name));
for (unsigned int i = 0; i < _from_multi_app->numGlobalApps(); i++)
if (_from_multi_app->hasLocalApp(i))
{
FEProblemBase & from_problem = getMultiApp()->appProblemBase(i);
PiecewiseBase & from_function =
dynamic_cast<PiecewiseBase &>(from_problem.getFunction(from_name));
transfer(from_function, to_function);
}
}
}
void
PiecewiseFunctionTransfer::transfer(PiecewiseBase & from_function, PiecewiseBase & to_function)
{
std::size_t n = from_function.functionSize();
std::vector<Real> x(n), y(n);
for (std::size_t i = 0; i < n; ++i)
{
x[i] = from_function.domain(i);
y[i] = from_function.range(i);
}
to_function.setData(x, y);
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS tbe15 (1.15.54); FILE MERGED 2004/12/17 12:29:40 sb 1.15.54.2: #i25819# Minor optimization. 2004/12/16 15:40:22 sb 1.15.54.1: #i25819# Flush instruction cache.<commit_after><|endoftext|> |
<commit_before>#include "controller_node.h"
#include <std_msgs/Bool.h>
#include <std_srvs/Empty.h>
#include <iostream>
Controller::Controller() :
speedX_(1.05f), speedY_(1.05f), speedZ_(1.05f), speedYaw_(1.01f), goal_reached_(true),
search_for_plane_(false), stick_to_plane_(false), sticking_distance_(0.5f), correction_speed_(0.5f) {
std::cout << "Controller node started..." << std::endl;
// get Ros parameters and set variables
nh_.param("speedForward", speedX_, speedX_);
nh_.param("speedRight", speedY_, speedY_);
nh_.param("speedUp", speedZ_, speedZ_);
nh_.param("speedYaw", speedYaw_, speedYaw_);
// set subscriber and publisher
sub_joy_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &Controller::callback, this);
sub_mocap_pose_ = nh_.subscribe<geometry_msgs::PoseWithCovarianceStamped>("vrpn_client/estimated_transform", 10, &Controller::setMocapPose, this);
sub_plane_tf_ = nh_.subscribe<geometry_msgs::TransformStamped>("plane", 10, &Controller::processPlaneMsg, this);
pub_pose_ = nh_.advertise<geometry_msgs::PoseStamped>("command/pose", 1);
pub_stickToSurface_ = nh_.advertise<std_msgs::Bool>("stickToSurface", 10);
std::cout << "speeds: " << speedX_ << " " << speedY_ << " " << speedZ_ << " " << speedYaw_ << std::endl;
// identity rotation matrix as quaternion
tf::Quaternion q;
q.setRPY(0,0,0);
// init mocap_tf
mavToWorld_.setOrigin( tf::Vector3(0,0,0) );
mavToWorld_.setRotation(q);
// init transform
transform_.setOrigin( tf::Vector3(0,0,0) );
transform_.setRotation(q);
// TBD if we should be able to change this via launch file
// init hover transform
hover_goal_tf_.setOrigin( tf::Vector3(0,0,1) );
hover_goal_tf_.setRotation(q);
// init plane_tf
plane_tf_.setOrigin(tf::Vector3(2,0,0));
tf::Quaternion plane_q;
plane_q.setRPY(0,0,-M_PI/4.f);
plane_tf_.setRotation(plane_q);
// init snap_goal_tf
snap_goal_tf_.setOrigin(tf::Vector3(0,0,0));
snap_goal_tf_.setRotation(q);
// set sensor offset tf by getting the relative offset
// tf::TransformListener listener;
// try {
// listener.lookupTransform("euroc_hex/ground_truth", "euroc_hex/vi_sensor/ground_truth", ros::Time(0), sensor_offset_tf_);
// } catch (tf::TransformException ex) {
// ROS_ERROR("%s",ex.what());
// }
// hack
tf::Transform mavToWorld;
mavToWorld.setOrigin(tf::Vector3(0,0,0.117));
mavToWorld.setRotation(tf::Quaternion(0,0,0,1));
tf::Transform sensorToWorld;
sensorToWorld.setOrigin(tf::Vector3(0.133,0,0.0605));
sensorToWorld.setRotation(tf::Quaternion(0,0.17365,0,0.98481));
sensorToMav_ = mavToWorld.inverse() * sensorToWorld;
}
void Controller::setMocapPose(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) {
mavToWorld_.setOrigin( tf::Vector3(msg->pose.pose.position.x, msg->pose.pose.position.y, msg->pose.pose.position.z) );
mavToWorld_.setRotation( tf::Quaternion(msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w) );
if(!goal_reached_) {
tf::Transform diff = mavToWorld_.inverse() * hover_goal_tf_;
if(diff.getOrigin().length() < 0.05f) {
goal_reached_ = true;
}
else {
transform_ = diff;
}
}
// world transform
tf::Transform curr_transform;
/// stick to plane
if(stick_to_plane_) {
testPlanes();
tf::Vector3 diff = snap_goal_tf_.getOrigin() - mavToWorld_.getOrigin();
curr_transform.setOrigin(mavToWorld_.getOrigin() + correction_speed_*diff);
curr_transform.setRotation(snap_goal_tf_.getRotation());
} else {
curr_transform = mavToWorld_ * transform_;
}
// convert tf into pose and publish the pose
tf::Vector3 desired_pos = curr_transform.getOrigin();
tf::Quaternion desired_rot = curr_transform.getRotation();
geometry_msgs::PoseStamped pose;
// set header
pose.header.stamp = ros::Time::now();
pose.header.frame_id = "world";
// set pose
pose.pose.position.x = desired_pos.x();
pose.pose.position.y = desired_pos.y();
pose.pose.position.z = desired_pos.z();
pose.pose.orientation.x = desired_rot.x();
pose.pose.orientation.y = desired_rot.y();
pose.pose.orientation.z = desired_rot.z();
pose.pose.orientation.w = desired_rot.w();
pub_pose_.publish(pose);
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(curr_transform, ros::Time::now(), "world", "controller") );
}
void Controller::callback(const sensor_msgs::Joy::ConstPtr& joy) {
/// translation from controller axis
float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS];
float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS];
float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS];
// yaw from axis
float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS];
// save only the latest relative transform in global variable transform_
transform_.setOrigin( tf::Vector3(jx,jy,jz) );
tf::Quaternion q;
q.setRPY(0,0,jr);
transform_.setRotation(q);
/// buttons
// tell PcMeshBuilder to search for a plane
if(joy->buttons[PS3_BUTTON_REAR_RIGHT_1]) {
search_for_plane_ = true;
std_msgs::Bool sticking;
sticking.data = search_for_plane_;
pub_stickToSurface_.publish(sticking);
}
if(joy->buttons[PS3_BUTTON_REAR_LEFT_1]) {
search_for_plane_ = false;
std_msgs::Bool sticking;
sticking.data = search_for_plane_;
pub_stickToSurface_.publish(sticking);
}
// enable or disable sticking to the plane
if(joy->buttons[PS3_BUTTON_REAR_RIGHT_2]) {
stick_to_plane_ = true;
}
if(joy->buttons[PS3_BUTTON_REAR_LEFT_2]) {
stick_to_plane_ = false;
}
// sticking distance
if(joy->buttons[PS3_BUTTON_CROSS_UP] && sticking_distance_ > 0.05f) {
sticking_distance_ -= 0.005f;
}
if(joy->buttons[PS3_BUTTON_CROSS_DOWN]) {
sticking_distance_ += 0.005f;
}
}
void Controller::takeoffAndHover() {
std_srvs::Empty::Request request;
std_srvs::Empty::Response response;
ros::service::call("euroc2/takeoff", request, response);
tf::Vector3 desired_pos = tf::Vector3( mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), 1.0f);
tf::Quaternion desired_rot = mavToWorld_.getRotation();
hover_goal_tf_.setOrigin(desired_pos);
hover_goal_tf_.setRotation(desired_rot);
}
// TODO add constant offset transform for camera
// TODO improve handedness correction
void Controller::processPlaneMsg(const geometry_msgs::TransformStamped::ConstPtr& msg) {
// realtive plane transform to mav
//planeToCam = plane_tf
plane_tf_.setOrigin( tf::Vector3(msg->transform.translation.x, msg->transform.translation.y, msg->transform.translation.z) );
plane_tf_.setRotation( tf::Quaternion(msg->transform.rotation.x, msg->transform.rotation.y, msg->transform.rotation.z, msg->transform.rotation.w) );
//plane_tf_.setOrigin( tf::Vector3(0,0,0) ); //TODO rm debug
//plane_tf_.setRotation( tf::Quaternion::getIdentity() );
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "plane_Cam_World") );
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "euroc_hex/vi_sensor/ground_truth", "plane_Cam") );
// plane forward is z should be x, hack to fix it for testing
//CamToSensor
// tf::Matrix3x3 tmp_rot = tf::Matrix3x3(0,-1,0,0,0,-1,1,0,0);
tf::Quaternion q1; q1.setRPY(0,M_PI/2.0,0);
tf::Quaternion q2; q2.setRPY(-M_PI/2.0,0,0);
tf::Quaternion correction_rot = q2*q1;
plane_tf_.setOrigin( tf::Matrix3x3(correction_rot)*plane_tf_.getOrigin() );
plane_tf_.setRotation( plane_tf_.getRotation() );
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "euroc_hex/vi_sensor/ground_truth", "plane_Sensor") );
/// testing ///
//// tf::Quaternion q1; q1.setRPY(0,-M_PI/2.0,0);
//// tf::Quaternion q2; q2.setRPY(M_PI/2.0,0,0);
//// tf::Quaternion q3; q3.setRPY(0,0,M_PI);
// tf::Quaternion q1; q1.setRPY(0,M_PI/2.0,0);
// tf::Quaternion q2; q2.setRPY(-M_PI/2.0,0,0);
// tf::Quaternion q3; q3.setRPY(0,0,0);
// correction_rot = q3*q2*q1;
// tf::Transform test0;
// test0.setOrigin(tf::Vector3(-0.5,-0.5,1));
// test0.setRotation(tf::Quaternion::getIdentity());
// br_tf_.sendTransform( tf::StampedTransform(test0, ros::Time::now(), "world", "test0") );
// tf::Transform test1;
// test1.setOrigin( tf::Matrix3x3(correction_rot)*test0.getOrigin() );
// test1.setRotation( test0.getRotation() );
// br_tf_.sendTransform( tf::StampedTransform(test1, ros::Time::now(), "world", "test1") );
/// end of testing section ///
// correct the relative camera offset
// planeToMav = plane_tf CORRECT
plane_tf_ = sensorToMav_.inverse()*plane_tf_;
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "plane_Mav_World") );
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "euroc_hex/ground_truth", "plane_Mav") );
// transform into global coordinates
// planeToWorld = plane_tf_ CORRECT
plane_tf_ = mavToWorld_*plane_tf_;
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "plane_Global") );
}
// TODO remove hacks enhance methods
void Controller::testPlanes() {
//// mav
// predicted mav tf
tf::Transform mav_tf = mavToWorld_ * transform_;
// Eigen conversions
Eigen::Vector3f mav_pos = Eigen::Vector3f( mav_tf.getOrigin().x(),
mav_tf.getOrigin().y(),
mav_tf.getOrigin().z());
//// plane
Eigen::Vector3f plane_pos = Eigen::Vector3f( plane_tf_.getOrigin().x(), plane_tf_.getOrigin().y(), plane_tf_.getOrigin().z() );
tf::Quaternion plane_q = plane_tf_.getRotation();
Eigen::Quaternionf plane_rot = Eigen::Quaternionf(plane_q.w(),plane_q.x(),plane_q.y(),plane_q.z());
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "normal") );
//// calculations
Eigen::Vector3f normal = plane_rot*forward;
normal.normalize();
// normal = -normal;
// determine if mav is in front or behind plane normal, take current pos to avoid switching of sides by wrong predictions in mav_tf
Eigen::Vector3f curr_pos = Eigen::Vector3f(mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), mavToWorld_.getOrigin().z());
int facing = normal.dot(curr_pos-plane_pos) >= 0 ? 1 : -1;
// calculate projected position of the mav onto the plane
Eigen::Vector3f proj_pos = mav_pos + (facing*sticking_distance_ - normal.dot(mav_pos-plane_pos))*normal;
// another hack
// tf::Quaternion correction_rot;
// correction_rot.setRPY(0,0,M_PI);
// set snapping goal tf
snap_goal_tf_.setOrigin( tf::Vector3(proj_pos.x(), proj_pos.y(), proj_pos.z()) );
// snap_goal_tf_.setRotation(correction_rot*plane_tf_.getRotation());
snap_goal_tf_.setRotation(plane_tf_.getRotation());
}
int main(int argc, char** argv) {
ros::init(argc, argv, "te_joy_controller");
Controller rc;
ros::spin();
}
<commit_msg>Fixed a bug with the sensor offset.<commit_after>#include "controller_node.h"
#include <std_msgs/Bool.h>
#include <std_srvs/Empty.h>
#include <iostream>
Controller::Controller() :
speedX_(1.05f), speedY_(1.05f), speedZ_(1.05f), speedYaw_(1.01f), goal_reached_(true),
search_for_plane_(false), stick_to_plane_(false), sticking_distance_(0.5f), correction_speed_(0.5f) {
std::cout << "Controller node started..." << std::endl;
// get Ros parameters and set variables
nh_.param("speedForward", speedX_, speedX_);
nh_.param("speedRight", speedY_, speedY_);
nh_.param("speedUp", speedZ_, speedZ_);
nh_.param("speedYaw", speedYaw_, speedYaw_);
// set subscriber and publisher
sub_joy_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &Controller::callback, this);
sub_mocap_pose_ = nh_.subscribe<geometry_msgs::PoseWithCovarianceStamped>("vrpn_client/estimated_transform", 10, &Controller::setMocapPose, this);
sub_plane_tf_ = nh_.subscribe<geometry_msgs::TransformStamped>("plane", 10, &Controller::processPlaneMsg, this);
pub_pose_ = nh_.advertise<geometry_msgs::PoseStamped>("command/pose", 1);
pub_stickToSurface_ = nh_.advertise<std_msgs::Bool>("stickToSurface", 10);
std::cout << "speeds: " << speedX_ << " " << speedY_ << " " << speedZ_ << " " << speedYaw_ << std::endl;
// identity rotation matrix as quaternion
tf::Quaternion q;
q.setRPY(0,0,0);
// init mocap_tf
mavToWorld_.setOrigin( tf::Vector3(0,0,0) );
mavToWorld_.setRotation(q);
// init transform
transform_.setOrigin( tf::Vector3(0,0,0) );
transform_.setRotation(q);
// TBD if we should be able to change this via launch file
// init hover transform
hover_goal_tf_.setOrigin( tf::Vector3(0,0,1) );
hover_goal_tf_.setRotation(q);
// init plane_tf
plane_tf_.setOrigin(tf::Vector3(2,0,0));
tf::Quaternion plane_q;
plane_q.setRPY(0,0,-M_PI/4.f);
plane_tf_.setRotation(plane_q);
// init snap_goal_tf
snap_goal_tf_.setOrigin(tf::Vector3(0,0,0));
snap_goal_tf_.setRotation(q);
// set sensor offset tf by getting the relative offset
// tf::TransformListener listener;
// try {
// listener.lookupTransform("euroc_hex/ground_truth", "euroc_hex/vi_sensor/ground_truth", ros::Time(0), sensor_offset_tf_);
// } catch (tf::TransformException ex) {
// ROS_ERROR("%s",ex.what());
// }
// hack
tf::Transform mavToWorld;
mavToWorld.setOrigin(tf::Vector3(0,0,0.117));
mavToWorld.setRotation(tf::Quaternion(0,0,0,1));
tf::Transform sensorToWorld;
sensorToWorld.setOrigin(tf::Vector3(0.133,0,0.0605));
sensorToWorld.setRotation(tf::Quaternion(0,0.17365,0,0.98481));
sensorToMav_ = mavToWorld.inverse() * sensorToWorld;
}
void Controller::setMocapPose(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) {
mavToWorld_.setOrigin( tf::Vector3(msg->pose.pose.position.x, msg->pose.pose.position.y, msg->pose.pose.position.z) );
mavToWorld_.setRotation( tf::Quaternion(msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w) );
if(!goal_reached_) {
tf::Transform diff = mavToWorld_.inverse() * hover_goal_tf_;
if(diff.getOrigin().length() < 0.05f) {
goal_reached_ = true;
}
else {
transform_ = diff;
}
}
// world transform
tf::Transform curr_transform;
/// stick to plane
if(stick_to_plane_) {
testPlanes();
tf::Vector3 diff = snap_goal_tf_.getOrigin() - mavToWorld_.getOrigin();
curr_transform.setOrigin(mavToWorld_.getOrigin() + correction_speed_*diff);
curr_transform.setRotation(snap_goal_tf_.getRotation());
} else {
curr_transform = mavToWorld_ * transform_;
}
// convert tf into pose and publish the pose
tf::Vector3 desired_pos = curr_transform.getOrigin();
tf::Quaternion desired_rot = curr_transform.getRotation();
geometry_msgs::PoseStamped pose;
// set header
pose.header.stamp = ros::Time::now();
pose.header.frame_id = "world";
// set pose
pose.pose.position.x = desired_pos.x();
pose.pose.position.y = desired_pos.y();
pose.pose.position.z = desired_pos.z();
pose.pose.orientation.x = desired_rot.x();
pose.pose.orientation.y = desired_rot.y();
pose.pose.orientation.z = desired_rot.z();
pose.pose.orientation.w = desired_rot.w();
pub_pose_.publish(pose);
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(curr_transform, ros::Time::now(), "world", "controller") );
}
void Controller::callback(const sensor_msgs::Joy::ConstPtr& joy) {
/// translation from controller axis
float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS];
float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS];
float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS];
// yaw from axis
float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS];
// save only the latest relative transform in global variable transform_
transform_.setOrigin( tf::Vector3(jx,jy,jz) );
tf::Quaternion q;
q.setRPY(0,0,jr);
transform_.setRotation(q);
/// buttons
// tell PcMeshBuilder to search for a plane
if(joy->buttons[PS3_BUTTON_REAR_RIGHT_1]) {
search_for_plane_ = true;
std_msgs::Bool sticking;
sticking.data = search_for_plane_;
pub_stickToSurface_.publish(sticking);
}
if(joy->buttons[PS3_BUTTON_REAR_LEFT_1]) {
search_for_plane_ = false;
std_msgs::Bool sticking;
sticking.data = search_for_plane_;
pub_stickToSurface_.publish(sticking);
}
// enable or disable sticking to the plane
if(joy->buttons[PS3_BUTTON_REAR_RIGHT_2]) {
stick_to_plane_ = true;
}
if(joy->buttons[PS3_BUTTON_REAR_LEFT_2]) {
stick_to_plane_ = false;
}
// sticking distance
if(joy->buttons[PS3_BUTTON_CROSS_UP] && sticking_distance_ > 0.05f) {
sticking_distance_ -= 0.005f;
}
if(joy->buttons[PS3_BUTTON_CROSS_DOWN]) {
sticking_distance_ += 0.005f;
}
}
void Controller::takeoffAndHover() {
std_srvs::Empty::Request request;
std_srvs::Empty::Response response;
ros::service::call("euroc2/takeoff", request, response);
tf::Vector3 desired_pos = tf::Vector3( mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), 1.0f);
tf::Quaternion desired_rot = mavToWorld_.getRotation();
hover_goal_tf_.setOrigin(desired_pos);
hover_goal_tf_.setRotation(desired_rot);
}
// TODO add constant offset transform for camera
// TODO improve handedness correction
void Controller::processPlaneMsg(const geometry_msgs::TransformStamped::ConstPtr& msg) {
// realtive plane transform to mav
//planeToCam = plane_tf
plane_tf_.setOrigin( tf::Vector3(msg->transform.translation.x, msg->transform.translation.y, msg->transform.translation.z) );
plane_tf_.setRotation( tf::Quaternion(msg->transform.rotation.x, msg->transform.rotation.y, msg->transform.rotation.z, msg->transform.rotation.w) );
//plane_tf_.setOrigin( tf::Vector3(0,0,0) ); //TODO rm debug
//plane_tf_.setRotation( tf::Quaternion::getIdentity() );
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "plane_Cam_World") );
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "euroc_hex/vi_sensor/ground_truth", "plane_Cam") );
// plane forward is z should be x, hack to fix it for testing
//CamToSensor
// tf::Matrix3x3 tmp_rot = tf::Matrix3x3(0,-1,0,0,0,-1,1,0,0);
tf::Quaternion q1; q1.setRPY(0,M_PI/2.0,0);
tf::Quaternion q2; q2.setRPY(-M_PI/2.0,0,0);
tf::Quaternion correction_rot = q2*q1;
plane_tf_.setOrigin( tf::Matrix3x3(correction_rot)*plane_tf_.getOrigin() );
plane_tf_.setRotation( plane_tf_.getRotation() );
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "euroc_hex/vi_sensor/ground_truth", "plane_Sensor") );
/// testing ///
//// tf::Quaternion q1; q1.setRPY(0,-M_PI/2.0,0);
//// tf::Quaternion q2; q2.setRPY(M_PI/2.0,0,0);
//// tf::Quaternion q3; q3.setRPY(0,0,M_PI);
// tf::Quaternion q1; q1.setRPY(0,M_PI/2.0,0);
// tf::Quaternion q2; q2.setRPY(-M_PI/2.0,0,0);
// tf::Quaternion q3; q3.setRPY(0,0,0);
// correction_rot = q3*q2*q1;
// tf::Transform test0;
// test0.setOrigin(tf::Vector3(-0.5,-0.5,1));
// test0.setRotation(tf::Quaternion::getIdentity());
// br_tf_.sendTransform( tf::StampedTransform(test0, ros::Time::now(), "world", "test0") );
// tf::Transform test1;
// test1.setOrigin( tf::Matrix3x3(correction_rot)*test0.getOrigin() );
// test1.setRotation( test0.getRotation() );
// br_tf_.sendTransform( tf::StampedTransform(test1, ros::Time::now(), "world", "test1") );
/// end of testing section ///
// correct the relative camera offset
// planeToMav = plane_tf CORRECT
plane_tf_ = sensorToMav_*plane_tf_;
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "plane_Mav_World") );
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "euroc_hex/ground_truth", "plane_Mav") );
// transform into global coordinates
// planeToWorld = plane_tf_ CORRECT
plane_tf_ = mavToWorld_*plane_tf_;
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "plane_Global") );
}
// TODO remove hacks enhance methods
void Controller::testPlanes() {
//// mav
// predicted mav tf
tf::Transform mav_tf = mavToWorld_ * transform_;
// Eigen conversions
Eigen::Vector3f mav_pos = Eigen::Vector3f( mav_tf.getOrigin().x(),
mav_tf.getOrigin().y(),
mav_tf.getOrigin().z());
//// plane
Eigen::Vector3f plane_pos = Eigen::Vector3f( plane_tf_.getOrigin().x(), plane_tf_.getOrigin().y(), plane_tf_.getOrigin().z() );
tf::Quaternion plane_q = plane_tf_.getRotation();
Eigen::Quaternionf plane_rot = Eigen::Quaternionf(plane_q.w(),plane_q.x(),plane_q.y(),plane_q.z());
// rviz debug
br_tf_.sendTransform( tf::StampedTransform(plane_tf_, ros::Time::now(), "world", "normal") );
//// calculations
Eigen::Vector3f normal = plane_rot*forward;
normal.normalize();
// normal = -normal;
// determine if mav is in front or behind plane normal, take current pos to avoid switching of sides by wrong predictions in mav_tf
Eigen::Vector3f curr_pos = Eigen::Vector3f(mavToWorld_.getOrigin().x(), mavToWorld_.getOrigin().y(), mavToWorld_.getOrigin().z());
int facing = normal.dot(curr_pos-plane_pos) >= 0 ? 1 : -1;
// calculate projected position of the mav onto the plane
Eigen::Vector3f proj_pos = mav_pos + (facing*sticking_distance_ - normal.dot(mav_pos-plane_pos))*normal;
// another hack
// tf::Quaternion correction_rot;
// correction_rot.setRPY(0,0,M_PI);
// set snapping goal tf
snap_goal_tf_.setOrigin( tf::Vector3(proj_pos.x(), proj_pos.y(), proj_pos.z()) );
// snap_goal_tf_.setRotation(correction_rot*plane_tf_.getRotation());
snap_goal_tf_.setRotation(plane_tf_.getRotation());
}
int main(int argc, char** argv) {
ros::init(argc, argv, "te_joy_controller");
Controller rc;
ros::spin();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2009 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// OptionsPasswordHistory.cpp : implementation file
//
#include "stdafx.h"
#include "passwordsafe.h"
#include "corelib/PwsPlatform.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#else
#include "resource.h"
#include "resource3.h" // String resources
#endif
#include "OptionsPasswordHistory.h"
#include "DboxMain.h" // needed for DboxMain::UpdatePasswordHistory
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COptionsPasswordHistory property page
IMPLEMENT_DYNCREATE(COptionsPasswordHistory, CPWPropertyPage)
COptionsPasswordHistory::COptionsPasswordHistory()
: CPWPropertyPage(COptionsPasswordHistory::IDD)
{
//{{AFX_DATA_INIT(COptionsPasswordHistory)
//}}AFX_DATA_INIT
m_ToolTipCtrl = NULL;
m_pwhaction = 0;
}
COptionsPasswordHistory::~COptionsPasswordHistory()
{
delete m_ToolTipCtrl;
}
void COptionsPasswordHistory::DoDataExchange(CDataExchange* pDX)
{
CPWPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(COptionsPasswordHistory)
DDX_Check(pDX, IDC_SAVEPWHISTORY, m_savepwhistory);
DDX_Text(pDX, IDC_DEFPWHNUM, m_pwhistorynumdefault);
//}}AFX_DATA_MAP
DDX_Radio(pDX, IDC_PWHISTORYNOACTION, m_pwhaction);
}
BEGIN_MESSAGE_MAP(COptionsPasswordHistory, CPWPropertyPage)
//{{AFX_MSG_MAP(COptionsPasswordHistory)
ON_BN_CLICKED(IDC_SAVEPWHISTORY, OnSavePWHistory)
ON_BN_CLICKED(IDC_APPLYPWHCHANGESNOW, OnApplyPWHChanges)
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_PWHISTORYNOACTION, OnPWHistoryNoAction)
ON_BN_CLICKED(IDC_RESETPWHISTORYOFF, OnPWHistoryDoAction)
ON_BN_CLICKED(IDC_RESETPWHISTORYON, OnPWHistoryDoAction)
ON_BN_CLICKED(IDC_SETMAXPWHISTORY, OnPWHistoryDoAction)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COptionsPasswordHistory message handlers
BOOL COptionsPasswordHistory::OnInitDialog()
{
BOOL bResult = CPWPropertyPage::OnInitDialog();
CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN);
pspin->SetBuddy(GetDlgItem(IDC_DEFPWHNUM));
pspin->SetRange(1, 255);
pspin->SetBase(10);
pspin->SetPos(m_pwhistorynumdefault);
// Tooltips on Property Pages
EnableToolTips();
m_ToolTipCtrl = new CToolTipCtrl;
if (!m_ToolTipCtrl->Create(this, TTS_ALWAYSTIP | TTS_BALLOON | TTS_NOPREFIX)) {
TRACE("Unable To create Property Page ToolTip\n");
return bResult;
}
// Activate the tooltip control.
m_ToolTipCtrl->Activate(TRUE);
m_ToolTipCtrl->SetMaxTipWidth(300);
// Quadruple the time to allow reading by user - there is a lot there!
int iTime = m_ToolTipCtrl->GetDelayTime(TTDT_AUTOPOP);
m_ToolTipCtrl->SetDelayTime(TTDT_AUTOPOP, 4 * iTime);
// Set the tooltip
// Note naming convention: string IDS_xxx corresponds to control IDC_xxx
CString cs_ToolTip;
cs_ToolTip.LoadString(IDS_RESETPWHISTORYOFF);
m_ToolTipCtrl->AddTool(GetDlgItem(IDC_RESETPWHISTORYOFF), cs_ToolTip);
cs_ToolTip.LoadString(IDS_RESETPWHISTORYON);
m_ToolTipCtrl->AddTool(GetDlgItem(IDC_RESETPWHISTORYON), cs_ToolTip);
cs_ToolTip.LoadString(IDS_SETMAXPWHISTORY);
m_ToolTipCtrl->AddTool(GetDlgItem(IDC_SETMAXPWHISTORY), cs_ToolTip);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL COptionsPasswordHistory::OnKillActive()
{
CPWPropertyPage::OnKillActive();
// Check that options, as set, are valid.
if (m_savepwhistory && ((m_pwhistorynumdefault < 1) || (m_pwhistorynumdefault > 255))) {
AfxMessageBox(IDS_DEFAULTNUMPWH);
((CEdit*)GetDlgItem(IDC_DEFPWHNUM))->SetFocus();
return FALSE;
}
//End check
return TRUE;
}
void COptionsPasswordHistory::OnSavePWHistory()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_SAVEPWHISTORY))->GetCheck() == 1) ? TRUE : FALSE;
GetDlgItem(IDC_PWHSPIN)->EnableWindow(enable);
GetDlgItem(IDC_DEFPWHNUM)->EnableWindow(enable);
}
void COptionsPasswordHistory::OnApplyPWHChanges()
{
ASSERT(m_pDboxMain != NULL);
UpdateData(TRUE);
m_pDboxMain->UpdatePasswordHistory(m_pwhaction, m_pwhistorynumdefault);
m_pwhaction = 0;
GetDlgItem(IDC_APPLYPWHCHANGESNOW)->EnableWindow(FALSE);
UpdateData(FALSE);
}
// Override PreTranslateMessage() so RelayEvent() can be
// called to pass a mouse message to CPWSOptions's
// tooltip control for processing.
BOOL COptionsPasswordHistory::PreTranslateMessage(MSG* pMsg)
{
if (m_ToolTipCtrl != NULL)
m_ToolTipCtrl->RelayEvent(pMsg);
return CPWPropertyPage::PreTranslateMessage(pMsg);
}
void COptionsPasswordHistory::OnPWHistoryNoAction()
{
GetDlgItem(IDC_APPLYPWHCHANGESNOW)->EnableWindow(FALSE);
}
void COptionsPasswordHistory::OnPWHistoryDoAction()
{
GetDlgItem(IDC_APPLYPWHCHANGESNOW)->EnableWindow(TRUE);
}
<commit_msg>Fix initial status of number of saved passwords edit control<commit_after>/*
* Copyright (c) 2003-2009 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// OptionsPasswordHistory.cpp : implementation file
//
#include "stdafx.h"
#include "passwordsafe.h"
#include "corelib/PwsPlatform.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#else
#include "resource.h"
#include "resource3.h" // String resources
#endif
#include "OptionsPasswordHistory.h"
#include "DboxMain.h" // needed for DboxMain::UpdatePasswordHistory
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COptionsPasswordHistory property page
IMPLEMENT_DYNCREATE(COptionsPasswordHistory, CPWPropertyPage)
COptionsPasswordHistory::COptionsPasswordHistory()
: CPWPropertyPage(COptionsPasswordHistory::IDD)
{
//{{AFX_DATA_INIT(COptionsPasswordHistory)
//}}AFX_DATA_INIT
m_ToolTipCtrl = NULL;
m_pwhaction = 0;
}
COptionsPasswordHistory::~COptionsPasswordHistory()
{
delete m_ToolTipCtrl;
}
void COptionsPasswordHistory::DoDataExchange(CDataExchange* pDX)
{
CPWPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(COptionsPasswordHistory)
DDX_Check(pDX, IDC_SAVEPWHISTORY, m_savepwhistory);
DDX_Text(pDX, IDC_DEFPWHNUM, m_pwhistorynumdefault);
//}}AFX_DATA_MAP
DDX_Radio(pDX, IDC_PWHISTORYNOACTION, m_pwhaction);
}
BEGIN_MESSAGE_MAP(COptionsPasswordHistory, CPWPropertyPage)
//{{AFX_MSG_MAP(COptionsPasswordHistory)
ON_BN_CLICKED(IDC_SAVEPWHISTORY, OnSavePWHistory)
ON_BN_CLICKED(IDC_APPLYPWHCHANGESNOW, OnApplyPWHChanges)
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_PWHISTORYNOACTION, OnPWHistoryNoAction)
ON_BN_CLICKED(IDC_RESETPWHISTORYOFF, OnPWHistoryDoAction)
ON_BN_CLICKED(IDC_RESETPWHISTORYON, OnPWHistoryDoAction)
ON_BN_CLICKED(IDC_SETMAXPWHISTORY, OnPWHistoryDoAction)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COptionsPasswordHistory message handlers
BOOL COptionsPasswordHistory::OnInitDialog()
{
BOOL bResult = CPWPropertyPage::OnInitDialog();
CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN);
pspin->SetBuddy(GetDlgItem(IDC_DEFPWHNUM));
pspin->SetRange(1, 255);
pspin->SetBase(10);
pspin->SetPos(m_pwhistorynumdefault);
GetDlgItem(IDC_PWHSPIN)->EnableWindow(m_savepwhistory);
GetDlgItem(IDC_DEFPWHNUM)->EnableWindow(m_savepwhistory);
// Tooltips on Property Pages
EnableToolTips();
m_ToolTipCtrl = new CToolTipCtrl;
if (!m_ToolTipCtrl->Create(this, TTS_ALWAYSTIP | TTS_BALLOON | TTS_NOPREFIX)) {
TRACE("Unable To create Property Page ToolTip\n");
return bResult;
}
// Activate the tooltip control.
m_ToolTipCtrl->Activate(TRUE);
m_ToolTipCtrl->SetMaxTipWidth(300);
// Quadruple the time to allow reading by user - there is a lot there!
int iTime = m_ToolTipCtrl->GetDelayTime(TTDT_AUTOPOP);
m_ToolTipCtrl->SetDelayTime(TTDT_AUTOPOP, 4 * iTime);
// Set the tooltip
// Note naming convention: string IDS_xxx corresponds to control IDC_xxx
CString cs_ToolTip;
cs_ToolTip.LoadString(IDS_RESETPWHISTORYOFF);
m_ToolTipCtrl->AddTool(GetDlgItem(IDC_RESETPWHISTORYOFF), cs_ToolTip);
cs_ToolTip.LoadString(IDS_RESETPWHISTORYON);
m_ToolTipCtrl->AddTool(GetDlgItem(IDC_RESETPWHISTORYON), cs_ToolTip);
cs_ToolTip.LoadString(IDS_SETMAXPWHISTORY);
m_ToolTipCtrl->AddTool(GetDlgItem(IDC_SETMAXPWHISTORY), cs_ToolTip);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL COptionsPasswordHistory::OnKillActive()
{
CPWPropertyPage::OnKillActive();
// Check that options, as set, are valid.
if (m_savepwhistory && ((m_pwhistorynumdefault < 1) || (m_pwhistorynumdefault > 255))) {
AfxMessageBox(IDS_DEFAULTNUMPWH);
((CEdit*)GetDlgItem(IDC_DEFPWHNUM))->SetFocus();
return FALSE;
}
//End check
return TRUE;
}
void COptionsPasswordHistory::OnSavePWHistory()
{
BOOL enable = (((CButton*)GetDlgItem(IDC_SAVEPWHISTORY))->GetCheck() == 1) ? TRUE : FALSE;
GetDlgItem(IDC_PWHSPIN)->EnableWindow(enable);
GetDlgItem(IDC_DEFPWHNUM)->EnableWindow(enable);
}
void COptionsPasswordHistory::OnApplyPWHChanges()
{
ASSERT(m_pDboxMain != NULL);
UpdateData(TRUE);
m_pDboxMain->UpdatePasswordHistory(m_pwhaction, m_pwhistorynumdefault);
m_pwhaction = 0;
GetDlgItem(IDC_APPLYPWHCHANGESNOW)->EnableWindow(FALSE);
UpdateData(FALSE);
}
// Override PreTranslateMessage() so RelayEvent() can be
// called to pass a mouse message to CPWSOptions's
// tooltip control for processing.
BOOL COptionsPasswordHistory::PreTranslateMessage(MSG* pMsg)
{
if (m_ToolTipCtrl != NULL)
m_ToolTipCtrl->RelayEvent(pMsg);
return CPWPropertyPage::PreTranslateMessage(pMsg);
}
void COptionsPasswordHistory::OnPWHistoryNoAction()
{
GetDlgItem(IDC_APPLYPWHCHANGESNOW)->EnableWindow(FALSE);
}
void COptionsPasswordHistory::OnPWHistoryDoAction()
{
GetDlgItem(IDC_APPLYPWHCHANGESNOW)->EnableWindow(TRUE);
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// ///
/// AliFemtoModelCorrFctnDirectYlm - the class for correlation function which ///
/// uses the model framework and weight generation and saves the generated ///
/// emission source ///
/// Authors: Adam Kisiel, [email protected] ///
/// ///
////////////////////////////////////////////////////////////////////////////////
#ifdef __ROOT__
ClassImp(AliFemtoModelCorrFctnDirectYlm, 1)
#endif
#include "AliFemtoModelGausLCMSFreezeOutGenerator.h"
#include "AliFemtoModelHiddenInfo.h"
#include "AliFemtoModelCorrFctnDirectYlm.h"
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm():
AliFemtoModelCorrFctn(),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(0)
{
// default constructor
fCYlmTrue = new AliFemtoCorrFctnDirectYlm();
fCYlmFake = new AliFemtoCorrFctnDirectYlm();
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const char *title, Int_t aMaxL, Int_t aNbins, Double_t aQinvLo, Double_t aQinvHi, int aUseLCMS=0):
AliFemtoModelCorrFctn(title, aNbins, aQinvLo, aQinvHi),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(aUseLCMS)
{
// basic constructor
char fname[1000];
snprintf(fname, 1000, "%s%s", title, "True");
fCYlmTrue = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
snprintf(fname, 1000, "%s%s", title, "Fake");
fCYlmFake = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn):
AliFemtoModelCorrFctn(aCorrFctn),
fCYlmTrue(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmTrue))),
fCYlmFake(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmFake))),
fUseLCMS(0)
{
// copy constructor
fUseLCMS = aCorrFctn.fUseLCMS;
// fCYlmTrue = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmTrue->Clone());
// fCYlmFake = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmFake->Clone());
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::~AliFemtoModelCorrFctnDirectYlm()
{
// destructor
if (fCYlmTrue) delete fCYlmTrue;
if (fCYlmFake) delete fCYlmFake;
if (fNumeratorTrue) delete fNumeratorTrue;
if (fNumeratorFake) delete fNumeratorFake;
if (fDenominator) delete fDenominator;
}
//_______________________
AliFemtoModelCorrFctnDirectYlm& AliFemtoModelCorrFctnDirectYlm::operator=(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
fUseLCMS = aCorrFctn.fUseLCMS;
if (aCorrFctn.fCYlmTrue)
fCYlmTrue = new AliFemtoCorrFctnDirectYlm(*aCorrFctn.fCYlmTrue);
else fCYlmTrue = 0;
if (aCorrFctn.fCYlmFake)
fCYlmFake = new AliFemtoCorrFctnDirectYlm(*aCorrFctn.fCYlmFake);
else fCYlmFake = 0;
if (aCorrFctn.fNumeratorTrue)
fNumeratorTrue = new TH1D(*aCorrFctn.fNumeratorTrue);
else
fNumeratorTrue = 0;
if (aCorrFctn.fNumeratorFake)
fNumeratorFake = new TH1D(*aCorrFctn.fNumeratorFake);
else
fNumeratorFake = 0;
if (aCorrFctn.fDenominator)
fDenominator = new TH1D(*aCorrFctn.fDenominator);
else
fDenominator = 0;
return *this;
}
//_______________________
AliFemtoString AliFemtoModelCorrFctnDirectYlm::Report()
{
// construct report
AliFemtoString tStr = "AliFemtoModelCorrFctnDirectYlm report";
return tStr;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddRealPair(AliFemtoPair* aPair)
{
// add real (effect) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS)
fCYlmTrue->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
else
fCYlmTrue->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddMixedPair(AliFemtoPair* aPair)
{
// add mixed (background) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS) {
fCYlmTrue->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
fCYlmFake->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
fCYlmFake->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
}
else {
fCYlmTrue->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
fCYlmFake->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
fCYlmFake->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
}
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Write()
{
// write out all the histograms
fCYlmTrue->Write();
fCYlmFake->Write();
}
//_______________________
TList* AliFemtoModelCorrFctnDirectYlm::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = AliFemtoModelCorrFctn::GetOutputList();
tOutputList->Clear();
TList *tListCfTrue = fCYlmTrue->GetOutputList();
TIter nextListCfTrue(tListCfTrue);
while (TObject *obj = nextListCfTrue()) {
tOutputList->Add(obj);
}
TList *tListCfFake = fCYlmFake->GetOutputList();
TIter nextListCfFake(tListCfFake);
while (TObject *obj = nextListCfFake()) {
tOutputList->Add(obj);
}
// tOutputList->Add(fCYlmTrue->GetOutputList());
// tOutputList->Add(fCYlmFake->GetOutputList());
return tOutputList;
}
//_______________________
AliFemtoModelCorrFctn* AliFemtoModelCorrFctnDirectYlm::Clone()
{
// Clone the correlation function
AliFemtoModelCorrFctnDirectYlm *tCopy = new AliFemtoModelCorrFctnDirectYlm(*this);
return tCopy;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Finish()
{
fCYlmTrue->Finish();
fCYlmFake->Finish();
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::SetUseLCMS(int aUseLCMS)
{
fUseLCMS = aUseLCMS;
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
int AliFemtoModelCorrFctnDirectYlm::GetUseLCMS()
{
return fUseLCMS;
}
<commit_msg>Fix Coverity<commit_after>////////////////////////////////////////////////////////////////////////////////
/// ///
/// AliFemtoModelCorrFctnDirectYlm - the class for correlation function which ///
/// uses the model framework and weight generation and saves the generated ///
/// emission source ///
/// Authors: Adam Kisiel, [email protected] ///
/// ///
////////////////////////////////////////////////////////////////////////////////
#ifdef __ROOT__
ClassImp(AliFemtoModelCorrFctnDirectYlm, 1)
#endif
#include "AliFemtoModelGausLCMSFreezeOutGenerator.h"
#include "AliFemtoModelHiddenInfo.h"
#include "AliFemtoModelCorrFctnDirectYlm.h"
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm():
AliFemtoModelCorrFctn(),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(0)
{
// default constructor
fCYlmTrue = new AliFemtoCorrFctnDirectYlm();
fCYlmFake = new AliFemtoCorrFctnDirectYlm();
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const char *title, Int_t aMaxL, Int_t aNbins, Double_t aQinvLo, Double_t aQinvHi, int aUseLCMS=0):
AliFemtoModelCorrFctn(title, aNbins, aQinvLo, aQinvHi),
fCYlmTrue(0),
fCYlmFake(0),
fUseLCMS(aUseLCMS)
{
// basic constructor
char fname[1000];
snprintf(fname, 1000, "%s%s", title, "True");
fCYlmTrue = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
snprintf(fname, 1000, "%s%s", title, "Fake");
fCYlmFake = new AliFemtoCorrFctnDirectYlm(fname, aMaxL, aNbins, aQinvLo, aQinvHi, fUseLCMS);
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::AliFemtoModelCorrFctnDirectYlm(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn):
AliFemtoModelCorrFctn(aCorrFctn),
fCYlmTrue(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmTrue))),
fCYlmFake(new AliFemtoCorrFctnDirectYlm(*(aCorrFctn.fCYlmFake))),
fUseLCMS(0)
{
// copy constructor
fUseLCMS = aCorrFctn.fUseLCMS;
// fCYlmTrue = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmTrue->Clone());
// fCYlmFake = dynamic_cast<AliFemtoCorrFctnDirectYlm*>(aCorrFctn.fCYlmFake->Clone());
}
//_______________________
AliFemtoModelCorrFctnDirectYlm::~AliFemtoModelCorrFctnDirectYlm()
{
// destructor
if (fCYlmTrue) delete fCYlmTrue;
if (fCYlmFake) delete fCYlmFake;
if (fNumeratorTrue) delete fNumeratorTrue;
if (fNumeratorFake) delete fNumeratorFake;
if (fDenominator) delete fDenominator;
}
//_______________________
AliFemtoModelCorrFctnDirectYlm& AliFemtoModelCorrFctnDirectYlm::operator=(const AliFemtoModelCorrFctnDirectYlm& aCorrFctn)
{
// assignment operator
if (this != &aCorrFctn) {
fUseLCMS = aCorrFctn.fUseLCMS;
if (fCYlmTrue) delete fCYlmTrue;
if (aCorrFctn.fCYlmTrue)
fCYlmTrue = new AliFemtoCorrFctnDirectYlm(*aCorrFctn.fCYlmTrue);
else fCYlmTrue = 0;
if (fCYlmFake) delete fCYlmFake;
if (aCorrFctn.fCYlmFake)
fCYlmFake = new AliFemtoCorrFctnDirectYlm(*aCorrFctn.fCYlmFake);
else fCYlmFake = 0;
if (fNumeratorTrue) delete fNumeratorTrue;
if (aCorrFctn.fNumeratorTrue)
fNumeratorTrue = new TH1D(*aCorrFctn.fNumeratorTrue);
else
fNumeratorTrue = 0;
if (fNumeratorFake) delete fNumeratorFake;
if (aCorrFctn.fNumeratorFake)
fNumeratorFake = new TH1D(*aCorrFctn.fNumeratorFake);
else
fNumeratorFake = 0;
if (fDenominator) delete fDenominator;
if (aCorrFctn.fDenominator)
fDenominator = new TH1D(*aCorrFctn.fDenominator);
else
fDenominator = 0;
}
return *this;
}
//_______________________
AliFemtoString AliFemtoModelCorrFctnDirectYlm::Report()
{
// construct report
AliFemtoString tStr = "AliFemtoModelCorrFctnDirectYlm report";
return tStr;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddRealPair(AliFemtoPair* aPair)
{
// add real (effect) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS)
fCYlmTrue->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
else
fCYlmTrue->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::AddMixedPair(AliFemtoPair* aPair)
{
// add mixed (background) pair
if (fPairCut)
if (!(fPairCut->Pass(aPair))) return;
Double_t weight = fManager->GetWeight(aPair);
if (fUseLCMS) {
fCYlmTrue->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
fCYlmFake->AddRealPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), weight);
fCYlmFake->AddMixedPair(aPair->QOutCMS(), aPair->QSideCMS(), aPair->QLongCMS(), 1.0);
}
else {
fCYlmTrue->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
fCYlmFake->AddRealPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), weight);
fCYlmFake->AddMixedPair(aPair->KOut(), aPair->KSide(), aPair->KLong(), 1.0);
}
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Write()
{
// write out all the histograms
fCYlmTrue->Write();
fCYlmFake->Write();
}
//_______________________
TList* AliFemtoModelCorrFctnDirectYlm::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = AliFemtoModelCorrFctn::GetOutputList();
tOutputList->Clear();
TList *tListCfTrue = fCYlmTrue->GetOutputList();
TIter nextListCfTrue(tListCfTrue);
while (TObject *obj = nextListCfTrue()) {
tOutputList->Add(obj);
}
TList *tListCfFake = fCYlmFake->GetOutputList();
TIter nextListCfFake(tListCfFake);
while (TObject *obj = nextListCfFake()) {
tOutputList->Add(obj);
}
// tOutputList->Add(fCYlmTrue->GetOutputList());
// tOutputList->Add(fCYlmFake->GetOutputList());
return tOutputList;
}
//_______________________
AliFemtoModelCorrFctn* AliFemtoModelCorrFctnDirectYlm::Clone()
{
// Clone the correlation function
AliFemtoModelCorrFctnDirectYlm *tCopy = new AliFemtoModelCorrFctnDirectYlm(*this);
return tCopy;
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::Finish()
{
fCYlmTrue->Finish();
fCYlmFake->Finish();
}
//_______________________
void AliFemtoModelCorrFctnDirectYlm::SetUseLCMS(int aUseLCMS)
{
fUseLCMS = aUseLCMS;
fCYlmTrue->SetUseLCMS(fUseLCMS);
fCYlmFake->SetUseLCMS(fUseLCMS);
}
//_______________________
int AliFemtoModelCorrFctnDirectYlm::GetUseLCMS()
{
return fUseLCMS;
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.6.14); FILE MERGED 2005/09/05 17:28:11 rt 1.6.14.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|> |
<commit_before>/************************************************
* static_assoc.hpp
* bptree
*
* Copyright (c) 2017, Chi-En Wu
* Distributed under MIT License
************************************************/
#ifndef BPTREE_INTERNAL_STATIC_ASSOC_HPP_
#define BPTREE_INTERNAL_STATIC_ASSOC_HPP_
#include <cstddef>
#include "./static_vector.hpp"
namespace bptree {
namespace internal {
/************************************************
* Declaration: class static_assoc<T, U, N>
************************************************/
template <typename ValueTraits, bool Unique, std::size_t N>
class static_assoc
: public ValueTraits,
private ValueTraits::value_compare {
private: // Private Type(s)
using value_traits = ValueTraits;
using underlying_type = static_vector<typename value_traits::value_type, N>;
public: // Public Type(s)
using key_type = typename value_traits::key_type;
using value_type = typename value_traits::value_type;
using key_compare = typename value_traits::key_compare;
using value_compare = typename value_traits::value_compare;
using reference = typename underlying_type::reference;
using const_reference = typename underlying_type::const_reference;
using pointer = typename underlying_type::pointer;
using const_pointer = typename underlying_type::const_pointer;
using size_type = typename underlying_type::size_type;
using difference_type = typename underlying_type::difference_type;
using iterator = typename underlying_type::iterator;
using const_iterator = typename underlying_type::const_iterator;
using reverse_iterator = typename underlying_type::reverse_iterator;
using const_reverse_iterator = typename underlying_type::const_reverse_iterator;
public: // Public Method(s)
static_assoc();
explicit static_assoc(key_compare comp);
template <typename InputIt>
static_assoc(InputIt first, InputIt last, key_compare const& comp = key_compare());
static_assoc(std::initializer_list<value_type> il, key_compare const& comp = key_compare());
static_assoc(static_assoc const&) = default;
static_assoc(static_assoc&&) = default;
static_assoc& operator=(std::initializer_list<value_type> il);
bool empty() const noexcept;
bool full() const noexcept;
size_type size() const noexcept;
constexpr size_type max_size() const noexcept;
constexpr size_type capacity() const noexcept;
iterator begin() noexcept;
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
const_reverse_iterator crbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
const_reverse_iterator crend() const noexcept;
key_compare key_comp() const;
value_compare value_comp() const;
private: // Private Method(s)
bool is_equal(value_type const& x, value_type const& y);
private: // Private Property(ies)
underlying_type values_;
};
/************************************************
* Implementation: class static_assoc<T, U, N>
************************************************/
template <typename T, bool U, std::size_t N>
inline static_assoc<T, U, N>::static_assoc()
: static_assoc(key_compare()) {
// do nothing
}
template <typename T, bool U, std::size_t N>
inline static_assoc<T, U, N>::static_assoc(key_compare comp)
: value_compare(comp), values_() {
// do nothing
}
template <typename T, bool U, std::size_t N>
template <typename InputIt>
static_assoc<T, U, N>::static_assoc(InputIt first, InputIt last, key_compare const& comp)
: static_assoc(comp) {
while (first != last) {
auto pos = std::upper_bound(values_.cbegin(), values_.cend(), *first, value_comp());
if (!U || pos == begin() || !is_equal(*(pos - 1), *first)) {
values_.insert(pos, *first);
}
++first;
}
}
template <typename T, bool U, std::size_t N>
inline static_assoc<T, U, N>::static_assoc(std::initializer_list<value_type> il,
key_compare const& comp)
: static_assoc(il.begin(), il.end(), comp) {
// do nothing
}
template <typename T, bool U, std::size_t N>
static_assoc<T, U, N>&
static_assoc<T, U, N>::operator=(std::initializer_list<value_type> il) {
values_.clear();
for (auto& value : il) {
auto pos = std::upper_bound(values_.cbegin(), values_.cend(), value, value_comp());
if (!U || pos == begin() || !is_equal(*(pos - 1), value)) {
values_.insert(pos, value);
}
}
return *this;
}
template <typename T, bool U, std::size_t N>
inline bool static_assoc<T, U, N>::empty() const noexcept {
return values_.empty();
}
template <typename T, bool U, std::size_t N>
inline bool static_assoc<T, U, N>::full() const noexcept {
return values_.full();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::size_type
static_assoc<T, U, N>::size() const noexcept {
return values_.size();
}
template <typename T, bool U, std::size_t N>
inline constexpr typename static_assoc<T, U, N>::size_type
static_assoc<T, U, N>::max_size() const noexcept {
return values_.max_size();
}
template <typename T, bool U, std::size_t N>
inline constexpr typename static_assoc<T, U, N>::size_type
static_assoc<T, U, N>::capacity() const noexcept {
return values_.capacity();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::iterator
static_assoc<T, U, N>::begin() noexcept {
return values_.begin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::begin() const noexcept {
return cbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::cbegin() const noexcept {
return values_.cbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::iterator
static_assoc<T, U, N>::end() noexcept {
return values_.end();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::end() const noexcept {
return cend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::cend() const noexcept {
return values_.cend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::reverse_iterator
static_assoc<T, U, N>::rbegin() noexcept {
return values_.rbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::rbegin() const noexcept {
return crbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::crbegin() const noexcept {
return values_.crbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::reverse_iterator
static_assoc<T, U, N>::rend() noexcept {
return values_.rend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::rend() const noexcept {
return crend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::crend() const noexcept {
return values_.crend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::key_compare
static_assoc<T, U, N>::key_comp() const {
return key_compare(*this);
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::value_compare
static_assoc<T, U, N>::value_comp() const {
return value_compare(*this);
}
template <typename T, bool U, std::size_t N>
inline bool static_assoc<T, U, N>::is_equal(value_type const& x, value_type const& y) {
return !value_compare::operator()(x, y) && !value_compare::operator()(y, x);
}
} // namespace internal
} // namespace bptree
#endif // BPTREE_INTERNAL_STATIC_ASSOC_HPP_
<commit_msg>:sparkles: Add `internal::static_assoc<>::clear()`<commit_after>/************************************************
* static_assoc.hpp
* bptree
*
* Copyright (c) 2017, Chi-En Wu
* Distributed under MIT License
************************************************/
#ifndef BPTREE_INTERNAL_STATIC_ASSOC_HPP_
#define BPTREE_INTERNAL_STATIC_ASSOC_HPP_
#include <cstddef>
#include "./static_vector.hpp"
namespace bptree {
namespace internal {
/************************************************
* Declaration: class static_assoc<T, U, N>
************************************************/
template <typename ValueTraits, bool Unique, std::size_t N>
class static_assoc
: public ValueTraits,
private ValueTraits::value_compare {
private: // Private Type(s)
using value_traits = ValueTraits;
using underlying_type = static_vector<typename value_traits::value_type, N>;
public: // Public Type(s)
using key_type = typename value_traits::key_type;
using value_type = typename value_traits::value_type;
using key_compare = typename value_traits::key_compare;
using value_compare = typename value_traits::value_compare;
using reference = typename underlying_type::reference;
using const_reference = typename underlying_type::const_reference;
using pointer = typename underlying_type::pointer;
using const_pointer = typename underlying_type::const_pointer;
using size_type = typename underlying_type::size_type;
using difference_type = typename underlying_type::difference_type;
using iterator = typename underlying_type::iterator;
using const_iterator = typename underlying_type::const_iterator;
using reverse_iterator = typename underlying_type::reverse_iterator;
using const_reverse_iterator = typename underlying_type::const_reverse_iterator;
public: // Public Method(s)
static_assoc();
explicit static_assoc(key_compare comp);
template <typename InputIt>
static_assoc(InputIt first, InputIt last, key_compare const& comp = key_compare());
static_assoc(std::initializer_list<value_type> il, key_compare const& comp = key_compare());
static_assoc(static_assoc const&) = default;
static_assoc(static_assoc&&) = default;
static_assoc& operator=(std::initializer_list<value_type> il);
void clear() noexcept;
bool empty() const noexcept;
bool full() const noexcept;
size_type size() const noexcept;
constexpr size_type max_size() const noexcept;
constexpr size_type capacity() const noexcept;
iterator begin() noexcept;
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
const_reverse_iterator crbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
const_reverse_iterator crend() const noexcept;
key_compare key_comp() const;
value_compare value_comp() const;
private: // Private Method(s)
bool is_equal(value_type const& x, value_type const& y);
private: // Private Property(ies)
underlying_type values_;
};
/************************************************
* Implementation: class static_assoc<T, U, N>
************************************************/
template <typename T, bool U, std::size_t N>
inline static_assoc<T, U, N>::static_assoc()
: static_assoc(key_compare()) {
// do nothing
}
template <typename T, bool U, std::size_t N>
inline static_assoc<T, U, N>::static_assoc(key_compare comp)
: value_compare(comp), values_() {
// do nothing
}
template <typename T, bool U, std::size_t N>
template <typename InputIt>
static_assoc<T, U, N>::static_assoc(InputIt first, InputIt last, key_compare const& comp)
: static_assoc(comp) {
while (first != last) {
auto pos = std::upper_bound(values_.cbegin(), values_.cend(), *first, value_comp());
if (!U || pos == begin() || !is_equal(*(pos - 1), *first)) {
values_.insert(pos, *first);
}
++first;
}
}
template <typename T, bool U, std::size_t N>
inline static_assoc<T, U, N>::static_assoc(std::initializer_list<value_type> il,
key_compare const& comp)
: static_assoc(il.begin(), il.end(), comp) {
// do nothing
}
template <typename T, bool U, std::size_t N>
static_assoc<T, U, N>&
static_assoc<T, U, N>::operator=(std::initializer_list<value_type> il) {
clear();
for (auto& value : il) {
auto pos = std::upper_bound(values_.cbegin(), values_.cend(), value, value_comp());
if (!U || pos == begin() || !is_equal(*(pos - 1), value)) {
values_.insert(pos, value);
}
}
return *this;
}
template <typename T, bool U, std::size_t N>
inline void static_assoc<T, U, N>::clear() noexcept {
values_.clear();
}
template <typename T, bool U, std::size_t N>
inline bool static_assoc<T, U, N>::empty() const noexcept {
return values_.empty();
}
template <typename T, bool U, std::size_t N>
inline bool static_assoc<T, U, N>::full() const noexcept {
return values_.full();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::size_type
static_assoc<T, U, N>::size() const noexcept {
return values_.size();
}
template <typename T, bool U, std::size_t N>
inline constexpr typename static_assoc<T, U, N>::size_type
static_assoc<T, U, N>::max_size() const noexcept {
return values_.max_size();
}
template <typename T, bool U, std::size_t N>
inline constexpr typename static_assoc<T, U, N>::size_type
static_assoc<T, U, N>::capacity() const noexcept {
return values_.capacity();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::iterator
static_assoc<T, U, N>::begin() noexcept {
return values_.begin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::begin() const noexcept {
return cbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::cbegin() const noexcept {
return values_.cbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::iterator
static_assoc<T, U, N>::end() noexcept {
return values_.end();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::end() const noexcept {
return cend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_iterator
static_assoc<T, U, N>::cend() const noexcept {
return values_.cend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::reverse_iterator
static_assoc<T, U, N>::rbegin() noexcept {
return values_.rbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::rbegin() const noexcept {
return crbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::crbegin() const noexcept {
return values_.crbegin();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::reverse_iterator
static_assoc<T, U, N>::rend() noexcept {
return values_.rend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::rend() const noexcept {
return crend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::const_reverse_iterator
static_assoc<T, U, N>::crend() const noexcept {
return values_.crend();
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::key_compare
static_assoc<T, U, N>::key_comp() const {
return key_compare(*this);
}
template <typename T, bool U, std::size_t N>
inline typename static_assoc<T, U, N>::value_compare
static_assoc<T, U, N>::value_comp() const {
return value_compare(*this);
}
template <typename T, bool U, std::size_t N>
inline bool static_assoc<T, U, N>::is_equal(value_type const& x, value_type const& y) {
return !value_compare::operator()(x, y) && !value_compare::operator()(y, x);
}
} // namespace internal
} // namespace bptree
#endif // BPTREE_INTERNAL_STATIC_ASSOC_HPP_
<|endoftext|> |
<commit_before><commit_msg>Replace ~CreateSessionDescriptionRequest CHECK with DLOG. During shutdown, it is not guaranteed that the tasks posted in OnSuccess and onFailure will complete. To avoid the CHECK during shutdown, it is replaced by DLOG.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MABPreparedStatement.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:29:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_PREPAREDSTATEMENT_HXX_
#define _CONNECTIVITY_MAB_PREPAREDSTATEMENT_HXX_
#ifndef _CONNECTIVITY_FILE_OPREPAREDSTATEMENT_HXX_
#include "file/FPreparedStatement.hxx"
#endif
namespace connectivity
{
namespace mozaddressbook
{
class OConnection;
class OMozabPreparedStatement : public file::OPreparedStatement
{
protected:
virtual file::OResultSet* createResultSet();
// here we create a SQL analyzer which doesn't support any restrictions
// these are already done by the server side
virtual file::OSQLAnalyzer* createAnalyzer();
public:
// DECLARE_CTY_DEFAULTS(file::OStatement);
OMozabPreparedStatement( file::OConnection* _pConnection ) : file::OPreparedStatement( _pConnection ){}
DECLARE_SERVICE_INFO();
};
}
}
#endif //_CONNECTIVITY_MAB_PREPAREDSTATEMENT_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.7.372); FILE MERGED 2008/04/01 10:53:40 thb 1.7.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:31 rt 1.7.372.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MABPreparedStatement.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_PREPAREDSTATEMENT_HXX_
#define _CONNECTIVITY_MAB_PREPAREDSTATEMENT_HXX_
#include "file/FPreparedStatement.hxx"
namespace connectivity
{
namespace mozaddressbook
{
class OConnection;
class OMozabPreparedStatement : public file::OPreparedStatement
{
protected:
virtual file::OResultSet* createResultSet();
// here we create a SQL analyzer which doesn't support any restrictions
// these are already done by the server side
virtual file::OSQLAnalyzer* createAnalyzer();
public:
// DECLARE_CTY_DEFAULTS(file::OStatement);
OMozabPreparedStatement( file::OConnection* _pConnection ) : file::OPreparedStatement( _pConnection ){}
DECLARE_SERVICE_INFO();
};
}
}
#endif //_CONNECTIVITY_MAB_PREPAREDSTATEMENT_HXX_
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
ifstream infile(fileName) ;
string line;
while(getline(infile, line)) {
istringstream iss(line);
int n;
iss >> n;
insert(listSize, n);
}
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
for(int i=0; i < listSize; i++) {
int value = *this->get(i);
int remainder = value%theInt;
cout << "value: " << value << ", Remainder: " << remainder << ", listSize: " << listSize << ", i: " << i << endl;
if (remainder == 0 && value > theInt) {
erase(i);
i--;
}
output();
}
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
for(int i=0; i < listSize; i++) {
int value = *this->get(i);
insert(0, value);
}
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
<commit_msg>first 2 working<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
ifstream infile(fileName) ;
string line;
while(getline(infile, line)) {
istringstream iss(line);
int n;
iss >> n;
insert(listSize, n);
}
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
for(int i=0; i < listSize; i++) {
int value = *this->get(i);
int remainder = value%theInt;
if (remainder == 0 && value > theInt) {
erase(i);
i--;
}
}
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
for(int i=0; i < listSize; i++) {
int value = *this->get(i);
insert(0, value);
}
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_EDITOR_EDITOR_HPP
#define RJ_GAME_EDITOR_EDITOR_HPP
#include "background_editor.hpp"
#include "editor_entity.hpp"
#include "itembar.hpp"
#include "mouse.hpp"
#include "settingsbar.hpp"
#include <rectojump/game/components/platform.hpp>
#include <rectojump/game/camera.hpp>
#include <rectojump/game/world.hpp>
namespace rj
{
template<typename Game_Handler, typename Game>
class editor
{
public:
using gh_type = Game_Handler;
Game_Handler& m_gamehandler;
Game& m_game;
world<Game_Handler>& m_gameworld;
entity_handler& m_entityhandler;
level_manager& m_levelmgr;
camera m_editarea_camera;
camera m_itembar_camera;
camera m_settingsbar_camera;
editor_mouse m_mouse;
background_editor<editor> m_background{*this};
itembar<Game_Handler> m_itembar;
settingsbar<editor> m_settingsbar;
public:
editor(Game_Handler& gh) :
m_gamehandler{gh},
m_game{gh.get_game()},
m_gameworld{m_game.get_world()},
m_entityhandler{m_gameworld.get_entityhandler()},
m_levelmgr{gh.get_levelmgr()},
m_editarea_camera{m_gamehandler.get_gamewindow()},
m_itembar_camera{m_gamehandler.get_gamewindow()},
m_settingsbar_camera{m_gamehandler.get_gamewindow()},
m_mouse{gh.get_render()},
m_itembar{gh, {settings::get_window_size<vec2f>().x, 100.f}},
m_settingsbar{*this, {300.f, settings::get_window_size<vec2f>().y - m_itembar.get_size().y}}
{this->init();}
void update(dur duration)
{
// edit area
m_editarea_camera.set_changes();
m_mouse.update(duration);
// itembar
m_itembar_camera.set_changes();
m_itembar.update(duration);
// settingsbar
m_settingsbar_camera.set_changes();
m_settingsbar.update(duration);
}
void render()
{
// edit area
m_editarea_camera.set_changes();
m_entityhandler.render();
m_mouse.render();
// itembar
m_itembar_camera.set_changes();
m_itembar.render();
// settingsbar
m_settingsbar_camera.set_changes();
m_settingsbar.render();
}
void handle_save()
{
level_data lv_data;
for(auto& a : m_entityhandler)
{
auto ent(this->to_editor_entity(a));
lv_data.add_entity(ent->get_figure(), entity_propertie::solid, ent->pos());
}
level_info lv_info{"Test", "ABC"};
music_data lv_music{'M', 'U', 'S', 'I', 'C'};
level_packer<packer_mode::pack> lv_packer{lv_music, lv_data, lv_info};
m_levelmgr.save_level(lv_packer, "TESTLV0");
}
void handle_load()
{
}
void on_activate()
{
m_background.reset();
}
auto get_gamehandler() noexcept
-> decltype(m_gamehandler)&
{return m_gamehandler;}
private:
void init()
{
// change mousetexture on itembar-item click
m_itembar.on_item_click =
[this](ui::base_btn_ptr& b){m_mouse.set_texture(b->get_texture());};
// init mouse texture
m_mouse.set_texture(&m_itembar.get_current_texture());
this->init_input();
this->init_cameras();
}
void init_input()
{
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos){this->on_mouse_left(pos);}, btn::Left);
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos){this->on_mouse_right(pos);}, btn::Right);
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos)
{m_editarea_camera.move({settings::get_editor_scroll_step(), 0.f});}, wheel::down);
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos)
{
if(m_editarea_camera.get_center().x >= m_editarea_camera.get_startcenter().x)
m_editarea_camera.move({-settings::get_editor_scroll_step(), 0.f});
}, wheel::up);
}
void init_cameras() noexcept
{
auto window_size(settings::get_window_size<vec2f>());
auto& itembar_size(m_itembar.get_size());
auto& settingsbar_size(m_settingsbar.get_size());
float itembar_top{(window_size.y - itembar_size.y) / window_size.y};
float itembar_height{itembar_size.y / window_size.y};
float editarea_height{(window_size.y - itembar_size.y) / window_size.y};
sf::View editarea_view{vec2f{window_size.x, window_size.y - itembar_size.y} / 2.f, {window_size.x, window_size.y - itembar_size.y}};
editarea_view.setViewport({0.f, 0.f, 1.f ,editarea_height});
m_editarea_camera.set_view(editarea_view);
sf::View itembar_view{vec2f{window_size.x, itembar_size.y} / 2.f, {window_size.x, itembar_size.y}};
itembar_view.setViewport({0.f, itembar_top, 1.f, itembar_height});
m_itembar_camera.set_view(itembar_view);
sf::View settingsbar_view{vec2f{settingsbar_size.x, window_size.y} / 2.f, {settingsbar_size.x, window_size.y}};
settingsbar_view.setViewport({(window_size.x - settingsbar_size.x) / window_size.x, 0.f, settingsbar_size.x / window_size.x, 1.f});
m_settingsbar_camera.set_view(settingsbar_view);
}
void on_mouse_left(const vec2f&)
{
// check the itembar and settingsbar bounds
auto itembar_mouse_bounds(bounds_from_vec(m_itembar_camera.get_mapped_mousepos()));
auto settingsbar_mouse_bounds(bounds_from_vec(m_settingsbar_camera.get_mapped_mousepos()));
if(itembar_mouse_bounds.intersects(m_itembar.get_bounds()) ||
settingsbar_mouse_bounds.intersects(m_settingsbar.get_bounds()))
return;
float f{48.f};
vec2f new_pos{round_to(m_editarea_camera.get_mapped_mousepos().x, f), round_to(m_editarea_camera.get_mapped_mousepos().y, f)};
// check if entity exists at this pos
auto iter(m_entityhandler.exists_entity_at(m_editarea_camera.get_mapped_mousepos()));
if(iter != std::end(m_entityhandler))
{
auto ptr(this->to_editor_entity(*iter));
m_mouse.set_texture(ptr->get_texture());
m_itembar.select(ptr->get_figure());
return;
}
// set entity at pos
if(m_mouse.get_texture())
{
auto ptr(m_gameworld.template create_entity<editor_entity>(new_pos));
ptr->render_object().setTexture(m_mouse.get_texture());
ptr->set_figure(m_itembar.get_current_figure());
}
}
void on_mouse_right(const vec2f&)
{
m_itembar.deselect_all();
m_mouse.clear();
auto iter(m_entityhandler.exists_entity_at(m_editarea_camera.get_mapped_mousepos()));
if(iter != std::end(m_entityhandler))
m_entityhandler.delete_entity(iter);
}
template<typename Ent_Ptr>
auto to_editor_entity(const Ent_Ptr& ptr)
-> decltype(std::static_pointer_cast<editor_entity>(ptr))
{return std::static_pointer_cast<editor_entity>(ptr);}
};
}
#endif // RJ_GAME_EDITOR_EDITOR_HPP
<commit_msg>editor: fixed testing public -> private<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_EDITOR_EDITOR_HPP
#define RJ_GAME_EDITOR_EDITOR_HPP
#include "background_editor.hpp"
#include "editor_entity.hpp"
#include "itembar.hpp"
#include "mouse.hpp"
#include "settingsbar.hpp"
#include <rectojump/game/components/platform.hpp>
#include <rectojump/game/camera.hpp>
#include <rectojump/game/world.hpp>
namespace rj
{
template<typename Game_Handler, typename Game>
class editor
{
public:
using gh_type = Game_Handler;
private:
Game_Handler& m_gamehandler;
Game& m_game;
world<Game_Handler>& m_gameworld;
entity_handler& m_entityhandler;
level_manager& m_levelmgr;
camera m_editarea_camera;
camera m_itembar_camera;
camera m_settingsbar_camera;
editor_mouse m_mouse;
background_editor<editor> m_background{*this};
itembar<Game_Handler> m_itembar;
settingsbar<editor> m_settingsbar;
public:
editor(Game_Handler& gh) :
m_gamehandler{gh},
m_game{gh.get_game()},
m_gameworld{m_game.get_world()},
m_entityhandler{m_gameworld.get_entityhandler()},
m_levelmgr{gh.get_levelmgr()},
m_editarea_camera{m_gamehandler.get_gamewindow()},
m_itembar_camera{m_gamehandler.get_gamewindow()},
m_settingsbar_camera{m_gamehandler.get_gamewindow()},
m_mouse{gh.get_render()},
m_itembar{gh, {settings::get_window_size<vec2f>().x, 100.f}},
m_settingsbar{*this, {300.f, settings::get_window_size<vec2f>().y - m_itembar.get_size().y}}
{this->init();}
void update(dur duration)
{
// edit area
m_editarea_camera.set_changes();
m_mouse.update(duration);
// itembar
m_itembar_camera.set_changes();
m_itembar.update(duration);
// settingsbar
m_settingsbar_camera.set_changes();
m_settingsbar.update(duration);
}
void render()
{
// edit area
m_editarea_camera.set_changes();
m_entityhandler.render();
m_mouse.render();
// itembar
m_itembar_camera.set_changes();
m_itembar.render();
// settingsbar
m_settingsbar_camera.set_changes();
m_settingsbar.render();
}
void handle_save(const std::string& level_name)
{
level_data lv_data;
for(auto& a : m_entityhandler)
{
auto ent(this->to_editor_entity(a));
lv_data.add_entity(ent->get_figure(), entity_propertie::solid, ent->pos());
}
level_info lv_info{"Test", "ABC"};
music_data lv_music{'M', 'U', 'S', 'I', 'C'};
level_packer<packer_mode::pack> lv_packer{lv_music, lv_data, lv_info};
m_levelmgr.save_level(lv_packer, level_name);
}
void handle_load(const std::string& level_name)
{
}
void on_activate()
{
m_background.reset();
}
auto get_gamehandler() noexcept
-> decltype(m_gamehandler)&
{return m_gamehandler;}
private:
void init()
{
// change mousetexture on itembar-item click
m_itembar.on_item_click =
[this](ui::base_btn_ptr& b){m_mouse.set_texture(b->get_texture());};
// init mouse texture
m_mouse.set_texture(&m_itembar.get_current_texture());
this->init_input();
this->init_cameras();
}
void init_input()
{
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos){this->on_mouse_left(pos);}, btn::Left);
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos){this->on_mouse_right(pos);}, btn::Right);
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos)
{m_editarea_camera.move({settings::get_editor_scroll_step(), 0.f});}, wheel::down);
m_gamehandler.template add_input<state::editor>(
[this](const vec2f& pos)
{
if(m_editarea_camera.get_center().x >= m_editarea_camera.get_startcenter().x)
m_editarea_camera.move({-settings::get_editor_scroll_step(), 0.f});
}, wheel::up);
}
void init_cameras() noexcept
{
auto window_size(settings::get_window_size<vec2f>());
auto& itembar_size(m_itembar.get_size());
auto& settingsbar_size(m_settingsbar.get_size());
float itembar_top{(window_size.y - itembar_size.y) / window_size.y};
float itembar_height{itembar_size.y / window_size.y};
float editarea_height{(window_size.y - itembar_size.y) / window_size.y};
sf::View editarea_view{vec2f{window_size.x, window_size.y - itembar_size.y} / 2.f, {window_size.x, window_size.y - itembar_size.y}};
editarea_view.setViewport({0.f, 0.f, 1.f ,editarea_height});
m_editarea_camera.set_view(editarea_view);
sf::View itembar_view{vec2f{window_size.x, itembar_size.y} / 2.f, {window_size.x, itembar_size.y}};
itembar_view.setViewport({0.f, itembar_top, 1.f, itembar_height});
m_itembar_camera.set_view(itembar_view);
sf::View settingsbar_view{vec2f{settingsbar_size.x, window_size.y} / 2.f, {settingsbar_size.x, window_size.y}};
settingsbar_view.setViewport({(window_size.x - settingsbar_size.x) / window_size.x, 0.f, settingsbar_size.x / window_size.x, 1.f});
m_settingsbar_camera.set_view(settingsbar_view);
}
void on_mouse_left(const vec2f&)
{
// check the itembar and settingsbar bounds
auto itembar_mouse_bounds(bounds_from_vec(m_itembar_camera.get_mapped_mousepos()));
auto settingsbar_mouse_bounds(bounds_from_vec(m_settingsbar_camera.get_mapped_mousepos()));
if(itembar_mouse_bounds.intersects(m_itembar.get_bounds()) ||
settingsbar_mouse_bounds.intersects(m_settingsbar.get_bounds()))
return;
float f{48.f};
vec2f new_pos{round_to(m_editarea_camera.get_mapped_mousepos().x, f), round_to(m_editarea_camera.get_mapped_mousepos().y, f)};
// check if entity exists at this pos
auto iter(m_entityhandler.exists_entity_at(m_editarea_camera.get_mapped_mousepos()));
if(iter != std::end(m_entityhandler))
{
auto ptr(this->to_editor_entity(*iter));
m_mouse.set_texture(ptr->get_texture());
m_itembar.select(ptr->get_figure());
return;
}
// set entity at pos
if(m_mouse.get_texture())
{
auto ptr(m_gameworld.template create_entity<editor_entity>(new_pos));
ptr->render_object().setTexture(m_mouse.get_texture());
ptr->set_figure(m_itembar.get_current_figure());
}
}
void on_mouse_right(const vec2f&)
{
m_itembar.deselect_all();
m_mouse.clear();
auto iter(m_entityhandler.exists_entity_at(m_editarea_camera.get_mapped_mousepos()));
if(iter != std::end(m_entityhandler))
m_entityhandler.delete_entity(iter);
}
template<typename Ent_Ptr>
auto to_editor_entity(const Ent_Ptr& ptr)
-> decltype(std::static_pointer_cast<editor_entity>(ptr))
{return std::static_pointer_cast<editor_entity>(ptr);}
};
}
#endif // RJ_GAME_EDITOR_EDITOR_HPP
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/tf_record_dataset_op.h"
#include "tensorflow/core/common_runtime/metrics.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/name_utils.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/inputbuffer.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/lib/io/zlib_compression_options.h"
#include "tensorflow/core/lib/io/zlib_inputstream.h"
namespace tensorflow {
namespace data {
// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following ops.
/* static */ constexpr const char* const TFRecordDatasetOp::kDatasetType;
/* static */ constexpr const char* const TFRecordDatasetOp::kFileNames;
/* static */ constexpr const char* const TFRecordDatasetOp::kCompressionType;
/* static */ constexpr const char* const TFRecordDatasetOp::kBufferSize;
constexpr char kCurrentFileIndex[] = "current_file_index";
constexpr char kOffset[] = "offset";
class TFRecordDatasetOp::Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, std::vector<string> filenames,
const string& compression_type, int64 buffer_size)
: DatasetBase(DatasetContext(ctx)),
filenames_(std::move(filenames)),
compression_type_(compression_type),
options_(io::RecordReaderOptions::CreateRecordReaderOptions(
compression_type)) {
if (buffer_size > 0) {
options_.buffer_size = buffer_size;
}
}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return absl::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix)});
}
const DataTypeVector& output_dtypes() const override {
static DataTypeVector* dtypes = new DataTypeVector({DT_STRING});
return *dtypes;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({{}});
return *shapes;
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
Status CheckExternalState() const override { return Status::OK(); }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames));
Node* compression_type = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(compression_type_, &compression_type));
Node* buffer_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(options_.buffer_size, &buffer_size));
TF_RETURN_IF_ERROR(b->AddDataset(
this, {filenames, compression_type, buffer_size}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
out_tensors->reserve(1);
mutex_lock l(mu_);
do {
// We are currently processing a file, so try to read the next record.
if (reader_) {
out_tensors->emplace_back(ctx->allocator({}), DT_STRING,
TensorShape({}));
Status s =
reader_->ReadRecord(&out_tensors->back().scalar<tstring>()());
if (s.ok()) {
metrics::RecordTFDataBytesRead(
kDatasetType, out_tensors->back().scalar<tstring>()().size());
*end_of_sequence = false;
return Status::OK();
}
out_tensors->pop_back();
if (!errors::IsOutOfRange(s)) {
// In case of other errors e.g., DataLoss, we still move forward
// the file index so that it works with ignore_errors.
// Otherwise the same file will repeat.
ResetStreamsLocked();
++current_file_index_;
return s;
}
// We have reached the end of the current file, so maybe move on to
// next file.
ResetStreamsLocked();
++current_file_index_;
}
// Iteration ends when there are no more files to process.
if (current_file_index_ == dataset()->filenames_.size()) {
*end_of_sequence = true;
return Status::OK();
}
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
} while (true);
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeSourceNode(std::move(args));
}
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name(kCurrentFileIndex),
current_file_index_));
if (reader_) {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name(kOffset), reader_->TellOffset()));
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
ResetStreamsLocked();
int64 current_file_index;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name(kCurrentFileIndex),
¤t_file_index));
current_file_index_ = size_t(current_file_index);
if (reader->Contains(full_name(kOffset))) {
int64 offset;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name(kOffset), &offset));
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
TF_RETURN_IF_ERROR(reader_->SeekOffset(offset));
}
return Status::OK();
}
private:
// Sets up reader streams to read from the file at `current_file_index_`.
Status SetupStreamsLocked(Env* env) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (current_file_index_ >= dataset()->filenames_.size()) {
return errors::InvalidArgument(
"current_file_index_:", current_file_index_,
" >= filenames_.size():", dataset()->filenames_.size());
}
// Actually move on to next file.
const string& next_filename = dataset()->filenames_[current_file_index_];
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(next_filename, &file_));
reader_ = absl::make_unique<io::SequentialRecordReader>(
file_.get(), dataset()->options_);
return Status::OK();
}
// Resets all reader streams.
void ResetStreamsLocked() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
reader_.reset();
file_.reset();
}
mutex mu_;
size_t current_file_index_ GUARDED_BY(mu_) = 0;
// `reader_` will borrow the object that `file_` points to, so
// we must destroy `reader_` before `file_`.
std::unique_ptr<RandomAccessFile> file_ GUARDED_BY(mu_);
std::unique_ptr<io::SequentialRecordReader> reader_ GUARDED_BY(mu_);
};
const std::vector<string> filenames_;
const tstring compression_type_;
io::RecordReaderOptions options_;
};
TFRecordDatasetOp::TFRecordDatasetOp(OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {}
void TFRecordDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase** output) {
const Tensor* filenames_tensor;
OP_REQUIRES_OK(ctx, ctx->input(kFileNames, &filenames_tensor));
OP_REQUIRES(
ctx, filenames_tensor->dims() <= 1,
errors::InvalidArgument("`filenames` must be a scalar or a vector."));
std::vector<string> filenames;
filenames.reserve(filenames_tensor->NumElements());
for (int i = 0; i < filenames_tensor->NumElements(); ++i) {
VLOG(2) << "Reading file: " << filenames_tensor->flat<tstring>()(i);
filenames.push_back(filenames_tensor->flat<tstring>()(i));
}
tstring compression_type;
OP_REQUIRES_OK(ctx, ParseScalarArgument<tstring>(ctx, kCompressionType,
&compression_type));
int64 buffer_size = -1;
OP_REQUIRES_OK(ctx,
ParseScalarArgument<int64>(ctx, kBufferSize, &buffer_size));
OP_REQUIRES(ctx, buffer_size >= 0,
errors::InvalidArgument(
"`buffer_size` must be >= 0 (0 == no buffering)"));
*output =
new Dataset(ctx, std::move(filenames), compression_type, buffer_size);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("TFRecordDataset").Device(DEVICE_CPU),
TFRecordDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
<commit_msg>Override buffer size when running on cloud tpu. A small buffer size adds a performance slowdown. Here we override the buffer size to a minimum recommended buffer size.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/tf_record_dataset_op.h"
#include "tensorflow/core/common_runtime/metrics.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/name_utils.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/inputbuffer.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/lib/io/zlib_compression_options.h"
#include "tensorflow/core/lib/io/zlib_inputstream.h"
namespace tensorflow {
namespace data {
// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following ops.
/* static */ constexpr const char* const TFRecordDatasetOp::kDatasetType;
/* static */ constexpr const char* const TFRecordDatasetOp::kFileNames;
/* static */ constexpr const char* const TFRecordDatasetOp::kCompressionType;
/* static */ constexpr const char* const TFRecordDatasetOp::kBufferSize;
constexpr char kCurrentFileIndex[] = "current_file_index";
constexpr char kOffset[] = "offset";
constexpr char kGcsFsPrefix[] = "gs://";
constexpr int64 kCloudTpuBlockSize = 127LL << 20; // 127MB.
bool is_cloud_tpu_gcs_fs() {
#if defined(PLATFORM_CLOUD_TPU) && defined(TPU_GCS_FS)
return true;
#endif
return false;
}
class TFRecordDatasetOp::Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, std::vector<string> filenames,
const string& compression_type, int64 buffer_size)
: DatasetBase(DatasetContext(ctx)),
filenames_(std::move(filenames)),
compression_type_(compression_type),
options_(io::RecordReaderOptions::CreateRecordReaderOptions(
compression_type)) {
if (buffer_size > 0) {
options_.buffer_size = buffer_size;
}
}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return absl::make_unique<Iterator>(Iterator::Params{
this, name_utils::IteratorPrefix(kDatasetType, prefix)});
}
const DataTypeVector& output_dtypes() const override {
static DataTypeVector* dtypes = new DataTypeVector({DT_STRING});
return *dtypes;
}
const std::vector<PartialTensorShape>& output_shapes() const override {
static std::vector<PartialTensorShape>* shapes =
new std::vector<PartialTensorShape>({{}});
return *shapes;
}
string DebugString() const override {
return name_utils::DatasetDebugString(kDatasetType);
}
Status CheckExternalState() const override { return Status::OK(); }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* filenames = nullptr;
TF_RETURN_IF_ERROR(b->AddVector(filenames_, &filenames));
Node* compression_type = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(compression_type_, &compression_type));
Node* buffer_size = nullptr;
TF_RETURN_IF_ERROR(b->AddScalar(options_.buffer_size, &buffer_size));
TF_RETURN_IF_ERROR(b->AddDataset(
this, {filenames, compression_type, buffer_size}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
out_tensors->reserve(1);
mutex_lock l(mu_);
do {
// We are currently processing a file, so try to read the next record.
if (reader_) {
out_tensors->emplace_back(ctx->allocator({}), DT_STRING,
TensorShape({}));
Status s =
reader_->ReadRecord(&out_tensors->back().scalar<tstring>()());
if (s.ok()) {
metrics::RecordTFDataBytesRead(
kDatasetType, out_tensors->back().scalar<tstring>()().size());
*end_of_sequence = false;
return Status::OK();
}
out_tensors->pop_back();
if (!errors::IsOutOfRange(s)) {
// In case of other errors e.g., DataLoss, we still move forward
// the file index so that it works with ignore_errors.
// Otherwise the same file will repeat.
ResetStreamsLocked();
++current_file_index_;
return s;
}
// We have reached the end of the current file, so maybe move on to
// next file.
ResetStreamsLocked();
++current_file_index_;
}
// Iteration ends when there are no more files to process.
if (current_file_index_ == dataset()->filenames_.size()) {
*end_of_sequence = true;
return Status::OK();
}
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
} while (true);
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeSourceNode(std::move(args));
}
Status SaveInternal(IteratorStateWriter* writer) override {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(writer->WriteScalar(full_name(kCurrentFileIndex),
current_file_index_));
if (reader_) {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name(kOffset), reader_->TellOffset()));
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
ResetStreamsLocked();
int64 current_file_index;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name(kCurrentFileIndex),
¤t_file_index));
current_file_index_ = size_t(current_file_index);
if (reader->Contains(full_name(kOffset))) {
int64 offset;
TF_RETURN_IF_ERROR(reader->ReadScalar(full_name(kOffset), &offset));
TF_RETURN_IF_ERROR(SetupStreamsLocked(ctx->env()));
TF_RETURN_IF_ERROR(reader_->SeekOffset(offset));
}
return Status::OK();
}
private:
// Sets up reader streams to read from the file at `current_file_index_`.
Status SetupStreamsLocked(Env* env) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (current_file_index_ >= dataset()->filenames_.size()) {
return errors::InvalidArgument(
"current_file_index_:", current_file_index_,
" >= filenames_.size():", dataset()->filenames_.size());
}
// Actually move on to next file.
const string& next_filename = dataset()->filenames_[current_file_index_];
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(next_filename, &file_));
reader_ = absl::make_unique<io::SequentialRecordReader>(
file_.get(), dataset()->options_);
return Status::OK();
}
// Resets all reader streams.
void ResetStreamsLocked() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
reader_.reset();
file_.reset();
}
mutex mu_;
size_t current_file_index_ GUARDED_BY(mu_) = 0;
// `reader_` will borrow the object that `file_` points to, so
// we must destroy `reader_` before `file_`.
std::unique_ptr<RandomAccessFile> file_ GUARDED_BY(mu_);
std::unique_ptr<io::SequentialRecordReader> reader_ GUARDED_BY(mu_);
};
const std::vector<string> filenames_;
const tstring compression_type_;
io::RecordReaderOptions options_;
};
TFRecordDatasetOp::TFRecordDatasetOp(OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {}
void TFRecordDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase** output) {
const Tensor* filenames_tensor;
OP_REQUIRES_OK(ctx, ctx->input(kFileNames, &filenames_tensor));
OP_REQUIRES(
ctx, filenames_tensor->dims() <= 1,
errors::InvalidArgument("`filenames` must be a scalar or a vector."));
bool is_gcs_fs = true;
std::vector<string> filenames;
filenames.reserve(filenames_tensor->NumElements());
for (int i = 0; i < filenames_tensor->NumElements(); ++i) {
VLOG(2) << "Reading file: " << filenames_tensor->flat<tstring>()(i);
filenames.push_back(filenames_tensor->flat<tstring>()(i));
is_gcs_fs &= absl::StartsWith(filenames[i], kGcsFsPrefix);
}
tstring compression_type;
OP_REQUIRES_OK(ctx, ParseScalarArgument<tstring>(ctx, kCompressionType,
&compression_type));
int64 buffer_size = -1;
OP_REQUIRES_OK(ctx,
ParseScalarArgument<int64>(ctx, kBufferSize, &buffer_size));
OP_REQUIRES(ctx, buffer_size >= 0,
errors::InvalidArgument(
"`buffer_size` must be >= 0 (0 == no buffering)"));
if (is_gcs_fs && is_cloud_tpu_gcs_fs() && buffer_size < kCloudTpuBlockSize) {
LOG(WARNING) << "User buffer size is too small for reading Cloud TPU "
<< "TFRecords stored in GCS. Overriding " << buffer_size
<< " to the minimum recommended buffer_size = "
<< kCloudTpuBlockSize;
buffer_size = kCloudTpuBlockSize;
}
*output =
new Dataset(ctx, std::move(filenames), compression_type, buffer_size);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("TFRecordDataset").Device(DEVICE_CPU),
TFRecordDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright (c) 2017-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP
#define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP
#include <cassert>
#include <memory>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <utility>
#include <vector>
#include "remove_first_state.hpp"
#include "shuffle_states.hpp"
#include "../apply_mode.hpp"
#include "../config.hpp"
#include "../demangle.hpp"
#include "../memory_input.hpp"
#include "../normal.hpp"
#include "../nothing.hpp"
#include "../parse.hpp"
#include "../rewind_mode.hpp"
#include "../internal/enable_control.hpp"
#include "../internal/has_unwind.hpp"
#include "../internal/iterator.hpp"
namespace TAO_PEGTL_NAMESPACE::parse_tree
{
template< typename T >
struct basic_node
{
using node_t = T;
using children_t = std::vector< std::unique_ptr< node_t > >;
children_t children;
std::string_view type;
std::string source;
TAO_PEGTL_NAMESPACE::internal::iterator m_begin;
TAO_PEGTL_NAMESPACE::internal::iterator m_end;
// each node will be default constructed
basic_node() = default;
// no copy/move is necessary
// (nodes are always owned/handled by a std::unique_ptr)
basic_node( const basic_node& ) = delete;
basic_node( basic_node&& ) = delete;
~basic_node() = default;
// no assignment either
basic_node& operator=( const basic_node& ) = delete;
basic_node& operator=( basic_node&& ) = delete;
[[nodiscard]] bool is_root() const noexcept
{
return type.empty();
}
template< typename U >
[[nodiscard]] bool is_type() const noexcept
{
return type == demangle< U >();
}
template< typename U >
void set_type() noexcept
{
type = demangle< U >();
}
[[nodiscard]] position begin() const
{
return position( m_begin, source );
}
[[nodiscard]] position end() const
{
return position( m_end, source );
}
[[nodiscard]] bool has_content() const noexcept
{
return m_end.data != nullptr;
}
[[nodiscard]] std::string_view string_view() const noexcept
{
assert( has_content() );
return std::string_view( m_begin.data, m_end.data - m_begin.data );
}
[[nodiscard]] std::string string() const
{
assert( has_content() );
return std::string( m_begin.data, m_end.data );
}
template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf >
[[nodiscard]] memory_input< P, Eol > as_memory_input() const
{
assert( has_content() );
return { m_begin.data, m_end.data, source, m_begin.byte, m_begin.line, m_begin.column };
}
template< typename... States >
void remove_content( States&&... /*unused*/ ) noexcept
{
m_end = TAO_PEGTL_NAMESPACE::internal::iterator();
}
// all non-root nodes are initialized by calling this method
template< typename Rule, typename ParseInput, typename... States >
void start( const ParseInput& in, States&&... /*unused*/ )
{
set_type< Rule >();
source = in.source();
m_begin = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() );
}
// if parsing of the rule succeeded, this method is called
template< typename Rule, typename ParseInput, typename... States >
void success( const ParseInput& in, States&&... /*unused*/ ) noexcept
{
m_end = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() );
}
// if parsing of the rule failed, this method is called
template< typename Rule, typename ParseInput, typename... States >
void failure( const ParseInput& /*unused*/, States&&... /*unused*/ ) noexcept
{}
// if parsing of the rule failed with an exception, this method is called
template< typename Rule, typename ParseInput, typename... States >
void unwind( const ParseInput& /*unused*/, States&&... /*unused*/ ) noexcept
{}
// if parsing succeeded and the (optional) transform call
// did not discard the node, it is appended to its parent.
// note that "child" is the node whose Rule just succeeded
// and "*this" is the parent where the node should be appended.
template< typename... States >
void emplace_back( std::unique_ptr< node_t >&& child, States&&... /*unused*/ )
{
assert( child );
children.emplace_back( std::move( child ) );
}
};
struct node
: basic_node< node >
{};
namespace internal
{
template< typename Node >
struct state
{
std::vector< std::unique_ptr< Node > > stack;
state()
{
emplace_back();
}
void emplace_back()
{
stack.emplace_back( std::make_unique< Node >() );
}
[[nodiscard]] std::unique_ptr< Node >& back() noexcept
{
assert( !stack.empty() );
return stack.back();
}
void pop_back() noexcept
{
assert( !stack.empty() );
return stack.pop_back();
}
};
template< typename Selector, typename... Parameters >
void transform( Parameters&&... /*unused*/ ) noexcept
{}
template< typename Selector, typename ParseInput, typename Node, typename... States >
auto transform( const ParseInput& in, std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( in, n, st... ) ) )
-> decltype( (void)Selector::transform( in, n, st... ) )
{
Selector::transform( in, n, st... );
}
template< typename Selector, typename ParseInput, typename Node, typename... States >
auto transform( const ParseInput& /*unused*/, std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( n, st... ) ) )
-> decltype( (void)Selector::transform( n, st... ) )
{
Selector::transform( n, st... );
}
template< typename Rule, template< typename... > class Selector >
inline constexpr bool is_selected_node = ( TAO_PEGTL_NAMESPACE::internal::enable_control< Rule > && Selector< Rule >::value );
template< unsigned Level, typename Subs, template< typename... > class Selector >
inline constexpr bool is_leaf{};
template< typename... Rules, template< typename... > class Selector >
inline constexpr bool is_leaf< 0, type_list< Rules... >, Selector > = ( sizeof...( Rules ) == 0 );
template< unsigned Level, typename Rule, template< typename... > class Selector >
inline constexpr bool is_unselected_branch = ( !is_selected_node< Rule, Selector > && is_leaf< Level, typename Rule::subs_t, Selector > );
template< unsigned Level, typename... Rules, template< typename... > class Selector >
inline constexpr bool is_leaf< Level, type_list< Rules... >, Selector > = ( is_unselected_branch< Level - 1, Rules, Selector > && ... );
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
struct make_control
{
template< typename Rule, bool, bool >
struct state_handler;
template< typename Rule >
using type = rotate_states_right< state_handler< Rule, is_selected_node< Rule, Selector >, is_leaf< 8, typename Rule::subs_t, Selector > > >;
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule >
struct make_control< Node, Selector, Control >::state_handler< Rule, false, true >
: remove_first_state< Control< Rule > >
{};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule >
struct make_control< Node, Selector, Control >::state_handler< Rule, false, false >
: remove_first_state< Control< Rule > >
{
static constexpr bool enable = true;
template< typename ParseInput, typename... States >
static void start( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
state.emplace_back();
}
template< typename ParseInput, typename... States >
static void success( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
auto n = std::move( state.back() );
state.pop_back();
for( auto& c : n->children ) {
state.back()->children.emplace_back( std::move( c ) );
}
}
template< typename ParseInput, typename... States >
static void failure( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
state.pop_back();
}
template< typename ParseInput, typename... States >
static void unwind( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
state.pop_back();
}
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule, bool B >
struct make_control< Node, Selector, Control >::state_handler< Rule, true, B >
: remove_first_state< Control< Rule > >
{
template< typename ParseInput, typename... States >
static void start( const ParseInput& in, state< Node >& state, States&&... st )
{
Control< Rule >::start( in, st... );
state.emplace_back();
state.back()->template start< Rule >( in, st... );
}
template< typename ParseInput, typename... States >
static void success( const ParseInput& in, state< Node >& state, States&&... st )
{
auto n = std::move( state.back() );
state.pop_back();
n->template success< Rule >( in, st... );
transform< Selector< Rule > >( in, n, st... );
if( n ) {
state.back()->emplace_back( std::move( n ), st... );
}
Control< Rule >::success( in, st... );
}
template< typename ParseInput, typename... States >
static void failure( const ParseInput& in, state< Node >& state, States&&... st )
{
state.back()->template failure< Rule >( in, st... );
state.pop_back();
Control< Rule >::failure( in, st... );
}
template< typename ParseInput, typename... States >
static void unwind( const ParseInput& in, state< Node >& state, States&&... st )
{
state.back()->template unwind< Rule >( in, st... );
state.pop_back();
if constexpr( TAO_PEGTL_NAMESPACE::internal::has_unwind< Control< Rule >, void, const ParseInput&, States... > ) {
Control< Rule >::unwind( in, st... );
}
}
};
template< typename >
using store_all = std::true_type;
template< typename >
struct selector;
template< typename T >
struct selector< std::tuple< T > >
{
using type = typename T::type;
};
template< typename... Ts >
struct selector< std::tuple< Ts... > >
{
static_assert( sizeof...( Ts ) == 0, "multiple matches found" );
using type = std::false_type;
};
template< typename T >
using selector_t = typename selector< T >::type;
template< typename Rule, typename Collection >
using select_tuple = std::conditional_t< Collection::template contains< Rule >, std::tuple< Collection >, std::tuple<> >;
} // namespace internal
template< typename Rule, typename... Collections >
using selector = internal::selector_t< decltype( std::tuple_cat( std::declval< internal::select_tuple< Rule, Collections > >()... ) ) >;
template< typename Base >
struct apply
: std::true_type
{
template< typename... Rules >
struct on
{
using type = Base;
template< typename Rule >
static constexpr bool contains = ( std::is_same_v< Rule, Rules > || ... );
};
};
struct store_content
: apply< store_content >
{};
// some nodes don't need to store their content
struct remove_content
: apply< remove_content >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->Node::remove_content( st... ) ) )
{
n->remove_content( st... );
}
};
// if a node has only one child, replace the node with its child, otherwise remove content
struct fold_one
: apply< fold_one >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.size(), n->Node::remove_content( st... ) ) )
{
if( n->children.size() == 1 ) {
n = std::move( n->children.front() );
}
else {
n->remove_content( st... );
}
}
};
// if a node has no children, discard the node, otherwise remove content
struct discard_empty
: apply< discard_empty >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( (void)n->children.empty(), n->Node::remove_content( st... ) ) )
{
if( n->children.empty() ) {
n.reset();
}
else {
n->remove_content( st... );
}
}
};
template< typename Rule,
typename Node,
template< typename... > class Selector = internal::store_all,
template< typename... > class Action = nothing,
template< typename... > class Control = normal,
typename ParseInput,
typename... States >
[[nodiscard]] std::unique_ptr< Node > parse( ParseInput&& in, States&&... st )
{
internal::state< Node > state;
if( !TAO_PEGTL_NAMESPACE::parse< Rule, Action, internal::make_control< Node, Selector, Control >::template type >( in, st..., state ) ) {
return nullptr;
}
assert( state.stack.size() == 1 );
return std::move( state.back() );
}
template< typename Rule,
template< typename... > class Selector = internal::store_all,
template< typename... > class Action = nothing,
template< typename... > class Control = normal,
typename ParseInput,
typename... States >
[[nodiscard]] std::unique_ptr< node > parse( ParseInput&& in, States&&... st )
{
return parse< Rule, node, Selector, Action, Control >( in, st... );
}
} // namespace TAO_PEGTL_NAMESPACE::parse_tree
#endif
<commit_msg>parse_tree::basic_node now uses template Source, defaults to string_view<commit_after>// Copyright (c) 2017-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP
#define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP
#include <cassert>
#include <memory>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <utility>
#include <vector>
#include "remove_first_state.hpp"
#include "shuffle_states.hpp"
#include "../apply_mode.hpp"
#include "../config.hpp"
#include "../demangle.hpp"
#include "../memory_input.hpp"
#include "../normal.hpp"
#include "../nothing.hpp"
#include "../parse.hpp"
#include "../rewind_mode.hpp"
#include "../internal/enable_control.hpp"
#include "../internal/has_unwind.hpp"
#include "../internal/iterator.hpp"
namespace TAO_PEGTL_NAMESPACE::parse_tree
{
template< typename T, typename Source = std::string_view >
struct basic_node
{
using node_t = T;
using children_t = std::vector< std::unique_ptr< node_t > >;
children_t children;
std::string_view type;
Source source;
TAO_PEGTL_NAMESPACE::internal::iterator m_begin;
TAO_PEGTL_NAMESPACE::internal::iterator m_end;
// each node will be default constructed
basic_node() = default;
// no copy/move is necessary
// (nodes are always owned/handled by a std::unique_ptr)
basic_node( const basic_node& ) = delete;
basic_node( basic_node&& ) = delete;
~basic_node() = default;
// no assignment either
basic_node& operator=( const basic_node& ) = delete;
basic_node& operator=( basic_node&& ) = delete;
[[nodiscard]] bool is_root() const noexcept
{
return type.empty();
}
template< typename U >
[[nodiscard]] bool is_type() const noexcept
{
return type == demangle< U >();
}
template< typename U >
void set_type() noexcept
{
type = demangle< U >();
}
[[nodiscard]] position begin() const
{
return position( m_begin, source );
}
[[nodiscard]] position end() const
{
return position( m_end, source );
}
[[nodiscard]] bool has_content() const noexcept
{
return m_end.data != nullptr;
}
[[nodiscard]] std::string_view string_view() const noexcept
{
assert( has_content() );
return std::string_view( m_begin.data, m_end.data - m_begin.data );
}
[[nodiscard]] std::string string() const
{
assert( has_content() );
return std::string( m_begin.data, m_end.data );
}
template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf >
[[nodiscard]] memory_input< P, Eol > as_memory_input() const
{
assert( has_content() );
return { m_begin.data, m_end.data, source, m_begin.byte, m_begin.line, m_begin.column };
}
template< typename... States >
void remove_content( States&&... /*unused*/ ) noexcept
{
m_end = TAO_PEGTL_NAMESPACE::internal::iterator();
}
// all non-root nodes are initialized by calling this method
template< typename Rule, typename ParseInput, typename... States >
void start( const ParseInput& in, States&&... /*unused*/ )
{
set_type< Rule >();
source = in.source();
m_begin = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() );
}
// if parsing of the rule succeeded, this method is called
template< typename Rule, typename ParseInput, typename... States >
void success( const ParseInput& in, States&&... /*unused*/ ) noexcept
{
m_end = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() );
}
// if parsing of the rule failed, this method is called
template< typename Rule, typename ParseInput, typename... States >
void failure( const ParseInput& /*unused*/, States&&... /*unused*/ ) noexcept
{}
// if parsing of the rule failed with an exception, this method is called
template< typename Rule, typename ParseInput, typename... States >
void unwind( const ParseInput& /*unused*/, States&&... /*unused*/ ) noexcept
{}
// if parsing succeeded and the (optional) transform call
// did not discard the node, it is appended to its parent.
// note that "child" is the node whose Rule just succeeded
// and "*this" is the parent where the node should be appended.
template< typename... States >
void emplace_back( std::unique_ptr< node_t >&& child, States&&... /*unused*/ )
{
assert( child );
children.emplace_back( std::move( child ) );
}
};
struct node
: basic_node< node >
{};
namespace internal
{
template< typename Node >
struct state
{
std::vector< std::unique_ptr< Node > > stack;
state()
{
emplace_back();
}
void emplace_back()
{
stack.emplace_back( std::make_unique< Node >() );
}
[[nodiscard]] std::unique_ptr< Node >& back() noexcept
{
assert( !stack.empty() );
return stack.back();
}
void pop_back() noexcept
{
assert( !stack.empty() );
return stack.pop_back();
}
};
template< typename Selector, typename... Parameters >
void transform( Parameters&&... /*unused*/ ) noexcept
{}
template< typename Selector, typename ParseInput, typename Node, typename... States >
auto transform( const ParseInput& in, std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( in, n, st... ) ) )
-> decltype( (void)Selector::transform( in, n, st... ) )
{
Selector::transform( in, n, st... );
}
template< typename Selector, typename ParseInput, typename Node, typename... States >
auto transform( const ParseInput& /*unused*/, std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( n, st... ) ) )
-> decltype( (void)Selector::transform( n, st... ) )
{
Selector::transform( n, st... );
}
template< typename Rule, template< typename... > class Selector >
inline constexpr bool is_selected_node = ( TAO_PEGTL_NAMESPACE::internal::enable_control< Rule > && Selector< Rule >::value );
template< unsigned Level, typename Subs, template< typename... > class Selector >
inline constexpr bool is_leaf{};
template< typename... Rules, template< typename... > class Selector >
inline constexpr bool is_leaf< 0, type_list< Rules... >, Selector > = ( sizeof...( Rules ) == 0 );
template< unsigned Level, typename Rule, template< typename... > class Selector >
inline constexpr bool is_unselected_branch = ( !is_selected_node< Rule, Selector > && is_leaf< Level, typename Rule::subs_t, Selector > );
template< unsigned Level, typename... Rules, template< typename... > class Selector >
inline constexpr bool is_leaf< Level, type_list< Rules... >, Selector > = ( is_unselected_branch< Level - 1, Rules, Selector > && ... );
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
struct make_control
{
template< typename Rule, bool, bool >
struct state_handler;
template< typename Rule >
using type = rotate_states_right< state_handler< Rule, is_selected_node< Rule, Selector >, is_leaf< 8, typename Rule::subs_t, Selector > > >;
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule >
struct make_control< Node, Selector, Control >::state_handler< Rule, false, true >
: remove_first_state< Control< Rule > >
{};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule >
struct make_control< Node, Selector, Control >::state_handler< Rule, false, false >
: remove_first_state< Control< Rule > >
{
static constexpr bool enable = true;
template< typename ParseInput, typename... States >
static void start( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
state.emplace_back();
}
template< typename ParseInput, typename... States >
static void success( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
auto n = std::move( state.back() );
state.pop_back();
for( auto& c : n->children ) {
state.back()->children.emplace_back( std::move( c ) );
}
}
template< typename ParseInput, typename... States >
static void failure( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
state.pop_back();
}
template< typename ParseInput, typename... States >
static void unwind( const ParseInput& /*unused*/, state< Node >& state, States&&... /*unused*/ )
{
state.pop_back();
}
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule, bool B >
struct make_control< Node, Selector, Control >::state_handler< Rule, true, B >
: remove_first_state< Control< Rule > >
{
template< typename ParseInput, typename... States >
static void start( const ParseInput& in, state< Node >& state, States&&... st )
{
Control< Rule >::start( in, st... );
state.emplace_back();
state.back()->template start< Rule >( in, st... );
}
template< typename ParseInput, typename... States >
static void success( const ParseInput& in, state< Node >& state, States&&... st )
{
auto n = std::move( state.back() );
state.pop_back();
n->template success< Rule >( in, st... );
transform< Selector< Rule > >( in, n, st... );
if( n ) {
state.back()->emplace_back( std::move( n ), st... );
}
Control< Rule >::success( in, st... );
}
template< typename ParseInput, typename... States >
static void failure( const ParseInput& in, state< Node >& state, States&&... st )
{
state.back()->template failure< Rule >( in, st... );
state.pop_back();
Control< Rule >::failure( in, st... );
}
template< typename ParseInput, typename... States >
static void unwind( const ParseInput& in, state< Node >& state, States&&... st )
{
state.back()->template unwind< Rule >( in, st... );
state.pop_back();
if constexpr( TAO_PEGTL_NAMESPACE::internal::has_unwind< Control< Rule >, void, const ParseInput&, States... > ) {
Control< Rule >::unwind( in, st... );
}
}
};
template< typename >
using store_all = std::true_type;
template< typename >
struct selector;
template< typename T >
struct selector< std::tuple< T > >
{
using type = typename T::type;
};
template< typename... Ts >
struct selector< std::tuple< Ts... > >
{
static_assert( sizeof...( Ts ) == 0, "multiple matches found" );
using type = std::false_type;
};
template< typename T >
using selector_t = typename selector< T >::type;
template< typename Rule, typename Collection >
using select_tuple = std::conditional_t< Collection::template contains< Rule >, std::tuple< Collection >, std::tuple<> >;
} // namespace internal
template< typename Rule, typename... Collections >
using selector = internal::selector_t< decltype( std::tuple_cat( std::declval< internal::select_tuple< Rule, Collections > >()... ) ) >;
template< typename Base >
struct apply
: std::true_type
{
template< typename... Rules >
struct on
{
using type = Base;
template< typename Rule >
static constexpr bool contains = ( std::is_same_v< Rule, Rules > || ... );
};
};
struct store_content
: apply< store_content >
{};
// some nodes don't need to store their content
struct remove_content
: apply< remove_content >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->Node::remove_content( st... ) ) )
{
n->remove_content( st... );
}
};
// if a node has only one child, replace the node with its child, otherwise remove content
struct fold_one
: apply< fold_one >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.size(), n->Node::remove_content( st... ) ) )
{
if( n->children.size() == 1 ) {
n = std::move( n->children.front() );
}
else {
n->remove_content( st... );
}
}
};
// if a node has no children, discard the node, otherwise remove content
struct discard_empty
: apply< discard_empty >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( (void)n->children.empty(), n->Node::remove_content( st... ) ) )
{
if( n->children.empty() ) {
n.reset();
}
else {
n->remove_content( st... );
}
}
};
template< typename Rule,
typename Node,
template< typename... > class Selector = internal::store_all,
template< typename... > class Action = nothing,
template< typename... > class Control = normal,
typename ParseInput,
typename... States >
[[nodiscard]] std::unique_ptr< Node > parse( ParseInput&& in, States&&... st )
{
internal::state< Node > state;
if( !TAO_PEGTL_NAMESPACE::parse< Rule, Action, internal::make_control< Node, Selector, Control >::template type >( in, st..., state ) ) {
return nullptr;
}
assert( state.stack.size() == 1 );
return std::move( state.back() );
}
template< typename Rule,
template< typename... > class Selector = internal::store_all,
template< typename... > class Action = nothing,
template< typename... > class Control = normal,
typename ParseInput,
typename... States >
[[nodiscard]] std::unique_ptr< node > parse( ParseInput&& in, States&&... st )
{
return parse< Rule, node, Selector, Action, Control >( in, st... );
}
} // namespace TAO_PEGTL_NAMESPACE::parse_tree
#endif
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::Circuit;
using ::tfq::CircuitFromProgram;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;
class TfqSimulateStateOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateStateOp(tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
DCHECK_EQ(3, context->num_inputs());
std::vector<Program> programs;
std::vector<int> num_qubits;
OP_REQUIRES_OK(context,
GetProgramsAndNumQubits(context, &programs, &num_qubits));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(
context, maps.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and values do not match. Got ", programs.size(),
" circuits and ", maps.size(), " values.")));
int max_num_qubits = 0;
for (const int num : num_qubits) {
max_num_qubits = std::max(max_num_qubits, num);
}
// TODO(pmassey): Investigate creating a matrix that isn't just the maximum
// required size.
const int output_dim_size = maps.size();
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_size);
output_shape.AddDim(1 << max_num_qubits);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<std::complex<float>>();
auto DoWork = [&](int start, int end) {
std::unique_ptr<StateSpace> state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
int old_num_qubits = -1;
for (int i = start; i < end; i++) {
Program program = programs[i];
const int num = num_qubits[i];
OP_REQUIRES_OK(context, ResolveSymbols(maps[i], &program));
// QSim work below
Circuit circuit;
OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));
// TODO(mbbrough): Update this allocation hack so that a StateSpace
// object can grow it's memory dynamically to larger and larger size
// without ever having to call free (until the very end). This is
// tricky to implement because right now certain statespaces can't
// simulate all states and we use StateSpaceSlow for smaller circuits.
if (num != old_num_qubits) {
state.reset(GetStateSpace(num, 1));
state->CreateState();
}
state->SetStateZero();
OP_REQUIRES_OK(context, state->Update(circuit));
uint64_t state_size = state->GetDimension();
for (uint64_t j = 0; j < state_size; j++) {
output_tensor(i, j) = state->GetAmpl(j);
}
for (uint64_t j = state_size; j < (uint64_t(1) << max_num_qubits);
j++) {
output_tensor(i, j) = std::complex<float>(-2, 0);
}
old_num_qubits = num;
}
};
const int block_size = GetBlockSize(context, output_dim_size);
context->device()
->tensorflow_cpu_worker_threads()
->workers->TransformRangeConcurrently(block_size, output_dim_size,
DoWork);
}
};
REGISTER_KERNEL_BUILDER(Name("TfqSimulateState").Device(tensorflow::DEVICE_CPU),
TfqSimulateStateOp);
REGISTER_OP("TfqSimulateState")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Output("wavefunction: complex64")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
// TODO(pmassey): Which output dimension size matters? Does this allocate
// any memory or gives hints to the graph building? I apparently just set
// this as rows in the previous run and that seemed to work.
tensorflow::shape_inference::DimensionHandle output_rows =
c->Dim(symbol_values_shape, 0);
tensorflow::shape_inference::DimensionHandle output_cols =
c->Dim(symbol_values_shape, 1);
c->set_output(0, c->Matrix(output_rows, output_cols));
return tensorflow::Status::OK();
});
} // namespace tfq
<commit_msg>Fixed state op shapeinference shaping. (#170)<commit_after>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::Circuit;
using ::tfq::CircuitFromProgram;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;
class TfqSimulateStateOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateStateOp(tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
DCHECK_EQ(3, context->num_inputs());
std::vector<Program> programs;
std::vector<int> num_qubits;
OP_REQUIRES_OK(context,
GetProgramsAndNumQubits(context, &programs, &num_qubits));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(
context, maps.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and values do not match. Got ", programs.size(),
" circuits and ", maps.size(), " values.")));
int max_num_qubits = 0;
for (const int num : num_qubits) {
max_num_qubits = std::max(max_num_qubits, num);
}
// TODO(pmassey): Investigate creating a matrix that isn't just the maximum
// required size.
const int output_dim_size = maps.size();
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_size);
output_shape.AddDim(1 << max_num_qubits);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<std::complex<float>>();
auto DoWork = [&](int start, int end) {
std::unique_ptr<StateSpace> state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
int old_num_qubits = -1;
for (int i = start; i < end; i++) {
Program program = programs[i];
const int num = num_qubits[i];
OP_REQUIRES_OK(context, ResolveSymbols(maps[i], &program));
// QSim work below
Circuit circuit;
OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));
// TODO(mbbrough): Update this allocation hack so that a StateSpace
// object can grow it's memory dynamically to larger and larger size
// without ever having to call free (until the very end). This is
// tricky to implement because right now certain statespaces can't
// simulate all states and we use StateSpaceSlow for smaller circuits.
if (num != old_num_qubits) {
state.reset(GetStateSpace(num, 1));
state->CreateState();
}
state->SetStateZero();
OP_REQUIRES_OK(context, state->Update(circuit));
uint64_t state_size = state->GetDimension();
for (uint64_t j = 0; j < state_size; j++) {
output_tensor(i, j) = state->GetAmpl(j);
}
for (uint64_t j = state_size; j < (uint64_t(1) << max_num_qubits);
j++) {
output_tensor(i, j) = std::complex<float>(-2, 0);
}
old_num_qubits = num;
}
};
const int block_size = GetBlockSize(context, output_dim_size);
context->device()
->tensorflow_cpu_worker_threads()
->workers->TransformRangeConcurrently(block_size, output_dim_size,
DoWork);
}
};
REGISTER_KERNEL_BUILDER(Name("TfqSimulateState").Device(tensorflow::DEVICE_CPU),
TfqSimulateStateOp);
REGISTER_OP("TfqSimulateState")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Output("wavefunction: complex64")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
c->set_output(
0, c->MakeShape(
{c->Dim(programs_shape, 0),
tensorflow::shape_inference::InferenceContext::kUnknownDim}));
return tensorflow::Status::OK();
});
} // namespace tfq
<|endoftext|> |
<commit_before>/*
* Copyright 2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log$
* Revision 1.4 2004/09/08 13:56:47 peiyongz
* Apache License Version 2.0
*
* Revision 1.3 2002/12/24 17:59:07 tng
* Build with ICU 2.4
*
* Revision 1.2 2002/11/04 15:17:01 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:34 peiyongz
* sane_include
*
* Revision 1.2 2001/05/11 13:26:52 tng
* Copyright update.
*
* Revision 1.1 2001/03/02 19:26:51 knoaman
* Schema: Regular expression handling part II
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/XMLUniCharacter.hpp>
#if defined (XML_USE_ICU_TRANSCODER)
#include <unicode/uchar.h>
#else
#include <xercesc/util/regx/UniCharTable.hpp>
#endif
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XMLUniCharacter: Public static methods
// ---------------------------------------------------------------------------
unsigned short XMLUniCharacter::getType(const XMLCh ch) {
#if defined (XML_USE_ICU_TRANSCODER)
return (unsigned short) u_charType(ch);
#else
return (unsigned short) fgUniCharsTable[ch];
#endif
}
XERCES_CPP_NAMESPACE_END
/**
* End of file XMLUniCharacter.cpp
*/
<commit_msg>390 update: use ICU table which is present with the uniconv390.<commit_after>/*
* Copyright 2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log$
* Revision 1.5 2005/05/19 15:46:32 cargilld
* 390 update: use ICU table which is present with the uniconv390.
*
* Revision 1.4 2004/09/08 13:56:47 peiyongz
* Apache License Version 2.0
*
* Revision 1.3 2002/12/24 17:59:07 tng
* Build with ICU 2.4
*
* Revision 1.2 2002/11/04 15:17:01 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:34 peiyongz
* sane_include
*
* Revision 1.2 2001/05/11 13:26:52 tng
* Copyright update.
*
* Revision 1.1 2001/03/02 19:26:51 knoaman
* Schema: Regular expression handling part II
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/XMLUniCharacter.hpp>
#if defined (XML_USE_ICU_TRANSCODER) || defined (XML_USE_UNICONV390_TRANSCODER)
#include <unicode/uchar.h>
#else
#include <xercesc/util/regx/UniCharTable.hpp>
#endif
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XMLUniCharacter: Public static methods
// ---------------------------------------------------------------------------
unsigned short XMLUniCharacter::getType(const XMLCh ch) {
#if defined (XML_USE_ICU_TRANSCODER) || defined (XML_USE_UNICONV390_TRANSCODER)
return (unsigned short) u_charType(ch);
#else
return (unsigned short) fgUniCharsTable[ch];
#endif
}
XERCES_CPP_NAMESPACE_END
/**
* End of file XMLUniCharacter.cpp
*/
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: sdrmediawindow.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-08-12 09:04:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SDR_CONTACT_SDRMEDIAWIMNDOW_HXX
#include <avmedia/mediawindow.hxx>
namespace sdr { namespace contact {
// ------------------
// - SdrMediaWindow -
// ------------------
class ViewObjectContactOfSdrMediaObj;
class SdrMediaWindow : public ::avmedia::MediaWindow
{
public:
SdrMediaWindow( Window* pParent, ViewObjectContactOfSdrMediaObj& rViewObjContact );
~SdrMediaWindow();
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void KeyUp( const KeyEvent& rKEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );
private:
ViewObjectContactOfSdrMediaObj& mrViewObjectContactOfSdrMediaObj;
};
} }
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.732); FILE MERGED 2005/09/05 14:26:28 rt 1.2.732.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdrmediawindow.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:03:42 $
*
* 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 _SDR_CONTACT_SDRMEDIAWIMNDOW_HXX
#include <avmedia/mediawindow.hxx>
namespace sdr { namespace contact {
// ------------------
// - SdrMediaWindow -
// ------------------
class ViewObjectContactOfSdrMediaObj;
class SdrMediaWindow : public ::avmedia::MediaWindow
{
public:
SdrMediaWindow( Window* pParent, ViewObjectContactOfSdrMediaObj& rViewObjContact );
~SdrMediaWindow();
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void KeyUp( const KeyEvent& rKEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );
private:
ViewObjectContactOfSdrMediaObj& mrViewObjectContactOfSdrMediaObj;
};
} }
#endif
<|endoftext|> |
<commit_before>#include "kernel.h"
#include "geometries.h"
#include "ilwisobject.h"
#include "ilwisdata.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "georefimplementation.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"
using namespace Ilwis;
CornersGeoReference::CornersGeoReference() : SimpelGeoReference("corners")
{
}
GeoRefImplementation *CornersGeoReference::create()
{
return new CornersGeoReference();
}
void CornersGeoReference::envelope(const Envelope &env)
{
_envelope = env;
}
bool CornersGeoReference::compute()
{
bool a = size().isNull();
bool b = _envelope.isValid();
if (a || !b)
return false;
_a12 = _a21 = 0;
std::vector<double> vec = _envelope.max_corner() - _envelope.min_corner();
if (abs(vec[0]) < 1e-6 || abs(vec[1]) < 1e-6) {
return false;
}
if (!_centerOfPixel) { // corners of corner pixels
_a11 = size().xsize() / vec[0];
double tempy = size().ysize();
_a22 = - tempy / vec[1];
_b1 = - _a11 * _envelope.min_corner().x;
_b2 = - _a22 * _envelope.max_corner().y;
}
else { // center of corner pixels
_a11 = (size().xsize() - 1) / vec[0];
double v1 = size().ysize() - 1;
double v2 = vec[1];
double v3 = -v1/v2;
_a22 = v3;
_b1 = 0.5 - _a11 * _envelope.min_corner().x;
_b2 = 0.5 - _a22 * _envelope.max_corner().y;
}
_det = _a11 * _a22;
return true;
}
Envelope CornersGeoReference::envelope() const
{
return _envelope;
}
QString CornersGeoReference::typeName()
{
return "corners";
}
<commit_msg>some wierdness with the compiler prevented the orignal test to succeed. rewrote it to a working version<commit_after>#include "kernel.h"
#include "geometries.h"
#include "ilwisobject.h"
#include "ilwisdata.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "georefimplementation.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"
using namespace Ilwis;
CornersGeoReference::CornersGeoReference() : SimpelGeoReference("corners")
{
}
GeoRefImplementation *CornersGeoReference::create()
{
return new CornersGeoReference();
}
void CornersGeoReference::envelope(const Envelope &env)
{
_envelope = env;
}
bool CornersGeoReference::compute()
{
bool a = size().isNull();
bool b = _envelope.isValid();
if (a || !b)
return false;
_a12 = _a21 = 0;
std::vector<double> vec = _envelope.max_corner() - _envelope.min_corner();
bool deltaxSmall = (std::abs(vec[0]) < 0.0000001);
bool deltaySmall = (std::abs(vec[1]) < 0.0000001);
if ( deltaxSmall || deltaySmall) {
return false;
}
if (!_centerOfPixel) { // corners of corner pixels
_a11 = size().xsize() / vec[0];
double tempy = size().ysize();
_a22 = - tempy / vec[1];
_b1 = - _a11 * _envelope.min_corner().x;
_b2 = - _a22 * _envelope.max_corner().y;
}
else { // center of corner pixels
_a11 = (size().xsize() - 1) / vec[0];
double v1 = size().ysize() - 1;
double v2 = vec[1];
double v3 = -v1/v2;
_a22 = v3;
_b1 = 0.5 - _a11 * _envelope.min_corner().x;
_b2 = 0.5 - _a22 * _envelope.max_corner().y;
}
_det = _a11 * _a22;
return true;
}
Envelope CornersGeoReference::envelope() const
{
return _envelope;
}
QString CornersGeoReference::typeName()
{
return "corners";
}
<|endoftext|> |
<commit_before>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2013 Steven Lovegrove
*
* 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 <pangolin/input_record_repeat.h>
using namespace std;
namespace pangolin
{
InputRecordRepeat::InputRecordRepeat(const std::string& var_record_prefix)
: record(false), play(false), index(-1)
{
RegisterGuiVarChangedCallback(&InputRecordRepeat::GuiVarChanged,(void*)this,var_record_prefix);
}
InputRecordRepeat::~InputRecordRepeat()
{
}
void InputRecordRepeat::SetIndex(int id)
{
// if( id < index )
// Clear();
index = id;
while( !play_queue.empty() && play_queue.front().index < index )
{
// 'Play' Frameinput
FrameInput in = play_queue.front();
play_queue.pop_front();
Var<std::string> var(in.var);
var = in.val;
}
}
void InputRecordRepeat::Record()
{
ClearBuffer();
play = false;
record = true;
}
void InputRecordRepeat::Stop()
{
record = false;
play = false;
}
void InputRecordRepeat::ClearBuffer()
{
index = -1;
record_queue.clear();
play_queue.clear();
}
ostream& operator<<(ostream& os, const FrameInput& fi )
{
os << fi.index << endl << fi.var << endl << fi.val << endl;
return os;
}
istream& operator>>(istream& is, FrameInput& fi)
{
is >> fi.index;
is.ignore(std::numeric_limits<streamsize>::max(),'\n');
getline(is,fi.var);
getline(is,fi.val);
return is;
}
void InputRecordRepeat::SaveBuffer(const std::string& filename)
{
ofstream f(filename.c_str());
for( std::list<FrameInput>::const_iterator i = record_queue.begin(); i!=record_queue.end(); ++i )
{
f << *i;
}
}
void InputRecordRepeat::LoadBuffer(const std::string& filename)
{
record_queue.clear();
ifstream f(filename.c_str());
while(f.good())
{
FrameInput fi;
f >> fi;
if( f.good() )
record_queue.push_back(fi);
}
}
void InputRecordRepeat::PlayBuffer()
{
play_queue = record_queue;
record = false;
play = true;
}
void InputRecordRepeat::PlayBuffer(int start, int end)
{
std::list<FrameInput>::iterator s = record_queue.begin();
std::list<FrameInput>::iterator e = record_queue.begin();
for(int i=0; i<start; i++) s++;
for(int i=0; i<end; i++) e++;
play_queue.clear();
play_queue.insert(play_queue.begin(),s,e);
record = false;
play = true;
}
int InputRecordRepeat::Size()
{
return record_queue.size();
}
void InputRecordRepeat::UpdateVariable(const std::string& name )
{
Var<std::string> var(name);
if( record )
{
FrameInput input;
input.index = index;
input.var = name;
input.val = var.a->Get();
record_queue.push_back(input);
}
}
void InputRecordRepeat::GuiVarChanged(void* data, const std::string& name, _Var& _var)
{
InputRecordRepeat* thisptr = (InputRecordRepeat*)data;
if( thisptr->record )
{
Var<std::string> var(_var);
FrameInput input;
input.index = thisptr->index;
input.var = name;
input.val = var.a->Get();
thisptr->record_queue.push_back(input);
}
}
}
<commit_msg>Include missing header file.<commit_after>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2013 Steven Lovegrove
*
* 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 <pangolin/input_record_repeat.h>
#include <limits>
using namespace std;
namespace pangolin
{
InputRecordRepeat::InputRecordRepeat(const std::string& var_record_prefix)
: record(false), play(false), index(-1)
{
RegisterGuiVarChangedCallback(&InputRecordRepeat::GuiVarChanged,(void*)this,var_record_prefix);
}
InputRecordRepeat::~InputRecordRepeat()
{
}
void InputRecordRepeat::SetIndex(int id)
{
// if( id < index )
// Clear();
index = id;
while( !play_queue.empty() && play_queue.front().index < index )
{
// 'Play' Frameinput
FrameInput in = play_queue.front();
play_queue.pop_front();
Var<std::string> var(in.var);
var = in.val;
}
}
void InputRecordRepeat::Record()
{
ClearBuffer();
play = false;
record = true;
}
void InputRecordRepeat::Stop()
{
record = false;
play = false;
}
void InputRecordRepeat::ClearBuffer()
{
index = -1;
record_queue.clear();
play_queue.clear();
}
ostream& operator<<(ostream& os, const FrameInput& fi )
{
os << fi.index << endl << fi.var << endl << fi.val << endl;
return os;
}
istream& operator>>(istream& is, FrameInput& fi)
{
is >> fi.index;
is.ignore(std::numeric_limits<streamsize>::max(),'\n');
getline(is,fi.var);
getline(is,fi.val);
return is;
}
void InputRecordRepeat::SaveBuffer(const std::string& filename)
{
ofstream f(filename.c_str());
for( std::list<FrameInput>::const_iterator i = record_queue.begin(); i!=record_queue.end(); ++i )
{
f << *i;
}
}
void InputRecordRepeat::LoadBuffer(const std::string& filename)
{
record_queue.clear();
ifstream f(filename.c_str());
while(f.good())
{
FrameInput fi;
f >> fi;
if( f.good() )
record_queue.push_back(fi);
}
}
void InputRecordRepeat::PlayBuffer()
{
play_queue = record_queue;
record = false;
play = true;
}
void InputRecordRepeat::PlayBuffer(int start, int end)
{
std::list<FrameInput>::iterator s = record_queue.begin();
std::list<FrameInput>::iterator e = record_queue.begin();
for(int i=0; i<start; i++) s++;
for(int i=0; i<end; i++) e++;
play_queue.clear();
play_queue.insert(play_queue.begin(),s,e);
record = false;
play = true;
}
int InputRecordRepeat::Size()
{
return record_queue.size();
}
void InputRecordRepeat::UpdateVariable(const std::string& name )
{
Var<std::string> var(name);
if( record )
{
FrameInput input;
input.index = index;
input.var = name;
input.val = var.a->Get();
record_queue.push_back(input);
}
}
void InputRecordRepeat::GuiVarChanged(void* data, const std::string& name, _Var& _var)
{
InputRecordRepeat* thisptr = (InputRecordRepeat*)data;
if( thisptr->record )
{
Var<std::string> var(_var);
FrameInput input;
input.index = thisptr->index;
input.var = name;
input.val = var.a->Get();
thisptr->record_queue.push_back(input);
}
}
}
<|endoftext|> |
<commit_before>/* Please refer to license.txt */
#include "interface.hpp"
#include <iostream>
#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"
#include "../file/file.hpp"
namespace GEngine
{
namespace mui
{
Interface::Interface()
{
//d2d = nullptr;
cegui_system = nullptr;
cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
cegui_logfile_path = CEGUI_LOGFILE_PATH;
cegui_schemes_path = CEGUI_SCHEMES_PATH;
cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
cegui_fonts_path = CEGUI_FONTS_PATH;
cegui_layouts_path = CEGUI_LAYOUTS_PATH;
cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;
cegui_resourceprovider = nullptr;
//cegui_root_window = nullptr;
//cegui_windowmanager = nullptr;
}
Interface::~Interface()
{
/*if (d2d)
{
d2d = nullptr;
}
if (cegui_root_window)
{
delete cegui_root_window;
}*/
cegui_system = nullptr;
cegui_resourceprovider = nullptr;
}
bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
//d2d = &_d2d;
//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.
try
{
CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();
std::string log_directory("");
mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
if (!mfile::FileManager::directoryExists(log_directory))
{
mfile::FileManager::mkDir(log_directory);
}
CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);
//Initialise the required dirs for the CEGUI DefaultResourceProvider.
cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
//Set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
//This is only needed if the resourceprovider's schemas is set.
//Setup default group for validation schemas.
//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
//{
// parser->setProperty("SchemaDefaultResourceGroup", "schemas");
//}
//Load the schemes specified in cegui_schemes.
for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
{
CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
}
//TODO: Handle the mouse.
/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/
//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.
sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);
//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
mapSFMLKeysToCEGUI();
mapSFMLMouseToCEGUI();
d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
d2d.cegui_renderer = &myRenderer;
d2d.default_d2d = true;
}
catch(CEGUI::Exception& e)
{
std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
return false;
}
addD2D(d2d); //Add the D2D to the list of D2Ds.
return true; //Success.
}
bool Interface::loadFont(std::string filepath)
{
font.loadFromFile(filepath);
return true;
}
void Interface::update()
{
std::vector<mgfx::d2d::D2D* >::iterator iter = windows.begin();
for (int i = 0; iter != windows.end(); ++iter, ++i)
{
mgfx::d2d::D2D *d2d = (*iter); //First point to this so I don't have to type crazy things every time.
CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.
context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.
//Now, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
}
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.
/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
//First, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
//onMouseButtonUp //Use this to check if the frame window's button was pressed.
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}
CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
//return cegui_root_window;
return d2d.getRootWindow();
}
void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
/*cegui_root_window = window;
CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
d2d.cegui_root_window = window;
d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}
CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
/*if (root) //If it's supposed to be the root window...
{
setRootWindow(window); //Set it.
}*/
return window;
}
void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
if (!d2d.cegui_renderer)
{
d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
}
if (!d2d.cegui_gui_context)
{
d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
}
windows.push_back(&d2d);
}
} //namespace mui
} //namespace GEngine
<commit_msg>Debugging something.<commit_after>/* Please refer to license.txt */
#include "interface.hpp"
#include <iostream>
#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"
#include "../file/file.hpp"
namespace GEngine
{
namespace mui
{
Interface::Interface()
{
//d2d = nullptr;
cegui_system = nullptr;
cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
cegui_logfile_path = CEGUI_LOGFILE_PATH;
cegui_schemes_path = CEGUI_SCHEMES_PATH;
cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
cegui_fonts_path = CEGUI_FONTS_PATH;
cegui_layouts_path = CEGUI_LAYOUTS_PATH;
cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;
cegui_resourceprovider = nullptr;
//cegui_root_window = nullptr;
//cegui_windowmanager = nullptr;
}
Interface::~Interface()
{
/*if (d2d)
{
d2d = nullptr;
}
if (cegui_root_window)
{
delete cegui_root_window;
}*/
cegui_system = nullptr;
cegui_resourceprovider = nullptr;
}
bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
//d2d = &_d2d;
//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.
try
{
CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();
std::string log_directory("");
mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
if (!mfile::FileManager::directoryExists(log_directory))
{
mfile::FileManager::mkDir(log_directory);
}
CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);
//Initialise the required dirs for the CEGUI DefaultResourceProvider.
cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
//Set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
//This is only needed if the resourceprovider's schemas is set.
//Setup default group for validation schemas.
//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
//{
// parser->setProperty("SchemaDefaultResourceGroup", "schemas");
//}
//Load the schemes specified in cegui_schemes.
for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
{
CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
}
//TODO: Handle the mouse.
/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/
//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.
sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);
//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
mapSFMLKeysToCEGUI();
mapSFMLMouseToCEGUI();
d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
d2d.cegui_renderer = &myRenderer;
d2d.default_d2d = true;
}
catch(CEGUI::Exception& e)
{
std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
return false;
}
addD2D(d2d); //Add the D2D to the list of D2Ds.
return true; //Success.
}
bool Interface::loadFont(std::string filepath)
{
font.loadFromFile(filepath);
return true;
}
void Interface::update()
{
std::vector<mgfx::d2d::D2D* >::iterator iter = windows.begin();
//for (int i = 0; iter != windows.end(); ++iter, ++i)
for (int i = 0; i < windows.size(); ++i)
{
//mgfx::d2d::D2D *d2d = (*iter); //First point to this so I don't have to type crazy things every time.
mgfx::d2d::D2D *d2d = windows[i]; //First point to this so I don't have to type crazy things every time.
CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.
context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.
//Now, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
}
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.
/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
//First, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
//onMouseButtonUp //Use this to check if the frame window's button was pressed.
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}
CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
//return cegui_root_window;
return d2d.getRootWindow();
}
void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
/*cegui_root_window = window;
CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
d2d.cegui_root_window = window;
d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}
CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
/*if (root) //If it's supposed to be the root window...
{
setRootWindow(window); //Set it.
}*/
return window;
}
void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
if (!d2d.cegui_renderer)
{
d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
}
if (!d2d.cegui_gui_context)
{
d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
}
windows.push_back(&d2d);
}
} //namespace mui
} //namespace GEngine
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: printdlg.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2008-01-29 16:11:22 $
*
* 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 _SV_PRINTDLG_HXX_
#define _SV_PRINTDLG_HXX_
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _VCL_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _VCL_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _VCL_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _VCL_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _VCL_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _VCL_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _VCL_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
class Printer;
class QueueInfo;
struct SvtPrinterImpl;
// ---------------------
// - PrintDialog-Types -
// ---------------------
enum PrintDialogRange{
PRINTDIALOG_ALL, PRINTDIALOG_SELECTION, PRINTDIALOG_FROMTO, PRINTDIALOG_RANGE };
enum PrintSheetRange
{
PRINTSHEETS_ALL,
PRINTSHEETS_SELECTED_SHEETS,
PRINTSHEETS_SELECTED_CELLS
};
// ---------------
// - PrintDialog -
// ---------------
class SVT_DLLPUBLIC PrintDialog : public ModalDialog
{
private:
FixedLine maFlPrinter;
FixedText maFtName;
ListBox maLbName;
PushButton maBtnProperties;
FixedText maFtStatus;
FixedInfo maFiStatus;
FixedText maFtType;
FixedInfo maFiType;
FixedText maFtLocation;
FixedInfo maFiLocation;
FixedText maFtComment;
FixedInfo maFiComment;
// "Print to file" or "Fax number"
CheckBox maCbxFilePrint;
FixedInfo maFiPrintFile;
FixedText maFiFaxNo;
Edit maEdtFaxNo;
//PushButton maBtnBrowse_nomore;
// "Print"
FixedLine maFlPrint;
RadioButton maRbtAllSheets;
RadioButton maRbtSelectedSheets;
RadioButton maRbtSelectedCells;
// "Print range"
FixedLine maFlPrintRange;
RadioButton maRbtAll;
RadioButton maRbtPages;
RadioButton maRbtSelection;
Edit maEdtPages;
FixedLine maFlSepCopiesRange;
// "Copies"
FixedLine maFlCopies;
FixedText maFtCopies;
NumericField maNumCopies;
FixedImage maImgCollate;
FixedImage maImgNotCollate;
CheckBox maCbxCollate;
FixedLine maFlSepButtonLine;
PushButton maBtnOptions;
OKButton maBtnOK;
CancelButton maBtnCancel;
HelpButton maBtnHelp;
AutoTimer maStatusTimer;
Printer* mpPrinter;
SvtPrinterImpl* mpPrinterImpl;
XubString maRangeText;
USHORT mnCopyCount;
USHORT mnFirstPage;
USHORT mnLastPage;
USHORT mnMinPage;
USHORT mnMaxPage;
PrintDialogRange meCheckRange;
BOOL mbAll;
BOOL mbSelection;
BOOL mbFromTo;
BOOL mbRange;
BOOL mbCollate;
BOOL mbCollateCheck;
BOOL mbOptions;
bool mbWithSheetsAndCells;
Link maOptionsHdlLink; // Link zum Options-Handler
Link maOKHdlLink; // Link zum OK-Handler
String maAllFilterStr;
SVT_DLLPRIVATE void ImplCheckOK();
SVT_DLLPRIVATE void ImplInitControls();
SVT_DLLPRIVATE void ImplFillDialogData();
SVT_DLLPRIVATE void ImplSetInfo();
SVT_DLLPRIVATE void ImplSetImages();
SVT_DLLPRIVATE bool ImplGetFilename();
DECL_DLLPRIVATE_LINK( ImplPropertiesHdl, void* );
DECL_DLLPRIVATE_LINK( ImplChangePrinterHdl, void* );
DECL_DLLPRIVATE_LINK( ImplModifyControlHdl, void* );
DECL_DLLPRIVATE_LINK( ImplStatusHdl, Timer* );
public:
PrintDialog( Window* pWindow, bool bWithSheetsAndCells );
~PrintDialog();
virtual long OK();
virtual long ClickOptionsHdl();
void SetPrinter( Printer* pNewPrinter ) { mpPrinter = pNewPrinter; }
Printer* GetPrinter() const { return mpPrinter; }
inline bool IsSheetRangeAvailable() const { return mbWithSheetsAndCells; }
void EnableSheetRange( bool bEnable, PrintSheetRange eRange );
bool IsSheetRangeEnabled( PrintSheetRange eRange ) const;
void CheckSheetRange( PrintSheetRange eRange );
PrintSheetRange GetCheckedSheetRange() const;
bool IsSheetRangeChecked( PrintSheetRange eRange ) const;
void EnableRange( PrintDialogRange eRange );
void DisableRange( PrintDialogRange eRange );
BOOL IsRangeEnabled( PrintDialogRange eRange ) const;
void CheckRange( PrintDialogRange eRange = PRINTDIALOG_ALL )
{ meCheckRange = eRange; }
PrintDialogRange GetCheckedRange() const { return meCheckRange; }
BOOL IsRangeChecked( PrintDialogRange eRange ) const;
void SetRangeText( const XubString& rRange ) { maRangeText = rRange; }
const XubString& GetRangeText() const { return maRangeText; }
void SetFirstPage( USHORT nPage = 0 );
USHORT GetFirstPage() const { return mnFirstPage; }
void SetLastPage( USHORT nPage = 0 );
USHORT GetLastPage() const { return mnLastPage; }
void SetMinPage( USHORT nPage = 1 ) { mnMinPage = nPage; }
USHORT GetMinPage() const { return mnMinPage; }
void SetMaxPage( USHORT nPage = 65535 ) { mnMaxPage = nPage; }
USHORT GetMaxPage() const { return mnMaxPage; }
void SetCopyCount( USHORT nCopies = 1 ) { mnCopyCount = nCopies; }
USHORT GetCopyCount() const { return mnCopyCount; }
void EnableCollate( BOOL bEnable = TRUE )
{ mbCollate = bEnable; }
BOOL IsCollateEnabled() const { return mbCollate; }
void CheckCollate( BOOL bCheck = TRUE )
{ mbCollateCheck = bCheck; }
BOOL IsCollateChecked() const { return mbCollateCheck; }
void ShowOptionsButton( BOOL bShow = TRUE )
{ mbOptions = bShow; }
BOOL IsOptionsButtonVisible() const { return mbOptions; }
void SetOptionsHdl( const Link& rLink ) { maOptionsHdlLink = rLink; }
const Link& GetOptionsHdl() const { return maOptionsHdlLink; }
void SetOKHdl( const Link& rLink ) { maOKHdlLink = rLink; }
const Link& GetOKHdl() const { return maOKHdlLink; }
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual long Notify( NotifyEvent& rNEvt );
virtual short Execute();
void DisableHelp();
};
inline void PrintDialog::EnableRange( PrintDialogRange eRange )
{
if ( eRange == PRINTDIALOG_ALL )
mbAll = TRUE;
else if ( eRange == PRINTDIALOG_SELECTION )
mbSelection = TRUE;
else if ( eRange == PRINTDIALOG_FROMTO )
mbFromTo = TRUE;
else
mbRange = TRUE;
}
inline void PrintDialog::DisableRange( PrintDialogRange eRange )
{
if ( eRange == PRINTDIALOG_ALL )
mbAll = FALSE;
else if ( eRange == PRINTDIALOG_SELECTION )
mbSelection = FALSE;
else if ( eRange == PRINTDIALOG_FROMTO )
mbFromTo = FALSE;
else
mbRange = FALSE;
}
inline BOOL PrintDialog::IsRangeEnabled( PrintDialogRange eRange ) const
{
BOOL bRet;
if ( eRange == PRINTDIALOG_ALL )
bRet = mbAll;
else if ( eRange == PRINTDIALOG_SELECTION )
bRet = mbSelection;
else if ( eRange == PRINTDIALOG_FROMTO )
bRet = mbFromTo;
else
bRet = mbRange;
return bRet;
}
inline BOOL PrintDialog::IsRangeChecked( PrintDialogRange eRange ) const
{
if ( eRange == meCheckRange )
return TRUE;
else
return FALSE;
}
inline void PrintDialog::SetFirstPage( USHORT nPage )
{
mnFirstPage = nPage;
if ( nPage && (nPage < mnMinPage) )
mnMinPage = nPage;
}
inline void PrintDialog::SetLastPage( USHORT nPage )
{
mnLastPage = nPage;
if ( nPage && (nPage > mnMaxPage) )
mnMaxPage = nPage;
}
#endif // _SV_PRINTDLG_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.74); FILE MERGED 2008/04/01 12:43:14 thb 1.4.74.2: #i85898# Stripping all external header guards 2008/03/31 13:01:07 rt 1.4.74.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: printdlg.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SV_PRINTDLG_HXX_
#define _SV_PRINTDLG_HXX_
#include "svtools/svtdllapi.h"
#ifndef _VCL_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _VCL_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _VCL_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _VCL_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _VCL_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _VCL_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _VCL_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#include <svtools/stdctrl.hxx>
class Printer;
class QueueInfo;
struct SvtPrinterImpl;
// ---------------------
// - PrintDialog-Types -
// ---------------------
enum PrintDialogRange{
PRINTDIALOG_ALL, PRINTDIALOG_SELECTION, PRINTDIALOG_FROMTO, PRINTDIALOG_RANGE };
enum PrintSheetRange
{
PRINTSHEETS_ALL,
PRINTSHEETS_SELECTED_SHEETS,
PRINTSHEETS_SELECTED_CELLS
};
// ---------------
// - PrintDialog -
// ---------------
class SVT_DLLPUBLIC PrintDialog : public ModalDialog
{
private:
FixedLine maFlPrinter;
FixedText maFtName;
ListBox maLbName;
PushButton maBtnProperties;
FixedText maFtStatus;
FixedInfo maFiStatus;
FixedText maFtType;
FixedInfo maFiType;
FixedText maFtLocation;
FixedInfo maFiLocation;
FixedText maFtComment;
FixedInfo maFiComment;
// "Print to file" or "Fax number"
CheckBox maCbxFilePrint;
FixedInfo maFiPrintFile;
FixedText maFiFaxNo;
Edit maEdtFaxNo;
//PushButton maBtnBrowse_nomore;
// "Print"
FixedLine maFlPrint;
RadioButton maRbtAllSheets;
RadioButton maRbtSelectedSheets;
RadioButton maRbtSelectedCells;
// "Print range"
FixedLine maFlPrintRange;
RadioButton maRbtAll;
RadioButton maRbtPages;
RadioButton maRbtSelection;
Edit maEdtPages;
FixedLine maFlSepCopiesRange;
// "Copies"
FixedLine maFlCopies;
FixedText maFtCopies;
NumericField maNumCopies;
FixedImage maImgCollate;
FixedImage maImgNotCollate;
CheckBox maCbxCollate;
FixedLine maFlSepButtonLine;
PushButton maBtnOptions;
OKButton maBtnOK;
CancelButton maBtnCancel;
HelpButton maBtnHelp;
AutoTimer maStatusTimer;
Printer* mpPrinter;
SvtPrinterImpl* mpPrinterImpl;
XubString maRangeText;
USHORT mnCopyCount;
USHORT mnFirstPage;
USHORT mnLastPage;
USHORT mnMinPage;
USHORT mnMaxPage;
PrintDialogRange meCheckRange;
BOOL mbAll;
BOOL mbSelection;
BOOL mbFromTo;
BOOL mbRange;
BOOL mbCollate;
BOOL mbCollateCheck;
BOOL mbOptions;
bool mbWithSheetsAndCells;
Link maOptionsHdlLink; // Link zum Options-Handler
Link maOKHdlLink; // Link zum OK-Handler
String maAllFilterStr;
SVT_DLLPRIVATE void ImplCheckOK();
SVT_DLLPRIVATE void ImplInitControls();
SVT_DLLPRIVATE void ImplFillDialogData();
SVT_DLLPRIVATE void ImplSetInfo();
SVT_DLLPRIVATE void ImplSetImages();
SVT_DLLPRIVATE bool ImplGetFilename();
DECL_DLLPRIVATE_LINK( ImplPropertiesHdl, void* );
DECL_DLLPRIVATE_LINK( ImplChangePrinterHdl, void* );
DECL_DLLPRIVATE_LINK( ImplModifyControlHdl, void* );
DECL_DLLPRIVATE_LINK( ImplStatusHdl, Timer* );
public:
PrintDialog( Window* pWindow, bool bWithSheetsAndCells );
~PrintDialog();
virtual long OK();
virtual long ClickOptionsHdl();
void SetPrinter( Printer* pNewPrinter ) { mpPrinter = pNewPrinter; }
Printer* GetPrinter() const { return mpPrinter; }
inline bool IsSheetRangeAvailable() const { return mbWithSheetsAndCells; }
void EnableSheetRange( bool bEnable, PrintSheetRange eRange );
bool IsSheetRangeEnabled( PrintSheetRange eRange ) const;
void CheckSheetRange( PrintSheetRange eRange );
PrintSheetRange GetCheckedSheetRange() const;
bool IsSheetRangeChecked( PrintSheetRange eRange ) const;
void EnableRange( PrintDialogRange eRange );
void DisableRange( PrintDialogRange eRange );
BOOL IsRangeEnabled( PrintDialogRange eRange ) const;
void CheckRange( PrintDialogRange eRange = PRINTDIALOG_ALL )
{ meCheckRange = eRange; }
PrintDialogRange GetCheckedRange() const { return meCheckRange; }
BOOL IsRangeChecked( PrintDialogRange eRange ) const;
void SetRangeText( const XubString& rRange ) { maRangeText = rRange; }
const XubString& GetRangeText() const { return maRangeText; }
void SetFirstPage( USHORT nPage = 0 );
USHORT GetFirstPage() const { return mnFirstPage; }
void SetLastPage( USHORT nPage = 0 );
USHORT GetLastPage() const { return mnLastPage; }
void SetMinPage( USHORT nPage = 1 ) { mnMinPage = nPage; }
USHORT GetMinPage() const { return mnMinPage; }
void SetMaxPage( USHORT nPage = 65535 ) { mnMaxPage = nPage; }
USHORT GetMaxPage() const { return mnMaxPage; }
void SetCopyCount( USHORT nCopies = 1 ) { mnCopyCount = nCopies; }
USHORT GetCopyCount() const { return mnCopyCount; }
void EnableCollate( BOOL bEnable = TRUE )
{ mbCollate = bEnable; }
BOOL IsCollateEnabled() const { return mbCollate; }
void CheckCollate( BOOL bCheck = TRUE )
{ mbCollateCheck = bCheck; }
BOOL IsCollateChecked() const { return mbCollateCheck; }
void ShowOptionsButton( BOOL bShow = TRUE )
{ mbOptions = bShow; }
BOOL IsOptionsButtonVisible() const { return mbOptions; }
void SetOptionsHdl( const Link& rLink ) { maOptionsHdlLink = rLink; }
const Link& GetOptionsHdl() const { return maOptionsHdlLink; }
void SetOKHdl( const Link& rLink ) { maOKHdlLink = rLink; }
const Link& GetOKHdl() const { return maOKHdlLink; }
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual long Notify( NotifyEvent& rNEvt );
virtual short Execute();
void DisableHelp();
};
inline void PrintDialog::EnableRange( PrintDialogRange eRange )
{
if ( eRange == PRINTDIALOG_ALL )
mbAll = TRUE;
else if ( eRange == PRINTDIALOG_SELECTION )
mbSelection = TRUE;
else if ( eRange == PRINTDIALOG_FROMTO )
mbFromTo = TRUE;
else
mbRange = TRUE;
}
inline void PrintDialog::DisableRange( PrintDialogRange eRange )
{
if ( eRange == PRINTDIALOG_ALL )
mbAll = FALSE;
else if ( eRange == PRINTDIALOG_SELECTION )
mbSelection = FALSE;
else if ( eRange == PRINTDIALOG_FROMTO )
mbFromTo = FALSE;
else
mbRange = FALSE;
}
inline BOOL PrintDialog::IsRangeEnabled( PrintDialogRange eRange ) const
{
BOOL bRet;
if ( eRange == PRINTDIALOG_ALL )
bRet = mbAll;
else if ( eRange == PRINTDIALOG_SELECTION )
bRet = mbSelection;
else if ( eRange == PRINTDIALOG_FROMTO )
bRet = mbFromTo;
else
bRet = mbRange;
return bRet;
}
inline BOOL PrintDialog::IsRangeChecked( PrintDialogRange eRange ) const
{
if ( eRange == meCheckRange )
return TRUE;
else
return FALSE;
}
inline void PrintDialog::SetFirstPage( USHORT nPage )
{
mnFirstPage = nPage;
if ( nPage && (nPage < mnMinPage) )
mnMinPage = nPage;
}
inline void PrintDialog::SetLastPage( USHORT nPage )
{
mnLastPage = nPage;
if ( nPage && (nPage > mnMaxPage) )
mnMaxPage = nPage;
}
#endif // _SV_PRINTDLG_HXX_
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/demangle.h"
namespace tensorflow {
ResourceHandle MakeResourceHandle(OpKernelContext* ctx, const string& container,
const string& name,
const TypeIndex& type_index) {
ResourceHandle result;
result.set_device(ctx->device()->attributes().name());
string actual_container;
if (!container.empty()) {
actual_container = container;
} else {
actual_container = ctx->resource_manager()->default_container();
}
result.set_container(actual_container);
result.set_name(name);
result.set_hash_code(type_index.hash_code());
result.set_maybe_type_name(type_index.name());
return result;
}
Status MakeResourceHandleToOutput(OpKernelContext* context, int output_index,
const string& container, const string& name,
const TypeIndex& type_index) {
Tensor* handle;
TF_RETURN_IF_ERROR(
context->allocate_output(output_index, TensorShape({}), &handle));
handle->scalar<ResourceHandle>()() =
MakeResourceHandle(context, container, name, type_index);
return Status::OK();
}
namespace internal {
Status ValidateDevice(OpKernelContext* ctx, const ResourceHandle& p) {
if (ctx->device()->attributes().name() != p.device()) {
return errors::InvalidArgument(
"Trying to access resource ", p.name(), " located in device ",
p.device(), " from device ", ctx->device()->attributes().name());
}
return Status::OK();
}
} // end namespace internal
Status ResourceMgr::InsertDebugTypeName(uint64 hash_code,
const string& type_name) {
auto iter = debug_type_names_.emplace(hash_code, type_name);
if (iter.first->second != type_name) {
return errors::AlreadyExists("Duplicate hash code found for type ",
type_name);
}
return Status::OK();
}
const char* ResourceMgr::DebugTypeName(uint64 hash_code) const {
auto type_name_iter = debug_type_names_.find(hash_code);
if (type_name_iter == debug_type_names_.end()) {
return "<unknown>";
} else {
return type_name_iter->second.c_str();
}
}
ResourceMgr::ResourceMgr() : default_container_("localhost") {}
ResourceMgr::ResourceMgr(const string& default_container)
: default_container_(default_container) {}
ResourceMgr::~ResourceMgr() { Clear(); }
void ResourceMgr::Clear() {
mutex_lock l(mu_);
for (const auto& p : containers_) {
for (const auto& q : *p.second) {
q.second->Unref();
}
delete p.second;
}
containers_.clear();
}
string ResourceMgr::DebugString() const {
mutex_lock l(mu_);
struct Line {
const string* container;
const string type;
const string* resource;
const string detail;
};
std::vector<Line> lines;
for (const auto& p : containers_) {
const string& container = p.first;
for (const auto& q : *p.second) {
const Key& key = q.first;
const char* type = DebugTypeName(key.first);
const string& resource = key.second;
Line l{&container, port::Demangle(type), &resource,
q.second->DebugString()};
lines.push_back(l);
}
}
std::vector<string> text;
text.reserve(lines.size());
for (const Line& line : lines) {
text.push_back(strings::Printf(
"%-20s | %-40s | %-40s | %-s", line.container->c_str(),
line.type.c_str(), line.resource->c_str(), line.detail.c_str()));
}
std::sort(text.begin(), text.end());
return str_util::Join(text, "\n");
}
Status ResourceMgr::DoCreate(const string& container, TypeIndex type,
const string& name, ResourceBase* resource) {
Container** b = &containers_[container];
if (*b == nullptr) {
*b = new Container;
}
if ((*b)->insert({{type.hash_code(), name}, resource}).second) {
TF_RETURN_IF_ERROR(InsertDebugTypeName(type.hash_code(), type.name()));
return Status::OK();
}
resource->Unref();
return errors::AlreadyExists("Resource ", container, "/", name, "/",
type.name());
}
Status ResourceMgr::DoLookup(const string& container, TypeIndex type,
const string& name,
ResourceBase** resource) const {
const Container* b = gtl::FindPtrOrNull(containers_, container);
if (b == nullptr) {
return errors::NotFound("Container ", container,
" does not exist. (Could not find resource: ",
container, "/", name, ")");
}
auto r = gtl::FindPtrOrNull(*b, {type.hash_code(), name});
if (r == nullptr) {
return errors::NotFound("Resource ", container, "/", name, "/", type.name(),
" does not exist.");
}
*resource = const_cast<ResourceBase*>(r);
(*resource)->Ref();
return Status::OK();
}
Status ResourceMgr::DoDelete(const string& container, uint64 type_hash_code,
const string& resource_name,
const string& type_name) {
ResourceBase* base = nullptr;
{
mutex_lock l(mu_);
Container* b = gtl::FindPtrOrNull(containers_, container);
if (b == nullptr) {
return errors::NotFound("Container ", container, " does not exist.");
}
auto iter = b->find({type_hash_code, resource_name});
if (iter == b->end()) {
return errors::NotFound("Resource ", container, "/", resource_name, "/",
type_name, " does not exist.");
}
base = iter->second;
b->erase(iter);
}
CHECK(base != nullptr);
base->Unref();
return Status::OK();
}
Status ResourceMgr::DoDelete(const string& container, TypeIndex type,
const string& resource_name) {
return DoDelete(container, type.hash_code(), resource_name, type.name());
}
Status ResourceMgr::Delete(const ResourceHandle& handle) {
return DoDelete(handle.container(), handle.hash_code(), handle.name(),
"<unknown>");
}
Status ResourceMgr::Cleanup(const string& container) {
Container* b = nullptr;
{
mutex_lock l(mu_);
auto iter = containers_.find(container);
if (iter == containers_.end()) {
// Nothing to cleanup, it's OK.
return Status::OK();
}
b = iter->second;
containers_.erase(iter);
}
CHECK(b != nullptr);
for (const auto& p : *b) {
p.second->Unref();
}
delete b;
return Status::OK();
}
static bool IsValidContainerName(StringPiece s) {
using ::tensorflow::strings::Scanner;
return Scanner(s)
.One(Scanner::LETTER_DIGIT_DOT)
.Any(Scanner::LETTER_DIGIT_DASH_DOT_SLASH)
.Eos()
.GetResult();
}
Status ContainerInfo::Init(ResourceMgr* rmgr, const NodeDef& ndef,
bool use_node_name_as_default) {
CHECK(rmgr);
rmgr_ = rmgr;
string attr_container;
TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "container", &attr_container));
if (!attr_container.empty() && !IsValidContainerName(attr_container)) {
return errors::InvalidArgument("container contains invalid characters: ",
attr_container);
}
string attr_shared_name;
TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "shared_name", &attr_shared_name));
if (!attr_shared_name.empty() && (attr_shared_name[0] == '_')) {
return errors::InvalidArgument("shared_name cannot start with '_':",
attr_shared_name);
}
if (!attr_container.empty()) {
container_ = attr_container;
} else {
container_ = rmgr_->default_container();
}
if (!attr_shared_name.empty()) {
name_ = attr_shared_name;
} else if (use_node_name_as_default) {
name_ = ndef.name();
} else {
resource_is_private_to_kernel_ = true;
static std::atomic<int64> counter(0);
name_ = strings::StrCat("_", counter.fetch_add(1), "_", ndef.name());
}
return Status::OK();
}
string ContainerInfo::DebugString() const {
return strings::StrCat("[", container(), ",", name(), ",",
resource_is_private_to_kernel() ? "private" : "public",
"]");
}
const ResourceHandle& HandleFromInput(OpKernelContext* ctx, int input) {
return ctx->input(input).flat<ResourceHandle>()(0);
}
Status HandleFromInput(OpKernelContext* ctx, StringPiece input,
ResourceHandle* handle) {
const Tensor* tensor;
TF_RETURN_IF_ERROR(ctx->input(input, &tensor));
*handle = tensor->flat<ResourceHandle>()(0);
return Status::OK();
}
Status DeleteResource(OpKernelContext* ctx, const ResourceHandle& p) {
TF_RETURN_IF_ERROR(internal::ValidateDevice(ctx, p));
return ctx->resource_manager()->Delete(p);
}
Status ResourceHandlesShape(shape_inference::InferenceContext* c) {
int n;
TF_RETURN_IF_ERROR(c->GetAttr("N", &n));
for (int i = 0; i < n; ++i) {
c->set_output(i, c->Scalar());
}
return Status::OK();
}
} // end namespace tensorflow
<commit_msg>[Perf] Use a shared lock to avoid slow paths<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/demangle.h"
namespace tensorflow {
ResourceHandle MakeResourceHandle(OpKernelContext* ctx, const string& container,
const string& name,
const TypeIndex& type_index) {
ResourceHandle result;
result.set_device(ctx->device()->attributes().name());
string actual_container;
if (!container.empty()) {
actual_container = container;
} else {
actual_container = ctx->resource_manager()->default_container();
}
result.set_container(actual_container);
result.set_name(name);
result.set_hash_code(type_index.hash_code());
result.set_maybe_type_name(type_index.name());
return result;
}
Status MakeResourceHandleToOutput(OpKernelContext* context, int output_index,
const string& container, const string& name,
const TypeIndex& type_index) {
Tensor* handle;
TF_RETURN_IF_ERROR(
context->allocate_output(output_index, TensorShape({}), &handle));
handle->scalar<ResourceHandle>()() =
MakeResourceHandle(context, container, name, type_index);
return Status::OK();
}
namespace internal {
Status ValidateDevice(OpKernelContext* ctx, const ResourceHandle& p) {
if (ctx->device()->attributes().name() != p.device()) {
return errors::InvalidArgument(
"Trying to access resource ", p.name(), " located in device ",
p.device(), " from device ", ctx->device()->attributes().name());
}
return Status::OK();
}
} // end namespace internal
Status ResourceMgr::InsertDebugTypeName(uint64 hash_code,
const string& type_name) {
auto iter = debug_type_names_.emplace(hash_code, type_name);
if (iter.first->second != type_name) {
return errors::AlreadyExists("Duplicate hash code found for type ",
type_name);
}
return Status::OK();
}
const char* ResourceMgr::DebugTypeName(uint64 hash_code) const {
auto type_name_iter = debug_type_names_.find(hash_code);
if (type_name_iter == debug_type_names_.end()) {
return "<unknown>";
} else {
return type_name_iter->second.c_str();
}
}
ResourceMgr::ResourceMgr() : default_container_("localhost") {}
ResourceMgr::ResourceMgr(const string& default_container)
: default_container_(default_container) {}
ResourceMgr::~ResourceMgr() { Clear(); }
void ResourceMgr::Clear() {
mutex_lock l(mu_);
for (const auto& p : containers_) {
for (const auto& q : *p.second) {
q.second->Unref();
}
delete p.second;
}
containers_.clear();
}
string ResourceMgr::DebugString() const {
mutex_lock l(mu_);
struct Line {
const string* container;
const string type;
const string* resource;
const string detail;
};
std::vector<Line> lines;
for (const auto& p : containers_) {
const string& container = p.first;
for (const auto& q : *p.second) {
const Key& key = q.first;
const char* type = DebugTypeName(key.first);
const string& resource = key.second;
Line l{&container, port::Demangle(type), &resource,
q.second->DebugString()};
lines.push_back(l);
}
}
std::vector<string> text;
text.reserve(lines.size());
for (const Line& line : lines) {
text.push_back(strings::Printf(
"%-20s | %-40s | %-40s | %-s", line.container->c_str(),
line.type.c_str(), line.resource->c_str(), line.detail.c_str()));
}
std::sort(text.begin(), text.end());
return str_util::Join(text, "\n");
}
Status ResourceMgr::DoCreate(const string& container, TypeIndex type,
const string& name, ResourceBase* resource) {
Container** b = &containers_[container];
if (*b == nullptr) {
*b = new Container;
}
if ((*b)->insert({{type.hash_code(), name}, resource}).second) {
TF_RETURN_IF_ERROR(InsertDebugTypeName(type.hash_code(), type.name()));
return Status::OK();
}
resource->Unref();
return errors::AlreadyExists("Resource ", container, "/", name, "/",
type.name());
}
Status ResourceMgr::DoLookup(const string& container, TypeIndex type,
const string& name,
ResourceBase** resource) const {
const Container* b = gtl::FindPtrOrNull(containers_, container);
if (b == nullptr) {
return errors::NotFound("Container ", container,
" does not exist. (Could not find resource: ",
container, "/", name, ")");
}
auto r = gtl::FindPtrOrNull(*b, {type.hash_code(), name});
if (r == nullptr) {
return errors::NotFound("Resource ", container, "/", name, "/", type.name(),
" does not exist.");
}
*resource = const_cast<ResourceBase*>(r);
(*resource)->Ref();
return Status::OK();
}
Status ResourceMgr::DoDelete(const string& container, uint64 type_hash_code,
const string& resource_name,
const string& type_name) {
ResourceBase* base = nullptr;
{
mutex_lock l(mu_);
Container* b = gtl::FindPtrOrNull(containers_, container);
if (b == nullptr) {
return errors::NotFound("Container ", container, " does not exist.");
}
auto iter = b->find({type_hash_code, resource_name});
if (iter == b->end()) {
return errors::NotFound("Resource ", container, "/", resource_name, "/",
type_name, " does not exist.");
}
base = iter->second;
b->erase(iter);
}
CHECK(base != nullptr);
base->Unref();
return Status::OK();
}
Status ResourceMgr::DoDelete(const string& container, TypeIndex type,
const string& resource_name) {
return DoDelete(container, type.hash_code(), resource_name, type.name());
}
Status ResourceMgr::Delete(const ResourceHandle& handle) {
return DoDelete(handle.container(), handle.hash_code(), handle.name(),
"<unknown>");
}
Status ResourceMgr::Cleanup(const string& container) {
{
tf_shared_lock l(mu_);
if (!gtl::FindOrNull(containers_, container)) {
// Nothing to cleanup.
return Status::OK();
}
}
Container* b = nullptr;
{
mutex_lock l(mu_);
auto iter = containers_.find(container);
if (iter == containers_.end()) {
// Nothing to cleanup, it's OK (concurrent cleanup).
return Status::OK();
}
b = iter->second;
containers_.erase(iter);
}
CHECK(b != nullptr);
for (const auto& p : *b) {
p.second->Unref();
}
delete b;
return Status::OK();
}
static bool IsValidContainerName(StringPiece s) {
using ::tensorflow::strings::Scanner;
return Scanner(s)
.One(Scanner::LETTER_DIGIT_DOT)
.Any(Scanner::LETTER_DIGIT_DASH_DOT_SLASH)
.Eos()
.GetResult();
}
Status ContainerInfo::Init(ResourceMgr* rmgr, const NodeDef& ndef,
bool use_node_name_as_default) {
CHECK(rmgr);
rmgr_ = rmgr;
string attr_container;
TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "container", &attr_container));
if (!attr_container.empty() && !IsValidContainerName(attr_container)) {
return errors::InvalidArgument("container contains invalid characters: ",
attr_container);
}
string attr_shared_name;
TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "shared_name", &attr_shared_name));
if (!attr_shared_name.empty() && (attr_shared_name[0] == '_')) {
return errors::InvalidArgument("shared_name cannot start with '_':",
attr_shared_name);
}
if (!attr_container.empty()) {
container_ = attr_container;
} else {
container_ = rmgr_->default_container();
}
if (!attr_shared_name.empty()) {
name_ = attr_shared_name;
} else if (use_node_name_as_default) {
name_ = ndef.name();
} else {
resource_is_private_to_kernel_ = true;
static std::atomic<int64> counter(0);
name_ = strings::StrCat("_", counter.fetch_add(1), "_", ndef.name());
}
return Status::OK();
}
string ContainerInfo::DebugString() const {
return strings::StrCat("[", container(), ",", name(), ",",
resource_is_private_to_kernel() ? "private" : "public",
"]");
}
const ResourceHandle& HandleFromInput(OpKernelContext* ctx, int input) {
return ctx->input(input).flat<ResourceHandle>()(0);
}
Status HandleFromInput(OpKernelContext* ctx, StringPiece input,
ResourceHandle* handle) {
const Tensor* tensor;
TF_RETURN_IF_ERROR(ctx->input(input, &tensor));
*handle = tensor->flat<ResourceHandle>()(0);
return Status::OK();
}
Status DeleteResource(OpKernelContext* ctx, const ResourceHandle& p) {
TF_RETURN_IF_ERROR(internal::ValidateDevice(ctx, p));
return ctx->resource_manager()->Delete(p);
}
Status ResourceHandlesShape(shape_inference::InferenceContext* c) {
int n;
TF_RETURN_IF_ERROR(c->GetAttr("N", &n));
for (int i = 0; i < n; ++i) {
c->set_output(i, c->Scalar());
}
return Status::OK();
}
} // end namespace tensorflow
<|endoftext|> |
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
//#include <boost>
#include <chrono>
#include <mitkCommon.h>
#include "mitkPALinearSpectralUnmixingFilter.h"
#include "mitkPASpectralUnmixingFilterBase.h"
#include "mitkPASpectralUnmixingFilterVigra.h"
#include "mitkPASpectralUnmixingSO2.h"
#include <mitkCommandLineParser.h>
#include <mitkException.h>
#include <mitkIOUtil.h>
#include <mitkUIDGenerator.h>
#include <itksys/SystemTools.hxx>
#include "mitkPreferenceListReaderOptionsFunctor.h"
struct InputParameters
{
std::string inputPath;
std::string outputPath;
int numberOfInputs;
};
InputParameters parseInput(int argc, char *argv[])
{
MITK_INFO << "Parsing arguments...";
mitkCommandLineParser parser;
parser.setCategory("MITK-Photoacoustics");
parser.setTitle("Mitk Spectral Unmixing App");
parser.setDescription("Batch processing for spectral unmixing.");
parser.setContributor("Computer Assisted Medical Interventions, DKFZ");
parser.setArgumentPrefix("--", "-");
parser.beginGroup("Required parameters");
parser.addArgument("inputPath",
"i",
mitkCommandLineParser::Directory,
"Input folder (directory)",
"input folder",
us::Any(),
false, false, false, mitkCommandLineParser::Input);
parser.addArgument("outputPath",
"o",
mitkCommandLineParser::Directory,
"Input save folder (directory)",
"input save folder",
us::Any(),
false, false, false, mitkCommandLineParser::Output);
parser.addArgument("numberOfInputs",
"n",
mitkCommandLineParser::Int,
"Number of Input files",
"number of inputs",
us::Any(),
false);
parser.endGroup();
InputParameters input;
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (argc == 0)
exit(-1);
for (int i = 0; i < argc; ++i)
{
MITK_INFO << argv[i];
}
if (parsedArgs.count("inputPath"))
{
input.inputPath = us::any_cast<std::string>(parsedArgs["inputPath"]);
}
else
{
MITK_ERROR << "Error: No inputPath";
mitkThrow() << "Error: No inputPath";
}
if (parsedArgs.count("outputPath"))
{
input.outputPath = us::any_cast<std::string>(parsedArgs["outputPath"]);
}
else
{
MITK_ERROR << "Error: No outputPath";
mitkThrow() << "Error: No outputPath";
}
if (parsedArgs.count("numberOfInputs"))
{
input.numberOfInputs = us::any_cast<int>(parsedArgs["numberOfInputs"]);
}
else
{
MITK_ERROR << "Error: No number of Inputs";
mitkThrow() << "Error: No number of Inputs";
}
MITK_INFO << "Parsing arguments...[Done]";
return input;
}
mitk::pa::SpectralUnmixingFilterBase::Pointer GetFilterInstance(std::string algorithm)
{
mitk::pa::SpectralUnmixingFilterBase::Pointer spectralUnmixingFilter;
if (algorithm == "QR")
{
spectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
dynamic_cast<mitk::pa::LinearSpectralUnmixingFilter *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::HOUSEHOLDERQR);
}
else if (algorithm == "SVD")
{
spectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
dynamic_cast<mitk::pa::LinearSpectralUnmixingFilter *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::JACOBISVD);
}
else if (algorithm == "LU")
{
spectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
dynamic_cast<mitk::pa::LinearSpectralUnmixingFilter *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::FULLPIVLU);
}
else if (algorithm == "NNLS")
{
spectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterVigra::New();
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::LARS);
}
else if (algorithm == "WLS")
{
spectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterVigra::New();
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::WEIGHTED);
/*std::vector<int> weigthVec = {39, 45, 47};
for (int i = 0; i < 3; ++i)
{
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(spectralUnmixingFilter.GetPointer())
->AddWeight(weigthVec[i]);
}*/
}
return spectralUnmixingFilter;
}
void add_weight(int weights, mitk::pa::SpectralUnmixingFilterBase::Pointer m_SpectralUnmixingFilter)
{
std::vector<int> weigthVec = { 30, 32, 33, 35, 37, 38, 40, 41, 43, 44, 45, 46, 47, 47,
47, 47, 47, 46, 46, 45, 44, 44, 43, 42, 42, 41 };
for (int i = 0; i < weights; ++i)
{
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(m_SpectralUnmixingFilter.GetPointer())
->AddWeight(weigthVec[i]);
}
}
int main(int argc, char *argv[])
{
auto input = parseInput(argc, argv);
std::string inputDir = input.inputPath;
std::string outputDir = input.outputPath;
unsigned int N = input.numberOfInputs;
/*
//maybee try with "itk system tools"
//auto test = itksys::SystemTools::GetFilenameName(argv[0]).c_str();
//MITK_INFO << "test: " << test;
/ +++ temporary solution BEGIN +++
std::vector<std::string> files;
std::string file;
for (int i = 1; i < 34; ++i)
{
if (i < 10)
{
file = "E:/NHDATA/sdmas_beamformed/merged/static-oxy_sdmas_00" + std::to_string(i) + "_merged.nrrd";
}
else
{
file = "E:/NHDATA/sdmas_beamformed/merged/static-oxy_sdmas_0" + std::to_string(i) + "_merged.nrrd";
}
files.push_back(file);
}
/ +++ temporary solution END +++
std::vector<std::string> files;
std::string file;
for (int i = 0; i < 7; ++i)
{
file = "E:/NHCAMI/cami-experimental/PAI/spectralUnmixing/inSilico/paImages/selection/noiselevel1_rep1000_wavelength_selction_data_" +
std::to_string(i) + ".nrrd";
files.push_back(file);
}
std::vector<std::string> files;
std::string file;
file = "E:/NHCAMI/cami-experimental/PAI/spectralUnmixing/inSilico/paImages/selection/noiselevel1_rep1000_wavelength_selction_data.nrrd";
files.push_back(file);*/
std::vector<std::string> algorithms = { "QR", "LU", "SVD", "NNLS", "WLS" };
int repetition = 6000;
for (unsigned alg = 0; alg < 5; ++alg)
{
ofstream myerrorfile;
myerrorfile.open("E:/NHDATA/time/time_evaluation_" + std::to_string(repetition)+"_" + algorithms[alg] + "_new02.txt");
int ctr = 0;
for(int i = 2; i < 27; ++i)
{
myerrorfile << std::to_string(i) + "\t";
std::string file;
if (i < 10)
file = "E:/NHDATA/time/input/time_0" + std::to_string(i) + ".nrrd";
else
file = "E:/NHDATA/time/input/time_" + std::to_string(i) + ".nrrd";
auto m_inputImage = mitk::IOUtil::Load<mitk::Image>(file);
MITK_INFO << "File: " << i;
for (int j = 0; j < repetition; ++j)
{
std::chrono::steady_clock::time_point _start;
_start = std::chrono::steady_clock::now();
mitk::pa::SpectralUnmixingFilterBase::Pointer m_SpectralUnmixingFilter = GetFilterInstance(algorithms[alg]);
m_SpectralUnmixingFilter->SetInput(m_inputImage);
m_SpectralUnmixingFilter->AddOutputs(2);
m_SpectralUnmixingFilter->Verbose(false);
m_SpectralUnmixingFilter->RelativeError(false);
m_SpectralUnmixingFilter->AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
for (int wl = 0; wl < i; ++wl)
{
m_SpectralUnmixingFilter->AddWavelength(700 + wl * 10);
}
if (alg == 4)
{
add_weight(i, m_SpectralUnmixingFilter);
}
m_SpectralUnmixingFilter->Update();
auto output1 = m_SpectralUnmixingFilter->GetOutput(0);
auto output2 = m_SpectralUnmixingFilter->GetOutput(1);
m_SpectralUnmixingFilter = nullptr;
std::chrono::steady_clock::time_point _end(std::chrono::steady_clock::now());
myerrorfile << std::chrono::duration_cast<std::chrono::duration<double>>(_end - _start).count() << "\t";
/*std::string unmixingOutputHbO2 = "E:/NHDATA/time/output/time_" + std::to_string(i) + ".nrrd";
std::string unmixingOutputHb = "E:/NHDATA/time/output/time_" + std::to_string(i) + ".nrrd";
mitk::IOUtil::Save(output1, unmixingOutputHbO2);
mitk::IOUtil::Save(output2, unmixingOutputHb);/*
/*
//auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
//m_sO2->Verbose(false);
//auto output1 = m_SpectralUnmixingFilter->GetOutput(0);
//auto output2 = m_SpectralUnmixingFilter->GetOutput(1);
//std::string unmixingOutputHbO2 ="E:/NHDATA/time/input/time_" + std::to_string(i) + ".nrrd";
//std::string unmixingOutputHb = outputDir + "/SUOutput/" + "Hb_" + algorithms[alg] + "_" + str_ctr + ".nrrd";
//mitk::IOUtil::Save(output1, unmixingOutputHbO2);
//mitk::IOUtil::Save(output2, unmixingOutputHb);
//m_sO2->SetInput(0, output1);
//m_sO2->SetInput(1, output2);
//m_sO2->Update();
//mitk::Image::Pointer sO2 = m_sO2->GetOutput(0);
//sO2->SetSpacing(output1->GetGeometry()->GetSpacing());
//std::string outputSo2 = outputDir + "/So2/" + algorithms[alg] + "/So2_" + algorithms[alg] + "_" + str_ctr + ".nrrd";
//std::string outputSo2 = outputDir + "/" + algorithms[alg] + "_sel_" + str_ctr + ".nrrd";
//std::string outputSo2 = outputDir + "/" + algorithms[alg] + "_sel.nrrd";
//mitk::IOUtil::Save(sO2, outputSo2);
//std::string outputSo2 = "E:/NHDATA/time/output/time_" + std::to_string(i) + algorithms[alg] + ".nrrd";
//mitk::IOUtil::Save(sO2, outputSo2);*/
}
myerrorfile << "\n";
}
myerrorfile.close();
}
MITK_INFO << "Spectral Unmixing DONE";
}
<commit_msg>Fix unbalanced nested comment<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
//#include <boost>
#include <chrono>
#include <mitkCommon.h>
#include "mitkPALinearSpectralUnmixingFilter.h"
#include "mitkPASpectralUnmixingFilterBase.h"
#include "mitkPASpectralUnmixingFilterVigra.h"
#include "mitkPASpectralUnmixingSO2.h"
#include <mitkCommandLineParser.h>
#include <mitkException.h>
#include <mitkIOUtil.h>
#include <mitkUIDGenerator.h>
#include <itksys/SystemTools.hxx>
#include "mitkPreferenceListReaderOptionsFunctor.h"
struct InputParameters
{
std::string inputPath;
std::string outputPath;
int numberOfInputs;
};
InputParameters parseInput(int argc, char *argv[])
{
MITK_INFO << "Parsing arguments...";
mitkCommandLineParser parser;
parser.setCategory("MITK-Photoacoustics");
parser.setTitle("Mitk Spectral Unmixing App");
parser.setDescription("Batch processing for spectral unmixing.");
parser.setContributor("Computer Assisted Medical Interventions, DKFZ");
parser.setArgumentPrefix("--", "-");
parser.beginGroup("Required parameters");
parser.addArgument("inputPath",
"i",
mitkCommandLineParser::Directory,
"Input folder (directory)",
"input folder",
us::Any(),
false, false, false, mitkCommandLineParser::Input);
parser.addArgument("outputPath",
"o",
mitkCommandLineParser::Directory,
"Input save folder (directory)",
"input save folder",
us::Any(),
false, false, false, mitkCommandLineParser::Output);
parser.addArgument("numberOfInputs",
"n",
mitkCommandLineParser::Int,
"Number of Input files",
"number of inputs",
us::Any(),
false);
parser.endGroup();
InputParameters input;
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (argc == 0)
exit(-1);
for (int i = 0; i < argc; ++i)
{
MITK_INFO << argv[i];
}
if (parsedArgs.count("inputPath"))
{
input.inputPath = us::any_cast<std::string>(parsedArgs["inputPath"]);
}
else
{
MITK_ERROR << "Error: No inputPath";
mitkThrow() << "Error: No inputPath";
}
if (parsedArgs.count("outputPath"))
{
input.outputPath = us::any_cast<std::string>(parsedArgs["outputPath"]);
}
else
{
MITK_ERROR << "Error: No outputPath";
mitkThrow() << "Error: No outputPath";
}
if (parsedArgs.count("numberOfInputs"))
{
input.numberOfInputs = us::any_cast<int>(parsedArgs["numberOfInputs"]);
}
else
{
MITK_ERROR << "Error: No number of Inputs";
mitkThrow() << "Error: No number of Inputs";
}
MITK_INFO << "Parsing arguments...[Done]";
return input;
}
mitk::pa::SpectralUnmixingFilterBase::Pointer GetFilterInstance(std::string algorithm)
{
mitk::pa::SpectralUnmixingFilterBase::Pointer spectralUnmixingFilter;
if (algorithm == "QR")
{
spectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
dynamic_cast<mitk::pa::LinearSpectralUnmixingFilter *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::HOUSEHOLDERQR);
}
else if (algorithm == "SVD")
{
spectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
dynamic_cast<mitk::pa::LinearSpectralUnmixingFilter *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::JACOBISVD);
}
else if (algorithm == "LU")
{
spectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
dynamic_cast<mitk::pa::LinearSpectralUnmixingFilter *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::FULLPIVLU);
}
else if (algorithm == "NNLS")
{
spectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterVigra::New();
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::LARS);
}
else if (algorithm == "WLS")
{
spectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterVigra::New();
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(spectralUnmixingFilter.GetPointer())
->SetAlgorithm(mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::WEIGHTED);
/*std::vector<int> weigthVec = {39, 45, 47};
for (int i = 0; i < 3; ++i)
{
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(spectralUnmixingFilter.GetPointer())
->AddWeight(weigthVec[i]);
}*/
}
return spectralUnmixingFilter;
}
void add_weight(int weights, mitk::pa::SpectralUnmixingFilterBase::Pointer m_SpectralUnmixingFilter)
{
std::vector<int> weigthVec = { 30, 32, 33, 35, 37, 38, 40, 41, 43, 44, 45, 46, 47, 47,
47, 47, 47, 46, 46, 45, 44, 44, 43, 42, 42, 41 };
for (int i = 0; i < weights; ++i)
{
dynamic_cast<mitk::pa::SpectralUnmixingFilterVigra *>(m_SpectralUnmixingFilter.GetPointer())
->AddWeight(weigthVec[i]);
}
}
int main(int argc, char *argv[])
{
auto input = parseInput(argc, argv);
std::string inputDir = input.inputPath;
std::string outputDir = input.outputPath;
unsigned int N = input.numberOfInputs;
/*
//maybee try with "itk system tools"
//auto test = itksys::SystemTools::GetFilenameName(argv[0]).c_str();
//MITK_INFO << "test: " << test;
/ +++ temporary solution BEGIN +++
std::vector<std::string> files;
std::string file;
for (int i = 1; i < 34; ++i)
{
if (i < 10)
{
file = "E:/NHDATA/sdmas_beamformed/merged/static-oxy_sdmas_00" + std::to_string(i) + "_merged.nrrd";
}
else
{
file = "E:/NHDATA/sdmas_beamformed/merged/static-oxy_sdmas_0" + std::to_string(i) + "_merged.nrrd";
}
files.push_back(file);
}
/ +++ temporary solution END +++
std::vector<std::string> files;
std::string file;
for (int i = 0; i < 7; ++i)
{
file = "E:/NHCAMI/cami-experimental/PAI/spectralUnmixing/inSilico/paImages/selection/noiselevel1_rep1000_wavelength_selction_data_" +
std::to_string(i) + ".nrrd";
files.push_back(file);
}
std::vector<std::string> files;
std::string file;
file = "E:/NHCAMI/cami-experimental/PAI/spectralUnmixing/inSilico/paImages/selection/noiselevel1_rep1000_wavelength_selction_data.nrrd";
files.push_back(file);*/
std::vector<std::string> algorithms = { "QR", "LU", "SVD", "NNLS", "WLS" };
int repetition = 6000;
for (unsigned alg = 0; alg < 5; ++alg)
{
ofstream myerrorfile;
myerrorfile.open("E:/NHDATA/time/time_evaluation_" + std::to_string(repetition)+"_" + algorithms[alg] + "_new02.txt");
int ctr = 0;
for(int i = 2; i < 27; ++i)
{
myerrorfile << std::to_string(i) + "\t";
std::string file;
if (i < 10)
file = "E:/NHDATA/time/input/time_0" + std::to_string(i) + ".nrrd";
else
file = "E:/NHDATA/time/input/time_" + std::to_string(i) + ".nrrd";
auto m_inputImage = mitk::IOUtil::Load<mitk::Image>(file);
MITK_INFO << "File: " << i;
for (int j = 0; j < repetition; ++j)
{
std::chrono::steady_clock::time_point _start;
_start = std::chrono::steady_clock::now();
mitk::pa::SpectralUnmixingFilterBase::Pointer m_SpectralUnmixingFilter = GetFilterInstance(algorithms[alg]);
m_SpectralUnmixingFilter->SetInput(m_inputImage);
m_SpectralUnmixingFilter->AddOutputs(2);
m_SpectralUnmixingFilter->Verbose(false);
m_SpectralUnmixingFilter->RelativeError(false);
m_SpectralUnmixingFilter->AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
for (int wl = 0; wl < i; ++wl)
{
m_SpectralUnmixingFilter->AddWavelength(700 + wl * 10);
}
if (alg == 4)
{
add_weight(i, m_SpectralUnmixingFilter);
}
m_SpectralUnmixingFilter->Update();
auto output1 = m_SpectralUnmixingFilter->GetOutput(0);
auto output2 = m_SpectralUnmixingFilter->GetOutput(1);
m_SpectralUnmixingFilter = nullptr;
std::chrono::steady_clock::time_point _end(std::chrono::steady_clock::now());
myerrorfile << std::chrono::duration_cast<std::chrono::duration<double>>(_end - _start).count() << "\t";
/*std::string unmixingOutputHbO2 = "E:/NHDATA/time/output/time_" + std::to_string(i) + ".nrrd";
std::string unmixingOutputHb = "E:/NHDATA/time/output/time_" + std::to_string(i) + ".nrrd";
mitk::IOUtil::Save(output1, unmixingOutputHbO2);
mitk::IOUtil::Save(output2, unmixingOutputHb);
//auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
//m_sO2->Verbose(false);
//auto output1 = m_SpectralUnmixingFilter->GetOutput(0);
//auto output2 = m_SpectralUnmixingFilter->GetOutput(1);
//std::string unmixingOutputHbO2 ="E:/NHDATA/time/input/time_" + std::to_string(i) + ".nrrd";
//std::string unmixingOutputHb = outputDir + "/SUOutput/" + "Hb_" + algorithms[alg] + "_" + str_ctr + ".nrrd";
//mitk::IOUtil::Save(output1, unmixingOutputHbO2);
//mitk::IOUtil::Save(output2, unmixingOutputHb);
//m_sO2->SetInput(0, output1);
//m_sO2->SetInput(1, output2);
//m_sO2->Update();
//mitk::Image::Pointer sO2 = m_sO2->GetOutput(0);
//sO2->SetSpacing(output1->GetGeometry()->GetSpacing());
//std::string outputSo2 = outputDir + "/So2/" + algorithms[alg] + "/So2_" + algorithms[alg] + "_" + str_ctr + ".nrrd";
//std::string outputSo2 = outputDir + "/" + algorithms[alg] + "_sel_" + str_ctr + ".nrrd";
//std::string outputSo2 = outputDir + "/" + algorithms[alg] + "_sel.nrrd";
//mitk::IOUtil::Save(sO2, outputSo2);
//std::string outputSo2 = "E:/NHDATA/time/output/time_" + std::to_string(i) + algorithms[alg] + ".nrrd";
//mitk::IOUtil::Save(sO2, outputSo2);*/
}
myerrorfile << "\n";
}
myerrorfile.close();
}
MITK_INFO << "Spectral Unmixing DONE";
}
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2018 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#include <DO/Sara/Core/MultiArray/InfiniteMultiArrayView.hpp>
#include <DO/Sara/Core/Timer.hpp>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/ImageProcessing.hpp>
#include <DO/Sara/Core/Tensor.hpp>
#include <DO/Sara/ImageProcessing/GemmBasedConvolution.hpp>
using namespace std;
using namespace DO::Sara;
template <typename T, int N>
Tensor_<T, N> transpose(const TensorView_<T, N>& x, const Matrix<int, N, 1>& order)
{
Matrix<int, N, 1> out_sizes;
for (int i = 0; i < N; ++i)
out_sizes[i] = x.size(order[i]);
Tensor_<T, N> out{out_sizes};
auto in_c = x.begin_array();
Matrix<int, N, 1> out_c = Matrix<int, N, 1>::Zero();
for ( ; !in_c.end(); ++in_c)
{
for (int i = 0; i < N; ++i)
out_c[i] = in_c.position()[order[i]];
out(out_c) = *in_c;
}
return out;
}
// Compute the size of the Gaussian kernel.
auto gaussian_kernel(float sigma, int gauss_truncate)
-> Image<float>
{
auto kernel_size = int(2 * gauss_truncate * sigma + 1);
// Make sure the Gaussian kernel is at least of size 3 and is of odd size.
kernel_size = std::max(3, kernel_size);
if (kernel_size % 2 == 0)
++kernel_size;
// Create the 1D Gaussian kernel.
auto kernel = Image<float>(kernel_size, kernel_size);
auto sum = 0.f;
// Compute the value of the Gaussian and the normalizing factor.
for (int y = 0; y < kernel_size; ++y)
{
const auto v = float(y) - kernel_size / 2.f;
const auto ky = exp(-v * v / (2.f * sigma * sigma));
for (int x = 0; x < kernel_size; ++x)
{
const auto u = float(x) - kernel_size / 2.f;
auto kx = exp(-u * u / (2.f * sigma * sigma));
kernel(x, y) = kx * ky;
sum += kernel(x, y);
}
}
kernel.flat_array() /= sum;
return kernel;
};
int test_grayscale_image()
{
auto image = Image<float>{};
imread(image, "/home/david/GitHub/DO-CV/sara/data/sunflowerField.jpg");
//const auto kernel = gaussian_kernel(3.f, 2);
auto kernel = Image<float>{3, 3};
kernel.matrix() = Matrix3f::Ones() / 9;
auto x = tensor_view(image);
auto k = tensor_view(kernel);
#ifdef DEBUG
const Vector2i strides{4, 4};
const auto xi = x.begin_stepped_subarray(Vector2i::Zero(), x.sizes(), strides);
auto szs = xi.stepped_subarray_sizes();
std::reverse(szs.data(), szs.data() + szs.size());
auto convolved_image = Image<float>{szs};
auto y = tensor_view(convolved_image);
gemm_convolve_strided(y, x, k, strides);
#else
// Stride in HxW order.
const Vector2i strides{2, 2};
auto y = gemm_convolve_strided(x, k, strides);
auto convolved_image = image_view(y);
#endif
create_window(convolved_image.sizes());
//display(convolved_image.compute<ColorRescale>());
display(convolved_image);
get_key();
close_window();
return EXIT_SUCCESS;
}
auto convolve_image_mean33(const Image<Rgb32f>& image)
-> Image<Rgb32f>
{
// Get the 3D float row-major tensor view in HxWxC format.
auto x =
tensor_view(image).reshape(Vector4i{1, image.height(), image.width(), 3});
auto convolved_image = Image<Rgb32f>{image.sizes()};
auto yt = tensor_view(convolved_image)
.reshape(Vector4i{1, image.height(), image.width(), 3});
constexpr auto kH = 3;
constexpr auto kW = 3;
constexpr auto kC = 3;
auto phi_x = im2col_strided(x, {1, kH, kW, kC}, {1, 1, 1, kC}, {0, 0, 0, 1});
cout << "phi = " << phi_x.matrix().rows() << " " << phi_x.matrix().cols() << endl;
// kH x kW x kI kO
Tensor_<float, 2> k{{ 3 * 3 * 3, 3}};
// Average on the R channel.
k.matrix().col(0) <<
1, 0, 0, 1, 0, 0, 1, 0, 0,
1, 0, 0, 1, 0, 0, 1, 0, 0,
1, 0, 0, 1, 0, 0, 1, 0, 0;
// Average on the G channel.
k.matrix().col(1) <<
0, 1, 0, 0, 1, 0, 0, 1, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0;
// Average on the B channel.
k.matrix().col(2) <<
0, 0, 1, 0, 0, 1, 0, 0, 1,
0, 0, 1, 0, 0, 1, 0, 0, 1,
0, 0, 1, 0, 0, 1, 0, 0, 1;
k.flat_array() /= 9;
cout << "k = " << k.matrix().rows() << " " << k.matrix().cols() << endl;
cout << k.matrix() << endl;
auto y = Tensor_<float, 4>{{1, 3, image.height(), image.width()}};
y.flat_array() = (phi_x.matrix() * k.matrix()).array();
yt = transpose(y, {0, 2, 3, 1});
return convolved_image;
}
int test_rgb_image()
{
// Read an image.
auto image = Image<Rgb32f>{};
imread(image, "/home/david/GitHub/DO-CV/sara/data/sunflowerField.jpg");
auto image_tensor =
tensor_view(image).reshape(Vector4i{1, image.height(), image.width(), 3});
// N H W C -> N C H W
// 0 1 2 3 0 3 1 2
auto x = transpose(image_tensor, Vector4i{0, 3, 1, 2});
auto h = image.height();
auto w = image.width();
auto kernel = gaussian_kernel(5.f, 2);
auto kw = kernel.width();
auto kh = kernel.height();
auto kc = 3;
auto ksz = kernel.size();
auto k = Tensor_<float, 2>{{kh * kw * 3, 3}};
k.matrix().col(0) << kernel.flat_array(), VectorXf::Zero(ksz), VectorXf::Zero(ksz);
k.matrix().col(1) << VectorXf::Zero(ksz), kernel.flat_array(), VectorXf::Zero(ksz);
k.matrix().col(2) << VectorXf::Zero(ksz), VectorXf::Zero(ksz), kernel.flat_array();
auto phi_x = im2col_strided(x, {1, kc, kh, kw}, {1, kc, 1, 1}, {0, 1, 0, 0});
auto y = Tensor_<float, 4>{{1, 3, h, w}};
y.flat_array() = (phi_x.matrix() * k.matrix()).array();
y = transpose(y, Vector4i{0, 2, 3, 1});
auto convolved_image = ImageView<Rgb32f>{reinterpret_cast<Rgb32f *>(y.data()), {w, h}};
create_window(convolved_image.sizes());
display(image);
get_key();
display(convolved_image);
get_key();
close_window();
return EXIT_SUCCESS;
}
GRAPHICS_MAIN()
{
//return test_grayscale_image();
return test_rgb_image();
}
<commit_msg>MAINT: clean code.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2018 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#include <DO/Sara/Core/MultiArray/InfiniteMultiArrayView.hpp>
#include <DO/Sara/Core/Timer.hpp>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/ImageProcessing.hpp>
#include <DO/Sara/Core/Tensor.hpp>
#include <DO/Sara/ImageProcessing/GemmBasedConvolution.hpp>
using namespace std;
using namespace DO::Sara;
template <typename T, int N>
Tensor_<T, N> transpose(const TensorView_<T, N>& x, const Matrix<int, N, 1>& order)
{
Matrix<int, N, 1> out_sizes;
for (int i = 0; i < N; ++i)
out_sizes[i] = x.size(order[i]);
Tensor_<T, N> out{out_sizes};
auto in_c = x.begin_array();
Matrix<int, N, 1> out_c = Matrix<int, N, 1>::Zero();
for ( ; !in_c.end(); ++in_c)
{
for (int i = 0; i < N; ++i)
out_c[i] = in_c.position()[order[i]];
out(out_c) = *in_c;
}
return out;
}
// Compute the size of the Gaussian kernel.
auto gaussian_kernel(float sigma, int gauss_truncate)
-> Image<float>
{
auto kernel_size = int(2 * gauss_truncate * sigma + 1);
// Make sure the Gaussian kernel is at least of size 3 and is of odd size.
kernel_size = std::max(3, kernel_size);
if (kernel_size % 2 == 0)
++kernel_size;
// Create the 1D Gaussian kernel.
auto kernel = Image<float>(kernel_size, kernel_size);
auto sum = 0.f;
// Compute the value of the Gaussian and the normalizing factor.
for (int y = 0; y < kernel_size; ++y)
{
const auto v = float(y) - kernel_size / 2.f;
const auto ky = exp(-v * v / (2.f * sigma * sigma));
for (int x = 0; x < kernel_size; ++x)
{
const auto u = float(x) - kernel_size / 2.f;
auto kx = exp(-u * u / (2.f * sigma * sigma));
kernel(x, y) = kx * ky;
sum += kernel(x, y);
}
}
kernel.flat_array() /= sum;
return kernel;
};
int test_grayscale_image()
{
auto image = Image<float>{};
imread(image, "/home/david/GitHub/DO-CV/sara/data/sunflowerField.jpg");
//const auto kernel = gaussian_kernel(3.f, 2);
auto kernel = Image<float>{3, 3};
kernel.matrix() = Matrix3f::Ones() / 9;
auto x = tensor_view(image);
auto k = tensor_view(kernel);
#ifdef DEBUG
const Vector2i strides{4, 4};
const auto xi = x.begin_stepped_subarray(Vector2i::Zero(), x.sizes(), strides);
auto szs = xi.stepped_subarray_sizes();
std::reverse(szs.data(), szs.data() + szs.size());
auto convolved_image = Image<float>{szs};
auto y = tensor_view(convolved_image);
gemm_convolve_strided(y, x, k, strides);
#else
// Stride in HxW order.
const Vector2i strides{2, 2};
auto y = gemm_convolve_strided(x, k, strides);
auto convolved_image = image_view(y);
#endif
create_window(convolved_image.sizes());
//display(convolved_image.compute<ColorRescale>());
display(convolved_image);
get_key();
close_window();
return EXIT_SUCCESS;
}
int test_rgb_image()
{
// Read an image.
auto image = Image<Rgb32f>{};
imread(image, "/home/david/GitHub/DO-CV/sara/data/sunflowerField.jpg");
auto image_tensor =
tensor_view(image).reshape(Vector4i{1, image.height(), image.width(), 3});
// N H W C -> N C H W
// 0 1 2 3 0 3 1 2
auto x = transpose(image_tensor, Vector4i{0, 3, 1, 2});
auto h = image.height();
auto w = image.width();
const auto kernel = gaussian_kernel(3.f, 2);
const auto kw = kernel.width();
const auto kh = kernel.height();
const auto kc = 3;
const auto ksz = kernel.size();
auto k = Tensor_<float, 2>{{kh * kw * 3, 3}};
// R plane G plane B plane
k.matrix().col(0) << kernel.flat_array(), VectorXf::Zero(ksz), VectorXf::Zero(ksz);
k.matrix().col(1) << VectorXf::Zero(ksz), kernel.flat_array(), VectorXf::Zero(ksz);
k.matrix().col(2) << VectorXf::Zero(ksz), VectorXf::Zero(ksz), kernel.flat_array();
auto phi_x = im2col_strided(x, {1, kc, kh, kw}, {1, kc, 2, 2}, {0, 1, 0, 0});
auto y = Tensor_<float, 4>{{1, 3, h / 2, w / 2}};
y.flat_array() = (phi_x.matrix() * k.matrix()).array();
y = transpose(y, Vector4i{0, 2, 3, 1});
auto convolved_image =
ImageView<Rgb32f>{reinterpret_cast<Rgb32f*>(y.data()), {w / 2, h / 2}};
create_window(image.sizes());
display(image);
get_key();
display(convolved_image);
get_key();
close_window();
return EXIT_SUCCESS;
}
GRAPHICS_MAIN()
{
//return test_grayscale_image();
return test_rgb_image();
}
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/evaluation/utils.h"
#if !defined(_WIN32)
#include <dirent.h>
#endif
#include <sys/stat.h>
#include <algorithm>
#include <fstream>
#include <memory>
#include <string>
namespace tflite {
namespace evaluation {
namespace {
TfLiteDelegatePtr CreateNullDelegate() {
return TfLiteDelegatePtr(nullptr, [](TfLiteDelegate*) {});
}
} // namespace
std::string StripTrailingSlashes(const std::string& path) {
int end = path.size();
while (end > 0 && path[end - 1] == '/') {
end--;
}
return path.substr(0, end);
}
bool ReadFileLines(const std::string& file_path,
std::vector<std::string>* lines_output) {
if (!lines_output) {
return false;
}
std::ifstream stream(file_path.c_str());
if (!stream) {
return false;
}
std::string line;
while (std::getline(stream, line)) {
lines_output->push_back(line);
}
return true;
}
#if !defined(_WIN32)
TfLiteStatus GetSortedFileNames(
const std::string& directory, std::vector<std::string>* result,
const std::unordered_set<std::string>& extensions) {
DIR* dir;
struct dirent* ent;
if (result == nullptr) {
return kTfLiteError;
}
result->clear();
std::string dir_path = StripTrailingSlashes(directory);
if ((dir = opendir(dir_path.c_str())) != nullptr) {
while ((ent = readdir(dir)) != nullptr) {
if (ent->d_type == DT_DIR) continue;
std::string filename(std::string(ent->d_name));
size_t lastdot = filename.find_last_of(".");
std::string ext = lastdot != std::string::npos ? filename.substr(lastdot)
: std::string();
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
if (!extensions.empty() && extensions.find(ext) == extensions.end()) {
continue;
}
result->emplace_back(dir_path + "/" + filename);
}
closedir(dir);
} else {
return kTfLiteError;
}
std::sort(result->begin(), result->end());
return kTfLiteOk;
}
#endif
// TODO(b/138448769): Migrate delegate helper APIs to lite/testing.
TfLiteDelegatePtr CreateNNAPIDelegate() {
#if defined(__ANDROID__)
return TfLiteDelegatePtr(
NnApiDelegate(),
// NnApiDelegate() returns a singleton, so provide a no-op deleter.
[](TfLiteDelegate*) {});
#else
return TfLiteDelegatePtr(nullptr, [](TfLiteDelegate*) {});
#endif // defined(__ANDROID__)
}
TfLiteDelegatePtr CreateNNAPIDelegate(StatefulNnApiDelegate::Options options) {
#if defined(__ANDROID__)
return TfLiteDelegatePtr(
new StatefulNnApiDelegate(options), [](TfLiteDelegate* delegate) {
delete reinterpret_cast<StatefulNnApiDelegate*>(delegate);
});
#else
return CreateNullDelegate();
#endif // defined(__ANDROID__)
}
#if defined(__ANDROID__)
TfLiteDelegatePtr CreateGPUDelegate(TfLiteGpuDelegateOptionsV2* options) {
return TfLiteDelegatePtr(TfLiteGpuDelegateV2Create(options),
&TfLiteGpuDelegateV2Delete);
}
#endif // defined(__ANDROID__)
TfLiteDelegatePtr CreateGPUDelegate() {
#if defined(__ANDROID__)
TfLiteGpuDelegateOptionsV2 options = TfLiteGpuDelegateOptionsV2Default();
options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_LATENCY;
options.inference_preference =
TFLITE_GPU_INFERENCE_PREFERENCE_SUSTAINED_SPEED;
return CreateGPUDelegate(&options);
#else
return CreateNullDelegate();
#endif // defined(__ANDROID__)
}
TfLiteDelegatePtr CreateHexagonDelegate(
const std::string& library_directory_path, bool profiling) {
#if defined(__ANDROID__) && (defined(__arm__) || defined(__aarch64__))
TfLiteHexagonDelegateOptions options = {0};
options.print_graph_profile = profiling;
return CreateHexagonDelegate(&options, library_directory_path);
#else
return CreateNullDelegate();
#endif // defined(__ANDROID__)
}
#if defined(__ANDROID__) && (defined(__arm__) || defined(__aarch64__))
TfLiteDelegatePtr CreateHexagonDelegate(
const TfLiteHexagonDelegateOptions* options,
const std::string& library_directory_path) {
if (library_directory_path.empty()) {
TfLiteHexagonInit();
} else {
TfLiteHexagonInitWithPath(library_directory_path.c_str());
}
TfLiteDelegate* delegate = TfLiteHexagonDelegateCreate(options);
if (!delegate) {
TfLiteHexagonTearDown();
return CreateNullDelegate();
}
return TfLiteDelegatePtr(delegate, [](TfLiteDelegate* delegate) {
TfLiteHexagonDelegateDelete(delegate);
TfLiteHexagonTearDown();
});
}
#endif
// TODO(b/149248802): include XNNPACK delegate when the issue is resolved.
#if defined(__Fuchsia__) || defined(TFLITE_WITHOUT_XNNPACK)
TfLiteDelegatePtr CreateXNNPACKDelegate(int num_threads) {
return CreateNullDelegate();
}
#else
TfLiteDelegatePtr CreateXNNPACKDelegate() {
TfLiteXNNPackDelegateOptions xnnpack_options =
TfLiteXNNPackDelegateOptionsDefault();
return CreateXNNPACKDelegate(&xnnpack_options);
}
TfLiteDelegatePtr CreateXNNPACKDelegate(
const TfLiteXNNPackDelegateOptions* xnnpack_options) {
auto xnnpack_delegate = TfLiteXNNPackDelegateCreate(xnnpack_options);
return TfLiteDelegatePtr(xnnpack_delegate, [](TfLiteDelegate* delegate) {
TfLiteXNNPackDelegateDelete(delegate);
});
}
TfLiteDelegatePtr CreateXNNPACKDelegate(int num_threads) {
auto opts = TfLiteXNNPackDelegateOptionsDefault();
// Note that we don't want to use the thread pool for num_threads == 1.
opts.num_threads = num_threads > 1 ? num_threads : 0;
return CreateXNNPACKDelegate(&opts);
}
#endif
} // namespace evaluation
} // namespace tflite
<commit_msg>Remove the unnecessary address-returning operator and lamda expression.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/evaluation/utils.h"
#if !defined(_WIN32)
#include <dirent.h>
#endif
#include <sys/stat.h>
#include <algorithm>
#include <fstream>
#include <memory>
#include <string>
namespace tflite {
namespace evaluation {
namespace {
TfLiteDelegatePtr CreateNullDelegate() {
return TfLiteDelegatePtr(nullptr, [](TfLiteDelegate*) {});
}
} // namespace
std::string StripTrailingSlashes(const std::string& path) {
int end = path.size();
while (end > 0 && path[end - 1] == '/') {
end--;
}
return path.substr(0, end);
}
bool ReadFileLines(const std::string& file_path,
std::vector<std::string>* lines_output) {
if (!lines_output) {
return false;
}
std::ifstream stream(file_path.c_str());
if (!stream) {
return false;
}
std::string line;
while (std::getline(stream, line)) {
lines_output->push_back(line);
}
return true;
}
#if !defined(_WIN32)
TfLiteStatus GetSortedFileNames(
const std::string& directory, std::vector<std::string>* result,
const std::unordered_set<std::string>& extensions) {
DIR* dir;
struct dirent* ent;
if (result == nullptr) {
return kTfLiteError;
}
result->clear();
std::string dir_path = StripTrailingSlashes(directory);
if ((dir = opendir(dir_path.c_str())) != nullptr) {
while ((ent = readdir(dir)) != nullptr) {
if (ent->d_type == DT_DIR) continue;
std::string filename(std::string(ent->d_name));
size_t lastdot = filename.find_last_of(".");
std::string ext = lastdot != std::string::npos ? filename.substr(lastdot)
: std::string();
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
if (!extensions.empty() && extensions.find(ext) == extensions.end()) {
continue;
}
result->emplace_back(dir_path + "/" + filename);
}
closedir(dir);
} else {
return kTfLiteError;
}
std::sort(result->begin(), result->end());
return kTfLiteOk;
}
#endif
// TODO(b/138448769): Migrate delegate helper APIs to lite/testing.
TfLiteDelegatePtr CreateNNAPIDelegate() {
#if defined(__ANDROID__)
return TfLiteDelegatePtr(
NnApiDelegate(),
// NnApiDelegate() returns a singleton, so provide a no-op deleter.
[](TfLiteDelegate*) {});
#else
return TfLiteDelegatePtr(nullptr, [](TfLiteDelegate*) {});
#endif // defined(__ANDROID__)
}
TfLiteDelegatePtr CreateNNAPIDelegate(StatefulNnApiDelegate::Options options) {
#if defined(__ANDROID__)
return TfLiteDelegatePtr(
new StatefulNnApiDelegate(options), [](TfLiteDelegate* delegate) {
delete reinterpret_cast<StatefulNnApiDelegate*>(delegate);
});
#else
return CreateNullDelegate();
#endif // defined(__ANDROID__)
}
#if defined(__ANDROID__)
TfLiteDelegatePtr CreateGPUDelegate(TfLiteGpuDelegateOptionsV2* options) {
return TfLiteDelegatePtr(TfLiteGpuDelegateV2Create(options),
TfLiteGpuDelegateV2Delete);
}
#endif // defined(__ANDROID__)
TfLiteDelegatePtr CreateGPUDelegate() {
#if defined(__ANDROID__)
TfLiteGpuDelegateOptionsV2 options = TfLiteGpuDelegateOptionsV2Default();
options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_LATENCY;
options.inference_preference =
TFLITE_GPU_INFERENCE_PREFERENCE_SUSTAINED_SPEED;
return CreateGPUDelegate(&options);
#else
return CreateNullDelegate();
#endif // defined(__ANDROID__)
}
TfLiteDelegatePtr CreateHexagonDelegate(
const std::string& library_directory_path, bool profiling) {
#if defined(__ANDROID__) && (defined(__arm__) || defined(__aarch64__))
TfLiteHexagonDelegateOptions options = {0};
options.print_graph_profile = profiling;
return CreateHexagonDelegate(&options, library_directory_path);
#else
return CreateNullDelegate();
#endif // defined(__ANDROID__)
}
#if defined(__ANDROID__) && (defined(__arm__) || defined(__aarch64__))
TfLiteDelegatePtr CreateHexagonDelegate(
const TfLiteHexagonDelegateOptions* options,
const std::string& library_directory_path) {
if (library_directory_path.empty()) {
TfLiteHexagonInit();
} else {
TfLiteHexagonInitWithPath(library_directory_path.c_str());
}
TfLiteDelegate* delegate = TfLiteHexagonDelegateCreate(options);
if (!delegate) {
TfLiteHexagonTearDown();
return CreateNullDelegate();
}
return TfLiteDelegatePtr(delegate, [](TfLiteDelegate* delegate) {
TfLiteHexagonDelegateDelete(delegate);
TfLiteHexagonTearDown();
});
}
#endif
// TODO(b/149248802): include XNNPACK delegate when the issue is resolved.
#if defined(__Fuchsia__) || defined(TFLITE_WITHOUT_XNNPACK)
TfLiteDelegatePtr CreateXNNPACKDelegate(int num_threads) {
return CreateNullDelegate();
}
#else
TfLiteDelegatePtr CreateXNNPACKDelegate() {
TfLiteXNNPackDelegateOptions xnnpack_options =
TfLiteXNNPackDelegateOptionsDefault();
return CreateXNNPACKDelegate(&xnnpack_options);
}
TfLiteDelegatePtr CreateXNNPACKDelegate(
const TfLiteXNNPackDelegateOptions* xnnpack_options) {
auto xnnpack_delegate = TfLiteXNNPackDelegateCreate(xnnpack_options);
return TfLiteDelegatePtr(xnnpack_delegate, TfLiteXNNPackDelegateDelete);
}
TfLiteDelegatePtr CreateXNNPACKDelegate(int num_threads) {
auto opts = TfLiteXNNPackDelegateOptionsDefault();
// Note that we don't want to use the thread pool for num_threads == 1.
opts.num_threads = num_threads > 1 ? num_threads : 0;
return CreateXNNPACKDelegate(&opts);
}
#endif
} // namespace evaluation
} // namespace tflite
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tbxalign.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2005-01-18 15:35:39 $
*
* 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 _AEITEM_HXX
#include <svtools/aeitem.hxx>
#endif
#pragma hdrstop
#include "dialmgr.hxx"
#include "dialogs.hrc"
#include "tbxalign.hxx"
#include "tbxdraw.hxx"
#include "tbxdraw.hrc"
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SFX_IMAGEMGR_HXX
#include <sfx2/imagemgr.hxx>
#endif
#include <vcl/svapp.hxx>
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include <sfx2/app.hxx>
#include <vcl/toolbox.hxx>
SFX_IMPL_TOOLBOX_CONTROL(SvxTbxCtlAlign, SfxAllEnumItem);
/*************************************************************************
|*
|* Klasse fuer SwToolbox
|*
\************************************************************************/
SvxTbxCtlAlign::SvxTbxCtlAlign( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx )
, m_aSubTbName( RTL_CONSTASCII_USTRINGPARAM( "alignmentbar" ))
, m_aSubTbResName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/alignmentbar" ))
{
rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
rTbx.Invalidate();
m_aCommand = m_aCommandURL;
}
/*************************************************************************
|*
|* Wenn man ein PopupWindow erzeugen will
|*
\************************************************************************/
SfxPopupWindowType SvxTbxCtlAlign::GetPopupWindowType() const
{
return(SFX_POPUPWINDOW_ONCLICK);
}
/*************************************************************************
|*
|* Hier wird das Fenster erzeugt
|* Lage der Toolbox mit GetToolBox() abfragbar
|* rItemRect sind die Screen-Koordinaten
|*
\************************************************************************/
SfxPopupWindow* SvxTbxCtlAlign::CreatePopupWindow()
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( GetSlotId() == SID_OBJECT_ALIGN )
createAndPositionSubToolBar( m_aSubTbResName );
return NULL;
}
//========================================================================
// XSubToolbarController
//========================================================================
::sal_Bool SAL_CALL SvxTbxCtlAlign::opensSubToolbar() throw (::com::sun::star::uno::RuntimeException)
{
// We control a sub-toolbar therefor, we have to return true.
return sal_True;
}
::rtl::OUString SAL_CALL SvxTbxCtlAlign::getSubToolbarName() throw (::com::sun::star::uno::RuntimeException)
{
// Provide the controlled sub-toolbar name, so we are notified whenever
// this toolbar executes a function.
::vos::OGuard aGuard( Application::GetSolarMutex() );
return m_aSubTbName;
}
void SAL_CALL SvxTbxCtlAlign::functionSelected( const ::rtl::OUString& aCommand ) throw (::com::sun::star::uno::RuntimeException)
{
// Our sub-toolbar wants to executes a function. We have to change
// the image of our toolbar button to reflect the new function.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( !m_bDisposed )
{
if ( aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
}
void SAL_CALL SvxTbxCtlAlign::updateImage() throw (::com::sun::star::uno::RuntimeException)
{
// We should update the button image of our parent (toolbar). Use the stored
// command to set the correct current image.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( m_aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, m_aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.444); FILE MERGED 2005/09/05 14:27:48 rt 1.4.444.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tbxalign.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:52:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _AEITEM_HXX
#include <svtools/aeitem.hxx>
#endif
#pragma hdrstop
#include "dialmgr.hxx"
#include "dialogs.hrc"
#include "tbxalign.hxx"
#include "tbxdraw.hxx"
#include "tbxdraw.hrc"
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SFX_IMAGEMGR_HXX
#include <sfx2/imagemgr.hxx>
#endif
#include <vcl/svapp.hxx>
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include <sfx2/app.hxx>
#include <vcl/toolbox.hxx>
SFX_IMPL_TOOLBOX_CONTROL(SvxTbxCtlAlign, SfxAllEnumItem);
/*************************************************************************
|*
|* Klasse fuer SwToolbox
|*
\************************************************************************/
SvxTbxCtlAlign::SvxTbxCtlAlign( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx )
, m_aSubTbName( RTL_CONSTASCII_USTRINGPARAM( "alignmentbar" ))
, m_aSubTbResName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/alignmentbar" ))
{
rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
rTbx.Invalidate();
m_aCommand = m_aCommandURL;
}
/*************************************************************************
|*
|* Wenn man ein PopupWindow erzeugen will
|*
\************************************************************************/
SfxPopupWindowType SvxTbxCtlAlign::GetPopupWindowType() const
{
return(SFX_POPUPWINDOW_ONCLICK);
}
/*************************************************************************
|*
|* Hier wird das Fenster erzeugt
|* Lage der Toolbox mit GetToolBox() abfragbar
|* rItemRect sind die Screen-Koordinaten
|*
\************************************************************************/
SfxPopupWindow* SvxTbxCtlAlign::CreatePopupWindow()
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( GetSlotId() == SID_OBJECT_ALIGN )
createAndPositionSubToolBar( m_aSubTbResName );
return NULL;
}
//========================================================================
// XSubToolbarController
//========================================================================
::sal_Bool SAL_CALL SvxTbxCtlAlign::opensSubToolbar() throw (::com::sun::star::uno::RuntimeException)
{
// We control a sub-toolbar therefor, we have to return true.
return sal_True;
}
::rtl::OUString SAL_CALL SvxTbxCtlAlign::getSubToolbarName() throw (::com::sun::star::uno::RuntimeException)
{
// Provide the controlled sub-toolbar name, so we are notified whenever
// this toolbar executes a function.
::vos::OGuard aGuard( Application::GetSolarMutex() );
return m_aSubTbName;
}
void SAL_CALL SvxTbxCtlAlign::functionSelected( const ::rtl::OUString& aCommand ) throw (::com::sun::star::uno::RuntimeException)
{
// Our sub-toolbar wants to executes a function. We have to change
// the image of our toolbar button to reflect the new function.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( !m_bDisposed )
{
if ( aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
}
void SAL_CALL SvxTbxCtlAlign::updateImage() throw (::com::sun::star::uno::RuntimeException)
{
// We should update the button image of our parent (toolbar). Use the stored
// command to set the correct current image.
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( m_aCommand.getLength() > 0 )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame( getFrameInterface());
Image aImage = GetImage( xFrame, m_aCommand, hasBigImages(), isHighContrast() );
if ( !!aImage )
GetToolBox().SetItemImage( GetId(), aImage );
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: regionsw.cxx,v $
*
* $Revision: 1.36 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:49:36 $
*
* 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_sw.hxx"
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _UITOOL_HXX
#include <uitool.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _SVTOOLS_PASSWORDHELPER_HXX
#include <svtools/PasswordHelper.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _PASSWD_HXX //autogen
#include <sfx2/passwd.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX //autogen
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif
#ifndef _LINKMGR_HXX
#include <sfx2/linkmgr.hxx>
#endif
#ifndef _SVX_SIZEITEM_HXX //autogen
#define ITEMID_SIZE 0
#include <svx/sizeitem.hxx>
#endif
#include <svx/htmlcfg.hxx>
#ifndef _BOOKMRK_HXX //autogen
#include <bookmrk.hxx>
#endif
#ifndef _SECTION_HXX
#include <section.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _REGIONSW_HXX
#include <regionsw.hxx>
#endif
#ifndef _BASESH_HXX
#include <basesh.hxx>
#endif
#ifndef _WDOCSH_HXX
#include <wdocsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo-Ids
#endif
#ifndef _COLUMN_HXX
#include <column.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _SWUNODEF_HXX
#include <swunodef.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _HELPID_H
#include <helpid.h>
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _REGIONSW_HRC
#include <regionsw.hrc>
#endif
#ifndef _COMCORE_HRC
#include <comcore.hrc>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#ifndef _SFX_BINDINGS_HXX
#include <sfx2/bindings.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
#ifndef _SVX_DLGUTIL_HXX
#include <svx/dlgutil.hxx>
#endif
#include "swabstdlg.hxx" //CHINA001
/*--------------------------------------------------------------------
Beschreibung: Bereiche einfuegen
--------------------------------------------------------------------*/
void SwBaseShell::InsertRegionDialog(SfxRequest& rReq)
{
SwWrtShell& rSh = GetShell();
const SfxItemSet *pSet = rReq.GetArgs();
SfxItemSet aSet(GetPool(),
RES_COL, RES_COL,
RES_LR_SPACE, RES_LR_SPACE,
RES_COLUMNBALANCE, RES_FRAMEDIR,
RES_BACKGROUND, RES_BACKGROUND,
RES_FRM_SIZE, RES_FRM_SIZE,
RES_FTN_AT_TXTEND, RES_END_AT_TXTEND,
SID_ATTR_PAGE_SIZE, SID_ATTR_PAGE_SIZE,
0);
if (!pSet || pSet->Count()==0)
{
SwRect aRect;
rSh.CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
aSet.Put(SwFmtFrmSize(ATT_VAR_SIZE, nWidth));
// Hoehe=Breite fuer konsistentere Vorschau (analog zu Bereich bearbeiten)
aSet.Put(SvxSizeItem(SID_ATTR_PAGE_SIZE, Size(nWidth, nWidth)));
//CHINA001 SwInsertSectionTabDialog aTabDlg(&GetView().GetViewFrame()->GetWindow(),aSet , rSh);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractInsertSectionTabDialog* aTabDlg = pFact->CreateInsertSectionTabDialog( ResId(DLG_INSERT_SECTION),
&GetView().GetViewFrame()->GetWindow(), aSet , rSh);
DBG_ASSERT(aTabDlg, "Dialogdiet fail!");//CHINA001
aTabDlg->Execute(); //CHINA001 aTabDlg.Execute();
rReq.Ignore();
delete aTabDlg; //add for CHINA001
}
else
{
const SfxPoolItem *pItem = 0;
String aTmpStr;
if ( SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_NAME, TRUE, &pItem) )
aTmpStr = rSh.GetUniqueSectionName(
&((const SfxStringItem *)pItem)->GetValue() );
else
aTmpStr = rSh.GetUniqueSectionName();
SwSection aSection(CONTENT_SECTION,aTmpStr);
rReq.SetReturnValue(SfxStringItem(FN_INSERT_REGION, aTmpStr));
aSet.Put( *pSet );
if(SFX_ITEM_SET == pSet->GetItemState(SID_ATTR_COLUMNS, FALSE, &pItem)||
SFX_ITEM_SET == pSet->GetItemState(FN_INSERT_REGION, FALSE, &pItem))
{
SwFmtCol aCol;
SwRect aRect;
rSh.CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
USHORT nCol = ((SfxUInt16Item *)pItem)->GetValue();
if(nCol)
{
aCol.Init( nCol, 0, nWidth );
aSet.Put(aCol);
}
}
else if(SFX_ITEM_SET == pSet->GetItemState(RES_COL, FALSE, &pItem))
{
aSet.Put(*pItem);
}
const BOOL bHidden = SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_HIDDEN, TRUE, &pItem)?
(BOOL)((const SfxBoolItem *)pItem)->GetValue():FALSE;
const BOOL bProtect = SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_PROTECT, TRUE, &pItem)?
(BOOL)((const SfxBoolItem *)pItem)->GetValue():FALSE;
// --> FME 2004-06-22 #114856# edit in readonly sections
const BOOL bEditInReadonly = SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_EDIT_IN_READONLY, TRUE, &pItem)?
(BOOL)((const SfxBoolItem *)pItem)->GetValue():FALSE;
// <--
aSection.SetProtect(bProtect);
aSection.SetHidden(bHidden);
// --> FME 2004-06-22 #114856# edit in readonly sections
aSection.SetEditInReadonly(bEditInReadonly);
// <--
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_CONDITION, TRUE, &pItem))
aSection.SetCondition(((const SfxStringItem *)pItem)->GetValue());
String aFile, aSub;
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_1, TRUE, &pItem))
aFile = ((const SfxStringItem *)pItem)->GetValue();
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_3, TRUE, &pItem))
aSub = ((const SfxStringItem *)pItem)->GetValue();
if(aFile.Len() || aSub.Len())
{
String sLinkFileName(sfx2::cTokenSeperator);
sLinkFileName += sfx2::cTokenSeperator;
sLinkFileName.SetToken(0, sfx2::cTokenSeperator,aFile);
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_2, TRUE, &pItem))
sLinkFileName.SetToken(1, sfx2::cTokenSeperator,
((const SfxStringItem *)pItem)->GetValue());
sLinkFileName += aSub;
aSection.SetType( FILE_LINK_SECTION );
aSection.SetLinkFileName(sLinkFileName);
}
rSh.InsertSection(aSection, aSet.Count() ? &aSet : 0);
rReq.Done();
}
}
IMPL_STATIC_LINK( SwWrtShell, InsertRegionDialog, SwSection*, pSect )
{
if( pSect )
{
SfxItemSet aSet(pThis->GetView().GetPool(),
RES_COL, RES_COL,
RES_BACKGROUND, RES_BACKGROUND,
RES_FRM_SIZE, RES_FRM_SIZE,
SID_ATTR_PAGE_SIZE, SID_ATTR_PAGE_SIZE,
0);
SwRect aRect;
pThis->CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
aSet.Put(SwFmtFrmSize(ATT_VAR_SIZE, nWidth));
// Hoehe=Breite fuer konsistentere Vorschau (analog zu Bereich bearbeiten)
aSet.Put(SvxSizeItem(SID_ATTR_PAGE_SIZE, Size(nWidth, nWidth)));
//CHINA001 SwInsertSectionTabDialog aTabDlg(&pThis->GetView().GetViewFrame()->GetWindow(),aSet , *pThis);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractInsertSectionTabDialog* aTabDlg = pFact->CreateInsertSectionTabDialog( ResId(DLG_INSERT_SECTION),
&pThis->GetView().GetViewFrame()->GetWindow(),aSet , *pThis);
DBG_ASSERT(aTabDlg, "Dialogdiet fail!");//CHINA001
aTabDlg->SetSection(*pSect); //CHINA001 aTabDlg.SetSection(*pSect);
aTabDlg->Execute(); //CHINA001 aTabDlg.Execute();
delete pSect;
delete aTabDlg; //add for CHINA001
}
return 0;
}
/*--------------------------------------------------------------------
Beschreibung: Bereich bearbeiten
--------------------------------------------------------------------*/
void SwBaseShell::EditRegionDialog(SfxRequest& rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
int nSlot = rReq.GetSlot();
const SfxPoolItem* pItem = 0;
if(pArgs)
pArgs->GetItemState(nSlot, FALSE, &pItem);
SwWrtShell& rWrtShell = GetShell();
switch ( nSlot )
{
case FN_EDIT_REGION:
{
Window* pParentWin = &GetView().GetViewFrame()->GetWindow();
BOOL bStart = TRUE;
if(bStart)
{
//CHINA001 SwEditRegionDlg* pEditRegionDlg = new SwEditRegionDlg(
//CHINA001 pParentWin, rWrtShell );
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractEditRegionDlg* pEditRegionDlg = pFact->CreateEditRegionDlg( ResId(MD_EDIT_REGION),
pParentWin, rWrtShell);
DBG_ASSERT(pEditRegionDlg, "Dialogdiet fail!");//CHINA001
if(pItem && pItem->ISA(SfxStringItem))
{
pEditRegionDlg->SelectSection(((const SfxStringItem*)pItem)->GetValue());
}
pEditRegionDlg->Execute();
delete pEditRegionDlg;
}
else
InfoBox(pParentWin, SW_RES(REG_WRONG_PASSWORD)).Execute();
}
break;
}
}
<commit_msg>INTEGRATION: CWS residcleanup (1.36.240); FILE MERGED 2007/03/04 17:02:59 pl 1.36.240.1: #i73635# ResId cleanup<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: regionsw.cxx,v $
*
* $Revision: 1.37 $
*
* last change: $Author: rt $ $Date: 2007-04-26 09:05:54 $
*
* 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_sw.hxx"
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _UITOOL_HXX
#include <uitool.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _SVTOOLS_PASSWORDHELPER_HXX
#include <svtools/PasswordHelper.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _PASSWD_HXX //autogen
#include <sfx2/passwd.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX //autogen
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif
#ifndef _LINKMGR_HXX
#include <sfx2/linkmgr.hxx>
#endif
#ifndef _SVX_SIZEITEM_HXX //autogen
#define ITEMID_SIZE 0
#include <svx/sizeitem.hxx>
#endif
#include <svx/htmlcfg.hxx>
#ifndef _BOOKMRK_HXX //autogen
#include <bookmrk.hxx>
#endif
#ifndef _SECTION_HXX
#include <section.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _REGIONSW_HXX
#include <regionsw.hxx>
#endif
#ifndef _BASESH_HXX
#include <basesh.hxx>
#endif
#ifndef _WDOCSH_HXX
#include <wdocsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo-Ids
#endif
#ifndef _COLUMN_HXX
#include <column.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _SWUNODEF_HXX
#include <swunodef.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _HELPID_H
#include <helpid.h>
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _REGIONSW_HRC
#include <regionsw.hrc>
#endif
#ifndef _COMCORE_HRC
#include <comcore.hrc>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#ifndef _SFX_BINDINGS_HXX
#include <sfx2/bindings.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
#ifndef _SVX_DLGUTIL_HXX
#include <svx/dlgutil.hxx>
#endif
#include "swabstdlg.hxx" //CHINA001
/*--------------------------------------------------------------------
Beschreibung: Bereiche einfuegen
--------------------------------------------------------------------*/
void SwBaseShell::InsertRegionDialog(SfxRequest& rReq)
{
SwWrtShell& rSh = GetShell();
const SfxItemSet *pSet = rReq.GetArgs();
SfxItemSet aSet(GetPool(),
RES_COL, RES_COL,
RES_LR_SPACE, RES_LR_SPACE,
RES_COLUMNBALANCE, RES_FRAMEDIR,
RES_BACKGROUND, RES_BACKGROUND,
RES_FRM_SIZE, RES_FRM_SIZE,
RES_FTN_AT_TXTEND, RES_END_AT_TXTEND,
SID_ATTR_PAGE_SIZE, SID_ATTR_PAGE_SIZE,
0);
if (!pSet || pSet->Count()==0)
{
SwRect aRect;
rSh.CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
aSet.Put(SwFmtFrmSize(ATT_VAR_SIZE, nWidth));
// Hoehe=Breite fuer konsistentere Vorschau (analog zu Bereich bearbeiten)
aSet.Put(SvxSizeItem(SID_ATTR_PAGE_SIZE, Size(nWidth, nWidth)));
//CHINA001 SwInsertSectionTabDialog aTabDlg(&GetView().GetViewFrame()->GetWindow(),aSet , rSh);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractInsertSectionTabDialog* aTabDlg = pFact->CreateInsertSectionTabDialog( DLG_INSERT_SECTION,
&GetView().GetViewFrame()->GetWindow(), aSet , rSh);
DBG_ASSERT(aTabDlg, "Dialogdiet fail!");//CHINA001
aTabDlg->Execute(); //CHINA001 aTabDlg.Execute();
rReq.Ignore();
delete aTabDlg; //add for CHINA001
}
else
{
const SfxPoolItem *pItem = 0;
String aTmpStr;
if ( SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_NAME, TRUE, &pItem) )
aTmpStr = rSh.GetUniqueSectionName(
&((const SfxStringItem *)pItem)->GetValue() );
else
aTmpStr = rSh.GetUniqueSectionName();
SwSection aSection(CONTENT_SECTION,aTmpStr);
rReq.SetReturnValue(SfxStringItem(FN_INSERT_REGION, aTmpStr));
aSet.Put( *pSet );
if(SFX_ITEM_SET == pSet->GetItemState(SID_ATTR_COLUMNS, FALSE, &pItem)||
SFX_ITEM_SET == pSet->GetItemState(FN_INSERT_REGION, FALSE, &pItem))
{
SwFmtCol aCol;
SwRect aRect;
rSh.CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
USHORT nCol = ((SfxUInt16Item *)pItem)->GetValue();
if(nCol)
{
aCol.Init( nCol, 0, nWidth );
aSet.Put(aCol);
}
}
else if(SFX_ITEM_SET == pSet->GetItemState(RES_COL, FALSE, &pItem))
{
aSet.Put(*pItem);
}
const BOOL bHidden = SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_HIDDEN, TRUE, &pItem)?
(BOOL)((const SfxBoolItem *)pItem)->GetValue():FALSE;
const BOOL bProtect = SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_PROTECT, TRUE, &pItem)?
(BOOL)((const SfxBoolItem *)pItem)->GetValue():FALSE;
// --> FME 2004-06-22 #114856# edit in readonly sections
const BOOL bEditInReadonly = SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_EDIT_IN_READONLY, TRUE, &pItem)?
(BOOL)((const SfxBoolItem *)pItem)->GetValue():FALSE;
// <--
aSection.SetProtect(bProtect);
aSection.SetHidden(bHidden);
// --> FME 2004-06-22 #114856# edit in readonly sections
aSection.SetEditInReadonly(bEditInReadonly);
// <--
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_REGION_CONDITION, TRUE, &pItem))
aSection.SetCondition(((const SfxStringItem *)pItem)->GetValue());
String aFile, aSub;
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_1, TRUE, &pItem))
aFile = ((const SfxStringItem *)pItem)->GetValue();
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_3, TRUE, &pItem))
aSub = ((const SfxStringItem *)pItem)->GetValue();
if(aFile.Len() || aSub.Len())
{
String sLinkFileName(sfx2::cTokenSeperator);
sLinkFileName += sfx2::cTokenSeperator;
sLinkFileName.SetToken(0, sfx2::cTokenSeperator,aFile);
if(SFX_ITEM_SET ==
pSet->GetItemState(FN_PARAM_2, TRUE, &pItem))
sLinkFileName.SetToken(1, sfx2::cTokenSeperator,
((const SfxStringItem *)pItem)->GetValue());
sLinkFileName += aSub;
aSection.SetType( FILE_LINK_SECTION );
aSection.SetLinkFileName(sLinkFileName);
}
rSh.InsertSection(aSection, aSet.Count() ? &aSet : 0);
rReq.Done();
}
}
IMPL_STATIC_LINK( SwWrtShell, InsertRegionDialog, SwSection*, pSect )
{
if( pSect )
{
SfxItemSet aSet(pThis->GetView().GetPool(),
RES_COL, RES_COL,
RES_BACKGROUND, RES_BACKGROUND,
RES_FRM_SIZE, RES_FRM_SIZE,
SID_ATTR_PAGE_SIZE, SID_ATTR_PAGE_SIZE,
0);
SwRect aRect;
pThis->CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
aSet.Put(SwFmtFrmSize(ATT_VAR_SIZE, nWidth));
// Hoehe=Breite fuer konsistentere Vorschau (analog zu Bereich bearbeiten)
aSet.Put(SvxSizeItem(SID_ATTR_PAGE_SIZE, Size(nWidth, nWidth)));
//CHINA001 SwInsertSectionTabDialog aTabDlg(&pThis->GetView().GetViewFrame()->GetWindow(),aSet , *pThis);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractInsertSectionTabDialog* aTabDlg = pFact->CreateInsertSectionTabDialog( DLG_INSERT_SECTION,
&pThis->GetView().GetViewFrame()->GetWindow(),aSet , *pThis);
DBG_ASSERT(aTabDlg, "Dialogdiet fail!");//CHINA001
aTabDlg->SetSection(*pSect); //CHINA001 aTabDlg.SetSection(*pSect);
aTabDlg->Execute(); //CHINA001 aTabDlg.Execute();
delete pSect;
delete aTabDlg; //add for CHINA001
}
return 0;
}
/*--------------------------------------------------------------------
Beschreibung: Bereich bearbeiten
--------------------------------------------------------------------*/
void SwBaseShell::EditRegionDialog(SfxRequest& rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
int nSlot = rReq.GetSlot();
const SfxPoolItem* pItem = 0;
if(pArgs)
pArgs->GetItemState(nSlot, FALSE, &pItem);
SwWrtShell& rWrtShell = GetShell();
switch ( nSlot )
{
case FN_EDIT_REGION:
{
Window* pParentWin = &GetView().GetViewFrame()->GetWindow();
BOOL bStart = TRUE;
if(bStart)
{
//CHINA001 SwEditRegionDlg* pEditRegionDlg = new SwEditRegionDlg(
//CHINA001 pParentWin, rWrtShell );
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractEditRegionDlg* pEditRegionDlg = pFact->CreateEditRegionDlg( MD_EDIT_REGION,
pParentWin, rWrtShell);
DBG_ASSERT(pEditRegionDlg, "Dialogdiet fail!");//CHINA001
if(pItem && pItem->ISA(SfxStringItem))
{
pEditRegionDlg->SelectSection(((const SfxStringItem*)pItem)->GetValue());
}
pEditRegionDlg->Execute();
delete pEditRegionDlg;
}
else
InfoBox(pParentWin, SW_RES(REG_WRONG_PASSWORD)).Execute();
}
break;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textglos.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:53:51 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#include "errhdl.hxx"
#include "view.hxx"
#include "initui.hxx"
#include "cmdid.h"
#include "textsh.hxx"
#include "initui.hxx"
//CHINA001 #include "glossary.hxx"
#include "gloshdl.hxx"
#include "glosdoc.hxx"
#include "gloslst.hxx"
#include "swabstdlg.hxx" //CHINA001
#include <misc.hrc> //CHINA001
// STATIC DATA -----------------------------------------------------------
void SwTextShell::ExecGlossary(SfxRequest &rReq)
{
USHORT nSlot = rReq.GetSlot();
::GetGlossaries()->UpdateGlosPath(!rReq.IsAPI() ||
FN_GLOSSARY_DLG == nSlot );
SwGlossaryHdl* pGlosHdl = GetView().GetGlosHdl();
// SwGlossaryList updaten?
BOOL bUpdateList = FALSE;
const SfxItemSet *pArgs = rReq.GetArgs();
const SfxPoolItem* pItem = 0;
if(pArgs)
pArgs->GetItemState(nSlot, FALSE, &pItem );
switch( nSlot )
{
case FN_GLOSSARY_DLG:
pGlosHdl->GlossaryDlg();
bUpdateList = TRUE;
rReq.Ignore();
break;
case FN_EXPAND_GLOSSARY:
{
BOOL bReturn;
bReturn = pGlosHdl->ExpandGlossary( TRUE );
rReq.SetReturnValue( SfxBoolItem( nSlot, bReturn ) );
rReq.Done();
}
break;
case FN_NEW_GLOSSARY:
if(pItem && pArgs->Count() == 3 )
{
String aGroup = (( const SfxStringItem *)pItem)->GetValue();
String aName;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_1, FALSE, &pItem ))
aName = (( const SfxStringItem *)pItem)->GetValue();
String aShortName;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_2, FALSE, &pItem ))
aShortName = (( const SfxStringItem *)pItem)->GetValue();
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
::GlossarySetActGroup fnSetActGroup = pFact->SetGlossaryActGroupFunc( DLG_RENAME_GLOS );
if ( fnSetActGroup )
(*fnSetActGroup)( aGroup );
//CHINA001 end
pGlosHdl->SetCurGroup(aGroup, TRUE);
//eingestellte Gruppe muss in NewGlossary ggf. erzeugt werden!
pGlosHdl->NewGlossary( aName, aShortName, TRUE );
rReq.Done();
}
bUpdateList = TRUE;
break;
case FN_SET_ACT_GLOSSARY:
if(pItem)
{
String aGroup = (( const SfxStringItem *)pItem)->GetValue();
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
::GlossarySetActGroup fnSetActGroup = pFact->SetGlossaryActGroupFunc( DLG_RENAME_GLOS );
if ( fnSetActGroup )
(*fnSetActGroup)( aGroup );
//CHINA001 end
rReq.Done();
}
break;
case FN_INSERT_GLOSSARY:
{
if(pItem && pArgs->Count() > 1)
{
String aGroup = (( const SfxStringItem *)pItem)->GetValue();
String aName;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_1, FALSE, &pItem ))
aName = (( const SfxStringItem *)pItem)->GetValue();
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
::GlossarySetActGroup fnSetActGroup = pFact->SetGlossaryActGroupFunc( DLG_RENAME_GLOS );
if ( fnSetActGroup )
(*fnSetActGroup)( aGroup );
//CHINA001 end
pGlosHdl->SetCurGroup(aGroup, TRUE);
rReq.SetReturnValue(SfxBoolItem(nSlot, pGlosHdl->InsertGlossary( aName )));
rReq.Done();
}
}
break;
default:
ASSERT(FALSE, falscher Dispatcher);
return;
}
if(bUpdateList)
{
SwGlossaryList* pList = ::GetGlossaryList();
if(pList->IsActive())
pList->Update();
}
}
<commit_msg>INTEGRATION: CWS writercorehandoff (1.6.466); FILE MERGED 2005/09/13 18:22:57 tra 1.6.466.3: RESYNC: (1.6-1.7); FILE MERGED 2005/06/07 14:16:00 fme 1.6.466.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:30:00 tra 1.6.466.1: Unnecessary includes removed #i50348#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textglos.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:54:47 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#include "errhdl.hxx"
#include "view.hxx"
#include "initui.hxx"
#include "cmdid.h"
#include "textsh.hxx"
#include "initui.hxx"
//CHINA001 #include "glossary.hxx"
#include "gloshdl.hxx"
#include "glosdoc.hxx"
#include "gloslst.hxx"
#include "swabstdlg.hxx" //CHINA001
#include <misc.hrc> //CHINA001
// STATIC DATA -----------------------------------------------------------
void SwTextShell::ExecGlossary(SfxRequest &rReq)
{
USHORT nSlot = rReq.GetSlot();
::GetGlossaries()->UpdateGlosPath(!rReq.IsAPI() ||
FN_GLOSSARY_DLG == nSlot );
SwGlossaryHdl* pGlosHdl = GetView().GetGlosHdl();
// SwGlossaryList updaten?
BOOL bUpdateList = FALSE;
const SfxItemSet *pArgs = rReq.GetArgs();
const SfxPoolItem* pItem = 0;
if(pArgs)
pArgs->GetItemState(nSlot, FALSE, &pItem );
switch( nSlot )
{
case FN_GLOSSARY_DLG:
pGlosHdl->GlossaryDlg();
bUpdateList = TRUE;
rReq.Ignore();
break;
case FN_EXPAND_GLOSSARY:
{
BOOL bReturn;
bReturn = pGlosHdl->ExpandGlossary( TRUE );
rReq.SetReturnValue( SfxBoolItem( nSlot, bReturn ) );
rReq.Done();
}
break;
case FN_NEW_GLOSSARY:
if(pItem && pArgs->Count() == 3 )
{
String aGroup = (( const SfxStringItem *)pItem)->GetValue();
String aName;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_1, FALSE, &pItem ))
aName = (( const SfxStringItem *)pItem)->GetValue();
String aShortName;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_2, FALSE, &pItem ))
aShortName = (( const SfxStringItem *)pItem)->GetValue();
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
::GlossarySetActGroup fnSetActGroup = pFact->SetGlossaryActGroupFunc( DLG_RENAME_GLOS );
if ( fnSetActGroup )
(*fnSetActGroup)( aGroup );
//CHINA001 end
pGlosHdl->SetCurGroup(aGroup, TRUE);
//eingestellte Gruppe muss in NewGlossary ggf. erzeugt werden!
pGlosHdl->NewGlossary( aName, aShortName, TRUE );
rReq.Done();
}
bUpdateList = TRUE;
break;
case FN_SET_ACT_GLOSSARY:
if(pItem)
{
String aGroup = (( const SfxStringItem *)pItem)->GetValue();
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
::GlossarySetActGroup fnSetActGroup = pFact->SetGlossaryActGroupFunc( DLG_RENAME_GLOS );
if ( fnSetActGroup )
(*fnSetActGroup)( aGroup );
//CHINA001 end
rReq.Done();
}
break;
case FN_INSERT_GLOSSARY:
{
if(pItem && pArgs->Count() > 1)
{
String aGroup = (( const SfxStringItem *)pItem)->GetValue();
String aName;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_1, FALSE, &pItem ))
aName = (( const SfxStringItem *)pItem)->GetValue();
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
::GlossarySetActGroup fnSetActGroup = pFact->SetGlossaryActGroupFunc( DLG_RENAME_GLOS );
if ( fnSetActGroup )
(*fnSetActGroup)( aGroup );
//CHINA001 end
pGlosHdl->SetCurGroup(aGroup, TRUE);
rReq.SetReturnValue(SfxBoolItem(nSlot, pGlosHdl->InsertGlossary( aName )));
rReq.Done();
}
}
break;
default:
ASSERT(FALSE, falscher Dispatcher);
return;
}
if(bUpdateList)
{
SwGlossaryList* pList = ::GetGlossaryList();
if(pList->IsActive())
pList->Update();
}
}
<|endoftext|> |
<commit_before>#include "../../../shared/generated/cpp/WebViewBase.h"
#include "../../../shared/System.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "rubyext/WebView.h"
//extern "C" HWND getMainWnd();
namespace rho {
using namespace apiGenerator;
using namespace common;
class CWebViewImpl: public CWebViewSingletonBase
{
int m_nNavigationTimeout;
double m_dZoomPage;
int m_nTextZoom;
public:
CWebViewImpl(): CWebViewSingletonBase(), m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1) {}
virtual void getFramework(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(System::getWebviewFramework());
}
virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(rho_webview_get_full_screen() != 0 ? true : false );
}
virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_full_screen_mode(value ? 1 : 0);
}
virtual void getNativeMenu(rho::apiGenerator::CMethodResult& oResult)
{
rho::Vector< Hashtable<String, String> > arRes;
RHODESAPP().getAppMenu().getMenuItemsEx(arRes);
oResult.set(arRes);
}
virtual void setNativeMenu( const rho::Vector<rho::String>& value, rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().getAppMenu().setAppMenuJSONItemsEx(value);
}
//Android only
virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){}
virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(false);
}
virtual void getEnableMediaPlaybackWithoutGesture(rho::apiGenerator::CMethodResult& oResult) {
oResult.set(false);
}
virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult){}
virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){}
//
virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(m_nNavigationTimeout);
}
virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult)
{
//m_nNavigationTimeout = value;
//rho_webview_setNavigationTimeout(m_nNavigationTimeout);
//TODO: implement rho_webview_setNavigationTimeout
}
virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("WebView.scrollTechnique") );
}
virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("WebView.fontFamily") );
}
virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("WebView.userAgent") );
}
virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getBool("WebView.viewportEnabled") );
}
virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getInt("WebView.viewportWidth") );
}
virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getInt("WebView.cacheSize") );
}
//TODO: EnableCache - does it supported by Webkit ?
virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){}
virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){}
//TODO: AcceptLanguage - does it supported by Webkit ?
virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){}
virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){}
virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(m_dZoomPage);
}
virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult)
{
//m_dZoomPage = value;
//RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage);
// TODO: implement webview zoom
}
virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( 1. );//m_nTextZoom
}
virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult)
{
//m_nTextZoom = value;
//RHODESAPP().getExtManager().zoomText( m_nTextZoom );
// TODO: implement webview zoom
}
virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_refresh(tabIndex);
}
virtual void navigate( const rho::String& url, int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_navigate(url.c_str(), tabIndex);
}
virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
//rho_webview_navigate_back();
//commented because every time it is navigating with default -1 instead of user defined tab index.
rho_webview_navigate_back_with_tab(tabIndex);
}
virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_current_location(tabIndex) );
}
virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_current_location(tabIndex) );
}
virtual void executeJavascript( const rho::String& javascriptText, int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_execute_js( javascriptText.c_str(), tabIndex );
}
virtual void active_tab(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_active_tab() );
}
virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_active_tab() );
}
virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_full_screen_mode(enable ? 1 : 0);
}
virtual void setCookie( const rho::String& url, const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_set_cookie( strdup(url.c_str()), strdup(cookie.c_str()) );
}
//Android only
virtual void save( const rho::String& format, const rho::String& path, int tabIndex, rho::apiGenerator::CMethodResult& oResult){}
//
};
////////////////////////////////////////////////////////////////////////
class CWebViewFactory: public CWebViewFactoryBase
{
public:
~CWebViewFactory(){}
IWebViewSingleton* createModuleSingleton()
{
return new CWebViewImpl();
}
};
}
extern "C" void Init_WebView()
{
rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() );
rho::Init_WebView_API();
RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi");
}
<commit_msg>FIXed KeyboardDisplayRequiresUserAction on CWebViewImpl<commit_after>#include "../../../shared/generated/cpp/WebViewBase.h"
#include "../../../shared/System.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "rubyext/WebView.h"
//extern "C" HWND getMainWnd();
namespace rho {
using namespace apiGenerator;
using namespace common;
class CWebViewImpl: public CWebViewSingletonBase
{
int m_nNavigationTimeout;
double m_dZoomPage;
int m_nTextZoom;
public:
CWebViewImpl(): CWebViewSingletonBase(), m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1) {}
virtual void getFramework(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(System::getWebviewFramework());
}
virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(rho_webview_get_full_screen() != 0 ? true : false );
}
virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_full_screen_mode(value ? 1 : 0);
}
virtual void getNativeMenu(rho::apiGenerator::CMethodResult& oResult)
{
rho::Vector< Hashtable<String, String> > arRes;
RHODESAPP().getAppMenu().getMenuItemsEx(arRes);
oResult.set(arRes);
}
virtual void setNativeMenu( const rho::Vector<rho::String>& value, rho::apiGenerator::CMethodResult& oResult)
{
RHODESAPP().getAppMenu().setAppMenuJSONItemsEx(value);
}
//Android only
virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){}
virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(false);
}
virtual void getEnableMediaPlaybackWithoutGesture(rho::apiGenerator::CMethodResult& oResult) {
oResult.set(false);
}
virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult){}
virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){}
//
virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(m_nNavigationTimeout);
}
virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult)
{
//m_nNavigationTimeout = value;
//rho_webview_setNavigationTimeout(m_nNavigationTimeout);
//TODO: implement rho_webview_setNavigationTimeout
}
virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("WebView.scrollTechnique") );
}
virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("WebView.fontFamily") );
}
virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getString("WebView.userAgent") );
}
virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getBool("WebView.viewportEnabled") );
}
virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getInt("WebView.viewportWidth") );
}
virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( RHOCONF().getInt("WebView.cacheSize") );
}
//TODO: EnableCache - does it supported by Webkit ?
virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){}
virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){}
//TODO: AcceptLanguage - does it supported by Webkit ?
virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){}
virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){}
virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(m_dZoomPage);
}
virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult)
{
//m_dZoomPage = value;
//RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage);
// TODO: implement webview zoom
}
virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( 1. );//m_nTextZoom
}
virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult)
{
//m_nTextZoom = value;
//RHODESAPP().getExtManager().zoomText( m_nTextZoom );
// TODO: implement webview zoom
}
virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_refresh(tabIndex);
}
virtual void navigate( const rho::String& url, int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_navigate(url.c_str(), tabIndex);
}
virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
//rho_webview_navigate_back();
//commented because every time it is navigating with default -1 instead of user defined tab index.
rho_webview_navigate_back_with_tab(tabIndex);
}
virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_current_location(tabIndex) );
}
virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_current_location(tabIndex) );
}
virtual void executeJavascript( const rho::String& javascriptText, int tabIndex, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_execute_js( javascriptText.c_str(), tabIndex );
}
virtual void active_tab(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_active_tab() );
}
virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set( rho_webview_active_tab() );
}
virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_full_screen_mode(enable ? 1 : 0);
}
virtual void setCookie( const rho::String& url, const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult)
{
rho_webview_set_cookie( strdup(url.c_str()), strdup(cookie.c_str()) );
}
//Android only
virtual void save( const rho::String& format, const rho::String& path, int tabIndex, rho::apiGenerator::CMethodResult& oResult){}
//
void getKeyboardDisplayRequiresUserAction(rho::apiGenerator::CMethodResult& oResult){}
void setKeyboardDisplayRequiresUserAction( bool keyboardDisplayRequiresUserAction, rho::apiGenerator::CMethodResult& oResult){}
};
////////////////////////////////////////////////////////////////////////
class CWebViewFactory: public CWebViewFactoryBase
{
public:
~CWebViewFactory(){}
IWebViewSingleton* createModuleSingleton()
{
return new CWebViewImpl();
}
};
}
extern "C" void Init_WebView()
{
rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() );
rho::Init_WebView_API();
RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi");
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 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.
*/
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <boost/filesystem/operations.hpp>
#include <Dataflow/Serialization/Network/NetworkXMLSerializer.h>
using namespace SCIRun::Dataflow::Networks;
void ToolkitFile::load(std::istream& istr)
{
auto xmlPtr = XMLSerializer::load_xml<ToolkitFile>(istr);
if (xmlPtr)
(*this) = *xmlPtr;
}
void ToolkitFile::save(std::ostream& ostr) const
{
XMLSerializer::save_xml(*this, ostr, "toolkit");
}
namespace
{
namespace fs = boost::filesystem;
fs::path addSlash(const fs::path& p)
{
auto fullBasePath(p);
if ("." != fullBasePath.filename())
fullBasePath += fs::path::preferred_separator;
return fullBasePath;
}
fs::path diffPath(const fs::path& basePath, const fs::path& newPath)
{
auto fullBasePath = addSlash(basePath);
auto tmpPath = newPath;
fs::path diffpath;
while (addSlash(tmpPath) != fullBasePath)
{
diffpath = tmpPath.stem() / diffpath;
tmpPath = tmpPath.parent_path();
}
auto filename = diffpath.leaf().string() + newPath.extension().string();
diffpath.remove_leaf() /= filename;
return diffpath;
}
}
ToolkitFile SCIRun::Dataflow::Networks::makeToolkitFromDirectory(const boost::filesystem::path& toolkitPath)
{
ToolkitFile toolkit;
for (const auto& p : boost::filesystem::recursive_directory_iterator(toolkitPath))
{
if (p.path().extension() == ".srn5")
{
auto path = diffPath(toolkitPath, p.path()).string();
std::replace(path.begin(), path.end(), '\\', '/');
toolkit.networks[path] = *XMLSerializer::load_xml<NetworkFile>(p.path().string());
}
}
return toolkit;
}
class NetworkSerializationWrapper : public NetworkSerializationInterface
{
public:
explicit NetworkSerializationWrapper(const NetworkXML* ) {}
std::map<std::string, std::pair<ModuleLookupInfo, ModuleStateHandle>> modules() const override
{
return {};
}
std::vector<ConnectionDescription> sortedConnections() const override
{
return {};
}
private:
};
NetworkSerializationInterfaceHandle NetworkXML::data() const
{
return makeShared<NetworkSerializationWrapper>(this);
}
<commit_msg>Green<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 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.
*/
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <boost/filesystem/operations.hpp>
#include <Dataflow/Serialization/Network/NetworkXMLSerializer.h>
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::State;
void ToolkitFile::load(std::istream& istr)
{
auto xmlPtr = XMLSerializer::load_xml<ToolkitFile>(istr);
if (xmlPtr)
(*this) = *xmlPtr;
}
void ToolkitFile::save(std::ostream& ostr) const
{
XMLSerializer::save_xml(*this, ostr, "toolkit");
}
namespace
{
namespace fs = boost::filesystem;
fs::path addSlash(const fs::path& p)
{
auto fullBasePath(p);
if ("." != fullBasePath.filename())
fullBasePath += fs::path::preferred_separator;
return fullBasePath;
}
fs::path diffPath(const fs::path& basePath, const fs::path& newPath)
{
auto fullBasePath = addSlash(basePath);
auto tmpPath = newPath;
fs::path diffpath;
while (addSlash(tmpPath) != fullBasePath)
{
diffpath = tmpPath.stem() / diffpath;
tmpPath = tmpPath.parent_path();
}
auto filename = diffpath.leaf().string() + newPath.extension().string();
diffpath.remove_leaf() /= filename;
return diffpath;
}
}
ToolkitFile SCIRun::Dataflow::Networks::makeToolkitFromDirectory(const boost::filesystem::path& toolkitPath)
{
ToolkitFile toolkit;
for (const auto& p : boost::filesystem::recursive_directory_iterator(toolkitPath))
{
if (p.path().extension() == ".srn5")
{
auto path = diffPath(toolkitPath, p.path()).string();
std::replace(path.begin(), path.end(), '\\', '/');
toolkit.networks[path] = *XMLSerializer::load_xml<NetworkFile>(p.path().string());
}
}
return toolkit;
}
class NetworkSerializationWrapper : public NetworkSerializationInterface
{
public:
explicit NetworkSerializationWrapper(const NetworkXML* xml)
{
if (!xml)
return;
for (const auto& mod : xml->modules)
{
moduleMap_[mod.first] = { mod.second.module, makeShared<SimpleMapModuleState>(mod.second.state) };
}
for (const auto& conn : xml->connections)
{
sortedConnections_.push_back(conn);
}
std::sort(sortedConnections_.begin(), sortedConnections_.end());
}
std::map<std::string, std::pair<ModuleLookupInfo, ModuleStateHandle>> modules() const override
{
return moduleMap_;
}
std::vector<ConnectionDescription> sortedConnections() const override
{
return sortedConnections_;
}
private:
std::map<std::string, std::pair<ModuleLookupInfo, ModuleStateHandle>> moduleMap_;
std::vector<ConnectionDescription> sortedConnections_;
};
NetworkSerializationInterfaceHandle NetworkXML::data() const
{
return makeShared<NetworkSerializationWrapper>(this);
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstddef>
#include <cstring>
#include <limits>
#include <system_error>
#include <vector>
#include <rdma/rdma_cma.h>
namespace crossbow {
namespace infinio {
class MmapRegion;
class ProtectionDomain;
/**
* @brief Buffer class pointing to a buffer space registered with an Infiniband device
*
* Each buffer has an unique ID associated with itself.
*/
class InfinibandBuffer {
public:
static constexpr uint16_t INVALID_ID = std::numeric_limits<uint16_t>::max();
InfinibandBuffer(uint16_t id)
: mId(id) {
memset(&mHandle, 0, sizeof(mHandle));
}
uint16_t id() const {
return mId;
}
/**
* @brief The number of buffers
*/
size_t count() const {
return 1;
}
/**
* @brief The total data length of all buffers
*/
uint32_t length() const {
return mHandle.length;
}
/**
* @brief Whether the buffer is valid
*/
bool valid() const {
return (mId != INVALID_ID);
}
/**
* @brief Shrinks the buffer space to the given length
*
* The new buffer length has to be smaller than the current length.
*
* @param length The new length of the buffer
*/
void shrink(uint32_t length) {
if (mHandle.length <= length) {
return;
}
mHandle.length = length;
}
void* data() {
return const_cast<void*>(const_cast<const InfinibandBuffer*>(this)->data());
}
const void* data() const {
return reinterpret_cast<void*>(mHandle.addr);
}
struct ibv_sge* handle() {
return &mHandle;
}
private:
friend class ScatterGatherBuffer;
uint32_t lkey() const {
return mHandle.lkey;
}
struct ibv_sge mHandle;
uint16_t mId;
};
/**
* @brief The LocalMemoryRegion class provides access to a memory region on the local host
*
* Can be used to let a remote host read and write to the memory region or read/write data from this region to a remote
* memory region.
*/
class LocalMemoryRegion {
public:
LocalMemoryRegion()
: mDataRegion(nullptr) {
}
/**
* @brief Registers the memory region
*
* @param domain The protection domain to register this region with
* @param data The start pointer of the memory region
* @param length The length of the memory region
* @param access Access flags for the Infiniband Adapter
*/
LocalMemoryRegion(const ProtectionDomain& domain, void* data, size_t length, int access);
LocalMemoryRegion(const ProtectionDomain& domain, MmapRegion& region, int access);
/**
* @brief Deregisters the memory region
*
* The data referenced by this memory region should not be used in any further RDMA operations.
*/
~LocalMemoryRegion();
LocalMemoryRegion(const LocalMemoryRegion&) = delete;
LocalMemoryRegion& operator=(const LocalMemoryRegion&) = delete;
LocalMemoryRegion(LocalMemoryRegion&& other)
: mDataRegion(other.mDataRegion) {
other.mDataRegion = nullptr;
}
LocalMemoryRegion& operator=(LocalMemoryRegion&& other);
uintptr_t address() const {
return reinterpret_cast<uintptr_t>(mDataRegion->addr);
}
size_t length() const {
return mDataRegion->length;
}
uint32_t rkey() const {
return mDataRegion->rkey;
}
/**
* @brief Acquire a buffer from the memory region for use in RDMA read and write requests
*
* The user has to take care that buffers do not overlap or read/writes are serialized.
*
* @param id User specified buffer ID
* @param offset Offset into the memory region the buffer should start
* @param length Length of the buffer
* @return A newly acquired buffer or a buffer with invalid ID in case of an error
*/
InfinibandBuffer acquireBuffer(uint16_t id, size_t offset, uint32_t length);
/**
* @brief Whether the buffer was acquired from this memory region
*/
bool belongsToRegion(InfinibandBuffer& buffer) {
return buffer.handle()->lkey == mDataRegion->lkey;
}
private:
friend class ScatterGatherBuffer;
uint32_t lkey() const {
return mDataRegion->lkey;
}
struct ibv_mr* mDataRegion;
};
/**
* @brief The RemoteMemoryRegion class provides access to a memory region on a remote host
*
* Can be used to read and write from/to the remote memory.
*/
class RemoteMemoryRegion {
public:
RemoteMemoryRegion()
: mAddress(0x0u),
mLength(0x0u),
mKey(0x0u) {
}
RemoteMemoryRegion(uintptr_t address, size_t length, uint32_t key)
: mAddress(address),
mLength(length),
mKey(key) {
}
uintptr_t address() const {
return mAddress;
}
size_t length() const {
return mLength;
}
uint32_t key() const {
return mKey;
}
private:
uintptr_t mAddress;
size_t mLength;
uint32_t mKey;
};
/**
* @brief Buffer class wrapping many buffers into a single one to be used in scatter / gather operations
*/
class ScatterGatherBuffer {
public:
ScatterGatherBuffer(uint16_t id)
: mId(id),
mLength(0) {
}
uint16_t id() const {
return mId;
}
/**
* @brief The number of buffers
*/
size_t count() const {
return mHandle.size();
}
/**
* @brief The total data length of all buffers
*/
size_t length() const {
return mLength;
}
void add(const LocalMemoryRegion& region, const void* addr, uint32_t length);
void add(const LocalMemoryRegion& region, size_t offset, uint32_t length) {
add(region, reinterpret_cast<const void*>(region.address() + offset), length);
}
void add(const InfinibandBuffer& buffer, size_t offset, uint32_t length);
void* data(size_t index) {
return const_cast<void*>(const_cast<const ScatterGatherBuffer*>(this)->data(index));
}
const void* data(size_t index) const {
return reinterpret_cast<const void*>(mHandle.at(index).addr);
}
struct ibv_sge* handle() {
return mHandle.data();
}
/**
* @brief Clears all buffers
*/
void reset() {
mHandle.clear();
mLength = 0;
}
private:
std::vector<struct ibv_sge> mHandle;
uint64_t mLength;
uint16_t mId;
};
} // namespace infinio
} // namespace crossbow
<commit_msg>Fix member variable initialization order<commit_after>#pragma once
#include <cstddef>
#include <cstring>
#include <limits>
#include <system_error>
#include <vector>
#include <rdma/rdma_cma.h>
namespace crossbow {
namespace infinio {
class MmapRegion;
class ProtectionDomain;
/**
* @brief Buffer class pointing to a buffer space registered with an Infiniband device
*
* Each buffer has an unique ID associated with itself.
*/
class InfinibandBuffer {
public:
static constexpr uint16_t INVALID_ID = std::numeric_limits<uint16_t>::max();
InfinibandBuffer(uint16_t id)
: mId(id) {
memset(&mHandle, 0, sizeof(mHandle));
}
uint16_t id() const {
return mId;
}
/**
* @brief The number of buffers
*/
size_t count() const {
return 1;
}
/**
* @brief The total data length of all buffers
*/
uint32_t length() const {
return mHandle.length;
}
/**
* @brief Whether the buffer is valid
*/
bool valid() const {
return (mId != INVALID_ID);
}
/**
* @brief Shrinks the buffer space to the given length
*
* The new buffer length has to be smaller than the current length.
*
* @param length The new length of the buffer
*/
void shrink(uint32_t length) {
if (mHandle.length <= length) {
return;
}
mHandle.length = length;
}
void* data() {
return const_cast<void*>(const_cast<const InfinibandBuffer*>(this)->data());
}
const void* data() const {
return reinterpret_cast<void*>(mHandle.addr);
}
struct ibv_sge* handle() {
return &mHandle;
}
private:
friend class ScatterGatherBuffer;
uint32_t lkey() const {
return mHandle.lkey;
}
struct ibv_sge mHandle;
uint16_t mId;
};
/**
* @brief The LocalMemoryRegion class provides access to a memory region on the local host
*
* Can be used to let a remote host read and write to the memory region or read/write data from this region to a remote
* memory region.
*/
class LocalMemoryRegion {
public:
LocalMemoryRegion()
: mDataRegion(nullptr) {
}
/**
* @brief Registers the memory region
*
* @param domain The protection domain to register this region with
* @param data The start pointer of the memory region
* @param length The length of the memory region
* @param access Access flags for the Infiniband Adapter
*/
LocalMemoryRegion(const ProtectionDomain& domain, void* data, size_t length, int access);
LocalMemoryRegion(const ProtectionDomain& domain, MmapRegion& region, int access);
/**
* @brief Deregisters the memory region
*
* The data referenced by this memory region should not be used in any further RDMA operations.
*/
~LocalMemoryRegion();
LocalMemoryRegion(const LocalMemoryRegion&) = delete;
LocalMemoryRegion& operator=(const LocalMemoryRegion&) = delete;
LocalMemoryRegion(LocalMemoryRegion&& other)
: mDataRegion(other.mDataRegion) {
other.mDataRegion = nullptr;
}
LocalMemoryRegion& operator=(LocalMemoryRegion&& other);
uintptr_t address() const {
return reinterpret_cast<uintptr_t>(mDataRegion->addr);
}
size_t length() const {
return mDataRegion->length;
}
uint32_t rkey() const {
return mDataRegion->rkey;
}
/**
* @brief Acquire a buffer from the memory region for use in RDMA read and write requests
*
* The user has to take care that buffers do not overlap or read/writes are serialized.
*
* @param id User specified buffer ID
* @param offset Offset into the memory region the buffer should start
* @param length Length of the buffer
* @return A newly acquired buffer or a buffer with invalid ID in case of an error
*/
InfinibandBuffer acquireBuffer(uint16_t id, size_t offset, uint32_t length);
/**
* @brief Whether the buffer was acquired from this memory region
*/
bool belongsToRegion(InfinibandBuffer& buffer) {
return buffer.handle()->lkey == mDataRegion->lkey;
}
private:
friend class ScatterGatherBuffer;
uint32_t lkey() const {
return mDataRegion->lkey;
}
struct ibv_mr* mDataRegion;
};
/**
* @brief The RemoteMemoryRegion class provides access to a memory region on a remote host
*
* Can be used to read and write from/to the remote memory.
*/
class RemoteMemoryRegion {
public:
RemoteMemoryRegion()
: mAddress(0x0u),
mLength(0x0u),
mKey(0x0u) {
}
RemoteMemoryRegion(uintptr_t address, size_t length, uint32_t key)
: mAddress(address),
mLength(length),
mKey(key) {
}
uintptr_t address() const {
return mAddress;
}
size_t length() const {
return mLength;
}
uint32_t key() const {
return mKey;
}
private:
uintptr_t mAddress;
size_t mLength;
uint32_t mKey;
};
/**
* @brief Buffer class wrapping many buffers into a single one to be used in scatter / gather operations
*/
class ScatterGatherBuffer {
public:
ScatterGatherBuffer(uint16_t id)
: mLength(0),
mId(id) {
}
uint16_t id() const {
return mId;
}
/**
* @brief The number of buffers
*/
size_t count() const {
return mHandle.size();
}
/**
* @brief The total data length of all buffers
*/
size_t length() const {
return mLength;
}
void add(const LocalMemoryRegion& region, const void* addr, uint32_t length);
void add(const LocalMemoryRegion& region, size_t offset, uint32_t length) {
add(region, reinterpret_cast<const void*>(region.address() + offset), length);
}
void add(const InfinibandBuffer& buffer, size_t offset, uint32_t length);
void* data(size_t index) {
return const_cast<void*>(const_cast<const ScatterGatherBuffer*>(this)->data(index));
}
const void* data(size_t index) const {
return reinterpret_cast<const void*>(mHandle.at(index).addr);
}
struct ibv_sge* handle() {
return mHandle.data();
}
/**
* @brief Clears all buffers
*/
void reset() {
mHandle.clear();
mLength = 0;
}
private:
std::vector<struct ibv_sge> mHandle;
uint64_t mLength;
uint16_t mId;
};
} // namespace infinio
} // namespace crossbow
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "deployconfiguration.h"
#include "buildmanager.h"
#include "buildsteplist.h"
#include "buildstepspage.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "target.h"
using namespace ProjectExplorer;
namespace {
const char * const BUILD_STEP_LIST_COUNT("ProjectExplorer.BuildConfiguration.BuildStepListCount");
const char * const BUILD_STEP_LIST_PREFIX("ProjectExplorer.BuildConfiguration.BuildStepList.");
} // namespace
DeployConfiguration::DeployConfiguration(Target *target, const QString &id) :
ProjectConfiguration(target, id),
m_stepList(0)
{
Q_ASSERT(target);
m_stepList = new BuildStepList(this, QLatin1String(Constants::BUILDSTEPS_DEPLOY));
//: Display name of the deploy build step list. Used as part of the labels in the project window.
m_stepList->setDisplayName(tr("Deploy"));
setDisplayName(tr("No deployment"));
}
DeployConfiguration::DeployConfiguration(Target *target, DeployConfiguration *source) :
ProjectConfiguration(target, source)
{
Q_ASSERT(target);
// Do not clone stepLists here, do that in the derived constructor instead
// otherwise BuildStepFactories might reject to set up a BuildStep for us
// since we are not yet the derived class!
}
DeployConfiguration::~DeployConfiguration()
{
delete m_stepList;
}
BuildStepList *DeployConfiguration::stepList() const
{
return m_stepList;
}
QVariantMap DeployConfiguration::toMap() const
{
QVariantMap map(ProjectConfiguration::toMap());
map.insert(QLatin1String(BUILD_STEP_LIST_COUNT), 1);
map.insert(QLatin1String(BUILD_STEP_LIST_PREFIX) % QLatin1String("0"), m_stepList->toMap());
return map;
}
DeployConfigurationWidget *DeployConfiguration::configurationWidget() const
{
return 0;
}
bool DeployConfiguration::fromMap(const QVariantMap &map)
{
if (!ProjectConfiguration::fromMap(map))
return false;
int maxI = map.value(QLatin1String(BUILD_STEP_LIST_COUNT), 0).toInt();
Q_ASSERT(maxI == 1);
QVariantMap data = map.value(QLatin1String(BUILD_STEP_LIST_PREFIX) % QLatin1String("0")).toMap();
if (!data.isEmpty()) {
m_stepList = new BuildStepList(this, data);
if (m_stepList->isNull()) {
qWarning() << "Failed to restore deploy step list";
delete m_stepList;
m_stepList = 0;
return false;
}
} else {
qWarning() << "No data for deploy step list found!";
}
// TODO: We assume that we have hold the deploy list
Q_ASSERT(m_stepList && m_stepList->id() == QLatin1String(ProjectExplorer::Constants::BUILDSTEPS_DEPLOY));
return true;
}
Target *DeployConfiguration::target() const
{
return static_cast<Target *>(parent());
}
void DeployConfiguration::cloneSteps(DeployConfiguration *source)
{
if (source == this)
return;
delete m_stepList;
m_stepList = new BuildStepList(this, source->stepList());
}
///
// DeployConfigurationFactory
///
DeployConfigurationFactory::DeployConfigurationFactory(QObject *parent) :
QObject(parent)
{ }
DeployConfigurationFactory::~DeployConfigurationFactory()
{ }
QStringList DeployConfigurationFactory::availableCreationIds(Target *parent) const
{
Q_UNUSED(parent);
return QStringList() << QLatin1String(Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
}
QString DeployConfigurationFactory::displayNameForId(const QString &id) const
{
if (id == QLatin1String(Constants::DEFAULT_DEPLOYCONFIGURATION_ID))
//: Display name of the default deploy configuration
return tr("Deploy Configuration");
return QString();
}
bool DeployConfigurationFactory::canCreate(Target *parent, const QString &id) const
{
Q_UNUSED(parent);
return id == QLatin1String(Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
}
DeployConfiguration *DeployConfigurationFactory::create(Target *parent, const QString &id)
{
if (!canCreate(parent, id))
return 0;
return new DeployConfiguration(parent, id);
}
bool DeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
{
return canCreate(parent, idFromMap(map));
}
DeployConfiguration *DeployConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
DeployConfiguration *dc = new DeployConfiguration(parent, idFromMap(map));
if (!dc->fromMap(map)) {
delete dc;
return 0;
}
return dc;
}
bool DeployConfigurationFactory::canClone(Target *parent, DeployConfiguration *product) const
{
return canCreate(parent, product->id());
}
DeployConfiguration *DeployConfigurationFactory::clone(Target *parent, DeployConfiguration *product)
{
if (!canClone(parent, product))
return 0;
return new DeployConfiguration(parent, product);
}
///
// DeployConfigurationWidget
///
DeployConfigurationWidget::DeployConfigurationWidget(QWidget *parent) : NamedWidget(parent)
{ }
<commit_msg>Compile fix on mac<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "deployconfiguration.h"
#include "buildmanager.h"
#include "buildsteplist.h"
#include "buildstepspage.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "target.h"
using namespace ProjectExplorer;
namespace {
const char * const BUILD_STEP_LIST_COUNT("ProjectExplorer.BuildConfiguration.BuildStepListCount");
const char * const BUILD_STEP_LIST_PREFIX("ProjectExplorer.BuildConfiguration.BuildStepList.");
} // namespace
DeployConfiguration::DeployConfiguration(Target *target, const QString &id) :
ProjectConfiguration(target, id),
m_stepList(0)
{
Q_ASSERT(target);
m_stepList = new BuildStepList(this, QLatin1String(Constants::BUILDSTEPS_DEPLOY));
//: Display name of the deploy build step list. Used as part of the labels in the project window.
m_stepList->setDisplayName(tr("Deploy"));
setDisplayName(tr("No deployment"));
}
DeployConfiguration::DeployConfiguration(Target *target, DeployConfiguration *source) :
ProjectConfiguration(target, source)
{
Q_ASSERT(target);
// Do not clone stepLists here, do that in the derived constructor instead
// otherwise BuildStepFactories might reject to set up a BuildStep for us
// since we are not yet the derived class!
}
DeployConfiguration::~DeployConfiguration()
{
delete m_stepList;
}
BuildStepList *DeployConfiguration::stepList() const
{
return m_stepList;
}
QVariantMap DeployConfiguration::toMap() const
{
QVariantMap map(ProjectConfiguration::toMap());
map.insert(QLatin1String(BUILD_STEP_LIST_COUNT), 1);
map.insert(QLatin1String(BUILD_STEP_LIST_PREFIX) + QLatin1String("0"), m_stepList->toMap());
return map;
}
DeployConfigurationWidget *DeployConfiguration::configurationWidget() const
{
return 0;
}
bool DeployConfiguration::fromMap(const QVariantMap &map)
{
if (!ProjectConfiguration::fromMap(map))
return false;
int maxI = map.value(QLatin1String(BUILD_STEP_LIST_COUNT), 0).toInt();
Q_ASSERT(maxI == 1);
QVariantMap data = map.value(QLatin1String(BUILD_STEP_LIST_PREFIX) + QLatin1String("0")).toMap();
if (!data.isEmpty()) {
m_stepList = new BuildStepList(this, data);
if (m_stepList->isNull()) {
qWarning() << "Failed to restore deploy step list";
delete m_stepList;
m_stepList = 0;
return false;
}
} else {
qWarning() << "No data for deploy step list found!";
}
// TODO: We assume that we have hold the deploy list
Q_ASSERT(m_stepList && m_stepList->id() == QLatin1String(ProjectExplorer::Constants::BUILDSTEPS_DEPLOY));
return true;
}
Target *DeployConfiguration::target() const
{
return static_cast<Target *>(parent());
}
void DeployConfiguration::cloneSteps(DeployConfiguration *source)
{
if (source == this)
return;
delete m_stepList;
m_stepList = new BuildStepList(this, source->stepList());
}
///
// DeployConfigurationFactory
///
DeployConfigurationFactory::DeployConfigurationFactory(QObject *parent) :
QObject(parent)
{ }
DeployConfigurationFactory::~DeployConfigurationFactory()
{ }
QStringList DeployConfigurationFactory::availableCreationIds(Target *parent) const
{
Q_UNUSED(parent);
return QStringList() << QLatin1String(Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
}
QString DeployConfigurationFactory::displayNameForId(const QString &id) const
{
if (id == QLatin1String(Constants::DEFAULT_DEPLOYCONFIGURATION_ID))
//: Display name of the default deploy configuration
return tr("Deploy Configuration");
return QString();
}
bool DeployConfigurationFactory::canCreate(Target *parent, const QString &id) const
{
Q_UNUSED(parent);
return id == QLatin1String(Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
}
DeployConfiguration *DeployConfigurationFactory::create(Target *parent, const QString &id)
{
if (!canCreate(parent, id))
return 0;
return new DeployConfiguration(parent, id);
}
bool DeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
{
return canCreate(parent, idFromMap(map));
}
DeployConfiguration *DeployConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
DeployConfiguration *dc = new DeployConfiguration(parent, idFromMap(map));
if (!dc->fromMap(map)) {
delete dc;
return 0;
}
return dc;
}
bool DeployConfigurationFactory::canClone(Target *parent, DeployConfiguration *product) const
{
return canCreate(parent, product->id());
}
DeployConfiguration *DeployConfigurationFactory::clone(Target *parent, DeployConfiguration *product)
{
if (!canClone(parent, product))
return 0;
return new DeployConfiguration(parent, product);
}
///
// DeployConfigurationWidget
///
DeployConfigurationWidget::DeployConfigurationWidget(QWidget *parent) : NamedWidget(parent)
{ }
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo 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 <algorithm>
#include <cmath>
#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "modules/planning/proto/dp_st_speed_config.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/path_decision.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_graph.h"
namespace apollo {
namespace planning {
using common::adapter::AdapterManager;
class DpStSpeedTest : public PlanningTestBase {
public:
void SetPathDataWithStraightLine() {
double l = 0.0;
const double ds = 1.0;
std::vector<common::FrenetFramePoint> points;
for (double s = 0.0; s < 100.0; s += ds) {
common::FrenetFramePoint ffp;
ffp.set_s(s);
ffp.set_l(l);
points.push_back(ffp);
}
FrenetFramePath path(points);
path_data_.SetReferenceLine(reference_line_);
path_data_.SetFrenetPath(path);
}
virtual void SetUp() {
google::InitGoogleLogging("DpStSpeedTest");
PlanningTestBase::SetUp();
const auto* frame = planning_.GetFrame();
reference_line_ = &(frame->reference_line());
SetPathDataWithStraightLine();
}
protected:
const ReferenceLine* reference_line_ = nullptr;
common::TrajectoryPoint init_point_;
SpeedData speed_data_; // output
PathData path_data_; // input
};
TEST_F(DpStSpeedTest, dp_st_graph_test) {
DpStSpeedConfig dp_st_speed_config;
DpStGraph dp_st_graph(dp_st_speed_config, path_data_);
}
} // namespace planning
} // namespace apollo
<commit_msg>Planning: fixed dp_st_graph_test<commit_after>/******************************************************************************
* Copyright 2017 The Apollo 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 <algorithm>
#include <cmath>
#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "modules/planning/proto/dp_st_speed_config.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/path_decision.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/optimizer/dp_st_speed/dp_st_graph.h"
namespace apollo {
namespace planning {
using common::adapter::AdapterManager;
class DpStSpeedTest : public PlanningTestBase {
public:
void SetPathDataWithStraightLine() {
double l = 0.0;
const double ds = 1.0;
std::vector<common::FrenetFramePoint> points;
for (double s = 0.0; s < 50.0; s += ds) {
common::FrenetFramePoint ffp;
ffp.set_s(s);
ffp.set_l(l);
points.push_back(ffp);
}
FrenetFramePath path(points);
path_data_.SetReferenceLine(reference_line_);
path_data_.SetFrenetPath(path);
}
virtual void SetUp() {
google::InitGoogleLogging("DpStSpeedTest");
PlanningTestBase::SetUp();
RunPlanning();
const auto* frame = planning_.GetFrame();
reference_line_ = &(frame->reference_line());
SetPathDataWithStraightLine();
}
protected:
const ReferenceLine* reference_line_ = nullptr;
common::TrajectoryPoint init_point_;
SpeedData speed_data_; // output
PathData path_data_; // input
};
TEST_F(DpStSpeedTest, dp_st_graph_test) {
DpStSpeedConfig dp_st_speed_config;
DpStGraph dp_st_graph(dp_st_speed_config, path_data_);
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Jolla Ltd.
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "private/qcontinuinganimationgroupjob_p.h"
#include "private/qanimationjobutil_p.h"
QT_BEGIN_NAMESPACE
QContinuingAnimationGroupJob::QContinuingAnimationGroupJob()
: QAnimationGroupJob()
{
}
QContinuingAnimationGroupJob::~QContinuingAnimationGroupJob()
{
}
void QContinuingAnimationGroupJob::updateCurrentTime(int /*currentTime*/)
{
if (!firstChild())
return;
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) {
if (animation->state() == state()) {
RETURN_IF_DELETED(animation->setCurrentTime(m_currentTime));
}
}
}
void QContinuingAnimationGroupJob::updateState(QAbstractAnimationJob::State newState,
QAbstractAnimationJob::State oldState)
{
QAnimationGroupJob::updateState(newState, oldState);
switch (newState) {
case Stopped:
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling())
animation->stop();
break;
case Paused:
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling())
if (animation->isRunning())
animation->pause();
break;
case Running:
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) {
resetUncontrolledAnimationFinishTime(animation);
animation->setDirection(m_direction);
animation->start();
}
break;
}
}
void QContinuingAnimationGroupJob::updateDirection(QAbstractAnimationJob::Direction direction)
{
if (!isStopped()) {
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) {
animation->setDirection(direction);
}
}
}
void QContinuingAnimationGroupJob::uncontrolledAnimationFinished(QAbstractAnimationJob *animation)
{
Q_ASSERT(animation && (animation->duration() == -1));
int uncontrolledRunningCount = 0;
for (QAbstractAnimationJob *child = firstChild(); child; child = child->nextSibling()) {
if (child == animation)
setUncontrolledAnimationFinishTime(animation, animation->currentTime());
else if (uncontrolledAnimationFinishTime(child) == -1)
++uncontrolledRunningCount;
}
if (uncontrolledRunningCount > 0)
return;
setUncontrolledAnimationFinishTime(this, currentTime());
stop();
}
QT_END_NAMESPACE
<commit_msg>Don't start continuing animation when it doesn't have children.<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Jolla Ltd.
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "private/qcontinuinganimationgroupjob_p.h"
#include "private/qanimationjobutil_p.h"
QT_BEGIN_NAMESPACE
QContinuingAnimationGroupJob::QContinuingAnimationGroupJob()
: QAnimationGroupJob()
{
}
QContinuingAnimationGroupJob::~QContinuingAnimationGroupJob()
{
}
void QContinuingAnimationGroupJob::updateCurrentTime(int /*currentTime*/)
{
Q_ASSERT(firstChild());
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) {
if (animation->state() == state()) {
RETURN_IF_DELETED(animation->setCurrentTime(m_currentTime));
}
}
}
void QContinuingAnimationGroupJob::updateState(QAbstractAnimationJob::State newState,
QAbstractAnimationJob::State oldState)
{
QAnimationGroupJob::updateState(newState, oldState);
switch (newState) {
case Stopped:
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling())
animation->stop();
break;
case Paused:
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling())
if (animation->isRunning())
animation->pause();
break;
case Running:
if (!firstChild()) {
stop();
return;
}
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) {
resetUncontrolledAnimationFinishTime(animation);
animation->setDirection(m_direction);
animation->start();
}
break;
}
}
void QContinuingAnimationGroupJob::updateDirection(QAbstractAnimationJob::Direction direction)
{
if (!isStopped()) {
for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) {
animation->setDirection(direction);
}
}
}
void QContinuingAnimationGroupJob::uncontrolledAnimationFinished(QAbstractAnimationJob *animation)
{
Q_ASSERT(animation && (animation->duration() == -1));
int uncontrolledRunningCount = 0;
for (QAbstractAnimationJob *child = firstChild(); child; child = child->nextSibling()) {
if (child == animation)
setUncontrolledAnimationFinishTime(animation, animation->currentTime());
else if (uncontrolledAnimationFinishTime(child) == -1)
++uncontrolledRunningCount;
}
if (uncontrolledRunningCount > 0)
return;
setUncontrolledAnimationFinishTime(this, currentTime());
stop();
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#ifndef LOGGER_HH
#define LOGGER_HH
#include <iostream>
#include <fstream>
#include <sstream>
///just a LOGINDENT value to be defined at build time. this way you have indent levels depending on built libraries
#ifndef LOGINDENTLVL
#define LOGINDENTLVL 0
#endif
///the default tab width for the indent...
#ifndef LOGINDENTWIDTH
#define LOGINDENTWIDTH 2
#endif
///just a LOGPREFIX value to be defined at build time. this way you can have a prefix for the whole project binary (library or executable)
#ifndef LOGPREFIX
#define LOGPREFIX "Default Log"
#endif
/**
* \class Logger
*
* \brief This class defines loglevel on top of clog
*
* This Logger use indentation levels, usually defined on build time.
* TODO : Add LogLevels to filter the console output as well as the file output (3 loglevel : quiet / normal / verbose)
*
* \author Alex
*
* \date 2005/10/05
*
* Contact: [email protected]
*
*/
typedef enum {quiet,normal,verbose} Loglevel;
class Logger //: public std::ostream
{
int _indentlvl,_indentwidth;
std::string _logprefix;
std::ofstream _ofstr;
bool _consoleLog;
bool _fileLog;
bool setLogfile( const std::string & filename);
public :
///Default Constructor that defines how to write the log
Logger(const std::string & LogPrefix = LOGPREFIX, int indentlevel = LOGINDENTLVL, int indentwidth = LOGINDENTWIDTH );
///Default Destructor that flush the Log Buffer
~Logger();
void toggleConsoleLog() { _consoleLog = !_consoleLog ; }
void enableConsoleLog() { _consoleLog= true ; }
void disableConsoleLog() { _consoleLog = false ; }
bool enableFileLog( const std::string & filename) { _fileLog= true ; return setLogfile(filename);}
void disableFileLog() { _fileLog = false ; _ofstr.close();}
//void add(const std::string & message); // not const because of initial '\n' in string from streams...
template<typename M> Logger& operator << (const M & msg);
//to enable manipulators on Logger
Logger& operator << (std::ostream& (*manip)(std::ostream&));
Logger& operator << (std::ios_base& (*manip)(std::ios_base&));
Logger& operator << (Logger& (*manip)(Logger&));//to enable specific manipulators on Logger
friend Logger& nl (Logger& log); // adds a prefix
friend Logger& endl (Logger& log); // adds a prefix
Logger & flush(void);
//TODO : handle operator<< and
//http://www.mactech.com/articles/mactech/Vol.16/16.04/StreamforAllSeasons/
//http://www.horstmann.com/cpp/iostreams.html
//http://spec.winprog.org/streams/
};
template<typename M> Logger& Logger::operator<< ( const M & msg)
{
if (_consoleLog) std::clog << msg;
if (_fileLog) _ofstr << msg;
return *this;
}
#endif
<commit_msg>moved logger from Common to SDLwrap, since it might depend on some SDL library feature to be thread safe or to write to a file...<commit_after><|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee Modules --- XRule Exception
*
* @author Sam Baskinger <[email protected]>
*/
#include "xrules_exception.hpp"
#include "xrules.hpp"
#include "xrules_acls.hpp"
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <strings.h>
namespace {
/**
* Utility function to parse an argument for XRuleException configurations.
*
* This takes an XRuleException argument, checks the provided prefix,
* and if it matches returns IB_OK and assigns the `char *` following the
* prefix in @a arg to @a rest. Thus, the caller is provided with
* the value following the prefix and may continue parsing it.
*
* @param[in] expected The expected value. A case insensitive comparison
* is done between @a expected and @a arg.
* @param[in] arg The argument to check.
* @param[in] rest The rest of @a arg following the prefix @a expected.
*
* @returns
* - IB_OK On success and a match.
* - IB_ENOENT If @a expected does not match @a arg.
*/
ib_status_t parse_arg(
const char *expected,
const char *arg,
const char **rest
)
{
size_t len = strlen(expected);
if (strncasecmp(expected, arg, len) == 0) {
(*rest) = arg+len;
return IB_OK;
}
else {
return IB_ENOENT;
}
}
/**
* Use ib_uuid_create_v4() to generate a name.
*
* This is used to name Actions when the name is not important.
*/
std::string random_name()
{
std::vector<char> uuid(IB_UUID_LENGTH);
IronBee::throw_if_error(ib_uuid_create_v4(&(uuid[0])));
return std::string(&(uuid[0]));
}
/**
* A ConclusionAction is an action that conditionally fires when it is applied.
*
* To implement an XRuleException we actually wire together many
* FactActions which, after each is called, attempts to apply the
* ConclusionAction.
*
* The ConclusionAction will only fire if all its facts are true (results=1).
*/
class ConclusionAction : public Action
{
public:
/**
* Construct a conclusion action that depends on @a results.
*
* @param[in] action The user's action to execute when all FactAction s
* are true.
* @param[in] results The number of results this ConclusionAction should
* create to be given to FactActions.
*/
ConclusionAction(action_ptr action, int results);
/**
* Return a reference to the boolean that denotes a particular result.
*
* @param[in] mdata Module data.
* @param[in] i The index of the result to fetch. This must be in
* the range 0 through the number of results specified when this
* object was created.
*
* @returns The int reference to assign to.
*/
int& result(
XRulesModuleTxData& mdata,
int i
);
private:
//! The action that is applied if all results are true.
action_ptr m_action;
/**
* A vector of results (0=failed/not executed, 1=success).
*
* Only when all of these are equal to 1 will ConclusionAction::m_action
* be executed.
*/
size_t m_results;
/**
* Apply this action to the transaction if all results are non-zero.
*
* @param[in] config Module configuration.
* @param[in] mdata The module.
* @param[in] tx The current transaction.
*/
virtual void apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const;
};
ConclusionAction::ConclusionAction(action_ptr action, int results):
Action(random_name(), 10),
m_action(action),
m_results(results)
{}
int& ConclusionAction::result(
XRulesModuleTxData& mdata,
int i
)
{
std::vector<int>& v = mdata.exception_facts[this];
if (v.size() <= m_results) {
v.resize(m_results);
}
return v[i];
}
void ConclusionAction::apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const
{
std::vector<int>& v = (*mdata).exception_facts[this];
BOOST_FOREACH(int r, v) {
if (r != 1) {
return;
}
}
/* If we reach this code, all results were = 1. Execute. */
(*m_action)(config, mdata, tx);
}
/**
* This action initializes facts to false (0) and sets them to true (1).
*
* To implement an XRuleException we must collect various facts, such as
* is a Path equal to some prefix, is a source IP in a subnet, etc.
* To collect these facts XRules are created and given FactActions
* which record that a given XRule was true and fired its action.
*
* When any FactAction fires, as its last action, it calls its
* associated ConclusionAction. A ConclusionAction will check if all
* FactActions have set their facts to true (1). Only if all facts are
* true does the ConclusionAction then fire its own associated Action.
* The ConclusionAction's Action is the action the user requested
* in the configuration language.
*/
class FactAction : public Action
{
public:
/**
* Construct a new action.
*
* @param[in] conclusion The conclusion action that this Fact is
* gating the execution of.
* @param[in] result_idx The index of the result in the result
* vector of the ConclusionAction.
*
* @note This takes a reference to a boolean because actions may
* not modify themselves.
*/
FactAction(action_ptr conclusion, int result_idx);
private:
action_ptr m_conclusion;
int m_result_idx;
/**
* Apply this action to the transaction.
*
* @param[in] config Module configuration.
* @param[in] mdata The module.
* @param[in] tx The current transaction.
*/
virtual void apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const;
};
FactAction::FactAction(action_ptr conclusion, int result_idx) :
Action(random_name(), 10),
m_conclusion(conclusion),
m_result_idx(result_idx)
{}
void FactAction::apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const
{
/* Update the results. */
static_cast<ConclusionAction&>(*m_conclusion).
result(*mdata, m_result_idx) = 1;
/* Having updated the results, try the conclusion. */
(*m_conclusion)(config, mdata, tx);
}
} /* Anonymous Namespace */
void XRuleException::xrule_directive(
XRulesModule module,
IronBee::ConfigurationParser cp,
const char * name,
IronBee::ConstList<const char *> all_params
)
{
IronBee::Context ctx = cp.current_context();
XRulesModuleConfig& cfg =
module.module().configuration_data<XRulesModuleConfig>(ctx);
/* The unparsed bits from parsing an action out of the params arg. */
IronBee::List<const char *> params =
IronBee::List<const char *>::create(cp.memory_manager());
/* Parse the action and put the remaining tokens in `params`. */
action_ptr user_action = module.parse_action(cp, all_params, params);
/* Construct a conclusion action that will fire the user's action. */
action_ptr conclusion(
boost::make_shared<ConclusionAction>(
user_action,
params.size()));
/* The conclusion action will log. The user action does not. */
user_action->logevent_msg() =
std::string("Exception matched: ") +
user_action->logevent_msg();
user_action->logevent_tag() = user_action->logevent_tag();
conclusion->logevent_msg() = "";
conclusion->logevent_tag() = "";
if (params.empty()) {
BOOST_THROW_EXCEPTION(
IronBee::einval()
<< IronBee::errinfo_what(
"XRuleException require at least 1 argument.")
);
}
int result_idx = 0;
BOOST_FOREACH(const char* param, params) {
const char* val;
/* Build a new FactAction to
* - Set the result `result_idx` to 1.
* - Fire the conclusion action. */
action_ptr action(
boost::make_shared<FactAction>(
conclusion,
result_idx));
++result_idx;
if (IB_OK == parse_arg("EventTag:", param, &val)) {
IronBee::List<const char *> l =
IronBee::List<const char *>::create(cp.memory_manager());
l.push_back(val);
action->logevent_msg() =
std::string("EventTag ") +
val +
" matched";
action->logevent_tag() = "xrules/tags";
cfg.event_xrules.push_back(
xrule_ptr(
new XRuleEventTag(l, action)));
}
else if (IB_OK == parse_arg("IPv4:", param, &val)) {
// Copy in an empty, uninitialized ipset entry.
ib_ipset4_entry_t entry;
memset(&entry, 0, sizeof(entry));
val = XRuleIP::normalize_ipv4(cp.memory_manager(), val);
IronBee::throw_if_error(
ib_ip4_str_to_net(val, &(entry.network)),
(std::string("Failed to get net from string: ")+val).c_str()
);
action->logevent_msg() =
std::string("IPv4 ") +
val +
" matched";
action->logevent_tag() = "xrules/ipv4";
// Put that action in the ip set.
entry.data = IronBee::value_to_data<action_ptr>(
action,
cp.engine().main_memory_mm().ib());
cfg.ipv4_list.push_back(entry);
}
else if (IB_OK == parse_arg("IPv6:", param, &val)) {
// Copy in an empty, uninitialized ipset entry.
ib_ipset6_entry_t entry;
memset(&entry, 0, sizeof(entry));
val = XRuleIP::normalize_ipv6(cp.memory_manager(), val);
IronBee::throw_if_error(
ib_ip6_str_to_net(val, &(entry.network)),
(std::string("Failed to get net from string: ")+val).c_str()
);
action->logevent_msg() =
std::string("IPv6 ") +
val +
" matched";
action->logevent_tag() = "xrules/ipv6";
// Put that action in the ip set.
entry.data = IronBee::value_to_data<action_ptr>(
action,
cp.engine().main_memory_mm().ib());
cfg.ipv6_list.push_back(entry);
}
else if (IB_OK == parse_arg("Geo:", param, &val)) {
action->logevent_msg() =
std::string("Geo ") +
val +
" matched";
action->logevent_tag() = "xrules/geo";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleGeo(val, action)));
}
else if (IB_OK == parse_arg("Path:", param, &val)) {
action->logevent_msg() =
std::string("Path ") +
val +
" matched";
action->logevent_tag() = "xrules/path";
cfg.req_xrules.push_back(
xrule_ptr(
new XRulePath(val, action)));
}
else if (IB_OK == parse_arg("Param:", param, &val)) {
action->logevent_msg() = std::string("Param ") + val + " matched";
action->logevent_tag() = "xrule/param";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleParam(val, cp.engine(), action)));
}
else if (IB_OK == parse_arg("Cookie:", param, &val)) {
action->logevent_msg() = std::string("Cookie ") + val + " matched";
action->logevent_tag() = "xrule/cookie";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleCookie(val, cp.engine(), action)));
}
else if (IB_OK == parse_arg("RequestHeader:", param, &val)) {
action->logevent_msg() =
std::string("RequestHeader ") + val + " matched";
action->logevent_tag() = "xrule/requestheader";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleRequestHeader(val, action)));
}
else if (IB_OK == parse_arg("Method:", param, &val)) {
action->logevent_msg() = std::string("Method ") + val + " matched";
action->logevent_tag() = "xrule/method";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleMethod(val, action)));
}
else if (IB_OK == parse_arg("Hostname:", param, &val)) {
action->logevent_msg() = std::string("Hostname ") + val + " matched";
action->logevent_tag() = "xrule/hostname";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleHostname(val, action)));
}
else {
BOOST_THROW_EXCEPTION(
IronBee::enoent()
<< IronBee::errinfo_what(
std::string("Unknown XRuleException: ")+param)
);
}
}
}
<commit_msg>xrule_exceptions.cpp: XRuleException now supports types RequestContentType:... and Time:... RNS-1394.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee Modules --- XRule Exception
*
* @author Sam Baskinger <[email protected]>
*/
#include "xrules_exception.hpp"
#include "xrules.hpp"
#include "xrules_acls.hpp"
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <strings.h>
namespace {
/**
* Utility function to parse an argument for XRuleException configurations.
*
* This takes an XRuleException argument, checks the provided prefix,
* and if it matches returns IB_OK and assigns the `char *` following the
* prefix in @a arg to @a rest. Thus, the caller is provided with
* the value following the prefix and may continue parsing it.
*
* @param[in] expected The expected value. A case insensitive comparison
* is done between @a expected and @a arg.
* @param[in] arg The argument to check.
* @param[in] rest The rest of @a arg following the prefix @a expected.
*
* @returns
* - IB_OK On success and a match.
* - IB_ENOENT If @a expected does not match @a arg.
*/
ib_status_t parse_arg(
const char *expected,
const char *arg,
const char **rest
)
{
size_t len = strlen(expected);
if (strncasecmp(expected, arg, len) == 0) {
(*rest) = arg+len;
return IB_OK;
}
else {
return IB_ENOENT;
}
}
/**
* Use ib_uuid_create_v4() to generate a name.
*
* This is used to name Actions when the name is not important.
*/
std::string random_name()
{
std::vector<char> uuid(IB_UUID_LENGTH);
IronBee::throw_if_error(ib_uuid_create_v4(&(uuid[0])));
return std::string(&(uuid[0]));
}
/**
* A ConclusionAction is an action that conditionally fires when it is applied.
*
* To implement an XRuleException we actually wire together many
* FactActions which, after each is called, attempts to apply the
* ConclusionAction.
*
* The ConclusionAction will only fire if all its facts are true (results=1).
*/
class ConclusionAction : public Action
{
public:
/**
* Construct a conclusion action that depends on @a results.
*
* @param[in] action The user's action to execute when all FactAction s
* are true.
* @param[in] results The number of results this ConclusionAction should
* create to be given to FactActions.
*/
ConclusionAction(action_ptr action, int results);
/**
* Return a reference to the boolean that denotes a particular result.
*
* @param[in] mdata Module data.
* @param[in] i The index of the result to fetch. This must be in
* the range 0 through the number of results specified when this
* object was created.
*
* @returns The int reference to assign to.
*/
int& result(
XRulesModuleTxData& mdata,
int i
);
private:
//! The action that is applied if all results are true.
action_ptr m_action;
/**
* A vector of results (0=failed/not executed, 1=success).
*
* Only when all of these are equal to 1 will ConclusionAction::m_action
* be executed.
*/
size_t m_results;
/**
* Apply this action to the transaction if all results are non-zero.
*
* @param[in] config Module configuration.
* @param[in] mdata The module.
* @param[in] tx The current transaction.
*/
virtual void apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const;
};
ConclusionAction::ConclusionAction(action_ptr action, int results):
Action(random_name(), 10),
m_action(action),
m_results(results)
{}
int& ConclusionAction::result(
XRulesModuleTxData& mdata,
int i
)
{
std::vector<int>& v = mdata.exception_facts[this];
if (v.size() <= m_results) {
v.resize(m_results);
}
return v[i];
}
void ConclusionAction::apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const
{
std::vector<int>& v = (*mdata).exception_facts[this];
BOOST_FOREACH(int r, v) {
if (r != 1) {
return;
}
}
/* If we reach this code, all results were = 1. Execute. */
(*m_action)(config, mdata, tx);
}
/**
* This action initializes facts to false (0) and sets them to true (1).
*
* To implement an XRuleException we must collect various facts, such as
* is a Path equal to some prefix, is a source IP in a subnet, etc.
* To collect these facts XRules are created and given FactActions
* which record that a given XRule was true and fired its action.
*
* When any FactAction fires, as its last action, it calls its
* associated ConclusionAction. A ConclusionAction will check if all
* FactActions have set their facts to true (1). Only if all facts are
* true does the ConclusionAction then fire its own associated Action.
* The ConclusionAction's Action is the action the user requested
* in the configuration language.
*/
class FactAction : public Action
{
public:
/**
* Construct a new action.
*
* @param[in] conclusion The conclusion action that this Fact is
* gating the execution of.
* @param[in] result_idx The index of the result in the result
* vector of the ConclusionAction.
*
* @note This takes a reference to a boolean because actions may
* not modify themselves.
*/
FactAction(action_ptr conclusion, int result_idx);
private:
action_ptr m_conclusion;
int m_result_idx;
/**
* Apply this action to the transaction.
*
* @param[in] config Module configuration.
* @param[in] mdata The module.
* @param[in] tx The current transaction.
*/
virtual void apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const;
};
FactAction::FactAction(action_ptr conclusion, int result_idx) :
Action(random_name(), 10),
m_conclusion(conclusion),
m_result_idx(result_idx)
{}
void FactAction::apply_impl(
const XRulesModuleConfig& config,
xrules_module_tx_data_ptr mdata,
IronBee::Transaction tx
) const
{
/* Update the results. */
static_cast<ConclusionAction&>(*m_conclusion).
result(*mdata, m_result_idx) = 1;
/* Having updated the results, try the conclusion. */
(*m_conclusion)(config, mdata, tx);
}
} /* Anonymous Namespace */
void XRuleException::xrule_directive(
XRulesModule module,
IronBee::ConfigurationParser cp,
const char * name,
IronBee::ConstList<const char *> all_params
)
{
IronBee::Context ctx = cp.current_context();
XRulesModuleConfig& cfg =
module.module().configuration_data<XRulesModuleConfig>(ctx);
/* The unparsed bits from parsing an action out of the params arg. */
IronBee::List<const char *> params =
IronBee::List<const char *>::create(cp.memory_manager());
/* Parse the action and put the remaining tokens in `params`. */
action_ptr user_action = module.parse_action(cp, all_params, params);
/* Construct a conclusion action that will fire the user's action. */
action_ptr conclusion(
boost::make_shared<ConclusionAction>(
user_action,
params.size()));
/* The conclusion action will log. The user action does not. */
user_action->logevent_msg() =
std::string("Exception matched: ") +
user_action->logevent_msg();
user_action->logevent_tag() = user_action->logevent_tag();
conclusion->logevent_msg() = "";
conclusion->logevent_tag() = "";
if (params.empty()) {
BOOST_THROW_EXCEPTION(
IronBee::einval()
<< IronBee::errinfo_what(
"XRuleException require at least 1 argument.")
);
}
int result_idx = 0;
BOOST_FOREACH(const char* param, params) {
const char* val;
/* Build a new FactAction to
* - Set the result `result_idx` to 1.
* - Fire the conclusion action. */
action_ptr action(
boost::make_shared<FactAction>(
conclusion,
result_idx));
++result_idx;
if (IB_OK == parse_arg("EventTag:", param, &val)) {
IronBee::List<const char *> l =
IronBee::List<const char *>::create(cp.memory_manager());
l.push_back(val);
action->logevent_msg() =
std::string("EventTag ") +
val +
" matched";
action->logevent_tag() = "xrules/tags";
cfg.event_xrules.push_back(
xrule_ptr(
new XRuleEventTag(l, action)));
}
else if (IB_OK == parse_arg("IPv4:", param, &val)) {
// Copy in an empty, uninitialized ipset entry.
ib_ipset4_entry_t entry;
memset(&entry, 0, sizeof(entry));
val = XRuleIP::normalize_ipv4(cp.memory_manager(), val);
IronBee::throw_if_error(
ib_ip4_str_to_net(val, &(entry.network)),
(std::string("Failed to get net from string: ")+val).c_str()
);
action->logevent_msg() =
std::string("IPv4 ") +
val +
" matched";
action->logevent_tag() = "xrules/ipv4";
// Put that action in the ip set.
entry.data = IronBee::value_to_data<action_ptr>(
action,
cp.engine().main_memory_mm().ib());
cfg.ipv4_list.push_back(entry);
}
else if (IB_OK == parse_arg("IPv6:", param, &val)) {
// Copy in an empty, uninitialized ipset entry.
ib_ipset6_entry_t entry;
memset(&entry, 0, sizeof(entry));
val = XRuleIP::normalize_ipv6(cp.memory_manager(), val);
IronBee::throw_if_error(
ib_ip6_str_to_net(val, &(entry.network)),
(std::string("Failed to get net from string: ")+val).c_str()
);
action->logevent_msg() =
std::string("IPv6 ") +
val +
" matched";
action->logevent_tag() = "xrules/ipv6";
// Put that action in the ip set.
entry.data = IronBee::value_to_data<action_ptr>(
action,
cp.engine().main_memory_mm().ib());
cfg.ipv6_list.push_back(entry);
}
else if (IB_OK == parse_arg("Geo:", param, &val)) {
action->logevent_msg() =
std::string("Geo ") +
val +
" matched";
action->logevent_tag() = "xrules/geo";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleGeo(val, action)));
}
else if (IB_OK == parse_arg("Path:", param, &val)) {
action->logevent_msg() =
std::string("Path ") +
val +
" matched";
action->logevent_tag() = "xrules/path";
cfg.req_xrules.push_back(
xrule_ptr(
new XRulePath(val, action)));
}
else if (IB_OK == parse_arg("Param:", param, &val)) {
action->logevent_msg() = std::string("Param ") + val + " matched";
action->logevent_tag() = "xrule/param";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleParam(val, cp.engine(), action)));
}
else if (IB_OK == parse_arg("Cookie:", param, &val)) {
action->logevent_msg() = std::string("Cookie ") + val + " matched";
action->logevent_tag() = "xrule/cookie";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleCookie(val, cp.engine(), action)));
}
else if (IB_OK == parse_arg("RequestHeader:", param, &val)) {
action->logevent_msg() =
std::string("RequestHeader ") + val + " matched";
action->logevent_tag() = "xrule/requestheader";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleRequestHeader(val, action)));
}
else if (IB_OK == parse_arg("Method:", param, &val)) {
action->logevent_msg() = std::string("Method ") + val + " matched";
action->logevent_tag() = "xrule/method";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleMethod(val, action)));
}
else if (IB_OK == parse_arg("Hostname:", param, &val)) {
action->logevent_msg() = std::string("Hostname ") + val + " matched";
action->logevent_tag() = "xrule/hostname";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleHostname(val, action)));
}
else if (IB_OK == parse_arg("RequestContentType", param, &val)) {
action->logevent_msg() =
std::string("RequestContentType ") + val + " matched";
action->logevent_tag() = "xrule/content_type/request";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleContentType(val, action,
"request_headers:Content-Type",
"request_headers:Content-Length",
"request_headers:Transport-Encoding")));
}
else if (IB_OK == parse_arg("Time", param, &val)) {
action->logevent_msg() = std::string("Time ") + val + " matched";
action->logevent_tag() = "xrule/time";
cfg.req_xrules.push_back(
xrule_ptr(
new XRuleTime(cp, val, action)));
}
else {
BOOST_THROW_EXCEPTION(
IronBee::enoent()
<< IronBee::errinfo_what(
std::string("Unknown XRuleException: ")+param)
);
}
}
}
<|endoftext|> |
<commit_before>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Sholazar_Basin
SD%Complete: 100
SDComment: Quest support: 11253, 11241.
SDCategory: howling_fjord
EndScriptData */
/* ContentData
npc_plaguehound_tracker
npc_apothecary_hanes
EndContentData */
#include "PassiveAI.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedEscortAI.h"
#include "ScriptedGossip.h"
#include "SpellInfo.h"
// Ours
class npc_attracted_reef_bull : public CreatureScript
{
public:
npc_attracted_reef_bull() : CreatureScript("npc_attracted_reef_bull") { }
struct npc_attracted_reef_bullAI : public NullCreatureAI
{
npc_attracted_reef_bullAI(Creature* creature) : NullCreatureAI(creature)
{
me->SetDisableGravity(true);
if (me->IsSummon())
if (Unit* owner = me->ToTempSummon()->GetSummonerUnit())
me->GetMotionMaster()->MovePoint(0, *owner);
}
void MovementInform(uint32 /*type*/, uint32 /*id*/) override
{
if (Creature* cow = me->FindNearestCreature(24797, 5.0f, true))
{
me->CastSpell(me, 44460, true);
me->DespawnOrUnsummon(10000);
cow->CastSpell(cow, 44460, true);
cow->DespawnOrUnsummon(10000);
if (me->IsSummon())
if (Unit* owner = me->ToTempSummon()->GetSummonerUnit())
owner->CastSpell(owner, 44463, true);
}
}
void SpellHit(Unit* caster, SpellInfo const* spellInfo) override
{
if (caster && spellInfo->Id == 44454)
me->GetMotionMaster()->MovePoint(0, *caster);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_attracted_reef_bullAI(creature);
}
};
// The cleansing
enum TurmoilTexts
{
SAY_TURMOIL_0 = 0,
SAY_TURMOIL_1 = 1,
SAY_TURMOIL_HALF_HP = 2,
SAY_TURMOIL_DEATH = 3,
};
class npc_your_inner_turmoil : public CreatureScript
{
public:
npc_your_inner_turmoil() : CreatureScript("npc_your_inner_turmoil") { }
struct npc_your_inner_turmoilAI : public ScriptedAI
{
npc_your_inner_turmoilAI(Creature* creature) : ScriptedAI(creature) {}
uint32 timer;
short phase;
bool health50;
void Reset() override
{
timer = 0;
phase = 0;
health50 = false;
}
void UpdateAI(uint32 diff) override
{
if (timer >= 6000 && phase < 2)
{
phase++;
setphase(phase);
timer = 0;
}
timer += diff;
DoMeleeAttackIfReady();
}
void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType /*damagetype*/, SpellSchoolMask /*damageSchoolMask*/) override
{
if (HealthBelowPct(50) && !health50)
{
Talk(SAY_TURMOIL_HALF_HP, me->ToTempSummon()->GetSummonerUnit()->ToPlayer());
health50 = true;
}
}
void JustDied(Unit* /*killer*/) override
{
Talk(SAY_TURMOIL_DEATH, me->ToTempSummon()->GetSummonerUnit()->ToPlayer());
}
void setphase(short newPhase)
{
Unit* summoner = me->ToTempSummon() ? me->ToTempSummon()->GetSummonerUnit() : nullptr;
if (!summoner || summoner->GetTypeId() != TYPEID_PLAYER)
return;
switch (newPhase)
{
case 1:
Talk(SAY_TURMOIL_0, summoner->ToPlayer());
return;
case 2:
{
Talk(SAY_TURMOIL_1, summoner->ToPlayer());
me->SetLevel(summoner->getLevel());
me->SetFaction(FACTION_MONSTER);
if (me->GetExactDist(summoner) < 50.0f)
{
me->UpdatePosition(summoner->GetPositionX(), summoner->GetPositionY(), summoner->GetPositionZ(), 0.0f, true);
summoner->CastSpell(me, 50218, true); // clone caster
AttackStart(summoner);
}
}
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_your_inner_turmoilAI(creature);
}
};
// Theirs
/*######
## npc_apothecary_hanes
######*/
enum Entries
{
NPC_APOTHECARY_HANES = 23784,
NPC_HANES_FIRE_TRIGGER = 23968,
QUEST_TRAIL_OF_FIRE = 11241,
SPELL_COSMETIC_LOW_POLY_FIRE = 56274,
SPELL_HEALING_POTION = 17534
};
class npc_apothecary_hanes : public CreatureScript
{
public:
npc_apothecary_hanes() : CreatureScript("npc_apothecary_hanes") { }
bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override
{
if (quest->GetQuestId() == QUEST_TRAIL_OF_FIRE)
{
creature->SetFaction(player->GetTeamId() == TEAM_ALLIANCE ? FACTION_ESCORTEE_A_PASSIVE : FACTION_ESCORTEE_H_PASSIVE);
CAST_AI(npc_escortAI, (creature->AI()))->Start(true, false, player->GetGUID());
}
return true;
}
struct npc_Apothecary_HanesAI : public npc_escortAI
{
npc_Apothecary_HanesAI(Creature* creature) : npc_escortAI(creature) { }
uint32 PotTimer;
void Reset() override
{
SetDespawnAtFar(false);
PotTimer = 10000; //10 sec cooldown on potion
}
void JustDied(Unit* /*killer*/) override
{
if (Player* player = GetPlayerForEscort())
player->FailQuest(QUEST_TRAIL_OF_FIRE);
}
void UpdateEscortAI(uint32 diff) override
{
if (HealthBelowPct(75))
{
if (PotTimer <= diff)
{
DoCast(me, SPELL_HEALING_POTION, true);
PotTimer = 10000;
}
else PotTimer -= diff;
}
if (GetAttack() && UpdateVictim())
DoMeleeAttackIfReady();
}
void WaypointReached(uint32 waypointId) override
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 1:
me->SetReactState(REACT_AGGRESSIVE);
SetRun(true);
break;
case 23:
player->GroupEventHappens(QUEST_TRAIL_OF_FIRE, me);
me->DespawnOrUnsummon();
break;
case 5:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(false);
break;
case 6:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(true);
break;
case 8:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(false);
break;
case 9:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
break;
case 10:
SetRun(true);
break;
case 13:
SetRun(false);
break;
case 14:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(true);
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_Apothecary_HanesAI(creature);
}
};
/*######
## npc_plaguehound_tracker
######*/
class npc_plaguehound_tracker : public CreatureScript
{
public:
npc_plaguehound_tracker() : CreatureScript("npc_plaguehound_tracker") { }
struct npc_plaguehound_trackerAI : public npc_escortAI
{
npc_plaguehound_trackerAI(Creature* creature) : npc_escortAI(creature) { }
void Reset() override
{
ObjectGuid summonerGUID;
if (me->IsSummon())
if (Unit* summoner = me->ToTempSummon()->GetSummonerUnit())
if (summoner->GetTypeId() == TYPEID_PLAYER)
summonerGUID = summoner->GetGUID();
if (!summonerGUID)
return;
me->SetWalk(true);
Start(false, false, summonerGUID);
}
void WaypointReached(uint32 waypointId) override
{
if (waypointId != 26)
return;
me->DespawnOrUnsummon();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_plaguehound_trackerAI(creature);
}
};
/*######
## npc_razael_and_lyana
######*/
enum Razael
{
QUEST_REPORTS_FROM_THE_FIELD = 11221,
NPC_RAZAEL = 23998,
NPC_LYANA = 23778,
GOSSIP_TEXTID_RAZAEL1 = 11562,
GOSSIP_TEXTID_RAZAEL2 = 11564,
GOSSIP_TEXTID_LYANA1 = 11586,
GOSSIP_TEXTID_LYANA2 = 11588
};
class npc_razael_and_lyana : public CreatureScript
{
public:
npc_razael_and_lyana() : CreatureScript("npc_razael_and_lyana") { }
bool OnGossipHello(Player* player, Creature* creature) override
{
if (creature->IsQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (player->GetQuestStatus(QUEST_REPORTS_FROM_THE_FIELD) == QUEST_STATUS_INCOMPLETE)
switch (creature->GetEntry())
{
case NPC_RAZAEL:
if (!player->GetReqKillOrCastCurrentCount(QUEST_REPORTS_FROM_THE_FIELD, NPC_RAZAEL))
{
AddGossipItemFor(player, 8870, 0, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
SendGossipMenuFor(player, GOSSIP_TEXTID_RAZAEL1, creature->GetGUID());
return true;
}
break;
case NPC_LYANA:
if (!player->GetReqKillOrCastCurrentCount(QUEST_REPORTS_FROM_THE_FIELD, NPC_LYANA))
{
AddGossipItemFor(player, 8879, 0, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
SendGossipMenuFor(player, GOSSIP_TEXTID_LYANA1, creature->GetGUID());
return true;
}
break;
}
SendGossipMenuFor(player, player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
ClearGossipMenuFor(player);
switch (action)
{
case GOSSIP_ACTION_INFO_DEF + 1:
SendGossipMenuFor(player, GOSSIP_TEXTID_RAZAEL2, creature->GetGUID());
player->TalkedToCreature(NPC_RAZAEL, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
SendGossipMenuFor(player, GOSSIP_TEXTID_LYANA2, creature->GetGUID());
player->TalkedToCreature(NPC_LYANA, creature->GetGUID());
break;
}
return true;
}
};
void AddSC_howling_fjord()
{
// Ours
new npc_attracted_reef_bull();
new npc_your_inner_turmoil();
// Theirs
new npc_apothecary_hanes();
new npc_plaguehound_tracker();
new npc_razael_and_lyana();
}
<commit_msg>fix(Core): Crashfix. (#12093)<commit_after>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Sholazar_Basin
SD%Complete: 100
SDComment: Quest support: 11253, 11241.
SDCategory: howling_fjord
EndScriptData */
/* ContentData
npc_plaguehound_tracker
npc_apothecary_hanes
EndContentData */
#include "PassiveAI.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedEscortAI.h"
#include "ScriptedGossip.h"
#include "SpellInfo.h"
// Ours
class npc_attracted_reef_bull : public CreatureScript
{
public:
npc_attracted_reef_bull() : CreatureScript("npc_attracted_reef_bull") { }
struct npc_attracted_reef_bullAI : public NullCreatureAI
{
npc_attracted_reef_bullAI(Creature* creature) : NullCreatureAI(creature)
{
me->SetDisableGravity(true);
if (me->IsSummon())
if (Unit* owner = me->ToTempSummon()->GetSummonerUnit())
me->GetMotionMaster()->MovePoint(0, *owner);
}
void MovementInform(uint32 /*type*/, uint32 /*id*/) override
{
if (Creature* cow = me->FindNearestCreature(24797, 5.0f, true))
{
me->CastSpell(me, 44460, true);
me->DespawnOrUnsummon(10000);
cow->CastSpell(cow, 44460, true);
cow->DespawnOrUnsummon(10000);
if (me->IsSummon())
if (Unit* owner = me->ToTempSummon()->GetSummonerUnit())
owner->CastSpell(owner, 44463, true);
}
}
void SpellHit(Unit* caster, SpellInfo const* spellInfo) override
{
if (caster && spellInfo->Id == 44454)
me->GetMotionMaster()->MovePoint(0, *caster);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_attracted_reef_bullAI(creature);
}
};
// The cleansing
enum TurmoilTexts
{
SAY_TURMOIL_0 = 0,
SAY_TURMOIL_1 = 1,
SAY_TURMOIL_HALF_HP = 2,
SAY_TURMOIL_DEATH = 3,
};
class npc_your_inner_turmoil : public CreatureScript
{
public:
npc_your_inner_turmoil() : CreatureScript("npc_your_inner_turmoil") { }
struct npc_your_inner_turmoilAI : public ScriptedAI
{
npc_your_inner_turmoilAI(Creature* creature) : ScriptedAI(creature) {}
uint32 timer;
short phase;
bool health50;
void Reset() override
{
timer = 0;
phase = 0;
health50 = false;
}
void UpdateAI(uint32 diff) override
{
if (timer >= 6000 && phase < 2)
{
phase++;
setphase(phase);
timer = 0;
}
timer += diff;
DoMeleeAttackIfReady();
}
void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType /*damagetype*/, SpellSchoolMask /*damageSchoolMask*/) override
{
if (HealthBelowPct(50) && !health50)
{
WorldObject* summoner = nullptr;
if (TempSummon const* tempSummon = me->ToTempSummon())
{
summoner = tempSummon->GetSummonerUnit();
}
Talk(SAY_TURMOIL_HALF_HP, summoner);
health50 = true;
}
}
void JustDied(Unit* /*killer*/) override
{
Talk(SAY_TURMOIL_DEATH, me->ToTempSummon()->GetSummonerUnit()->ToPlayer());
}
void setphase(short newPhase)
{
Unit* summoner = me->ToTempSummon() ? me->ToTempSummon()->GetSummonerUnit() : nullptr;
if (!summoner || summoner->GetTypeId() != TYPEID_PLAYER)
return;
switch (newPhase)
{
case 1:
Talk(SAY_TURMOIL_0, summoner->ToPlayer());
return;
case 2:
{
Talk(SAY_TURMOIL_1, summoner->ToPlayer());
me->SetLevel(summoner->getLevel());
me->SetFaction(FACTION_MONSTER);
if (me->GetExactDist(summoner) < 50.0f)
{
me->UpdatePosition(summoner->GetPositionX(), summoner->GetPositionY(), summoner->GetPositionZ(), 0.0f, true);
summoner->CastSpell(me, 50218, true); // clone caster
AttackStart(summoner);
}
}
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_your_inner_turmoilAI(creature);
}
};
// Theirs
/*######
## npc_apothecary_hanes
######*/
enum Entries
{
NPC_APOTHECARY_HANES = 23784,
NPC_HANES_FIRE_TRIGGER = 23968,
QUEST_TRAIL_OF_FIRE = 11241,
SPELL_COSMETIC_LOW_POLY_FIRE = 56274,
SPELL_HEALING_POTION = 17534
};
class npc_apothecary_hanes : public CreatureScript
{
public:
npc_apothecary_hanes() : CreatureScript("npc_apothecary_hanes") { }
bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override
{
if (quest->GetQuestId() == QUEST_TRAIL_OF_FIRE)
{
creature->SetFaction(player->GetTeamId() == TEAM_ALLIANCE ? FACTION_ESCORTEE_A_PASSIVE : FACTION_ESCORTEE_H_PASSIVE);
CAST_AI(npc_escortAI, (creature->AI()))->Start(true, false, player->GetGUID());
}
return true;
}
struct npc_Apothecary_HanesAI : public npc_escortAI
{
npc_Apothecary_HanesAI(Creature* creature) : npc_escortAI(creature) { }
uint32 PotTimer;
void Reset() override
{
SetDespawnAtFar(false);
PotTimer = 10000; //10 sec cooldown on potion
}
void JustDied(Unit* /*killer*/) override
{
if (Player* player = GetPlayerForEscort())
player->FailQuest(QUEST_TRAIL_OF_FIRE);
}
void UpdateEscortAI(uint32 diff) override
{
if (HealthBelowPct(75))
{
if (PotTimer <= diff)
{
DoCast(me, SPELL_HEALING_POTION, true);
PotTimer = 10000;
}
else PotTimer -= diff;
}
if (GetAttack() && UpdateVictim())
DoMeleeAttackIfReady();
}
void WaypointReached(uint32 waypointId) override
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 1:
me->SetReactState(REACT_AGGRESSIVE);
SetRun(true);
break;
case 23:
player->GroupEventHappens(QUEST_TRAIL_OF_FIRE, me);
me->DespawnOrUnsummon();
break;
case 5:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(false);
break;
case 6:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(true);
break;
case 8:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(false);
break;
case 9:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
break;
case 10:
SetRun(true);
break;
case 13:
SetRun(false);
break;
case 14:
if (Unit* Trigger = me->FindNearestCreature(NPC_HANES_FIRE_TRIGGER, 10.0f))
Trigger->CastSpell(Trigger, SPELL_COSMETIC_LOW_POLY_FIRE, false);
SetRun(true);
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_Apothecary_HanesAI(creature);
}
};
/*######
## npc_plaguehound_tracker
######*/
class npc_plaguehound_tracker : public CreatureScript
{
public:
npc_plaguehound_tracker() : CreatureScript("npc_plaguehound_tracker") { }
struct npc_plaguehound_trackerAI : public npc_escortAI
{
npc_plaguehound_trackerAI(Creature* creature) : npc_escortAI(creature) { }
void Reset() override
{
ObjectGuid summonerGUID;
if (me->IsSummon())
if (Unit* summoner = me->ToTempSummon()->GetSummonerUnit())
if (summoner->GetTypeId() == TYPEID_PLAYER)
summonerGUID = summoner->GetGUID();
if (!summonerGUID)
return;
me->SetWalk(true);
Start(false, false, summonerGUID);
}
void WaypointReached(uint32 waypointId) override
{
if (waypointId != 26)
return;
me->DespawnOrUnsummon();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_plaguehound_trackerAI(creature);
}
};
/*######
## npc_razael_and_lyana
######*/
enum Razael
{
QUEST_REPORTS_FROM_THE_FIELD = 11221,
NPC_RAZAEL = 23998,
NPC_LYANA = 23778,
GOSSIP_TEXTID_RAZAEL1 = 11562,
GOSSIP_TEXTID_RAZAEL2 = 11564,
GOSSIP_TEXTID_LYANA1 = 11586,
GOSSIP_TEXTID_LYANA2 = 11588
};
class npc_razael_and_lyana : public CreatureScript
{
public:
npc_razael_and_lyana() : CreatureScript("npc_razael_and_lyana") { }
bool OnGossipHello(Player* player, Creature* creature) override
{
if (creature->IsQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (player->GetQuestStatus(QUEST_REPORTS_FROM_THE_FIELD) == QUEST_STATUS_INCOMPLETE)
switch (creature->GetEntry())
{
case NPC_RAZAEL:
if (!player->GetReqKillOrCastCurrentCount(QUEST_REPORTS_FROM_THE_FIELD, NPC_RAZAEL))
{
AddGossipItemFor(player, 8870, 0, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
SendGossipMenuFor(player, GOSSIP_TEXTID_RAZAEL1, creature->GetGUID());
return true;
}
break;
case NPC_LYANA:
if (!player->GetReqKillOrCastCurrentCount(QUEST_REPORTS_FROM_THE_FIELD, NPC_LYANA))
{
AddGossipItemFor(player, 8879, 0, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
SendGossipMenuFor(player, GOSSIP_TEXTID_LYANA1, creature->GetGUID());
return true;
}
break;
}
SendGossipMenuFor(player, player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
ClearGossipMenuFor(player);
switch (action)
{
case GOSSIP_ACTION_INFO_DEF + 1:
SendGossipMenuFor(player, GOSSIP_TEXTID_RAZAEL2, creature->GetGUID());
player->TalkedToCreature(NPC_RAZAEL, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
SendGossipMenuFor(player, GOSSIP_TEXTID_LYANA2, creature->GetGUID());
player->TalkedToCreature(NPC_LYANA, creature->GetGUID());
break;
}
return true;
}
};
void AddSC_howling_fjord()
{
// Ours
new npc_attracted_reef_bull();
new npc_your_inner_turmoil();
// Theirs
new npc_apothecary_hanes();
new npc_plaguehound_tracker();
new npc_razael_and_lyana();
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Tavendo GmbH
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include <msgpack.hpp>
#include <string>
#include <unordered_map>
namespace autobahn {
inline wamp_subscribe_options::wamp_subscribe_options()
: m_match()
{
}
inline const std::string& wamp_subscribe_options::match() const
{
return *m_match;
}
inline const bool wamp_subscribe_options::is_match_set() const
{
return m_match.is_initialized();
}
inline void wamp_subscribe_options::set_match(const std::string& match)
{
if (!(match == "exact" || match == "prefix" || match == "wildcard"))
{
throw std::runtime_error("The value of 'match' must be 'exact', 'prefix', or 'wildcard'.");
}
m_match = match;
}
} // namespace autobahn
namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
namespace adaptor {
template<>
struct convert<autobahn::wamp_subscribe_options>
{
msgpack::object const& operator()(
msgpack::object const& object,
autobahn::wamp_subscribe_options& options) const
{
return object;
}
};
template<>
struct pack<autobahn::wamp_subscribe_options>
{
template <typename Stream>
msgpack::packer<Stream>& operator()(
msgpack::packer<Stream>& packer,
autobahn::wamp_subscribe_options const& options) const
{
std::map<std::string, std::string> options_map;
bool should_pack_options = false;
if (options.is_match_set())
{
options_map["match"] = options.match();
should_pack_options = true;
}
if (should_pack_options)
{
packer.pack(options_map);
}
else
{
packer.pack_map(0);
}
return packer;
}
};
template <>
struct object_with_zone<autobahn::wamp_subscribe_options>
{
void operator()(
msgpack::object::with_zone& object,
const autobahn::wamp_subscribe_options& options)
{
std::map<std::string, std::string> options_map;
bool should_copy_options = false;
if (options.is_match_set())
{
options_map["match"] = options.match();
should_copy_options = true;
}
if (should_copy_options)
{
object << options_map;
}
}
};
} // namespace adaptor
} // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS)
} // namespace msgpack
<commit_msg>Fix subscribe options<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Tavendo GmbH
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include <msgpack.hpp>
#include <string>
#include <unordered_map>
namespace autobahn {
inline wamp_subscribe_options::wamp_subscribe_options()
: m_match()
{
}
inline const std::string& wamp_subscribe_options::match() const
{
return *m_match;
}
inline const bool wamp_subscribe_options::is_match_set() const
{
return m_match.is_initialized();
}
inline void wamp_subscribe_options::set_match(const std::string& match)
{
if (!(match == "exact" || match == "prefix" || match == "wildcard"))
{
throw std::runtime_error("The value of 'match' must be 'exact', 'prefix', or 'wildcard'.");
}
m_match = match;
}
} // namespace autobahn
namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
namespace adaptor {
template<>
struct convert<autobahn::wamp_subscribe_options>
{
msgpack::object const& operator()(
msgpack::object const& object,
autobahn::wamp_subscribe_options& options) const
{
return object;
}
};
template<>
struct pack<autobahn::wamp_subscribe_options>
{
template <typename Stream>
msgpack::packer<Stream>& operator()(
msgpack::packer<Stream>& packer,
autobahn::wamp_subscribe_options const& options) const
{
std::map<std::string, std::string> options_map;
if (options.is_match_set())
{
options_map["match"] = options.match();
}
packer.pack(options_map);
return packer;
}
};
template <>
struct object_with_zone<autobahn::wamp_subscribe_options>
{
void operator()(
msgpack::object::with_zone& object,
const autobahn::wamp_subscribe_options& options)
{
std::map<std::string, std::string> options_map;
if (options.is_match_set())
{
options_map["match"] = options.match();
}
object << options_map;
}
};
} // namespace adaptor
} // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS)
} // namespace msgpack
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tplparam.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:50:07 $
*
* 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 <precomp.h>
#include "tplparam.hxx"
// NOT FULLY DEFINED SERVICES
#include <cpp/c_gate.hxx>
namespace ary
{
namespace cpp
{
namespace ut
{
TplParameter_Type::TplParameter_Type( Tid i_nType )
: nType(i_nType)
{
}
TplParameter_Type::~TplParameter_Type()
{
}
intt
TplParameter_Type::Compare( const TemplateParameter & i_rOther ) const
{
const TplParameter_Type * pOther
= dynamic_cast< const TplParameter_Type* >( &i_rOther );
if (pOther == 0)
return -1;
return nType - pOther->nType;
}
void
TplParameter_Type::Get_Text( StreamStr & o_rOut,
const ary::cpp::DisplayGate & i_rGate ) const
{
i_rGate.Get_TypeText( o_rOut, nType );
}
TplParameter_Const::TplParameter_Const( const udmstri & i_sConst )
: sConstant(i_sConst)
{
}
TplParameter_Const::~TplParameter_Const()
{
}
intt
TplParameter_Const::Compare( const TemplateParameter & i_rOther ) const
{
const TplParameter_Const * pOther
= dynamic_cast< const TplParameter_Const* >( &i_rOther );
if (pOther == 0)
return +1;
return strcmp( sConstant.c_str(), pOther->sConstant.c_str() );
}
void
TplParameter_Const::Get_Text( StreamStr & o_rOut,
const ary::cpp::DisplayGate & ) const
{
o_rOut << sConstant;
}
} // namespace ut
} // namespace cpp
} // namespace ary
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.6); FILE MERGED 2006/09/01 17:15:17 kaib 1.3.6.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tplparam.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 16:19:54 $
*
* 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_autodoc.hxx"
#include <precomp.h>
#include "tplparam.hxx"
// NOT FULLY DEFINED SERVICES
#include <cpp/c_gate.hxx>
namespace ary
{
namespace cpp
{
namespace ut
{
TplParameter_Type::TplParameter_Type( Tid i_nType )
: nType(i_nType)
{
}
TplParameter_Type::~TplParameter_Type()
{
}
intt
TplParameter_Type::Compare( const TemplateParameter & i_rOther ) const
{
const TplParameter_Type * pOther
= dynamic_cast< const TplParameter_Type* >( &i_rOther );
if (pOther == 0)
return -1;
return nType - pOther->nType;
}
void
TplParameter_Type::Get_Text( StreamStr & o_rOut,
const ary::cpp::DisplayGate & i_rGate ) const
{
i_rGate.Get_TypeText( o_rOut, nType );
}
TplParameter_Const::TplParameter_Const( const udmstri & i_sConst )
: sConstant(i_sConst)
{
}
TplParameter_Const::~TplParameter_Const()
{
}
intt
TplParameter_Const::Compare( const TemplateParameter & i_rOther ) const
{
const TplParameter_Const * pOther
= dynamic_cast< const TplParameter_Const* >( &i_rOther );
if (pOther == 0)
return +1;
return strcmp( sConstant.c_str(), pOther->sConstant.c_str() );
}
void
TplParameter_Const::Get_Text( StreamStr & o_rOut,
const ary::cpp::DisplayGate & ) const
{
o_rOut << sConstant;
}
} // namespace ut
} // namespace cpp
} // namespace ary
<|endoftext|> |
<commit_before>#include "dwarf.h"
#include "symbols.h"
#include "../ast/error.h"
#include "../pkg/package.h"
#include "../type/subtype.h"
#include "../../libponyrt/mem/pool.h"
#include "../../libponyrt/pony.h"
#define OFFSET_CLASS (sizeof(void*) * 8)
#define OFFSET_ACTOR (sizeof(pony_actor_pad_t) * 8)
using namespace llvm;
using namespace llvm::dwarf;
typedef struct frame_t frame_t;
struct frame_t
{
size_t size;
subnodes_t* members;
frame_t* prev;
};
struct dwarf_t
{
symbols_t* symbols;
DataLayout* layout;
frame_t* frame;
};
/**
* Every call to dwarf_forward causes a dwarf_frame_t to be pushed onto
* the stack.
*/
static frame_t* push_frame(dwarf_t* dwarf)
{
frame_t* frame = POOL_ALLOC(frame_t);
memset(frame, 0, sizeof(frame_t));
frame->prev = dwarf->frame;
dwarf->frame = frame;
return frame;
}
/**
* Every call to dwarf_composite causes a dwarf_frame_t to be popped from
* the stack.
*/
static void pop_frame(dwarf_t* dwarf)
{
frame_t* frame = dwarf->frame;
dwarf->frame = frame->prev;
POOL_FREE(frame_t, frame);
}
/**
* Collect type information such as file and line scope. The definition
* of tuple types is lexically unscoped, because tuple type names are
* ambiguous.
*/
static void setup_dwarf(dwarf_t* dwarf, gentype_t* g, LLVMTypeRef typeref,
symbol_scope_t* scope, bool definition, bool prelim)
{
ast_t* ast = g->ast;
Type* type = unwrap(typeref);
memset(scope, 0, sizeof(symbol_scope_t));
if(definition && ast_id(ast) != TK_TUPLETYPE)
{
ast = (ast_t*)ast_data(ast);
ast_t* module = ast_nearest(ast, TK_MODULE);
source_t* source = (source_t*)ast_data(module);
scope->file = symbols_file(dwarf->symbols, source->file);
}
if(!prelim)
{
g->size = dwarf->layout->getTypeSizeInBits(type);
g->align = dwarf->layout->getABITypeAlignment(type) << 3;
}
scope->line = ast_line(ast);
scope->pos = ast_pos(ast);
}
void dwarf_compileunit(dwarf_t* dwarf, ast_t* program)
{
assert(ast_id(program) == TK_PROGRAM);
ast_t* package = ast_child(program);
const char* path = package_path(package);
const char* name = package_filename(package);
symbols_package(dwarf->symbols, path, name);
}
void dwarf_forward(dwarf_t* dwarf, gentype_t* g)
{
if(!symbols_known_type(dwarf->symbols, g->type_name))
{
frame_t* frame = push_frame(dwarf);
LLVMTypeRef typeref = g->structure;
size_t size = g->field_count;
// The field count for non-tuple types does not contain
// the methods, which in the dwarf world are subnodes
// just like fields.
if(g->underlying != TK_TUPLETYPE)
{
/*Type* ptr = unwrap(g->structure_ptr);
g->size = dwarf->layout->getTypeSizeInBits(ptr);
g->align = dwarf->layout->getABITypeAlignment(ptr) << 3;*/
ast_t* def = (ast_t*)ast_data(g->ast);
size += ast_childcount(ast_childidx(def, 4)) - size;
} else {
typeref = g->primitive;
}
frame->size = size;
symbol_scope_t scope;
setup_dwarf(dwarf, g, typeref, &scope, true, true);
symbols_declare(dwarf->symbols, g, &frame->members, size, &scope);
}
}
void dwarf_basic(dwarf_t* dwarf, gentype_t* g)
{
// Basic types are builtin, hence have no compilation
// unit scope and their size and ABI alignment depends
// on the primitive structure.
symbol_scope_t scope;
setup_dwarf(dwarf, g, g->primitive, &scope, false, false);
symbols_basic(dwarf->symbols, g);
}
void dwarf_pointer(dwarf_t* dwarf, gentype_t* ptr, gentype_t* g)
{
symbol_scope_t scope;
setup_dwarf(dwarf, ptr, ptr->use_type, &scope, false, false);
symbols_pointer(dwarf->symbols, ptr, g);
}
void dwarf_trait(dwarf_t* dwarf, gentype_t* g)
{
// Trait definitions have a scope, but are modeled
// as opaque classes from which other classes may
// inherit. There is no need to set the size and
// align to 0, because gentype_t was memset.
symbol_scope_t scope;
setup_dwarf(dwarf, g, g->use_type, &scope, true, false);
symbols_trait(dwarf->symbols, g, &scope);
}
void dwarf_composite(dwarf_t* dwarf, gentype_t* g)
{
size_t offset = 0;
switch(g->underlying)
{
case TK_ACTOR: offset = OFFSET_ACTOR;
case TK_PRIMITIVE:
case TK_CLASS: offset += OFFSET_CLASS;
default: {}
}
LLVMTypeRef typeref = g->structure;
if(g->underlying == TK_TUPLETYPE)
typeref = g->primitive;
symbol_scope_t scope;
setup_dwarf(dwarf, g, typeref, &scope, true, false);
symbols_composite(dwarf->symbols, g, offset, dwarf->frame->members,
&scope);
pop_frame(dwarf);
}
void dwarf_field(dwarf_t* dwarf, gentype_t* composite, gentype_t* field,
size_t index)
{
const char* name = "anon";
bool is_private = false;
bool constant = false;
// TK_TUPLETYPE fields are anonymous.
if(composite->underlying != TK_TUPLETYPE)
{
ast_t* def = (ast_t*)ast_data(composite->ast);
ast_t* members = ast_childidx(def, 4);
ast_t* field = ast_childidx(members, index);
assert(ast_id(field) == TK_FVAR || ast_id(field) == TK_FLET);
if(ast_id(field) == TK_FLET)
constant = true;
name = ast_name(ast_child(field));
is_private = name[0] == '_';
}
symbol_scope_t scope;
setup_dwarf(dwarf, field, field->use_type, &scope, false, false);
symbols_member(dwarf->symbols, field, dwarf->frame->members, &scope,
name, is_private, constant, index);
}
void dwarf_init(compile_t* c)
{
c->dwarf = POOL_ALLOC(dwarf_t);
c->dwarf->symbols = symbols_init(c);
c->dwarf->layout = unwrap(c->target_data);
c->dwarf->frame = NULL;
}
void dwarf_finalise(dwarf_t* dwarf)
{
symbols_finalise(dwarf->symbols);
POOL_FREE(dwarf_t, dwarf);
}
<commit_msg>intermediate commit<commit_after>#include "dwarf.h"
#include "symbols.h"
#include "../ast/error.h"
#include "../pkg/package.h"
#include "../type/subtype.h"
#include "../../libponyrt/mem/pool.h"
#include "../../libponyrt/pony.h"
#include <platform.h>
#define OFFSET_CLASS (sizeof(void*) * 8)
#define OFFSET_ACTOR (sizeof(pony_actor_pad_t) * 8)
using namespace llvm;
using namespace llvm::dwarf;
typedef struct frame_t frame_t;
struct frame_t
{
size_t size;
subnodes_t* members;
frame_t* prev;
};
struct dwarf_t
{
symbols_t* symbols;
DataLayout* layout;
frame_t* frame;
};
/**
* Every call to dwarf_forward causes a frame_t to be pushed onto
* the stack.
*/
static frame_t* push_frame(dwarf_t* dwarf)
{
frame_t* frame = POOL_ALLOC(frame_t);
memset(frame, 0, sizeof(frame_t));
frame->prev = dwarf->frame;
dwarf->frame = frame;
return frame;
}
/**
* Every call to dwarf_composite causes a frame_t to be popped from
* the stack.
*/
static void pop_frame(dwarf_t* dwarf)
{
frame_t* frame = dwarf->frame;
dwarf->frame = frame->prev;
POOL_FREE(frame_t, frame);
}
/**
* Collect type information such as file and line scope. The definition
* of tuple types is lexically unscoped, because tuple type names are
* ambiguous.
*/
static void setup_dwarf(dwarf_t* dwarf, gentype_t* g, LLVMTypeRef typeref,
symbol_scope_t* scope, bool definition, bool prelim)
{
ast_t* ast = g->ast;
Type* type = unwrap(typeref);
memset(scope, 0, sizeof(symbol_scope_t));
if(definition && ast_id(ast) != TK_TUPLETYPE)
{
ast = (ast_t*)ast_data(ast);
ast_t* module = ast_nearest(ast, TK_MODULE);
source_t* source = (source_t*)ast_data(module);
scope->file = symbols_file(dwarf->symbols, source->file);
}
if(!prelim)
{
g->size = dwarf->layout->getTypeSizeInBits(type);
g->align = dwarf->layout->getABITypeAlignment(type) << 3;
}
scope->line = ast_line(ast);
scope->pos = ast_pos(ast);
}
void dwarf_compileunit(dwarf_t* dwarf, ast_t* program)
{
assert(ast_id(program) == TK_PROGRAM);
ast_t* package = ast_child(program);
const char* path = package_path(package);
const char* name = package_filename(package);
symbols_package(dwarf->symbols, path, name);
}
void dwarf_forward(dwarf_t* dwarf, gentype_t* g)
{
if(!symbols_known_type(dwarf->symbols, g->type_name))
{
frame_t* frame = push_frame(dwarf);
LLVMTypeRef typeref = g->structure;
size_t size = g->field_count;
// The field count for non-tuple types does not contain
// the methods, which in the dwarf world are subnodes
// just like fields.
if(g->underlying != TK_TUPLETYPE)
{
ast_t* def = (ast_t*)ast_data(g->ast);
size += ast_childcount(ast_childidx(def, 4)) - size;
} else {
typeref = g->primitive;
}
frame->size = size;
symbol_scope_t scope;
setup_dwarf(dwarf, g, typeref, &scope, true, true);
symbols_declare(dwarf->symbols, g, &frame->members, size, &scope);
}
}
void dwarf_basic(dwarf_t* dwarf, gentype_t* g)
{
// Basic types are builtin, hence have no compilation
// unit scope and their size and ABI alignment depends
// on the primitive structure.
symbol_scope_t scope;
setup_dwarf(dwarf, g, g->primitive, &scope, false, false);
symbols_basic(dwarf->symbols, g);
}
void dwarf_pointer(dwarf_t* dwarf, gentype_t* ptr, gentype_t* g)
{
symbol_scope_t scope;
setup_dwarf(dwarf, ptr, ptr->use_type, &scope, false, false);
symbols_pointer(dwarf->symbols, ptr, g);
}
void dwarf_trait(dwarf_t* dwarf, gentype_t* g)
{
// Trait definitions have a scope, but are modeled
// as opaque classes from which other classes may
// inherit. There is no need to set the size and
// align to 0, because gentype_t was memset.
symbol_scope_t scope;
setup_dwarf(dwarf, g, g->use_type, &scope, true, false);
symbols_trait(dwarf->symbols, g, &scope);
}
void dwarf_composite(dwarf_t* dwarf, gentype_t* g)
{
size_t offset = 0;
switch(g->underlying)
{
case TK_ACTOR: offset = OFFSET_ACTOR;
case TK_PRIMITIVE:
case TK_CLASS: offset += OFFSET_CLASS;
default: {}
}
LLVMTypeRef typeref = g->structure;
if(g->underlying == TK_TUPLETYPE)
typeref = g->primitive;
symbol_scope_t scope;
setup_dwarf(dwarf, g, typeref, &scope, true, false);
symbols_composite(dwarf->symbols, g, offset, dwarf->frame->members,
&scope);
pop_frame(dwarf);
}
void dwarf_field(dwarf_t* dwarf, gentype_t* composite, gentype_t* field,
size_t index)
{
char buf[32];
memset(buf, 0, sizeof(buf));
const char* name = NULL;
bool is_private = false;
bool constant = false;
if(composite->underlying != TK_TUPLETYPE)
{
ast_t* def = (ast_t*)ast_data(composite->ast);
ast_t* members = ast_childidx(def, 4);
ast_t* field = ast_childidx(members, index);
assert(ast_id(field) == TK_FVAR || ast_id(field) == TK_FLET);
if(ast_id(field) == TK_FLET)
constant = true;
name = ast_name(ast_child(field));
is_private = name[0] == '_';
} else {
snprintf(buf, sizeof(buf), "_" __zu, index);
name = buf;
}
symbol_scope_t scope;
setup_dwarf(dwarf, field, field->use_type, &scope, false, false);
symbols_member(dwarf->symbols, field, dwarf->frame->members, &scope,
name, is_private, constant, index);
}
void dwarf_init(compile_t* c)
{
c->dwarf = POOL_ALLOC(dwarf_t);
c->dwarf->symbols = symbols_init(c);
c->dwarf->layout = unwrap(c->target_data);
c->dwarf->frame = NULL;
}
void dwarf_finalise(dwarf_t* dwarf)
{
symbols_finalise(dwarf->symbols);
POOL_FREE(dwarf_t, dwarf);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "library/vm/vm.h"
namespace lean {
static void del_instr_at(unsigned pc, buffer<vm_instr> & code) {
code.erase(pc);
// we must adjust pc of other instructions
for (unsigned i = 0; i < code.size(); i++) {
vm_instr & c = code[i];
for (unsigned j = 0; j < c.get_num_pcs(); j++) {
if (c.get_pc(j) > pc)
c.set_pc(j, c.get_pc(j) - 1);
}
}
}
/**
\brief Applies the following transformation
...
pc: drop n
pc+1: drop m
...
===>
...
pc: drop n+m
... */
static void compress_drop_drop(buffer<vm_instr> & code) {
if (code.empty()) return;
unsigned i = code.size() - 1;
while (i > 0) {
--i;
if (code[i].op() == opcode::Drop &&
code[i+1].op() == opcode::Drop) {
code[i] = mk_drop_instr(code[i].get_num() + code[i+1].get_num());
del_instr_at(i+1, code);
}
}
}
/**
\brief Applies the following transformation
pc_1 : goto pc_2
...
pc_2 : ret
===>
pc_1 : ret
...
pc_2 : ret */
static void compress_goto_ret(buffer<vm_instr> & code) {
unsigned i = code.size();
while (i > 0) {
--i;
if (code[i].op() == opcode::Goto) {
unsigned pc = code[i].get_goto_pc();
if (code[pc].op() == opcode::Ret) {
code[i] = mk_ret_instr();
}
}
}
}
void optimize(environment const &, buffer<vm_instr> & code) {
compress_goto_ret(code);
compress_drop_drop(code);
}
}
<commit_msg>fix(library/vm/optimize): bytecode optimization<commit_after>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "library/vm/vm.h"
namespace lean {
static void del_instr_at(unsigned pc, buffer<vm_instr> & code) {
code.erase(pc);
// we must adjust pc of other instructions
for (unsigned i = 0; i < code.size(); i++) {
vm_instr & c = code[i];
for (unsigned j = 0; j < c.get_num_pcs(); j++) {
if (c.get_pc(j) > pc)
c.set_pc(j, c.get_pc(j) - 1);
}
}
}
typedef rb_tree<unsigned, unsigned_cmp> addr_set;
/* Collect addresses in addr_set that are goto/branching targets */
static void collect_targets(buffer<vm_instr> & code, addr_set & r) {
for (auto c : code) {
for (unsigned j = 0; j < c.get_num_pcs(); j++)
r.insert(c.get_pc(j));
}
}
/**
\brief Applies the following transformation
...
pc: drop n
pc+1: drop m
...
===>
...
pc: drop n+m
... */
static void compress_drop_drop(buffer<vm_instr> & code) {
if (code.empty()) return;
addr_set targets;
collect_targets(code, targets);
unsigned i = code.size() - 1;
while (i > 0) {
--i;
if (code[i].op() == opcode::Drop &&
code[i+1].op() == opcode::Drop &&
/* If i+1 is a goto/branch target, then we should not merge the two Drops */
!targets.contains(i+1)) {
code[i] = mk_drop_instr(code[i].get_num() + code[i+1].get_num());
del_instr_at(i+1, code);
}
}
}
/**
\brief Applies the following transformation
pc_1 : goto pc_2
...
pc_2 : ret
===>
pc_1 : ret
...
pc_2 : ret */
static void compress_goto_ret(buffer<vm_instr> & code) {
unsigned i = code.size();
while (i > 0) {
--i;
if (code[i].op() == opcode::Goto) {
unsigned pc = code[i].get_goto_pc();
if (code[pc].op() == opcode::Ret) {
code[i] = mk_ret_instr();
}
}
}
}
void optimize(environment const &, buffer<vm_instr> & code) {
compress_goto_ret(code);
compress_drop_drop(code);
}
}
<|endoftext|> |
<commit_before>#define CDM_CONFIGURE_NAMESPACE a0038876
#include "../../cdm/application/using_boost/cdm.hpp"
#include "log.hpp"
#include "boost_root.hpp"
#include <boost/test/unit_test.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <silicium/file_operations.hpp>
#ifdef _WIN32
#include <shlobj.h>
#endif
namespace
{
Si::absolute_path const this_file = *Si::absolute_path::create(__FILE__);
Si::absolute_path const test = *Si::parent(this_file);
Si::absolute_path const repository = *Si::parent(test);
#ifdef _WIN32
struct CoTaskMemFreeDeleter
{
void operator()(void *memory) const
{
CoTaskMemFree(memory);
}
};
Si::absolute_path get_home()
{
PWSTR path;
HRESULT rc = SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, NULL, &path);
if (rc != S_OK)
{
throw std::runtime_error("Could not get home");
}
std::unique_ptr<wchar_t, CoTaskMemFreeDeleter> raii_path(path);
return Si::absolute_path::create(raii_path.get()).or_throw([] { throw std::runtime_error("Windows returned a non-absolute path for home"); });
}
#endif
}
BOOST_AUTO_TEST_CASE(test_using_boost)
{
Si::absolute_path const app_source = repository / Si::relative_path("application/using_boost");
Si::absolute_path const tmp = Si::temporary_directory(Si::throw_) / *Si::path_segment::create("cdm_b");
Si::absolute_path const module_temporaries = tmp / *Si::path_segment::create("build");
Si::absolute_path const module_permanent =
#ifdef _WIN32
get_home() / Si::relative_path(".cdm_cache")
#else
tmp / *Si::path_segment::create("perm")
#endif
;
Si::absolute_path const application_build_dir = tmp / *Si::path_segment::create("app_build");
Si::recreate_directories(module_temporaries, Si::throw_);
Si::recreate_directories(module_permanent, Si::throw_);
Si::recreate_directories(application_build_dir, Si::throw_);
auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(std::cerr));
CDM_CONFIGURE_NAMESPACE::configure(module_temporaries, module_permanent, app_source, application_build_dir, cdm::get_boost_root_for_testing(), output);
{
std::vector<Si::os_string> arguments;
arguments.push_back(SILICIUM_SYSTEM_LITERAL("--build"));
arguments.push_back(SILICIUM_SYSTEM_LITERAL("."));
BOOST_REQUIRE_EQUAL(0, Si::run_process(Si::cmake_exe, arguments, application_build_dir, output));
}
{
std::vector<Si::os_string> arguments;
Si::relative_path const relative(
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL("Debug/")
#endif
SILICIUM_SYSTEM_LITERAL("using_boost")
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL(".exe")
#endif
);
BOOST_REQUIRE_EQUAL(0, Si::run_process(application_build_dir / relative, arguments, application_build_dir, output));
}
}
<commit_msg>do not delete the permanent cache<commit_after>#define CDM_CONFIGURE_NAMESPACE a0038876
#include "../../cdm/application/using_boost/cdm.hpp"
#include "log.hpp"
#include "boost_root.hpp"
#include <boost/test/unit_test.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <silicium/file_operations.hpp>
#ifdef _WIN32
#include <shlobj.h>
#endif
namespace
{
Si::absolute_path const this_file = *Si::absolute_path::create(__FILE__);
Si::absolute_path const test = *Si::parent(this_file);
Si::absolute_path const repository = *Si::parent(test);
#ifdef _WIN32
struct CoTaskMemFreeDeleter
{
void operator()(void *memory) const
{
CoTaskMemFree(memory);
}
};
Si::absolute_path get_home()
{
PWSTR path;
HRESULT rc = SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, NULL, &path);
if (rc != S_OK)
{
throw std::runtime_error("Could not get home");
}
std::unique_ptr<wchar_t, CoTaskMemFreeDeleter> raii_path(path);
return Si::absolute_path::create(raii_path.get()).or_throw([] { throw std::runtime_error("Windows returned a non-absolute path for home"); });
}
#endif
}
BOOST_AUTO_TEST_CASE(test_using_boost)
{
Si::absolute_path const app_source = repository / Si::relative_path("application/using_boost");
Si::absolute_path const tmp = Si::temporary_directory(Si::throw_) / *Si::path_segment::create("cdm_b");
Si::recreate_directories(tmp, Si::throw_);
Si::absolute_path const module_temporaries = tmp / *Si::path_segment::create("build");
Si::create_directories(module_temporaries, Si::throw_);
Si::absolute_path const module_permanent =
#ifdef _WIN32
get_home() / Si::relative_path(".cdm_cache")
#else
tmp / *Si::path_segment::create("perm")
#endif
;
Si::absolute_path const application_build_dir = tmp / *Si::path_segment::create("app_build");
Si::create_directories(application_build_dir, Si::throw_);
auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(std::cerr));
CDM_CONFIGURE_NAMESPACE::configure(module_temporaries, module_permanent, app_source, application_build_dir, cdm::get_boost_root_for_testing(), output);
{
std::vector<Si::os_string> arguments;
arguments.push_back(SILICIUM_SYSTEM_LITERAL("--build"));
arguments.push_back(SILICIUM_SYSTEM_LITERAL("."));
BOOST_REQUIRE_EQUAL(0, Si::run_process(Si::cmake_exe, arguments, application_build_dir, output));
}
{
std::vector<Si::os_string> arguments;
Si::relative_path const relative(
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL("Debug/")
#endif
SILICIUM_SYSTEM_LITERAL("using_boost")
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL(".exe")
#endif
);
BOOST_REQUIRE_EQUAL(0, Si::run_process(application_build_dir / relative, arguments, application_build_dir, output));
}
}
<|endoftext|> |
<commit_before>#include <Halide.h>
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
Var x, y;
{
// Define a reduction with two update steps
Func f;
f(x) = sin(x);
RDom r1(1, 10);
Expr xl = r1; // left to right pass
Expr xr = 10 - r1; // right to left pass
f(xl) = f(xl - 1) + f(xl);
f(xr) = f(xr + 1) + f(xr);
Image<float> result = f.realize(11);
// The same thing in C
float ref[11];
for (int i = 0; i < 11; i++) {
ref[i] = sinf(i);
}
for (int i = 1; i < 11; i++) {
ref[i] += ref[i-1];
}
for (int i = 10; i >= 0; i--) {
ref[i] += ref[i+1];
}
for (int i = 0; i < 11; i++) {
if (fabs(result(i) - ref[i]) > 0.0001f) {
printf("result(%d) = %f instead of %f\n",
i, result(i), ref[i]);
return -1;
}
}
}
{
// Define a reduction that fills an array, integrates it, then
// manually change certain values. One of the values will
// depend on another function.
Func f, g;
g(x) = x*x;
f(x) = x;
// Integrate from 1 to 10
RDom r(1, 10);
f(r) = f(r) + f(r-1);
// Clobber two values
f(17) = 8;
f(109) = 4;
// Clobber a range using another func
RDom r2(4, 5);
f(r2) = g(r2);
g.compute_at(f, r2);
Image<int> result = f.realize(110);
int correct[110];
for (int i = 0; i < 110; i++) {
correct[i] = i;
}
for (int i = 1; i < 11; i++) {
correct[i] += correct[i-1];
}
correct[17] = 8;
correct[109] = 4;
for (int i = 4; i < 9; i++) {
correct[i] = i*i;
}
for (int i = 0; i < 110; i++) {
if (correct[i] != result(i)) {
printf("result(%d) = %d instead of %d\n",
i, result(i), correct[i]);
return -1;
}
}
}
{
// Create a fully unrolled fibonacci routine composed almost
// entirely of single assignment statements. The horror!
Func f;
f(x) = 1;
for (int i = 2; i < 20; i++) {
f(i) = f(i-1) + f(i-2);
}
Image<int> result = f.realize(20);
int ref[20];
ref[0] = 1;
ref[1] = 1;
for (int i = 2; i < 20; i++) {
ref[i] = ref[i-1] + ref[i-2];
if (ref[i] != result(i)) {
printf("fibonacci(%d) = %d instead of %d\n",
i, result(i), ref[i]);
return -1;
}
}
}
{
// Make an integral image
Func f;
f(x, y) = sin(x + y);
RDom r(1, 99);
f(x, r) += f(x, r - 1);
f(r, y) += f(r - 1, y);
// Walk down the image in vectors
f.update(0).vectorize(x, 4);
// Walk across the image in parallel. We need to do an unsafe
// reorder operation here to move y to the outer loop, because
// we don't have the ability to reorder vars with rvars yet.
f.update(1).reorder(Var(r.x.name()), y).parallel(y);
Image<float> result = f.realize(100, 100);
// Now the equivalent in C (cheating and using Halide for the initial image)
Image<float> ref = lambda(x, y, sin(x+y)).realize(100, 100);
for (int y = 1; y < 100; y++) {
for (int x = 0; x < 100; x++) {
ref(x, y) += ref(x, y - 1);
}
}
for (int y = 0; y < 100; y++) {
for (int x = 1; x < 100; x++) {
ref(x, y) += ref(x - 1, y);
}
}
// Check they're the same
for (int y = 0; y < 100; y++) {
for (int x = 0; x < 100; x++) {
if (fabs(ref(x, y) - result(x, y)) > 0.0001f) {
printf("integral image at (%d, %d) = %f instead of %f\n",
x, y, result(x, y), ref(x, y));
return -1;
}
}
}
}
{
// Walk down an image using a few different factors of splits
Func f;
RDom r(1, 99);
Var xo, xi;
ImageParam input(Float(32), 2);
f(x, y) = input(x, y);
f(x, r) += f(x, r-1);
f(x, r) += f(x, r-1);
f(x, r) += f(x, r-1);
f(x, r) += f(x, r-1);
f.update(0).split(x, x, xi, 8);
f.update(1).split(x, x, xi, 12);
f.update(2).split(x, x, xi, 18);
// The minimum realization factor is now 72 (the least common
// multiple of the split factors). So if we ask for an output
// of size 100x10, we'll need an input of size 144 x 100. 144
// being the smallest multiple of 72 larger than 100.
f.infer_input_bounds(100, 10);
Image<float> in = input.get();
if (in.width() != 144 || in.height() != 100) {
printf("Unexpected image size: %d x %d instead of 144 x 100\n",
in.width(), in.height());
return -1;
}
}
printf("Success!\n");
return 0;
}
<commit_msg>Bugfix in C reference code for a test<commit_after>#include <Halide.h>
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
Var x, y;
{
// Define a reduction with two update steps
Func f;
f(x) = sin(x);
RDom r1(1, 10);
Expr xl = r1; // left to right pass
Expr xr = 10 - r1; // right to left pass
f(xl) = f(xl - 1) + f(xl);
f(xr) = f(xr + 1) + f(xr);
Image<float> result = f.realize(11);
// The same thing in C
float ref[11];
for (int i = 0; i < 11; i++) {
ref[i] = sinf(i);
}
for (int i = 1; i < 11; i++) {
ref[i] += ref[i-1];
}
for (int i = 9; i >= 0; i--) {
ref[i] += ref[i+1];
}
for (int i = 0; i < 11; i++) {
if (fabs(result(i) - ref[i]) > 0.0001f) {
printf("result(%d) = %f instead of %f\n",
i, result(i), ref[i]);
return -1;
}
}
}
{
// Define a reduction that fills an array, integrates it, then
// manually change certain values. One of the values will
// depend on another function.
Func f, g;
g(x) = x*x;
f(x) = x;
// Integrate from 1 to 10
RDom r(1, 10);
f(r) = f(r) + f(r-1);
// Clobber two values
f(17) = 8;
f(109) = 4;
// Clobber a range using another func
RDom r2(4, 5);
f(r2) = g(r2);
g.compute_at(f, r2);
Image<int> result = f.realize(110);
int correct[110];
for (int i = 0; i < 110; i++) {
correct[i] = i;
}
for (int i = 1; i < 11; i++) {
correct[i] += correct[i-1];
}
correct[17] = 8;
correct[109] = 4;
for (int i = 4; i < 9; i++) {
correct[i] = i*i;
}
for (int i = 0; i < 110; i++) {
if (correct[i] != result(i)) {
printf("result(%d) = %d instead of %d\n",
i, result(i), correct[i]);
return -1;
}
}
}
{
// Create a fully unrolled fibonacci routine composed almost
// entirely of single assignment statements. The horror!
Func f;
f(x) = 1;
for (int i = 2; i < 20; i++) {
f(i) = f(i-1) + f(i-2);
}
Image<int> result = f.realize(20);
int ref[20];
ref[0] = 1;
ref[1] = 1;
for (int i = 2; i < 20; i++) {
ref[i] = ref[i-1] + ref[i-2];
if (ref[i] != result(i)) {
printf("fibonacci(%d) = %d instead of %d\n",
i, result(i), ref[i]);
return -1;
}
}
}
{
// Make an integral image
Func f;
f(x, y) = sin(x + y);
RDom r(1, 99);
f(x, r) += f(x, r - 1);
f(r, y) += f(r - 1, y);
// Walk down the image in vectors
f.update(0).vectorize(x, 4);
// Walk across the image in parallel. We need to do an unsafe
// reorder operation here to move y to the outer loop, because
// we don't have the ability to reorder vars with rvars yet.
f.update(1).reorder(Var(r.x.name()), y).parallel(y);
Image<float> result = f.realize(100, 100);
// Now the equivalent in C (cheating and using Halide for the initial image)
Image<float> ref = lambda(x, y, sin(x+y)).realize(100, 100);
for (int y = 1; y < 100; y++) {
for (int x = 0; x < 100; x++) {
ref(x, y) += ref(x, y - 1);
}
}
for (int y = 0; y < 100; y++) {
for (int x = 1; x < 100; x++) {
ref(x, y) += ref(x - 1, y);
}
}
// Check they're the same
for (int y = 0; y < 100; y++) {
for (int x = 0; x < 100; x++) {
if (fabs(ref(x, y) - result(x, y)) > 0.0001f) {
printf("integral image at (%d, %d) = %f instead of %f\n",
x, y, result(x, y), ref(x, y));
return -1;
}
}
}
}
{
// Walk down an image using a few different factors of splits
Func f;
RDom r(1, 99);
Var xo, xi;
ImageParam input(Float(32), 2);
f(x, y) = input(x, y);
f(x, r) += f(x, r-1);
f(x, r) += f(x, r-1);
f(x, r) += f(x, r-1);
f(x, r) += f(x, r-1);
f.update(0).split(x, x, xi, 8);
f.update(1).split(x, x, xi, 12);
f.update(2).split(x, x, xi, 18);
// The minimum realization factor is now 72 (the least common
// multiple of the split factors). So if we ask for an output
// of size 100x10, we'll need an input of size 144 x 100. 144
// being the smallest multiple of 72 larger than 100.
f.infer_input_bounds(100, 10);
Image<float> in = input.get();
if (in.width() != 144 || in.height() != 100) {
printf("Unexpected image size: %d x %d instead of 144 x 100\n",
in.width(), in.height());
return -1;
}
}
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* 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 <iostream>
#include <votca/tools/application.h>
#include <votca/tools/version.h>
#include <votca/tools/globals.h>
#include <votca/tools/propertyiomanipulator.h>
#include <boost/format.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
namespace votca { namespace tools {
using namespace std;
Application::Application()
: _op_desc("Allowed options"), _continue_execution(true)
{
}
Application::~Application()
{
}
string Application::VersionString()
{
return "";
}
void Application::ShowHelpText(std::ostream &out)
{
out << "==================================================\n";
out << "======== VOTCA (http://www.votca.org) ========\n";
out << "==================================================\n\n";
out << "please submit bugs to [email protected]\n\n";
out << ProgramName();
if(VersionString() != "")
out << ", version " << VersionString();
out << endl
<< "votca_tools, version " << ToolsVersionStr()
<< "\n\n";
HelpText(out);
// remove Hidden group from the option list and print
out << "\n\n" << VisibleOptions() << endl;
//out << "\n\n" << OptionsDesc() << endl;
}
void Application::ShowManPage(std::ostream &out) {
out << boost::format(globals::man::header) % ProgramName() % VersionString();
out << boost::format(globals::man::name) % ProgramName() % globals::url;
out << boost::format(globals::man::synopsis) % ProgramName();
std::stringstream ss;
HelpText(ss);
out << boost::format(globals::man::description) % ss.str();
out << boost::format(globals::man::options);
typedef std::vector<boost::shared_ptr<boost::program_options::option_description> >::const_iterator OptionsIterator;
OptionsIterator it = _op_desc.options().begin(), it_end = _op_desc.options().end();
while(it < it_end) {
string format_name = (*it)->format_name() + " " + (*it)->format_parameter();
boost::replace_all(format_name, "-", "\\-");
out << boost::format(globals::man::option) % format_name % (*it)->description();
++it;
}
out << boost::format(globals::man::authors) % globals::email;
out << boost::format(globals::man::copyright) % globals::url;
}
void Application::ShowTEXPage(std::ostream &out) {
string program_name = ProgramName();
boost::replace_all(program_name, "_", "\\_");
out << boost::format(globals::tex::section) % program_name;
out << boost::format(globals::tex::label) % ProgramName();
std::stringstream ss, os;
HelpText(ss);
out << boost::format(globals::tex::description) % ss.str();
typedef std::vector<boost::shared_ptr<boost::program_options::option_description> >::const_iterator OptionsIterator;
OptionsIterator it = _op_desc.options().begin(), it_end = _op_desc.options().end();
while(it < it_end) {
string format_name = (*it)->format_name() + " " + (*it)->format_parameter();
boost::replace_all(format_name, "-", "{-}");
os << boost::format(globals::tex::option) % format_name % (*it)->description();
++it;
}
out << boost::format(globals::tex::options) % os.str();
}
int Application::Exec(int argc, char **argv)
{
try {
//_continue_execution = true;
AddProgramOptions()("help,h", " display this help and exit");
AddProgramOptions()("verbose,v", " be loud and noisy");
AddProgramOptions("Hidden")("man", " output man-formatted manual pages");
AddProgramOptions("Hidden")("tex", " output tex-formatted manual pages");
Initialize(); // initialize program-specific parameters
ParseCommandLine(argc, argv); // initialize general parameters & read input file
if (_op_vm.count("verbose")) {
globals::verbose = true;
}
if (_op_vm.count("man")) {
ShowManPage(cout);
return 0;
}
if (_op_vm.count("tex")) {
ShowTEXPage(cout);
return 0;
}
if (_op_vm.count("help")) {
ShowHelpText(cout);
return 0;
}
if(!EvaluateOptions()) {
ShowHelpText(cout);
return -1;
}
if(_continue_execution)
Run();
else cout << "nothing to be done - stopping here\n";
}
catch(std::exception &error) {
cerr << "an error occurred:\n" << error.what() << endl;
return -1;
}
return 0;
}
boost::program_options::options_description_easy_init
Application::AddProgramOptions(const string &group)
{
// if no group is given, add it to standard options
if(group == "")
return _op_desc.add_options();
// does group already exist, if yes, add it there
std::map<string, boost::program_options::options_description>::iterator iter;
iter = _op_groups.find(group);
if(iter!=_op_groups.end())
return iter->second.add_options();
// no group with given name was found -> create group
_op_groups.insert(make_pair(group, boost::program_options::options_description(group)));
return _op_groups[group].add_options();
}
void Application::ParseCommandLine(int argc, char **argv)
{
namespace po = boost::program_options;
std::map<string, boost::program_options::options_description>::iterator iter;
// default options should be added to visible (the rest is handled via a map))
_visible_options.add(_op_desc);
// add all categories to list of available options
for(iter=_op_groups.begin(); iter!=_op_groups.end(); ++iter) {
_op_desc.add(iter->second);
if ( iter->first != "Hidden" ) _visible_options.add(iter->second);
}
// parse the command line
try {
po::store(po::parse_command_line(argc, argv, _op_desc), _op_vm);
po::notify(_op_vm);
}
catch(boost::program_options::error& err) {
throw runtime_error(string("error parsing command line: ") + err.what());
}
}
void Application::CheckRequired(const string &option_name, const string &error_msg)
{
if(!_op_vm.count(option_name)) {
ShowHelpText(cout);
throw std::runtime_error("missing argument " + option_name + "\n" + error_msg);
}
}
void Application::PrintDescription(std::ostream &out, const string &calculator_name, const string help_path, HelpType help_type )
{
boost::format _format("%|3t|%1% %|20t|%2% \n");
string help_string;
boost::filesystem::path arg_path;
Property options;
string xmlFile = (arg_path / string(getenv("VOTCASHARE")) / help_path / (boost::format("%1%.%2%") % calculator_name % "xml").str()).string().c_str();
// loading the documentation xml file from VOTCASHARE
char *votca_share = getenv("VOTCASHARE");
if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files.");
try {
load_property_from_xml(options, xmlFile);
Property &calculator_options = options.get("options." + calculator_name);
Property::AttributeIterator atr_it = calculator_options.findAttribute("help");
if (atr_it != calculator_options.lastAttribute()) {
help_string = (*atr_it).second;
} else {
if (tools::globals::verbose) out << _format % calculator_name % "Undocumented";
return;
}
switch (help_type) {
default:
break;
case HelpShort: // short description of the calculator
out << _format % calculator_name % help_string;
break;
case HelpLong:
votca::tools::PropertyIOManipulator iom(votca::tools::PropertyIOManipulator::HLP, 2, "");
out << iom << options;
break;
}
} catch (std::exception &error) {
if (tools::globals::verbose) out << _format % calculator_name % "Undocumented";
}
}
}}
<commit_msg>put test earlier<commit_after>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* 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 <iostream>
#include <votca/tools/application.h>
#include <votca/tools/version.h>
#include <votca/tools/globals.h>
#include <votca/tools/propertyiomanipulator.h>
#include <boost/format.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
namespace votca { namespace tools {
using namespace std;
Application::Application()
: _op_desc("Allowed options"), _continue_execution(true)
{
}
Application::~Application()
{
}
string Application::VersionString()
{
return "";
}
void Application::ShowHelpText(std::ostream &out)
{
out << "==================================================\n";
out << "======== VOTCA (http://www.votca.org) ========\n";
out << "==================================================\n\n";
out << "please submit bugs to [email protected]\n\n";
out << ProgramName();
if(VersionString() != "")
out << ", version " << VersionString();
out << endl
<< "votca_tools, version " << ToolsVersionStr()
<< "\n\n";
HelpText(out);
// remove Hidden group from the option list and print
out << "\n\n" << VisibleOptions() << endl;
//out << "\n\n" << OptionsDesc() << endl;
}
void Application::ShowManPage(std::ostream &out) {
out << boost::format(globals::man::header) % ProgramName() % VersionString();
out << boost::format(globals::man::name) % ProgramName() % globals::url;
out << boost::format(globals::man::synopsis) % ProgramName();
std::stringstream ss;
HelpText(ss);
out << boost::format(globals::man::description) % ss.str();
out << boost::format(globals::man::options);
typedef std::vector<boost::shared_ptr<boost::program_options::option_description> >::const_iterator OptionsIterator;
OptionsIterator it = _op_desc.options().begin(), it_end = _op_desc.options().end();
while(it < it_end) {
string format_name = (*it)->format_name() + " " + (*it)->format_parameter();
boost::replace_all(format_name, "-", "\\-");
out << boost::format(globals::man::option) % format_name % (*it)->description();
++it;
}
out << boost::format(globals::man::authors) % globals::email;
out << boost::format(globals::man::copyright) % globals::url;
}
void Application::ShowTEXPage(std::ostream &out) {
string program_name = ProgramName();
boost::replace_all(program_name, "_", "\\_");
out << boost::format(globals::tex::section) % program_name;
out << boost::format(globals::tex::label) % ProgramName();
std::stringstream ss, os;
HelpText(ss);
out << boost::format(globals::tex::description) % ss.str();
typedef std::vector<boost::shared_ptr<boost::program_options::option_description> >::const_iterator OptionsIterator;
OptionsIterator it = _op_desc.options().begin(), it_end = _op_desc.options().end();
while(it < it_end) {
string format_name = (*it)->format_name() + " " + (*it)->format_parameter();
boost::replace_all(format_name, "-", "{-}");
os << boost::format(globals::tex::option) % format_name % (*it)->description();
++it;
}
out << boost::format(globals::tex::options) % os.str();
}
int Application::Exec(int argc, char **argv)
{
try {
//_continue_execution = true;
AddProgramOptions()("help,h", " display this help and exit");
AddProgramOptions()("verbose,v", " be loud and noisy");
AddProgramOptions("Hidden")("man", " output man-formatted manual pages");
AddProgramOptions("Hidden")("tex", " output tex-formatted manual pages");
Initialize(); // initialize program-specific parameters
ParseCommandLine(argc, argv); // initialize general parameters & read input file
if (_op_vm.count("verbose")) {
globals::verbose = true;
}
if (_op_vm.count("man")) {
ShowManPage(cout);
return 0;
}
if (_op_vm.count("tex")) {
ShowTEXPage(cout);
return 0;
}
if (_op_vm.count("help")) {
ShowHelpText(cout);
return 0;
}
if(!EvaluateOptions()) {
ShowHelpText(cout);
return -1;
}
if(_continue_execution)
Run();
else cout << "nothing to be done - stopping here\n";
}
catch(std::exception &error) {
cerr << "an error occurred:\n" << error.what() << endl;
return -1;
}
return 0;
}
boost::program_options::options_description_easy_init
Application::AddProgramOptions(const string &group)
{
// if no group is given, add it to standard options
if(group == "")
return _op_desc.add_options();
// does group already exist, if yes, add it there
std::map<string, boost::program_options::options_description>::iterator iter;
iter = _op_groups.find(group);
if(iter!=_op_groups.end())
return iter->second.add_options();
// no group with given name was found -> create group
_op_groups.insert(make_pair(group, boost::program_options::options_description(group)));
return _op_groups[group].add_options();
}
void Application::ParseCommandLine(int argc, char **argv)
{
namespace po = boost::program_options;
std::map<string, boost::program_options::options_description>::iterator iter;
// default options should be added to visible (the rest is handled via a map))
_visible_options.add(_op_desc);
// add all categories to list of available options
for(iter=_op_groups.begin(); iter!=_op_groups.end(); ++iter) {
_op_desc.add(iter->second);
if ( iter->first != "Hidden" ) _visible_options.add(iter->second);
}
// parse the command line
try {
po::store(po::parse_command_line(argc, argv, _op_desc), _op_vm);
po::notify(_op_vm);
}
catch(boost::program_options::error& err) {
throw runtime_error(string("error parsing command line: ") + err.what());
}
}
void Application::CheckRequired(const string &option_name, const string &error_msg)
{
if(!_op_vm.count(option_name)) {
ShowHelpText(cout);
throw std::runtime_error("missing argument " + option_name + "\n" + error_msg);
}
}
void Application::PrintDescription(std::ostream &out, const string &calculator_name, const string help_path, HelpType help_type )
{
boost::format _format("%|3t|%1% %|20t|%2% \n");
string help_string;
boost::filesystem::path arg_path;
Property options;
// loading the documentation xml file from VOTCASHARE
char *votca_share = getenv("VOTCASHARE");
if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files.");
string xmlFile = (arg_path / string(getenv("VOTCASHARE")) / help_path / (boost::format("%1%.%2%") % calculator_name % "xml").str()).string().c_str();
try {
load_property_from_xml(options, xmlFile);
Property &calculator_options = options.get("options." + calculator_name);
Property::AttributeIterator atr_it = calculator_options.findAttribute("help");
if (atr_it != calculator_options.lastAttribute()) {
help_string = (*atr_it).second;
} else {
if (tools::globals::verbose) out << _format % calculator_name % "Undocumented";
return;
}
switch (help_type) {
default:
break;
case HelpShort: // short description of the calculator
out << _format % calculator_name % help_string;
break;
case HelpLong:
votca::tools::PropertyIOManipulator iom(votca::tools::PropertyIOManipulator::HLP, 2, "");
out << iom << options;
break;
}
} catch (std::exception &error) {
if (tools::globals::verbose) out << _format % calculator_name % "Undocumented";
}
}
}}
<|endoftext|> |
<commit_before>//
// ParametricLink.cpp
// NetworkSimulator
//
// Created by Tommi Gröhn on 18.11.2015.
// Copyright (c) 2015 tommigrohn. All rights reserved.
//
#include <sstream>
#include "ParametricLink.h"
ParametricLink::ParametricLink() {
previousTime = 0.0;
packetToTransitTime = 0.0;
logging = true;
}
ParametricLink::ParametricLink(double transmissionSpeed, double propagationDelay) {
this->transmissionSpeed = transmissionSpeed; // interval
this->propagationDelay = propagationDelay; // transmission time per packet
previousTime = 0.0;
packetToTransitTime = 0.0;
logging = true;
}
void ParametricLink::run(double currentTime) {
double timeDelta = currentTime - previousTime;
previousTime = currentTime;
std::stringstream ss;
// waiting time until next packet will be picked for transmission
if (!packetsWaiting.empty()) packetToTransitTime -= timeDelta;
// add packets to transmission if there is some waiting...
if (packetToTransitTime <= 0.0 && !packetsWaiting.empty()) {
// debug output
std::cout << "Added to transmission..." << std::endl;
auto it = packetsWaiting.begin();
// packet size determines total duration of transmission
packetsInTransmission.insert({*it, propagationDelay});
packetsWaiting.erase(it);
// reset waiting time (proportional to the size of added packet)
packetToTransitTime = transmissionSpeed * (*it)->getSize();
}
// handle packets being transmitted
for (auto it = packetsInTransmission.begin(); it != packetsInTransmission.end();) {
it->second -= timeDelta;
// if transmission time has passed...
if (it->second <= 0.0) {
// deliver it to destination node
destination->receivePacket(it->first);
// add packet to transmission log {packetId, deliveryTime}
if (logging) transmittedPackets.push_back({it->first->getID(), currentTime});
// debug output
std::cout
<< "Parametric link "
<< source->getAddress() << "-"
<< destination->getAddress() << " forwarded "
<< it->first->getData() << " to node "
<< destination->getAddress() << std::endl;
it = packetsInTransmission.erase(it);
} else {
// debugging helper stringstream, format [packetData, timeToDelivery]
ss << "[" << it->first->getData() << ", " << it->second << "]";
it++;
}
}
// debug output
if (!packetsInTransmission.empty()) {
std::cout
<< ss.str()
<< " in transmission on parametric link "
<< source->getAddress() << "-"
<< destination->getAddress()
<< std::endl;
}
}
<commit_msg>Fixed packet transmission time calculation<commit_after>//
// ParametricLink.cpp
// NetworkSimulator
//
// Created by Tommi Gröhn on 18.11.2015.
// Copyright (c) 2015 tommigrohn. All rights reserved.
//
#include <sstream>
#include "ParametricLink.h"
ParametricLink::ParametricLink() {
previousTime = 0.0;
packetToTransitTime = 0.0;
logging = true;
}
ParametricLink::ParametricLink(double transmissionSpeed, double propagationDelay) {
this->transmissionSpeed = transmissionSpeed; // interval
this->propagationDelay = propagationDelay; // transmission time per packet
previousTime = 0.0;
packetToTransitTime = 0.0;
logging = true;
}
void ParametricLink::run(double currentTime) {
double timeDelta = currentTime - previousTime;
previousTime = currentTime;
std::stringstream ss;
// waiting time until next packet will be picked for transmission
if (!packetsWaiting.empty()) packetToTransitTime -= timeDelta;
// add packets to transmission if there is some waiting...
if (packetToTransitTime <= 0.0 && !packetsWaiting.empty()) {
// debug output
std::cout << "Added to transmission..." << std::endl;
auto it = packetsWaiting.begin();
// packet size determines total duration of transmission
packetsInTransmission.insert({*it, propagationDelay});
packetsWaiting.erase(it);
// reset waiting time (proportional to the size of added packet)
// "time to transmit a packet == packet size / link speed"
packetToTransitTime = (*it)->getSize() / transmissionSpeed;
}
// handle packets being transmitted
for (auto it = packetsInTransmission.begin(); it != packetsInTransmission.end();) {
it->second -= timeDelta;
// if transmission time has passed...
if (it->second <= 0.0) {
// deliver it to destination node
destination->receivePacket(it->first);
// add packet to transmission log {packetId, deliveryTime}
if (logging) transmittedPackets.push_back({it->first->getID(), currentTime});
// debug output
std::cout
<< "Parametric link "
<< source->getAddress() << "-"
<< destination->getAddress() << " forwarded "
<< it->first->getData() << " to node "
<< destination->getAddress() << std::endl;
it = packetsInTransmission.erase(it);
} else {
// debugging helper stringstream, format [packetData, timeToDelivery]
ss << "[" << it->first->getData() << ", " << it->second << "]";
it++;
}
}
// debug output
if (!packetsInTransmission.empty()) {
std::cout
<< ss.str()
<< " in transmission on parametric link "
<< source->getAddress() << "-"
<< destination->getAddress()
<< std::endl;
}
}
<|endoftext|> |
<commit_before>#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
// system
#include <sstream>
// boost
#include <boost/filesystem.hpp>
// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>
// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>
// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/model/thermalblock.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/finitevolume/dune-pdelab.hh>
#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif
const std::string id = "stationary.linear.elliptic.fv.dp";
/**
\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 ensureParamFile(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 << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
file << "[stuff.grid.provider.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 = 4" << std::endl;
file << "filename = " << id << ".grid" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
file << "diffusion.order = 0" << std::endl;
file << "diffusion.variable = x" << std::endl;
file << "diffusion.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "force.order = 0" << std::endl;
file << "force.variable = x" << std::endl;
file << "force.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "dirichlet.order = 0" << std::endl;
file << "dirichlet.variable = x" << std::endl;
file << "dirichlet.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "neumann.order = 0" << std::endl;
file << "neumann.variable = x" << std::endl;
file << "neumann.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.model.thermalblock]" << std::endl;
file << "diffusion.order = 0" << std::endl;
file << "diffusion.lowerLeft = [0.0; 0.0; 0.0]" << std::endl; // should coincide with the grid
file << "diffusion.upperRight = [1.0; 1.0; 1.0]" << std::endl; // should coincide with the grid
file << "diffusion.numElements = [2; 2; 2]" << std::endl;
file << "diffusion.components = [1.0; 10.0; 3.0; 2.1]" << std::endl;
file << "force.order = 0" << std::endl;
file << "force.variable = x" << std::endl;
file << "force.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "dirichlet.order = 0" << std::endl;
file << "dirichlet.variable = x" << std::endl;
file << "dirichlet.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "neumann.order = 0" << std::endl;
file << "neumann.variable = x" << std::endl;
file << "neumann.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.finitevolume.dune-pdelab]" << std::endl;
file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
file << "solve.maxIter = 5000" << std::endl;
file << "solve.precision = 1e-12" << std::endl;
file << "visualize.filename = " << id << ".solution" << std::endl;
file << "visualize.name = solution" << std::endl;
file.close();
} // only write param file if there is none
} // void ensureParamFile()
template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
Dune::shared_ptr< Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > >
createModel(const Dune::Stuff::Common::ExtendedParameterTree& paramTree)
{
// prepare
paramTree.assertKey(id + ".model");
const std::string modelId = paramTree.sub(id).get("model", "default_value");
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelInterfaceType;
// choose model
if (modelId == "detailed.solvers.stationary.linear.elliptic.model.default") {
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
paramTree.assertSub(ModelType::id(), id);
Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
return model;
} else if (modelId == "detailed.solvers.stationary.linear.elliptic.model.thermalblock") {
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
paramTree.assertSub(ModelType::id(), id);
Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
return model;
} else {
std::stringstream msg;
msg << std::endl << "Error in " << id << ": unknown model ('" << modelId << "') given in the following Dune::Parametertree" << std::endl;
paramTree.report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
} // choose model
} // ... createModel(...)
int main(int argc, char** argv)
{
try {
// mpi
Dune::MPIHelper::instance(argc, argv);
// parameter
const std::string filename = id + ".param";
ensureParamFile(filename);
Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);
// logger
Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
Dune::Stuff::Common::LOG_CONSOLE |
Dune::Stuff::Common::LOG_DEBUG);
Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();
// timer
Dune::Timer timer;
// grid
info << "setting up grid: " << std::endl;
debug.suspend();
typedef Dune::Stuff::Grid::Provider::Cube<> GridProviderType;
paramTree.assertSub(GridProviderType::id(), id);
const GridProviderType gridProvider(paramTree.sub(GridProviderType::id()));
typedef GridProviderType::GridType GridType;
const GridType& grid = gridProvider.grid();
typedef GridType::LeafGridView GridViewType;
const Dune::shared_ptr< const GridViewType > gridView(new GridViewType(grid.leafView()));
info << " done (took " << timer.elapsed()
<< " sec, has " << grid.size(0) << " element";
if (grid.size(0) > 1)
info << "s";
info << ")" << std::endl;
info << "visualizing grid... " << std::flush;
timer.reset();
gridProvider.visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_grid"));
info << " done (took " << timer.elapsed() << " sek)" << std::endl;
debug.resume();
// model
info << "setting up model... " << std::flush;
timer.reset();
const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
const unsigned int DUNE_UNUSED(dimRange) = 1;
typedef GridProviderType::CoordinateType::value_type DomainFieldType;
typedef DomainFieldType RangeFieldType;
paramTree.assertSub(id, id);
typedef Dune::Detailed::Solvers
::Stationary
::Linear
::Elliptic
::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
const Dune::shared_ptr< const ModelType >
model = createModel< DomainFieldType, dimDomain, RangeFieldType, dimRange >(paramTree);
typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// solver
info << "initializing solver:" << std::endl;
typedef Dune::Detailed::Solvers
::Stationary
::Linear
::Elliptic
::FiniteVolume::DunePdelab< ModelType, GridViewType, BoundaryInfoType, polOrder > SolverType;
paramTree.assertSub(SolverType::id(), id);
SolverType solver(model, gridView, boundaryInfo);
solver.init(" ", debug);
info << "solving:" << std::endl;
typedef SolverType::TrialVectorType SolutionType;
typedef Dune::shared_ptr<SolutionType> solution_ptr;
solution_ptr solution = solution_ptr(new SolutionType(*(solver.gridFunctionSpace()),0.0));
// evtl. dieses Anlegen des Vektors in eine Methode createVector() auslagern (die in DunePdelab liegt)?!
// solution_ptr solution = solver.createVector();
solver.solve(*solution, paramTree.sub(SolverType::id()).sub("solve"), " ", debug);
info << "postprocessing:" << std::endl;
solver.visualize(*solution,
paramTree.sub(SolverType::id()).sub("visualize").get("filename", id + "_solution"),
paramTree.sub(SolverType::id()).sub("visualize").get("name", "solution"),
" ",
debug);
// if we came that far we can as well be happy about it
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>added mixed boundary types (should be cleaned up)<commit_after>#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
// system
#include <sstream>
// boost
#include <boost/filesystem.hpp>
// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>
// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>
// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/model/thermalblock.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/finitevolume/dune-pdelab.hh>
#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif
const std::string id = "stationary.linear.elliptic.fv.dp";
/**
\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 ensureParamFile(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 << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
file << "[stuff.grid.provider.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 = 4" << std::endl;
file << "filename = " << id << ".grid" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
file << "diffusion.order = 0" << std::endl;
file << "diffusion.variable = x" << std::endl;
file << "diffusion.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "force.order = 0" << std::endl;
file << "force.variable = x" << std::endl;
file << "force.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "dirichlet.order = 0" << std::endl;
file << "dirichlet.variable = x" << std::endl;
file << "dirichlet.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "neumann.order = 0" << std::endl;
file << "neumann.variable = x" << std::endl;
file << "neumann.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.model.thermalblock]" << std::endl;
file << "diffusion.order = 0" << std::endl;
file << "diffusion.lowerLeft = [0.0; 0.0; 0.0]" << std::endl; // should coincide with the grid
file << "diffusion.upperRight = [1.0; 1.0; 1.0]" << std::endl; // should coincide with the grid
file << "diffusion.numElements = [2; 2; 2]" << std::endl;
file << "diffusion.components = [1.0; 10.0; 3.0; 2.1]" << std::endl;
file << "force.order = 0" << std::endl;
file << "force.variable = x" << std::endl;
file << "force.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "dirichlet.order = 0" << std::endl;
file << "dirichlet.variable = x" << std::endl;
file << "dirichlet.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "neumann.order = 0" << std::endl;
file << "neumann.variable = x" << std::endl;
file << "neumann.expression = [1.0; 1.0; 1.0]" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.finitevolume.dune-pdelab]" << std::endl;
file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
file << "solve.maxIter = 5000" << std::endl;
file << "solve.precision = 1e-12" << std::endl;
file << "visualize.filename = " << id << ".solution" << std::endl;
file << "visualize.name = solution" << std::endl;
file.close();
} // only write param file if there is none
} // void ensureParamFile()
template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
Dune::shared_ptr< Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > >
createModel(const Dune::Stuff::Common::ExtendedParameterTree& paramTree)
{
// prepare
paramTree.assertKey(id + ".model");
const std::string modelId = paramTree.sub(id).get("model", "default_value");
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelInterfaceType;
// choose model
if (modelId == "detailed.solvers.stationary.linear.elliptic.model.default") {
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
paramTree.assertSub(ModelType::id(), id);
Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
return model;
} else if (modelId == "detailed.solvers.stationary.linear.elliptic.model.thermalblock") {
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
paramTree.assertSub(ModelType::id(), id);
Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
return model;
} else {
std::stringstream msg;
msg << std::endl << "Error in " << id << ": unknown model ('" << modelId << "') given in the following Dune::Parametertree" << std::endl;
paramTree.report(msg);
DUNE_THROW(Dune::InvalidStateException, msg.str());
} // choose model
} // ... createModel(...)
int main(int argc, char** argv)
{
try {
// mpi
Dune::MPIHelper::instance(argc, argv);
// parameter
const std::string filename = id + ".param";
ensureParamFile(filename);
Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);
// logger
Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
Dune::Stuff::Common::LOG_CONSOLE |
Dune::Stuff::Common::LOG_DEBUG);
Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();
// timer
Dune::Timer timer;
// grid
info << "setting up grid: " << std::endl;
debug.suspend();
typedef Dune::Stuff::Grid::Provider::Cube<> GridProviderType;
paramTree.assertSub(GridProviderType::id(), id);
const GridProviderType gridProvider(paramTree.sub(GridProviderType::id()));
typedef GridProviderType::GridType GridType;
const GridType& grid = gridProvider.grid();
typedef GridType::LeafGridView GridViewType;
const Dune::shared_ptr< const GridViewType > gridView(new GridViewType(grid.leafView()));
info << " done (took " << timer.elapsed()
<< " sec, has " << grid.size(0) << " element";
if (grid.size(0) > 1)
info << "s";
info << ")" << std::endl;
info << "visualizing grid... " << std::flush;
timer.reset();
gridProvider.visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_grid"));
info << " done (took " << timer.elapsed() << " sek)" << std::endl;
debug.resume();
// model
info << "setting up model... " << std::flush;
timer.reset();
const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
const unsigned int DUNE_UNUSED(dimRange) = 1;
typedef GridProviderType::CoordinateType::value_type DomainFieldType;
typedef DomainFieldType RangeFieldType;
paramTree.assertSub(id, id);
typedef Dune::Detailed::Solvers
::Stationary
::Linear
::Elliptic
::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
const Dune::shared_ptr< const ModelType >
model = createModel< DomainFieldType, dimDomain, RangeFieldType, dimRange >(paramTree);
typedef Dune::Stuff::Grid::BoundaryInfo::IdBased BoundaryInfoType;
typedef typename BoundaryInfoType::IdSetType IdSetType;
typedef typename BoundaryInfoType::IdSetMapType IdSetMapType;
Dune::shared_ptr< IdSetMapType > boundaryIdSetMap(new IdSetMapType());
IdSetType dirichletSet;
dirichletSet.insert(1);
IdSetType neumannSet;
neumannSet.insert(2);
neumannSet.insert(3);
neumannSet.insert(4);
boundaryIdSetMap->insert(std::pair< std::string, IdSetType >("dirichlet", dirichletSet));
boundaryIdSetMap->insert(std::pair< std::string, IdSetType >("neumann", neumannSet));
const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType(boundaryIdSetMap));
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// solver
info << "initializing solver:" << std::endl;
typedef Dune::Detailed::Solvers
::Stationary
::Linear
::Elliptic
::FiniteVolume::DunePdelab< ModelType, GridViewType, BoundaryInfoType, polOrder > SolverType;
paramTree.assertSub(SolverType::id(), id);
SolverType solver(model, gridView, boundaryInfo);
solver.init(" ", debug);
info << "solving:" << std::endl;
typedef SolverType::TrialVectorType SolutionType;
typedef Dune::shared_ptr<SolutionType> solution_ptr;
solution_ptr solution = solution_ptr(new SolutionType(*(solver.gridFunctionSpace()),0.0));
// evtl. dieses Anlegen des Vektors in eine Methode createVector() auslagern (die in DunePdelab liegt)?!
// solution_ptr solution = solver.createVector();
solver.solve(*solution, paramTree.sub(SolverType::id()).sub("solve"), " ", debug);
info << "postprocessing:" << std::endl;
solver.visualize(*solution,
paramTree.sub(SolverType::id()).sub("visualize").get("filename", id + "_solution"),
paramTree.sub(SolverType::id()).sub("visualize").get("name", "solution"),
" ",
debug);
// if we came that far we can as well be happy about it
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>/* Copyright (c) 2020 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 "paddle/fluid/framework/ir/mkldnn/scale_matmul_fuse_pass.h"
#include <string>
#include <vector>
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/string/pretty_log.h"
namespace paddle {
namespace framework {
namespace ir {
class Graph;
using string::PrettyLogDetail;
ScaleMatmulFusePass::ScaleMatmulFusePass() {
AddOpCompat(OpCompat("matmul"))
.AddInput("X")
.IsTensor()
.End()
.AddInput("Y")
.IsTensor()
.End()
.AddOutput("Out")
.IsTensor()
.End()
.AddAttr("alpha")
.IsNumGT(0.0f)
.End()
.AddAttr("transpose_X")
.IsType<bool>()
.End()
.AddAttr("transpose_Y")
.IsType<bool>()
.End();
AddOpCompat(OpCompat("scale"))
.AddInput("X")
.IsTensor()
.End()
.AddOutput("Out")
.IsTensor()
.End()
.AddAttr("scale")
.IsNumGT(0.0f)
.End()
.AddAttr("bias")
.IsNumEQ(0.0f)
.End()
.AddAttr("bias_after_scale")
.IsOptional()
.IsType<bool>()
.End();
}
void ScaleMatmulFusePass::ApplyImpl(ir::Graph* graph) const {
PADDLE_ENFORCE_NOT_NULL(graph,
platform::errors::InvalidArgument(
"Pointer to graph argument should not be NULL."));
FusePassBase::Init("scale_matmul_fuse_pass", graph);
GraphPatternDetector gpd;
patterns::ScaleMatmul scale_matmul_pattern{gpd.mutable_pattern(),
"scale_matmul"};
scale_matmul_pattern();
int found_scale_matmul_fuse_count = 0;
auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
Graph* g) {
if (!IsCompat(subgraph, g)) {
LOG(WARNING) << "Pass in op compat failed.";
return;
}
GET_IR_NODE_FROM_SUBGRAPH(scale_in, scale_in, scale_matmul_pattern);
GET_IR_NODE_FROM_SUBGRAPH(scale_op, scale_op, scale_matmul_pattern);
GET_IR_NODE_FROM_SUBGRAPH(scale_out, scale_out, scale_matmul_pattern);
GET_IR_NODE_FROM_SUBGRAPH(matmul_op, matmul_op, scale_matmul_pattern);
if (scale_op->Op()->GetAttrIfExists<float>("bias") == 0.0) {
auto matmul_alpha = matmul_op->Op()->GetAttrIfExists<float>("alpha");
auto scale_scale = scale_op->Op()->GetAttrIfExists<float>("scale");
PADDLE_ENFORCE_GT(
matmul_alpha, 0.0f,
platform::errors::InvalidArgument(
"Alpha(%f) of matmul op should have positive value.",
matmul_alpha));
PADDLE_ENFORCE_GT(scale_scale, 0.0f,
platform::errors::InvalidArgument(
"Scale(%f) of scale op should have positive value.",
scale_scale));
std::string matmul_op_input_name;
for (auto name : matmul_op->Op()->InputNames())
for (auto input_name : matmul_op->Op()->Input(name))
if (input_name == scale_out->Name()) matmul_op_input_name = name;
PADDLE_ENFORCE_NE(
matmul_op_input_name.empty(), true,
platform::errors::NotFound("Operator after scale operator(%s) "
"should have scale output as input.",
scale_out->Name()));
matmul_op->Op()->SetAttr("alpha", matmul_alpha * scale_scale);
matmul_op->Op()->SetInput(matmul_op_input_name,
std::vector<std::string>({scale_in->Name()}));
IR_NODE_LINK_TO(scale_in, matmul_op);
if (!IsCompat(*matmul_op->Op())) {
LOG(WARNING) << "scale_matmul_fuse_pass in out fc op compat failed.";
return;
}
GraphSafeRemoveNodes(graph, {scale_op, scale_out});
found_scale_matmul_fuse_count++;
}
};
gpd(graph, handler);
AddStatis(found_scale_matmul_fuse_count);
if (!Has("disable_logs") || !Get<bool>("disable_logs"))
PrettyLogDetail("--- fused %d scale with matmul",
found_scale_matmul_fuse_count);
}
} // namespace ir
} // namespace framework
} // namespace paddle
REGISTER_PASS(scale_matmul_fuse_pass,
paddle::framework::ir::ScaleMatmulFusePass);
REGISTER_PASS_CAPABILITY(scale_matmul_fuse_pass)
.AddCombination(
paddle::framework::compatible::OpVersionComparatorCombination()
.EQ("scale", 0)
.LE("matmul", 1));
<commit_msg>fix scale_matmul fuse pass (#43089)<commit_after>/* Copyright (c) 2020 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 "paddle/fluid/framework/ir/mkldnn/scale_matmul_fuse_pass.h"
#include <string>
#include <vector>
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/string/pretty_log.h"
namespace paddle {
namespace framework {
namespace ir {
class Graph;
using string::PrettyLogDetail;
ScaleMatmulFusePass::ScaleMatmulFusePass() {
AddOpCompat(OpCompat("matmul"))
.AddInput("X")
.IsTensor()
.End()
.AddInput("Y")
.IsTensor()
.End()
.AddOutput("Out")
.IsTensor()
.End()
.AddAttr("alpha")
.IsNumGT(0.0f)
.End()
.AddAttr("transpose_X")
.IsType<bool>()
.End()
.AddAttr("transpose_Y")
.IsType<bool>()
.End();
AddOpCompat(OpCompat("scale"))
.AddInput("X")
.IsTensor()
.End()
.AddOutput("Out")
.IsTensor()
.End()
.AddAttr("scale")
.IsNumGT(0.0f)
.End()
.AddAttr("bias")
.IsNumEQ(0.0f)
.End()
.AddAttr("bias_after_scale")
.IsOptional()
.IsType<bool>()
.End();
}
void ScaleMatmulFusePass::ApplyImpl(ir::Graph* graph) const {
PADDLE_ENFORCE_NOT_NULL(graph,
platform::errors::InvalidArgument(
"Pointer to graph argument should not be NULL."));
FusePassBase::Init("scale_matmul_fuse_pass", graph);
GraphPatternDetector gpd;
patterns::ScaleMatmul scale_matmul_pattern{gpd.mutable_pattern(),
"scale_matmul"};
scale_matmul_pattern();
int found_scale_matmul_fuse_count = 0;
auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
Graph* g) {
if (!IsCompat(subgraph, g)) {
LOG(WARNING) << "Pass in op compat failed.";
return;
}
GET_IR_NODE_FROM_SUBGRAPH(scale_in, scale_in, scale_matmul_pattern);
GET_IR_NODE_FROM_SUBGRAPH(scale_op, scale_op, scale_matmul_pattern);
GET_IR_NODE_FROM_SUBGRAPH(scale_out, scale_out, scale_matmul_pattern);
GET_IR_NODE_FROM_SUBGRAPH(matmul_op, matmul_op, scale_matmul_pattern);
if ((scale_out->outputs).size() != 1) {
return;
}
if (scale_op->Op()->GetAttrIfExists<float>("bias") == 0.0) {
auto matmul_alpha = matmul_op->Op()->GetAttrIfExists<float>("alpha");
auto scale_scale = scale_op->Op()->GetAttrIfExists<float>("scale");
PADDLE_ENFORCE_GT(
matmul_alpha, 0.0f,
platform::errors::InvalidArgument(
"Alpha(%f) of matmul op should have positive value.",
matmul_alpha));
PADDLE_ENFORCE_GT(scale_scale, 0.0f,
platform::errors::InvalidArgument(
"Scale(%f) of scale op should have positive value.",
scale_scale));
std::string matmul_op_input_name;
for (auto name : matmul_op->Op()->InputNames())
for (auto input_name : matmul_op->Op()->Input(name))
if (input_name == scale_out->Name()) matmul_op_input_name = name;
PADDLE_ENFORCE_NE(
matmul_op_input_name.empty(), true,
platform::errors::NotFound("Operator after scale operator(%s) "
"should have scale output as input.",
scale_out->Name()));
matmul_op->Op()->SetAttr("alpha", matmul_alpha * scale_scale);
matmul_op->Op()->SetInput(matmul_op_input_name,
std::vector<std::string>({scale_in->Name()}));
IR_NODE_LINK_TO(scale_in, matmul_op);
if (!IsCompat(*matmul_op->Op())) {
LOG(WARNING) << "scale_matmul_fuse_pass in out fc op compat failed.";
return;
}
GraphSafeRemoveNodes(graph, {scale_op, scale_out});
found_scale_matmul_fuse_count++;
}
};
gpd(graph, handler);
AddStatis(found_scale_matmul_fuse_count);
if (!Has("disable_logs") || !Get<bool>("disable_logs"))
PrettyLogDetail("--- fused %d scale with matmul",
found_scale_matmul_fuse_count);
}
} // namespace ir
} // namespace framework
} // namespace paddle
REGISTER_PASS(scale_matmul_fuse_pass,
paddle::framework::ir::ScaleMatmulFusePass);
REGISTER_PASS_CAPABILITY(scale_matmul_fuse_pass)
.AddCombination(
paddle::framework::compatible::OpVersionComparatorCombination()
.EQ("scale", 0)
.LE("matmul", 1));
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qtlocalpeer.h"
#include <QCoreApplication>
#include <QTime>
#if defined(Q_OS_WIN)
#include <QLibrary>
#include <qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif
#if defined(Q_OS_UNIX)
#include <time.h>
#include <unistd.h>
#endif
namespace SharedTools {
static const char ack[] = "ack";
QString QtLocalPeer::appSessionId(const QString &appId)
{
QByteArray idc = appId.toUtf8();
quint16 idNum = qChecksum(idc.constData(), idc.size());
//### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqeness probability. Every-other-char split would be best.
QString res = QLatin1String("qtsingleapplication-")
+ QString::number(idNum, 16);
#if defined(Q_OS_WIN)
if (!pProcessIdToSessionId) {
QLibrary lib(QLatin1String("kernel32"));
pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
}
if (pProcessIdToSessionId) {
DWORD sessionId = 0;
pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
res += QLatin1Char('-') + QString::number(sessionId, 16);
}
#else
res += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
return res;
}
QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
: QObject(parent), id(appId)
{
if (id.isEmpty())
id = QCoreApplication::applicationFilePath(); //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win
socketName = appSessionId(id);
server = new QLocalServer(this);
QString lockName = QDir(QDir::tempPath()).absolutePath()
+ QLatin1Char('/') + socketName
+ QLatin1String("-lockfile");
lockFile.setFileName(lockName);
lockFile.open(QIODevice::ReadWrite);
}
bool QtLocalPeer::isClient()
{
if (lockFile.isLocked())
return false;
if (!lockFile.lock(QtLockedFile::WriteLock, false))
return true;
if (!QLocalServer::removeServer(socketName))
qWarning("QtSingleCoreApplication: could not cleanup socket");
bool res = server->listen(socketName);
if (!res)
qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
return false;
}
bool QtLocalPeer::sendMessage(const QString &message, int timeout, bool block)
{
if (!isClient())
return false;
QLocalSocket socket;
bool connOk = false;
for (int i = 0; i < 2; i++) {
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2);
if (connOk || i)
break;
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
if (!connOk)
return false;
QByteArray uMsg(message.toUtf8());
QDataStream ds(&socket);
ds.writeBytes(uMsg.constData(), uMsg.size());
bool res = socket.waitForBytesWritten(timeout);
res &= socket.waitForReadyRead(timeout); // wait for ack
res &= (socket.read(qstrlen(ack)) == ack);
if (block) // block until peer disconnects
socket.waitForDisconnected(-1);
return res;
}
void QtLocalPeer::receiveConnection()
{
QLocalSocket* socket = server->nextPendingConnection();
if (!socket)
return;
// Why doesn't Qt have a blocking stream that takes care of this shait???
while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {
if (!socket->isValid()) // stale request
return;
socket->waitForReadyRead(1000);
}
QDataStream ds(socket);
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
uMsg.resize(remaining);
int got = 0;
char* uMsgBuf = uMsg.data();
//qDebug() << "RCV: remaining" << remaining;
do {
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
//qDebug() << "RCV: got" << got << "remaining" << remaining;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000));
//### error check: got<0
if (got < 0) {
qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
delete socket;
return;
}
// ### async this
QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
socket->write(ack, qstrlen(ack));
socket->waitForBytesWritten(1000);
emit messageReceived(message, socket); // ##(might take a long time to return)
}
} // namespace SharedTools
<commit_msg>bugfix for compiler error on ubuntu 16.04. - QDataStream<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qtlocalpeer.h"
#include <QCoreApplication>
#include <QTime>
#if defined(Q_OS_WIN)
#include <QLibrary>
#include <qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif
#if defined(Q_OS_UNIX)
#include <time.h>
#include <unistd.h>
#endif
// @FIXME: bugfix for strange new compiler error on ubuntu 16.04 = ‘QDataStream ds’ has initializer but incomplete type
// not sure if that collides on other systems:
#include <QDataStream>
namespace SharedTools {
static const char ack[] = "ack";
QString QtLocalPeer::appSessionId(const QString &appId)
{
QByteArray idc = appId.toUtf8();
quint16 idNum = qChecksum(idc.constData(), idc.size());
//### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqeness probability. Every-other-char split would be best.
QString res = QLatin1String("qtsingleapplication-")
+ QString::number(idNum, 16);
#if defined(Q_OS_WIN)
if (!pProcessIdToSessionId) {
QLibrary lib(QLatin1String("kernel32"));
pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
}
if (pProcessIdToSessionId) {
DWORD sessionId = 0;
pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
res += QLatin1Char('-') + QString::number(sessionId, 16);
}
#else
res += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
return res;
}
QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
: QObject(parent), id(appId)
{
if (id.isEmpty())
id = QCoreApplication::applicationFilePath(); //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win
socketName = appSessionId(id);
server = new QLocalServer(this);
QString lockName = QDir(QDir::tempPath()).absolutePath()
+ QLatin1Char('/') + socketName
+ QLatin1String("-lockfile");
lockFile.setFileName(lockName);
lockFile.open(QIODevice::ReadWrite);
}
bool QtLocalPeer::isClient()
{
if (lockFile.isLocked())
return false;
if (!lockFile.lock(QtLockedFile::WriteLock, false))
return true;
if (!QLocalServer::removeServer(socketName))
qWarning("QtSingleCoreApplication: could not cleanup socket");
bool res = server->listen(socketName);
if (!res)
qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
return false;
}
bool QtLocalPeer::sendMessage(const QString &message, int timeout, bool block)
{
if (!isClient())
return false;
QLocalSocket socket;
bool connOk = false;
for (int i = 0; i < 2; i++) {
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2);
if (connOk || i)
break;
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
if (!connOk)
return false;
QByteArray uMsg(message.toUtf8());
QDataStream ds(&socket);
ds.writeBytes(uMsg.constData(), uMsg.size());
bool res = socket.waitForBytesWritten(timeout);
res &= socket.waitForReadyRead(timeout); // wait for ack
res &= (socket.read(qstrlen(ack)) == ack);
if (block) // block until peer disconnects
socket.waitForDisconnected(-1);
return res;
}
void QtLocalPeer::receiveConnection()
{
QLocalSocket* socket = server->nextPendingConnection();
if (!socket)
return;
// Why doesn't Qt have a blocking stream that takes care of this shait???
while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {
if (!socket->isValid()) // stale request
return;
socket->waitForReadyRead(1000);
}
QDataStream ds(socket);
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
uMsg.resize(remaining);
int got = 0;
char* uMsgBuf = uMsg.data();
//qDebug() << "RCV: remaining" << remaining;
do {
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
//qDebug() << "RCV: got" << got << "remaining" << remaining;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000));
//### error check: got<0
if (got < 0) {
qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
delete socket;
return;
}
// ### async this
QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
socket->write(ack, qstrlen(ack));
socket->waitForBytesWritten(1000);
emit messageReceived(message, socket); // ##(might take a long time to return)
}
} // namespace SharedTools
<|endoftext|> |
<commit_before>#include <sstream>
#include <string>
#include <tuple>
#include <optional>
#include <functional>
#include <unordered_map>
#include "tuple_iterate.h"
#include "dataconsts.h"
#include "entity_system.h"
#include "chat/whisper_chat.h"
#include "components/client.h"
namespace {
template <typename... Args>
class Parser {
public:
Parser(std::stringstream&& ss) {
size_t index = 0;
Core::for_each(args, [&ss, &index, this](auto& data) {
is_arg_ok[index++] = parse(ss, data);
});
}
bool is_good() const {
return std::all_of(is_arg_ok.cbegin(), is_arg_ok.cend(), [](bool i) {
return i;
});
}
bool is_arg_good(size_t index) const {
return is_arg_ok[index];
}
template <size_t N>
decltype(auto) get_arg() {
return std::get<N>(args);
}
private:
std::array<bool, sizeof...(Args)> is_arg_ok;
std::tuple<Args...> args;
template <typename T>
static bool parse(std::stringstream& ss, T& h) {
return static_cast<bool>(ss >> h);
}
template <typename T>
static bool parse(std::stringstream& ss, std::optional<T>& h) {
T tmp;
const bool has_data = static_cast<bool>(ss >> tmp);
if (has_data) {
h = tmp;
}
return true;
}
};
template <>
class Parser<> {
public:
Parser(std::stringstream&&) {}
bool is_good() const {
return true;
}
};
void item(EntitySystem&, RoseCommon::Entity, Parser<int, int>) {
}
void teleport(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<int, int, int, std::optional<uint16_t>> parser) {
if (!parser.is_good()) {
Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage /tp <map_id> <x> <y> [client_id]");
return;
}
entitySystem.teleport_entity(entity, parser.get_arg<1>() * 100, parser.get_arg<2>() * 100, parser.get_arg<0>());
}
void zuly(EntitySystem&, RoseCommon::Entity, Parser<int>) {
}
}
#define REGISTER_FUNCTION(f) [](EntitySystem& en, RoseCommon::Entity e, std::stringstream&& ss) { f(en, e, {std::move(ss)}); }
void help(EntitySystem&, RoseCommon::Entity, Parser<std::optional<std::string>>);
static const std::unordered_map<std::string, std::tuple<uint16_t, std::function<void(EntitySystem&, RoseCommon::Entity, std::stringstream&&)>, std::string>> commands = {
{"/help", {1, REGISTER_FUNCTION(help), "Prints this help. Usage: /help [command]"}},
//{"/item", {100, REGISTER_FUNCTION(item), "Creates an item. Usage: /item <type> <id>"}},
//{"/zuly", {100, REGISTER_FUNCTION(zuly), "Adds zulies to your inventory (you can add a negative amount). Usage: /zuly <amount>"}},
{"/tp", {200, REGISTER_FUNCTION(teleport), "Teleports a player or self. usage: /tp <map_id> <x> <y> [client_id]"}}
};
static const std::unordered_map<std::string, std::string> aliases = {
{"/halp", "/help"},
{"/teleport", "/tp"}
};
void help(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<std::optional<std::string>> parser) {
if (!parser.is_good()) {
Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage: /help [command]");
return;
}
Chat::send_whisper(entitySystem, entity, "help (<required args> [optional args]):");
if (!parser.get_arg<0>()) {
for (const auto& command : commands) {
Chat::send_whisper(entitySystem, entity, std::get<2>(command.second));
}
} else {
if (const auto it = commands.find(parser.get_arg<0>().value()); it != commands.end()) {
Chat::send_whisper(entitySystem, entity, std::get<2>(it->second));
} else {
Chat::send_whisper(entitySystem, entity, fmt::format("Error, no command {} found.", parser.get_arg<0>().value()));
}
}
}
void execute_gm(EntitySystem& entitySystem, RoseCommon::Entity entity, const std::string& message) {
const uint16_t access_level = entitySystem.get_component<Component::Client>(entity).access_level;
std::stringstream ss(message);
std::string command;
ss >> command;
if (const auto it = aliases.find(command); it != aliases.cend()) {
command = it->second;
}
if (const auto it = commands.find(command); it != commands.end() && access_level >= std::get<0>(it->second)) {
std::get<1>(it->second)(entitySystem, entity, std::move(ss));
} else {
Chat::send_whisper(entitySystem, entity, "Error, no known command/not enough permissions");
}
}
<commit_msg>Update gm_commands.cpp<commit_after>#include <sstream>
#include <string>
#include <tuple>
#include <optional>
#include <functional>
#include <unordered_map>
#include "tuple_iterate.h"
#include "dataconsts.h"
#include "entity_system.h"
#include "chat/whisper_chat.h"
#include "components/client.h"
namespace {
template <typename... Args>
class Parser {
public:
Parser(std::stringstream&& ss) {
size_t index = 0;
Core::for_each(args, [&ss, &index, this](auto& data) {
is_arg_ok[index++] = parse(ss, data);
});
}
bool is_good() const {
return std::all_of(is_arg_ok.cbegin(), is_arg_ok.cend(), [](bool i) {
return i;
});
}
bool is_arg_good(size_t index) const {
return is_arg_ok[index];
}
template <size_t N>
decltype(auto) get_arg() {
return std::get<N>(args);
}
private:
std::array<bool, sizeof...(Args)> is_arg_ok;
std::tuple<Args...> args;
template <typename T>
static bool parse(std::stringstream& ss, T& h) {
return static_cast<bool>(ss >> h);
}
template <typename T>
static bool parse(std::stringstream& ss, std::optional<T>& h) {
T tmp;
const bool has_data = static_cast<bool>(ss >> tmp);
if (has_data) {
h = tmp;
}
return true;
}
};
template <>
class Parser<> {
public:
Parser(std::stringstream&&) {}
bool is_good() const {
return true;
}
};
[[maybe_unused]] void item(EntitySystem&, RoseCommon::Entity, Parser<int, int>) {
}
void teleport(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<int, int, int, std::optional<uint16_t>> parser) {
if (!parser.is_good()) {
Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage /tp <map_id> <x> <y> [client_id]");
return;
}
entitySystem.teleport_entity(entity, parser.get_arg<1>() * 100, parser.get_arg<2>() * 100, parser.get_arg<0>());
}
[[maybe_unused]] void zuly(EntitySystem&, RoseCommon::Entity, Parser<int>) {
}
}
#define REGISTER_FUNCTION(f) [](EntitySystem& en, RoseCommon::Entity e, std::stringstream&& ss) { f(en, e, {std::move(ss)}); }
void help(EntitySystem&, RoseCommon::Entity, Parser<std::optional<std::string>>);
static const std::unordered_map<std::string, std::tuple<uint16_t, std::function<void(EntitySystem&, RoseCommon::Entity, std::stringstream&&)>, std::string>> commands = {
{"/help", {1, REGISTER_FUNCTION(help), "Prints this help. Usage: /help [command]"}},
//{"/item", {100, REGISTER_FUNCTION(item), "Creates an item. Usage: /item <type> <id>"}},
//{"/zuly", {100, REGISTER_FUNCTION(zuly), "Adds zulies to your inventory (you can add a negative amount). Usage: /zuly <amount>"}},
{"/tp", {200, REGISTER_FUNCTION(teleport), "Teleports a player or self. usage: /tp <map_id> <x> <y> [client_id]"}}
};
static const std::unordered_map<std::string, std::string> aliases = {
{"/halp", "/help"},
{"/teleport", "/tp"}
};
void help(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<std::optional<std::string>> parser) {
if (!parser.is_good()) {
Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage: /help [command]");
return;
}
Chat::send_whisper(entitySystem, entity, "help (<required args> [optional args]):");
if (!parser.get_arg<0>()) {
for (const auto& command : commands) {
Chat::send_whisper(entitySystem, entity, std::get<2>(command.second));
}
} else {
if (const auto it = commands.find(parser.get_arg<0>().value()); it != commands.end()) {
Chat::send_whisper(entitySystem, entity, std::get<2>(it->second));
} else {
Chat::send_whisper(entitySystem, entity, fmt::format("Error, no command {} found.", parser.get_arg<0>().value()));
}
}
}
void execute_gm(EntitySystem& entitySystem, RoseCommon::Entity entity, const std::string& message) {
const uint16_t access_level = entitySystem.get_component<Component::Client>(entity).access_level;
std::stringstream ss(message);
std::string command;
ss >> command;
if (const auto it = aliases.find(command); it != aliases.cend()) {
command = it->second;
}
if (const auto it = commands.find(command); it != commands.end() && access_level >= std::get<0>(it->second)) {
std::get<1>(it->second)(entitySystem, entity, std::move(ss));
} else {
Chat::send_whisper(entitySystem, entity, "Error, no known command/not enough permissions");
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "XalanDiagnosticMemoryManager.hpp"
#if !defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream>
#endif
#include <ctype.h>
#include "xercesc/util/PlatformUtils.hpp"
XALAN_CPP_NAMESPACE_BEGIN
XalanDiagnosticMemoryManager::XalanDiagnosticMemoryManager(
MemoryManager& theMemoryManager,
bool fAssertErrors,
StreamType* theStream) :
m_memoryManager(theMemoryManager),
m_assertErrors(fAssertErrors),
m_locked(false),
m_sequence(0),
m_highWaterMark(0),
m_currentAllocated(0),
m_allocations(theMemoryManager),
m_stream(theStream)
{
}
XalanDiagnosticMemoryManager::~XalanDiagnosticMemoryManager()
{
if (m_allocations.size() > 0 && m_stream != 0)
{
*m_stream << "Detected memory leaks. "
<< m_allocations.size()
<< " blocks are still allocated.\n";
}
}
void*
XalanDiagnosticMemoryManager::allocate(size_type size)
{
void* theResult = 0;
if (m_locked == true)
{
if (m_stream != 0)
{
*m_stream << "Attempt to allocate "
<< size
<< " bytes from locked instance "
<< this
<< ".\n";
dumpStatistics(m_stream);
}
throw LockException();
}
else
{
theResult =
m_memoryManager.allocate(size);
assert(theResult != 0);
assert(m_allocations.find(theResult) == m_allocations.end());
m_currentAllocated += size;
if (m_currentAllocated > m_highWaterMark)
{
m_highWaterMark = m_currentAllocated;
}
m_allocations.insert(MapType::value_type(theResult, Data(size, m_sequence++)));
}
return theResult;
}
void
XalanDiagnosticMemoryManager::deallocate(void* pointer)
{
if (m_locked == true)
{
if (m_stream != 0)
{
*m_stream << "Attempt to deallocate address "
<< pointer
<< " with locked instance "
<< this
<< ".\n";
}
throw LockException();
}
else
{
if (pointer != 0)
{
MapType::iterator i =
m_allocations.find(pointer);
if (i != m_allocations.end())
{
m_memoryManager.deallocate(pointer);
assert(m_currentAllocated >= i->second.m_size);
m_currentAllocated -= i->second.m_size;
m_allocations.erase(i);
}
else
{
if (m_stream != 0)
{
*m_stream << "Attempt to free unallocated address "
<< pointer
<< " with instance "
<< this
<< ".\n";
}
assert(!m_assertErrors);
}
}
}
}
void
XalanDiagnosticMemoryManager::dumpStatistics(
StreamType* theStream,
size_type theBytesToDump)
{
StreamType* const diagStream = theStream != 0 ? theStream : m_stream;
if (diagStream != 0)
{
*diagStream << "Total number of allocations: "
<< m_sequence
<< ".\n"
<< "Total current allocations: "
<< m_allocations.size()
<< ".\n"
<< "Total bytes currently allocated: "
<< m_currentAllocated
<< ".\n"
<< "Peak bytes allocated: "
<< m_highWaterMark
<< ".\n";
for(const_iterator i = m_allocations.begin();
i != m_allocations.end();
++i)
{
const void* const thePointer = i->first;
const Data& theData = i->second;
XALAN_USING_STD(dec);
*diagStream << "Block at address "
<< thePointer
<< " with sequence "
<< dec
<< theData.m_sequence
<< " is "
<< theData.m_size
<< " bytes long.\n";
XALAN_USING_XERCES(XMLPlatformUtils);
const size_type theHeaderSize =
XMLPlatformUtils::alignPointerForNewBlockAllocation(sizeof(MemoryManager*));
const char* const theChars =
reinterpret_cast<const char*>(thePointer) +
theHeaderSize;
const unsigned char* const theUChars =
reinterpret_cast<const unsigned char*>(theChars);
if (theBytesToDump != 0)
{
XALAN_USING_STD(hex);
const size_type theCount =
theBytesToDump > theData.m_size ?
theData.m_size :
theBytesToDump;
{
*diagStream << "(";
for (size_t j = 0; j < theCount; ++j)
{
const char ch = isprint(theChars[j]) ?
theChars[j] :
' ';
*diagStream << ch;
}
*diagStream << ") ";
}
if (theCount < theBytesToDump)
{
for (size_t j = theCount; j < theBytesToDump; ++j)
{
*diagStream << ' ';
}
}
{
*diagStream << hex;
for (size_t j = 0; j < theCount; ++j)
{
*diagStream << unsigned(theUChars[j])
<< " ";
}
}
*diagStream << "\n";
}
}
}
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Don't dump statistics when reporting an allocation error with a locked instance.<commit_after>/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "XalanDiagnosticMemoryManager.hpp"
#if !defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream>
#endif
#include <ctype.h>
#include "xercesc/util/PlatformUtils.hpp"
XALAN_CPP_NAMESPACE_BEGIN
XalanDiagnosticMemoryManager::XalanDiagnosticMemoryManager(
MemoryManager& theMemoryManager,
bool fAssertErrors,
StreamType* theStream) :
m_memoryManager(theMemoryManager),
m_assertErrors(fAssertErrors),
m_locked(false),
m_sequence(0),
m_highWaterMark(0),
m_currentAllocated(0),
m_allocations(theMemoryManager),
m_stream(theStream)
{
}
XalanDiagnosticMemoryManager::~XalanDiagnosticMemoryManager()
{
if (m_allocations.size() > 0 && m_stream != 0)
{
*m_stream << "Detected memory leaks. "
<< m_allocations.size()
<< " blocks are still allocated.\n";
}
}
void*
XalanDiagnosticMemoryManager::allocate(size_type size)
{
void* theResult = 0;
if (m_locked == true)
{
if (m_stream != 0)
{
*m_stream << "Attempt to allocate "
<< size
<< " bytes from locked instance "
<< this
<< ".\n";
}
throw LockException();
}
else
{
theResult =
m_memoryManager.allocate(size);
assert(theResult != 0);
assert(m_allocations.find(theResult) == m_allocations.end());
m_currentAllocated += size;
if (m_currentAllocated > m_highWaterMark)
{
m_highWaterMark = m_currentAllocated;
}
m_allocations.insert(MapType::value_type(theResult, Data(size, m_sequence++)));
}
return theResult;
}
void
XalanDiagnosticMemoryManager::deallocate(void* pointer)
{
if (m_locked == true)
{
if (m_stream != 0)
{
*m_stream << "Attempt to deallocate address "
<< pointer
<< " with locked instance "
<< this
<< ".\n";
}
throw LockException();
}
else
{
if (pointer != 0)
{
MapType::iterator i =
m_allocations.find(pointer);
if (i != m_allocations.end())
{
m_memoryManager.deallocate(pointer);
assert(m_currentAllocated >= i->second.m_size);
m_currentAllocated -= i->second.m_size;
m_allocations.erase(i);
}
else
{
if (m_stream != 0)
{
*m_stream << "Attempt to free unallocated address "
<< pointer
<< " with instance "
<< this
<< ".\n";
}
assert(!m_assertErrors);
}
}
}
}
void
XalanDiagnosticMemoryManager::dumpStatistics(
StreamType* theStream,
size_type theBytesToDump)
{
StreamType* const diagStream = theStream != 0 ? theStream : m_stream;
if (diagStream != 0)
{
*diagStream << "Total number of allocations: "
<< m_sequence
<< ".\n"
<< "Total current allocations: "
<< m_allocations.size()
<< ".\n"
<< "Total bytes currently allocated: "
<< m_currentAllocated
<< ".\n"
<< "Peak bytes allocated: "
<< m_highWaterMark
<< ".\n";
for(const_iterator i = m_allocations.begin();
i != m_allocations.end();
++i)
{
const void* const thePointer = i->first;
const Data& theData = i->second;
XALAN_USING_STD(dec);
*diagStream << "Block at address "
<< thePointer
<< " with sequence "
<< dec
<< theData.m_sequence
<< " is "
<< theData.m_size
<< " bytes long.\n";
XALAN_USING_XERCES(XMLPlatformUtils);
const size_type theHeaderSize =
XMLPlatformUtils::alignPointerForNewBlockAllocation(sizeof(MemoryManager*));
const char* const theChars =
reinterpret_cast<const char*>(thePointer) +
theHeaderSize;
const unsigned char* const theUChars =
reinterpret_cast<const unsigned char*>(theChars);
if (theBytesToDump != 0)
{
XALAN_USING_STD(hex);
const size_type theCount =
theBytesToDump > theData.m_size ?
theData.m_size :
theBytesToDump;
{
*diagStream << "(";
for (size_t j = 0; j < theCount; ++j)
{
const char ch = isprint(theChars[j]) ?
theChars[j] :
' ';
*diagStream << ch;
}
*diagStream << ") ";
}
if (theCount < theBytesToDump)
{
for (size_t j = theCount; j < theBytesToDump; ++j)
{
*diagStream << ' ';
}
}
{
*diagStream << hex;
for (size_t j = 0; j < theCount; ++j)
{
*diagStream << unsigned(theUChars[j])
<< " ";
}
}
*diagStream << "\n";
}
}
}
}
XALAN_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include <QAudioOutput>
#include <QAudioDeviceInfo>
#include <QAudioInput>
class Window2 : public QWidget
{
Q_OBJECT
public slots:
//![0]
void stateChanged(QAudio::State newState)
{
switch(newState) {
case QAudio::StopState:
if (input->error() != QAudio::NoError) {
// Error handling
} else {
}
break;
//![0]
default:
;
}
}
private:
QAudioInput *input;
};
class Window : public QWidget
{
Q_OBJECT
public:
Window()
{
output = new QAudioOutput;
connect(output, SIGNAL(stateChanged(QAudio::State)),
this, SLOT(stateChanged(QAudio::State)));
}
private:
void setupFormat()
{
//![1]
QAudioFormat format;
format.setFrequency(44100);
//![1]
format.setChannels(2);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
//![2]
format.setSampleType(QAudioFormat::SignedInt);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if (!info.isFormatSupported(format))
format = info.nearestFormat(format);
//![2]
}
public slots:
//![3]
void stateChanged(QAudio::State newState)
{
switch (newState) {
case QAudio::StopState:
if (output->error() != QAudio::NoError) {
// Do your error handlin
} else {
// Normal stop
}
break;
//![3]
// Handle
case QAudio::ActiveState:
// Handle active state...
break;
break;
default:
;
}
}
private:
QAudioOutput *output;
};
int main(int argv, char **args)
{
QApplication app(argv, args);
Window window;
window.show();
return app.exec();
}
#include "main.moc"
<commit_msg>Doc: Fixed comments in a code snippet.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include <QAudioOutput>
#include <QAudioDeviceInfo>
#include <QAudioInput>
class Window2 : public QWidget
{
Q_OBJECT
public slots:
//![0]
void stateChanged(QAudio::State newState)
{
switch(newState) {
case QAudio::StopState:
if (input->error() != QAudio::NoError) {
// Error handling
} else {
}
break;
//![0]
default:
;
}
}
private:
QAudioInput *input;
};
class Window : public QWidget
{
Q_OBJECT
public:
Window()
{
output = new QAudioOutput;
connect(output, SIGNAL(stateChanged(QAudio::State)),
this, SLOT(stateChanged(QAudio::State)));
}
private:
void setupFormat()
{
//![1]
QAudioFormat format;
format.setFrequency(44100);
//![1]
format.setChannels(2);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
//![2]
format.setSampleType(QAudioFormat::SignedInt);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if (!info.isFormatSupported(format))
format = info.nearestFormat(format);
//![2]
}
public slots:
//![3]
void stateChanged(QAudio::State newState)
{
switch (newState) {
case QAudio::StopState:
if (output->error() != QAudio::NoError) {
// Perform error handling
} else {
// Normal stop
}
break;
//![3]
// Handle
case QAudio::ActiveState:
// Handle active state...
break;
break;
default:
;
}
}
private:
QAudioOutput *output;
};
int main(int argv, char **args)
{
QApplication app(argv, args);
Window window;
window.show();
return app.exec();
}
#include "main.moc"
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/mat/prob/bernoulli_logit_glm_lpmf.hpp>
namespace stan {
namespace math {
/**
* @deprecated use <code>bernoulli_logit_glm_lpmf</code>
*/
template <bool propto, typename T_n, typename T_x, typename T_alpha,
typename T_beta>
typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
return bernoulli_logit_glm_lpmf<propto, T_n, T_x, T_alpha, T_beta>(n, x, alpha,
beta);
}
/**
* @deprecated use <code>bernoulli_logit_glm_lpmf</code>
*/
template <typename T_n, typename T_x, typename T_alpha, typename T_beta>
inline typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
return bernoulli_logit_glm_lpmf<false>(n, x, alpha, beta);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>satisfied cpplint again<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP
#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/mat/prob/bernoulli_logit_glm_lpmf.hpp>
namespace stan {
namespace math {
/**
* @deprecated use <code>bernoulli_logit_glm_lpmf</code>
*/
template <bool propto, typename T_n, typename T_x, typename T_alpha,
typename T_beta>
typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
return bernoulli_logit_glm_lpmf<propto, T_n, T_x, T_alpha, T_beta>(n, x,
alpha,
beta);
}
/**
* @deprecated use <code>bernoulli_logit_glm_lpmf</code>
*/
template <typename T_n, typename T_x, typename T_alpha, typename T_beta>
inline typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
return bernoulli_logit_glm_lpmf<false>(n, x, alpha, beta);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: overlayanimatedbitmapex.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 13:06:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
#define _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
#ifndef _SDR_OVERLAY_OVERLAYOBJECT_HXX
#include <svx/sdr/overlay/overlayobject.hxx>
#endif
#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace overlay
{
class OverlayAnimatedBitmapEx : public OverlayObjectWithBasePosition
{
protected:
// the Bitmaps
BitmapEx maBitmapEx1;
BitmapEx maBitmapEx2;
// position of the basePosition inside the Bitmaps, in pixels
sal_uInt16 mnCenterX1;
sal_uInt16 mnCenterY1;
sal_uInt16 mnCenterX2;
sal_uInt16 mnCenterY2;
// bitfield
// Flag to remember which state to draw. Inited with sal_False (0)
unsigned mbOverlayState : 1;
// Draw geometry
virtual void drawGeometry(OutputDevice& rOutputDevice);
// Create the BaseRange. This method needs to calculate maBaseRange.
virtual void createBaseRange(OutputDevice& rOutputDevice);
public:
OverlayAnimatedBitmapEx(
const basegfx::B2DPoint& rBasePos,
const BitmapEx& rBitmapEx1, const BitmapEx& rBitmapEx2,
sal_uInt16 nCenX1 = 0, sal_uInt16 nCenY1 = 0,
sal_uInt16 nCenX2 = 0, sal_uInt16 nCenY2 = 0);
virtual ~OverlayAnimatedBitmapEx();
const BitmapEx& getBitmapEx1() const { return maBitmapEx1; }
const BitmapEx& getBitmapEx2() const { return maBitmapEx2; }
void setBitmapEx1(const BitmapEx& rNew);
void setBitmapEx2(const BitmapEx& rNew);
sal_uInt16 getCenterX1() const { return mnCenterX1; }
sal_uInt16 getCenterY1() const { return mnCenterY1; }
sal_uInt16 getCenterX2() const { return mnCenterX2; }
sal_uInt16 getCenterY2() const { return mnCenterY2; }
void setCenterXY1(sal_uInt16 nNewX, sal_uInt16 nNewY);
void setCenterXY2(sal_uInt16 nNewX, sal_uInt16 nNewY);
// execute event from base class ::sdr::animation::Event. Default
// implementation does nothing and does not create a new event.
virtual void Trigger(sal_uInt32 nTime);
// Zoom has changed. If the objects logical size
// depends on the MapMode of the used OutputDevice, use this call
// to invalidate the range in logical coordinates.
virtual void zoomHasChanged();
};
} // end of namespace overlay
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif //_SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
// eof
<commit_msg>INTEGRATION: CWS aw051 (1.2.222); FILE MERGED 2007/05/03 14:16:50 aw 1.2.222.1: #i53286# using GetCursorBlinkRate now<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: overlayanimatedbitmapex.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2007-07-18 10:51:17 $
*
* 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 _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
#define _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
#ifndef _SDR_OVERLAY_OVERLAYOBJECT_HXX
#include <svx/sdr/overlay/overlayobject.hxx>
#endif
#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace overlay
{
class OverlayAnimatedBitmapEx : public OverlayObjectWithBasePosition
{
protected:
// the Bitmaps
BitmapEx maBitmapEx1;
BitmapEx maBitmapEx2;
// position of the basePosition inside the Bitmaps, in pixels
sal_uInt16 mnCenterX1;
sal_uInt16 mnCenterY1;
sal_uInt16 mnCenterX2;
sal_uInt16 mnCenterY2;
// #i53216# added CursorBlinkTime (in ms)
sal_uInt32 mnBlinkTime;
// bitfield
// Flag to remember which state to draw. Inited with sal_False (0)
unsigned mbOverlayState : 1;
// Draw geometry
virtual void drawGeometry(OutputDevice& rOutputDevice);
// Create the BaseRange. This method needs to calculate maBaseRange.
virtual void createBaseRange(OutputDevice& rOutputDevice);
// #i53216# check blink time value range (currently 25 < mnBlinkTime < 10000)
void impCheckBlinkTimeValueRange();
public:
OverlayAnimatedBitmapEx(
const basegfx::B2DPoint& rBasePos,
const BitmapEx& rBitmapEx1,
const BitmapEx& rBitmapEx2,
sal_uInt32 nBlinkTime = 500,
sal_uInt16 nCenX1 = 0,
sal_uInt16 nCenY1 = 0,
sal_uInt16 nCenX2 = 0,
sal_uInt16 nCenY2 = 0);
virtual ~OverlayAnimatedBitmapEx();
const BitmapEx& getBitmapEx1() const { return maBitmapEx1; }
const BitmapEx& getBitmapEx2() const { return maBitmapEx2; }
void setBitmapEx1(const BitmapEx& rNew);
void setBitmapEx2(const BitmapEx& rNew);
sal_uInt16 getCenterX1() const { return mnCenterX1; }
sal_uInt16 getCenterY1() const { return mnCenterY1; }
sal_uInt16 getCenterX2() const { return mnCenterX2; }
sal_uInt16 getCenterY2() const { return mnCenterY2; }
void setCenterXY1(sal_uInt16 nNewX, sal_uInt16 nNewY);
void setCenterXY2(sal_uInt16 nNewX, sal_uInt16 nNewY);
// #i53216# added CursorBlinkTime (in ms)
sal_uInt32 getBlinkTime() const { return mnBlinkTime; }
void setBlinkTime(sal_uInt32 nNew);
// execute event from base class ::sdr::animation::Event. Default
// implementation does nothing and does not create a new event.
virtual void Trigger(sal_uInt32 nTime);
// Zoom has changed. If the objects logical size
// depends on the MapMode of the used OutputDevice, use this call
// to invalidate the range in logical coordinates.
virtual void zoomHasChanged();
};
} // end of namespace overlay
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif //_SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
// eof
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactofsdrmediaobj.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2007-01-22 15:14:39 $
*
* 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_svx.hxx"
#include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx>
#include "svdomedia.hxx"
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx>
#endif
namespace sdr { namespace contact {
// ----------------------------
// - ViewContactOfSdrMediaObj -
// ----------------------------
ViewContactOfSdrMediaObj::ViewContactOfSdrMediaObj( SdrMediaObj& rMediaObj ) :
ViewContactOfSdrObj( rMediaObj )
{
}
// ------------------------------------------------------------------------------
ViewContactOfSdrMediaObj::~ViewContactOfSdrMediaObj()
{
}
// ------------------------------------------------------------------------------
sal_Bool ViewContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC)
{
return ViewContactOfSdrObj::PaintObject( rDisplayInfo, rPaintRectangle, rAssociatedVOC );
}
// ------------------------------------------------------------------------------
ViewObjectContact& ViewContactOfSdrMediaObj::CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact)
{
return *( new ViewObjectContactOfSdrMediaObj( rObjectContact, *this, static_cast< SdrMediaObj& >( GetSdrObject() ).getMediaProperties() ) );
}
// ------------------------------------------------------------------------------
bool ViewContactOfSdrMediaObj::hasPreferredSize() const
{
// #i71805# Since we may have a whole bunch of VOCs here, make a loop
// return true if all have their preferred size
bool bRetval(true);
for(sal_uInt32 a(0L); bRetval && a < maVOCList.Count(); a++)
{
if(!static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->hasPreferredSize())
{
bRetval = false;
}
}
return bRetval;
}
// ------------------------------------------------------------------------------
Size ViewContactOfSdrMediaObj::getPreferredSize() const
{
// #i71805# Since we may have a whole bunch of VOCs here, make a loop
// return first useful size -> the size from the first which is visualized as a window
for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
{
Size aSize(static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->getPreferredSize());
if(0 != aSize.getWidth() || 0 != aSize.getHeight())
{
return aSize;
}
}
return Size();
}
// ------------------------------------------------------------------------------
void ViewContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const
{
// #i71805# Since we may have a whole bunch of VOCs here, make a loop
for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
{
static_cast< ViewObjectContactOfSdrMediaObj* >(maVOCList.GetObject(a))->updateMediaItem(rItem);
}
}
// ------------------------------------------------------------------------------
void ViewContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )
{
for( sal_uInt32 n(0L); n < maVOCList.Count(); n++ )
{
static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( n ) )->executeMediaItem( rItem );
}
}
// ------------------------------------------------------------------------------
void ViewContactOfSdrMediaObj::mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState )
{
static_cast< SdrMediaObj& >( GetSdrObject() ).mediaPropertiesChanged( rNewState );
}
// ------------------------------------------------------------------------------
// #i72701#
sal_Bool ViewContactOfSdrMediaObj::ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC)
{
// set pos/size of associated media window
const ViewObjectContactOfSdrMediaObj& rVOC(dynamic_cast< const ViewObjectContactOfSdrMediaObj& >(rAssociatedVOC));
rVOC.checkMediaWindowPosition(rDisplayInfo);
// call parent
return ViewContactOfSdrObj::ShouldPaintObject(rDisplayInfo, rAssociatedVOC);
}
// ------------------------------------------------------------------------------
}} // end of namespace sdr::contact
// eof
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.130); FILE MERGED 2007/06/04 13:27:16 vg 1.9.130.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactofsdrmediaobj.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:45:50 $
*
* 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_svx.hxx"
#include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx>
#include <svx/svdomedia.hxx>
#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx>
#endif
namespace sdr { namespace contact {
// ----------------------------
// - ViewContactOfSdrMediaObj -
// ----------------------------
ViewContactOfSdrMediaObj::ViewContactOfSdrMediaObj( SdrMediaObj& rMediaObj ) :
ViewContactOfSdrObj( rMediaObj )
{
}
// ------------------------------------------------------------------------------
ViewContactOfSdrMediaObj::~ViewContactOfSdrMediaObj()
{
}
// ------------------------------------------------------------------------------
sal_Bool ViewContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC)
{
return ViewContactOfSdrObj::PaintObject( rDisplayInfo, rPaintRectangle, rAssociatedVOC );
}
// ------------------------------------------------------------------------------
ViewObjectContact& ViewContactOfSdrMediaObj::CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact)
{
return *( new ViewObjectContactOfSdrMediaObj( rObjectContact, *this, static_cast< SdrMediaObj& >( GetSdrObject() ).getMediaProperties() ) );
}
// ------------------------------------------------------------------------------
bool ViewContactOfSdrMediaObj::hasPreferredSize() const
{
// #i71805# Since we may have a whole bunch of VOCs here, make a loop
// return true if all have their preferred size
bool bRetval(true);
for(sal_uInt32 a(0L); bRetval && a < maVOCList.Count(); a++)
{
if(!static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->hasPreferredSize())
{
bRetval = false;
}
}
return bRetval;
}
// ------------------------------------------------------------------------------
Size ViewContactOfSdrMediaObj::getPreferredSize() const
{
// #i71805# Since we may have a whole bunch of VOCs here, make a loop
// return first useful size -> the size from the first which is visualized as a window
for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
{
Size aSize(static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->getPreferredSize());
if(0 != aSize.getWidth() || 0 != aSize.getHeight())
{
return aSize;
}
}
return Size();
}
// ------------------------------------------------------------------------------
void ViewContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const
{
// #i71805# Since we may have a whole bunch of VOCs here, make a loop
for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
{
static_cast< ViewObjectContactOfSdrMediaObj* >(maVOCList.GetObject(a))->updateMediaItem(rItem);
}
}
// ------------------------------------------------------------------------------
void ViewContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )
{
for( sal_uInt32 n(0L); n < maVOCList.Count(); n++ )
{
static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( n ) )->executeMediaItem( rItem );
}
}
// ------------------------------------------------------------------------------
void ViewContactOfSdrMediaObj::mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState )
{
static_cast< SdrMediaObj& >( GetSdrObject() ).mediaPropertiesChanged( rNewState );
}
// ------------------------------------------------------------------------------
// #i72701#
sal_Bool ViewContactOfSdrMediaObj::ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC)
{
// set pos/size of associated media window
const ViewObjectContactOfSdrMediaObj& rVOC(dynamic_cast< const ViewObjectContactOfSdrMediaObj& >(rAssociatedVOC));
rVOC.checkMediaWindowPosition(rDisplayInfo);
// call parent
return ViewContactOfSdrObj::ShouldPaintObject(rDisplayInfo, rAssociatedVOC);
}
// ------------------------------------------------------------------------------
}} // end of namespace sdr::contact
// eof
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: customshapeproperties.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-04-02 14:10:12 $
*
* 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 _SDR_PROPERTIES_CUSTOMSHAPEPROPERTIES_HXX
#include <svx/sdr/properties/customshapeproperties.hxx>
#endif
#ifndef _SVDOASHP_HXX
#include <svdoashp.hxx>
#endif
#ifndef _EEITEMID_HXX
#include <eeitemid.hxx>
#endif
#ifndef _SDTAGITM_HXX
#include <sdtagitm.hxx>
#endif
#ifndef _SFX_WHITER_HXX
#include <svtools/whiter.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
SfxItemSet& CustomShapeProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)
{
return *(new SfxItemSet(rPool,
// ranges from SdrAttrObj
SDRATTR_START, SDRATTRSET_SHADOW,
SDRATTRSET_OUTLINER, SDRATTRSET_MISC,
SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION,
// Graphic Attributes
SDRATTR_GRAF_FIRST, SDRATTRSET_GRAF,
// 3d Properties
SDRATTR_3D_FIRST, SDRATTR_3D_LAST,
// CustomShape properties
SDRATTR_CUSTOMSHAPE_FIRST, SDRATTR_CUSTOMSHAPE_LAST,
// range from SdrTextObj
EE_ITEMS_START, EE_ITEMS_END,
// end
0, 0));
}
sal_Bool CustomShapeProperties::AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem ) const
{
sal_Bool bAllowItemChange = sal_True;
if ( !pNewItem )
{
if ( ( nWhich >= SDRATTR_CUSTOMSHAPE_FIRST ) && ( nWhich <= SDRATTR_CUSTOMSHAPE_LAST ) )
bAllowItemChange = sal_False;
}
if ( bAllowItemChange )
bAllowItemChange = TextProperties::AllowItemChange( nWhich, pNewItem );
return bAllowItemChange;
}
void CustomShapeProperties::ClearObjectItem(const sal_uInt16 nWhich)
{
if ( !nWhich )
{
SfxWhichIter aIter( *mpItemSet );
sal_uInt16 nWhich = aIter.FirstWhich();
while( nWhich )
{
TextProperties::ClearObjectItem( nWhich );
nWhich = aIter.NextWhich();
}
}
else
TextProperties::ClearObjectItem( nWhich );
}
void CustomShapeProperties::ClearObjectItemDirect(const sal_uInt16 nWhich)
{
if ( !nWhich )
{
SfxWhichIter aIter( *mpItemSet );
sal_uInt16 nWhich = aIter.FirstWhich();
while( nWhich )
{
TextProperties::ClearObjectItemDirect( nWhich );
nWhich = aIter.NextWhich();
}
}
else
TextProperties::ClearObjectItemDirect( nWhich );
}
void CustomShapeProperties::ItemSetChanged(const SfxItemSet& rSet)
{
SdrObjCustomShape& rObj = (SdrObjCustomShape&)GetSdrObject();
if( SFX_ITEM_SET == rSet.GetItemState( SDRATTR_TEXT_AUTOGROWSIZE ) )
{
rObj.bTextFrame = ((SdrTextAutoGrowSizeItem&)rSet.Get( SDRATTR_TEXT_AUTOGROWSIZE )).GetValue() != 0;
}
// call parent
TextProperties::ItemSetChanged(rSet);
// local changes
delete rObj.pRenderedCustomShape, rObj.pRenderedCustomShape = 0L;
}
void CustomShapeProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem)
{
SdrTextObj& rObj = (SdrTextObj&)GetSdrObject();
OutlinerParaObject* pParaObj = rObj.GetOutlinerParaObject();
if( pNewItem && ( SDRATTR_TEXT_AUTOGROWSIZE == nWhich ) )
{
rObj.bTextFrame = ((SdrTextAutoGrowSizeItem*)pNewItem)->GetValue() != 0;
}
// call parent
TextProperties::ItemChange( nWhich, pNewItem );
}
CustomShapeProperties::CustomShapeProperties(SdrObject& rObj)
: TextProperties(rObj)
{
}
CustomShapeProperties::CustomShapeProperties(const CustomShapeProperties& rProps, SdrObject& rObj)
: TextProperties(rProps, rObj)
{
}
CustomShapeProperties::~CustomShapeProperties()
{
}
BaseProperties& CustomShapeProperties::Clone(SdrObject& rObj) const
{
return *(new CustomShapeProperties(*this, rObj));
}
} // end of namespace properties
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS sj09 (1.2.8); FILE MERGED 2004/09/16 13:11:31 sj 1.2.8.3: AutoGrowSize has been removed 2004/07/28 12:30:54 sj 1.2.8.2: solved problems with default properties 2004/06/14 16:55:33 sj 1.2.8.1: cached render object is now stored as XShape reference<commit_after>/*************************************************************************
*
* $RCSfile: customshapeproperties.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-10-12 14:15:48 $
*
* 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 _SDR_PROPERTIES_CUSTOMSHAPEPROPERTIES_HXX
#include <svx/sdr/properties/customshapeproperties.hxx>
#endif
#ifndef _SVDOASHP_HXX
#include <svdoashp.hxx>
#endif
#ifndef _EEITEMID_HXX
#include <eeitemid.hxx>
#endif
#ifndef _SDTAGITM_HXX
#include <sdtagitm.hxx>
#endif
#ifndef _SFX_WHITER_HXX
#include <svtools/whiter.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
SfxItemSet& CustomShapeProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)
{
return *(new SfxItemSet(rPool,
// ranges from SdrAttrObj
SDRATTR_START, SDRATTRSET_SHADOW,
SDRATTRSET_OUTLINER, SDRATTRSET_MISC,
SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION,
// Graphic Attributes
SDRATTR_GRAF_FIRST, SDRATTRSET_GRAF,
// 3d Properties
SDRATTR_3D_FIRST, SDRATTR_3D_LAST,
// CustomShape properties
SDRATTR_CUSTOMSHAPE_FIRST, SDRATTR_CUSTOMSHAPE_LAST,
// range from SdrTextObj
EE_ITEMS_START, EE_ITEMS_END,
// end
0, 0));
}
sal_Bool CustomShapeProperties::AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem ) const
{
sal_Bool bAllowItemChange = sal_True;
if ( !pNewItem )
{
if ( ( nWhich >= SDRATTR_CUSTOMSHAPE_FIRST ) && ( nWhich <= SDRATTR_CUSTOMSHAPE_LAST ) )
bAllowItemChange = sal_False;
}
if ( bAllowItemChange )
bAllowItemChange = TextProperties::AllowItemChange( nWhich, pNewItem );
return bAllowItemChange;
}
void CustomShapeProperties::ClearObjectItem(const sal_uInt16 nWhich)
{
if ( !nWhich )
{
SfxWhichIter aIter( *mpItemSet );
sal_uInt16 nWhich = aIter.FirstWhich();
while( nWhich )
{
TextProperties::ClearObjectItem( nWhich );
nWhich = aIter.NextWhich();
}
}
else
TextProperties::ClearObjectItem( nWhich );
}
void CustomShapeProperties::ClearObjectItemDirect(const sal_uInt16 nWhich)
{
if ( !nWhich )
{
SfxWhichIter aIter( *mpItemSet );
sal_uInt16 nWhich = aIter.FirstWhich();
while( nWhich )
{
TextProperties::ClearObjectItemDirect( nWhich );
nWhich = aIter.NextWhich();
}
}
else
TextProperties::ClearObjectItemDirect( nWhich );
}
void CustomShapeProperties::ItemSetChanged(const SfxItemSet& rSet)
{
SdrObjCustomShape& rObj = (SdrObjCustomShape&)GetSdrObject();
if( SFX_ITEM_SET == rSet.GetItemState( SDRATTR_TEXT_AUTOGROWHEIGHT ) )
{
rObj.bTextFrame = ((SdrTextAutoGrowHeightItem&)rSet.Get( SDRATTR_TEXT_AUTOGROWHEIGHT )).GetValue() != 0;
}
// call parent
TextProperties::ItemSetChanged(rSet);
// local changes, removing cached objects
rObj.mXRenderedCustomShape = NULL;
}
void CustomShapeProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem)
{
SdrTextObj& rObj = (SdrTextObj&)GetSdrObject();
OutlinerParaObject* pParaObj = rObj.GetOutlinerParaObject();
if( pNewItem && ( SDRATTR_TEXT_AUTOGROWHEIGHT == nWhich ) )
{
rObj.bTextFrame = ((SdrTextAutoGrowHeightItem*)pNewItem)->GetValue() != 0;
}
// call parent
TextProperties::ItemChange( nWhich, pNewItem );
}
void CustomShapeProperties::ForceDefaultAttributes()
{
/* SJ: Following is is no good if creating customshapes leading to objects that are white after loading via xml
SdrTextObj& rObj = (SdrTextObj&)GetSdrObject();
sal_Bool bTextFrame(rObj.IsTextFrame());
// force ItemSet
GetObjectItemSet();
if(bTextFrame)
{
mpItemSet->Put(XLineStyleItem(XLINE_NONE));
mpItemSet->Put(XFillColorItem(String(), Color(COL_WHITE)));
mpItemSet->Put(XFillStyleItem(XFILL_NONE));
}
else
{
mpItemSet->Put(SvxAdjustItem(SVX_ADJUST_CENTER));
mpItemSet->Put(SdrTextHorzAdjustItem(SDRTEXTHORZADJUST_CENTER));
mpItemSet->Put(SdrTextVertAdjustItem(SDRTEXTVERTADJUST_CENTER));
}
*/
}
CustomShapeProperties::CustomShapeProperties(SdrObject& rObj)
: TextProperties(rObj)
{
}
CustomShapeProperties::CustomShapeProperties(const CustomShapeProperties& rProps, SdrObject& rObj)
: TextProperties(rProps, rObj)
{
}
CustomShapeProperties::~CustomShapeProperties()
{
}
BaseProperties& CustomShapeProperties::Clone(SdrObject& rObj) const
{
return *(new CustomShapeProperties(*this, rObj));
}
} // end of namespace properties
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|> |
<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/session_bundle/session_bundle.h"
#include <string>
#include <utility>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "tensorflow/contrib/session_bundle/manifest.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tensorflow/core/protobuf/saver.pb.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace contrib {
namespace {
// Create a session using the given options and load the graph.
Status CreateSessionFromGraphDef(
const tensorflow::SessionOptions& options, const GraphDef& graph,
std::unique_ptr<tensorflow::Session>* session) {
session->reset(NewSession(options));
return (*session)->Create(graph);
}
Status GetMetaGraphDefFromExport(const StringPiece export_dir,
tensorflow::MetaGraphDef* meta_graph_def) {
const string meta_graph_def_path =
tensorflow::io::JoinPath(export_dir, kMetaGraphDefFilename);
return ReadBinaryProto(Env::Default(), meta_graph_def_path, meta_graph_def);
}
// Creates a string tensor.
Tensor CreateStringTensor(const string& value) {
Tensor tensor(DT_STRING, TensorShape({}));
tensor.scalar<string>()() = value;
return tensor;
}
// Adds Assets related tensors (assets_dir and asset files) to the inputs.
void AddAssetsTensorsToInputs(const StringPiece export_dir,
const std::vector<AssetFile>& asset_files,
std::vector<std::pair<string, Tensor>>* inputs) {
if (!asset_files.empty()) {
for (auto& asset : asset_files) {
Tensor assets_file_tensor = CreateStringTensor(tensorflow::io::JoinPath(
tensorflow::io::JoinPath(export_dir, kAssetsDirectory),
asset.filename()));
inputs->push_back(
{asset.tensor_binding().tensor_name(), assets_file_tensor});
}
}
}
// Historically, model exporter(exporter.py) takes only saver with
// sharded=True, and therefore always exports checkpoint in pattern file names.
// In practice, instead of training from scratch and export directly, we
// usually want to restore from existing checkpoints and then export directly.
// To support such case, model exporter now supports reusing saver object
// restored from existing checkpoint, that may have sharded=False - it will
// then export checkpoint file in plain file name.
// This method is to support models exported by both types of saver object.
// The change is backward-compatible, therefore no changes are needed for
// existing model exports.
string GetVariablesFilename(const StringPiece export_dir) {
const char kVariablesFilename[] = "export";
const char kVariablesFilenamePattern[] = "export-\?\?\?\?\?-of-\?\?\?\?\?";
if (Env::Default()->FileExists(
tensorflow::io::JoinPath(export_dir, kVariablesFilename))) {
return tensorflow::io::JoinPath(export_dir, kVariablesFilename);
} else {
return tensorflow::io::JoinPath(export_dir, kVariablesFilenamePattern);
}
}
Status RunRestoreOp(const StringPiece export_dir,
const std::vector<AssetFile>& asset_files,
const StringPiece restore_op_name,
const StringPiece variables_filename_const_op_name,
tensorflow::Session* session) {
LOG(INFO) << "Running restore op for SessionBundle";
Tensor variables_tensor = CreateStringTensor(
GetVariablesFilename(export_dir));
std::vector<std::pair<string, Tensor>> inputs = {
{variables_filename_const_op_name.ToString(), variables_tensor}};
AddAssetsTensorsToInputs(export_dir, asset_files, &inputs);
return session->Run(inputs, {}, {restore_op_name.ToString()}, nullptr);
}
Status RunInitOp(const StringPiece export_dir,
const std::vector<AssetFile>& asset_files,
const StringPiece init_op_name, tensorflow::Session* session) {
LOG(INFO) << "Running init op for SessionBundle";
std::vector<std::pair<string, Tensor>> inputs;
AddAssetsTensorsToInputs(export_dir, asset_files, &inputs);
return session->Run(inputs, {}, {init_op_name.ToString()}, nullptr);
}
} // namespace
tensorflow::Status LoadSessionBundleFromPath(
const tensorflow::SessionOptions& options, const StringPiece export_dir,
SessionBundle* bundle) {
LOG(INFO) << "Attempting to load a SessionBundle from: " << export_dir;
TF_RETURN_IF_ERROR(
GetMetaGraphDefFromExport(export_dir, &(bundle->meta_graph_def)));
auto collection_def = bundle->meta_graph_def.collection_def();
if (collection_def.find(kGraphKey) != collection_def.end()) {
// Use serving graph_def in MetaGraphDef collection_def.
if (collection_def[kGraphKey].any_list().value_size() != 1) {
return errors::FailedPrecondition(
strings::StrCat("Expected exactly one serving GraphDef in : ",
bundle->meta_graph_def.DebugString()));
}
tensorflow::GraphDef graph_def;
collection_def[kGraphKey].any_list().value(0).UnpackTo(&graph_def);
TF_RETURN_IF_ERROR(
CreateSessionFromGraphDef(options, graph_def, &bundle->session));
} else {
// Fallback to use the graph_def in the MetaGraphDef.
const tensorflow::GraphDef& graph_def = bundle->meta_graph_def.graph_def();
TF_RETURN_IF_ERROR(
CreateSessionFromGraphDef(options, graph_def, &bundle->session));
}
std::vector<AssetFile> asset_files;
auto any_assets = collection_def[kAssetsKey].any_list().value();
for (const auto any_asset : any_assets) {
AssetFile asset_file;
any_asset.UnpackTo(&asset_file);
asset_files.push_back(asset_file);
}
TF_RETURN_IF_ERROR(
RunRestoreOp(export_dir, asset_files,
bundle->meta_graph_def.saver_def().restore_op_name(),
bundle->meta_graph_def.saver_def().filename_tensor_name(),
bundle->session.get()));
if (collection_def.find(kInitOpKey) != collection_def.end()) {
if (collection_def[kInitOpKey].node_list().value_size() != 1) {
return errors::FailedPrecondition(
strings::StrCat("Expected exactly one serving init op in : ",
bundle->meta_graph_def.DebugString()));
}
return RunInitOp(export_dir, asset_files,
collection_def[kInitOpKey].node_list().value(0),
bundle->session.get());
}
LOG(INFO) << "Done loading SessionBundle";
return Status::OK();
}
} // namespace contrib
} // namespace tensorflow
<commit_msg>Prevents local copying of CollectionDef map.<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/session_bundle/session_bundle.h"
#include <string>
#include <utility>
#include <vector>
#include "google/protobuf/any.pb.h"
#include "tensorflow/contrib/session_bundle/manifest.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tensorflow/core/protobuf/saver.pb.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace contrib {
namespace {
// Create a session using the given options and load the graph.
Status CreateSessionFromGraphDef(
const tensorflow::SessionOptions& options, const GraphDef& graph,
std::unique_ptr<tensorflow::Session>* session) {
session->reset(NewSession(options));
return (*session)->Create(graph);
}
Status GetMetaGraphDefFromExport(const StringPiece export_dir,
tensorflow::MetaGraphDef* meta_graph_def) {
const string meta_graph_def_path =
tensorflow::io::JoinPath(export_dir, kMetaGraphDefFilename);
return ReadBinaryProto(Env::Default(), meta_graph_def_path, meta_graph_def);
}
// Creates a string tensor.
Tensor CreateStringTensor(const string& value) {
Tensor tensor(DT_STRING, TensorShape({}));
tensor.scalar<string>()() = value;
return tensor;
}
// Adds Assets related tensors (assets_dir and asset files) to the inputs.
void AddAssetsTensorsToInputs(const StringPiece export_dir,
const std::vector<AssetFile>& asset_files,
std::vector<std::pair<string, Tensor>>* inputs) {
if (!asset_files.empty()) {
for (auto& asset : asset_files) {
Tensor assets_file_tensor = CreateStringTensor(tensorflow::io::JoinPath(
tensorflow::io::JoinPath(export_dir, kAssetsDirectory),
asset.filename()));
inputs->push_back(
{asset.tensor_binding().tensor_name(), assets_file_tensor});
}
}
}
// Historically, model exporter(exporter.py) takes only saver with
// sharded=True, and therefore always exports checkpoint in pattern file names.
// In practice, instead of training from scratch and export directly, we
// usually want to restore from existing checkpoints and then export directly.
// To support such case, model exporter now supports reusing saver object
// restored from existing checkpoint, that may have sharded=False - it will
// then export checkpoint file in plain file name.
// This method is to support models exported by both types of saver object.
// The change is backward-compatible, therefore no changes are needed for
// existing model exports.
string GetVariablesFilename(const StringPiece export_dir) {
const char kVariablesFilename[] = "export";
const char kVariablesFilenamePattern[] = "export-\?\?\?\?\?-of-\?\?\?\?\?";
if (Env::Default()->FileExists(
tensorflow::io::JoinPath(export_dir, kVariablesFilename))) {
return tensorflow::io::JoinPath(export_dir, kVariablesFilename);
} else {
return tensorflow::io::JoinPath(export_dir, kVariablesFilenamePattern);
}
}
Status RunRestoreOp(const StringPiece export_dir,
const std::vector<AssetFile>& asset_files,
const StringPiece restore_op_name,
const StringPiece variables_filename_const_op_name,
tensorflow::Session* session) {
LOG(INFO) << "Running restore op for SessionBundle";
Tensor variables_tensor = CreateStringTensor(
GetVariablesFilename(export_dir));
std::vector<std::pair<string, Tensor>> inputs = {
{variables_filename_const_op_name.ToString(), variables_tensor}};
AddAssetsTensorsToInputs(export_dir, asset_files, &inputs);
return session->Run(inputs, {}, {restore_op_name.ToString()}, nullptr);
}
Status RunInitOp(const StringPiece export_dir,
const std::vector<AssetFile>& asset_files,
const StringPiece init_op_name, tensorflow::Session* session) {
LOG(INFO) << "Running init op for SessionBundle";
std::vector<std::pair<string, Tensor>> inputs;
AddAssetsTensorsToInputs(export_dir, asset_files, &inputs);
return session->Run(inputs, {}, {init_op_name.ToString()}, nullptr);
}
} // namespace
tensorflow::Status LoadSessionBundleFromPath(
const tensorflow::SessionOptions& options, const StringPiece export_dir,
SessionBundle* const bundle) {
LOG(INFO) << "Attempting to load a SessionBundle from: " << export_dir;
TF_RETURN_IF_ERROR(
GetMetaGraphDefFromExport(export_dir, &(bundle->meta_graph_def)));
const auto& collection_def_map = bundle->meta_graph_def.collection_def();
const auto graph_it = bundle->meta_graph_def.collection_def().find(kGraphKey);
if (graph_it != collection_def_map.end()) {
const CollectionDef& graph_collection_def = graph_it->second;
// Use serving graph_def in MetaGraphDef collection_def.
if (graph_collection_def.any_list().value_size() != 1) {
return errors::FailedPrecondition(
strings::StrCat("Expected exactly one serving GraphDef in : ",
bundle->meta_graph_def.DebugString()));
}
tensorflow::GraphDef graph_def;
graph_collection_def.any_list().value(0).UnpackTo(&graph_def);
TF_RETURN_IF_ERROR(
CreateSessionFromGraphDef(options, graph_def, &bundle->session));
} else {
// Fallback to use the graph_def in the MetaGraphDef.
const tensorflow::GraphDef& graph_def = bundle->meta_graph_def.graph_def();
TF_RETURN_IF_ERROR(
CreateSessionFromGraphDef(options, graph_def, &bundle->session));
}
std::vector<AssetFile> asset_files;
const auto assets_it = collection_def_map.find(kAssetsKey);
if (assets_it != collection_def_map.end()) {
const auto& any_assets = assets_it->second.any_list().value();
for (const auto& any_asset : any_assets) {
AssetFile asset_file;
any_asset.UnpackTo(&asset_file);
asset_files.push_back(asset_file);
}
}
TF_RETURN_IF_ERROR(
RunRestoreOp(export_dir, asset_files,
bundle->meta_graph_def.saver_def().restore_op_name(),
bundle->meta_graph_def.saver_def().filename_tensor_name(),
bundle->session.get()));
const auto init_op_it = collection_def_map.find(kInitOpKey);
if (init_op_it != collection_def_map.end()) {
if (init_op_it->second.node_list().value_size() != 1) {
return errors::FailedPrecondition(
strings::StrCat("Expected exactly one serving init op in : ",
bundle->meta_graph_def.DebugString()));
}
return RunInitOp(export_dir, asset_files,
init_op_it->second.node_list().value(0),
bundle->session.get());
}
LOG(INFO) << "Done loading SessionBundle";
return Status::OK();
}
} // namespace contrib
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/gpu/process_state.h"
#include <vector>
#include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h"
#include "tensorflow/core/common_runtime/gpu/gpu_debug_allocator.h"
#include "tensorflow/core/common_runtime/gpu/gpu_init.h"
#include "tensorflow/core/common_runtime/gpu/pool_allocator.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/tracking_allocator.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/env_var.h"
// If these flags need to be runtime configurable, consider adding
// options to ConfigProto.
// If true, register CPU RAM used to copy to/from GPU RAM with the
// CUDA driver.
const bool FLAGS_brain_mem_reg_cuda_dma = true;
// If true, record attributes of memory allocations and
// dynamically check for appropriate use of registered memory.
// Should only be true for debugging or diagnosis of
// performance issues.
const bool FLAGS_brain_gpu_record_mem_types = false;
namespace gpu = ::perftools::gputools;
namespace tensorflow {
ProcessState* ProcessState::instance_ = nullptr;
/*static*/ ProcessState* ProcessState::singleton() {
if (instance_ == nullptr) {
instance_ = new ProcessState;
}
return instance_;
}
ProcessState::ProcessState() : gpu_device_enabled_(false) {
CHECK(instance_ == nullptr);
instance_ = this;
}
ProcessState::~ProcessState() {
for (auto p : gpu_allocators_) {
delete p;
}
instance_ = nullptr;
}
string ProcessState::MemDesc::DebugString() {
return strings::StrCat((loc == CPU ? "CPU " : "GPU "), dev_index, ", dma: ",
gpu_registered, ", nic: ", nic_registered);
}
ProcessState::MemDesc ProcessState::PtrType(const void* ptr) {
if (FLAGS_brain_gpu_record_mem_types) {
auto iter = mem_desc_map_.find(ptr);
if (iter != mem_desc_map_.end()) {
return iter->second;
}
}
return MemDesc();
}
Allocator* ProcessState::GetGPUAllocator(const GPUOptions& options, int gpu_id,
size_t total_bytes) {
#if GOOGLE_CUDA
const string& allocator_type = options.allocator_type();
mutex_lock lock(mu_);
gpu::Platform* gpu_platform = GPUMachineManager();
// Verify that gpu_id is legitimate.
CHECK_LT(gpu_id, gpu_platform->VisibleDeviceCount())
<< "gpu_id is outside discovered device range";
if (gpu_id >= static_cast<int64>(gpu_allocators_.size())) {
gpu_allocators_.resize(gpu_id + 1);
if (FLAGS_brain_gpu_record_mem_types) gpu_al_.resize(gpu_id + 1);
}
if (gpu_allocators_[gpu_id] == nullptr) {
VisitableAllocator* gpu_allocator;
// Validate allocator types.
if (!allocator_type.empty() && allocator_type != "BFC") {
LOG(ERROR) << "Invalid allocator type: " << allocator_type;
return nullptr;
}
gpu_allocator = new GPUBFCAllocator(gpu_id, total_bytes, options);
// If true, checks for memory overwrites by writing
// distinctive patterns on both ends of allocated memory.
static const bool kGPUDebug = false;
if (kGPUDebug) {
gpu_allocator = new GPUDebugAllocator(gpu_allocator, gpu_id);
gpu_allocator = new GPUNanResetAllocator(gpu_allocator, gpu_id);
}
gpu_allocators_[gpu_id] = gpu_allocator;
// If there are any pending AllocVisitors for this bus, add
// them now.
gpu::StreamExecutor* se =
gpu_platform->ExecutorForDevice(gpu_id).ValueOrDie();
int bus_id = se->GetDeviceDescription().numa_node();
if (bus_id >= 0 && bus_id < static_cast<int64>(gpu_visitors_.size())) {
for (auto v : gpu_visitors_[bus_id]) {
gpu_allocators_[gpu_id]->AddAllocVisitor(v);
}
}
if (FLAGS_brain_gpu_record_mem_types) {
MemDesc md;
md.loc = MemDesc::GPU;
md.dev_index = gpu_id;
md.gpu_registered = false;
md.nic_registered = true;
if (static_cast<int64>(gpu_al_.size()) <= gpu_id)
gpu_al_.resize(gpu_id + 1);
gpu_al_[gpu_id] = new internal::RecordingAllocator(
&mem_desc_map_, gpu_allocators_[gpu_id], md, &mu_);
}
}
if (FLAGS_brain_gpu_record_mem_types) return gpu_al_[gpu_id];
return gpu_allocators_[gpu_id];
#else
LOG(FATAL) << "GPUAllocator unavailable. Not compiled with --config=cuda.";
return nullptr;
#endif // GOOGLE_CUDA
}
Allocator* ProcessState::GetCPUAllocator(int numa_node) {
// Although we're temporarily ignoring numa_node, check for legality.
CHECK_GE(numa_node, 0);
// TODO(tucker): actually maintain separate CPUAllocators for
// different numa_nodes. For now, just one.
numa_node = 0;
mutex_lock lock(mu_);
while (cpu_allocators_.size() <= static_cast<size_t>(numa_node)) {
Allocator* allocator =
new PoolAllocator(100 /*pool_size_limit*/, true /*auto_resize*/,
new BasicCPUAllocator(), new NoopRounder, "cpu_pool");
if (LogMemory::IsEnabled()) {
// Wrap the allocator to track allocation ids for better logging
// at the cost of performance.
allocator = new TrackingAllocator(allocator, true);
}
cpu_allocators_.push_back(allocator);
}
return cpu_allocators_[0];
}
Allocator* ProcessState::GetCUDAHostAllocator(int numa_node) {
if (!HasGPUDevice() || !FLAGS_brain_mem_reg_cuda_dma) {
return cpu_allocator();
}
// Although we're temporarily ignoring numa_node, check for legality.
CHECK_GE(numa_node, 0);
// TODO(tucker): actually maintain separate CPUAllocators for
// different numa_nodes. For now, just one.
numa_node = 0;
mutex_lock lock(mu_);
// Find the first valid StreamExecutor to request CUDA host memory
// through, since any will work.
//
// This search isn't super clean, and it would be nice to use a
// better source of information about which executor to use. For
// example, process_state could maybe save the first stream executor
// it knows is valid.
gpu::StreamExecutor* se = nullptr;
for (int i = 0; i < static_cast<int>(gpu_allocators_.size()); ++i) {
if (gpu_allocators_[i] != nullptr) {
se = GPUMachineManager()->ExecutorForDevice(i).ValueOrDie();
break;
}
}
CHECK_NE(nullptr, se);
while (static_cast<int>(cuda_host_allocators_.size()) <= numa_node) {
// TODO(zheng-xq): evaluate whether 64GB by default is the best choice.
int64 cuda_host_mem_limit_in_mb = -1;
Status status = ReadInt64FromEnvVar("TF_CUDA_HOST_MEM_LIMIT_IN_MB",
1LL << 16 /*64GB max by default*/,
&cuda_host_mem_limit_in_mb);
if (!status.ok()) {
LOG(ERROR) << "GetCUDAHostAllocator: " << status.error_message();
}
int64 cuda_host_mem_limit = cuda_host_mem_limit_in_mb * (1LL << 20);
Allocator* allocator =
new BFCAllocator(new CUDAHostAllocator(se), cuda_host_mem_limit,
true /*allow_growth*/, "cuda_host_bfc" /*name*/);
if (LogMemory::IsEnabled()) {
// Wrap the allocator to track allocation ids for better logging
// at the cost of performance.
allocator = new TrackingAllocator(allocator, true);
}
cuda_host_allocators_.push_back(allocator);
if (FLAGS_brain_gpu_record_mem_types) {
MemDesc md;
md.loc = MemDesc::CPU;
md.dev_index = 0;
md.gpu_registered = true;
md.nic_registered = false;
cuda_al_.push_back(new internal::RecordingAllocator(
&mem_desc_map_, cuda_host_allocators_.back(), md, &mu_));
}
}
if (FLAGS_brain_gpu_record_mem_types) return cuda_al_[0];
return cuda_host_allocators_[0];
}
void ProcessState::AddGPUAllocVisitor(int bus_id, AllocVisitor visitor) {
#if GOOGLE_CUDA
mutex_lock lock(mu_);
gpu::Platform* gpu_platform = GPUMachineManager();
for (int gpu_id = 0; gpu_id < static_cast<int64>(gpu_allocators_.size());
++gpu_id) {
gpu::StreamExecutor* se =
gpu_platform->ExecutorForDevice(gpu_id).ValueOrDie();
if (gpu_allocators_[gpu_id] &&
(se->GetDeviceDescription().numa_node() + 1) == bus_id) {
gpu_allocators_[gpu_id]->AddAllocVisitor(visitor);
}
}
while (bus_id >= static_cast<int64>(gpu_visitors_.size())) {
gpu_visitors_.push_back(std::vector<AllocVisitor>());
}
gpu_visitors_[bus_id].push_back(visitor);
#endif // GOOGLE_CUDA
}
} // namespace tensorflow
<commit_msg>Add env variable to use BFCAllocator as a CPU allocator in ProcessState<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/gpu/process_state.h"
#include <vector>
#include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h"
#include "tensorflow/core/common_runtime/gpu/gpu_debug_allocator.h"
#include "tensorflow/core/common_runtime/gpu/gpu_init.h"
#include "tensorflow/core/common_runtime/gpu/pool_allocator.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/tracking_allocator.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/env_var.h"
// If these flags need to be runtime configurable, consider adding
// options to ConfigProto.
// If true, register CPU RAM used to copy to/from GPU RAM with the
// CUDA driver.
const bool FLAGS_brain_mem_reg_cuda_dma = true;
// If true, record attributes of memory allocations and
// dynamically check for appropriate use of registered memory.
// Should only be true for debugging or diagnosis of
// performance issues.
const bool FLAGS_brain_gpu_record_mem_types = false;
namespace gpu = ::perftools::gputools;
namespace tensorflow {
ProcessState* ProcessState::instance_ = nullptr;
/*static*/ ProcessState* ProcessState::singleton() {
if (instance_ == nullptr) {
instance_ = new ProcessState;
}
return instance_;
}
ProcessState::ProcessState() : gpu_device_enabled_(false) {
CHECK(instance_ == nullptr);
instance_ = this;
}
ProcessState::~ProcessState() {
for (auto p : gpu_allocators_) {
delete p;
}
instance_ = nullptr;
}
string ProcessState::MemDesc::DebugString() {
return strings::StrCat((loc == CPU ? "CPU " : "GPU "), dev_index, ", dma: ",
gpu_registered, ", nic: ", nic_registered);
}
ProcessState::MemDesc ProcessState::PtrType(const void* ptr) {
if (FLAGS_brain_gpu_record_mem_types) {
auto iter = mem_desc_map_.find(ptr);
if (iter != mem_desc_map_.end()) {
return iter->second;
}
}
return MemDesc();
}
Allocator* ProcessState::GetGPUAllocator(const GPUOptions& options, int gpu_id,
size_t total_bytes) {
#if GOOGLE_CUDA
const string& allocator_type = options.allocator_type();
mutex_lock lock(mu_);
gpu::Platform* gpu_platform = GPUMachineManager();
// Verify that gpu_id is legitimate.
CHECK_LT(gpu_id, gpu_platform->VisibleDeviceCount())
<< "gpu_id is outside discovered device range";
if (gpu_id >= static_cast<int64>(gpu_allocators_.size())) {
gpu_allocators_.resize(gpu_id + 1);
if (FLAGS_brain_gpu_record_mem_types) gpu_al_.resize(gpu_id + 1);
}
if (gpu_allocators_[gpu_id] == nullptr) {
VisitableAllocator* gpu_allocator;
// Validate allocator types.
if (!allocator_type.empty() && allocator_type != "BFC") {
LOG(ERROR) << "Invalid allocator type: " << allocator_type;
return nullptr;
}
gpu_allocator = new GPUBFCAllocator(gpu_id, total_bytes, options);
// If true, checks for memory overwrites by writing
// distinctive patterns on both ends of allocated memory.
static const bool kGPUDebug = false;
if (kGPUDebug) {
gpu_allocator = new GPUDebugAllocator(gpu_allocator, gpu_id);
gpu_allocator = new GPUNanResetAllocator(gpu_allocator, gpu_id);
}
gpu_allocators_[gpu_id] = gpu_allocator;
// If there are any pending AllocVisitors for this bus, add
// them now.
gpu::StreamExecutor* se =
gpu_platform->ExecutorForDevice(gpu_id).ValueOrDie();
int bus_id = se->GetDeviceDescription().numa_node();
if (bus_id >= 0 && bus_id < static_cast<int64>(gpu_visitors_.size())) {
for (auto v : gpu_visitors_[bus_id]) {
gpu_allocators_[gpu_id]->AddAllocVisitor(v);
}
}
if (FLAGS_brain_gpu_record_mem_types) {
MemDesc md;
md.loc = MemDesc::GPU;
md.dev_index = gpu_id;
md.gpu_registered = false;
md.nic_registered = true;
if (static_cast<int64>(gpu_al_.size()) <= gpu_id)
gpu_al_.resize(gpu_id + 1);
gpu_al_[gpu_id] = new internal::RecordingAllocator(
&mem_desc_map_, gpu_allocators_[gpu_id], md, &mu_);
}
}
if (FLAGS_brain_gpu_record_mem_types) return gpu_al_[gpu_id];
return gpu_allocators_[gpu_id];
#else
LOG(FATAL) << "GPUAllocator unavailable. Not compiled with --config=cuda.";
return nullptr;
#endif // GOOGLE_CUDA
}
Allocator* ProcessState::GetCPUAllocator(int numa_node) {
// Although we're temporarily ignoring numa_node, check for legality.
CHECK_GE(numa_node, 0);
// TODO(tucker): actually maintain separate CPUAllocators for
// different numa_nodes. For now, just one.
numa_node = 0;
mutex_lock lock(mu_);
while (cpu_allocators_.size() <= static_cast<size_t>(numa_node)) {
bool use_bfc_allocator = false;
// TODO(reedwm): Switch default to BGFAllocator if it's at least as fast and
// efficient.
Status status = ReadBoolFromEnvVar("TF_CPU_ALLOCATOR_USE_BFC", false,
&use_bfc_allocator);
if (!status.ok()) {
LOG(ERROR) << "GetCPUAllocator: " << status.error_message();
}
Allocator* allocator;
if (use_bfc_allocator) {
// TODO(reedwm): evaluate whether 64GB by default is the best choice.
int64 cpu_mem_limit_in_mb = -1;
Status status = ReadInt64FromEnvVar("TF_CPU_BFC_MEM_LIMIT_IN_MB",
1LL << 16 /*64GB max by default*/,
&cpu_mem_limit_in_mb);
if (!status.ok()) {
LOG(ERROR) << "GetCPUAllocator: " << status.error_message();
}
int64 cpu_mem_limit = cpu_mem_limit_in_mb * (1LL << 20);
allocator = new BFCAllocator(new BasicCPUAllocator(), cpu_mem_limit,
true /*allow_growth*/,
"bfc_cpu_allocator_for_gpu" /*name*/);
VLOG(2) << "Using BFCAllocator with memory limit of "
<< cpu_mem_limit_in_mb << " MB for ProcessState CPU allocator";
} else {
allocator = new PoolAllocator(
100 /*pool_size_limit*/, true /*auto_resize*/,
new BasicCPUAllocator(), new NoopRounder, "cpu_pool");
VLOG(2) << "Using PoolAllocator for ProcessState CPU allocator";
}
if (LogMemory::IsEnabled()) {
// Wrap the allocator to track allocation ids for better logging
// at the cost of performance.
allocator = new TrackingAllocator(allocator, true);
}
cpu_allocators_.push_back(allocator);
}
return cpu_allocators_[0];
}
Allocator* ProcessState::GetCUDAHostAllocator(int numa_node) {
if (!HasGPUDevice() || !FLAGS_brain_mem_reg_cuda_dma) {
return cpu_allocator();
}
// Although we're temporarily ignoring numa_node, check for legality.
CHECK_GE(numa_node, 0);
// TODO(tucker): actually maintain separate CPUAllocators for
// different numa_nodes. For now, just one.
numa_node = 0;
mutex_lock lock(mu_);
// Find the first valid StreamExecutor to request CUDA host memory
// through, since any will work.
//
// This search isn't super clean, and it would be nice to use a
// better source of information about which executor to use. For
// example, process_state could maybe save the first stream executor
// it knows is valid.
gpu::StreamExecutor* se = nullptr;
for (int i = 0; i < static_cast<int>(gpu_allocators_.size()); ++i) {
if (gpu_allocators_[i] != nullptr) {
se = GPUMachineManager()->ExecutorForDevice(i).ValueOrDie();
break;
}
}
CHECK_NE(nullptr, se);
while (static_cast<int>(cuda_host_allocators_.size()) <= numa_node) {
// TODO(zheng-xq): evaluate whether 64GB by default is the best choice.
int64 cuda_host_mem_limit_in_mb = -1;
Status status = ReadInt64FromEnvVar("TF_CUDA_HOST_MEM_LIMIT_IN_MB",
1LL << 16 /*64GB max by default*/,
&cuda_host_mem_limit_in_mb);
if (!status.ok()) {
LOG(ERROR) << "GetCUDAHostAllocator: " << status.error_message();
}
int64 cuda_host_mem_limit = cuda_host_mem_limit_in_mb * (1LL << 20);
Allocator* allocator =
new BFCAllocator(new CUDAHostAllocator(se), cuda_host_mem_limit,
true /*allow_growth*/, "cuda_host_bfc" /*name*/);
if (LogMemory::IsEnabled()) {
// Wrap the allocator to track allocation ids for better logging
// at the cost of performance.
allocator = new TrackingAllocator(allocator, true);
}
cuda_host_allocators_.push_back(allocator);
if (FLAGS_brain_gpu_record_mem_types) {
MemDesc md;
md.loc = MemDesc::CPU;
md.dev_index = 0;
md.gpu_registered = true;
md.nic_registered = false;
cuda_al_.push_back(new internal::RecordingAllocator(
&mem_desc_map_, cuda_host_allocators_.back(), md, &mu_));
}
}
if (FLAGS_brain_gpu_record_mem_types) return cuda_al_[0];
return cuda_host_allocators_[0];
}
void ProcessState::AddGPUAllocVisitor(int bus_id, AllocVisitor visitor) {
#if GOOGLE_CUDA
mutex_lock lock(mu_);
gpu::Platform* gpu_platform = GPUMachineManager();
for (int gpu_id = 0; gpu_id < static_cast<int64>(gpu_allocators_.size());
++gpu_id) {
gpu::StreamExecutor* se =
gpu_platform->ExecutorForDevice(gpu_id).ValueOrDie();
if (gpu_allocators_[gpu_id] &&
(se->GetDeviceDescription().numa_node() + 1) == bus_id) {
gpu_allocators_[gpu_id]->AddAllocVisitor(visitor);
}
}
while (bus_id >= static_cast<int64>(gpu_visitors_.size())) {
gpu_visitors_.push_back(std::vector<AllocVisitor>());
}
gpu_visitors_[bus_id].push_back(visitor);
#endif // GOOGLE_CUDA
}
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following op.
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the experiment names and for how much percentage
// of the jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"disable_intra_op_parallelism", 5}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
<commit_msg>[tf.data] Increase the rollout percentage of `disable_intra_op_parallelism` to 20.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following op.
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the experiment names and for how much percentage
// of the jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"disable_intra_op_parallelism", 20}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"enable_gradient_descent", 100},
{"map_parallelization", 1}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list and log them.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<commit_msg>[tf.data] Increase the roll out percentage of optimization `map_parallelization` to 5%.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments = {
{"enable_gradient_descent", 100},
{"map_parallelization", 5}
};
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list and log them.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<|endoftext|> |
<commit_before>// [WriteFile Name=PortalUserInfo, Category=CloudAndPortal]
// [Legal]
// Copyright 2016 Esri.
// 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.
// [Legal]
#include "PortalUserInfo.h"
#include "AuthenticationManager.h"
#include "Credential.h"
#include "CredentialCache.h"
#include "Portal.h"
#include "PortalUser.h"
#include <QUrl>
using namespace Esri::ArcGISRuntime;
const QString PortalUserInfo::UNKNOWN = "????";
PortalUserInfo::PortalUserInfo(QQuickItem* parent /* = nullptr */):
QQuickItem(parent),
m_credential(new Credential(OAuthClientInfo("W3hPKzPbeJ0tr8aj", OAuthMode::User), this)),
m_portal(new Portal(m_credential, this))
{
connect(m_portal, &Portal::loadStatusChanged, this, &PortalUserInfo::onPortalLoadStatusChanged);
connect(m_portal, &Portal::doneLoading, this, &PortalUserInfo::loadErrorMessageChanged);
emit authManagerChanged();
AuthenticationManager::instance()->setCredentialCacheEnabled(false);
}
PortalUserInfo::~PortalUserInfo()
{
}
void PortalUserInfo::init()
{
qmlRegisterUncreatableType<AuthenticationManager>("Esri.Samples", 1, 0, "AuthenticationManager", "AuthenticationManager is uncreateable");
qmlRegisterType<PortalUserInfo>("Esri.Samples", 1, 0, "PortalUserInfoSample");
}
void PortalUserInfo::componentComplete()
{
QQuickItem::componentComplete();
load();
}
AuthenticationManager *PortalUserInfo::authManager() const
{
return AuthenticationManager::instance();
}
void PortalUserInfo::load()
{
if (!m_portal || !m_credential)
return;
if (m_portal->loadStatus() == LoadStatus::NotLoaded)
m_portal->load();
else if (m_portal->loadStatus() == LoadStatus::FailedToLoad)
m_portal->retryLoad();
}
QString PortalUserInfo::username() const
{
if (m_user)
return m_user->username();
return UNKNOWN;
}
bool PortalUserInfo::loaded()
{
if (m_portal)
return m_portal->loadStatus() == LoadStatus::Loaded;
return false;
}
QString PortalUserInfo::fullName() const
{
if (m_user)
return m_user->fullName();
return UNKNOWN;
}
QString PortalUserInfo::email() const
{
if (m_user)
return m_user->email();
return UNKNOWN;
}
QString PortalUserInfo::bio() const
{
if (m_user)
return m_user->userDescription();
return UNKNOWN;
}
QString PortalUserInfo::access() const
{
if (!m_user)
return UNKNOWN;
switch (m_user->access())
{
return UNKNOWN;
case PortalAccess::Organization:
return "Organization";
case PortalAccess::Private:
return "Only you";
case PortalAccess::Public:
return "Everyone";
case PortalAccess::Shared:
return "Shared Groups";
default:
return UNKNOWN;
}
}
QUrl PortalUserInfo::thumbnailUrl() const
{
if (m_user && !m_user->thumbnailUrl().isEmpty())
return m_user->thumbnailUrl();
return QUrl("qrc:/Samples/CloudAndPortal/PortalUserInfo/placeholder_img.png");
}
QString PortalUserInfo::orgTitle() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->organizationName();
return "";
}
QString PortalUserInfo::orgDescription() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->organizationDescription();
return "";
}
QUrl PortalUserInfo::orgThumbnailUrl() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->thumbnailUrl();
return QUrl();
}
QString PortalUserInfo::canSearchPublic() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->isCanSearchPublic() ? "True" : "False";
return "";
}
QString PortalUserInfo::canSharePublic() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->isCanSharePublic() ? "True" : "False";
return "";
}
QString PortalUserInfo::loadErrorMessage() const
{
if (m_portal)
return m_portal->loadError().message();
return "";
}
void PortalUserInfo::onPortalLoadStatusChanged(LoadStatus loadStatus)
{
switch (loadStatus) {
case LoadStatus::Loaded:
if (m_portal)
m_user = m_portal->portalUser();
emit fullNameChanged();
emit usernameChanged();
emit emailChanged();
emit bioChanged();
emit accessChanged();
emit thumbnailUrlChanged();
break;
case LoadStatus::Loading:
break;
case LoadStatus::FailedToLoad:
if (m_portal)
m_portal->retryLoad();
break;
case LoadStatus::NotLoaded:
break;
case LoadStatus::Unknown:
break;
default:
break;
}
emit loadedChanged();
}
<commit_msg>fix text<commit_after>// [WriteFile Name=PortalUserInfo, Category=CloudAndPortal]
// [Legal]
// Copyright 2016 Esri.
// 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.
// [Legal]
#include "PortalUserInfo.h"
#include "AuthenticationManager.h"
#include "Credential.h"
#include "CredentialCache.h"
#include "Portal.h"
#include "PortalUser.h"
#include <QUrl>
using namespace Esri::ArcGISRuntime;
const QString PortalUserInfo::UNKNOWN = "Unknown";
PortalUserInfo::PortalUserInfo(QQuickItem* parent /* = nullptr */):
QQuickItem(parent),
m_credential(new Credential(OAuthClientInfo("W3hPKzPbeJ0tr8aj", OAuthMode::User), this)),
m_portal(new Portal(m_credential, this))
{
connect(m_portal, &Portal::loadStatusChanged, this, &PortalUserInfo::onPortalLoadStatusChanged);
connect(m_portal, &Portal::doneLoading, this, &PortalUserInfo::loadErrorMessageChanged);
emit authManagerChanged();
AuthenticationManager::instance()->setCredentialCacheEnabled(false);
}
PortalUserInfo::~PortalUserInfo()
{
}
void PortalUserInfo::init()
{
qmlRegisterUncreatableType<AuthenticationManager>("Esri.Samples", 1, 0, "AuthenticationManager", "AuthenticationManager is uncreateable");
qmlRegisterType<PortalUserInfo>("Esri.Samples", 1, 0, "PortalUserInfoSample");
}
void PortalUserInfo::componentComplete()
{
QQuickItem::componentComplete();
load();
}
AuthenticationManager *PortalUserInfo::authManager() const
{
return AuthenticationManager::instance();
}
void PortalUserInfo::load()
{
if (!m_portal || !m_credential)
return;
if (m_portal->loadStatus() == LoadStatus::NotLoaded)
m_portal->load();
else if (m_portal->loadStatus() == LoadStatus::FailedToLoad)
m_portal->retryLoad();
}
QString PortalUserInfo::username() const
{
if (m_user)
return m_user->username();
return UNKNOWN;
}
bool PortalUserInfo::loaded()
{
if (m_portal)
return m_portal->loadStatus() == LoadStatus::Loaded;
return false;
}
QString PortalUserInfo::fullName() const
{
if (m_user)
return m_user->fullName();
return UNKNOWN;
}
QString PortalUserInfo::email() const
{
if (m_user)
return m_user->email();
return UNKNOWN;
}
QString PortalUserInfo::bio() const
{
if (m_user)
return m_user->userDescription();
return UNKNOWN;
}
QString PortalUserInfo::access() const
{
if (!m_user)
return UNKNOWN;
switch (m_user->access())
{
return UNKNOWN;
case PortalAccess::Organization:
return "Organization";
case PortalAccess::Private:
return "Only you";
case PortalAccess::Public:
return "Everyone";
case PortalAccess::Shared:
return "Shared Groups";
default:
return UNKNOWN;
}
}
QUrl PortalUserInfo::thumbnailUrl() const
{
if (m_user && !m_user->thumbnailUrl().isEmpty())
return m_user->thumbnailUrl();
return QUrl("qrc:/Samples/CloudAndPortal/PortalUserInfo/placeholder_img.png");
}
QString PortalUserInfo::orgTitle() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->organizationName();
return "";
}
QString PortalUserInfo::orgDescription() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->organizationDescription();
return "";
}
QUrl PortalUserInfo::orgThumbnailUrl() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->thumbnailUrl();
return QUrl();
}
QString PortalUserInfo::canSearchPublic() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->isCanSearchPublic() ? "True" : "False";
return "";
}
QString PortalUserInfo::canSharePublic() const
{
if (m_portal && m_portal->portalInfo())
return m_portal->portalInfo()->isCanSharePublic() ? "True" : "False";
return "";
}
QString PortalUserInfo::loadErrorMessage() const
{
if (m_portal)
return m_portal->loadError().message();
return "";
}
void PortalUserInfo::onPortalLoadStatusChanged(LoadStatus loadStatus)
{
switch (loadStatus) {
case LoadStatus::Loaded:
if (m_portal)
m_user = m_portal->portalUser();
emit fullNameChanged();
emit usernameChanged();
emit emailChanged();
emit bioChanged();
emit accessChanged();
emit thumbnailUrlChanged();
break;
case LoadStatus::Loading:
break;
case LoadStatus::FailedToLoad:
if (m_portal)
m_portal->retryLoad();
break;
case LoadStatus::NotLoaded:
break;
case LoadStatus::Unknown:
break;
default:
break;
}
emit loadedChanged();
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkGaussianImageSource.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkKullbackLeiblerCompareHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"
#include "itkTestingMacros.h"
/** This test uses two 2D-Gaussians (standard deviation RegionSize/2).
This test computes the mutual information between the two images.
*/
int
itkCompareHistogramImageToImageMetricTest(int, char *[])
{
// Create two simple images.
constexpr unsigned int ImageDimension = 2;
using PixelType = double;
using CoordinateRepresentationType = double;
// Allocate Images
using MovingImageType = itk::Image<PixelType, ImageDimension>;
using FixedImageType = itk::Image<PixelType, ImageDimension>;
// Declare Gaussian Sources
using MovingImageSourceType = itk::GaussianImageSource<MovingImageType>;
using FixedImageSourceType = itk::GaussianImageSource<FixedImageType>;
// Note: the following declarations are classical arrays
FixedImageType::SizeValueType fixedImageSize[] = { 100, 100 };
MovingImageType::SizeValueType movingImageSize[] = { 100, 100 };
FixedImageType::SpacingValueType fixedImageSpacing[] = { 1.0f, 1.0f };
MovingImageType::SpacingValueType movingImageSpacing[] = { 1.0f, 1.0f };
FixedImageType::PointValueType fixedImageOrigin[] = { 0.0f, 0.0f };
MovingImageType::PointValueType movingImageOrigin[] = { 0.0f, 0.0f };
MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New();
FixedImageSourceType::Pointer fixedImageSource = FixedImageSourceType::New();
movingImageSource->SetSize(movingImageSize);
movingImageSource->SetOrigin(movingImageOrigin);
movingImageSource->SetSpacing(movingImageSpacing);
movingImageSource->SetNormalized(false);
movingImageSource->SetScale(250.0f);
fixedImageSource->SetSize(fixedImageSize);
fixedImageSource->SetOrigin(fixedImageOrigin);
fixedImageSource->SetSpacing(fixedImageSpacing);
fixedImageSource->SetNormalized(false);
fixedImageSource->SetScale(250.0f);
ITK_TRY_EXPECT_NO_EXCEPTION(movingImageSource->Update()); // Force the filter to run
ITK_TRY_EXPECT_NO_EXCEPTION(fixedImageSource->Update()); // Force the filter to run
MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput();
// Set up the metric.
using MetricType = itk::KullbackLeiblerCompareHistogramImageToImageMetric<FixedImageType, MovingImageType>;
using TransformBaseType = MetricType::TransformType;
using ScalesType = MetricType::ScalesType;
using ParametersType = TransformBaseType::ParametersType;
MetricType::Pointer metric = MetricType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(
metric, KullbackLeiblerCompareHistogramImageToImageMetric, CompareHistogramImageToImageMetric);
auto epsilon = 1e-12;
ITK_TEST_SET_GET_VALUE(epsilon, metric->GetEpsilon());
unsigned int nBins = 256;
MetricType::HistogramType::SizeType histSize;
histSize.SetSize(2);
histSize[0] = nBins;
histSize[1] = nBins;
metric->SetHistogramSize(histSize);
// Plug the images into the metric.
metric->SetFixedImage(fixedImage);
metric->SetMovingImage(movingImage);
// Set up a transform.
using TransformType = itk::TranslationTransform<CoordinateRepresentationType, ImageDimension>;
TransformType::Pointer transform = TransformType::New();
metric->SetTransform(transform);
// Set up an interpolator.
using InterpolatorType = itk::LinearInterpolateImageFunction<MovingImageType, double>;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
interpolator->SetInputImage(movingImage);
metric->SetInterpolator(interpolator);
// Define the region over which the metric will be computed.
metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());
// Set up transform parameters.
ParametersType parameters(transform->GetNumberOfParameters());
for (unsigned int k = 0; k < ImageDimension; ++k)
{
parameters[k] = 0.0f;
}
// Set scales for derivative calculation.
ScalesType scales(transform->GetNumberOfParameters());
for (unsigned int k = 0; k < transform->GetNumberOfParameters(); ++k)
{
scales[k] = 1;
}
metric->SetDerivativeStepLengthScales(scales);
// Now set up the Training Stuff
metric->SetTrainingTransform(transform);
metric->SetTrainingFixedImage(fixedImage);
metric->SetTrainingFixedImageRegion(fixedImage->GetBufferedRegion());
metric->SetTrainingMovingImage(movingImage);
metric->SetTrainingInterpolator(interpolator);
// Initialize the metric.
metric->Initialize();
// Print out metric value and derivative.
MetricType::MeasureType measure = metric->GetValue(parameters);
MetricType::DerivativeType derivative;
metric->GetDerivative(parameters, derivative);
std::cout << "Metric value = " << measure << std::endl << "Derivative = " << derivative << std::endl;
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Improve KLCompareHistogramImageToImageMetric coverage<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkGaussianImageSource.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkKullbackLeiblerCompareHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"
#include "itkTestingMacros.h"
/** This test uses two 2D-Gaussians (standard deviation RegionSize/2).
This test computes the mutual information between the two images.
*/
int
itkCompareHistogramImageToImageMetricTest(int, char *[])
{
// Create two simple images.
constexpr unsigned int ImageDimension = 2;
using PixelType = double;
using CoordinateRepresentationType = double;
// Allocate Images
using MovingImageType = itk::Image<PixelType, ImageDimension>;
using FixedImageType = itk::Image<PixelType, ImageDimension>;
// Declare Gaussian Sources
using MovingImageSourceType = itk::GaussianImageSource<MovingImageType>;
using FixedImageSourceType = itk::GaussianImageSource<FixedImageType>;
// Note: the following declarations are classical arrays
FixedImageType::SizeValueType fixedImageSize[] = { 100, 100 };
MovingImageType::SizeValueType movingImageSize[] = { 100, 100 };
FixedImageType::SpacingValueType fixedImageSpacing[] = { 1.0f, 1.0f };
MovingImageType::SpacingValueType movingImageSpacing[] = { 1.0f, 1.0f };
FixedImageType::PointValueType fixedImageOrigin[] = { 0.0f, 0.0f };
MovingImageType::PointValueType movingImageOrigin[] = { 0.0f, 0.0f };
MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New();
FixedImageSourceType::Pointer fixedImageSource = FixedImageSourceType::New();
movingImageSource->SetSize(movingImageSize);
movingImageSource->SetOrigin(movingImageOrigin);
movingImageSource->SetSpacing(movingImageSpacing);
movingImageSource->SetNormalized(false);
movingImageSource->SetScale(250.0f);
fixedImageSource->SetSize(fixedImageSize);
fixedImageSource->SetOrigin(fixedImageOrigin);
fixedImageSource->SetSpacing(fixedImageSpacing);
fixedImageSource->SetNormalized(false);
fixedImageSource->SetScale(250.0f);
ITK_TRY_EXPECT_NO_EXCEPTION(movingImageSource->Update()); // Force the filter to run
ITK_TRY_EXPECT_NO_EXCEPTION(fixedImageSource->Update()); // Force the filter to run
MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput();
// Set up the metric.
using MetricType = itk::KullbackLeiblerCompareHistogramImageToImageMetric<FixedImageType, MovingImageType>;
using TransformBaseType = MetricType::TransformType;
using ScalesType = MetricType::ScalesType;
using ParametersType = TransformBaseType::ParametersType;
MetricType::Pointer metric = MetricType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(
metric, KullbackLeiblerCompareHistogramImageToImageMetric, CompareHistogramImageToImageMetric);
auto epsilon = 1e-12;
metric->SetEpsilon(epsilon);
ITK_TEST_SET_GET_VALUE(epsilon, metric->GetEpsilon());
unsigned int nBins = 256;
MetricType::HistogramType::SizeType histSize;
histSize.SetSize(2);
histSize[0] = nBins;
histSize[1] = nBins;
metric->SetHistogramSize(histSize);
// Plug the images into the metric.
metric->SetFixedImage(fixedImage);
metric->SetMovingImage(movingImage);
// Set up a transform.
using TransformType = itk::TranslationTransform<CoordinateRepresentationType, ImageDimension>;
TransformType::Pointer transform = TransformType::New();
metric->SetTransform(transform);
// Set up an interpolator.
using InterpolatorType = itk::LinearInterpolateImageFunction<MovingImageType, double>;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
interpolator->SetInputImage(movingImage);
metric->SetInterpolator(interpolator);
// Define the region over which the metric will be computed.
metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());
// Set up transform parameters.
ParametersType parameters(transform->GetNumberOfParameters());
for (unsigned int k = 0; k < ImageDimension; ++k)
{
parameters[k] = 0.0f;
}
// Set scales for derivative calculation.
ScalesType scales(transform->GetNumberOfParameters());
for (unsigned int k = 0; k < transform->GetNumberOfParameters(); ++k)
{
scales[k] = 1;
}
metric->SetDerivativeStepLengthScales(scales);
// Now set up the Training Stuff
metric->SetTrainingTransform(transform);
metric->SetTrainingFixedImage(fixedImage);
metric->SetTrainingFixedImageRegion(fixedImage->GetBufferedRegion());
metric->SetTrainingMovingImage(movingImage);
metric->SetTrainingInterpolator(interpolator);
// Initialize the metric.
metric->Initialize();
// Print out metric value and derivative.
MetricType::MeasureType measure = metric->GetValue(parameters);
MetricType::DerivativeType derivative;
metric->GetDerivative(parameters, derivative);
std::cout << "Metric value = " << measure << std::endl << "Derivative = " << derivative << std::endl;
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**
* @file r_tree_descent_heuristic_impl.hpp
* @author Andrew Wells
*
* Implementation of RTreeDescentHeuristic, a class that chooses the best child
* of a node in an R tree when inserting a new point.
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP
#include "r_tree_descent_heuristic.hpp"
namespace mlpack {
namespace tree {
template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(const TreeType* node,
const arma::vec& point)
{
std::vector<double> scores(node->NumChildren());
std::vector<int> vols(node->NumChildren());
double minScore = DBL_MAX;
int bestIndex = 0;
bool tied = false;
for (size_t i = 0; i < node->NumChildren(); i++)
{
double v1 = 1.0;
double v2 = 1.0;
for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
{
v1 *= node->Children()[i]->Bound()[j].Width();
v2 *= node->Children()[i]->Bound()[j].Contains(point[j]) ?
node->Children()[i]->Bound()[j].Width() :
(node->Children()[i]->Bound()[j].Hi() < point[j] ?
(point[j] - node->Children()[i]->Bound()[j].Lo()) :
(node->Children()[i]->Bound()[j].Hi() - point[j]));
}
assert(v2 - v1 >= 0);
vols[i] = v1;
scores[i] = v2 - v1;
if (v2 - v1 < minScore)
{
minScore = v2 - v1;
bestIndex = i;
}
else if (v2 - v1 == minScore)
{
tied = true;
}
}
if (tied)
{
// We break ties by choosing the smallest bound.
double minVol = DBL_MAX;
bestIndex = 0;
for (int i = 0; i < scores.size(); i++)
{
if (scores[i] == minScore)
{
if (vols[i] < minVol)
{
minVol = vols[i];
bestIndex = i;
}
}
}
}
return bestIndex;
}
template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(
const TreeType* node,
const TreeType* insertedNode)
{
std::vector<double> scores(node->NumChildren());
std::vector<int> vols(node->NumChildren());
double minScore = DBL_MAX;
int bestIndex = 0;
bool tied = false;
for (size_t i = 0; i < node->NumChildren(); i++)
{
double v1 = 1.0;
double v2 = 1.0;
for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
{
v1 *= node->Children()[i]->Bound()[j].Width();
v2 *= node->Children()[i]->Bound()[j].Contains(insertedNode->Bound()[j]) ?
node->Children()[i]->Bound()[j].Width() :
(insertedNode->Bound()[j].Contains(node->Children()[i]->Bound()[j]) ?
insertedNode->Bound()[j].Width() :
(insertedNode->Bound()[j].Lo() < node->Children()[i]->Bound()[j].Lo()
? (node->Children()[i]->Bound()[j].Hi() -
insertedNode->Bound()[j].Lo()) : (insertedNode->Bound()[j].Hi() -
node->Children()[i]->Bound()[j].Lo())));
}
assert(v2 - v1 >= 0);
vols[i] = v1;
scores[i] = v2 - v1;
if (v2 - v1 < minScore)
{
minScore = v2 - v1;
bestIndex = i;
}
else if (v2 - v1 == minScore)
{
tied = true;
}
}
if (tied)
{
// We break ties by choosing the smallest bound.
double minVol = DBL_MAX;
bestIndex = 0;
for (int i = 0; i < scores.size(); i++)
{
if (scores[i] == minScore)
{
if(vols[i] < minVol)
{
minVol = vols[i];
bestIndex = i;
}
}
}
}
return bestIndex;
}
}; // namespace tree
}; // namespace mlpack
#endif
<commit_msg>Don't use auxiliary structures; find the best node with O(1) storage. Minor speed improvement.<commit_after>/**
* @file r_tree_descent_heuristic_impl.hpp
* @author Andrew Wells
*
* Implementation of RTreeDescentHeuristic, a class that chooses the best child
* of a node in an R tree when inserting a new point.
*/
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP
#include "r_tree_descent_heuristic.hpp"
namespace mlpack {
namespace tree {
template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(const TreeType* node,
const arma::vec& point)
{
double minScore = DBL_MAX;
int bestIndex = 0;
double bestVol = 0.0;
for (size_t i = 0; i < node->NumChildren(); i++)
{
double v1 = 1.0;
double v2 = 1.0;
for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
{
v1 *= node->Children()[i]->Bound()[j].Width();
v2 *= node->Children()[i]->Bound()[j].Contains(point[j]) ?
node->Children()[i]->Bound()[j].Width() :
(node->Children()[i]->Bound()[j].Hi() < point[j] ?
(point[j] - node->Children()[i]->Bound()[j].Lo()) :
(node->Children()[i]->Bound()[j].Hi() - point[j]));
}
assert(v2 - v1 >= 0);
if ((v2 - v1) < minScore)
{
minScore = v2 - v1;
bestVol = v1;
bestIndex = i;
}
else if ((v2 - v1) == minScore && v1 < bestVol)
{
bestVol = v1;
bestIndex = i;
}
}
return bestIndex;
}
template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(
const TreeType* node,
const TreeType* insertedNode)
{
double minScore = DBL_MAX;
int bestIndex = 0;
double bestVol = 0.0;
for (size_t i = 0; i < node->NumChildren(); i++)
{
double v1 = 1.0;
double v2 = 1.0;
for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
{
v1 *= node->Children()[i]->Bound()[j].Width();
v2 *= node->Children()[i]->Bound()[j].Contains(insertedNode->Bound()[j]) ?
node->Children()[i]->Bound()[j].Width() :
(insertedNode->Bound()[j].Contains(node->Children()[i]->Bound()[j]) ?
insertedNode->Bound()[j].Width() :
(insertedNode->Bound()[j].Lo() < node->Children()[i]->Bound()[j].Lo()
? (node->Children()[i]->Bound()[j].Hi() -
insertedNode->Bound()[j].Lo()) : (insertedNode->Bound()[j].Hi() -
node->Children()[i]->Bound()[j].Lo())));
}
assert(v2 - v1 >= 0);
if ((v2 - v1) < minScore)
{
minScore = v2 - v1;
bestVol = v1;
bestIndex = i;
}
else if ((v2 - v1) == minScore && v1 < bestVol)
{
bestVol = v1;
bestIndex = i;
}
}
return bestIndex;
}
}; // namespace tree
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: vclxaccessiblecomponent.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: fs $ $Date: 2002-04-25 11:21:20 $
*
* 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_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef COMPHELPER_ACCIMPLACCESS_HXX
#include <comphelper/accimplaccess.hxx>
#endif
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#include <tools/gen.hxx> // Size
#include <tools/link.hxx> // Size
class Window;
class VCLXWindow;
class VclSimpleEvent;
class VclWindowEvent;
namespace utl {
class AccessibleStateSetHelper;
}
//class MutexHelper_Impl
//{
//protected:
// ::osl::Mutex maMutex;
//};
//typedef cppu::WeakComponentImplHelper3<
// ::drafts::com::sun::star::accessibility::XAccessibleContext,
// ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent,
// ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster
// > VCLXAccessibleComponentBase;
typedef ::comphelper::OAccessibleExtendedComponentHelper VCLXAccessibleComponentBase;
// ----------------------------------------------------
// class VCLXAccessibleComponent
// ----------------------------------------------------
class VCLXAccessibleComponent
:public VCLXAccessibleComponentBase
,public ::comphelper::OAccessibleImplementationAccess
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow;
VCLXWindow* mpVCLXindow;
ULONG nDummy1;
ULONG nDummy2;
void* pDummy1;
void* pDummy2;
protected:
// ::osl::Mutex& GetMutex() { return maMutex; }
DECL_LINK( WindowEventListener, VclSimpleEvent* );
virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );
virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet );
public:
VCLXAccessibleComponent( VCLXWindow* pVCLXindow );
~VCLXAccessibleComponent();
VCLXWindow* GetVCLXWindow() const { return mpVCLXindow; }
Window* GetWindow() const;
virtual void SAL_CALL disposing();
// ::com::sun::star::uno::XInterface
DECLARE_XINTERFACE()
// ::com::sun::star::lang::XTypeProvider
DECLARE_XTYPEPROVIDER()
// ::drafts::com::sun::star::accessibility::XAccessibleContext
sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) throw (::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException);
sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getAccessibleDescription( ) throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::lang::Locale SAL_CALL getLocale( ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException);
// ::drafts::com::sun::star::accessibility::XAccessibleComponent
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL isShowing( ) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL isVisible( ) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL isFocusTraversable( ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL grabFocus( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding( ) throw (::com::sun::star::uno::RuntimeException);
// ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent
virtual sal_Int32 SAL_CALL getForeground( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getBackground( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isEnabled( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getToolTipText( ) throw (::com::sun::star::uno::RuntimeException);
protected:
// base class overridables
::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException);
private:
/** we may be reparented (if external components use OAccessibleImplementationAccess base class),
so this method here returns the parent in the VCL world, in opposite to the parent
an external component gave us
@precond
the caller must ensure thread safety, i.e. our mutex must be locked
*/
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
getVclParent() const;
};
/* ----------------------------------------------------------
Accessibility only for the Window hierarchy!
Maybe derived classes must overwrite these Accessibility interfaces:
// XAccessibleContext:
sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole()
OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription
OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText()
Reference< XAccessibleRelationSet > getAccessibleRelationSet()
Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... )
// ::drafts::com::sun::star::accessibility::XAccessibleComponent
sal_Bool isFocusTraversable()
Any getAccessibleKeyBinding()
---------------------------------------------------------- */
#endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
<commit_msg>#98750# removed some obsolete (commented anyway) stuff left over from the previous change<commit_after>/*************************************************************************
*
* $RCSfile: vclxaccessiblecomponent.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: fs $ $Date: 2002-04-26 14:34:58 $
*
* 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_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef COMPHELPER_ACCIMPLACCESS_HXX
#include <comphelper/accimplaccess.hxx>
#endif
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#include <tools/gen.hxx> // Size
#include <tools/link.hxx> // Size
class Window;
class VCLXWindow;
class VclSimpleEvent;
class VclWindowEvent;
namespace utl {
class AccessibleStateSetHelper;
}
typedef ::comphelper::OAccessibleExtendedComponentHelper VCLXAccessibleComponentBase;
// ----------------------------------------------------
// class VCLXAccessibleComponent
// ----------------------------------------------------
class VCLXAccessibleComponent
:public VCLXAccessibleComponentBase
,public ::comphelper::OAccessibleImplementationAccess
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow;
VCLXWindow* mpVCLXindow;
ULONG nDummy1;
ULONG nDummy2;
void* pDummy1;
void* pDummy2;
protected:
DECL_LINK( WindowEventListener, VclSimpleEvent* );
virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );
virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet );
public:
VCLXAccessibleComponent( VCLXWindow* pVCLXindow );
~VCLXAccessibleComponent();
VCLXWindow* GetVCLXWindow() const { return mpVCLXindow; }
Window* GetWindow() const;
virtual void SAL_CALL disposing();
// ::com::sun::star::uno::XInterface
DECLARE_XINTERFACE()
// ::com::sun::star::lang::XTypeProvider
DECLARE_XTYPEPROVIDER()
// ::drafts::com::sun::star::accessibility::XAccessibleContext
sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) throw (::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException);
sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getAccessibleDescription( ) throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::lang::Locale SAL_CALL getLocale( ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException);
// ::drafts::com::sun::star::accessibility::XAccessibleComponent
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL isShowing( ) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL isVisible( ) throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL isFocusTraversable( ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
void SAL_CALL grabFocus( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding( ) throw (::com::sun::star::uno::RuntimeException);
// ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent
virtual sal_Int32 SAL_CALL getForeground( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getBackground( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isEnabled( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getToolTipText( ) throw (::com::sun::star::uno::RuntimeException);
protected:
// base class overridables
::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException);
private:
/** we may be reparented (if external components use OAccessibleImplementationAccess base class),
so this method here returns the parent in the VCL world, in opposite to the parent
an external component gave us
@precond
the caller must ensure thread safety, i.e. our mutex must be locked
*/
::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
getVclParent() const;
};
/* ----------------------------------------------------------
Accessibility only for the Window hierarchy!
Maybe derived classes must overwrite these Accessibility interfaces:
// XAccessibleContext:
sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole()
OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription
OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText()
Reference< XAccessibleRelationSet > getAccessibleRelationSet()
Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... )
// ::drafts::com::sun::star::accessibility::XAccessibleComponent
sal_Bool isFocusTraversable()
Any getAccessibleKeyBinding()
---------------------------------------------------------- */
#endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/glue/plugins/gtk_plugin_container_manager.h"
#include <gtk/gtk.h>
#include "app/gfx/gtk_util.h"
#include "base/logging.h"
#include "webkit/glue/plugins/gtk_plugin_container.h"
#include "webkit/glue/webplugin.h"
GtkWidget* GtkPluginContainerManager::CreatePluginContainer(
gfx::PluginWindowHandle id) {
DCHECK(host_widget_);
GtkWidget *widget = gtk_plugin_container_new();
plugin_window_to_widget_map_.insert(std::make_pair(id, widget));
// The Realize callback is responsible for adding the plug into the socket.
// The reason is 2-fold:
// - the plug can't be added until the socket is realized, but this may not
// happen until the socket is attached to a top-level window, which isn't the
// case for background tabs.
// - when dragging tabs, the socket gets unrealized, which breaks the XEMBED
// connection. We need to make it again when the tab is reattached, and the
// socket gets realized again.
//
// Note, the RealizeCallback relies on the plugin_window_to_widget_map_ to
// have the mapping.
g_signal_connect(G_OBJECT(widget), "realize",
G_CALLBACK(RealizeCallback), this);
// Don't destroy the widget when the plug is removed.
g_signal_connect(G_OBJECT(widget), "plug-removed",
G_CALLBACK(gtk_true), NULL);
gtk_container_add(GTK_CONTAINER(host_widget_), widget);
gtk_widget_show(widget);
return widget;
}
void GtkPluginContainerManager::DestroyPluginContainer(
gfx::PluginWindowHandle id) {
DCHECK(host_widget_);
GtkWidget* widget = MapIDToWidget(id);
if (widget)
gtk_widget_destroy(widget);
plugin_window_to_widget_map_.erase(id);
}
void GtkPluginContainerManager::MovePluginContainer(
const webkit_glue::WebPluginGeometry& move) {
DCHECK(host_widget_);
GtkWidget *widget = MapIDToWidget(move.window);
if (!widget)
return;
DCHECK(!GTK_WIDGET_NO_WINDOW(widget));
DCHECK(GTK_WIDGET_REALIZED(widget));
if (!move.visible) {
gtk_widget_hide(widget);
return;
} else {
gtk_widget_show(widget);
}
GdkRectangle clip_rect = move.clip_rect.ToGdkRectangle();
GdkRegion* clip_region = gdk_region_rectangle(&clip_rect);
gfx::SubtractRectanglesFromRegion(clip_region, move.cutout_rects);
gdk_window_shape_combine_region(widget->window, clip_region, 0, 0);
gdk_region_destroy(clip_region);
// Update the window position. Resizing is handled by WebPluginDelegate.
// TODO(deanm): Verify that we only need to move and not resize.
// TODO(evanm): we should cache the last shape and position and skip all
// of this business in the common case where nothing has changed.
int current_x, current_y;
// Until the above TODO is resolved, we can grab the last position
// off of the GtkFixed with a bit of hackery.
GValue value = {0};
g_value_init(&value, G_TYPE_INT);
gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
"x", &value);
current_x = g_value_get_int(&value);
gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
"y", &value);
current_y = g_value_get_int(&value);
g_value_unset(&value);
if (move.window_rect.x() != current_x ||
move.window_rect.y() != current_y) {
// Calling gtk_fixed_move unnecessarily is a no-no, as it causes the
// parent window to repaint!
gtk_fixed_move(GTK_FIXED(host_widget_),
widget,
move.window_rect.x(),
move.window_rect.y());
}
gtk_plugin_container_set_size(widget,
move.window_rect.width(),
move.window_rect.height());
}
GtkWidget* GtkPluginContainerManager::MapIDToWidget(
gfx::PluginWindowHandle id) {
PluginWindowToWidgetMap::const_iterator i =
plugin_window_to_widget_map_.find(id);
if (i != plugin_window_to_widget_map_.end())
return i->second;
LOG(ERROR) << "Request for widget host for unknown window id " << id;
return NULL;
}
gfx::PluginWindowHandle GtkPluginContainerManager::MapWidgetToID(
GtkWidget* widget) {
for (PluginWindowToWidgetMap::const_iterator i =
plugin_window_to_widget_map_.begin();
i != plugin_window_to_widget_map_.end(); ++i) {
if (i->second == widget)
return i->first;
}
LOG(ERROR) << "Request for id for unknown widget";
return 0;
}
// static
void GtkPluginContainerManager::RealizeCallback(GtkWidget* widget,
void* user_data) {
GtkPluginContainerManager* plugin_container_manager =
static_cast<GtkPluginContainerManager*>(user_data);
gfx::PluginWindowHandle id = plugin_container_manager->MapWidgetToID(widget);
if (id)
gtk_socket_add_id(GTK_SOCKET(widget), id);
}
<commit_msg>linux: obey move.rects_valid in WebPluginGeometry<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/glue/plugins/gtk_plugin_container_manager.h"
#include <gtk/gtk.h>
#include "app/gfx/gtk_util.h"
#include "base/logging.h"
#include "webkit/glue/plugins/gtk_plugin_container.h"
#include "webkit/glue/webplugin.h"
GtkWidget* GtkPluginContainerManager::CreatePluginContainer(
gfx::PluginWindowHandle id) {
DCHECK(host_widget_);
GtkWidget *widget = gtk_plugin_container_new();
plugin_window_to_widget_map_.insert(std::make_pair(id, widget));
// The Realize callback is responsible for adding the plug into the socket.
// The reason is 2-fold:
// - the plug can't be added until the socket is realized, but this may not
// happen until the socket is attached to a top-level window, which isn't the
// case for background tabs.
// - when dragging tabs, the socket gets unrealized, which breaks the XEMBED
// connection. We need to make it again when the tab is reattached, and the
// socket gets realized again.
//
// Note, the RealizeCallback relies on the plugin_window_to_widget_map_ to
// have the mapping.
g_signal_connect(G_OBJECT(widget), "realize",
G_CALLBACK(RealizeCallback), this);
// Don't destroy the widget when the plug is removed.
g_signal_connect(G_OBJECT(widget), "plug-removed",
G_CALLBACK(gtk_true), NULL);
gtk_container_add(GTK_CONTAINER(host_widget_), widget);
gtk_widget_show(widget);
return widget;
}
void GtkPluginContainerManager::DestroyPluginContainer(
gfx::PluginWindowHandle id) {
DCHECK(host_widget_);
GtkWidget* widget = MapIDToWidget(id);
if (widget)
gtk_widget_destroy(widget);
plugin_window_to_widget_map_.erase(id);
}
void GtkPluginContainerManager::MovePluginContainer(
const webkit_glue::WebPluginGeometry& move) {
DCHECK(host_widget_);
GtkWidget *widget = MapIDToWidget(move.window);
if (!widget)
return;
DCHECK(!GTK_WIDGET_NO_WINDOW(widget));
if (!move.visible) {
gtk_widget_hide(widget);
return;
}
DCHECK(GTK_WIDGET_REALIZED(widget));
gtk_widget_show(widget);
if (!move.rects_valid)
return;
GdkRectangle clip_rect = move.clip_rect.ToGdkRectangle();
GdkRegion* clip_region = gdk_region_rectangle(&clip_rect);
gfx::SubtractRectanglesFromRegion(clip_region, move.cutout_rects);
gdk_window_shape_combine_region(widget->window, clip_region, 0, 0);
gdk_region_destroy(clip_region);
// Update the window position. Resizing is handled by WebPluginDelegate.
// TODO(deanm): Verify that we only need to move and not resize.
// TODO(evanm): we should cache the last shape and position and skip all
// of this business in the common case where nothing has changed.
int current_x, current_y;
// Until the above TODO is resolved, we can grab the last position
// off of the GtkFixed with a bit of hackery.
GValue value = {0};
g_value_init(&value, G_TYPE_INT);
gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
"x", &value);
current_x = g_value_get_int(&value);
gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
"y", &value);
current_y = g_value_get_int(&value);
g_value_unset(&value);
if (move.window_rect.x() != current_x ||
move.window_rect.y() != current_y) {
// Calling gtk_fixed_move unnecessarily is a no-no, as it causes the
// parent window to repaint!
gtk_fixed_move(GTK_FIXED(host_widget_),
widget,
move.window_rect.x(),
move.window_rect.y());
}
gtk_plugin_container_set_size(widget,
move.window_rect.width(),
move.window_rect.height());
}
GtkWidget* GtkPluginContainerManager::MapIDToWidget(
gfx::PluginWindowHandle id) {
PluginWindowToWidgetMap::const_iterator i =
plugin_window_to_widget_map_.find(id);
if (i != plugin_window_to_widget_map_.end())
return i->second;
LOG(ERROR) << "Request for widget host for unknown window id " << id;
return NULL;
}
gfx::PluginWindowHandle GtkPluginContainerManager::MapWidgetToID(
GtkWidget* widget) {
for (PluginWindowToWidgetMap::const_iterator i =
plugin_window_to_widget_map_.begin();
i != plugin_window_to_widget_map_.end(); ++i) {
if (i->second == widget)
return i->first;
}
LOG(ERROR) << "Request for id for unknown widget";
return 0;
}
// static
void GtkPluginContainerManager::RealizeCallback(GtkWidget* widget,
void* user_data) {
GtkPluginContainerManager* plugin_container_manager =
static_cast<GtkPluginContainerManager*>(user_data);
gfx::PluginWindowHandle id = plugin_container_manager->MapWidgetToID(widget);
if (id)
gtk_socket_add_id(GTK_SOCKET(widget), id);
}
<|endoftext|> |
<commit_before><commit_msg>COMP: more typename outside template declaration<commit_after><|endoftext|> |
<commit_before>#ifndef CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP
#define CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP
#include "DataContainer.hpp"
#include "../InputRegister.hpp"
#include "../HoldingRegister.hpp"
#include "../DiscreteInput.hpp"
#include "../Coil.hpp"
namespace cutehmi {
namespace modbus {
namespace internal {
template <typename R>
struct RegisterTraits
{
typedef typename RegisterTraits<R>::Container Container;
};
template <>
struct RegisterTraits<InputRegister>
{
typedef DataContainer<InputRegister *> Container;
};
template <>
struct RegisterTraits<HoldingRegister>
{
typedef DataContainer<HoldingRegister *> Container;
};
template <>
struct RegisterTraits<DiscreteInput>
{
typedef DataContainer<DiscreteInput *> Container;
};
template <>
struct RegisterTraits<Coil>
{
typedef DataContainer<Coil *> Container;
};
}
}
}
#endif
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<commit_msg>Remove self-recurring "Container" typedef.<commit_after>#ifndef CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP
#define CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP
#include "DataContainer.hpp"
#include "../InputRegister.hpp"
#include "../HoldingRegister.hpp"
#include "../DiscreteInput.hpp"
#include "../Coil.hpp"
namespace cutehmi {
namespace modbus {
namespace internal {
template <typename R>
struct RegisterTraits
{
};
template <>
struct RegisterTraits<InputRegister>
{
typedef DataContainer<InputRegister *> Container;
};
template <>
struct RegisterTraits<HoldingRegister>
{
typedef DataContainer<HoldingRegister *> Container;
};
template <>
struct RegisterTraits<DiscreteInput>
{
typedef DataContainer<DiscreteInput *> Container;
};
template <>
struct RegisterTraits<Coil>
{
typedef DataContainer<Coil *> Container;
};
}
}
}
#endif
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<|endoftext|> |
<commit_before><commit_msg>Rotation<commit_after><|endoftext|> |
<commit_before>#include "timezoneview.h"
#include "dcpdatetime.h"
#include "datetimetranslation.h"
#include "dcptable.h"
#include "dcptimezonedelegate.h"
#include "dcptimezonedata.h"
#include "dcptimezoneconf.h"
#include <duitextedit.h>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QSortFilterProxyModel>
#include <DuiSceneManager>
#include <QModelIndex>
TimeZoneView::TimeZoneView(QGraphicsWidget *parent)
:DcpWidget(parent),
m_SelectedItem(-1)
{
setReferer(DcpDateTime::Main);
initWidget();
}
TimeZoneView::~TimeZoneView()
{
}
void TimeZoneView::initWidget()
{
// mainLayout
QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(Qt::Vertical, this);
// m_TextEdit
m_TextEdit = new DuiTextEdit(DuiTextEditModel::SingleLine,
DcpDateTime::InputCountryText,
this);
m_TextEdit->setObjectName("InputTextEdit");
m_TextEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
connect(m_TextEdit, SIGNAL(gainedFocus(DuiTextEdit *, Qt::FocusReason)),
this, SLOT(clearTextEdit(DuiTextEdit *)));
connect(m_TextEdit, SIGNAL(textChanged()), this, SLOT(filteringListItems()));
layout->addItem(m_TextEdit);
// model:
m_FullModel = new QStandardItemModel(this);
// TODO XXX: this has to be optimized, a lot of copying
QMultiMap<QString, DcpTimeZoneData*> zoneMap =
DcpTimeZoneConf::instance()->getMap();
QMultiMap<QString, DcpTimeZoneData*>::ConstIterator zoneIter =
zoneMap.constBegin();
QString defaultCity = DcpTimeZoneConf::instance()->defaultTimeZone().city();
while (zoneIter != zoneMap.constEnd()) {
DcpTimeZoneData* tz = zoneIter.value();
QStandardItem* item = new QStandardItem();
item->setData(tz->city(), DcpTimeZoneDelegate::TextRole1);
item->setData(tz->gmt() + " " + tz->city(),
DcpTimeZoneDelegate::TextRole2);
bool selected = false;
if (m_SelectedItem == -1 && tz->city() == defaultCity) {
m_SelectedItem = m_FullModel->rowCount();
selected = true;
}
item->setData(selected, DcpTimeZoneDelegate::CheckedRole);
item->setData(tz->timeZone(), DcpTimeZoneDelegate::ZoneIdRole);
m_FullModel->appendRow(item);
zoneIter++;
}
QSortFilterProxyModel* filterModel = new QSortFilterProxyModel(this);
filterModel->setSourceModel(m_FullModel);
filterModel->setFilterRole(DcpTimeZoneDelegate::TextRole1);
filterModel->setSortRole(DcpTimeZoneDelegate::TextRole1);
filterModel->sort(0);
// Table:
m_Table = new DcpTable();
m_Table->setDelegate(new DcpTimeZoneDelegate());
m_Table->setModel(filterModel);
connect (m_Table, SIGNAL(clicked ( const QModelIndex &)),
this, SLOT(onItemClicked( const QModelIndex &)));
layout->addItem(m_Table);
// handle orientation
connect(DuiSceneManager::instance(),
SIGNAL(orientationChanged(const Dui::Orientation &)),
this, SLOT(orientationChanged()));
orientationChanged();
}
void TimeZoneView::clearTextEdit(DuiTextEdit *textEdit)
{
if (textEdit->text() == DcpDateTime::InputCountryText) {
textEdit->setText("");
}
}
void TimeZoneView::filteringListItems()
{
QString sample = m_TextEdit->text();
if (sample == DcpDateTime::InputCountryText)
sample = "";
proxyModel()->setFilterRegExp(QRegExp(sample, Qt::CaseInsensitive,
QRegExp::FixedString));
}
QSortFilterProxyModel*
TimeZoneView::proxyModel()
{
QSortFilterProxyModel* proxyModel =
qobject_cast<QSortFilterProxyModel*>(m_Table->model());
Q_ASSERT(proxyModel);
return proxyModel;
}
void TimeZoneView::orientationChanged()
{
QSize size = DuiSceneManager::instance()->visibleSceneSize();
setMinimumHeight(size.height()-60);
}
void
TimeZoneView::onItemClicked( const QModelIndex &index)
{
if (m_SelectedItem != -1) {
selectItem(m_SelectedItem, false);
}
m_SelectedItem = proxyModel()->mapToSource(index).row();
if (m_SelectedItem != -1) {
selectItem(m_SelectedItem);
}
}
void
TimeZoneView::selectItem(int item, bool selected)
{
m_FullModel->setData( m_FullModel->index(item, 0),
selected, DcpTimeZoneDelegate::CheckedRole);
}
bool TimeZoneView::back()
{
QString zoneId = m_FullModel->index(m_SelectedItem,0).data(
DcpTimeZoneDelegate::ZoneIdRole).toString();
if (!zoneId.isEmpty()) {
DcpTimeZoneConf::instance()->setDefaultTimeZone(zoneId);
}
return DcpWidget::back();
}
<commit_msg>show country too<commit_after>#include "timezoneview.h"
#include "dcpdatetime.h"
#include "datetimetranslation.h"
#include "dcptable.h"
#include "dcptimezonedelegate.h"
#include "dcptimezonedata.h"
#include "dcptimezoneconf.h"
#include <duitextedit.h>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QSortFilterProxyModel>
#include <DuiSceneManager>
#include <QModelIndex>
TimeZoneView::TimeZoneView(QGraphicsWidget *parent)
:DcpWidget(parent),
m_SelectedItem(-1)
{
setReferer(DcpDateTime::Main);
initWidget();
}
TimeZoneView::~TimeZoneView()
{
}
void TimeZoneView::initWidget()
{
// mainLayout
QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(Qt::Vertical, this);
// m_TextEdit
m_TextEdit = new DuiTextEdit(DuiTextEditModel::SingleLine,
DcpDateTime::InputCountryText,
this);
m_TextEdit->setObjectName("InputTextEdit");
m_TextEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
connect(m_TextEdit, SIGNAL(gainedFocus(DuiTextEdit *, Qt::FocusReason)),
this, SLOT(clearTextEdit(DuiTextEdit *)));
connect(m_TextEdit, SIGNAL(textChanged()), this, SLOT(filteringListItems()));
layout->addItem(m_TextEdit);
// model:
m_FullModel = new QStandardItemModel(this);
// TODO XXX: this has to be optimized, a lot of copying
QMultiMap<QString, DcpTimeZoneData*> zoneMap =
DcpTimeZoneConf::instance()->getMap();
QMultiMap<QString, DcpTimeZoneData*>::ConstIterator zoneIter =
zoneMap.constBegin();
QString defaultCity = DcpTimeZoneConf::instance()->defaultTimeZone().city();
while (zoneIter != zoneMap.constEnd()) {
DcpTimeZoneData* tz = zoneIter.value();
QStandardItem* item = new QStandardItem();
item->setData(tz->city(), DcpTimeZoneDelegate::TextRole1);
item->setData(tz->gmt() + " " + tz->country(),
DcpTimeZoneDelegate::TextRole2);
bool selected = false;
if (m_SelectedItem == -1 && tz->city() == defaultCity) {
m_SelectedItem = m_FullModel->rowCount();
selected = true;
}
item->setData(selected, DcpTimeZoneDelegate::CheckedRole);
item->setData(tz->timeZone(), DcpTimeZoneDelegate::ZoneIdRole);
m_FullModel->appendRow(item);
zoneIter++;
}
QSortFilterProxyModel* filterModel = new QSortFilterProxyModel(this);
filterModel->setSourceModel(m_FullModel);
filterModel->setFilterRole(DcpTimeZoneDelegate::TextRole1);
filterModel->setSortRole(DcpTimeZoneDelegate::TextRole1);
filterModel->sort(0);
// Table:
m_Table = new DcpTable();
m_Table->setDelegate(new DcpTimeZoneDelegate());
m_Table->setModel(filterModel);
connect (m_Table, SIGNAL(clicked ( const QModelIndex &)),
this, SLOT(onItemClicked( const QModelIndex &)));
layout->addItem(m_Table);
// handle orientation
connect(DuiSceneManager::instance(),
SIGNAL(orientationChanged(const Dui::Orientation &)),
this, SLOT(orientationChanged()));
orientationChanged();
}
void TimeZoneView::clearTextEdit(DuiTextEdit *textEdit)
{
if (textEdit->text() == DcpDateTime::InputCountryText) {
textEdit->setText("");
}
}
void TimeZoneView::filteringListItems()
{
QString sample = m_TextEdit->text();
if (sample == DcpDateTime::InputCountryText)
sample = "";
proxyModel()->setFilterRegExp(QRegExp(sample, Qt::CaseInsensitive,
QRegExp::FixedString));
}
QSortFilterProxyModel*
TimeZoneView::proxyModel()
{
QSortFilterProxyModel* proxyModel =
qobject_cast<QSortFilterProxyModel*>(m_Table->model());
Q_ASSERT(proxyModel);
return proxyModel;
}
void TimeZoneView::orientationChanged()
{
QSize size = DuiSceneManager::instance()->visibleSceneSize();
setMinimumHeight(size.height()-60);
}
void
TimeZoneView::onItemClicked( const QModelIndex &index)
{
if (m_SelectedItem != -1) {
selectItem(m_SelectedItem, false);
}
m_SelectedItem = proxyModel()->mapToSource(index).row();
if (m_SelectedItem != -1) {
selectItem(m_SelectedItem);
}
}
void
TimeZoneView::selectItem(int item, bool selected)
{
m_FullModel->setData( m_FullModel->index(item, 0),
selected, DcpTimeZoneDelegate::CheckedRole);
}
bool TimeZoneView::back()
{
QString zoneId = m_FullModel->index(m_SelectedItem,0).data(
DcpTimeZoneDelegate::ZoneIdRole).toString();
if (!zoneId.isEmpty()) {
DcpTimeZoneConf::instance()->setDefaultTimeZone(zoneId);
}
return DcpWidget::back();
}
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file settingscontrollergui.cpp
* @author Juan GPC <[email protected]>
* @since 0.1.0
* @date May, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Juan GPC. 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 MNE-CPP authors 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.
*
*
* @brief SettingsControllerGUI class definition.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "settingscontrollergui.h"
#include "mainwindow.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDir>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QDateTime>
#include <QtGlobal>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNEANONYMIZE;
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
initParser();
parseInputs(arguments);
setupCommunication();
initializeOptionsState();
m_pWin->show();
// m_bInputFileInformationVisible = m_pWin->getExtraInfoVisibility();
// readData();
QString msg("Mellow greetings!");
m_pWin->statusMsg(msg,2000);
}
void SettingsControllerGui::executeAnonymizer()
{
m_pWin->statusMsg("Anonymizing the input file into the output file.",2000);
m_pAnonymizer->anonymizeFile();
m_pWin->statusMsg("Your file is ready!");
}
void SettingsControllerGui::readData()
{
if(m_pAnonymizer->isFileInSet())
{
QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
m_pAnonymizer->setFileOut(fileOutStr);
m_pWin->setDefaultStateExtraInfo();
bool verboseMode(m_pAnonymizer->getVerboseMode());
m_pAnonymizer->setVerboseMode(false);
m_pWin->statusMsg("Reading input file information...",0);
m_pAnonymizer->anonymizeFile();
QFile fileOut(fileOutStr);
fileOut.remove();
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
m_pAnonymizer->setVerboseMode(verboseMode);
QString msg2("Input file information read correctly.");
m_pWin->statusMsg(msg2,2000);
} else {
m_pWin->winPopup("Cannot read data. Please select a valid input file first.");
}
}
void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
QFileInfo newfiInFile(strInFile);
if(newfiInFile.isDir())
{
m_pWin->statusMsg("Invalid input file. That's a directory");
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
return;
}
if(QString::compare(newfiInFile.suffix(),QString("fif")) != 0)
{
m_pWin->statusMsg("The input file extension must be \".fif\" 0.");
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
QFileInfo inDir(newfiInFile.absolutePath());
if(!inDir.isReadable())
{
m_pWin->statusMsg("You might not have reading permissions to this folder");
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
return;
}
if( m_fiInFileInfo != newfiInFile )
{
m_fiInFileInfo.setFile(newfiInFile.absoluteFilePath());
m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());
generateDefaultOutputFileName();
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
}
}
void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
QFileInfo newfiOutFile(strOutFile);
if(m_fiOutFileInfo.isDir())
{
QString fileOutDefaultName(newfiOutFile.absolutePath() + m_fiInFileInfo.baseName() +
"_anonymized." + m_fiInFileInfo.completeSuffix());
m_fiOutFileInfo.setFile(fileOutDefaultName);
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
if(QString::compare(newfiOutFile.suffix(),QString("fif")) != 0)
{
m_pWin->statusMsg("The output file extension must be \".fif\" 0.");
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
QFileInfo outDir(newfiOutFile.absolutePath());
if(!outDir.isWritable())
{
m_pWin->winPopup("You might not have writing permissions to this folder");
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
if(m_fiOutFileInfo != newfiOutFile)
{
m_fiOutFileInfo.setFile(strOutFile);
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}
}
void SettingsControllerGui::setupCommunication()
{
//view to controller
QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
this,&SettingsControllerGui::fileInChanged);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
this,&SettingsControllerGui::fileOutChanged);
QObject::connect(m_pWin.data(),&MainWindow::readInputDataButtonClicked,
this,&SettingsControllerGui::readData);
//from view to model
QObject::connect(m_pWin.data(),&MainWindow::bruteModeChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setBruteMode);
QObject::connect(m_pWin.data(),&MainWindow::measurementDateChanged,
m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setMeasurementDate));
QObject::connect(m_pWin.data(),&MainWindow::useMeasurementOffset,
m_pAnonymizer.data(),&FiffAnonymizer::setUseMeasurementDateOffset);
QObject::connect(m_pWin.data(),&MainWindow::measurementDateOffsetChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setMeasurementDateOffset);
QObject::connect(m_pWin.data(),&MainWindow::birthdayDateChanged,
m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setSubjectBirthday));
QObject::connect(m_pWin.data(),&MainWindow::useBirthdayOffset,
m_pAnonymizer.data(),&FiffAnonymizer::setUseSubjectBirthdayOffset);
QObject::connect(m_pWin.data(),&MainWindow::birthdayOffsetChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setSubjectBirthdayOffset);
QObject::connect(m_pWin.data(),&MainWindow::subjectHisIdChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setSubjectHisId);
//from model to view
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
m_pWin.data(),&MainWindow::setLineEditIdMacAddress);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
m_pWin.data(),&MainWindow::setLineEditFileComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
m_pWin.data(),&MainWindow::setLineEditFileExperimenter);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
m_pWin.data(),&MainWindow::setLineEditSubjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
m_pWin.data(),&MainWindow::setLineEditSubjectLastName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
m_pWin.data(),&MainWindow::setComboBoxSubjectSex);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
m_pWin.data(),&MainWindow::setLineEditSubjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
m_pWin.data(),&MainWindow::setLineEditSubjectHisId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
m_pWin.data(),&MainWindow::setLineEditProjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
m_pWin.data(),&MainWindow::setLineEditProjectName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
m_pWin.data(),&MainWindow::setLineEditProjectAim);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
m_pWin.data(),&MainWindow::setLineEditProjectPersons);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
m_pWin.data(),&MainWindow::setLineEditProjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}
void SettingsControllerGui::initializeOptionsState()
{
if(m_pAnonymizer->isFileInSet())
{
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
}
if(m_pAnonymizer->isFileOutSet())
{
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
}
m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
if(m_bHisIdSpecified)
{
m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
}
}
<commit_msg>fix anonymize without input file specified<commit_after>//=============================================================================================================
/**
* @file settingscontrollergui.cpp
* @author Juan GPC <[email protected]>
* @since 0.1.0
* @date May, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Juan GPC. 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 MNE-CPP authors 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.
*
*
* @brief SettingsControllerGUI class definition.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "settingscontrollergui.h"
#include "mainwindow.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDir>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QDateTime>
#include <QtGlobal>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNEANONYMIZE;
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
initParser();
parseInputs(arguments);
setupCommunication();
initializeOptionsState();
m_pWin->show();
// m_bInputFileInformationVisible = m_pWin->getExtraInfoVisibility();
// readData();
QString msg("Mellow greetings!");
m_pWin->statusMsg(msg,2000);
}
void SettingsControllerGui::executeAnonymizer()
{
if(!m_pAnonymizer->isFileInSet())
{
m_pWin->winPopup("Please specify a valid input file first.");
return;
}
if(!m_pAnonymizer->isFileOutSet())
{
m_pWin->winPopup("Please specify a valid output file first.");
return;
}
m_pWin->statusMsg("Anonymizing the input file into the output file.",2000);
m_pAnonymizer->anonymizeFile();
m_pWin->statusMsg("Your file is ready!");
}
void SettingsControllerGui::readData()
{
if(m_pAnonymizer->isFileInSet())
{
QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
m_pAnonymizer->setFileOut(fileOutStr);
m_pWin->setDefaultStateExtraInfo();
bool verboseMode(m_pAnonymizer->getVerboseMode());
m_pAnonymizer->setVerboseMode(false);
m_pWin->statusMsg("Reading input file information...",0);
m_pAnonymizer->anonymizeFile();
QFile fileOut(fileOutStr);
fileOut.remove();
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
m_pAnonymizer->setVerboseMode(verboseMode);
QString msg2("Input file information read correctly.");
m_pWin->statusMsg(msg2,2000);
} else {
m_pWin->winPopup("Cannot read data. Please select a valid input file first.");
}
}
void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
QFileInfo newfiInFile(strInFile);
if(newfiInFile.isDir())
{
m_pWin->statusMsg("Invalid input file. That's a directory");
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
return;
}
if(QString::compare(newfiInFile.suffix(),QString("fif")) != 0)
{
m_pWin->statusMsg("The input file extension must be \".fif\" 0.");
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
QFileInfo inDir(newfiInFile.absolutePath());
if(!inDir.isReadable())
{
m_pWin->statusMsg("You might not have reading permissions to this folder");
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
return;
}
if( m_fiInFileInfo != newfiInFile )
{
m_fiInFileInfo.setFile(newfiInFile.absoluteFilePath());
m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());
generateDefaultOutputFileName();
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
}
}
void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
QFileInfo newfiOutFile(strOutFile);
if(m_fiOutFileInfo.isDir())
{
QString fileOutDefaultName(newfiOutFile.absolutePath() + m_fiInFileInfo.baseName() +
"_anonymized." + m_fiInFileInfo.completeSuffix());
m_fiOutFileInfo.setFile(fileOutDefaultName);
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
if(QString::compare(newfiOutFile.suffix(),QString("fif")) != 0)
{
m_pWin->statusMsg("The output file extension must be \".fif\" 0.");
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
QFileInfo outDir(newfiOutFile.absolutePath());
if(!outDir.isWritable())
{
m_pWin->winPopup("You might not have writing permissions to this folder");
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
return;
}
if(m_fiOutFileInfo != newfiOutFile)
{
m_fiOutFileInfo.setFile(strOutFile);
m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}
}
void SettingsControllerGui::setupCommunication()
{
//view to controller
QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
this,&SettingsControllerGui::fileInChanged);
QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
this,&SettingsControllerGui::fileOutChanged);
QObject::connect(m_pWin.data(),&MainWindow::readInputDataButtonClicked,
this,&SettingsControllerGui::readData);
//from view to model
QObject::connect(m_pWin.data(),&MainWindow::bruteModeChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setBruteMode);
QObject::connect(m_pWin.data(),&MainWindow::measurementDateChanged,
m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setMeasurementDate));
QObject::connect(m_pWin.data(),&MainWindow::useMeasurementOffset,
m_pAnonymizer.data(),&FiffAnonymizer::setUseMeasurementDateOffset);
QObject::connect(m_pWin.data(),&MainWindow::measurementDateOffsetChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setMeasurementDateOffset);
QObject::connect(m_pWin.data(),&MainWindow::birthdayDateChanged,
m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setSubjectBirthday));
QObject::connect(m_pWin.data(),&MainWindow::useBirthdayOffset,
m_pAnonymizer.data(),&FiffAnonymizer::setUseSubjectBirthdayOffset);
QObject::connect(m_pWin.data(),&MainWindow::birthdayOffsetChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setSubjectBirthdayOffset);
QObject::connect(m_pWin.data(),&MainWindow::subjectHisIdChanged,
m_pAnonymizer.data(),&FiffAnonymizer::setSubjectHisId);
//from model to view
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
m_pWin.data(),&MainWindow::setLineEditIdMacAddress);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
m_pWin.data(),&MainWindow::setLineEditFileComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
m_pWin.data(),&MainWindow::setLineEditFileExperimenter);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
m_pWin.data(),&MainWindow::setLineEditSubjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
m_pWin.data(),&MainWindow::setLineEditSubjectLastName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
m_pWin.data(),&MainWindow::setComboBoxSubjectSex);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHand);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
m_pWin.data(),&MainWindow::setLineEditSubjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
m_pWin.data(),&MainWindow::setLineEditSubjectHisId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
m_pWin.data(),&MainWindow::setLineEditProjectId);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
m_pWin.data(),&MainWindow::setLineEditProjectName);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
m_pWin.data(),&MainWindow::setLineEditProjectAim);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
m_pWin.data(),&MainWindow::setLineEditProjectPersons);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
m_pWin.data(),&MainWindow::setLineEditProjectComment);
QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}
void SettingsControllerGui::initializeOptionsState()
{
if(m_pAnonymizer->isFileInSet())
{
m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
}
if(m_pAnonymizer->isFileOutSet())
{
m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
}
m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
if(m_bHisIdSpecified)
{
m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2004 by Stanislav Karchebny *
* [email protected] *
* *
* Licensed under GPL. *
***************************************************************************/
#include "feed.h"
#include "feedscollection.h"
#include <kurl.h>
#include <kdebug.h>
#include <qlistview.h>
using namespace Akregator;
using namespace RSS;
Feed::Feed(QListViewItem *i, FeedsCollection *coll)
: FeedGroup(i, coll)
, title()
, xmlUrl()
, htmlUrl()
, description()
, isLiveJournal(false)
, ljUserName()
, ljAuthMode(AuthNone)
, ljLogin()
, ljPassword()
, updateTitle(false)
, articles()
, m_item(i)
, m_collection(coll)
{
updateView();
}
Feed::~Feed()
{
}
void Feed::destroy()
{
m_collection->remove(m_item);
delete this;
}
void Feed::updateView()
{
}
/*void Feed::open(QTextStream &ts)
{
}*/
QString Feed::ljAuthModeStr()
{
if (ljAuthMode == AuthLocal)
return "local";
if (ljAuthMode == AuthGlobal)
return "global";
return "none";
}
/*static*/ Feed::LJAuthMode Feed::authModeFromString(const QString &mode)
{
QString m = mode.lower();
if (m == "local")
return AuthLocal;
if (m == "global")
return AuthGlobal;
return AuthNone;
}
void Feed::save(QTextStream &ts, int /*depth*/)
{
ts << "<outline text=\"" << title << "\" "
"title=\"" << title << "\" "
"xmlUrl=\"" << xmlUrl << "\" "
"htmlUrl=\"" << htmlUrl << "\" "
"description=\"" << description << "\" "
"isLiveJournal=\"" << isLiveJournal << "\" "
"ljUserName=\"" << ljUserName << "\" "
"ljAuthMode=\"" << ljAuthModeStr() << "\" "
"ljLogin=\"" << ljLogin << "\" "
"ljPassword=\"" << ljPassword << "\" "
"updateTitle=\"" << updateTitle << "\" "
"type=\"akrss\" "
"version=\"RSS\"/>" << endl;
}
void Feed::fetch()
{
Loader *loader = Loader::create( this, SLOT(fetchCompleted(Loader *, Document, Status)) );
loader->loadFrom( xmlUrl, new FileRetriever );
}
void Feed::fetchCompleted(Loader */*loader*/, Document doc, Status status)
{
// Note that Loader::~Loader() is private, so you cannot delete Loader instances.
// You don't need to do that anyway since Loader instances delete themselves.
if (status != RSS::Success)
return;
kdDebug() << "Feed fetched successfully [" << doc.title() << "]" << endl;
if (updateTitle || title.isEmpty()) title = doc.title();
description = doc.description();
htmlUrl = doc.link().url();
articles = doc.articles();
emit fetched(this);
}
#include "feed.moc"
<commit_msg>Be less verbose (silly)<commit_after>/***************************************************************************
* Copyright (C) 2004 by Stanislav Karchebny *
* [email protected] *
* *
* Licensed under GPL. *
***************************************************************************/
#include "feed.h"
#include "feedscollection.h"
#include <kurl.h>
#include <kdebug.h>
#include <qlistview.h>
using namespace Akregator;
using namespace RSS;
Feed::Feed(QListViewItem *i, FeedsCollection *coll)
: FeedGroup(i, coll)
, title()
, xmlUrl()
, htmlUrl()
, description()
, isLiveJournal(false)
, ljUserName()
, ljAuthMode(AuthNone)
, ljLogin()
, ljPassword()
, updateTitle(false)
, articles()
, m_item(i)
, m_collection(coll)
{
updateView();
}
Feed::~Feed()
{
}
void Feed::destroy()
{
m_collection->remove(m_item);
delete this;
}
void Feed::updateView()
{
}
/*void Feed::open(QTextStream &ts)
{
}*/
QString Feed::ljAuthModeStr()
{
if (ljAuthMode == AuthLocal)
return "local";
if (ljAuthMode == AuthGlobal)
return "global";
return "none";
}
/*static*/ Feed::LJAuthMode Feed::authModeFromString(const QString &mode)
{
QString m = mode.lower();
if (m == "local")
return AuthLocal;
if (m == "global")
return AuthGlobal;
return AuthNone;
}
void Feed::save(QTextStream &ts, int /*depth*/)
{
ts << "<outline text=\"" << title << "\" "
"title=\"" << title << "\" "
"xmlUrl=\"" << xmlUrl << "\" "
"htmlUrl=\"" << htmlUrl << "\" "
"description=\"" << description << "\" "
"isLiveJournal=\"" << isLiveJournal << "\" "
"ljUserName=\"" << ljUserName << "\" "
"ljAuthMode=\"" << ljAuthModeStr() << "\" "
"ljLogin=\"" << ljLogin << "\" "
"ljPassword=\"" << ljPassword << "\" "
"updateTitle=\"" << updateTitle << "\" "
"type=\"akrss\" "
"version=\"RSS\"/>" << endl;
}
void Feed::fetch()
{
Loader *loader = Loader::create( this, SLOT(fetchCompleted(Loader *, Document, Status)) );
loader->loadFrom( xmlUrl, new FileRetriever );
}
void Feed::fetchCompleted(Loader */*loader*/, Document doc, Status status)
{
// Note that Loader::~Loader() is private, so you cannot delete Loader instances.
// You don't need to do that anyway since Loader instances delete themselves.
if (status != Success)
return;
kdDebug() << "Feed fetched successfully [" << doc.title() << "]" << endl;
if (updateTitle || title.isEmpty()) title = doc.title();
description = doc.description();
htmlUrl = doc.link().url();
articles = doc.articles();
emit fetched(this);
}
#include "feed.moc"
<|endoftext|> |
<commit_before>/*
* MediaManager.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <[email protected]>
* Contact: José Antonio Santos Cadenas <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "MediaHandler.hpp"
namespace kurento
{
void
MediaHandler::sendEvent (MediaEvent &event)
{
// TODO: Implement this trying to send the event to the possible addresses
}
}
<commit_msg>Send events to a random client<commit_after>/*
* MediaManager.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <[email protected]>
* Contact: José Antonio Santos Cadenas <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "MediaHandler.hpp"
#include "thrift/transport/TSocket.h"
#include "thrift/transport/TBufferTransports.h"
#include "thrift/protocol/TBinaryProtocol.h"
#include "MediaHandlerService.h"
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::protocol;
namespace kurento
{
void
MediaHandler::sendEvent (MediaEvent &event)
{
mutex.lock();
std::list<std::shared_ptr<MediaHandlerAddress>>::iterator randIt = addresses.begin();
std::advance (randIt, std::rand() % addresses.size() );
std::shared_ptr<MediaHandlerAddress> addr = *randIt;
mutex.unlock();
boost::shared_ptr<TSocket> socket (new TSocket (addr->address, addr->port) );
boost::shared_ptr<TTransport> transport (new TFramedTransport (socket) );
boost::shared_ptr<TBinaryProtocol> protocol (new TBinaryProtocol (transport) );
try {
transport->open();
MediaHandlerServiceClient client (protocol);
client.onEvent (event);
//TODO: Move the reply wating to a different thread to avoid locking main loop
transport->close();
} catch (...) {
// TODO: Try to send event again or raise error;
}
}
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InvocationOptions.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <stdio.h>
#ifdef WIN32
#include <Windows.h>
#include <shlobj.h>
#else
#include <limits.h> /* PATH_MAX */
#include <dlfcn.h>
#endif
namespace {
#if defined(LLVM_ON_UNIX)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
if (!env_var)
env_var = getenv("DYLD_LIBRARY_PATH");
if (!env_var)
env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
if (env_var != 0) {
static const char PathSeparator = ':';
const char* at = env_var;
const char* delim = strchr(at, PathSeparator);
while (delim != 0) {
std::string tmp(at, size_t(delim-at));
if (llvm::sys::fs::is_directory(tmp.c_str()))
Paths.push_back(tmp);
at = delim + 1;
delim = strchr(at, PathSeparator);
}
if (*at != 0)
if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
Paths.push_back(at);
}
#if defined(__APPLE__) || defined(__CYGWIN__)
Paths.push_back("/usr/local/lib/");
Paths.push_back("/usr/X11R6/lib/");
Paths.push_back("/usr/lib/");
Paths.push_back("/lib/");
Paths.push_back("/lib/x86_64-linux-gnu/");
Paths.push_back("/usr/local/lib64/");
Paths.push_back("/usr/lib64/");
Paths.push_back("/lib64/");
#else
static bool initialized = false;
static std::vector<std::string> SysPaths;
if (!initialized) {
// trick to get the system search path
std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
FILE *pf = popen(cmd.c_str (), "r");
std::string result = "";
std::string sys_path = "";
char buffer[128];
while (!feof(pf)) {
if (fgets(buffer, 128, pf) != NULL)
result += buffer;
}
pclose(pf);
std::size_t from
= result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
std::size_t to = result.find("(system search path)");
if (from != std::string::npos && to != std::string::npos) {
from += 12;
sys_path = result.substr(from, to-from);
sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),
sys_path.end());
sys_path += ':';
}
static const char PathSeparator = ':';
const char* at = sys_path.c_str();
const char* delim = strchr(at, PathSeparator);
while (delim != 0) {
std::string tmp(at, size_t(delim-at));
if (llvm::sys::fs::is_directory(tmp.c_str()))
SysPaths.push_back(tmp);
at = delim + 1;
delim = strchr(at, PathSeparator);
}
initialized = true;
}
for (std::vector<std::string>::const_iterator I = SysPaths.begin(),
E = SysPaths.end(); I != E; ++I)
Paths.push_back((*I).c_str());
#endif
}
#elif defined(LLVM_ON_WIN32)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char buff[MAX_PATH];
// Generic form of C:\Windows\System32
HRESULT res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get system directory");
return;
}
Paths.push_back(buff);
// Reset buff.
buff[0] = 0;
// Generic form of C:\Windows
res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get windows directory");
return;
}
Paths.push_back(buff);
}
#else
# error "Unsupported platform."
#endif
}
namespace cling {
DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
: m_Opts(Opts) {
GetSystemLibraryPaths(m_SystemSearchPaths);
m_SystemSearchPaths.push_back(".");
}
DynamicLibraryManager::~DynamicLibraryManager() {}
static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {
using namespace llvm::sys::fs;
file_magic Magic;
llvm::error_code Error = identify_magic(LibName, Magic);
bool onDisk = (Error == llvm::errc::success);
if (exists)
*exists = onDisk;
return onDisk &&
#ifdef __APPLE__
(Magic == file_magic::macho_fixed_virtual_memory_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib_stub)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
(Magic == file_magic::pecoff_executable)
#else
(Magic == file_magic::elf_shared_object)
#endif
#elif defined(LLVM_ON_WIN32)
(Magic == file_magic::pecoff_executable)
#else
# error "Unsupported platform."
#endif
;
}
std::string
DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {
llvm::SmallVector<std::string, 128>
Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());
for (llvm::SmallVectorImpl<std::string>::const_iterator
IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {
llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop
llvm::sys::path::append(ThisPath, libStem);
bool exists;
if (isSharedLib(ThisPath.str(), &exists))
return ThisPath.str();
if (exists)
return "";
}
return "";
}
std::string
DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {
using namespace llvm::sys;
std::string foundDyLib = lookupLibInPaths(libStem);
if (foundDyLib.empty()) {
// Add DyLib extension:
llvm::SmallString<512> filenameWithExt(libStem);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
filenameWithExt += DyLibExt;
foundDyLib = lookupLibInPaths(filenameWithExt);
#ifdef __APPLE__
if (foundDyLib.empty()) {
filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
filenameWithExt += ".dylib";
foundDyLib = lookupLibInPaths(filenameWithExt);
}
#endif
}
if (foundDyLib.empty())
return "";
// get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
llvm::SmallString<_MAX_PATH> FullPath("");
char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);
#else
llvm::SmallString<PATH_MAX+1> FullPath("");
char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());
#endif
if (res == 0) {
llvm::errs() << "cling::Interpreter::tryLinker(): error getting real "
"(canonical) path of library " << foundDyLib << '\n';
return foundDyLib;
}
FullPath.set_size(strlen(res));
return FullPath.str();
}
std::string
DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {
llvm::SmallString<128> Absolute(libStem);
llvm::sys::fs::make_absolute(Absolute);
bool isAbsolute = libStem == Absolute;
// If it is an absolute path, don't try iterate over the paths.
if (isAbsolute) {
if (isSharedLib(libStem))
return libStem;
else
return "";
}
std::string foundName = lookupLibMaybeAddExt(libStem);
if (foundName.empty() && !libStem.startswith("lib")) {
// try with "lib" prefix:
foundName = lookupLibMaybeAddExt("lib" + libStem.str());
}
if (isSharedLib(foundName))
return foundName;
return "";
}
DynamicLibraryManager::LoadLibResult
DynamicLibraryManager::loadLibrary(const std::string& libStem,
bool permanent) {
std::string canonicalLoadedLib = lookupLibrary(libStem);
if (canonicalLoadedLib.empty())
return kLoadLibNotFound;
if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())
return kLoadLibAlreadyLoaded;
std::string errMsg;
// TODO: !permanent case
#if defined(LLVM_ON_WIN32)
HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,
DONT_RESOLVE_DLL_REFERENCES);
errMsg = "LoadLibraryEx: GetLastError() returned ";
errMsg += GetLastError();
#else
const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),
RTLD_LAZY|RTLD_GLOBAL);
if (const char* DyLibError = dlerror()) {
errMsg = DyLibError;
}
#endif
if (!dyLibHandle) {
llvm::errs() << "cling::DyLibMan::loadLibrary(): " << errMsg << '\n';
return kLoadLibLoadError;
}
std::pair<DyLibs::iterator, bool> insRes
= m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
canonicalLoadedLib));
if (!insRes.second)
return kLoadLibAlreadyLoaded;
m_LoadedLibraries.insert(canonicalLoadedLib);
return kLoadLibSuccess;
}
void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {
std::string canonicalLoadedLib = lookupLibrary(libStem);
if (!isLibraryLoaded(canonicalLoadedLib))
return;
DyLibHandle dyLibHandle = 0;
for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
I != E; ++I) {
if (I->second == canonicalLoadedLib)
dyLibHandle = I->first;
}
std::string errMsg;
// TODO: !permanent case
#if defined(LLVM_ON_WIN32)
UnloadLibraryEx(dyLibHandle);
errMsg = "UnoadLibraryEx: GetLastError() returned ";
errMsg += GetLastError();
#else
dlclose(const_cast<void*>(dyLibHandle));
if (const char* DyLibError = dlerror()) {
errMsg = DyLibError;
}
#endif
m_DyLibs.erase(dyLibHandle);
m_LoadedLibraries.erase(canonicalLoadedLib);
}
bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {
// get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
char buf[_MAX_PATH];
char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);
#else
char buf[PATH_MAX+1];
char *res = realpath(fullPath.str().c_str(), buf);
#endif
if (res == 0) {
llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n";
return false;
}
if (m_LoadedLibraries.find(buf) != m_LoadedLibraries.end()) return true;
return false;
}
void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
}
} // end namespace cling
<commit_msg>Name order.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InvocationOptions.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#ifdef WIN32
#include <Windows.h>
#include <shlobj.h>
#else
#include <limits.h> /* PATH_MAX */
#include <dlfcn.h>
#endif
namespace {
#if defined(LLVM_ON_UNIX)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
if (!env_var)
env_var = getenv("DYLD_LIBRARY_PATH");
if (!env_var)
env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
if (env_var != 0) {
static const char PathSeparator = ':';
const char* at = env_var;
const char* delim = strchr(at, PathSeparator);
while (delim != 0) {
std::string tmp(at, size_t(delim-at));
if (llvm::sys::fs::is_directory(tmp.c_str()))
Paths.push_back(tmp);
at = delim + 1;
delim = strchr(at, PathSeparator);
}
if (*at != 0)
if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
Paths.push_back(at);
}
#if defined(__APPLE__) || defined(__CYGWIN__)
Paths.push_back("/usr/local/lib/");
Paths.push_back("/usr/X11R6/lib/");
Paths.push_back("/usr/lib/");
Paths.push_back("/lib/");
Paths.push_back("/lib/x86_64-linux-gnu/");
Paths.push_back("/usr/local/lib64/");
Paths.push_back("/usr/lib64/");
Paths.push_back("/lib64/");
#else
static bool initialized = false;
static std::vector<std::string> SysPaths;
if (!initialized) {
// trick to get the system search path
std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
FILE *pf = popen(cmd.c_str (), "r");
std::string result = "";
std::string sys_path = "";
char buffer[128];
while (!feof(pf)) {
if (fgets(buffer, 128, pf) != NULL)
result += buffer;
}
pclose(pf);
std::size_t from
= result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
std::size_t to = result.find("(system search path)");
if (from != std::string::npos && to != std::string::npos) {
from += 12;
sys_path = result.substr(from, to-from);
sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),
sys_path.end());
sys_path += ':';
}
static const char PathSeparator = ':';
const char* at = sys_path.c_str();
const char* delim = strchr(at, PathSeparator);
while (delim != 0) {
std::string tmp(at, size_t(delim-at));
if (llvm::sys::fs::is_directory(tmp.c_str()))
SysPaths.push_back(tmp);
at = delim + 1;
delim = strchr(at, PathSeparator);
}
initialized = true;
}
for (std::vector<std::string>::const_iterator I = SysPaths.begin(),
E = SysPaths.end(); I != E; ++I)
Paths.push_back((*I).c_str());
#endif
}
#elif defined(LLVM_ON_WIN32)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char buff[MAX_PATH];
// Generic form of C:\Windows\System32
HRESULT res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get system directory");
return;
}
Paths.push_back(buff);
// Reset buff.
buff[0] = 0;
// Generic form of C:\Windows
res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get windows directory");
return;
}
Paths.push_back(buff);
}
#else
# error "Unsupported platform."
#endif
}
namespace cling {
DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
: m_Opts(Opts) {
GetSystemLibraryPaths(m_SystemSearchPaths);
m_SystemSearchPaths.push_back(".");
}
DynamicLibraryManager::~DynamicLibraryManager() {}
static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {
using namespace llvm::sys::fs;
file_magic Magic;
llvm::error_code Error = identify_magic(LibName, Magic);
bool onDisk = (Error == llvm::errc::success);
if (exists)
*exists = onDisk;
return onDisk &&
#ifdef __APPLE__
(Magic == file_magic::macho_fixed_virtual_memory_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib_stub)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
(Magic == file_magic::pecoff_executable)
#else
(Magic == file_magic::elf_shared_object)
#endif
#elif defined(LLVM_ON_WIN32)
(Magic == file_magic::pecoff_executable)
#else
# error "Unsupported platform."
#endif
;
}
std::string
DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {
llvm::SmallVector<std::string, 128>
Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());
for (llvm::SmallVectorImpl<std::string>::const_iterator
IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {
llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop
llvm::sys::path::append(ThisPath, libStem);
bool exists;
if (isSharedLib(ThisPath.str(), &exists))
return ThisPath.str();
if (exists)
return "";
}
return "";
}
std::string
DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {
using namespace llvm::sys;
std::string foundDyLib = lookupLibInPaths(libStem);
if (foundDyLib.empty()) {
// Add DyLib extension:
llvm::SmallString<512> filenameWithExt(libStem);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
filenameWithExt += DyLibExt;
foundDyLib = lookupLibInPaths(filenameWithExt);
#ifdef __APPLE__
if (foundDyLib.empty()) {
filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
filenameWithExt += ".dylib";
foundDyLib = lookupLibInPaths(filenameWithExt);
}
#endif
}
if (foundDyLib.empty())
return "";
// get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
llvm::SmallString<_MAX_PATH> FullPath("");
char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);
#else
llvm::SmallString<PATH_MAX+1> FullPath("");
char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());
#endif
if (res == 0) {
llvm::errs() << "cling::Interpreter::tryLinker(): error getting real "
"(canonical) path of library " << foundDyLib << '\n';
return foundDyLib;
}
FullPath.set_size(strlen(res));
return FullPath.str();
}
std::string
DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {
llvm::SmallString<128> Absolute(libStem);
llvm::sys::fs::make_absolute(Absolute);
bool isAbsolute = libStem == Absolute;
// If it is an absolute path, don't try iterate over the paths.
if (isAbsolute) {
if (isSharedLib(libStem))
return libStem;
else
return "";
}
std::string foundName = lookupLibMaybeAddExt(libStem);
if (foundName.empty() && !libStem.startswith("lib")) {
// try with "lib" prefix:
foundName = lookupLibMaybeAddExt("lib" + libStem.str());
}
if (isSharedLib(foundName))
return foundName;
return "";
}
DynamicLibraryManager::LoadLibResult
DynamicLibraryManager::loadLibrary(const std::string& libStem,
bool permanent) {
std::string canonicalLoadedLib = lookupLibrary(libStem);
if (canonicalLoadedLib.empty())
return kLoadLibNotFound;
if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())
return kLoadLibAlreadyLoaded;
std::string errMsg;
// TODO: !permanent case
#if defined(LLVM_ON_WIN32)
HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,
DONT_RESOLVE_DLL_REFERENCES);
errMsg = "LoadLibraryEx: GetLastError() returned ";
errMsg += GetLastError();
#else
const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),
RTLD_LAZY|RTLD_GLOBAL);
if (const char* DyLibError = dlerror()) {
errMsg = DyLibError;
}
#endif
if (!dyLibHandle) {
llvm::errs() << "cling::DyLibMan::loadLibrary(): " << errMsg << '\n';
return kLoadLibLoadError;
}
std::pair<DyLibs::iterator, bool> insRes
= m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
canonicalLoadedLib));
if (!insRes.second)
return kLoadLibAlreadyLoaded;
m_LoadedLibraries.insert(canonicalLoadedLib);
return kLoadLibSuccess;
}
void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {
std::string canonicalLoadedLib = lookupLibrary(libStem);
if (!isLibraryLoaded(canonicalLoadedLib))
return;
DyLibHandle dyLibHandle = 0;
for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
I != E; ++I) {
if (I->second == canonicalLoadedLib)
dyLibHandle = I->first;
}
std::string errMsg;
// TODO: !permanent case
#if defined(LLVM_ON_WIN32)
UnloadLibraryEx(dyLibHandle);
errMsg = "UnoadLibraryEx: GetLastError() returned ";
errMsg += GetLastError();
#else
dlclose(const_cast<void*>(dyLibHandle));
if (const char* DyLibError = dlerror()) {
errMsg = DyLibError;
}
#endif
m_DyLibs.erase(dyLibHandle);
m_LoadedLibraries.erase(canonicalLoadedLib);
}
bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {
// get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
char buf[_MAX_PATH];
char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);
#else
char buf[PATH_MAX+1];
char *res = realpath(fullPath.str().c_str(), buf);
#endif
if (res == 0) {
llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n";
return false;
}
if (m_LoadedLibraries.find(buf) != m_LoadedLibraries.end()) return true;
return false;
}
void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
}
} // end namespace cling
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InvocationOptions.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#ifdef WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#endif
namespace cling {
DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
: m_Opts(Opts) { }
DynamicLibraryManager::~DynamicLibraryManager() {}
static bool isSharedLib(llvm::StringRef LibName, bool& exists) {
using namespace llvm::sys::fs;
file_magic Magic;
llvm::error_code Error = identify_magic(LibName, Magic);
exists = (Error == llvm::errc::success);
return exists &&
#ifdef __APPLE__
(Magic == file_magic::macho_fixed_virtual_memory_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib_stub)
#elif defined(LLVM_ON_UNIX)
Magic == file_magic::elf_shared_object
#elif defined(LLVM_ON_WIN32)
# error "Windows DLLs not yet implemented!"
//Magic == file_magic::pecoff_executable?
#else
# error "Unsupported platform."
#endif
;
}
static void
findSharedLibrary(llvm::StringRef fileStem,
const llvm::SmallVectorImpl<std::string>& Paths,
llvm::SmallString<512>& FoundDyLib,
bool& exists, bool& isDyLib) {
for (llvm::SmallVectorImpl<std::string>::const_iterator
IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {
llvm::SmallString<512> ThisPath(*IPath);
llvm::sys::path::append(ThisPath, fileStem);
isDyLib = isSharedLib(ThisPath.str(), exists);
if (isDyLib)
ThisPath.swap(FoundDyLib);
if (exists)
return;
}
}
#if defined(LLVM_ON_UNIX)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
if (!env_var)
env_var = getenv("DYLD_LIBRARY_PATH");
if (!env_var)
env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
if (env_var != 0) {
static const char PathSeparator = ':';
const char* at = env_var;
const char* delim = strchr(at, PathSeparator);
while (delim != 0) {
std::string tmp(at, size_t(delim-at));
if (llvm::sys::fs::is_directory(tmp.c_str()))
Paths.push_back(tmp);
at = delim + 1;
delim = strchr(at, PathSeparator);
}
if (*at != 0)
if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
Paths.push_back(at);
}
Paths.push_back("/usr/local/lib/");
Paths.push_back("/usr/X11R6/lib/");
Paths.push_back("/usr/lib/");
Paths.push_back("/lib/");
}
#elif defined(LLVM_ON_WIN32)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char buff[MAX_PATH];
// Generic form of C:\Windows\System32
HRESULT res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get system directory");
return;
}
Paths.push_back(buff);
// Reset buff.
buff[0] = 0;
// Generic form of C:\Windows
res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get windows directory");
return;
}
Paths.push_back(buff);
}
#else
# error "Unsupported platform."
#endif
DynamicLibraryManager::LoadLibResult
DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,
bool isAbsolute, bool& exists,
bool& isDyLib) {
using namespace llvm::sys;
exists = false;
isDyLib = false;
llvm::SmallString<512> FoundDyLib;
if (isAbsolute) {
isDyLib = isSharedLib(filename, exists);
if (isDyLib)
FoundDyLib = filename;
} else {
llvm::SmallVector<std::string, 16>
SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
GetSystemLibraryPaths(SearchPaths);
findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);
if (!exists) {
// Add DyLib extension:
llvm::SmallString<512> filenameWithExt(filename);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
filenameWithExt += DyLibExt;
findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
isDyLib);
#ifdef __APPLE__
if (!exists) {
filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
filenameWithExt += ".dylib";
findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
isDyLib);
}
#endif
}
}
if (!isDyLib)
return kLoadLibError;
assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!");
// TODO: !permanent case
#ifdef WIN32
# error "Windows DLL opening still needs to be implemented!"
void* dyLibHandle = needs to be implemented!;
std::string errMsg;
#else
const void* dyLibHandle
= dlopen(FoundDyLib.c_str(), RTLD_LAZY|RTLD_GLOBAL);
std::string errMsg;
if (const char* DyLibError = dlerror()) {
errMsg = DyLibError;
}
#endif
if (!dyLibHandle) {
llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n';
return kLoadLibError;
}
std::pair<DyLibs::iterator, bool> insRes
= m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
FoundDyLib.str()));
if (!insRes.second)
return kLoadLibExists;
return kLoadLibSuccess;
}
DynamicLibraryManager::LoadLibResult
DynamicLibraryManager::loadLibrary(const std::string& filename,
bool permanent, bool* tryCode) {
// If it's not an absolute path, prepend "lib"
llvm::SmallString<128> Absolute((llvm::StringRef(filename)));
llvm::sys::fs::make_absolute(Absolute);
bool isAbsolute = filename == Absolute.c_str();
bool exists = false;
bool isDyLib = false;
LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,
isDyLib);
if (tryCode) {
*tryCode = !isDyLib;
if (isAbsolute)
*tryCode &= exists;
}
if (exists)
return res;
if (!isAbsolute && filename.compare(0, 3, "lib")) {
// try with "lib" prefix:
res = tryLinker("lib" + filename, permanent, false, exists, isDyLib);
if (tryCode) {
*tryCode = !isDyLib;
if (isAbsolute)
*tryCode &= exists;
}
if (res != kLoadLibError)
return res;
}
return kLoadLibError;
}
bool
DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const{
for(DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
I != E; ++I) {
if (fullPath.equals((I->second)))
return true;
}
return false;
}
void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
}
} // end namespace cling
<commit_msg>Remove misplaced and duplicate comment.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InvocationOptions.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#ifdef WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#endif
namespace cling {
DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
: m_Opts(Opts) { }
DynamicLibraryManager::~DynamicLibraryManager() {}
static bool isSharedLib(llvm::StringRef LibName, bool& exists) {
using namespace llvm::sys::fs;
file_magic Magic;
llvm::error_code Error = identify_magic(LibName, Magic);
exists = (Error == llvm::errc::success);
return exists &&
#ifdef __APPLE__
(Magic == file_magic::macho_fixed_virtual_memory_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib
|| Magic == file_magic::macho_dynamically_linked_shared_lib_stub)
#elif defined(LLVM_ON_UNIX)
Magic == file_magic::elf_shared_object
#elif defined(LLVM_ON_WIN32)
# error "Windows DLLs not yet implemented!"
//Magic == file_magic::pecoff_executable?
#else
# error "Unsupported platform."
#endif
;
}
static void
findSharedLibrary(llvm::StringRef fileStem,
const llvm::SmallVectorImpl<std::string>& Paths,
llvm::SmallString<512>& FoundDyLib,
bool& exists, bool& isDyLib) {
for (llvm::SmallVectorImpl<std::string>::const_iterator
IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {
llvm::SmallString<512> ThisPath(*IPath);
llvm::sys::path::append(ThisPath, fileStem);
isDyLib = isSharedLib(ThisPath.str(), exists);
if (isDyLib)
ThisPath.swap(FoundDyLib);
if (exists)
return;
}
}
#if defined(LLVM_ON_UNIX)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
if (!env_var)
env_var = getenv("DYLD_LIBRARY_PATH");
if (!env_var)
env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
if (env_var != 0) {
static const char PathSeparator = ':';
const char* at = env_var;
const char* delim = strchr(at, PathSeparator);
while (delim != 0) {
std::string tmp(at, size_t(delim-at));
if (llvm::sys::fs::is_directory(tmp.c_str()))
Paths.push_back(tmp);
at = delim + 1;
delim = strchr(at, PathSeparator);
}
if (*at != 0)
if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
Paths.push_back(at);
}
Paths.push_back("/usr/local/lib/");
Paths.push_back("/usr/X11R6/lib/");
Paths.push_back("/usr/lib/");
Paths.push_back("/lib/");
}
#elif defined(LLVM_ON_WIN32)
static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
char buff[MAX_PATH];
// Generic form of C:\Windows\System32
HRESULT res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get system directory");
return;
}
Paths.push_back(buff);
// Reset buff.
buff[0] = 0;
// Generic form of C:\Windows
res = SHGetFolderPathA(NULL,
CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
NULL,
SHGFP_TYPE_CURRENT,
buff);
if (res != S_OK) {
assert(0 && "Failed to get windows directory");
return;
}
Paths.push_back(buff);
}
#else
# error "Unsupported platform."
#endif
DynamicLibraryManager::LoadLibResult
DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,
bool isAbsolute, bool& exists,
bool& isDyLib) {
using namespace llvm::sys;
exists = false;
isDyLib = false;
llvm::SmallString<512> FoundDyLib;
if (isAbsolute) {
isDyLib = isSharedLib(filename, exists);
if (isDyLib)
FoundDyLib = filename;
} else {
llvm::SmallVector<std::string, 16>
SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
GetSystemLibraryPaths(SearchPaths);
findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);
if (!exists) {
// Add DyLib extension:
llvm::SmallString<512> filenameWithExt(filename);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
filenameWithExt += DyLibExt;
findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
isDyLib);
#ifdef __APPLE__
if (!exists) {
filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
filenameWithExt += ".dylib";
findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
isDyLib);
}
#endif
}
}
if (!isDyLib)
return kLoadLibError;
assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!");
// TODO: !permanent case
#ifdef WIN32
# error "Windows DLL opening still needs to be implemented!"
void* dyLibHandle = needs to be implemented!;
std::string errMsg;
#else
const void* dyLibHandle
= dlopen(FoundDyLib.c_str(), RTLD_LAZY|RTLD_GLOBAL);
std::string errMsg;
if (const char* DyLibError = dlerror()) {
errMsg = DyLibError;
}
#endif
if (!dyLibHandle) {
llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n';
return kLoadLibError;
}
std::pair<DyLibs::iterator, bool> insRes
= m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
FoundDyLib.str()));
if (!insRes.second)
return kLoadLibExists;
return kLoadLibSuccess;
}
DynamicLibraryManager::LoadLibResult
DynamicLibraryManager::loadLibrary(const std::string& filename,
bool permanent, bool* tryCode) {
llvm::SmallString<128> Absolute((llvm::StringRef(filename)));
llvm::sys::fs::make_absolute(Absolute);
bool isAbsolute = filename == Absolute.c_str();
bool exists = false;
bool isDyLib = false;
LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,
isDyLib);
if (tryCode) {
*tryCode = !isDyLib;
if (isAbsolute)
*tryCode &= exists;
}
if (exists)
return res;
if (!isAbsolute && filename.compare(0, 3, "lib")) {
// try with "lib" prefix:
res = tryLinker("lib" + filename, permanent, false, exists, isDyLib);
if (tryCode) {
*tryCode = !isDyLib;
if (isAbsolute)
*tryCode &= exists;
}
if (res != kLoadLibError)
return res;
}
return kLoadLibError;
}
bool
DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const{
for(DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
I != E; ++I) {
if (fullPath.equals((I->second)))
return true;
}
return false;
}
void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
}
} // end namespace cling
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simpleinteractionrequest.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 16:31:42 $
*
* 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 _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX
#define _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX
#ifndef _UCBHELPER_INTERATIONREQUEST_HXX
#include <ucbhelper/interactionrequest.hxx>
#endif
#ifndef INCLUDED_UCBHELPERDLLAPI_H
#include "ucbhelper/ucbhelperdllapi.h"
#endif
namespace ucbhelper {
/** These are the constants that can be passed to the constructor of class
* SimpleInteractionRequest and that are returned by method
* SimpleInteractionRequest::getResponse().
*/
/** The request was not (yet) handled by the interaction handler. */
static const sal_Int32 CONTINUATION_UNKNOWN = 0;
/** The interaction handler selected XInteractionAbort. */
static const sal_Int32 CONTINUATION_ABORT = 1;
/** The interaction handler selected XInteractionRetry. */
static const sal_Int32 CONTINUATION_RETRY = 2;
/** The interaction handler selected XInteractionApprove. */
static const sal_Int32 CONTINUATION_APPROVE = 4;
/** The interaction handler selected XInteractionDisapprove. */
static const sal_Int32 CONTINUATION_DISAPPROVE = 8;
/**
* This class implements a simple interaction request. The user must not deal
* with XInteractionContinuations directly, but can use constants that are
* mapped internally to the according objects. This class encapsulates the
* standard Interaction Continuations "Abort", "Retry", "Approve" and
* "Disaprrove". Instances can be passed directly to
* XInteractionHandler::handle(...).
*
* @see InteractionRequest
* @see InteractionAbort
* @see InteractionRetry
* @see InteractionApprove
* @see InteractionDisapprove
*/
class UCBHELPER_DLLPUBLIC SimpleInteractionRequest : public ucbhelper::InteractionRequest
{
public:
/**
* Constructor.
*
* @param rRequest is the exception describing the error.
* @param nContinuations contains the possible "answers" for the request.
* This can be any of the CONTINUATION_* constants combinations
* listed above.
*/
SimpleInteractionRequest( const com::sun::star::uno::Any & rRequest,
const sal_Int32 nContinuations );
/**
* After passing this request to XInteractionHandler::handle, this method
* returns the continuation that was choosen by the interaction handler.
*
* @return the continuation choosen by an interaction handler or
* CONTINUATION_UNKNOWN, if the request was not (yet) handled.
*/
const sal_Int32 getResponse() const;
};
} // namespace ucbhelper
#endif /* !_UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.3.104); FILE MERGED 2008/04/01 12:58:45 thb 1.3.104.2: #i85898# Stripping all external header guards 2008/03/31 15:31:30 rt 1.3.104.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simpleinteractionrequest.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX
#define _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX
#include <ucbhelper/interactionrequest.hxx>
#include "ucbhelper/ucbhelperdllapi.h"
namespace ucbhelper {
/** These are the constants that can be passed to the constructor of class
* SimpleInteractionRequest and that are returned by method
* SimpleInteractionRequest::getResponse().
*/
/** The request was not (yet) handled by the interaction handler. */
static const sal_Int32 CONTINUATION_UNKNOWN = 0;
/** The interaction handler selected XInteractionAbort. */
static const sal_Int32 CONTINUATION_ABORT = 1;
/** The interaction handler selected XInteractionRetry. */
static const sal_Int32 CONTINUATION_RETRY = 2;
/** The interaction handler selected XInteractionApprove. */
static const sal_Int32 CONTINUATION_APPROVE = 4;
/** The interaction handler selected XInteractionDisapprove. */
static const sal_Int32 CONTINUATION_DISAPPROVE = 8;
/**
* This class implements a simple interaction request. The user must not deal
* with XInteractionContinuations directly, but can use constants that are
* mapped internally to the according objects. This class encapsulates the
* standard Interaction Continuations "Abort", "Retry", "Approve" and
* "Disaprrove". Instances can be passed directly to
* XInteractionHandler::handle(...).
*
* @see InteractionRequest
* @see InteractionAbort
* @see InteractionRetry
* @see InteractionApprove
* @see InteractionDisapprove
*/
class UCBHELPER_DLLPUBLIC SimpleInteractionRequest : public ucbhelper::InteractionRequest
{
public:
/**
* Constructor.
*
* @param rRequest is the exception describing the error.
* @param nContinuations contains the possible "answers" for the request.
* This can be any of the CONTINUATION_* constants combinations
* listed above.
*/
SimpleInteractionRequest( const com::sun::star::uno::Any & rRequest,
const sal_Int32 nContinuations );
/**
* After passing this request to XInteractionHandler::handle, this method
* returns the continuation that was choosen by the interaction handler.
*
* @return the continuation choosen by an interaction handler or
* CONTINUATION_UNKNOWN, if the request was not (yet) handled.
*/
const sal_Int32 getResponse() const;
};
} // namespace ucbhelper
#endif /* !_UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX */
<|endoftext|> |
<commit_before>/*
* Copyright 2012-2013 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This Atmel Studio 6 project automatically includes all needed Arduino source files, you just have to point it to the right directories.
* To compile this project on your computer, you will have to set an environment variable to find your local Arduino installation.
* Set the variable ARDUINO_HOME to point to your local Arduino path, without trailing slash, e.g. 'D:\arduino-1.01'. Instructions on the wiki here:
* http://wiki.brewpi.com/index.php/Setting_up_the_brewpi-avr_Project
* 'ArduinoFunctions.cpp' includes all the source files from Arduino that are used. You might have to edit it if you are not using a Leonardo.
* That is all that is needed! No hassle with makefiles and compiling libraries.
*/
#include "Brewpi.h"
#include "Ticks.h"
#include "Display.h"
#include "TempControl.h"
#include "PiLink.h"
#include "Menu.h"
#include "Pins.h"
#include "RotaryEncoder.h"
#include "Buzzer.h"
#include "TempSensor.h"
#include "TempSensorMock.h"
#include "OneWireTempSensor.h"
#include "TempSensorExternal.h"
#include "Ticks.h"
#include "Sensor.h"
#include "FastDigitalPin.h"
#include "OneWireActuator.h"
#include "SettingsManager.h"
#if BREWPI_SIMULATE
#include "Simulator.h"
#endif
// global class objects static and defined in class cpp and h files
// instantiate and configure the sensors, actuators and controllers we want to use
void setup(void);
void loop (void);
/* Configure the counter and delay timer. The actual type of these will vary depending upon the environment.
* They are non-virtual to keep code size minimal, so typedefs and preprocessing are used to select the actual compile-time type used. */
TicksImpl ticks = TicksImpl(TICKS_IMPL_CONFIG);
DelayImpl wait = DelayImpl(DELAY_IMPL_CONFIG);
DisplayType realDisplay;
DisplayType DISPLAY_REF display = realDisplay;
void setup()
{
piLink.init();
logDebug("started");
tempControl.init();
settingsManager.loadSettings();
#if BREWPI_SIMULATE
simulator.step();
// initialize the filters with the assigned initial temp value
tempControl.beerSensor->init();
tempControl.fridgeSensor->init();
#endif
display.init();
display.printStationaryText();
display.printState();
rotaryEncoder.init();
#if BREWPI_BUZZER
buzzer.init();
buzzer.beep(2, 500);
#endif
logDebug("init complete");
}
void brewpiLoop(void)
{
static unsigned long lastUpdate = 0;
if(ticks.millis() - lastUpdate >= (1000)) { //update settings every second
lastUpdate = ticks.millis();
tempControl.updateTemperatures();
tempControl.detectPeaks();
tempControl.updatePID();
tempControl.updateState();
tempControl.updateOutputs();
#if BREWPI_MENU
if(rotaryEncoder.pushed()){
rotaryEncoder.resetPushed();
menu.pickSettingToChange();
}
#endif
// update the lcd for the chamber being displayed
display.printState();
display.printAllTemperatures();
display.printMode();
display.updateBacklight();
}
//listen for incoming serial connections while waiting to update
piLink.receive();
}
void loop() {
#if BREWPI_SIMULATE
simulateLoop();
#else
brewpiLoop();
#endif
}
<commit_msg>output a data point on every state transition for better analysis<commit_after>/*
* Copyright 2012-2013 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This Atmel Studio 6 project automatically includes all needed Arduino source files, you just have to point it to the right directories.
* To compile this project on your computer, you will have to set an environment variable to find your local Arduino installation.
* Set the variable ARDUINO_HOME to point to your local Arduino path, without trailing slash, e.g. 'D:\arduino-1.01'. Instructions on the wiki here:
* http://wiki.brewpi.com/index.php/Setting_up_the_brewpi-avr_Project
* 'ArduinoFunctions.cpp' includes all the source files from Arduino that are used. You might have to edit it if you are not using a Leonardo.
* That is all that is needed! No hassle with makefiles and compiling libraries.
*/
#include "Brewpi.h"
#include "Ticks.h"
#include "Display.h"
#include "TempControl.h"
#include "PiLink.h"
#include "Menu.h"
#include "Pins.h"
#include "RotaryEncoder.h"
#include "Buzzer.h"
#include "TempSensor.h"
#include "TempSensorMock.h"
#include "OneWireTempSensor.h"
#include "TempSensorExternal.h"
#include "Ticks.h"
#include "Sensor.h"
#include "FastDigitalPin.h"
#include "OneWireActuator.h"
#include "SettingsManager.h"
#if BREWPI_SIMULATE
#include "Simulator.h"
#endif
// global class objects static and defined in class cpp and h files
// instantiate and configure the sensors, actuators and controllers we want to use
void setup(void);
void loop (void);
/* Configure the counter and delay timer. The actual type of these will vary depending upon the environment.
* They are non-virtual to keep code size minimal, so typedefs and preprocessing are used to select the actual compile-time type used. */
TicksImpl ticks = TicksImpl(TICKS_IMPL_CONFIG);
DelayImpl wait = DelayImpl(DELAY_IMPL_CONFIG);
DisplayType realDisplay;
DisplayType DISPLAY_REF display = realDisplay;
void setup()
{
piLink.init();
logDebug("started");
tempControl.init();
settingsManager.loadSettings();
#if BREWPI_SIMULATE
simulator.step();
// initialize the filters with the assigned initial temp value
tempControl.beerSensor->init();
tempControl.fridgeSensor->init();
#endif
display.init();
display.printStationaryText();
display.printState();
rotaryEncoder.init();
#if BREWPI_BUZZER
buzzer.init();
buzzer.beep(2, 500);
#endif
logDebug("init complete");
}
void brewpiLoop(void)
{
static unsigned long lastUpdate = 0;
uint8_t oldState;
if(ticks.millis() - lastUpdate >= (1000)) { //update settings every second
lastUpdate = ticks.millis();
tempControl.updateTemperatures();
tempControl.detectPeaks();
tempControl.updatePID();
oldState = tempControl.getState();
tempControl.updateState();
if(oldState != tempControl.getState()){
piLink.printTemperatures(); // add a data point at every state transition
}
tempControl.updateOutputs();
#if BREWPI_MENU
if(rotaryEncoder.pushed()){
rotaryEncoder.resetPushed();
menu.pickSettingToChange();
}
#endif
// update the lcd for the chamber being displayed
display.printState();
display.printAllTemperatures();
display.printMode();
display.updateBacklight();
}
//listen for incoming serial connections while waiting to update
piLink.receive();
}
void loop() {
#if BREWPI_SIMULATE
simulateLoop();
#else
brewpiLoop();
#endif
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/in_process_webkit/indexed_db_context.h"
#include "content/browser/in_process_webkit/webkit_context.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/content_switches.h"
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kUnlimitedQuotaForIndexedDB);
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
class IndexedDBLevelDBBrowserTest : public IndexedDBBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kLevelDBIndexedDatabase);
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBLevelDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
// TODO(hans): If this starts failing, please disable and ping crbug.com/70773.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// TODO(hans): If this starts failing, please disable and ping crbug.com/70773.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
// TODO(hans): If this starts failing, please disable and ping crbug.com/70773.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
// TODO(hans): If this starts failing, please disable and ping crbug.com/70773.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// TODO(hans): If this starts failing, please disable and ping crbug.com/70773.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_84933.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
// Create test files.
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath indexeddb_dir = temp_dir.path().Append(
IndexedDBContext::kIndexedDBDirectory);
ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));
FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
file_name_1.append(IndexedDBContext::kIndexedDBExtension);
FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
file_name_2.append(IndexedDBContext::kIndexedDBExtension);
FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
WebKitContext *webkit_context = profile.GetWebKitContext();
webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<ThreadTestHelper> helper(
new ThreadTestHelper(BrowserThread::WEBKIT));
ASSERT_TRUE(helper->Run());
// Because we specified https for scheme to be skipped the second file
// should survive and the first go into vanity.
ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed,
DatabaseCallbacksTest) {
SimpleTest(
testUrl(FilePath(FILE_PATH_LITERAL("database_callbacks_first.html"))));
}
<commit_msg>Disable IndexedDB tests again (basically revert r89153), they are still flaky.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/in_process_webkit/indexed_db_context.h"
#include "content/browser/in_process_webkit/webkit_context.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/content_switches.h"
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kUnlimitedQuotaForIndexedDB);
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
class IndexedDBLevelDBBrowserTest : public IndexedDBBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kLevelDBIndexedDatabase);
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBLevelDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// Flaky: http://crbug.com/70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) {
const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_84933.html")));
// Just navigate to the URL. Test will crash if it fails.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
// Create test files.
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath indexeddb_dir = temp_dir.path().Append(
IndexedDBContext::kIndexedDBDirectory);
ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));
FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
file_name_1.append(IndexedDBContext::kIndexedDBExtension);
FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
file_name_2.append(IndexedDBContext::kIndexedDBExtension);
FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
WebKitContext *webkit_context = profile.GetWebKitContext();
webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<ThreadTestHelper> helper(
new ThreadTestHelper(BrowserThread::WEBKIT));
ASSERT_TRUE(helper->Run());
// Because we specified https for scheme to be skipped the second file
// should survive and the first go into vanity.
ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed,
DatabaseCallbacksTest) {
SimpleTest(
testUrl(FilePath(FILE_PATH_LITERAL("database_callbacks_first.html"))));
}
<|endoftext|> |
<commit_before>/*
* arcball.cpp
*
* Created on: 10.05.2012
* @author Ralph Schurade
*/
#include "arcball.h"
#include "../../data/models.h"
#include <QtDebug>
#include <math.h>
ArcBall::ArcBall( int width, int height ) :
CameraBase( width, height ),
Epsilon( 0.00001 ),
m_moveX( 0 ),
m_moveY( 0 ),
m_oldMoveX( 0 ),
m_oldMoveY( 0 ),
m_midClickX( 0 ),
m_midClickY( 0 )
{
m_currentRot.setToIdentity();
m_lastRot.setToIdentity();
}
ArcBall::~ArcBall()
{
}
// maps the specified mouse position to the sphere defined
// with center and radius. the resulting vector lies on the
// surface of the sphere.
QVector3D ArcBall::map_sphere( int x, int y )
{
float tmpx = ( x * m_adjust_width ) - 1.0;
float tmpy = 1.0 - ( y * m_adjust_height );
float length = ( tmpx * tmpx ) + ( tmpy * tmpy );
QVector3D bm;
if ( length > 1.0 )
{
float norm = 1.0 / sqrt( length );
bm.setX( tmpx * norm );
bm.setY( tmpy * norm );
bm.setZ( 0.0 );
}
else
{
bm.setX( tmpx );
bm.setY( tmpy );
bm.setZ( sqrt( 1.0 - length ) );
}
return bm;
}
/// sets the current position and calculates the current
/// rotation matrix.
void ArcBall::drag( int x, int y )
{
QVector3D v_to = map_sphere( x, y );
QVector3D perp = QVector3D::crossProduct( v_from, v_to);
if ( perp.length() > Epsilon )
{
q_current_rotation.setX( perp.x() );
q_current_rotation.setY( perp.y() );
q_current_rotation.setZ( perp.z() );;
q_current_rotation.setScalar( ( v_from.x() * v_to.x() ) + ( v_from.y() * v_to.y() ) + ( v_from.z() * v_to.z() ) );
}
else
{
q_current_rotation.setX( 0.0 );
q_current_rotation.setY( 0.0 );
q_current_rotation.setZ( 0.0 );
q_current_rotation.setScalar( 0.0 );
}
m_currentRot.setToIdentity();
m_currentRot.rotate( q_current_rotation );
m_currentRot = m_currentRot * m_lastRot ;
}
/// indicates the beginning of the dragging.
void ArcBall::click( int x, int y )
{
m_lastRot = m_currentRot;
v_mouse_down.setX( x );
v_mouse_down.setY( y );
v_mouse_down.setZ( 0.0 );
v_from = map_sphere( x, y );
}
void ArcBall::midClick( int x, int y )
{
m_midClickX = x;
m_midClickY = y;
m_oldMoveX = m_moveX;
m_oldMoveY = m_moveY;
}
void ArcBall::mouseWheel( float step )
{
if ( step < 0 )
{
m_zoom *= 1.1;
}
else
{
m_zoom /= 1.1;
m_zoom = qMax( 0.2f, m_zoom );
}
}
void ArcBall::midDrag( int x, int y )
{
m_moveX = m_oldMoveX + ( ( m_midClickX - x ) / 2 ) / m_zoom;
m_moveY = m_oldMoveY + ( ( m_midClickY - y ) / 2 ) / m_zoom;
}
void ArcBall::setRotCenter( float x, float y, float z )
{
m_rotCenter = QVector3D( -x, -y, -z );
}
void ArcBall::setView( Fn::Orient view )
{
m_zoom = 1.0;
m_moveX = 0;
m_moveY = 0;
m_oldMoveX = 0;
m_oldMoveY = 0;
m_currentRot.setToIdentity();
m_lastRot.setToIdentity();
QQuaternion rotx( sqrt(0.5), 0, 0, sqrt(0.5) );
QQuaternion rot_x( -sqrt(0.5), 0, 0, sqrt(0.5) );
QQuaternion roty( 0, sqrt(0.5), 0, sqrt(0.5) );
QQuaternion rot_y( 0, -sqrt(0.5), 0, sqrt(0.5) );
QQuaternion rotz( 0, 0, sqrt(0.5), sqrt(0.5) );
QQuaternion rot_z( 0, 0, -sqrt(0.5), sqrt(0.5) );
switch( view )
{
case Fn::Orient::NONE:
break;
case Fn::Orient::AXIAL:
break;
case Fn::Orient::CORONAL:
m_currentRot.rotate( rotz );
m_currentRot.rotate( rotx );
m_currentRot.rotate( rotx );
break;
case Fn::Orient::SAGITTAL:
m_currentRot.rotate( rot_x );
m_currentRot.rotate( rot_y );
break;
case Fn::Orient::AXIAL2:
m_currentRot.rotate( rot_y );
m_currentRot.rotate( roty );
break;
case Fn::Orient::CORONAL2:
m_currentRot.rotate( rotz );
break;
case Fn::Orient::SAGITTAL2:
m_currentRot.rotate( rotx );
m_currentRot.rotate( roty );
break;
}
}
/// returns the rotation matrix to be used directly
QMatrix4x4 ArcBall::getMVMat()
{
QMatrix4x4 mv;
mv.setToIdentity();
mv = m_currentRot * mv ;
float dist = Models::getGlobal( Fn::Property::G_ARCBALL_DISTANCE ).toFloat();
QVector3D halfMove( -m_moveX, m_moveY, -dist );
QMatrix4x4 tmp;
tmp.setToIdentity();
tmp.translate( halfMove );
tmp = tmp * m_currentRot;
mv = mv + tmp;
mv.translate( m_rotCenter );
return mv;
}
float ArcBall::getMoveX()
{
return m_moveX;
}
float ArcBall::getMoveY()
{
return m_moveY;
}
void ArcBall::setMoveX( float x )
{
m_moveX = x;
}
void ArcBall::setMoveY( float y )
{
m_moveY = y;
}
QList<QVariant> ArcBall::getState()
{
QList<QVariant> state;
state.push_back( "currentRot" );
state.push_back( m_currentRot );
state.push_back( "lastRot" );
state.push_back( m_lastRot );
state.push_back( "moveX" );
state.push_back( m_moveX );
state.push_back( "moveY" );
state.push_back( m_moveY );
state.push_back( "oldMoveX" );
state.push_back( m_oldMoveX );
state.push_back( "oldMoveY" );
state.push_back( m_oldMoveY );
state.push_back( "midClickX" );
state.push_back( m_midClickX );
state.push_back( "midClickY" );
state.push_back( m_midClickY );
state.push_back( "zoom" );
state.push_back( m_zoom );
state.push_back( "rotCenter" );
state.push_back( m_rotCenter );
state.push_back( "current_rotation" );
state.push_back( q_current_rotation );
return state;
}
void ArcBall::setState( QList<QVariant> state )
{
m_currentRot = state[0].value<QMatrix4x4>();
m_lastRot = state[1].value<QMatrix4x4>();
m_moveX = state[2].toInt();
m_moveY = state[3].toInt();
m_oldMoveX = state[4].toInt();
m_oldMoveY = state[5].toInt();
m_midClickX = state[6].toInt();
m_midClickY = state[7].toInt();
m_zoom = state[8].toFloat();
m_rotCenter = state[9].value<QVector3D>();
q_current_rotation = state[10].value<QQuaternion>();
}
void ArcBall::setState( QMap<QString, QVariant> state )
{
m_currentRot = state["currentRot"].value<QMatrix4x4>();
m_lastRot = state["lastRot"].value<QMatrix4x4>();
m_moveX = state["moveX"].toInt();
m_moveY = state["moveY"].toInt();
m_oldMoveX = state["oldMoveX"].toInt();
m_oldMoveY = state["oldMoveY"].toInt();
m_midClickX = state["midClickX"].toInt();
m_midClickY = state["midClickY"].toInt();
m_zoom = state["zoom"].toFloat();
m_rotCenter = state["rotCenter"].value<QVector3D>();
q_current_rotation = state["current_rotation"].value<QQuaternion>();
}
QQuaternion ArcBall::getRotation()
{
return mat2quat( m_currentRot );
}
void ArcBall::setRotation( QQuaternion quat )
{
m_currentRot.setToIdentity();
m_lastRot.setToIdentity();
m_currentRot.rotate( quat );
}
inline float SIGN(float x) {return (x >= 0.0f) ? +1.0f : -1.0f;}
inline float NORM(float a, float b, float c, float d) {return sqrt(a * a + b * b + c * c + d * d);}
QQuaternion ArcBall::mat2quat( QMatrix4x4 &mat )
{
double r11 = mat( 0, 0 );
double r12 = mat( 0, 1 );
double r13 = mat( 0, 2 );
double r21 = mat( 1, 0 );
double r22 = mat( 1, 1 );
double r23 = mat( 1, 2 );
double r31 = mat( 2, 0 );
double r32 = mat( 2, 1 );
double r33 = mat( 2, 2 );
double q0 = ( r11 + r22 + r33 + 1.0f ) / 4.0f;
double q1 = ( r11 - r22 - r33 + 1.0f ) / 4.0f;
double q2 = ( -r11 + r22 - r33 + 1.0f ) / 4.0f;
double q3 = ( -r11 - r22 + r33 + 1.0f ) / 4.0f;
if ( q0 < 0.0f )
q0 = 0.0f;
if ( q1 < 0.0f )
q1 = 0.0f;
if ( q2 < 0.0f )
q2 = 0.0f;
if ( q3 < 0.0f )
q3 = 0.0f;
q0 = sqrt( q0 );
q1 = sqrt( q1 );
q2 = sqrt( q2 );
q3 = sqrt( q3 );
if ( q0 >= q1 && q0 >= q2 && q0 >= q3 )
{
q0 *= +1.0f;
q1 *= SIGN( r32 - r23 );
q2 *= SIGN( r13 - r31 );
q3 *= SIGN( r21 - r12 );
}
else if ( q1 >= q0 && q1 >= q2 && q1 >= q3 )
{
q0 *= SIGN( r32 - r23 );
q1 *= +1.0f;
q2 *= SIGN( r21 + r12 );
q3 *= SIGN( r13 + r31 );
}
else if ( q2 >= q0 && q2 >= q1 && q2 >= q3 )
{
q0 *= SIGN( r13 - r31 );
q1 *= SIGN( r21 + r12 );
q2 *= +1.0f;
q3 *= SIGN( r32 + r23 );
}
else if ( q3 >= q0 && q3 >= q1 && q3 >= q2 )
{
q0 *= SIGN( r21 - r12 );
q1 *= SIGN( r31 + r13 );
q2 *= SIGN( r32 + r23 );
q3 *= +1.0f;
}
else
{
printf( "coding error\n" );
}
double r = NORM( q0, q1, q2, q3 );
q0 /= r;
q1 /= r;
q2 /= r;
q3 /= r;
return QQuaternion( q0, q1, q2, q3 );
}
QVector3D ArcBall::getRotCenter()
{
return m_rotCenter;
}
<commit_msg>reversed mousewheel zoom<commit_after>/*
* arcball.cpp
*
* Created on: 10.05.2012
* @author Ralph Schurade
*/
#include "arcball.h"
#include "../../data/models.h"
#include <QtDebug>
#include <math.h>
ArcBall::ArcBall( int width, int height ) :
CameraBase( width, height ),
Epsilon( 0.00001 ),
m_moveX( 0 ),
m_moveY( 0 ),
m_oldMoveX( 0 ),
m_oldMoveY( 0 ),
m_midClickX( 0 ),
m_midClickY( 0 )
{
m_currentRot.setToIdentity();
m_lastRot.setToIdentity();
}
ArcBall::~ArcBall()
{
}
// maps the specified mouse position to the sphere defined
// with center and radius. the resulting vector lies on the
// surface of the sphere.
QVector3D ArcBall::map_sphere( int x, int y )
{
float tmpx = ( x * m_adjust_width ) - 1.0;
float tmpy = 1.0 - ( y * m_adjust_height );
float length = ( tmpx * tmpx ) + ( tmpy * tmpy );
QVector3D bm;
if ( length > 1.0 )
{
float norm = 1.0 / sqrt( length );
bm.setX( tmpx * norm );
bm.setY( tmpy * norm );
bm.setZ( 0.0 );
}
else
{
bm.setX( tmpx );
bm.setY( tmpy );
bm.setZ( sqrt( 1.0 - length ) );
}
return bm;
}
/// sets the current position and calculates the current
/// rotation matrix.
void ArcBall::drag( int x, int y )
{
QVector3D v_to = map_sphere( x, y );
QVector3D perp = QVector3D::crossProduct( v_from, v_to);
if ( perp.length() > Epsilon )
{
q_current_rotation.setX( perp.x() );
q_current_rotation.setY( perp.y() );
q_current_rotation.setZ( perp.z() );;
q_current_rotation.setScalar( ( v_from.x() * v_to.x() ) + ( v_from.y() * v_to.y() ) + ( v_from.z() * v_to.z() ) );
}
else
{
q_current_rotation.setX( 0.0 );
q_current_rotation.setY( 0.0 );
q_current_rotation.setZ( 0.0 );
q_current_rotation.setScalar( 0.0 );
}
m_currentRot.setToIdentity();
m_currentRot.rotate( q_current_rotation );
m_currentRot = m_currentRot * m_lastRot ;
}
/// indicates the beginning of the dragging.
void ArcBall::click( int x, int y )
{
m_lastRot = m_currentRot;
v_mouse_down.setX( x );
v_mouse_down.setY( y );
v_mouse_down.setZ( 0.0 );
v_from = map_sphere( x, y );
}
void ArcBall::midClick( int x, int y )
{
m_midClickX = x;
m_midClickY = y;
m_oldMoveX = m_moveX;
m_oldMoveY = m_moveY;
}
void ArcBall::mouseWheel( float step )
{
if ( step < 0 )
{
m_zoom /= 1.1;
m_zoom = qMax( 0.2f, m_zoom );
}
else
{
m_zoom *= 1.1;
}
}
void ArcBall::midDrag( int x, int y )
{
m_moveX = m_oldMoveX + ( ( m_midClickX - x ) / 2 ) / m_zoom;
m_moveY = m_oldMoveY + ( ( m_midClickY - y ) / 2 ) / m_zoom;
}
void ArcBall::setRotCenter( float x, float y, float z )
{
m_rotCenter = QVector3D( -x, -y, -z );
}
void ArcBall::setView( Fn::Orient view )
{
m_zoom = 1.0;
m_moveX = 0;
m_moveY = 0;
m_oldMoveX = 0;
m_oldMoveY = 0;
m_currentRot.setToIdentity();
m_lastRot.setToIdentity();
QQuaternion rotx( sqrt(0.5), 0, 0, sqrt(0.5) );
QQuaternion rot_x( -sqrt(0.5), 0, 0, sqrt(0.5) );
QQuaternion roty( 0, sqrt(0.5), 0, sqrt(0.5) );
QQuaternion rot_y( 0, -sqrt(0.5), 0, sqrt(0.5) );
QQuaternion rotz( 0, 0, sqrt(0.5), sqrt(0.5) );
QQuaternion rot_z( 0, 0, -sqrt(0.5), sqrt(0.5) );
switch( view )
{
case Fn::Orient::NONE:
break;
case Fn::Orient::AXIAL:
break;
case Fn::Orient::CORONAL:
m_currentRot.rotate( rotz );
m_currentRot.rotate( rotx );
m_currentRot.rotate( rotx );
break;
case Fn::Orient::SAGITTAL:
m_currentRot.rotate( rot_x );
m_currentRot.rotate( rot_y );
break;
case Fn::Orient::AXIAL2:
m_currentRot.rotate( rot_y );
m_currentRot.rotate( roty );
break;
case Fn::Orient::CORONAL2:
m_currentRot.rotate( rotz );
break;
case Fn::Orient::SAGITTAL2:
m_currentRot.rotate( rotx );
m_currentRot.rotate( roty );
break;
}
}
/// returns the rotation matrix to be used directly
QMatrix4x4 ArcBall::getMVMat()
{
QMatrix4x4 mv;
mv.setToIdentity();
mv = m_currentRot * mv ;
float dist = Models::getGlobal( Fn::Property::G_ARCBALL_DISTANCE ).toFloat();
QVector3D halfMove( -m_moveX, m_moveY, -dist );
QMatrix4x4 tmp;
tmp.setToIdentity();
tmp.translate( halfMove );
tmp = tmp * m_currentRot;
mv = mv + tmp;
mv.translate( m_rotCenter );
return mv;
}
float ArcBall::getMoveX()
{
return m_moveX;
}
float ArcBall::getMoveY()
{
return m_moveY;
}
void ArcBall::setMoveX( float x )
{
m_moveX = x;
}
void ArcBall::setMoveY( float y )
{
m_moveY = y;
}
QList<QVariant> ArcBall::getState()
{
QList<QVariant> state;
state.push_back( "currentRot" );
state.push_back( m_currentRot );
state.push_back( "lastRot" );
state.push_back( m_lastRot );
state.push_back( "moveX" );
state.push_back( m_moveX );
state.push_back( "moveY" );
state.push_back( m_moveY );
state.push_back( "oldMoveX" );
state.push_back( m_oldMoveX );
state.push_back( "oldMoveY" );
state.push_back( m_oldMoveY );
state.push_back( "midClickX" );
state.push_back( m_midClickX );
state.push_back( "midClickY" );
state.push_back( m_midClickY );
state.push_back( "zoom" );
state.push_back( m_zoom );
state.push_back( "rotCenter" );
state.push_back( m_rotCenter );
state.push_back( "current_rotation" );
state.push_back( q_current_rotation );
return state;
}
void ArcBall::setState( QList<QVariant> state )
{
m_currentRot = state[0].value<QMatrix4x4>();
m_lastRot = state[1].value<QMatrix4x4>();
m_moveX = state[2].toInt();
m_moveY = state[3].toInt();
m_oldMoveX = state[4].toInt();
m_oldMoveY = state[5].toInt();
m_midClickX = state[6].toInt();
m_midClickY = state[7].toInt();
m_zoom = state[8].toFloat();
m_rotCenter = state[9].value<QVector3D>();
q_current_rotation = state[10].value<QQuaternion>();
}
void ArcBall::setState( QMap<QString, QVariant> state )
{
m_currentRot = state["currentRot"].value<QMatrix4x4>();
m_lastRot = state["lastRot"].value<QMatrix4x4>();
m_moveX = state["moveX"].toInt();
m_moveY = state["moveY"].toInt();
m_oldMoveX = state["oldMoveX"].toInt();
m_oldMoveY = state["oldMoveY"].toInt();
m_midClickX = state["midClickX"].toInt();
m_midClickY = state["midClickY"].toInt();
m_zoom = state["zoom"].toFloat();
m_rotCenter = state["rotCenter"].value<QVector3D>();
q_current_rotation = state["current_rotation"].value<QQuaternion>();
}
QQuaternion ArcBall::getRotation()
{
return mat2quat( m_currentRot );
}
void ArcBall::setRotation( QQuaternion quat )
{
m_currentRot.setToIdentity();
m_lastRot.setToIdentity();
m_currentRot.rotate( quat );
}
inline float SIGN(float x) {return (x >= 0.0f) ? +1.0f : -1.0f;}
inline float NORM(float a, float b, float c, float d) {return sqrt(a * a + b * b + c * c + d * d);}
QQuaternion ArcBall::mat2quat( QMatrix4x4 &mat )
{
double r11 = mat( 0, 0 );
double r12 = mat( 0, 1 );
double r13 = mat( 0, 2 );
double r21 = mat( 1, 0 );
double r22 = mat( 1, 1 );
double r23 = mat( 1, 2 );
double r31 = mat( 2, 0 );
double r32 = mat( 2, 1 );
double r33 = mat( 2, 2 );
double q0 = ( r11 + r22 + r33 + 1.0f ) / 4.0f;
double q1 = ( r11 - r22 - r33 + 1.0f ) / 4.0f;
double q2 = ( -r11 + r22 - r33 + 1.0f ) / 4.0f;
double q3 = ( -r11 - r22 + r33 + 1.0f ) / 4.0f;
if ( q0 < 0.0f )
q0 = 0.0f;
if ( q1 < 0.0f )
q1 = 0.0f;
if ( q2 < 0.0f )
q2 = 0.0f;
if ( q3 < 0.0f )
q3 = 0.0f;
q0 = sqrt( q0 );
q1 = sqrt( q1 );
q2 = sqrt( q2 );
q3 = sqrt( q3 );
if ( q0 >= q1 && q0 >= q2 && q0 >= q3 )
{
q0 *= +1.0f;
q1 *= SIGN( r32 - r23 );
q2 *= SIGN( r13 - r31 );
q3 *= SIGN( r21 - r12 );
}
else if ( q1 >= q0 && q1 >= q2 && q1 >= q3 )
{
q0 *= SIGN( r32 - r23 );
q1 *= +1.0f;
q2 *= SIGN( r21 + r12 );
q3 *= SIGN( r13 + r31 );
}
else if ( q2 >= q0 && q2 >= q1 && q2 >= q3 )
{
q0 *= SIGN( r13 - r31 );
q1 *= SIGN( r21 + r12 );
q2 *= +1.0f;
q3 *= SIGN( r32 + r23 );
}
else if ( q3 >= q0 && q3 >= q1 && q3 >= q2 )
{
q0 *= SIGN( r21 - r12 );
q1 *= SIGN( r31 + r13 );
q2 *= SIGN( r32 + r23 );
q3 *= +1.0f;
}
else
{
printf( "coding error\n" );
}
double r = NORM( q0, q1, q2, q3 );
q0 /= r;
q1 /= r;
q2 /= r;
q3 /= r;
return QQuaternion( q0, q1, q2, q3 );
}
QVector3D ArcBall::getRotCenter()
{
return m_rotCenter;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/gtk_key_bindings_handler.h"
#include <gdk/gdkkeysyms.h>
#include <string>
#include <utility>
#include <vector>
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/edit_command.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "testing/gtest/include/gtest/gtest.h"
class GtkKeyBindingsHandlerTest : public testing::Test {
protected:
struct EditCommand {
const char* name;
const char* value;
};
GtkKeyBindingsHandlerTest()
: window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)),
handler_(NULL) {
FilePath gtkrc;
PathService::Get(chrome::DIR_TEST_DATA, >krc);
gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc");
CHECK(file_util::PathExists(gtkrc)) << gtkrc.value();
gtk_rc_parse(gtkrc.value().c_str());
GtkWidget* fixed = gtk_fixed_new();
handler_ = new GtkKeyBindingsHandler(fixed);
gtk_container_add(GTK_CONTAINER(window_), fixed);
gtk_widget_show(fixed);
gtk_widget_show(window_);
}
~GtkKeyBindingsHandlerTest() {
gtk_widget_destroy(window_);
delete handler_;
}
NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) {
GdkKeymap* keymap =
gdk_keymap_get_for_display(gtk_widget_get_display(window_));
CHECK(keymap != NULL);
GdkKeymapKey *keys = NULL;
gint n_keys = 0;
if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) {
GdkEventKey event;
event.type = GDK_KEY_PRESS;
event.window = NULL;
event.send_event = 0;
event.time = 0;
event.state = state;
event.keyval = keyval;
event.length = 0;
event.string = NULL;
event.hardware_keycode = keys[0].keycode;
event.group = keys[0].group;
event.is_modifier = 0;
g_free(keys);
LOG(INFO) << "Create key event: keyval:" << keyval
<< " hardware_keycode:" << event.hardware_keycode
<< " group:" << static_cast<unsigned int>(event.group);
return NativeWebKeyboardEvent(&event);
}
CHECK(false) << "Failed to create key event for keyval:" << keyval;
return NativeWebKeyboardEvent();
}
void TestKeyBinding(const NativeWebKeyboardEvent& event,
const EditCommand expected_result[],
size_t size) {
EditCommands result;
ASSERT_TRUE(handler_->Match(event, &result));
ASSERT_EQ(size, result.size());
for (size_t i = 0; i < size; ++i) {
ASSERT_STREQ(expected_result[i].name, result[i].name.c_str());
ASSERT_STREQ(expected_result[i].value, result[i].value.c_str());
}
}
protected:
GtkWidget* window_;
GtkKeyBindingsHandler* handler_;
};
// Does not work in a chroot. See bug 60363.
TEST_F(GtkKeyBindingsHandlerTest, FAILS_MoveCursor) {
static const EditCommand kEditCommands[] = {
// "move-cursor" (logical-positions, -2, 0)
{ "MoveBackward", "" },
{ "MoveBackward", "" },
// "move-cursor" (logical-positions, 2, 0)
{ "MoveForward", "" },
{ "MoveForward", "" },
// "move-cursor" (visual-positions, -1, 1)
{ "MoveLeftAndModifySelection", "" },
// "move-cursor" (visual-positions, 1, 1)
{ "MoveRightAndModifySelection", "" },
// "move-cursor" (words, -1, 0)
{ "MoveWordBackward", "" },
// "move-cursor" (words, 1, 0)
{ "MoveWordForward", "" },
// "move-cursor" (display-lines, -1, 0)
{ "MoveUp", "" },
// "move-cursor" (display-lines, 1, 0)
{ "MoveDown", "" },
// "move-cursor" (display-line-ends, -1, 0)
{ "MoveToBeginningOfLine", "" },
// "move-cursor" (display-line-ends, 1, 0)
{ "MoveToEndOfLine", "" },
// "move-cursor" (paragraph-ends, -1, 0)
{ "MoveToBeginningOfParagraph", "" },
// "move-cursor" (paragraph-ends, 1, 0)
{ "MoveToEndOfParagraph", "" },
// "move-cursor" (pages, -1, 0)
{ "MovePageUp", "" },
// "move-cursor" (pages, 1, 0)
{ "MovePageDown", "" },
// "move-cursor" (buffer-ends, -1, 0)
{ "MoveToBeginningOfDocument", "" },
// "move-cursor" (buffer-ends, 1, 0)
{ "MoveToEndOfDocument", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK),
kEditCommands, arraysize(kEditCommands));
}
// Does not work in a chroot. See bug 60363.
TEST_F(GtkKeyBindingsHandlerTest, FAILS_DeleteFromCursor) {
static const EditCommand kEditCommands[] = {
// "delete-from-cursor" (chars, -2)
{ "DeleteBackward", "" },
{ "DeleteBackward", "" },
// "delete-from-cursor" (chars, 2)
{ "DeleteForward", "" },
{ "DeleteForward", "" },
// "delete-from-cursor" (word-ends, -1)
{ "DeleteWordBackward", "" },
// "delete-from-cursor" (word-ends, 1)
{ "DeleteWordForward", "" },
// "delete-from-cursor" (words, -1)
{ "MoveWordBackward", "" },
{ "DeleteWordForward", "" },
// "delete-from-cursor" (words, 1)
{ "MoveWordForward", "" },
{ "DeleteWordBackward", "" },
// "delete-from-cursor" (display-lines, -1)
{ "MoveToBeginningOfLine", "" },
{ "DeleteToEndOfLine", "" },
// "delete-from-cursor" (display-lines, 1)
{ "MoveToBeginningOfLine", "" },
{ "DeleteToEndOfLine", "" },
// "delete-from-cursor" (display-line-ends, -1)
{ "DeleteToBeginningOfLine", "" },
// "delete-from-cursor" (display-line-ends, 1)
{ "DeleteToEndOfLine", "" },
// "delete-from-cursor" (paragraph-ends, -1)
{ "DeleteToBeginningOfParagraph", "" },
// "delete-from-cursor" (paragraph-ends, 1)
{ "DeleteToEndOfParagraph", "" },
// "delete-from-cursor" (paragraphs, -1)
{ "MoveToBeginningOfParagraph", "" },
{ "DeleteToEndOfParagraph", "" },
// "delete-from-cursor" (paragraphs, 1)
{ "MoveToBeginningOfParagraph", "" },
{ "DeleteToEndOfParagraph", "" },
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK),
kEditCommands, arraysize(kEditCommands));
}
// Does not work in a chroot. See bug 60363.
TEST_F(GtkKeyBindingsHandlerTest, FAILS_OtherActions) {
static const EditCommand kBackspace[] = {
{ "DeleteBackward", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK),
kBackspace, arraysize(kBackspace));
static const EditCommand kCopyClipboard[] = {
{ "Copy", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK),
kCopyClipboard, arraysize(kCopyClipboard));
static const EditCommand kCutClipboard[] = {
{ "Cut", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK),
kCutClipboard, arraysize(kCutClipboard));
static const EditCommand kInsertAtCursor[] = {
{ "InsertText", "hello" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK),
kInsertAtCursor, arraysize(kInsertAtCursor));
static const EditCommand kPasteClipboard[] = {
{ "Paste", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK),
kPasteClipboard, arraysize(kPasteClipboard));
static const EditCommand kSelectAll[] = {
{ "Unselect", "" },
{ "SelectAll", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK),
kSelectAll, arraysize(kSelectAll));
static const EditCommand kSetAnchor[] = {
{ "SetMark", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK),
kSetAnchor, arraysize(kSetAnchor));
}
<commit_msg>Remove all CHECK() in gtk_key_bindings_handler_unittest.cc<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/gtk_key_bindings_handler.h"
#include <gdk/gdkkeysyms.h>
#include <string>
#include <utility>
#include <vector>
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/edit_command.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "testing/gtest/include/gtest/gtest.h"
class GtkKeyBindingsHandlerTest : public testing::Test {
protected:
struct EditCommand {
const char* name;
const char* value;
};
GtkKeyBindingsHandlerTest()
: window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)),
handler_(NULL) {
FilePath gtkrc;
PathService::Get(chrome::DIR_TEST_DATA, >krc);
gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc");
gtk_rc_parse(gtkrc.value().c_str());
GtkWidget* fixed = gtk_fixed_new();
handler_ = new GtkKeyBindingsHandler(fixed);
gtk_container_add(GTK_CONTAINER(window_), fixed);
gtk_widget_show(fixed);
gtk_widget_show(window_);
}
~GtkKeyBindingsHandlerTest() {
gtk_widget_destroy(window_);
delete handler_;
}
NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) {
GdkKeymap* keymap =
gdk_keymap_get_for_display(gtk_widget_get_display(window_));
GdkKeymapKey *keys = NULL;
gint n_keys = 0;
if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) {
GdkEventKey event;
event.type = GDK_KEY_PRESS;
event.window = NULL;
event.send_event = 0;
event.time = 0;
event.state = state;
event.keyval = keyval;
event.length = 0;
event.string = NULL;
event.hardware_keycode = keys[0].keycode;
event.group = keys[0].group;
event.is_modifier = 0;
g_free(keys);
return NativeWebKeyboardEvent(&event);
}
LOG(ERROR) << "Failed to create key event for keyval:" << keyval;
return NativeWebKeyboardEvent();
}
void TestKeyBinding(const NativeWebKeyboardEvent& event,
const EditCommand expected_result[],
size_t size) {
EditCommands result;
ASSERT_TRUE(handler_->Match(event, &result));
ASSERT_EQ(size, result.size());
for (size_t i = 0; i < size; ++i) {
ASSERT_STREQ(expected_result[i].name, result[i].name.c_str());
ASSERT_STREQ(expected_result[i].value, result[i].value.c_str());
}
}
protected:
GtkWidget* window_;
GtkKeyBindingsHandler* handler_;
};
// Does not work in a chroot. See bug 60363.
TEST_F(GtkKeyBindingsHandlerTest, FAILS_MoveCursor) {
static const EditCommand kEditCommands[] = {
// "move-cursor" (logical-positions, -2, 0)
{ "MoveBackward", "" },
{ "MoveBackward", "" },
// "move-cursor" (logical-positions, 2, 0)
{ "MoveForward", "" },
{ "MoveForward", "" },
// "move-cursor" (visual-positions, -1, 1)
{ "MoveLeftAndModifySelection", "" },
// "move-cursor" (visual-positions, 1, 1)
{ "MoveRightAndModifySelection", "" },
// "move-cursor" (words, -1, 0)
{ "MoveWordBackward", "" },
// "move-cursor" (words, 1, 0)
{ "MoveWordForward", "" },
// "move-cursor" (display-lines, -1, 0)
{ "MoveUp", "" },
// "move-cursor" (display-lines, 1, 0)
{ "MoveDown", "" },
// "move-cursor" (display-line-ends, -1, 0)
{ "MoveToBeginningOfLine", "" },
// "move-cursor" (display-line-ends, 1, 0)
{ "MoveToEndOfLine", "" },
// "move-cursor" (paragraph-ends, -1, 0)
{ "MoveToBeginningOfParagraph", "" },
// "move-cursor" (paragraph-ends, 1, 0)
{ "MoveToEndOfParagraph", "" },
// "move-cursor" (pages, -1, 0)
{ "MovePageUp", "" },
// "move-cursor" (pages, 1, 0)
{ "MovePageDown", "" },
// "move-cursor" (buffer-ends, -1, 0)
{ "MoveToBeginningOfDocument", "" },
// "move-cursor" (buffer-ends, 1, 0)
{ "MoveToEndOfDocument", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK),
kEditCommands, arraysize(kEditCommands));
}
// Does not work in a chroot. See bug 60363.
TEST_F(GtkKeyBindingsHandlerTest, FAILS_DeleteFromCursor) {
static const EditCommand kEditCommands[] = {
// "delete-from-cursor" (chars, -2)
{ "DeleteBackward", "" },
{ "DeleteBackward", "" },
// "delete-from-cursor" (chars, 2)
{ "DeleteForward", "" },
{ "DeleteForward", "" },
// "delete-from-cursor" (word-ends, -1)
{ "DeleteWordBackward", "" },
// "delete-from-cursor" (word-ends, 1)
{ "DeleteWordForward", "" },
// "delete-from-cursor" (words, -1)
{ "MoveWordBackward", "" },
{ "DeleteWordForward", "" },
// "delete-from-cursor" (words, 1)
{ "MoveWordForward", "" },
{ "DeleteWordBackward", "" },
// "delete-from-cursor" (display-lines, -1)
{ "MoveToBeginningOfLine", "" },
{ "DeleteToEndOfLine", "" },
// "delete-from-cursor" (display-lines, 1)
{ "MoveToBeginningOfLine", "" },
{ "DeleteToEndOfLine", "" },
// "delete-from-cursor" (display-line-ends, -1)
{ "DeleteToBeginningOfLine", "" },
// "delete-from-cursor" (display-line-ends, 1)
{ "DeleteToEndOfLine", "" },
// "delete-from-cursor" (paragraph-ends, -1)
{ "DeleteToBeginningOfParagraph", "" },
// "delete-from-cursor" (paragraph-ends, 1)
{ "DeleteToEndOfParagraph", "" },
// "delete-from-cursor" (paragraphs, -1)
{ "MoveToBeginningOfParagraph", "" },
{ "DeleteToEndOfParagraph", "" },
// "delete-from-cursor" (paragraphs, 1)
{ "MoveToBeginningOfParagraph", "" },
{ "DeleteToEndOfParagraph", "" },
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK),
kEditCommands, arraysize(kEditCommands));
}
// Does not work in a chroot. See bug 60363.
TEST_F(GtkKeyBindingsHandlerTest, FAILS_OtherActions) {
static const EditCommand kBackspace[] = {
{ "DeleteBackward", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK),
kBackspace, arraysize(kBackspace));
static const EditCommand kCopyClipboard[] = {
{ "Copy", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK),
kCopyClipboard, arraysize(kCopyClipboard));
static const EditCommand kCutClipboard[] = {
{ "Cut", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK),
kCutClipboard, arraysize(kCutClipboard));
static const EditCommand kInsertAtCursor[] = {
{ "InsertText", "hello" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK),
kInsertAtCursor, arraysize(kInsertAtCursor));
static const EditCommand kPasteClipboard[] = {
{ "Paste", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK),
kPasteClipboard, arraysize(kPasteClipboard));
static const EditCommand kSelectAll[] = {
{ "Unselect", "" },
{ "SelectAll", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK),
kSelectAll, arraysize(kSelectAll));
static const EditCommand kSetAnchor[] = {
{ "SetMark", "" }
};
TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK),
kSetAnchor, arraysize(kSetAnchor));
}
<|endoftext|> |
<commit_before>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// 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.
// A driver for Google JS Test test. Looks for a file named
// "*-gjstest-scripts.binarypb" in the directory identified by TEST_SRCDIR, and
// runs its scripts and then any tests that its scripts registered.
//
// TODO(jacobsa): These should probably be changed into flags that the user
// gives explicitly. Maybe this should be combined with the compiler tool too.
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include "base/integral_types.h"
#include "base/logging.h"
#include "file/file_utils.h"
#include "gjstest/internal/compiler/compiler.pb.h"
#include "gjstest/internal/driver/cpp/driver.h"
#include "strings/strutil.h"
DEFINE_string(filter, "", "Regular expression for test names to run.");
namespace gjstest {
// Look for a file with the given suffix in the supplied directory, crashing if
// there is not exactly one such file. Return the path to the single file.
static string FindSingleFileWithSuffix(
const string& directory,
const string& suffix) {
vector<string> files;
FindFiles(directory, &files);
string result;
for (uint32 i = 0; i < files.size(); ++i) {
const string& path = files[i];
if (HasSuffixString(path, suffix)) {
CHECK(result.empty())
<< "Duplicate match for suffix: " << suffix << "\n"
<< "1st match: " << result << "\n"
<< "2nd match: " << path << "\n";
result = path;
}
}
CHECK(!result.empty()) << "Couldn't find file with suffix: " << suffix;
return result;
}
static bool Run() {
// Find the file containing the scripts to be run, and load its contents.
const string scripts_path =
FindSingleFileWithSuffix(
StringFromEnv("TEST_SRCDIR", ""),
"-gjstest-scripts.binarypb");
NamedScripts scripts;
CHECK(scripts.ParseFromString(ReadFileOrDie(scripts_path)))
<< "Couldn't parse NamedScripts proto.";
// Run the tests.
string output;
string xml;
const bool success = RunTests(scripts, FLAGS_filter, &output, &xml);
// Log the output.
LOG(ERROR) << output;
// Write out the XML file to the appropriate place.
const string xml_path = StringFromEnv("XML_OUTPUT_FILE", "");
WriteStringToFileOrDie(xml, xml_path);
return success;
}
} // namespace gjstest
int main(int argc, char** argv) {
// TODO(jacobsa): Initialize flags and logging.
// Turn off timestamp and file number junk in the output of LOG().
FLAGS_log_prefix = false;
return gjstest::Run() ? 0 : 1;
}
<commit_msg>Fixed more errors.<commit_after>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// 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.
// A driver for Google JS Test test. Looks for a file named
// "*-gjstest-scripts.binarypb" in the directory identified by TEST_SRCDIR, and
// runs its scripts and then any tests that its scripts registered.
//
// TODO(jacobsa): These should probably be changed into flags that the user
// gives explicitly. Maybe this should be combined with the compiler tool too.
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include "base/integral_types.h"
#include "base/logging.h"
#include "file/file_utils.h"
#include "gjstest/internal/compiler/compiler.pb.h"
#include "gjstest/internal/driver/cpp/driver.h"
#include "strings/strutil.h"
DEFINE_string(filter, "", "Regular expression for test names to run.");
namespace gjstest {
// Look for a file with the given suffix in the supplied directory, crashing if
// there is not exactly one such file. Return the path to the single file.
static string FindSingleFileWithSuffix(
const string& directory,
const string& suffix) {
vector<string> files;
FindFiles(directory, &files);
string result;
for (uint32 i = 0; i < files.size(); ++i) {
const string& path = files[i];
if (HasSuffixString(path, suffix)) {
CHECK(result.empty())
<< "Duplicate match for suffix: " << suffix << "\n"
<< "1st match: " << result << "\n"
<< "2nd match: " << path << "\n";
result = path;
}
}
CHECK(!result.empty()) << "Couldn't find file with suffix: " << suffix;
return result;
}
static bool Run() {
// Find the file containing the scripts to be run, and load its contents.
const string scripts_path =
FindSingleFileWithSuffix(
google::StringFromEnv("TEST_SRCDIR", ""),
"-gjstest-scripts.binarypb");
NamedScripts scripts;
CHECK(scripts.ParseFromString(ReadFileOrDie(scripts_path)))
<< "Couldn't parse NamedScripts proto.";
// Run the tests.
string output;
string xml;
const bool success = RunTests(scripts, FLAGS_filter, &output, &xml);
// Log the output.
LOG(ERROR) << output;
// Write out the XML file to the appropriate place.
const string xml_path = google::StringFromEnv("XML_OUTPUT_FILE", "");
WriteStringToFileOrDie(xml, xml_path);
return success;
}
} // namespace gjstest
int main(int argc, char** argv) {
// TODO(jacobsa): Initialize flags and logging.
// Turn off timestamp and file number junk in the output of LOG().
FLAGS_log_prefix = false;
return gjstest::Run() ? 0 : 1;
}
<|endoftext|> |
<commit_before>#include "model_item.h"
#include <QDebug>
/////////////////////////////////////////////////////////
void ModelItem::init(bool isFolder) {
names = 0;
childItems = QList<ModelItem*>();
if (isFolder) {
state = new ModelItemState(STATE_UNPROCESSED);
state -> setProceed();
folders = new QHash<QString, ModelItem *>();
} else {
folders = 0;
}
}
void ModelItem::rootItemInit() {
path = QString();
name = QString("--(O_o)--");
extension = QString();
}
ModelItem::ModelItem() {
init(true);
rootItemInit();
parentItem = 0;
}
ModelItem::ModelItem(QJsonObject * attrs, ModelItem *parent) {
init(true);
parentItem = parent;
if (attrs -> contains("p")) {
name = path = attrs -> value("p").toString();
if (parent != 0)
parent -> folders -> insert(name, this);
} else {
name = attrs -> value("n").toString();
state = new ModelItemState(attrs -> value("s").toInt());
extension = attrs -> value("e").toString();
}
if (attrs -> contains("c")) {
QJsonArray ar = attrs -> value("c").toArray();
QJsonObject iter_obj;
foreach(QJsonValue obj, ar) {
iter_obj = obj.toObject();
new ModelItem(&iter_obj, this);
}
}
if (parent != 0) {
parent -> appendChild(this);
} else {
rootItemInit();
}
}
ModelItem::ModelItem(QString file_path, ModelItem *parent, int init_state) {
state = new ModelItemState(init_state);
parentItem = parent;
if (!state -> isUnprocessed()) {
init(false);
path = file_path.section('/', 0, -2);
name = file_path.section('/', -1, -1);
extension = name.section('.', -1, -1);
name = name.section('.', 0, -2);
} else {
init(true);
name = path = file_path;
extension = QString();
if (parent != 0)
parent -> folders -> insert(name, this);
}
if (parent != 0) { parent -> appendChild(this);}
}
ModelItem::~ModelItem() {
qDeleteAll(childItems);
delete state;
if (folders != 0) {
delete folders;
}
if (names != 0)
delete names;
if (parentItem != 0)
delete parentItem;
}
/////////////////////////////////////////////////////////
ModelItem *ModelItem::parent() {
return parentItem;
}
/////////////////////////////////////////////////////////
ModelItem *ModelItem::child(int row) {
return childItems.value(row);
}
int ModelItem::childCount() const {
return childItems.count();
}
void ModelItem::appendChild(ModelItem *item) {
childItems.append(item);
}
bool ModelItem::insertChildren(int position, int count, int /*columns*/) {
if (position < 0 || position > childItems.size())
return false;
for (int row = 0; row < count; ++row) {
// QVector<QVariant> data(columns);
// ModelItem *item = new ModelItem(data, this);
ModelItem *item = new ModelItem(QString("BLA"), this);
childItems.insert(position, item);
}
return true;
}
bool ModelItem::removeChildren(int position, int count)
{
if (position < 0 || position + count > childItems.size())
return false;
for (int row = 0; row < count; ++row)
delete childItems.takeAt(position);
return true;
}
/////////////////////////////////////////////////////////
int ModelItem::column() const {
return 0;
}
int ModelItem::columnCount() const {
return 1;
// if (parentItem == 0)
// return 0;
// else
// return 1;
}
bool ModelItem::removeColumns(int /*position*/, int /*columns*/) {
// if (position < 0 || position + columns > itemData.size())
// return false;
// for (int column = 0; column < columns; ++column)
// itemData.remove(position);
// foreach (TreeItem *child, childItems)
// child->removeColumns(position, columns);
return true;
}
bool ModelItem::insertColumns(int /*position*/, int /*columns*/) {
// if (position < 0 || position > itemData.size())
// return false;
// for (int column = 0; column < columns; ++column)
// itemData.insert(position, QVariant());
// foreach (TreeItem *child, childItems)
// child->insertColumns(position, columns);
return true;
}
/////////////////////////////////////////////////////////
int ModelItem::row() const {
if (parentItem)
return parentItem->childItems.indexOf(const_cast<ModelItem*>(this));
return 0;
}
/////////////////////////////////////////////////////////
QVariant ModelItem::data(int column) const {
switch(column) {
case NAMEUID: return name;
case EXTENSIONUID: return extension;
case PATHUID: return path;
default: return QVariant();
}
}
bool ModelItem::setData(int column, const QVariant &value) {
if (column < 0 || column >= 2)
// if (column < 0 || column >= itemData.size())
return false;
// itemData[column] = value;
switch(column) {
case NAMEUID: name = value.toString();
case EXTENSIONUID: extension = value.toString();
case PATHUID: path = value.toString();
}
// itemData[column] = value;
return true;
}
/////////////////////////////////////////////////////////
QString ModelItem::fullpath() const {
ModelItem * curr = parentItem;
QString path_buff = "";
while(curr != 0) {
path_buff = curr -> path + '/' + path_buff;
curr = curr -> parentItem;
}
return path_buff.mid(1) + name + '.' + extension;
}
//////////////////////////properties///////////////////////////////
ModelItemState * ModelItem::getState() const {
return state;
}
void ModelItem::setState(int new_state, bool append_to_library) {
if (state -> setBit(new_state) && append_to_library) {
if (state -> isListened())
Library::instance() -> addItem(this, STATE_LISTENED);
else if (state -> isLiked())
Library::instance() -> addItem(this, STATE_LIKED);
}
}
///////////////////////////////////////////////////////
QJsonObject ModelItem::toJSON() {
// TODO: logic build needed
QJsonObject root = QJsonObject();
if (childItems.length() > 0) {
QJsonArray ar = QJsonArray();
for(int i=0; i < childItems.length(); i++)
ar.append(childItems.at(i)->toJSON());
root["c"] = ar;
}
if (state -> isUnprocessed())
root["p"] = path;
else {
root["n"] = name;
root["s"] = state -> getFuncValue();
root["e"] = extension;
}
return root;
}
//TODO: add list of extensions for extension serialization to extension index in list
<commit_msg>fix item deleting<commit_after>#include "model_item.h"
#include <QDebug>
/////////////////////////////////////////////////////////
void ModelItem::init(bool isFolder) {
names = 0;
childItems = QList<ModelItem*>();
if (isFolder) {
state = new ModelItemState(STATE_UNPROCESSED);
state -> setProceed();
folders = new QHash<QString, ModelItem *>();
} else {
folders = 0;
}
}
void ModelItem::rootItemInit() {
path = QString();
name = QString("--(O_o)--");
extension = QString();
}
ModelItem::ModelItem() {
init(true);
rootItemInit();
parentItem = 0;
}
ModelItem::ModelItem(QJsonObject * attrs, ModelItem *parent) {
init(true);
parentItem = parent;
if (attrs -> contains("p")) {
name = path = attrs -> value("p").toString();
if (parent != 0)
parent -> folders -> insert(name, this);
} else {
name = attrs -> value("n").toString();
state = new ModelItemState(attrs -> value("s").toInt());
extension = attrs -> value("e").toString();
}
if (attrs -> contains("c")) {
QJsonArray ar = attrs -> value("c").toArray();
QJsonObject iter_obj;
foreach(QJsonValue obj, ar) {
iter_obj = obj.toObject();
new ModelItem(&iter_obj, this);
}
}
if (parent != 0) {
parent -> appendChild(this);
} else {
rootItemInit();
}
}
ModelItem::ModelItem(QString file_path, ModelItem *parent, int init_state) {
state = new ModelItemState(init_state);
parentItem = parent;
if (!state -> isUnprocessed()) {
init(false);
path = file_path.section('/', 0, -2);
name = file_path.section('/', -1, -1);
extension = name.section('.', -1, -1);
name = name.section('.', 0, -2);
} else {
init(true);
name = path = file_path;
extension = QString();
if (parent != 0)
parent -> folders -> insert(name, this);
}
if (parent != 0) { parent -> appendChild(this);}
}
ModelItem::~ModelItem() {
qDeleteAll(childItems);
delete state;
delete folders;
delete names;
}
/////////////////////////////////////////////////////////
ModelItem *ModelItem::parent() {
return parentItem;
}
/////////////////////////////////////////////////////////
ModelItem *ModelItem::child(int row) {
return childItems.value(row);
}
int ModelItem::childCount() const {
return childItems.count();
}
void ModelItem::appendChild(ModelItem *item) {
childItems.append(item);
}
bool ModelItem::insertChildren(int position, int count, int /*columns*/) {
if (position < 0 || position > childItems.size())
return false;
for (int row = 0; row < count; ++row) {
// QVector<QVariant> data(columns);
// ModelItem *item = new ModelItem(data, this);
ModelItem *item = new ModelItem(QString("BLA"), this);
childItems.insert(position, item);
}
return true;
}
bool ModelItem::removeChildren(int position, int count)
{
if (position < 0 || position + count > childItems.size())
return false;
for (int row = 0; row < count; ++row)
delete childItems.takeAt(position);
return true;
}
/////////////////////////////////////////////////////////
int ModelItem::column() const {
return 0;
}
int ModelItem::columnCount() const {
return 1;
// if (parentItem == 0)
// return 0;
// else
// return 1;
}
bool ModelItem::removeColumns(int /*position*/, int /*columns*/) {
// if (position < 0 || position + columns > itemData.size())
// return false;
// for (int column = 0; column < columns; ++column)
// itemData.remove(position);
// foreach (TreeItem *child, childItems)
// child->removeColumns(position, columns);
return true;
}
bool ModelItem::insertColumns(int /*position*/, int /*columns*/) {
// if (position < 0 || position > itemData.size())
// return false;
// for (int column = 0; column < columns; ++column)
// itemData.insert(position, QVariant());
// foreach (TreeItem *child, childItems)
// child->insertColumns(position, columns);
return true;
}
/////////////////////////////////////////////////////////
int ModelItem::row() const {
if (parentItem)
return parentItem->childItems.indexOf(const_cast<ModelItem*>(this));
return 0;
}
/////////////////////////////////////////////////////////
QVariant ModelItem::data(int column) const {
switch(column) {
case NAMEUID: return name;
case EXTENSIONUID: return extension;
case PATHUID: return path;
default: return QVariant();
}
}
bool ModelItem::setData(int column, const QVariant &value) {
if (column < 0 || column >= 2)
// if (column < 0 || column >= itemData.size())
return false;
// itemData[column] = value;
switch(column) {
case NAMEUID: name = value.toString();
case EXTENSIONUID: extension = value.toString();
case PATHUID: path = value.toString();
}
// itemData[column] = value;
return true;
}
/////////////////////////////////////////////////////////
QString ModelItem::fullpath() const {
ModelItem * curr = parentItem;
QString path_buff = "";
while(curr != 0) {
path_buff = curr -> path + '/' + path_buff;
curr = curr -> parentItem;
}
return path_buff.mid(1) + name + '.' + extension;
}
//////////////////////////properties///////////////////////////////
ModelItemState * ModelItem::getState() const {
return state;
}
void ModelItem::setState(int new_state, bool append_to_library) {
if (state -> setBit(new_state) && append_to_library) {
if (state -> isListened())
Library::instance() -> addItem(this, STATE_LISTENED);
else if (state -> isLiked())
Library::instance() -> addItem(this, STATE_LIKED);
}
}
///////////////////////////////////////////////////////
QJsonObject ModelItem::toJSON() {
// TODO: logic build needed
QJsonObject root = QJsonObject();
if (childItems.length() > 0) {
QJsonArray ar = QJsonArray();
for(int i=0; i < childItems.length(); i++)
ar.append(childItems.at(i)->toJSON());
root["c"] = ar;
}
if (state -> isUnprocessed())
root["p"] = path;
else {
root["n"] = name;
root["s"] = state -> getFuncValue();
root["e"] = extension;
}
return root;
}
//TODO: add list of extensions for extension serialization to extension index in list
<|endoftext|> |
<commit_before>#include "envoy/common/exception.h"
#include "envoy/type/matcher/v3/regex.pb.h"
#include "common/common/regex.h"
#include "test/test_common/logging.h"
#include "test/test_common/test_runtime.h"
#include "test/test_common/utility.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Regex {
namespace {
TEST(Utility, ParseStdRegex) {
EXPECT_THROW_WITH_REGEX(Utility::parseStdRegex("(+invalid)"), EnvoyException,
"Invalid regex '\\(\\+invalid\\)': .+");
EXPECT_THROW_WITH_REGEX(Utility::parseStdRegexAsCompiledMatcher("(+invalid)"), EnvoyException,
"Invalid regex '\\(\\+invalid\\)': .+");
{
std::regex regex = Utility::parseStdRegex("x*");
EXPECT_NE(0, regex.flags() & std::regex::optimize);
}
{
std::regex regex = Utility::parseStdRegex("x*", std::regex::icase);
EXPECT_NE(0, regex.flags() & std::regex::icase);
EXPECT_EQ(0, regex.flags() & std::regex::optimize);
}
{
// Regression test to cover high-complexity regular expressions that throw on std::regex_match.
// Note that not all std::regex_match implementations will throw when matching against the
// expression below, but at least clang 9.0.0 under linux does.
auto matcher = Utility::parseStdRegexAsCompiledMatcher(
"|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
EXPECT_FALSE(matcher->match("0"));
}
}
TEST(Utility, ParseRegex) {
{
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.mutable_google_re2();
matcher.set_regex("(+invalid)");
EXPECT_THROW_WITH_MESSAGE(Utility::parseRegex(matcher), EnvoyException,
"no argument for repetition operator: +");
}
// Regression test for https://github.com/envoyproxy/envoy/issues/7728
{
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.mutable_google_re2();
matcher.set_regex("/asdf/.*");
const auto compiled_matcher = Utility::parseRegex(matcher);
const std::string long_string = "/asdf/" + std::string(50 * 1024, 'a');
EXPECT_TRUE(compiled_matcher->match(long_string));
}
// Positive case to ensure no max program size is enforced.
{
TestScopedRuntime scoped_runtime;
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
EXPECT_NO_THROW(Utility::parseRegex(matcher));
}
// Verify max program size with the deprecated field codepath plus runtime.
// The deprecated field codepath precedes any runtime settings.
{
TestScopedRuntime scoped_runtime;
Runtime::LoaderSingleton::getExisting()->mergeValues(
{{"re2.max_program_size.error_level", "3"}});
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2()->mutable_max_program_size()->set_value(1);
#ifndef GTEST_USES_SIMPLE_RE
EXPECT_THROW_WITH_REGEX(Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of [0-9]+ > max program size of 1\\.");
#else
EXPECT_THROW_WITH_REGEX(Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of \\d+ > max program size of 1\\.");
#endif
}
// Verify that an exception is thrown for the error level max program size.
{
TestScopedRuntime scoped_runtime;
Runtime::LoaderSingleton::getExisting()->mergeValues(
{{"re2.max_program_size.error_level", "1"}});
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
#ifndef GTEST_USES_SIMPLE_RE
EXPECT_THROW_WITH_REGEX(
Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of [0-9]+ > max program size of 1 set for the error level threshold\\.");
#else
EXPECT_THROW_WITH_REGEX(
Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of \\d+ > max program size of 1 set for the error level threshold\\.");
#endif
}
// Verify that the error level max program size defaults to 100 if not set by runtime.
{
TestScopedRuntime scoped_runtime;
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex(
"/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*");
matcher.mutable_google_re2();
#ifndef GTEST_USES_SIMPLE_RE
EXPECT_THROW_WITH_REGEX(Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of [0-9]+ > max program size of 100 set for the "
"error level threshold\\.");
#else
EXPECT_THROW_WITH_REGEX(
Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of \\d+ > max program size of 100 set for the error level threshold\\.");
#endif
}
// Verify that a warning is logged for the warn level max program size.
{
TestScopedRuntime scoped_runtime;
Envoy::Stats::Counter& warn_count =
Runtime::LoaderSingleton::getExisting()->getRootScope().counterFromString(
"re2.exceeded_warn_level");
Runtime::LoaderSingleton::getExisting()->mergeValues(
{{"re2.max_program_size.warn_level", "1"}});
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
EXPECT_NO_THROW(Utility::parseRegex(matcher));
EXPECT_EQ(1, warn_count.value());
EXPECT_LOG_CONTAINS("warn", "> max program size of 1 set for the warn level threshold",
Utility::parseRegex(matcher));
EXPECT_EQ(2, warn_count.value());
}
// Verify that no check is performed if the warn level max program size is not set by runtime.
{
TestScopedRuntime scoped_runtime;
Envoy::Stats::Counter& warn_count =
Runtime::LoaderSingleton::getExisting()->getRootScope().counterFromString(
"re2.exceeded_warn_level");
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
EXPECT_NO_THROW(Utility::parseRegex(matcher));
EXPECT_LOG_NOT_CONTAINS("warn", "> max program size", Utility::parseRegex(matcher));
EXPECT_EQ(0, warn_count.value());
}
}
} // namespace
} // namespace Regex
} // namespace Envoy
<commit_msg>route: adding tests (#15931)<commit_after>#include "envoy/common/exception.h"
#include "envoy/type/matcher/v3/regex.pb.h"
#include "common/common/regex.h"
#include "test/test_common/logging.h"
#include "test/test_common/test_runtime.h"
#include "test/test_common/utility.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Regex {
namespace {
TEST(Utility, ParseStdRegex) {
EXPECT_THROW_WITH_REGEX(Utility::parseStdRegex("(+invalid)"), EnvoyException,
"Invalid regex '\\(\\+invalid\\)': .+");
EXPECT_THROW_WITH_REGEX(Utility::parseStdRegexAsCompiledMatcher("(+invalid)"), EnvoyException,
"Invalid regex '\\(\\+invalid\\)': .+");
{
std::regex regex = Utility::parseStdRegex("x*");
EXPECT_NE(0, regex.flags() & std::regex::optimize);
}
{
std::regex regex = Utility::parseStdRegex("x*", std::regex::icase);
EXPECT_NE(0, regex.flags() & std::regex::icase);
EXPECT_EQ(0, regex.flags() & std::regex::optimize);
}
{
// Regression test to cover high-complexity regular expressions that throw on std::regex_match.
// Note that not all std::regex_match implementations will throw when matching against the
// expression below, but at least clang 9.0.0 under linux does.
auto matcher = Utility::parseStdRegexAsCompiledMatcher(
"|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
EXPECT_FALSE(matcher->match("0"));
}
}
TEST(Utility, ParseRegex) {
{
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.mutable_google_re2();
matcher.set_regex("(+invalid)");
EXPECT_THROW_WITH_MESSAGE(Utility::parseRegex(matcher), EnvoyException,
"no argument for repetition operator: +");
}
// Regression test for https://github.com/envoyproxy/envoy/issues/7728
{
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.mutable_google_re2();
matcher.set_regex("/asdf/.*");
const auto compiled_matcher = Utility::parseRegex(matcher);
const std::string long_string = "/asdf/" + std::string(50 * 1024, 'a');
EXPECT_TRUE(compiled_matcher->match(long_string));
}
// Regression test for https://github.com/envoyproxy/envoy/issues/15826
{
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.mutable_google_re2();
matcher.set_regex("/status/200(/.*)?$");
const auto compiled_matcher = Utility::parseRegex(matcher);
EXPECT_TRUE(compiled_matcher->match("/status/200"));
EXPECT_TRUE(compiled_matcher->match("/status/200/"));
EXPECT_TRUE(compiled_matcher->match("/status/200/foo"));
EXPECT_FALSE(compiled_matcher->match("/status/200foo"));
}
// Positive case to ensure no max program size is enforced.
{
TestScopedRuntime scoped_runtime;
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
EXPECT_NO_THROW(Utility::parseRegex(matcher));
}
// Verify max program size with the deprecated field codepath plus runtime.
// The deprecated field codepath precedes any runtime settings.
{
TestScopedRuntime scoped_runtime;
Runtime::LoaderSingleton::getExisting()->mergeValues(
{{"re2.max_program_size.error_level", "3"}});
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2()->mutable_max_program_size()->set_value(1);
#ifndef GTEST_USES_SIMPLE_RE
EXPECT_THROW_WITH_REGEX(Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of [0-9]+ > max program size of 1\\.");
#else
EXPECT_THROW_WITH_REGEX(Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of \\d+ > max program size of 1\\.");
#endif
}
// Verify that an exception is thrown for the error level max program size.
{
TestScopedRuntime scoped_runtime;
Runtime::LoaderSingleton::getExisting()->mergeValues(
{{"re2.max_program_size.error_level", "1"}});
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
#ifndef GTEST_USES_SIMPLE_RE
EXPECT_THROW_WITH_REGEX(
Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of [0-9]+ > max program size of 1 set for the error level threshold\\.");
#else
EXPECT_THROW_WITH_REGEX(
Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of \\d+ > max program size of 1 set for the error level threshold\\.");
#endif
}
// Verify that the error level max program size defaults to 100 if not set by runtime.
{
TestScopedRuntime scoped_runtime;
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex(
"/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*/asdf/.*");
matcher.mutable_google_re2();
#ifndef GTEST_USES_SIMPLE_RE
EXPECT_THROW_WITH_REGEX(Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of [0-9]+ > max program size of 100 set for the "
"error level threshold\\.");
#else
EXPECT_THROW_WITH_REGEX(
Utility::parseRegex(matcher), EnvoyException,
"RE2 program size of \\d+ > max program size of 100 set for the error level threshold\\.");
#endif
}
// Verify that a warning is logged for the warn level max program size.
{
TestScopedRuntime scoped_runtime;
Envoy::Stats::Counter& warn_count =
Runtime::LoaderSingleton::getExisting()->getRootScope().counterFromString(
"re2.exceeded_warn_level");
Runtime::LoaderSingleton::getExisting()->mergeValues(
{{"re2.max_program_size.warn_level", "1"}});
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
EXPECT_NO_THROW(Utility::parseRegex(matcher));
EXPECT_EQ(1, warn_count.value());
EXPECT_LOG_CONTAINS("warn", "> max program size of 1 set for the warn level threshold",
Utility::parseRegex(matcher));
EXPECT_EQ(2, warn_count.value());
}
// Verify that no check is performed if the warn level max program size is not set by runtime.
{
TestScopedRuntime scoped_runtime;
Envoy::Stats::Counter& warn_count =
Runtime::LoaderSingleton::getExisting()->getRootScope().counterFromString(
"re2.exceeded_warn_level");
envoy::type::matcher::v3::RegexMatcher matcher;
matcher.set_regex("/asdf/.*");
matcher.mutable_google_re2();
EXPECT_NO_THROW(Utility::parseRegex(matcher));
EXPECT_LOG_NOT_CONTAINS("warn", "> max program size", Utility::parseRegex(matcher));
EXPECT_EQ(0, warn_count.value());
}
}
} // namespace
} // namespace Regex
} // namespace Envoy
<|endoftext|> |
<commit_before>#include "patterns.h"
#include <iostream>
#include <cstdlib>
#include "tbb/tbb.h"
namespace {
using std::string;
using std::cout;
using std::endl;
using std::to_string;
using tbb::parallel_for;
using tbb::blocked_range;
int add_five(const int num) {
return num + 5;
}
template <typename T>
void print_array(T* array, const size_t size) {
string outstr = "{";
for(int i = 0, end = size; i != end; ++i)
outstr += to_string(array[i]) + ", ";
outstr.erase(outstr.size() - 2);
outstr += "}";
cout << outstr << endl;
}
template <typename T>
T sum_array(T* array, const size_t len) {
T sum = 0;
for(size_t i = 0, end = len; i != end; ++i)
sum += array[i];
return sum;
}
/// body for tbb::parallel_scan
/// used by scan()
class Body {
int result;
int* const y;
const int* const z;
public:
Body(int y_[], const int z_[]) : result(0), z(z_), y(y_) {}
Body(Body& b) : z(b.z), y(b.y), result(0) {}
Body(Body& b, tbb::split) : z(b.z), y(b.y), result(0) {}
void assign(Body& b, tbb::split) {result = b.result;}
void assign(Body& b) {result = b.result;}
void reverse_join(Body& a) {result = a.result;}
int get_result() const {return result;}
template<typename Tag>
void operator()(const blocked_range<int>& r, Tag) {
int temp = result;
for(int i = r.begin(); i < r.end(); ++i) {
temp = temp + z[i];
if(Tag::is_final_scan())
y[i] = temp;
}
result = temp;
}
};
}
namespace patterns {
void map() {
cout << "map pattern" << endl;
cout << "-----------" << endl;
cout << "mapping add_five() onto each element of ";
const int size = 10;
int input[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_array(input, size);
int output[size];
parallel_for(0, size, 1, [input, &output](int i) {
output[i] = add_five(input[i]);
});
cout << "output: ";
print_array(output, size);
cout << endl;
}
void stencil() {
cout << "stencil pattern" << endl;
cout << "---------------" << endl;
cout << "summing each element with its neighbors, of ";
const int size = 10;
int input[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_array(input, size);
int output[size] = {0};
output[0] = sum_array(input, 2);
output[size-1] = sum_array(&input[size-2], 2);
parallel_for(1, size-1, 1, [input, &output](int i) {
output[i] = sum_array((int*)&input[i-1], 3);
});
cout << "output: ";
print_array(output, size);
cout << endl;
}
void reduce() {
cout << "reduce pattern" << endl;
cout << "--------------" << endl;
cout << "multiplying each element of ";
const int size = 10;
int input[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print_array(input, size);
auto multFunc = [](int x, int y) -> int {
return x * y;
};
auto combineFunc = [](const blocked_range<int*>& r, int init) -> int {
for(int* i = r.begin(); i != r.end(); ++i)
init *= *i;
return init;
};
const int product = parallel_reduce(blocked_range<int*>(input, input+size), 1, combineFunc, multFunc);
cout << "product: " << product << endl;
}
void scan() {
using namespace tbb; //debug
cout << "scan pattern (aka parallel prefix)" << endl;
cout << "----------------------------------" << endl;
cout << "computing the sum of each previous element in ";
const int size = 10;
int input[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print_array(input, size);
int output[size] = {0};
Body body(output, input);
parallel_scan(blocked_range<int>(0, size), body);
cout << "output: ";
print_array(output, size);
cout << endl;
}
} // namespace patterns
<commit_msg>fixed missing double newline from reduce output<commit_after>#include "patterns.h"
#include <iostream>
#include <cstdlib>
#include "tbb/tbb.h"
namespace {
using std::string;
using std::cout;
using std::endl;
using std::to_string;
using tbb::parallel_for;
using tbb::blocked_range;
int add_five(const int num) {
return num + 5;
}
template <typename T>
void print_array(T* array, const size_t size) {
string outstr = "{";
for(int i = 0, end = size; i != end; ++i)
outstr += to_string(array[i]) + ", ";
outstr.erase(outstr.size() - 2);
outstr += "}";
cout << outstr << endl;
}
template <typename T>
T sum_array(T* array, const size_t len) {
T sum = 0;
for(size_t i = 0, end = len; i != end; ++i)
sum += array[i];
return sum;
}
/// body for tbb::parallel_scan
/// used by scan()
class Body {
int result;
int* const y;
const int* const z;
public:
Body(int y_[], const int z_[]) : result(0), z(z_), y(y_) {}
Body(Body& b) : z(b.z), y(b.y), result(0) {}
Body(Body& b, tbb::split) : z(b.z), y(b.y), result(0) {}
void assign(Body& b, tbb::split) {result = b.result;}
void assign(Body& b) {result = b.result;}
void reverse_join(Body& a) {result = a.result;}
int get_result() const {return result;}
template<typename Tag>
void operator()(const blocked_range<int>& r, Tag) {
int temp = result;
for(int i = r.begin(); i < r.end(); ++i) {
temp = temp + z[i];
if(Tag::is_final_scan())
y[i] = temp;
}
result = temp;
}
};
}
namespace patterns {
void map() {
cout << "map pattern" << endl;
cout << "-----------" << endl;
cout << "mapping add_five() onto each element of ";
const int size = 10;
int input[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_array(input, size);
int output[size];
parallel_for(0, size, 1, [input, &output](int i) {
output[i] = add_five(input[i]);
});
cout << "output: ";
print_array(output, size);
cout << endl;
}
void stencil() {
cout << "stencil pattern" << endl;
cout << "---------------" << endl;
cout << "summing each element with its neighbors, of ";
const int size = 10;
int input[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_array(input, size);
int output[size] = {0};
output[0] = sum_array(input, 2);
output[size-1] = sum_array(&input[size-2], 2);
parallel_for(1, size-1, 1, [input, &output](int i) {
output[i] = sum_array((int*)&input[i-1], 3);
});
cout << "output: ";
print_array(output, size);
cout << endl;
}
void reduce() {
cout << "reduce pattern" << endl;
cout << "--------------" << endl;
cout << "multiplying each element of ";
const int size = 10;
int input[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print_array(input, size);
auto multFunc = [](int x, int y) -> int {
return x * y;
};
auto combineFunc = [](const blocked_range<int*>& r, int init) -> int {
for(int* i = r.begin(); i != r.end(); ++i)
init *= *i;
return init;
};
const int product = parallel_reduce(blocked_range<int*>(input, input+size), 1, combineFunc, multFunc);
cout << "product: " << product << endl << endl;
}
void scan() {
using namespace tbb; //debug
cout << "scan pattern (aka parallel prefix)" << endl;
cout << "----------------------------------" << endl;
cout << "computing the sum of each previous element in ";
const int size = 10;
int input[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print_array(input, size);
int output[size] = {0};
Body body(output, input);
parallel_scan(blocked_range<int>(0, size), body);
cout << "output: ";
print_array(output, size);
cout << endl;
}
} // namespace patterns
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <time.h>
#include <cstdlib>
#include <ctime>
#include "MyBot.h"
MyBot::MyBot()
{
srand(time(NULL));
std::cout.sync_with_stdio(0);
getInit(my_tag, present_map);
sendInitResponse("CppBot" + std::to_string(my_tag));
// FOR DEBUGGING PURPOSES. Clears the test file
std::ofstream ofs;
ofs.open(std::to_string(my_tag) +".log", std::ofstream::out | std::ofstream::trunc);
ofs.close();
}
void MyBot::run()
{
while(true)
{
moves.clear();
messagesFromMe.clear();
hlt::Message exampleMessage;
exampleMessage.type = hlt::MessageType::ATTACK;
exampleMessage.senderID = my_tag;
exampleMessage.recipientID = my_tag != 1 ? 1 : 2;
exampleMessage.targetID = my_tag;
messagesFromMe.push_back(exampleMessage);
getFrame(present_map, messagesToMe);
for(unsigned short a = 0; a < present_map.map_height; a++)
{
for(unsigned short b = 0; b < present_map.map_width; b++)
{
if (present_map.getSite({b, a}, STILL).owner == my_tag)
{
if (float(rand()) / RAND_MAX > .20)
{
moves.insert({ { b, a }, (unsigned char)(rand() % 5) });
}
else moves.insert({ { b, a }, (unsigned char)(STILL) });
}
}
}
sendFrame(moves, messagesFromMe);
}
}
int main()
{
srand(time(NULL));
MyBot r = MyBot();
r.run();
return 0;
}
<commit_msg>Wierd merge #2<commit_after>#include <stdlib.h>
#include <time.h>
#include <cstdlib>
#include <ctime>
#include "MyBot.h"
MyBot::MyBot()
{
srand(time(NULL));
std::cout.sync_with_stdio(0);
getInit(my_tag, present_map);
sendInitResponse("CppBot" + std::to_string(my_tag));
// FOR DEBUGGING PURPOSES. Clears the test file
std::ofstream ofs;
ofs.open(std::to_string(my_tag) +".log", std::ofstream::out | std::ofstream::trunc);
ofs.close();
}
void MyBot::run()
{
while(true)
{
moves.clear();
messagesFromMe.clear();
<<<<<<< HEAD
hlt::Message exampleMessage;
exampleMessage.type = hlt::MessageType::ATTACK;
exampleMessage.senderID = my_tag;
exampleMessage.recipientID = my_tag != 1 ? 1 : 2;
exampleMessage.targetID = my_tag;
messagesFromMe.push_back(exampleMessage);
=======
hlt::Message exampleMessage;
exampleMessage.type = hlt::MessageType::ATTACK;
exampleMessage.senderID = my_tag;
exampleMessage.recipientID = my_tag != 1 ? 1 : 2;
exampleMessage.targetID = my_tag;
messagesFromMe.push_back(exampleMessage);
>>>>>>> ab8c458... Fix merges
getFrame(present_map, messagesToMe);
for(unsigned short a = 0; a < present_map.map_height; a++)
{
for(unsigned short b = 0; b < present_map.map_width; b++)
{
if (present_map.getSite({b, a}, STILL).owner == my_tag)
{
if (float(rand()) / RAND_MAX > .20)
{
moves.insert({ { b, a }, (unsigned char)(rand() % 5) });
}
else moves.insert({ { b, a }, (unsigned char)(STILL) });
}
}
}
sendFrame(moves, messagesFromMe);
}
}
int main()
{
srand(time(NULL));
MyBot r = MyBot();
r.run();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "amalgamated_budget.hpp"
#include "account.hpp"
#include "account_impl.hpp"
#include "account_type.hpp"
#include "budget_item_reader.hpp"
#include "draft_journal.hpp"
#include "entry.hpp"
#include "frequency.hpp"
#include "interval_type.hpp"
#include "phatbooks_exceptions.hpp"
#include "repeater.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/static_assert.hpp>
#include <jewel/decimal.hpp>
#include <sqloxx/sql_statement.hpp>
#include <algorithm>
#include <cassert>
#include <numeric>
#include <ostream>
#include <utility>
#include <vector>
using boost::scoped_ptr;
using jewel::Decimal;
using sqloxx::SQLStatement;
using std::accumulate;
using std::ostream;
using std::pair;
using std::vector;
namespace gregorian = boost::gregorian;
// For debugging only
#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;
// End debugging stuff
namespace phatbooks
{
BOOST_STATIC_ASSERT((boost::is_same<Account::Id, AccountImpl::Id>::value));
void
AmalgamatedBudget::setup_tables(PhatbooksDatabaseConnection& dbc)
{
dbc.execute_sql
( "create index budget_item_account_index on budget_items(account_id)"
);
// NOTE UserDraftJournalReader has knowledge of this schema. Ensure
// any changes to the schema are also reflected there, as appropriate.
dbc.execute_sql
( "create table amalgamated_budget_data"
"("
"journal_id integer unique not null "
"references draft_journal_detail, "
"balancing_account_id integer unique not null "
"references accounts"
")"
);
DraftJournal instrument(dbc);
instrument.set_name("AMALGAMATED BUDGET JOURNAL");
instrument.set_whether_actual(false);
instrument.set_comment("");
Repeater repeater(dbc);
repeater.set_frequency(Frequency(1, interval_type::days));
repeater.set_next_date(gregorian::day_clock::local_day());
instrument.push_repeater(repeater);
instrument.save();
Account balancing_account(dbc);
balancing_account.set_account_type(account_type::pure_envelope);
balancing_account.set_name("BUDGET IMBALANCE");
balancing_account.set_description("");
Commodity const balancing_account_commodity = dbc.default_commodity();
balancing_account.set_commodity(balancing_account_commodity);
balancing_account.save();
SQLStatement statement
( dbc,
"insert into amalgamated_budget_data"
"(journal_id, balancing_account_id) "
"values(:journal_id, :balancing_account_id)"
);
statement.bind(":journal_id", instrument.id());
statement.bind(":balancing_account_id", balancing_account.id());
statement.step_final();
return;
}
AmalgamatedBudget::AmalgamatedBudget
( PhatbooksDatabaseConnection& p_database_connection
):
m_is_loaded(false),
m_database_connection(p_database_connection),
m_frequency(1, interval_type::days),
m_map(new Map),
m_instrument(0),
m_balancing_account(0)
{
}
AmalgamatedBudget::~AmalgamatedBudget()
{
delete m_instrument;
m_instrument = 0;
delete m_balancing_account;
m_balancing_account = 0;
}
void
AmalgamatedBudget::load() const
{
if (m_is_loaded)
{
return;
}
assert (!m_is_loaded);
load_balancing_account();
load_instrument();
load_map();
m_is_loaded = true;
return;
}
Frequency
AmalgamatedBudget::frequency() const
{
load();
assert (m_frequency.num_steps() == 1);
return m_frequency;
}
void
AmalgamatedBudget::set_frequency(Frequency const& p_frequency)
{
load();
m_frequency = p_frequency;
regenerate();
return;
}
Decimal
AmalgamatedBudget::budget(AccountImpl::Id p_account_id) const
{
load();
Map::const_iterator it = m_map->find(p_account_id);
assert (it != m_map->end());
return it->second;
}
namespace
{
Decimal map_entry_accumulation_aux
( Decimal const& dec,
pair<AccountImpl::Id, Decimal> const& rhs
)
{
return dec + rhs.second;
}
} // end anonymous namespace
Decimal
AmalgamatedBudget::balance() const
{
load();
return accumulate
( m_map->begin(),
m_map->end(),
Decimal(0, 0),
map_entry_accumulation_aux
);
}
void
AmalgamatedBudget::generate_supported_frequencies(vector<Frequency>& vec)
{
// NOTE This is co-dependent with the function
// AmalgamatedBudget::supports_frequency. If this
// changes, that must change too.
vec.reserve(10);
vec.push_back(Frequency(1, interval_type::days));
vec.push_back(Frequency(1, interval_type::weeks));
vec.push_back(Frequency(2, interval_type::weeks));
vec.push_back(Frequency(4, interval_type::weeks));
vec.push_back(Frequency(1, interval_type::months));
vec.push_back(Frequency(2, interval_type::months));
vec.push_back(Frequency(3, interval_type::months));
vec.push_back(Frequency(4, interval_type::months));
vec.push_back(Frequency(6, interval_type::months));
vec.push_back(Frequency(12, interval_type::months));
return;
}
bool
AmalgamatedBudget::supports_frequency(Frequency const& p_frequency)
{
// NOTE This is co-dependent with the function
// AmalgamatedBudget::supported_frequencies. If this changes,
// that must change too.
switch (p_frequency.step_type())
{
case interval_type::days:
return p_frequency.num_steps() == 1;
case interval_type::weeks:
switch (p_frequency.num_steps())
{
case 1: case 2: return true;
case 3: return false;
case 4: return true;
default: return false;
}
case interval_type::months:
switch (p_frequency.num_steps())
{
case 1: case 2: case 3: case 4: return true;
case 5: return false;
case 6: return true;
case 7: case 8: case 9: case 10: case 11: return false;
case 12: return true;
default: return false;
}
case interval_type::month_ends:
return false;
default:
assert (false);
}
}
Account
AmalgamatedBudget::balancing_account() const
{
load();
assert (m_balancing_account != 0);
return *m_balancing_account;
}
DraftJournal
AmalgamatedBudget::instrument() const
{
load();
return *m_instrument;
}
void
AmalgamatedBudget::regenerate()
{
// If amalgamated_budget_data has not yet been populated, then
// proceeding here would cause the program to crash, as
// we wouldn't be able to load the balancing account id, etc..
// So if amalgamated_budget_data has not been created yet,
// we simply return. It is expected this will only happen on
// initial setup of the database (due to calling of
// regenerate() by hook in AccountImpl saving method, when
// balancing account is first saved).
SQLStatement statement
( m_database_connection,
"select * from amalgamated_budget_data"
);
if (statement.step())
{
load();
regenerate_map();
regenerate_instrument();
statement.step_final();
}
return;
}
void
AmalgamatedBudget::load_map() const
{
assert (!m_is_loaded);
assert (m_map->empty());
generate_map();
return;
}
void
AmalgamatedBudget::generate_map() const
{
scoped_ptr<Map> map_elect(new Map);
assert (map_elect->empty());
SQLStatement account_selector
( m_database_connection,
"select account_id from accounts"
);
while (account_selector.step())
{
AccountImpl::Id const account_id =
account_selector.extract<AccountImpl::Id>(0);
Account const account(m_database_connection, account_id);
(*map_elect)[account_id] =
Decimal(0, account.commodity().precision());
}
BudgetItemReader budget_item_reader(m_database_connection);
BudgetItemReader::const_iterator const beg = budget_item_reader.begin();
BudgetItemReader::const_iterator const end = budget_item_reader.end();
// First we calculate budgets amalgamated on the basis of
// the canonical frequency
BudgetItemReader::const_iterator it = beg;
for ( ; it != end; ++it)
{
Frequency const raw_frequency = it->frequency();
if (!AmalgamatedBudget::supports_frequency(raw_frequency))
{
throw InvalidFrequencyException
( "Frequency not supported by AmalgamatedBudget."
);
}
AccountImpl::Id const account_id = it->account().id();
jewel::Decimal const raw_amount = it->amount();
jewel::Decimal const canonical_amount = convert_to_canonical
( raw_frequency,
raw_amount
);
Map::iterator tmit = map_elect->find(account_id);
assert (tmit != map_elect->end());
tmit->second += canonical_amount;
}
// Now convert to desired frequency
for
( Map::iterator mit = map_elect->begin(), mend = map_elect->end();
mit != mend;
++mit
)
{
mit->second = round
( convert_from_canonical(m_frequency, mit->second),
Account(m_database_connection, mit->first).commodity().precision()
);
}
using std::swap;
swap(m_map, map_elect);
return;
}
void
AmalgamatedBudget::regenerate_map()
{
load();
generate_map();
return;
}
void
AmalgamatedBudget::regenerate_instrument()
{
load();
DraftJournal fresh_journal(m_database_connection);
fresh_journal.mimic(*m_instrument);
reflect_entries(fresh_journal);
reflect_repeater(fresh_journal);
// Deal with imbalance
Decimal const imbalance = fresh_journal.balance();
if (imbalance != Decimal(0, 0))
{
Account const ba = balancing_account();
Entry balancing_entry(m_database_connection);
balancing_entry.set_account(ba);
balancing_entry.set_comment("");
balancing_entry.set_whether_reconciled(false);
balancing_entry.set_amount
( -round(imbalance, ba.commodity().precision())
);
fresh_journal.push_entry(balancing_entry);
assert (fresh_journal.is_balanced());
}
m_instrument->mimic(fresh_journal);
m_instrument->save();
return;
}
void
AmalgamatedBudget::load_balancing_account() const
{
SQLStatement statement
( m_database_connection,
"select balancing_account_id from amalgamated_budget_data"
);
bool check = statement.step();
assert (check);
if (m_balancing_account)
{
delete m_balancing_account;
m_balancing_account = 0;
}
m_balancing_account = new Account
( m_database_connection,
statement.extract<Account::Id>(0)
);
statement.step_final();
return;
}
void
AmalgamatedBudget::load_instrument() const
{
// Set the instrument (the DraftJournal that carries out
// the AmalgamatedBudget)
SQLStatement statement
( m_database_connection,
"select journal_id from amalgamated_budget_data"
);
statement.step();
if (m_instrument)
{
delete m_instrument;
m_instrument = 0;
}
m_instrument = new DraftJournal
( m_database_connection,
statement.extract<DraftJournal::Id>(0)
);
statement.step_final();
return;
}
void
AmalgamatedBudget::reflect_entries(DraftJournal& p_journal)
{
load();
p_journal.clear_entries();
Map const& map = *m_map;
for
( Map::const_iterator it = map.begin(), end = map.end();
it != end;
++it
)
{
if (it->second != Decimal(0, 0))
{
Entry entry(m_database_connection);
entry.set_account
( Account(m_database_connection, it->first)
);
entry.set_comment("");
entry.set_amount(-(it->second));
entry.set_whether_reconciled(false);
p_journal.push_entry(entry);
}
}
return;
}
void
AmalgamatedBudget::reflect_repeater(DraftJournal& p_journal)
{
load();
vector<Repeater> const& old_repeaters = p_journal.repeaters();
if (old_repeaters.size() == 1)
{
Frequency const old_frequency = old_repeaters[0].frequency();
if
( old_frequency.step_type() == m_frequency.step_type() &&
old_frequency.num_steps() == m_frequency.num_steps()
)
{
return;
}
}
p_journal.clear_repeaters();
Repeater new_repeater(m_database_connection);
new_repeater.set_frequency(m_frequency);
new_repeater.set_next_date(gregorian::day_clock::local_day());
assert (p_journal.repeaters().empty());
p_journal.push_repeater(new_repeater);
return;
}
} // namespace phatbooks
<commit_msg>Changed name of "system generated" Account, "BUDGET IMBALANCE", to "Budget imbalance" - easier on the eyes.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "amalgamated_budget.hpp"
#include "account.hpp"
#include "account_impl.hpp"
#include "account_type.hpp"
#include "budget_item_reader.hpp"
#include "draft_journal.hpp"
#include "entry.hpp"
#include "frequency.hpp"
#include "interval_type.hpp"
#include "phatbooks_exceptions.hpp"
#include "repeater.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/static_assert.hpp>
#include <jewel/decimal.hpp>
#include <sqloxx/sql_statement.hpp>
#include <algorithm>
#include <cassert>
#include <numeric>
#include <ostream>
#include <utility>
#include <vector>
using boost::scoped_ptr;
using jewel::Decimal;
using sqloxx::SQLStatement;
using std::accumulate;
using std::ostream;
using std::pair;
using std::vector;
namespace gregorian = boost::gregorian;
// For debugging only
#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;
// End debugging stuff
namespace phatbooks
{
BOOST_STATIC_ASSERT((boost::is_same<Account::Id, AccountImpl::Id>::value));
void
AmalgamatedBudget::setup_tables(PhatbooksDatabaseConnection& dbc)
{
dbc.execute_sql
( "create index budget_item_account_index on budget_items(account_id)"
);
// NOTE UserDraftJournalReader has knowledge of this schema. Ensure
// any changes to the schema are also reflected there, as appropriate.
dbc.execute_sql
( "create table amalgamated_budget_data"
"("
"journal_id integer unique not null "
"references draft_journal_detail, "
"balancing_account_id integer unique not null "
"references accounts"
")"
);
DraftJournal instrument(dbc);
instrument.set_name("AMALGAMATED BUDGET JOURNAL");
instrument.set_whether_actual(false);
instrument.set_comment("");
Repeater repeater(dbc);
repeater.set_frequency(Frequency(1, interval_type::days));
repeater.set_next_date(gregorian::day_clock::local_day());
instrument.push_repeater(repeater);
instrument.save();
Account balancing_account(dbc);
balancing_account.set_account_type(account_type::pure_envelope);
balancing_account.set_name("Budget imbalance");
balancing_account.set_description("");
Commodity const balancing_account_commodity = dbc.default_commodity();
balancing_account.set_commodity(balancing_account_commodity);
balancing_account.save();
SQLStatement statement
( dbc,
"insert into amalgamated_budget_data"
"(journal_id, balancing_account_id) "
"values(:journal_id, :balancing_account_id)"
);
statement.bind(":journal_id", instrument.id());
statement.bind(":balancing_account_id", balancing_account.id());
statement.step_final();
return;
}
AmalgamatedBudget::AmalgamatedBudget
( PhatbooksDatabaseConnection& p_database_connection
):
m_is_loaded(false),
m_database_connection(p_database_connection),
m_frequency(1, interval_type::days),
m_map(new Map),
m_instrument(0),
m_balancing_account(0)
{
}
AmalgamatedBudget::~AmalgamatedBudget()
{
delete m_instrument;
m_instrument = 0;
delete m_balancing_account;
m_balancing_account = 0;
}
void
AmalgamatedBudget::load() const
{
if (m_is_loaded)
{
return;
}
assert (!m_is_loaded);
load_balancing_account();
load_instrument();
load_map();
m_is_loaded = true;
return;
}
Frequency
AmalgamatedBudget::frequency() const
{
load();
assert (m_frequency.num_steps() == 1);
return m_frequency;
}
void
AmalgamatedBudget::set_frequency(Frequency const& p_frequency)
{
load();
m_frequency = p_frequency;
regenerate();
return;
}
Decimal
AmalgamatedBudget::budget(AccountImpl::Id p_account_id) const
{
load();
Map::const_iterator it = m_map->find(p_account_id);
assert (it != m_map->end());
return it->second;
}
namespace
{
Decimal map_entry_accumulation_aux
( Decimal const& dec,
pair<AccountImpl::Id, Decimal> const& rhs
)
{
return dec + rhs.second;
}
} // end anonymous namespace
Decimal
AmalgamatedBudget::balance() const
{
load();
return accumulate
( m_map->begin(),
m_map->end(),
Decimal(0, 0),
map_entry_accumulation_aux
);
}
void
AmalgamatedBudget::generate_supported_frequencies(vector<Frequency>& vec)
{
// NOTE This is co-dependent with the function
// AmalgamatedBudget::supports_frequency. If this
// changes, that must change too.
vec.reserve(10);
vec.push_back(Frequency(1, interval_type::days));
vec.push_back(Frequency(1, interval_type::weeks));
vec.push_back(Frequency(2, interval_type::weeks));
vec.push_back(Frequency(4, interval_type::weeks));
vec.push_back(Frequency(1, interval_type::months));
vec.push_back(Frequency(2, interval_type::months));
vec.push_back(Frequency(3, interval_type::months));
vec.push_back(Frequency(4, interval_type::months));
vec.push_back(Frequency(6, interval_type::months));
vec.push_back(Frequency(12, interval_type::months));
return;
}
bool
AmalgamatedBudget::supports_frequency(Frequency const& p_frequency)
{
// NOTE This is co-dependent with the function
// AmalgamatedBudget::supported_frequencies. If this changes,
// that must change too.
switch (p_frequency.step_type())
{
case interval_type::days:
return p_frequency.num_steps() == 1;
case interval_type::weeks:
switch (p_frequency.num_steps())
{
case 1: case 2: return true;
case 3: return false;
case 4: return true;
default: return false;
}
case interval_type::months:
switch (p_frequency.num_steps())
{
case 1: case 2: case 3: case 4: return true;
case 5: return false;
case 6: return true;
case 7: case 8: case 9: case 10: case 11: return false;
case 12: return true;
default: return false;
}
case interval_type::month_ends:
return false;
default:
assert (false);
}
}
Account
AmalgamatedBudget::balancing_account() const
{
load();
assert (m_balancing_account != 0);
return *m_balancing_account;
}
DraftJournal
AmalgamatedBudget::instrument() const
{
load();
return *m_instrument;
}
void
AmalgamatedBudget::regenerate()
{
// If amalgamated_budget_data has not yet been populated, then
// proceeding here would cause the program to crash, as
// we wouldn't be able to load the balancing account id, etc..
// So if amalgamated_budget_data has not been created yet,
// we simply return. It is expected this will only happen on
// initial setup of the database (due to calling of
// regenerate() by hook in AccountImpl saving method, when
// balancing account is first saved).
SQLStatement statement
( m_database_connection,
"select * from amalgamated_budget_data"
);
if (statement.step())
{
load();
regenerate_map();
regenerate_instrument();
statement.step_final();
}
return;
}
void
AmalgamatedBudget::load_map() const
{
assert (!m_is_loaded);
assert (m_map->empty());
generate_map();
return;
}
void
AmalgamatedBudget::generate_map() const
{
scoped_ptr<Map> map_elect(new Map);
assert (map_elect->empty());
SQLStatement account_selector
( m_database_connection,
"select account_id from accounts"
);
while (account_selector.step())
{
AccountImpl::Id const account_id =
account_selector.extract<AccountImpl::Id>(0);
Account const account(m_database_connection, account_id);
(*map_elect)[account_id] =
Decimal(0, account.commodity().precision());
}
BudgetItemReader budget_item_reader(m_database_connection);
BudgetItemReader::const_iterator const beg = budget_item_reader.begin();
BudgetItemReader::const_iterator const end = budget_item_reader.end();
// First we calculate budgets amalgamated on the basis of
// the canonical frequency
BudgetItemReader::const_iterator it = beg;
for ( ; it != end; ++it)
{
Frequency const raw_frequency = it->frequency();
if (!AmalgamatedBudget::supports_frequency(raw_frequency))
{
throw InvalidFrequencyException
( "Frequency not supported by AmalgamatedBudget."
);
}
AccountImpl::Id const account_id = it->account().id();
jewel::Decimal const raw_amount = it->amount();
jewel::Decimal const canonical_amount = convert_to_canonical
( raw_frequency,
raw_amount
);
Map::iterator tmit = map_elect->find(account_id);
assert (tmit != map_elect->end());
tmit->second += canonical_amount;
}
// Now convert to desired frequency
for
( Map::iterator mit = map_elect->begin(), mend = map_elect->end();
mit != mend;
++mit
)
{
mit->second = round
( convert_from_canonical(m_frequency, mit->second),
Account(m_database_connection, mit->first).commodity().precision()
);
}
using std::swap;
swap(m_map, map_elect);
return;
}
void
AmalgamatedBudget::regenerate_map()
{
load();
generate_map();
return;
}
void
AmalgamatedBudget::regenerate_instrument()
{
load();
DraftJournal fresh_journal(m_database_connection);
fresh_journal.mimic(*m_instrument);
reflect_entries(fresh_journal);
reflect_repeater(fresh_journal);
// Deal with imbalance
Decimal const imbalance = fresh_journal.balance();
if (imbalance != Decimal(0, 0))
{
Account const ba = balancing_account();
Entry balancing_entry(m_database_connection);
balancing_entry.set_account(ba);
balancing_entry.set_comment("");
balancing_entry.set_whether_reconciled(false);
balancing_entry.set_amount
( -round(imbalance, ba.commodity().precision())
);
fresh_journal.push_entry(balancing_entry);
assert (fresh_journal.is_balanced());
}
m_instrument->mimic(fresh_journal);
m_instrument->save();
return;
}
void
AmalgamatedBudget::load_balancing_account() const
{
SQLStatement statement
( m_database_connection,
"select balancing_account_id from amalgamated_budget_data"
);
bool check = statement.step();
assert (check);
if (m_balancing_account)
{
delete m_balancing_account;
m_balancing_account = 0;
}
m_balancing_account = new Account
( m_database_connection,
statement.extract<Account::Id>(0)
);
statement.step_final();
return;
}
void
AmalgamatedBudget::load_instrument() const
{
// Set the instrument (the DraftJournal that carries out
// the AmalgamatedBudget)
SQLStatement statement
( m_database_connection,
"select journal_id from amalgamated_budget_data"
);
statement.step();
if (m_instrument)
{
delete m_instrument;
m_instrument = 0;
}
m_instrument = new DraftJournal
( m_database_connection,
statement.extract<DraftJournal::Id>(0)
);
statement.step_final();
return;
}
void
AmalgamatedBudget::reflect_entries(DraftJournal& p_journal)
{
load();
p_journal.clear_entries();
Map const& map = *m_map;
for
( Map::const_iterator it = map.begin(), end = map.end();
it != end;
++it
)
{
if (it->second != Decimal(0, 0))
{
Entry entry(m_database_connection);
entry.set_account
( Account(m_database_connection, it->first)
);
entry.set_comment("");
entry.set_amount(-(it->second));
entry.set_whether_reconciled(false);
p_journal.push_entry(entry);
}
}
return;
}
void
AmalgamatedBudget::reflect_repeater(DraftJournal& p_journal)
{
load();
vector<Repeater> const& old_repeaters = p_journal.repeaters();
if (old_repeaters.size() == 1)
{
Frequency const old_frequency = old_repeaters[0].frequency();
if
( old_frequency.step_type() == m_frequency.step_type() &&
old_frequency.num_steps() == m_frequency.num_steps()
)
{
return;
}
}
p_journal.clear_repeaters();
Repeater new_repeater(m_database_connection);
new_repeater.set_frequency(m_frequency);
new_repeater.set_next_date(gregorian::day_clock::local_day());
assert (p_journal.repeaters().empty());
p_journal.push_repeater(new_repeater);
return;
}
} // namespace phatbooks
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, 2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SIM_POWER_POWER_MODEL_HH__
#define __SIM_POWER_POWER_MODEL_HH__
#include "base/statistics.hh"
#include "enums/PMType.hh"
#include "params/PowerModel.hh"
#include "params/PowerModelState.hh"
#include "sim/probe/probe.hh"
class SimObject;
class ClockedObject;
/**
* A PowerModelState is an abstract class used as interface to get power
* figures out of SimObjects
*/
class PowerModelState : public SimObject
{
public:
typedef PowerModelStateParams Params;
PowerModelState(const Params *p);
/**
* Get the dynamic power consumption.
*
* @return Power (Watts) consumed by this object (dynamic component)
*/
virtual double getDynamicPower() const = 0;
/**
* Get the static power consumption.
*
* @return Power (Watts) consumed by this object (static component)
*/
virtual double getStaticPower() const = 0;
/**
* Temperature update.
*
* @param temp Current temperature of the HW part (Celsius)
*/
virtual void setTemperature(double temp) { _temp = temp; }
void setClockedObject(ClockedObject * clkobj) {
clocked_object = clkobj;
}
void regStats() {
dynamicPower
.method(this, &PowerModelState::getDynamicPower)
.name(params()->name + ".dynamic_power")
.desc("Dynamic power for this object (Watts)")
;
staticPower
.method(this, &PowerModelState::getStaticPower)
.name(params()->name + ".static_power")
.desc("Static power for this object (Watts)")
;
}
protected:
Stats::Value dynamicPower, staticPower;
/** Current temperature */
double _temp;
/** The clocked object we belong to */
ClockedObject * clocked_object;
};
/**
* @sa \ref gem5PowerModel "gem5 Power Model"
*
* A PowerModel is a class containing a power model for a SimObject.
* The PM describes the power consumption for every power state.
*/
class PowerModel : public SimObject
{
public:
typedef PowerModelParams Params;
PowerModel(const Params *p);
/**
* Get the dynamic power consumption.
*
* @return Power (Watts) consumed by this object (dynamic component)
*/
double getDynamicPower() const;
/**
* Get the static power consumption.
*
* @return Power (Watts) consumed by this object (static component)
*/
double getStaticPower() const;
void regStats() {
dynamicPower
.method(this, &PowerModel::getDynamicPower)
.name(params()->name + ".dynamic_power")
.desc("Dynamic power for this power state")
;
staticPower
.method(this, &PowerModel::getStaticPower)
.name(params()->name + ".static_power")
.desc("Static power for this power state")
;
}
void setClockedObject(ClockedObject *clkobj);
virtual void regProbePoints();
void thermalUpdateCallback(const double & temp);
protected:
/** Listener class to catch thermal events */
class ThermalProbeListener : public ProbeListenerArgBase<double>
{
public:
ThermalProbeListener(PowerModel &_pm, ProbeManager *pm,
const std::string &name)
: ProbeListenerArgBase(pm, name), pm(_pm) {}
void notify(const double &temp)
{
pm.thermalUpdateCallback(temp);
}
protected:
PowerModel ±
};
Stats::Value dynamicPower, staticPower;
/** Actual power models (one per power state) */
std::vector<PowerModelState*> states_pm;
/** Listener to catch temperature changes in the SubSystem */
std::unique_ptr<ThermalProbeListener> thermalListener;
/** The subsystem this power model belongs to */
SubSystem * subsystem;
/** The clocked object we belong to */
ClockedObject * clocked_object;
/** The type of power model - collects all power, static or dynamic only */
Enums::PMType power_model_type;
};
#endif
<commit_msg>power: Fix regStats for PowerModel and PowerModelState<commit_after>/*
* Copyright (c) 2016, 2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SIM_POWER_POWER_MODEL_HH__
#define __SIM_POWER_POWER_MODEL_HH__
#include "base/statistics.hh"
#include "enums/PMType.hh"
#include "params/PowerModel.hh"
#include "params/PowerModelState.hh"
#include "sim/probe/probe.hh"
class SimObject;
class ClockedObject;
/**
* A PowerModelState is an abstract class used as interface to get power
* figures out of SimObjects
*/
class PowerModelState : public SimObject
{
public:
typedef PowerModelStateParams Params;
PowerModelState(const Params *p);
/**
* Get the dynamic power consumption.
*
* @return Power (Watts) consumed by this object (dynamic component)
*/
virtual double getDynamicPower() const = 0;
/**
* Get the static power consumption.
*
* @return Power (Watts) consumed by this object (static component)
*/
virtual double getStaticPower() const = 0;
/**
* Temperature update.
*
* @param temp Current temperature of the HW part (Celsius)
*/
virtual void setTemperature(double temp) { _temp = temp; }
void setClockedObject(ClockedObject * clkobj) {
clocked_object = clkobj;
}
void regStats() {
SimObject::regStats();
dynamicPower
.method(this, &PowerModelState::getDynamicPower)
.name(params()->name + ".dynamic_power")
.desc("Dynamic power for this object (Watts)")
;
staticPower
.method(this, &PowerModelState::getStaticPower)
.name(params()->name + ".static_power")
.desc("Static power for this object (Watts)")
;
}
protected:
Stats::Value dynamicPower, staticPower;
/** Current temperature */
double _temp;
/** The clocked object we belong to */
ClockedObject * clocked_object;
};
/**
* @sa \ref gem5PowerModel "gem5 Power Model"
*
* A PowerModel is a class containing a power model for a SimObject.
* The PM describes the power consumption for every power state.
*/
class PowerModel : public SimObject
{
public:
typedef PowerModelParams Params;
PowerModel(const Params *p);
/**
* Get the dynamic power consumption.
*
* @return Power (Watts) consumed by this object (dynamic component)
*/
double getDynamicPower() const;
/**
* Get the static power consumption.
*
* @return Power (Watts) consumed by this object (static component)
*/
double getStaticPower() const;
void regStats() {
SimObject::regStats();
dynamicPower
.method(this, &PowerModel::getDynamicPower)
.name(params()->name + ".dynamic_power")
.desc("Dynamic power for this power state")
;
staticPower
.method(this, &PowerModel::getStaticPower)
.name(params()->name + ".static_power")
.desc("Static power for this power state")
;
}
void setClockedObject(ClockedObject *clkobj);
virtual void regProbePoints();
void thermalUpdateCallback(const double & temp);
protected:
/** Listener class to catch thermal events */
class ThermalProbeListener : public ProbeListenerArgBase<double>
{
public:
ThermalProbeListener(PowerModel &_pm, ProbeManager *pm,
const std::string &name)
: ProbeListenerArgBase(pm, name), pm(_pm) {}
void notify(const double &temp)
{
pm.thermalUpdateCallback(temp);
}
protected:
PowerModel ±
};
Stats::Value dynamicPower, staticPower;
/** Actual power models (one per power state) */
std::vector<PowerModelState*> states_pm;
/** Listener to catch temperature changes in the SubSystem */
std::unique_ptr<ThermalProbeListener> thermalListener;
/** The subsystem this power model belongs to */
SubSystem * subsystem;
/** The clocked object we belong to */
ClockedObject * clocked_object;
/** The type of power model - collects all power, static or dynamic only */
Enums::PMType power_model_type;
};
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/atomicops.h"
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
const base::subtle::Atomic32 kMagicValue = 42;
void ReadUninitializedValue(char *ptr) {
// The || in the conditional is to prevent clang from optimizing away the
// jump -- valgrind only catches jumps and conditional moves, but clang uses
// the borrow flag if the condition is just `*ptr == '\0'`.
if (*ptr == '\0' || *ptr == 64) {
(*ptr)++;
} else {
(*ptr)--;
}
}
void ReadValueOutOfArrayBoundsLeft(char *ptr) {
char c = ptr[-2];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
char c = ptr[size + 1];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
ptr[-1] = kMagicValue;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
ptr[size] = kMagicValue;
}
void MakeSomeErrors(char *ptr, size_t size) {
ReadUninitializedValue(ptr);
ReadValueOutOfArrayBoundsLeft(ptr);
ReadValueOutOfArrayBoundsRight(ptr, size);
WriteValueOutOfArrayBoundsLeft(ptr);
WriteValueOutOfArrayBoundsRight(ptr, size);
}
} // namespace
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
TEST(ToolsSanityTest, AccessesToNewMemory) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
char *foo = new char[10];
MakeSomeErrors(foo, 10);
delete [] foo;
foo[5] = 0; // Use after delete. This won't break anything under Valgrind.
}
TEST(ToolsSanityTest, AccessesToMallocMemory) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
char *foo = reinterpret_cast<char*>(malloc(10));
MakeSomeErrors(foo, 10);
free(foo);
foo[5] = 0; // Use after free. This won't break anything under Valgrind.
}
TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int[10];
delete foo;
}
TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int;
(void) foo;
delete [] foo;
}
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
bool *value_;
};
class ReleaseStoreThread : public PlatformThread::Delegate {
public:
explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
~ReleaseStoreThread() {}
void ThreadMain() {
base::subtle::Release_Store(value_, kMagicValue);
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
base::subtle::Atomic32 *value_;
};
class AcquireLoadThread : public PlatformThread::Delegate {
public:
explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
~AcquireLoadThread() {}
void ThreadMain() {
// Wait for the other thread to make Release_Store
PlatformThread::Sleep(100);
base::subtle::Acquire_Load(value_);
}
private:
base::subtle::Atomic32 *value_;
};
void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Create(0, d1, &a);
PlatformThread::Create(0, d2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
}
} // namespace
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AnnotateBenignRace) {
bool shared = false;
ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AtomicsAreIgnored) {
base::subtle::Atomic32 shared = 0;
ReleaseStoreThread thread1(&shared);
AcquireLoadThread thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_EQ(kMagicValue, shared);
}
} // namespace base
<commit_msg>Actually run the sanity tests under AddressSanitizer. Review URL: http://codereview.chromium.org/8116028<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file contains intentional memory errors, some of which may lead to
// crashes if the test is ran without special memory testing tools. We use these
// errors to verify the sanity of the tools.
#include "base/atomicops.h"
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
const base::subtle::Atomic32 kMagicValue = 42;
// Helper for memory accesses that can potentially corrupt memory or cause a
// crash during a native run.
#ifdef ADDRESS_SANITIZER
#define HARMFUL_ACCESS(action,error_regexp) EXPECT_DEATH(action,error_regexp)
#else
#define HARMFUL_ACCESS(action,error_regexp) \
do { if (RunningOnValgrind()) { action; } } while (0)
#endif
void ReadUninitializedValue(char *ptr) {
// The || in the conditional is to prevent clang from optimizing away the
// jump -- valgrind only catches jumps and conditional moves, but clang uses
// the borrow flag if the condition is just `*ptr == '\0'`.
if (*ptr == '\0' || *ptr == 64) {
(*ptr)++;
} else {
(*ptr)--;
}
}
void ReadValueOutOfArrayBoundsLeft(char *ptr) {
char c = ptr[-2];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
char c = ptr[size + 1];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
ptr[-1] = kMagicValue;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
ptr[size] = kMagicValue;
}
void MakeSomeErrors(char *ptr, size_t size) {
ReadUninitializedValue(ptr);
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(ptr),
"heap-buffer-overflow.*2 bytes to the left");
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(ptr, size),
"heap-buffer-overflow.*1 bytes to the right");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(ptr),
"heap-buffer-overflow.*1 bytes to the left");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(ptr, size),
"heap-buffer-overflow.*0 bytes to the right");
}
} // namespace
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
TEST(ToolsSanityTest, AccessesToNewMemory) {
char *foo = new char[10];
MakeSomeErrors(foo, 10);
delete [] foo;
// Use after delete.
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, AccessesToMallocMemory) {
char *foo = reinterpret_cast<char*>(malloc(10));
MakeSomeErrors(foo, 10);
free(foo);
// Use after free.
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
#ifndef ADDRESS_SANITIZER
// This test may corrupt memory if not run under Valgrind or compiled with
// AddressSanitizer.
if (!RunningOnValgrind())
return;
#endif
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int[10];
delete foo;
}
TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
#ifndef ADDRESS_SANITIZER
// This test may corrupt memory if not run under Valgrind or compiled with
// AddressSanitizer.
if (!RunningOnValgrind())
return;
#endif
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int;
(void) foo;
delete [] foo;
}
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
bool *value_;
};
class ReleaseStoreThread : public PlatformThread::Delegate {
public:
explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
~ReleaseStoreThread() {}
void ThreadMain() {
base::subtle::Release_Store(value_, kMagicValue);
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
base::subtle::Atomic32 *value_;
};
class AcquireLoadThread : public PlatformThread::Delegate {
public:
explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
~AcquireLoadThread() {}
void ThreadMain() {
// Wait for the other thread to make Release_Store
PlatformThread::Sleep(100);
base::subtle::Acquire_Load(value_);
}
private:
base::subtle::Atomic32 *value_;
};
void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Create(0, d1, &a);
PlatformThread::Create(0, d2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
}
} // namespace
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AnnotateBenignRace) {
bool shared = false;
ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AtomicsAreIgnored) {
base::subtle::Atomic32 shared = 0;
ReleaseStoreThread thread1(&shared);
AcquireLoadThread thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_EQ(kMagicValue, shared);
}
} // namespace base
<|endoftext|> |
<commit_before>// Author:Frankie.Chu
// Date:9 April,2012
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Modified record:
//
/*******************************************************************************/
#include "TM1637.h"
#include <inttypes.h>
#include "../wiring/wiring.h"
static int8_t TubeTab[] = {0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};//0~9,A,b,C,d,E,F
TM1637::TM1637(uint8_t Clk, uint8_t Data)
{
Clkpin = Clk;
Datapin = Data;
pinMode(Clkpin,OUTPUT);
pinMode(Datapin,OUTPUT);
}
void TM1637::init(void)
{
clearDisplay();
}
void TM1637::writeByte(int8_t wr_data)
{
uint8_t i,count1;
for(i=0;i<8;i++) //sent 8bit data
{
digitalWrite(Clkpin,LOW);
if(wr_data & 0x01)digitalWrite(Datapin,HIGH);//LSB first
else digitalWrite(Datapin,LOW);
wr_data >>= 1;
digitalWrite(Clkpin,HIGH);
}
digitalWrite(Clkpin,LOW); //wait for the ACK
digitalWrite(Datapin,HIGH);
digitalWrite(Clkpin,HIGH);
pinMode(Datapin,INPUT);
while(digitalRead(Datapin))
{
count1 +=1;
if(count1 == 200)//
{
pinMode(Datapin,OUTPUT);
digitalWrite(Datapin,LOW);
count1 =0;
}
pinMode(Datapin,INPUT);
}
pinMode(Datapin,OUTPUT);
}
//send start signal to TM1637
void TM1637::start(void)
{
digitalWrite(Clkpin,HIGH);//send start signal to TM1637
digitalWrite(Datapin,HIGH);
digitalWrite(Datapin,LOW);
digitalWrite(Clkpin,LOW);
}
//End of transmission
void TM1637::stop(void)
{
digitalWrite(Clkpin,LOW);
digitalWrite(Datapin,LOW);
digitalWrite(Clkpin,HIGH);
digitalWrite(Datapin,HIGH);
}
//display function.Write to full-screen.
void TM1637::display(int8_t DispData[])
{
int8_t SegData[4];
uint8_t i;
for(i = 0;i < 4;i ++)
{
SegData[i] = DispData[i];
}
coding(SegData);
start(); //start signal sent to TM1637 from MCU
writeByte(ADDR_AUTO);//
stop(); //
start(); //
writeByte(Cmd_SetAddr);//
for(i=0;i < 4;i ++)
{
writeByte(SegData[i]); //
}
stop(); //
start(); //
writeByte(Cmd_DispCtrl);//
stop(); //
}
//******************************************
void TM1637::display(uint8_t BitAddr,int8_t DispData)
{
int8_t SegData;
SegData = coding(DispData);
start(); //start signal sent to TM1637 from MCU
writeByte(ADDR_FIXED);//
stop(); //
start(); //
writeByte(BitAddr|0xc0);//
writeByte(SegData);//
stop(); //
start(); //
writeByte(Cmd_DispCtrl);//
stop(); //
}
void TM1637::clearDisplay(void)
{
display(0x00,0x7f);
display(0x01,0x7f);
display(0x02,0x7f);
display(0x03,0x7f);
}
//To take effect the next time it displays.
void TM1637::set(uint8_t brightness,uint8_t SetData,uint8_t SetAddr)
{
Cmd_SetData = SetData;
Cmd_SetAddr = SetAddr;
Cmd_DispCtrl = 0x88 + brightness;//Set the brightness and it takes effect the next time it displays.
}
//Whether to light the clock point ":".
//To take effect the next time it displays.
void TM1637::point(boolean PointFlag)
{
_PointFlag = PointFlag;
}
void TM1637::coding(int8_t DispData[])
{
uint8_t PointData;
if(_PointFlag == POINT_ON)PointData = 0x80;
else PointData = 0;
for(uint8_t i = 0;i < 4;i ++)
{
if(DispData[i] == 0x7f)DispData[i] = 0x00;
else DispData[i] = TubeTab[DispData[i]] + PointData;
}
}
int8_t TM1637::coding(int8_t DispData)
{
uint8_t PointData;
if(_PointFlag == POINT_ON)PointData = 0x80;
else PointData = 0;
if(DispData == 0x7f) DispData = 0x00 + PointData;//The bit digital tube off
else DispData = TubeTab[DispData] + PointData;
return DispData;
}
<commit_msg>Update TM1637.cpp<commit_after>// Author:Frankie.Chu
// Date:9 April,2012
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Modified record:
//
/*******************************************************************************/
#include "TM1637.h"
#include <inttypes.h>
#include "../wiring/wiring.h"
static int8_t TubeTab[] = {0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};//0~9,A,b,C,d,E,F
TM1637::TM1637(uint8_t Clk, uint8_t Data)
{
Clkpin = Clk;
Datapin = Data;
pinMode(Clkpin,OUTPUT);
pinMode(Datapin,OUTPUT);
}
void TM1637::init(void)
{
clearDisplay();
}
void TM1637::writeByte(int8_t wr_data)
{
uint8_t i,count1;
for(i=0;i<8;i++) //sent 8bit data
{
digitalWrite(Clkpin,LOW);
if(wr_data & 0x01)digitalWrite(Datapin,HIGH);//LSB first
else digitalWrite(Datapin,LOW);
wr_data >>= 1;
digitalWrite(Clkpin,HIGH);
}
digitalWrite(Clkpin,LOW); //wait for the ACK
digitalWrite(Datapin,HIGH);
digitalWrite(Clkpin,HIGH);
pinMode(Datapin,INPUT);
while(digitalRead(Datapin))
{
count1 +=1;
if(count1 == 200)//
{
pinMode(Datapin,OUTPUT);
digitalWrite(Datapin,LOW);
count1 =0;
}
pinMode(Datapin,INPUT);
}
pinMode(Datapin,OUTPUT);
}
//send start signal to TM1637
void TM1637::start(void)
{
digitalWrite(Clkpin,HIGH);//send start signal to TM1637
digitalWrite(Datapin,HIGH);
digitalWrite(Datapin,LOW);
digitalWrite(Clkpin,LOW);
}
//End of transmission
void TM1637::stop(void)
{
digitalWrite(Clkpin,LOW);
digitalWrite(Datapin,LOW);
digitalWrite(Clkpin,HIGH);
digitalWrite(Datapin,HIGH);
}
//display function.Write to full-screen.
void TM1637::display(int8_t DispData[])
{
int8_t SegData[4];
uint8_t i;
for(i = 0;i < 4;i ++)
{
SegData[i] = DispData[i];
}
coding(SegData);
start(); //start signal sent to TM1637 from MCU
writeByte(ADDR_AUTO);//
stop(); //
start(); //
writeByte(Cmd_SetAddr);//
for(i=0;i < 4;i ++)
{
writeByte(SegData[i]); //
}
stop(); //
start(); //
writeByte(Cmd_DispCtrl);//
stop(); //
}
//******************************************
void TM1637::display(uint8_t BitAddr,int8_t DispData)
{
int8_t SegData;
SegData = coding(DispData);
start(); //start signal sent to TM1637 from MCU
writeByte(ADDR_FIXED);//
stop(); //
start(); //
writeByte(BitAddr|0xc0);//
writeByte(SegData);//
stop(); //
start(); //
writeByte(Cmd_DispCtrl);//
stop(); //
}
void TM1637::clearDisplay(void)
{
display(0x00,0x7f);
display(0x01,0x7f);
display(0x02,0x7f);
display(0x03,0x7f);
}
//To take effect the next time it displays.
void TM1637::set(uint8_t brightness,uint8_t SetData,uint8_t SetAddr)
{
Cmd_SetData = SetData;
Cmd_SetAddr = SetAddr;
Cmd_DispCtrl = 0x88 + brightness;//Set the brightness and it takes effect the next time it displays.
}
//Whether to light the clock point ":".
//To take effect the next time it displays.
void TM1637::point(bool PointFlag)
{
_PointFlag = PointFlag;
}
void TM1637::coding(int8_t DispData[])
{
uint8_t PointData;
if(_PointFlag == POINT_ON)PointData = 0x80;
else PointData = 0;
for(uint8_t i = 0;i < 4;i ++)
{
if(DispData[i] == 0x7f)DispData[i] = 0x00;
else DispData[i] = TubeTab[DispData[i]] + PointData;
}
}
int8_t TM1637::coding(int8_t DispData)
{
uint8_t PointData;
if(_PointFlag == POINT_ON)PointData = 0x80;
else PointData = 0;
if(DispData == 0x7f) DispData = 0x00 + PointData;//The bit digital tube off
else DispData = TubeTab[DispData] + PointData;
return DispData;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.