text stringlengths 54 60.6k |
|---|
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetOptionsTest
#include <boost/test/unit_test.hpp>
#define private public
#include "../../JPetOptions/JPetOptions.h"
//JPetOptions
//public methods
//JPetOptions();
//explicit JPetOptions(const Options& opts);
//bool areCorrect(const Options& opts) const;
//const char* getInputFile() const;
//const char* getOutputFile() const;
//long long getFirstEvent() const;
//long long getLastEvent() const;
//int getRunNumber() const;
//bool isProgressBar() const;
//FileType getInputFileType() const;
//FileType getOutputFileType() const;
//inline Options getOptions() const;
//static Options getDefaultOptions();
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE( my_test1 )
{
JPetOptions opts;
auto default_opts = JPetOptions::getDefaultOptions();
BOOST_REQUIRE(opts.getOptions() == default_opts);
}
BOOST_AUTO_TEST_CASE(petOptionsDefaultConstrutorTest)
{
JPetOptions::Options options = {
{"inputFile", ""},
{"inputFileType", ""},
{"outputFile", ""},
{"outputFileType", ""},
{"firstEvent", "-1"},
{"lastEvent", "-1"},
{"progressBar", "false"},
{"runId", "-1"}
};
JPetOptions petOptions;
BOOST_REQUIRE_EQUAL(CommonTools::mapComparator(petOptions.getOptions(), options), true);
}
BOOST_AUTO_TEST_CASE(petOptionsBasicTest)
{
JPetOptions::Options options = {
{"inputFile", "input"},
{"outputFile", "output"},
{"firstEvent", "8246821 0xffff 020"},
{"lastEvent", "8246821 0xffff 020"},
{"runId", "2001, A Space Odyssey"},
{"progressBar", "true"},
{"inputFileType", "root"},
{"outputFileType", "scope"}
};
JPetOptions petOptions(options);
BOOST_REQUIRE_EQUAL(petOptions.getInputFile(), "input");
BOOST_REQUIRE_EQUAL(petOptions.getOutputFile(), "output");
auto firstEvent = petOptions.getFirstEvent();
BOOST_REQUIRE_EQUAL(firstEvent, 8246821);
auto lastEvent = petOptions.getLastEvent();
BOOST_REQUIRE_EQUAL(lastEvent, 8246821);
int runNumberHex = petOptions.getRunNumber();
BOOST_REQUIRE_EQUAL(runNumberHex, 2001);
BOOST_REQUIRE_EQUAL(petOptions.isProgressBar(), true);
BOOST_REQUIRE_EQUAL(petOptions.getInputFileType(), JPetOptions::FileType::kRoot);
BOOST_REQUIRE_EQUAL(petOptions.getOutputFileType(), JPetOptions::FileType::kScope);
BOOST_REQUIRE_EQUAL(CommonTools::mapComparator(petOptions.getOptions(), options), true);
BOOST_REQUIRE_EQUAL(CommonTools::mapComparator(petOptions.getDefaultOptions(), options), false);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Make petOptionsDefaultConstrutorTest successful.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetOptionsTest
#include <boost/test/unit_test.hpp>
#define private public
#include "../../JPetOptions/JPetOptions.h"
//JPetOptions
//public methods
//JPetOptions();
//explicit JPetOptions(const Options& opts);
//bool areCorrect(const Options& opts) const;
//const char* getInputFile() const;
//const char* getOutputFile() const;
//long long getFirstEvent() const;
//long long getLastEvent() const;
//int getRunNumber() const;
//bool isProgressBar() const;
//FileType getInputFileType() const;
//FileType getOutputFileType() const;
//inline Options getOptions() const;
//static Options getDefaultOptions();
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE( my_test1 )
{
JPetOptions opts;
auto default_opts = JPetOptions::getDefaultOptions();
BOOST_REQUIRE(opts.getOptions() == default_opts);
}
BOOST_AUTO_TEST_CASE(petOptionsDefaultConstrutorTest)
{
JPetOptions::Options options = {
{"inputFile", ""},
{"inputFileType", ""},
{"outputFile", "root"},
{"outputFileType", "test.root"},
{"firstEvent", "-1"},
{"lastEvent", "-1"},
{"progressBar", "false"},
{"runId", "-1"}
};
JPetOptions petOptions;
BOOST_REQUIRE_EQUAL(CommonTools::mapComparator(petOptions.getOptions(), options), true);
}
BOOST_AUTO_TEST_CASE(petOptionsBasicTest)
{
JPetOptions::Options options = {
{"inputFile", "input"},
{"outputFile", "output"},
{"firstEvent", "8246821 0xffff 020"},
{"lastEvent", "8246821 0xffff 020"},
{"runId", "2001, A Space Odyssey"},
{"progressBar", "true"},
{"inputFileType", "root"},
{"outputFileType", "scope"}
};
JPetOptions petOptions(options);
BOOST_REQUIRE_EQUAL(petOptions.getInputFile(), "input");
BOOST_REQUIRE_EQUAL(petOptions.getOutputFile(), "output");
auto firstEvent = petOptions.getFirstEvent();
BOOST_REQUIRE_EQUAL(firstEvent, 8246821);
auto lastEvent = petOptions.getLastEvent();
BOOST_REQUIRE_EQUAL(lastEvent, 8246821);
int runNumberHex = petOptions.getRunNumber();
BOOST_REQUIRE_EQUAL(runNumberHex, 2001);
BOOST_REQUIRE_EQUAL(petOptions.isProgressBar(), true);
BOOST_REQUIRE_EQUAL(petOptions.getInputFileType(), JPetOptions::FileType::kRoot);
BOOST_REQUIRE_EQUAL(petOptions.getOutputFileType(), JPetOptions::FileType::kScope);
BOOST_REQUIRE_EQUAL(CommonTools::mapComparator(petOptions.getOptions(), options), true);
BOOST_REQUIRE_EQUAL(CommonTools::mapComparator(petOptions.getDefaultOptions(), options), false);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> vvi;
vvi.push_back(vector<int> ());
for (int i = 0; i < nums.size(); i++) {
vector<vector<int>> temp;
for (int j = 0; j < vvi.size(); j++) {
vector<int> v(vvi[j]);
v.push_back(nums[i]);
temp.push_back(v);
}
vvi.insert(vvi.end(), temp.begin(), temp.end());
}
return vvi;
}
};
<commit_msg>Delete 078 leetcode subsets<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Declaration of ATL module object for EXE module.
#include <atlbase.h>
#include <atlhost.h>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/logging_win.h"
#include "ceee/ie/broker/broker.h"
#include "ceee/ie/broker/broker_rpc_server.h"
#include "ceee/ie/broker/chrome_postman.h"
#include "ceee/ie/broker/executors_manager.h"
#include "ceee/ie/broker/resource.h"
#include "ceee/ie/broker/window_events_funnel.h"
#include "ceee/ie/common/crash_reporter.h"
#include "ceee/common/com_utils.h"
#include "chrome/common/url_constants.h"
#include "chrome_frame/metrics_service.h"
namespace {
const wchar_t kLogFileName[] = L"CeeeBroker.log";
// {6E3D6168-1DD2-4edb-A183-584C2C66E96D}
const GUID kCeeeBrokerLogProviderName =
{ 0x6e3d6168, 0x1dd2, 0x4edb,
{ 0xa1, 0x83, 0x58, 0x4c, 0x2c, 0x66, 0xe9, 0x6d } };
} // namespace
// Object entries go here instead of with each object, so that we can keep
// the objects in a lib, and also to decrease the amount of magic.
OBJECT_ENTRY_AUTO(__uuidof(CeeeBroker), CeeeBroker)
class CeeeBrokerModule : public CAtlExeModuleT<CeeeBrokerModule> {
public:
CeeeBrokerModule();
~CeeeBrokerModule();
DECLARE_LIBID(LIBID_CeeeBrokerLib)
static HRESULT WINAPI UpdateRegistryAppId(BOOL register) throw();
// We have our own version so that we can explicitly specify
// that we want to be in a multi threaded apartment.
static HRESULT InitializeCom();
// Prevent COM objects we don't own to control our lock count.
// To properly manage our lifespan, yet still be able to control the
// lifespan of the ChromePostman's thread, we must only rely on the
// CeeeBroker implementation of the IExternalConnection interface
// as well as the ExecutorsManager map content to decide when to die.
virtual LONG Lock() {
return 1;
}
virtual LONG Unlock() {
return 1;
}
// We prevent access to the module lock count from objects we don't
// own by overriding the Un/Lock methods above. But when we want to
// access the module lock count, we do it from here, and bypass our
// override. These are the entry points that only our code accesses.
LONG LockModule() {
return CAtlExeModuleT<CeeeBrokerModule>::Lock();
}
LONG UnlockModule() {
return CAtlExeModuleT<CeeeBrokerModule>::Unlock();
}
HRESULT PostMessageLoop();
HRESULT PreMessageLoop(int show);
private:
// We maintain a postman COM object on the stack so that we can
// properly initialize and terminate it at the right time.
CComObjectStackEx<ChromePostman> chrome_postman_;
CrashReporter crash_reporter_;
base::AtExitManager at_exit_;
BrokerRpcServer rpc_server_;
};
CeeeBrokerModule module;
extern "C" int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int nShowCmd) {
return module.WinMain(nShowCmd);
}
CeeeBrokerModule::CeeeBrokerModule()
: crash_reporter_(L"ceee_broker") {
TRACE_EVENT_BEGIN("ceee.broker", this, "");
wchar_t logfile_path[MAX_PATH];
DWORD len = ::GetTempPath(arraysize(logfile_path), logfile_path);
::PathAppend(logfile_path, kLogFileName);
// It seems we're obliged to initialize the current command line
// before initializing logging.
CommandLine::Init(0, NULL);
logging::InitLogging(
logfile_path,
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE,
logging::APPEND_TO_OLD_LOG_FILE);
// Initialize ETW logging.
logging::LogEventProvider::Initialize(kCeeeBrokerLogProviderName);
// Initialize control hosting.
BOOL initialized = AtlAxWinInit();
DCHECK(initialized);
// Needs to be called before we can use GURL.
chrome::RegisterChromeSchemes();
crash_reporter_.InitializeCrashReporting(false);
}
HRESULT CeeeBrokerModule::InitializeCom() {
HRESULT hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
return hr;
// We need to initialize security before setting global options.
hr = ::CoInitializeSecurity(NULL,
-1,
NULL,
NULL,
// Clients must identify.
RPC_C_IMP_LEVEL_IDENTIFY,
// And we identify.
RPC_C_IMP_LEVEL_IDENTIFY,
NULL,
// We don't want low integrity to be able to
// instantiate arbitrary objects in our process.
EOAC_NO_CUSTOM_MARSHAL,
NULL);
DCHECK(SUCCEEDED(hr));
// Ensure the marshaling machinery doesn't eat our crashes.
CComPtr<IGlobalOptions> options;
hr = options.CoCreateInstance(CLSID_GlobalOptions);
if (SUCCEEDED(hr)) {
hr = options->Set(COMGLB_EXCEPTION_HANDLING, COMGLB_EXCEPTION_DONOT_HANDLE);
}
DLOG_IF(WARNING, FAILED(hr)) << "IGlobalOptions::Set failed "
<< com::LogHr(hr);
// The above is best-effort, don't bail on error.
return S_OK;
}
HRESULT CeeeBrokerModule::PreMessageLoop(int show) {
// It's important to initialize the postman BEFORE we make the Broker
// and the event funnel available, since we may get requests to execute
// API invocation or Fire events before the postman is ready to handle them.
chrome_postman_.Init();
WindowEventsFunnel::Initialize();
if (!rpc_server_.Start())
return RPC_E_FAULT;
// Initialize metrics. We need the rpc_server_ above to be available.
MetricsService::Start();
return CAtlExeModuleT<CeeeBrokerModule>::PreMessageLoop(show);
}
HRESULT CeeeBrokerModule::PostMessageLoop() {
HRESULT hr = CAtlExeModuleT<CeeeBrokerModule>::PostMessageLoop();
Singleton<ExecutorsManager,
ExecutorsManager::SingletonTraits>()->Terminate();
WindowEventsFunnel::Terminate();
// Upload data if necessary.
MetricsService::Stop();
chrome_postman_.Term();
return hr;
}
CeeeBrokerModule::~CeeeBrokerModule() {
crash_reporter_.ShutdownCrashReporting();
logging::CloseLogFile();
TRACE_EVENT_END("ceee.broker", this, "");
}
HRESULT WINAPI CeeeBrokerModule::UpdateRegistryAppId(BOOL reg) throw() {
return com::ModuleRegistrationWithoutAppid(IDR_BROKER_MODULE, reg);
}
namespace ceee_module_util {
LONG LockModule() {
return module.LockModule();
}
LONG UnlockModule() {
return module.UnlockModule();
}
} // namespace
<commit_msg>Committing patch http://codereview.chromium.org/5288001/ from vitalybuka@google.com.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Declaration of ATL module object for EXE module.
#include <atlbase.h>
#include <atlhost.h>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/logging_win.h"
#include "ceee/ie/broker/broker.h"
#include "ceee/ie/broker/broker_rpc_server.h"
#include "ceee/ie/broker/chrome_postman.h"
#include "ceee/ie/broker/executors_manager.h"
#include "ceee/ie/broker/resource.h"
#include "ceee/ie/broker/window_events_funnel.h"
#include "ceee/ie/common/crash_reporter.h"
#include "ceee/common/com_utils.h"
#include "chrome/common/url_constants.h"
#include "chrome_frame/metrics_service.h"
namespace {
const wchar_t kLogFileName[] = L"CeeeBroker.log";
// {6E3D6168-1DD2-4edb-A183-584C2C66E96D}
const GUID kCeeeBrokerLogProviderName =
{ 0x6e3d6168, 0x1dd2, 0x4edb,
{ 0xa1, 0x83, 0x58, 0x4c, 0x2c, 0x66, 0xe9, 0x6d } };
} // namespace
// Object entries go here instead of with each object, so that we can keep
// the objects in a lib, and also to decrease the amount of magic.
OBJECT_ENTRY_AUTO(__uuidof(CeeeBroker), CeeeBroker)
class CeeeBrokerModule : public CAtlExeModuleT<CeeeBrokerModule> {
public:
CeeeBrokerModule();
~CeeeBrokerModule();
DECLARE_LIBID(LIBID_CeeeBrokerLib)
static HRESULT WINAPI UpdateRegistryAppId(BOOL register) throw();
// We have our own version so that we can explicitly specify
// that we want to be in a multi threaded apartment.
static HRESULT InitializeCom();
// Prevent COM objects we don't own to control our lock count.
// To properly manage our lifespan, yet still be able to control the
// lifespan of the ChromePostman's thread, we must only rely on the
// CeeeBroker implementation of the IExternalConnection interface
// as well as the ExecutorsManager map content to decide when to die.
virtual LONG Lock() {
return 1;
}
virtual LONG Unlock() {
return 1;
}
// We prevent access to the module lock count from objects we don't
// own by overriding the Un/Lock methods above. But when we want to
// access the module lock count, we do it from here, and bypass our
// override. These are the entry points that only our code accesses.
LONG LockModule() {
return CAtlExeModuleT<CeeeBrokerModule>::Lock();
}
LONG UnlockModule() {
return CAtlExeModuleT<CeeeBrokerModule>::Unlock();
}
HRESULT PostMessageLoop();
HRESULT PreMessageLoop(int show);
private:
void TearDown();
// We maintain a postman COM object on the stack so that we can
// properly initialize and terminate it at the right time.
CComObjectStackEx<ChromePostman> chrome_postman_;
CrashReporter crash_reporter_;
base::AtExitManager at_exit_;
BrokerRpcServer rpc_server_;
};
CeeeBrokerModule module;
extern "C" int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int nShowCmd) {
return module.WinMain(nShowCmd);
}
CeeeBrokerModule::CeeeBrokerModule()
: crash_reporter_(L"ceee_broker") {
TRACE_EVENT_BEGIN("ceee.broker", this, "");
wchar_t logfile_path[MAX_PATH];
DWORD len = ::GetTempPath(arraysize(logfile_path), logfile_path);
::PathAppend(logfile_path, kLogFileName);
// It seems we're obliged to initialize the current command line
// before initializing logging.
CommandLine::Init(0, NULL);
logging::InitLogging(
logfile_path,
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::LOCK_LOG_FILE,
logging::APPEND_TO_OLD_LOG_FILE);
// Initialize ETW logging.
logging::LogEventProvider::Initialize(kCeeeBrokerLogProviderName);
// Initialize control hosting.
BOOL initialized = AtlAxWinInit();
DCHECK(initialized);
// Needs to be called before we can use GURL.
chrome::RegisterChromeSchemes();
crash_reporter_.InitializeCrashReporting(false);
}
HRESULT CeeeBrokerModule::InitializeCom() {
HRESULT hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
return hr;
// We need to initialize security before setting global options.
hr = ::CoInitializeSecurity(NULL,
-1,
NULL,
NULL,
// Clients must identify.
RPC_C_IMP_LEVEL_IDENTIFY,
// And we identify.
RPC_C_IMP_LEVEL_IDENTIFY,
NULL,
// We don't want low integrity to be able to
// instantiate arbitrary objects in our process.
EOAC_NO_CUSTOM_MARSHAL,
NULL);
DCHECK(SUCCEEDED(hr));
// Ensure the marshaling machinery doesn't eat our crashes.
CComPtr<IGlobalOptions> options;
hr = options.CoCreateInstance(CLSID_GlobalOptions);
if (SUCCEEDED(hr)) {
hr = options->Set(COMGLB_EXCEPTION_HANDLING, COMGLB_EXCEPTION_DONOT_HANDLE);
}
DLOG_IF(WARNING, FAILED(hr)) << "IGlobalOptions::Set failed "
<< com::LogHr(hr);
// The above is best-effort, don't bail on error.
return S_OK;
}
HRESULT CeeeBrokerModule::PreMessageLoop(int show) {
// It's important to initialize the postman BEFORE we make the Broker
// and the event funnel available, since we may get requests to execute
// API invocation or Fire events before the postman is ready to handle them.
chrome_postman_.Init();
WindowEventsFunnel::Initialize();
// Another instance of broker may be shutting down right now. Do several
// attempts in hope the process exits and releases endpoint.
for (int i = 0; i < 10 && !rpc_server_.Start(); ++i)
Sleep(500);
// Initialize metrics. We need the rpc_server_ above to be available.
MetricsService::Start();
HRESULT hr = rpc_server_.is_started() ? S_OK : RPC_E_FAULT;
if (SUCCEEDED(hr))
hr = CAtlExeModuleT<CeeeBrokerModule>::PreMessageLoop(show);
if (FAILED(hr))
TearDown();
return hr;
}
HRESULT CeeeBrokerModule::PostMessageLoop() {
HRESULT hr = CAtlExeModuleT<CeeeBrokerModule>::PostMessageLoop();
TearDown();
return hr;
}
void CeeeBrokerModule::TearDown() {
rpc_server_.Stop();
Singleton<ExecutorsManager,
ExecutorsManager::SingletonTraits>()->Terminate();
WindowEventsFunnel::Terminate();
// Upload data if necessary.
MetricsService::Stop();
chrome_postman_.Term();
}
CeeeBrokerModule::~CeeeBrokerModule() {
crash_reporter_.ShutdownCrashReporting();
logging::CloseLogFile();
TRACE_EVENT_END("ceee.broker", this, "");
}
HRESULT WINAPI CeeeBrokerModule::UpdateRegistryAppId(BOOL reg) throw() {
return com::ModuleRegistrationWithoutAppid(IDR_BROKER_MODULE, reg);
}
namespace ceee_module_util {
LONG LockModule() {
return module.LockModule();
}
LONG UnlockModule() {
return module.UnlockModule();
}
} // namespace
<|endoftext|> |
<commit_before>/*--------------------------------------------------------------------------------------------------
* Author:
* Date: 2016-08-18
* Assignment: Final Project
* Source File: interface.cpp
* Language: C/C++
* Course: Operating Systems
* Purpose: Contains the implementation of the interface class.
-------------------------------------------------------------------------------------------------*/
#include "constants.h"
#include "ext2.h"
#include "interface.h"
#include "utility.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <stdexcept>
#include <cstdio>
#include <time.h>
using namespace std;
using namespace vdi_explorer;
namespace vdi_explorer
{
// @TODO Make an actual throwable error.
interface::interface(ext2 * _file_system)
{
file_system = _file_system;
if (file_system == nullptr)
{
cout << "Error opening the file system object.";
throw;
}
}
interface::~interface()
{
return;
}
void interface::interactive()
{
string command_string;
vector<string> tokens;
vector<string> tokens2;
while (true)
{
cout << "\nCommand: ";
getline(cin, command_string);
tokens = utility::tokenize(command_string, DELIMITER_SPACE);
tokens2 = utility::tokenize(command_string, DELIMITER_FSLASH);
// Debug info.
for (unsigned int i = 0; i < tokens.size(); i++)
cout << "debug (ext2::interface::interactive): " << tokens[i] << endl;
// End debug info.
if (tokens.size() == 0)
continue;
switch (hash_command(tokens[0]))
{
case code_cd:
if (tokens.size() < 2)
{
cout << "Not enough arguments.\n";
command_help("cd");
}
else
{
command_cd(tokens[1]);
}
break;
case code_cp:
if (tokens.size() < 4)
{
cout << "Not enough arguments.\n";
command_help("cp");
}
else
{
command_cp(tokens[1], tokens[2], tokens[3]);
}
break;
case code_exit:
command_exit();
break;
case code_help:
if (tokens.size() < 2)
{
command_help("");
}
else
{
command_help(tokens[1]);
}
break;
case code_ls:
if (tokens.size() < 2)
{
command_ls("");
}
else
{
command_ls(tokens[1]);
}
break;
case code_pwd:
command_pwd();
break;
// Debug
case code_dump_pwd_inode:
command_dump_pwd_inode();
break;
case code_dump_block:
command_dump_block(stoi(tokens[1]));
break;
case code_dump_inode:
command_dump_inode(stoi(tokens[1]));
break;
// End debug.
case code_unknown:
cout << "Unknown command.\n";
break;
default:
// A Bad Thing happened. This should never get triggered.
cout << "A Bad Thing happened. You should not be seeing this.";
break;
}
}
}
void interface::command_cd(const string & directory)
{
file_system->set_pwd(directory);
return;
}
void interface::command_cp(const string & direction,
const string & copy_from,
const string & copy_to)
{
cout << "*** Implementation in progress. Bust out the bugspray. ***\n";
fstream os_file;
if (direction == "in")
{
cout << "Not implemented yet.\n";
return;
}
else if (direction == "out")
{
// Attempt to open the file for input to see if it already exists.
os_file.open(copy_to, ios_base::in);
bool file_exists = os_file.good();
os_file.close();
// Actually check if the file exists.
if (file_exists)
{
cout << "Error, file already exists.";
return;
}
else
{
// Open file for writing.
os_file.open(copy_to, ios::out | ios::binary);
if (!os_file.good())
{
cout << "Error opening file for writing.\n";
return;
}
// Actually copy file out from the other file system.
bool successful = file_system->file_read(os_file, copy_from);
os_file.close();
if (!successful)
{
remove(copy_to.c_str());
}
}
}
}
// @TODO format output neatly into appropriately sized columns -> function in utility?
// @TODO sort vector by name
// @TODO implement "a" and "l" switches
// @TODO colorize:
// Blue: Directory
// Green: Executable or recognized data file
// Sky Blue: Linked file
// Yellow with black background: Device
// Pink: Graphic image file
// Red: Archive file
// @TODO add '/' to directories when displayed
void interface::command_ls(const string & switches)
{
vector<fs_entry_posix> file_listing = file_system->get_directory_contents();
vector<string> filename_tokens;
for (u32 i = 0; i < file_listing.size(); i++)
{
filename_tokens = utility::tokenize(file_listing[i].name, DELIMITER_DOT);
string file_extension = (filename_tokens.size() > 1 ? filename_tokens.back() : "");
if (switches == "-l" || switches == "-al"){
if (switches == "-l" && (file_listing[i].name == "." || file_listing[i].name ==".."));
else
{ // list permissions for each file
if (file_listing[i].type == EXT2_DIR_TYPE_DIR)
cout << "d";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_USER_READ)
cout << "r";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_USER_WRITE)
cout << "w";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_USER_EXECUTE)
cout << "x";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_GROUP_READ)
cout << "r";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_GROUP_WRITE)
cout << "w";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_GROUP_EXECUTE)
cout << "x";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_OTHER_READ)
cout << "r";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_OTHER_WRITE)
cout << "w";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_OTHER_EXECUTE)
cout << "x ";
else
cout << "- ";
// set file type, UID, GID, and size
cout << setw(2) << ((file_listing[i].type== EXT2_DIR_TYPE_DIR)?2:1)<< " ";
cout << setw(5) << file_listing[i].user_id<< " ";
cout << setw(5) << file_listing[i].group_id << " ";
cout << setw(10) << file_listing[i].size << " ";
// translate unix epoch timestamps to readable time
time_t now;
struct tm ts;
char buf[80];
now = file_listing[i].timestamp_modified;
ts = *localtime(&now);
strftime(buf, sizeof(buf), "%b %d %M:%S", &ts);
printf("%s ", buf);
}
}
if (file_listing[i].type == EXT2_DIR_TYPE_DIR){
if (switches == "-l"){
if (file_listing[i].name == "." || file_listing[i].name ==".."); // don't print out . and .. directories with -l switch
else
cout << "\033[1;34m" << file_listing[i].name << "\033[0m"; //blue (bold) - directory or recognized data file }
}
else
cout << "\033[1;34m" << file_listing[i].name << "\033[0m"; //blue (bold) - directory or recognized data file
}
else if ((file_listing[i].type == EXT2_DIR_TYPE_FILE) &&
(file_listing[i].permissions & EXT2_INODE_PERM_USER_EXECUTE ||
file_listing[i].permissions & EXT2_INODE_PERM_GROUP_EXECUTE ||
file_listing[i].permissions & EXT2_INODE_PERM_OTHER_EXECUTE)){
cout << "\033[2;31m" << file_listing[i].name << "\033[0m"; //green - executable files
}
else if (file_listing[i].type == EXT2_INODE_TYPE_SYMLINK)
cout << "\033[6;31m" << file_listing[i].name << "\033[0m"; //cyan - linked file
else if (file_listing[i].type == EXT2_INODE_TYPE_SYMLINK)
cout << "\033[3;31m" << file_listing[i].name << "\033[0m"; //yellow (with black background) - device
else if ((file_listing[i].type == EXT2_DIR_TYPE_FILE) &&
(file_extension == "png" ||
file_extension == "jpg" ||
file_extension == "raw" ||
file_extension == "gif" ||
file_extension == "bmp" ||
file_extension == "tif")){
cout << "\033[5;31m" << file_listing[i].name << "\033[0m"; }//pink - graphic image file
else if ((file_listing[i].type == EXT2_DIR_TYPE_FILE) &&
(file_extension == "zip" ||
file_extension == "tar" ||
file_extension == "rar" ||
file_extension == ".tar.xz" ||
file_extension == "7z" ||
file_extension == "xz")){
cout << "\033[0;31m" << file_listing[i].name << "\033[0m"; }//red - archive file
else
cout << file_extension << file_listing[i].name;
if ((switches == "-l" && (file_listing[i].name != "." && file_listing[i].name !="..")) || switches == "-al")
cout << "\n";
else if (switches == "-l" && (file_listing[i].name == "." || file_listing[i].name ==".."));
else
cout << "\t";
}
return;
}
void interface::command_exit()
{
// exit the program
exit(0);
}
void interface::command_help(const string & command)
{
command_code hashed_command = hash_command(command);
switch (hashed_command)
{
case code_none:
case code_cd:
// explain cd command
cout << "cd <directory_to_change_to>\n";
cout << "Change directory command. This command will change the present working " <<
"directory to the one specified.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_cp:
// explain cp command
cout << "cp <in|out> <file_to_copy_from> <file_to_copy_to>\n";
cout << "Copy a file between the host OS and the virtual hard drive and vice " <<
"versa.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_exit:
// explain exit command
cout << "exit\n";
cout << "Exits the program.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_help:
// explain help command
cout << "help [command]\n";
cout << "Procides help on the various commands.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_ls:
// explain ls command
cout << "ls [-al]\n";
cout << "List the contents of the present working directory.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_pwd:
// explain pwd command
cout << "pwd\n";
cout << "Prints out the present working directory.\n";
break;
case code_unknown:
// unknown command
cout << command << endl;
cout << "Unknown command.\n";
break;
default:
// A Bad Thing happened. This should never get triggered.
cout << "A Bad Thing happened. You should not be seeing this.";
break;
}
}
void interface::command_pwd()
{
cout << file_system->get_pwd() << endl;
return;
}
// Debug.
void interface::command_dump_pwd_inode()
{
file_system->debug_dump_pwd_inode();
}
void interface::command_dump_block(u32 block_to_dump)
{
file_system->debug_dump_block(block_to_dump);
}
void interface::command_dump_inode(u32 inode_to_dump)
{
file_system->debug_dump_inode(inode_to_dump);
}
// End debug.
interface::command_code interface::hash_command(const string & command)
{
if (command == "cd")
{
return code_cd;
}
else if (command == "cp")
{
return code_cp;
}
else if (command == "exit")
{
return code_exit;
}
else if (command == "help")
{
return code_help;
}
else if (command == "ls")
{
return code_ls;
}
else if (command == "ls -l") // long list version of ls
{
return code_ls;
}
else if (command == "pwd")
{
return code_pwd;
}
else if (command == "")
{
return code_none;
}
// Debug.
else if (command == "dump_pwd_inode")
{
return code_dump_pwd_inode;
}
else if (command == "dump_block")
{
return code_dump_block;
}
else if (command == "dump_inode")
{
return code_dump_inode;
}
// End debug.
else
{
return code_unknown;
}
}
} // namespace vdi_explorer<commit_msg>colorization fixed, ls bug fixed<commit_after>/*--------------------------------------------------------------------------------------------------
* Author:
* Date: 2016-08-18
* Assignment: Final Project
* Source File: interface.cpp
* Language: C/C++
* Course: Operating Systems
* Purpose: Contains the implementation of the interface class.
-------------------------------------------------------------------------------------------------*/
#include "constants.h"
#include "ext2.h"
#include "interface.h"
#include "utility.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <stdexcept>
#include <cstdio>
#include <time.h>
using namespace std;
using namespace vdi_explorer;
namespace vdi_explorer
{
// @TODO Make an actual throwable error.
interface::interface(ext2 * _file_system)
{
file_system = _file_system;
if (file_system == nullptr)
{
cout << "Error opening the file system object.";
throw;
}
}
interface::~interface()
{
return;
}
void interface::interactive()
{
string command_string;
vector<string> tokens;
vector<string> tokens2;
while (true)
{
cout << "\nCommand: ";
getline(cin, command_string);
tokens = utility::tokenize(command_string, DELIMITER_SPACE);
tokens2 = utility::tokenize(command_string, DELIMITER_FSLASH);
// Debug info.
for (unsigned int i = 0; i < tokens.size(); i++)
cout << "debug (ext2::interface::interactive): " << tokens[i] << endl;
// End debug info.
if (tokens.size() == 0)
continue;
switch (hash_command(tokens[0]))
{
case code_cd:
if (tokens.size() < 2)
{
cout << "Not enough arguments.\n";
command_help("cd");
}
else
{
command_cd(tokens[1]);
}
break;
case code_cp:
if (tokens.size() < 4)
{
cout << "Not enough arguments.\n";
command_help("cp");
}
else
{
command_cp(tokens[1], tokens[2], tokens[3]);
}
break;
case code_exit:
command_exit();
break;
case code_help:
if (tokens.size() < 2)
{
command_help("");
}
else
{
command_help(tokens[1]);
}
break;
case code_ls:
if (tokens.size() < 2)
{
command_ls("");
}
else
{
command_ls(tokens[1]);
}
break;
case code_pwd:
command_pwd();
break;
// Debug
case code_dump_pwd_inode:
command_dump_pwd_inode();
break;
case code_dump_block:
command_dump_block(stoi(tokens[1]));
break;
case code_dump_inode:
command_dump_inode(stoi(tokens[1]));
break;
// End debug.
case code_unknown:
cout << "Unknown command.\n";
break;
default:
// A Bad Thing happened. This should never get triggered.
cout << "A Bad Thing happened. You should not be seeing this.";
break;
}
}
}
void interface::command_cd(const string & directory)
{
file_system->set_pwd(directory);
return;
}
void interface::command_cp(const string & direction,
const string & copy_from,
const string & copy_to)
{
cout << "*** Implementation in progress. Bust out the bugspray. ***\n";
fstream os_file;
if (direction == "in")
{
cout << "Not implemented yet.\n";
return;
}
else if (direction == "out")
{
// Attempt to open the file for input to see if it already exists.
os_file.open(copy_to, ios_base::in);
bool file_exists = os_file.good();
os_file.close();
// Actually check if the file exists.
if (file_exists)
{
cout << "Error, file already exists.";
return;
}
else
{
// Open file for writing.
os_file.open(copy_to, ios::out | ios::binary);
if (!os_file.good())
{
cout << "Error opening file for writing.\n";
return;
}
// Actually copy file out from the other file system.
bool successful = file_system->file_read(os_file, copy_from);
os_file.close();
if (!successful)
{
remove(copy_to.c_str());
}
}
}
}
// @TODO format output neatly into appropriately sized columns -> function in utility?
// @TODO sort vector by name
// @TODO colorize:
// Yellow with black background: Device
// Pink: Graphic image file
void interface::command_ls(const string & switches)
{
vector<fs_entry_posix> file_listing = file_system->get_directory_contents();
vector<string> filename_tokens;
for (u32 i = 0; i < file_listing.size(); i++)
{
filename_tokens = utility::tokenize(file_listing[i].name, DELIMITER_DOT);
string file_extension = (filename_tokens.size() > 1 ? filename_tokens.back() : "");
if (switches == "-l" || switches == "-al"){
if (switches == "-l" && (file_listing[i].name == "." || file_listing[i].name ==".."));
else
{ // list permissions for each file
if (file_listing[i].type == EXT2_DIR_TYPE_DIR)
cout << "d";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_USER_READ)
cout << "r";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_USER_WRITE)
cout << "w";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_USER_EXECUTE)
cout << "x";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_GROUP_READ)
cout << "r";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_GROUP_WRITE)
cout << "w";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_GROUP_EXECUTE)
cout << "x";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_OTHER_READ)
cout << "r";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_OTHER_WRITE)
cout << "w";
else
cout << "-";
if (file_listing[i].permissions & EXT2_INODE_PERM_OTHER_EXECUTE)
cout << "x ";
else
cout << "- ";
// set file type, UID, GID, and size
cout << setw(2) << ((file_listing[i].type== EXT2_DIR_TYPE_DIR)?2:1)<< " ";
cout << setw(5) << file_listing[i].user_id<< " ";
cout << setw(5) << file_listing[i].group_id << " ";
cout << setw(10) << file_listing[i].size << " ";
// translate unix epoch timestamps to readable time
time_t curr;
struct tm ts;
char buf[80];
curr = file_listing[i].timestamp_modified;
ts = *localtime(&curr);
strftime(buf, sizeof(buf), "%b %d %M:%S", &ts);
printf("%s ", buf);
}
}
if (file_listing[i].type == EXT2_DIR_TYPE_DIR){
if (switches != "-al" ){
if (file_listing[i].name == "." || file_listing[i].name ==".."); // don't print out . and .. directories with -l switch
else
cout << "\033[1;34m" << file_listing[i].name << "\033[0m"<< "/"; //blue (bold) - directory or recognized data file }
}
else if ((switches == "-al" ) && (file_listing[i].name == "." || file_listing[i].name ==".."))
cout << "\033[1;34m" << file_listing[i].name << "\033[0m";
else
cout << "\033[1;34m" << file_listing[i].name << "\033[0m" << "/"; //blue (bold) - directory or recognized data file
}
else if ((file_listing[i].type == EXT2_DIR_TYPE_FILE) &&
(file_listing[i].permissions & EXT2_INODE_PERM_USER_EXECUTE ||
file_listing[i].permissions & EXT2_INODE_PERM_GROUP_EXECUTE ||
file_listing[i].permissions & EXT2_INODE_PERM_OTHER_EXECUTE)){
cout << "\033[1;32m" << file_listing[i].name << "\033[0m" << "*"; //green - executable files
}
else if (file_listing[i].type == EXT2_INODE_TYPE_SYMLINK)
cout << "\033[6;36m" << file_listing[i].name << "\033[0m"; //cyan - linked file
else if (file_listing[i].type == EXT2_INODE_TYPE_SYMLINK)
cout << "\033[3;33m" << file_listing[i].name << "\033[0m"; //yellow (with black background) - device
else if ((file_listing[i].type == EXT2_DIR_TYPE_FILE) &&
(file_extension == "png" ||
file_extension == "jpg" ||
file_extension == "raw" ||
file_extension == "gif" ||
file_extension == "bmp" ||
file_extension == "tif")){ //38 - black
cout << "\033[5;31m" << file_listing[i].name << "\033[0m"; }//pink - graphic image file
else if ((file_listing[i].type == EXT2_DIR_TYPE_FILE) &&
(file_extension == "zip" ||
file_extension == "tar" ||
file_extension == "rar" ||
file_extension == "7z" ||
file_extension == "xz")){
cout << "\033[0;31m" << file_listing[i].name << "\033[0m"; }//red - archive file
else
cout << file_extension << file_listing[i].name;
if ((switches == "-l" && (file_listing[i].name != "." && file_listing[i].name !="..")) || switches == "-al")
cout << "\n";
else if (switches != "-al" && (file_listing[i].name == "." || file_listing[i].name ==".."));
else
cout << "\t";
}
return;
}
void interface::command_exit()
{
// exit the program
exit(0);
}
void interface::command_help(const string & command)
{
command_code hashed_command = hash_command(command);
switch (hashed_command)
{
case code_none:
case code_cd:
// explain cd command
cout << "cd <directory_to_change_to>\n";
cout << "Change directory command. This command will change the present working " <<
"directory to the one specified.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_cp:
// explain cp command
cout << "cp <in|out> <file_to_copy_from> <file_to_copy_to>\n";
cout << "Copy a file between the host OS and the virtual hard drive and vice " <<
"versa.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_exit:
// explain exit command
cout << "exit\n";
cout << "Exits the program.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_help:
// explain help command
cout << "help [command]\n";
cout << "Procides help on the various commands.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_ls:
// explain ls command
cout << "ls [-al]\n";
cout << "List the contents of the present working directory.\n";
if (hashed_command != code_none)
break;
else
cout << endl;
case code_pwd:
// explain pwd command
cout << "pwd\n";
cout << "Prints out the present working directory.\n";
break;
case code_unknown:
// unknown command
cout << command << endl;
cout << "Unknown command.\n";
break;
default:
// A Bad Thing happened. This should never get triggered.
cout << "A Bad Thing happened. You should not be seeing this.";
break;
}
}
void interface::command_pwd()
{
cout << file_system->get_pwd() << endl;
return;
}
// Debug.
void interface::command_dump_pwd_inode()
{
file_system->debug_dump_pwd_inode();
}
void interface::command_dump_block(u32 block_to_dump)
{
file_system->debug_dump_block(block_to_dump);
}
void interface::command_dump_inode(u32 inode_to_dump)
{
file_system->debug_dump_inode(inode_to_dump);
}
// End debug.
interface::command_code interface::hash_command(const string & command)
{
if (command == "cd")
{
return code_cd;
}
else if (command == "cp")
{
return code_cp;
}
else if (command == "exit")
{
return code_exit;
}
else if (command == "help")
{
return code_help;
}
else if (command == "ls")
{
return code_ls;
}
else if (command == "ls -l") // long list version of ls
{
return code_ls;
}
else if (command == "pwd")
{
return code_pwd;
}
else if (command == "")
{
return code_none;
}
// Debug.
else if (command == "dump_pwd_inode")
{
return code_dump_pwd_inode;
}
else if (command == "dump_block")
{
return code_dump_block;
}
else if (command == "dump_inode")
{
return code_dump_inode;
}
// End debug.
else
{
return code_unknown;
}
}
} // namespace vdi_explorer<|endoftext|> |
<commit_before>// sphere tracing demo with a few random elements
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <algorithm>
#include "render.h"
#include "vec3.h"
float frame_ = 0;
vec3 lcol(0.5,0.7,0.5);
float mshiny[] = {100,10,10,10};
vec3 mcol[] = {
vec3(1.0f, 1.0f, 1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(1.0f, 0.2f, 0.0f),
vec3(0.22f, 0.62f, 0.0f)};
float udRoundBox(const vec3& p, const vec3& b, float r)
{
return length(max(abs(p)-b,0.0))-r;
}
float sdSphere( vec3 p, float s )
{
return length(p)-s;
}
vec3 rotateY(vec3 p, float a) {
float ca = cos(a), sa = sin(a);
return vec3(p.x*ca-p.z*sa, p.y, p.x*sa+p.z*ca);
}
vec3 rotateX(vec3 p, float a) {
float ca = cos(a), sa = sin(a);
return vec3(p.x, p.y*ca-p.z*sa, p.y*sa+p.z*ca);
}
float arc1(const vec3 &q, float r1, float r2, float zpos) {
//return std::max(
// fabsf(q.z + zpos), std::max(
return std::max(
std::max(-q.x - q.y, q.x - q.y),
fabsf(length(vec3(q.x, q.y, 0)) - r1)) - r2;
}
// returns minimum distance to scene, material m, and normal n
float dist(const vec3 &p, int *m) {
*m = -1;
float d = 1e30;
float dplane = p.y + 50;
if (dplane < d) {
*m = ((lrint(p.x*0.01)&1)^(lrint(p.z*0.01)&1));
d = dplane;
}
//vec3 q = rotateX(rotateY(p, -frame_*0.07), frame_*0.025);
vec3 q = rotateY(p, frame_*0.07);
float dcyl = std::max(
std::max(q.z - 10.0f, -10.0f - q.z),
length(vec3(q.x, q.y, 0)) - 50.0f);
dcyl = std::max(dcyl, -arc1(q - vec3(0, -10, 0), 40, 5, 6));
dcyl = std::max(dcyl, -arc1(q - vec3(0, -25, 0), 35, 4, 6));
dcyl = std::max(dcyl, -arc1(q - vec3(0, -35, 0), 30, 3, 6));
if (dcyl < d) {
d = dcyl;
*m = 3;
}
return d;
}
float shadow(const vec3& ro, const vec3& rd, float mint, float maxt) {
int m;
float res = 1.0;
for (float t = mint; t < maxt; ) {
float h = dist(ro+rd*t, &m);
if (h < 0.001) {
return 0;
}
res = std::min( res, 10.0f*h/t );
t += h;
}
return res;
}
vec3 lighting(const vec3 &p, int m, const vec3& lightpos) {
vec3 lightdir = normalize(lightpos - p);
// yet another trick from iq: use the distance field to compute dot(light,
// normal) instead of explicitly finding a normal.
// http://www.pouet.net/topic.php?which=7535&page=1
int _m;
float diffuse = std::max(0.0f, 10.0f*dist(p+lightdir*0.1, &_m));
float s = std::max(0.3f, shadow(p, lightdir, 0.01, length(p-lightpos)));
float l = std::max(0.1f, diffuse * s);
return mcol[m]*l + lcol*pow(l, mshiny[m]);
}
int main()
{
int x,y;
render_init();
for(;;) {
vec3 campos = vec3(120*sin(frame_*0.01), 40 + 30*sin(frame_*0.03), -120*cos(frame_*0.01));
vec3 camz = normalize(campos*-1);
//vec3 lightpos = vec3(200,400,campos.z);
//vec3 lightpos = campos;
//vec3 lightpos = vec3(100*sin(frame_*0.08), 50, -100*cos(frame_*0.04));
vec3 lightpos = vec3(100*sin(frame_*0.037), 40, campos.z);
vec3 lightpos2 = vec3(0, 200, 0);
vec3 camx = normalize(cross(camz, vec3(0,1,0)));
vec3 camy = normalize(cross(camx, camz));
for(y=0;y<24;y++) {
int fg=7, bg=0;
for(x=0;x<80;x++) {
vec3 color = vec3(0,0,0);
#ifdef AA
for(float xx = -0.25;xx<=0.25;xx+=0.5) { // 2 x samples
for(float yy = -0.75;yy<=0.75;yy+=0.5) { // 4 y samples
vec3 dir = normalize(vec3(x-40.0f+xx,25.0f-2.0f*y+yy,70.0f));
#else
vec3 dir = normalize(vec3(x-40.0f,25.0f-2.0f*y,70.0f));
#endif
dir = camx*dir.x + camy*dir.y + camz*dir.z;
float t = 0;
int m = -1;
for (int iter = 0; iter < 64 && t < 1e6; iter++) {
vec3 p = dir*t + campos;
float d = dist(p, &m);
if (d < 0.001) {
color = color + lighting(p, m, lightpos);
break;
}
t += d;
}
#ifdef AA
}
}
render_color(color * 0.125, x, y, &fg, &bg);
#else
render_color(color, x, y, &fg, &bg);
#endif
}
printf("\x1b[0m\n");
}
fflush(stdout);
usleep(20000);
frame_ += 1;
printf("\x1b[24A");
}
}
<commit_msg>simplified spotify logo a bit<commit_after>// sphere tracing demo with a few random elements
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <algorithm>
#include "render.h"
#include "vec3.h"
float frame_ = 0;
vec3 lcol(0.5,0.7,0.5);
float mshiny[] = {100,10,10,10};
vec3 mcol[] = {
vec3(1.0f, 1.0f, 1.0f),
vec3(0.0f, 0.0f, 1.0f),
vec3(1.0f, 0.2f, 0.0f),
vec3(0.22f, 0.62f, 0.0f)};
float udRoundBox(const vec3& p, const vec3& b, float r)
{
return length(max(abs(p)-b,0.0))-r;
}
float sdSphere( vec3 p, float s )
{
return length(p)-s;
}
vec3 rotateY(vec3 p, float a) {
float ca = cos(a), sa = sin(a);
return vec3(p.x*ca-p.z*sa, p.y, p.x*sa+p.z*ca);
}
vec3 rotateX(vec3 p, float a) {
float ca = cos(a), sa = sin(a);
return vec3(p.x, p.y*ca-p.z*sa, p.y*sa+p.z*ca);
}
float arc1(const vec3 &q, float r1, float r2, float zpos) {
//return std::max(
// fabsf(q.z + zpos), std::max(
return std::max(
std::max(-q.x - q.y, q.x - q.y),
fabsf(length(vec3(q.x, q.y, 0)) - r1)) - r2;
}
// returns minimum distance to scene, material m, and normal n
float dist(const vec3 &p, int *m) {
*m = -1;
float d = 1e30;
float dplane = p.y + 50;
if (dplane < d) {
// *m = ((lrint(p.x*0.01)&1)^(lrint(p.z*0.01)&1));
*m = 0;
d = dplane;
}
//vec3 q = rotateX(rotateY(p, -frame_*0.07), frame_*0.025);
//vec3 q = rotateY(p, frame_*0.07);
vec3 q = p;
float dcyl = std::max(
std::max(q.z - 10.0f, -10.0f - q.z),
length(vec3(q.x, q.y, 0)) - 50.0f);
dcyl = std::max(dcyl, -arc1(q - vec3(0, -10, 0), 40, 5, 6));
dcyl = std::max(dcyl, -arc1(q - vec3(0, -25, 0), 35, 4, 6));
dcyl = std::max(dcyl, -arc1(q - vec3(0, -35, 0), 30, 3, 6));
if (dcyl < d) {
d = dcyl;
*m = 3;
}
return d;
}
float shadow(const vec3& ro, const vec3& rd, float mint, float maxt) {
int m;
float res = 1.0;
for (float t = mint; t < maxt; ) {
float h = dist(ro+rd*t, &m);
if (h < 0.001) {
return 0;
}
res = std::min( res, 20.0f*h/t );
t += h;
}
return res;
}
vec3 lighting(const vec3 &p, int m, const vec3& lightpos) {
vec3 lightdir = normalize(lightpos - p);
// yet another trick from iq: use the distance field to compute dot(light,
// normal) instead of explicitly finding a normal.
// http://www.pouet.net/topic.php?which=7535&page=1
int _m;
float diffuse = std::max(0.0f, 10.0f*dist(p+lightdir*0.1, &_m));
float s = std::max(0.3f, shadow(p, lightdir, 0.01, length(p-lightpos)));
float l = std::max(0.1f, diffuse * s);
return mcol[m]*l + lcol*pow(l, mshiny[m]);
}
int main()
{
int x,y;
render_init();
for(;;) {
vec3 campos = vec3(130*sin(frame_*0.02), 50 + 40*sin(frame_*0.03), -130*cos(frame_*0.02));
vec3 lightpos = vec3(200.0*sin(frame_*0.05),100,campos.z);
vec3 camz = normalize(campos*-1);
vec3 camx = normalize(cross(camz, vec3(0,1,0)));
vec3 camy = normalize(cross(camx, camz));
for(y=0;y<24;y++) {
int fg=7, bg=0;
for(x=0;x<80;x++) {
vec3 color = vec3(0,0,0);
#ifdef AA
for(float xx = -0.25;xx<=0.25;xx+=0.5) { // 2 x samples
for(float yy = -0.75;yy<=0.75;yy+=0.5) { // 4 y samples
vec3 dir = normalize(vec3(x-40.0f+xx,25.0f-2.0f*y+yy,70.0f));
#else
vec3 dir = normalize(vec3(x-40.0f,25.0f-2.0f*y,70.0f));
#endif
dir = camx*dir.x + camy*dir.y + camz*dir.z;
float t = 0;
int m = -1;
for (int iter = 0; iter < 64 && t < 1e6; iter++) {
vec3 p = dir*t + campos;
float d = dist(p, &m);
if (d < 0.001) {
color = color + lighting(p, m, lightpos);
break;
}
t += d;
}
#ifdef AA
}
}
render_color(color * 0.125, x, y, &fg, &bg);
#else
render_color(color, x, y, &fg, &bg);
#endif
}
printf("\x1b[0m\n");
}
fflush(stdout);
usleep(20000);
frame_ += 1;
printf("\x1b[24A");
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef TOKDEF
# define TOKDEF(k, s)
#endif
#ifndef TOKEN
# define TOKEN(k, s) TOKDEF(TK_##k, s)
#endif
#ifndef PUNCTUATOR
# define PUNCTUATOR(k, s) TOKEN(k, s)
#endif
#ifndef KEYWORD
# define KEYWORD(k, s) TOKDEF(KW_##k, s)
#endif
PUNCTUATOR(LPAREN, "(")
PUNCTUATOR(RPAREN, ")")
PUNCTUATOR(LBRACKET, "[")
PUNCTUATOR(RBRACKET, "]")
PUNCTUATOR(LBRACE, "{")
PUNCTUATOR(RBRACE, "}")
PUNCTUATOR(COLON, ":")
PUNCTUATOR(DOT, ".")
PUNCTUATOR(COMMA, ",")
PUNCTUATOR(STAR, "*")
PUNCTUATOR(SLASH, "/")
PUNCTUATOR(PERCENT, "%")
PUNCTUATOR(PLUS, "+")
PUNCTUATOR(MINUS, "-")
PUNCTUATOR(PIPE, "|")
PUNCTUATOR(AMP, "&")
PUNCTUATOR(BANG, "!")
PUNCTUATOR(EQ, "=")
PUNCTUATOR(LT, "<")
PUNCTUATOR(GT, ">")
PUNCTUATOR(LTEQ, "<=")
PUNCTUATOR(GTEQ, ">=")
PUNCTUATOR(EQEQ, "==")
PUNCTUATOR(BANGEQ, "!=")
KEYWORD(CLASS, "class")
KEYWORD(FALSE, "false")
KEYWORD(META, "meta")
KEYWORD(TRUE, "true")
KEYWORD(VAR, "var")
TOKEN(IDENTIFIER, "identifier")
TOKEN(NUMERIC, "numeric")
TOKEN(STRING, "string")
TOKEN(NL, "new-line")
TOKEN(ERROR, "error")
TOKEN(EOF, "eof")
#undef KEYWORD
#undef PUNCTUATOR
#undef TOKEN
#undef TOKDEF
<commit_msg>:construction: chore(kinds): add if and else kindsw<commit_after>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef TOKDEF
# define TOKDEF(k, s)
#endif
#ifndef TOKEN
# define TOKEN(k, s) TOKDEF(TK_##k, s)
#endif
#ifndef PUNCTUATOR
# define PUNCTUATOR(k, s) TOKEN(k, s)
#endif
#ifndef KEYWORD
# define KEYWORD(k, s) TOKDEF(KW_##k, s)
#endif
PUNCTUATOR(LPAREN, "(")
PUNCTUATOR(RPAREN, ")")
PUNCTUATOR(LBRACKET, "[")
PUNCTUATOR(RBRACKET, "]")
PUNCTUATOR(LBRACE, "{")
PUNCTUATOR(RBRACE, "}")
PUNCTUATOR(COLON, ":")
PUNCTUATOR(DOT, ".")
PUNCTUATOR(COMMA, ",")
PUNCTUATOR(STAR, "*")
PUNCTUATOR(SLASH, "/")
PUNCTUATOR(PERCENT, "%")
PUNCTUATOR(PLUS, "+")
PUNCTUATOR(MINUS, "-")
PUNCTUATOR(PIPE, "|")
PUNCTUATOR(AMP, "&")
PUNCTUATOR(BANG, "!")
PUNCTUATOR(EQ, "=")
PUNCTUATOR(LT, "<")
PUNCTUATOR(GT, ">")
PUNCTUATOR(LTEQ, "<=")
PUNCTUATOR(GTEQ, ">=")
PUNCTUATOR(EQEQ, "==")
PUNCTUATOR(BANGEQ, "!=")
KEYWORD(CLASS, "class")
KEYWORD(ELSE, "else")
KEYWORD(FALSE, "false")
KEYWORD(IF, "if")
KEYWORD(META, "meta")
KEYWORD(TRUE, "true")
KEYWORD(VAR, "var")
TOKEN(IDENTIFIER, "identifier")
TOKEN(NUMERIC, "numeric")
TOKEN(STRING, "string")
TOKEN(NL, "new-line")
TOKEN(ERROR, "error")
TOKEN(EOF, "eof")
#undef KEYWORD
#undef PUNCTUATOR
#undef TOKEN
#undef TOKDEF
<|endoftext|> |
<commit_before>#include <cstdio>
#include <iterator>
#include "tictactoe.hpp"
TicTacToe* TicTacToe::GetChild(Integer move)
{
if (!children[move])
children[move] = new TicTacToe(this, move, -Infinity, +Infinity);
return children[move];
}
bool TicTacToe::IsWin() const
{
const Integer parentTurn = parent->Turn;
switch (move)
{
case 0:
return parentTurn == Board[1] && parentTurn == Board[2] ||
parentTurn == Board[3] && parentTurn == Board[6] ||
parentTurn == Board[4] && parentTurn == Board[8];
case 1:
return parentTurn == Board[0] && parentTurn == Board[2] ||
parentTurn == Board[4] && parentTurn == Board[7];
case 2:
return parentTurn == Board[1] && parentTurn == Board[0] ||
parentTurn == Board[5] && parentTurn == Board[8] ||
parentTurn == Board[4] && parentTurn == Board[6];
case 3:
return parentTurn == Board[4] && parentTurn == Board[5] ||
parentTurn == Board[0] && parentTurn == Board[6];
case 4:
return parentTurn == Board[3] && parentTurn == Board[5] ||
parentTurn == Board[1] && parentTurn == Board[7] ||
parentTurn == Board[0] && parentTurn == Board[8] ||
parentTurn == Board[2] && parentTurn == Board[6];
case 5:
return parentTurn == Board[4] && parentTurn == Board[3] ||
parentTurn == Board[2] && parentTurn == Board[8];
case 6:
return parentTurn == Board[7] && parentTurn == Board[8] ||
parentTurn == Board[3] && parentTurn == Board[0] ||
parentTurn == Board[4] && parentTurn == Board[2];
case 7:
return parentTurn == Board[6] && parentTurn == Board[8] ||
parentTurn == Board[4] && parentTurn == Board[1];
case 8:
return parentTurn == Board[7] && parentTurn == Board[6] ||
parentTurn == Board[5] && parentTurn == Board[2] ||
parentTurn == Board[4] && parentTurn == Board[0];
default:
return false;
}
}
TicTacToe::TicTacToe():
Turn(Max), move(-1), Depth(0), alpha(-Infinity), beta(+Infinity), parent(nullptr)
{
Search();
}
TicTacToe::TicTacToe(const TicTacToe* parent, Integer move, Integer alpha, Integer beta):
Turn(-parent->Turn), move(move), Depth(parent->Depth + 1), alpha(alpha), beta(beta), parent(parent)
{
std::copy(std::begin(parent->Board), std::end(parent->Board), Board);
Board[move] = parent->Turn;
bool isWin = IsWin(), isFull = Depth == Size;
if (isWin || isFull)
Payoff = isWin ? parent->Turn * (10 - Depth) : Zero;
else
Search();
}
void TicTacToe::Search()
{
if (Max == Turn)
{
Integer max = -Infinity;
for (Integer p = 0; p < Size; ++p)
if (Zero == Board[p])
{
children[p] = new TicTacToe(this, p, alpha, beta);
if (children[p]->Payoff > max)
{
max = children[p]->Payoff;
if (max > alpha && (alpha = max) >= beta)
break;
}
}
Payoff = max;
}
else
{
Integer min = +Infinity;
for (Integer p = 0; p < Size; ++p)
if (Zero == Board[p])
{
children[p] = new TicTacToe(this, p, alpha, beta);
if (children[p]->Payoff < min)
{
min = children[p]->Payoff;
if (min < beta && (beta = min) <= alpha)
break;
}
}
Payoff = min;
}
}
TicTacToe::~TicTacToe()
{
for (auto child: children)
delete child;
}
void TicTacToe::Print() const
{
auto getPlayerSign = [](Integer turn) {
switch (turn)
{
case Max:
return 'x';
case Min:
return 'o';
default:
return ' ';
}
};
printf(
"+---+---+---+\n"
"| %c | %c | %c |\n"
"+---+---+---+\n"
"| %c | %c | %c |\n"
"+---+---+---+\n"
"| %c | %c | %c |\n"
"+---+---+---+\n",
getPlayerSign(Board[0]), getPlayerSign(Board[1]), getPlayerSign(Board[2]),
getPlayerSign(Board[3]), getPlayerSign(Board[4]), getPlayerSign(Board[5]),
getPlayerSign(Board[6]), getPlayerSign(Board[7]), getPlayerSign(Board[8])
);
}
<commit_msg>tictactoe: added parentheses around `&&` clauses and fixed member initialization order<commit_after>#include <cstdio>
#include <iterator>
#include "tictactoe.hpp"
TicTacToe* TicTacToe::GetChild(Integer move)
{
if (!children[move])
children[move] = new TicTacToe(this, move, -Infinity, +Infinity);
return children[move];
}
bool TicTacToe::IsWin() const
{
const Integer parentTurn = parent->Turn;
switch (move)
{
case 0:
return (parentTurn == Board[1] && parentTurn == Board[2]) ||
(parentTurn == Board[3] && parentTurn == Board[6]) ||
(parentTurn == Board[4] && parentTurn == Board[8]);
case 1:
return (parentTurn == Board[0] && parentTurn == Board[2]) ||
(parentTurn == Board[4] && parentTurn == Board[7]);
case 2:
return (parentTurn == Board[1] && parentTurn == Board[0]) ||
(parentTurn == Board[5] && parentTurn == Board[8]) ||
(parentTurn == Board[4] && parentTurn == Board[6]);
case 3:
return (parentTurn == Board[4] && parentTurn == Board[5]) ||
(parentTurn == Board[0] && parentTurn == Board[6]);
case 4:
return (parentTurn == Board[3] && parentTurn == Board[5]) ||
(parentTurn == Board[1] && parentTurn == Board[7]) ||
(parentTurn == Board[0] && parentTurn == Board[8]) ||
(parentTurn == Board[2] && parentTurn == Board[6]);
case 5:
return (parentTurn == Board[4] && parentTurn == Board[3]) ||
(parentTurn == Board[2] && parentTurn == Board[8]);
case 6:
return (parentTurn == Board[7] && parentTurn == Board[8]) ||
(parentTurn == Board[3] && parentTurn == Board[0]) ||
(parentTurn == Board[4] && parentTurn == Board[2]);
case 7:
return (parentTurn == Board[6] && parentTurn == Board[8]) ||
(parentTurn == Board[4] && parentTurn == Board[1]);
case 8:
return (parentTurn == Board[7] && parentTurn == Board[6]) ||
(parentTurn == Board[5] && parentTurn == Board[2]) ||
(parentTurn == Board[4] && parentTurn == Board[0]);
default:
return false;
}
}
TicTacToe::TicTacToe():
parent(nullptr), move(-1), alpha(-Infinity), beta(+Infinity), Turn(Max), Depth(0)
{
Search();
}
TicTacToe::TicTacToe(const TicTacToe* parent, Integer move, Integer alpha, Integer beta):
parent(parent), move(move), alpha(alpha), beta(beta), Turn(-parent->Turn), Depth(parent->Depth + 1)
{
std::copy(std::begin(parent->Board), std::end(parent->Board), Board);
Board[move] = parent->Turn;
bool isWin = IsWin(), isFull = Depth == Size;
if (isWin || isFull)
Payoff = isWin ? parent->Turn * (10 - Depth) : Zero;
else
Search();
}
void TicTacToe::Search()
{
if (Max == Turn)
{
Integer max = -Infinity;
for (Integer p = 0; p < Size; ++p)
if (Zero == Board[p])
{
children[p] = new TicTacToe(this, p, alpha, beta);
if (children[p]->Payoff > max)
{
max = children[p]->Payoff;
if (max > alpha && (alpha = max) >= beta)
break;
}
}
Payoff = max;
}
else
{
Integer min = +Infinity;
for (Integer p = 0; p < Size; ++p)
if (Zero == Board[p])
{
children[p] = new TicTacToe(this, p, alpha, beta);
if (children[p]->Payoff < min)
{
min = children[p]->Payoff;
if (min < beta && (beta = min) <= alpha)
break;
}
}
Payoff = min;
}
}
TicTacToe::~TicTacToe()
{
for (auto child: children)
delete child;
}
void TicTacToe::Print() const
{
auto getPlayerSign = [](Integer turn) {
switch (turn)
{
case Max:
return 'x';
case Min:
return 'o';
default:
return ' ';
}
};
printf(
"+---+---+---+\n"
"| %c | %c | %c |\n"
"+---+---+---+\n"
"| %c | %c | %c |\n"
"+---+---+---+\n"
"| %c | %c | %c |\n"
"+---+---+---+\n",
getPlayerSign(Board[0]), getPlayerSign(Board[1]), getPlayerSign(Board[2]),
getPlayerSign(Board[3]), getPlayerSign(Board[4]), getPlayerSign(Board[5]),
getPlayerSign(Board[6]), getPlayerSign(Board[7]), getPlayerSign(Board[8])
);
}
<|endoftext|> |
<commit_before>// -*- C++ -*-
// ex1_histogram.cc
// an exercise for the sandia 2014 clinic team.
// here we do a histogram calculation over unsigned ints
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <array>
#include <string>
#include <chrono>
#include <algorithm>
// header file for openmp
#include <omp.h>
// header files for tbb
#include <tbb/blocked_range.h>
#include <tbb/parallel_reduce.h>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include <tbb/atomic.h>
// header files for cuda implementation
#include "ex1_histogram_cuda.cuh"
// header files for kokkos
#include <Kokkos_Core.hpp>
using std::string;
using std::vector;
using std::array;
using std::chrono::high_resolution_clock;
using std::chrono::duration;
using std::chrono::duration_cast;
using tbb::atomic;
class TbbOutputter {
public:
vector<unsigned int> * input_;
atomic<unsigned long> * result_;
unsigned long numBuckets_;
unsigned long size_;
TbbOutputter(vector<unsigned int> * input, atomic<unsigned long> * results,
unsigned long numBuckets, unsigned long size)
: input_(input), result_(results), numBuckets_(numBuckets), size_(size) {
}
TbbOutputter(const TbbOutputter & other,
tbb::split)
: input_(other.input_), result_(other.result_),
numBuckets_(other.numBuckets_), size_(other.size_){
//printf("split copy constructor called\n");
}
void operator()(const tbb::blocked_range<size_t> & range) {
//printf("TbbOutputter asked to process range from %7zu to %7zu\n",
//range.begin(), range.end());
unsigned long bucketSize = size_/numBuckets_;
for(unsigned long i=range.begin(); i!= range.end(); ++i ) {
(result_ + (((*input_)[i])/bucketSize))->fetch_and_increment();
}
}
void join(const TbbOutputter & other) {
}
private:
TbbOutputter();
};
struct KokkosFunctor {
const unsigned int _bucketSize;
KokkosFunctor(const double bucketSize) : _bucketSize(bucketSize) {
}
KOKKOS_INLINE_FUNCTION
void operator()(const unsigned int elementIndex) const {
}
private:
KokkosFunctor();
};
int main(int argc, char* argv[]) {
// a couple of inputs. change the numberOfIntervals to control the amount
// of work done
const unsigned int numberOfElements = 1e2;
// The number of buckets in our histogram
const unsigned int numberOfBuckets = 1e2;
// these are c++ timers...for timing
high_resolution_clock::time_point tic;
high_resolution_clock::time_point toc;
printf("Creating the input vector \n");
vector<unsigned int> input(numberOfElements);
for(unsigned int i = 0; i < numberOfElements; ++i) {
input[i] = i;
}
//std::random_shuffle(input.begin(), input.end());
// ===============================================================
// ********************** < do slow serial> **********************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
vector<unsigned int> slowSerialHistogram(numberOfBuckets);
tic = high_resolution_clock::now();
const unsigned int bucketSize = input.size()/numberOfBuckets;
for (unsigned int index = 0; index < numberOfElements; ++index) {
const unsigned int value = input[index];
const unsigned int bucketNumber = value / bucketSize;
slowSerialHistogram[bucketNumber] += 1;
}
toc = high_resolution_clock::now();
const double slowSerialElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
for(unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex){
if(slowSerialHistogram[bucketIndex]!= bucketSize)
fprintf(stderr, "wrong");
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do slow serial> **********************
// ===============================================================
// ===============================================================
// ********************** < do fast serial> **********************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
vector<unsigned int> fastSerialHistogram(numberOfBuckets, 0);
tic = high_resolution_clock::now();
// TODO: can you make the serial one go faster? i can get about a
// 15-20% speedup, but that's about it. not very interesting
// TODO: do this better
for (unsigned int index = 0; index < numberOfElements; ++index) {
const unsigned int value = input[index];
const unsigned int bucketNumber = value / bucketSize;
slowSerialHistogram[bucketNumber] += 1;
}
toc = high_resolution_clock::now();
const double fastSerialElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (fastSerialHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, fastSerialHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("fast: time %8.2e speedup %8.2e\n",
fastSerialElapsedTime,
slowSerialElapsedTime / fastSerialElapsedTime);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do fast serial> **********************
// ===============================================================
// we will repeat the computation for each of the numbers of threads
vector<unsigned int> numberOfThreadsArray;
numberOfThreadsArray.push_back(1);
numberOfThreadsArray.push_back(2);
numberOfThreadsArray.push_back(4);
numberOfThreadsArray.push_back(8);
numberOfThreadsArray.push_back(16);
numberOfThreadsArray.push_back(24);
const size_t grainSize =
std::max(unsigned(1e4), numberOfElements / 48);
// ===============================================================
// ********************** < do tbb> ******************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with tbb\n");
// for each number of threads
for (const unsigned int numberOfThreads :
numberOfThreadsArray) {
// initialize tbb's threading system for this number of threads
tbb::task_scheduler_init init(numberOfThreads);
atomic<unsigned long> * results = new atomic<unsigned long>[numberOfBuckets];
//bzero(results, sizeof(atomic<unsigned long>) * numberOfElements);
TbbOutputter tbbOutputter(&input, results, numberOfBuckets, numberOfElements);
// start timing
tic = high_resolution_clock::now();
// dispatch threads
parallel_reduce(tbb::blocked_range<size_t>(0, numberOfElements,
grainSize),
tbbOutputter);
// stop timing
toc = high_resolution_clock::now();
const double threadedElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
atomic<unsigned long> * tbbHistogram = tbbOutputter.result_;
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (tbbHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, unsigned(tbbHistogram[bucketIndex]),
bucketSize);
exit(1);
}
}
// output speedup
printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n",
numberOfThreads,
threadedElapsedTime,
fastSerialElapsedTime / threadedElapsedTime,
100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads);
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do tbb> ******************************
// ===============================================================
// ===============================================================
// ********************** < do openmp> ***************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with openmp\n");
// for each number of threads
for (const unsigned int numberOfThreads :
numberOfThreadsArray) {
// set the number of threads for openmp
omp_set_num_threads(numberOfThreads);
vector<unsigned int> ompHistogram(numberOfBuckets, 0);
// start timing
tic = high_resolution_clock::now();
// TODO: do openmp
// stop timing
toc = high_resolution_clock::now();
const double threadedElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (ompHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, ompHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n",
numberOfThreads,
threadedElapsedTime,
fastSerialElapsedTime / threadedElapsedTime,
100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads);
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do openmp> ***************************
// ===============================================================
// ===============================================================
// ********************** < do cuda> *****************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with cuda\n");
// we will repeat the computation for each of the numbers of threads
vector<unsigned int> threadsPerBlockArray;
threadsPerBlockArray.push_back(32);
threadsPerBlockArray.push_back(64);
threadsPerBlockArray.push_back(128);
threadsPerBlockArray.push_back(256);
threadsPerBlockArray.push_back(512);
printf("performing calculations with cuda\n");
// for each number of threads per block
for (const unsigned int numberOfThreadsPerBlock :
threadsPerBlockArray) {
vector<unsigned int> cudaHistogram(numberOfBuckets, 0);
// start timing
tic = high_resolution_clock::now();
// TODO: do cuda stuff
// do scalar integration with cuda for this number of threads per block
cudaDoHistogramPopulation(numberOfThreadsPerBlock,
&cudaHistogram[0]);
// stop timing
toc = high_resolution_clock::now();
const double cudaElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (cudaHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, cudaHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("%3u : time %8.2e speedup %8.2e\n",
numberOfThreadsPerBlock,
cudaElapsedTime,
fastSerialElapsedTime / cudaElapsedTime);
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do cuda> *****************************
// ===============================================================
// ===============================================================
// ********************** < do kokkos> *****************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with kokkos running on %s\n",
typeid(Kokkos::DefaultExecutionSpace).name());
Kokkos::initialize();
// start timing
tic = high_resolution_clock::now();
// TODO: do kokkos stuff
// stop timing
toc = high_resolution_clock::now();
const double kokkosElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
vector<unsigned int> kokkosHistogram(numberOfBuckets, 0);
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (kokkosHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, kokkosHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("kokkos : time %8.2e speedup %8.2e\n",
kokkosElapsedTime,
fastSerialElapsedTime / kokkosElapsedTime);
Kokkos::finalize();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do kokkos> ***************************
// ===============================================================
return 0;
}
<commit_msg>openmp<commit_after>// -*- C++ -*-
// ex1_histogram.cc
// an exercise for the sandia 2014 clinic team.
// here we do a histogram calculation over unsigned ints
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <array>
#include <string>
#include <chrono>
#include <algorithm>
// header file for openmp
#include <omp.h>
// header files for tbb
#include <tbb/blocked_range.h>
#include <tbb/parallel_reduce.h>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include <tbb/atomic.h>
// header files for cuda implementation
#include "ex1_histogram_cuda.cuh"
// header files for kokkos
#include <Kokkos_Core.hpp>
using std::string;
using std::vector;
using std::array;
using std::chrono::high_resolution_clock;
using std::chrono::duration;
using std::chrono::duration_cast;
using tbb::atomic;
class TbbOutputter {
public:
vector<unsigned int> * input_;
atomic<unsigned long> * result_;
unsigned long numBuckets_;
unsigned long size_;
TbbOutputter(vector<unsigned int> * input, atomic<unsigned long> * results,
unsigned long numBuckets, unsigned long size)
: input_(input), result_(results), numBuckets_(numBuckets), size_(size) {
}
TbbOutputter(const TbbOutputter & other,
tbb::split)
: input_(other.input_), result_(other.result_),
numBuckets_(other.numBuckets_), size_(other.size_){
//printf("split copy constructor called\n");
}
void operator()(const tbb::blocked_range<size_t> & range) {
//printf("TbbOutputter asked to process range from %7zu to %7zu\n",
//range.begin(), range.end());
unsigned long bucketSize = size_/numBuckets_;
for(unsigned long i=range.begin(); i!= range.end(); ++i ) {
(result_ + (((*input_)[i])/bucketSize))->fetch_and_increment();
}
}
void join(const TbbOutputter & other) {
}
private:
TbbOutputter();
};
struct KokkosFunctor {
const unsigned int _bucketSize;
KokkosFunctor(const double bucketSize) : _bucketSize(bucketSize) {
}
KOKKOS_INLINE_FUNCTION
void operator()(const unsigned int elementIndex) const {
}
private:
KokkosFunctor();
};
int main(int argc, char* argv[]) {
// a couple of inputs. change the numberOfIntervals to control the amount
// of work done
const unsigned int numberOfElements = 1e2;
// The number of buckets in our histogram
const unsigned int numberOfBuckets = 1e2;
// these are c++ timers...for timing
high_resolution_clock::time_point tic;
high_resolution_clock::time_point toc;
printf("Creating the input vector \n");
vector<unsigned int> input(numberOfElements);
for(unsigned int i = 0; i < numberOfElements; ++i) {
input[i] = i;
}
//std::random_shuffle(input.begin(), input.end());
// ===============================================================
// ********************** < do slow serial> **********************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
vector<unsigned int> slowSerialHistogram(numberOfBuckets);
tic = high_resolution_clock::now();
const unsigned int bucketSize = input.size()/numberOfBuckets;
for (unsigned int index = 0; index < numberOfElements; ++index) {
const unsigned int value = input[index];
const unsigned int bucketNumber = value / bucketSize;
slowSerialHistogram[bucketNumber] += 1;
}
toc = high_resolution_clock::now();
const double slowSerialElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
for(unsigned int bucketIndex = 0; bucketIndex < numberOfBuckets; ++bucketIndex){
if(slowSerialHistogram[bucketIndex]!= bucketSize)
fprintf(stderr, "wrong");
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do slow serial> **********************
// ===============================================================
// ===============================================================
// ********************** < do fast serial> **********************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
vector<unsigned int> fastSerialHistogram(numberOfBuckets, 0);
tic = high_resolution_clock::now();
// TODO: can you make the serial one go faster? i can get about a
// 15-20% speedup, but that's about it. not very interesting
// TODO: do this better
for (unsigned int index = 0; index < numberOfElements; ++index) {
const unsigned int value = input[index];
const unsigned int bucketNumber = value / bucketSize;
slowSerialHistogram[bucketNumber] += 1;
}
toc = high_resolution_clock::now();
const double fastSerialElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (fastSerialHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, fastSerialHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("fast: time %8.2e speedup %8.2e\n",
fastSerialElapsedTime,
slowSerialElapsedTime / fastSerialElapsedTime);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do fast serial> **********************
// ===============================================================
// we will repeat the computation for each of the numbers of threads
vector<unsigned int> numberOfThreadsArray;
numberOfThreadsArray.push_back(1);
numberOfThreadsArray.push_back(2);
numberOfThreadsArray.push_back(4);
numberOfThreadsArray.push_back(8);
numberOfThreadsArray.push_back(16);
numberOfThreadsArray.push_back(24);
const size_t grainSize =
std::max(unsigned(1e4), numberOfElements / 48);
// ===============================================================
// ********************** < do tbb> ******************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with tbb\n");
// for each number of threads
for (const unsigned int numberOfThreads :
numberOfThreadsArray) {
// initialize tbb's threading system for this number of threads
tbb::task_scheduler_init init(numberOfThreads);
atomic<unsigned long> * results = new atomic<unsigned long>[numberOfBuckets];
//bzero(results, sizeof(atomic<unsigned long>) * numberOfElements);
TbbOutputter tbbOutputter(&input, results, numberOfBuckets, numberOfElements);
// start timing
tic = high_resolution_clock::now();
// dispatch threads
parallel_reduce(tbb::blocked_range<size_t>(0, numberOfElements,
grainSize),
tbbOutputter);
// stop timing
toc = high_resolution_clock::now();
const double threadedElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
atomic<unsigned long> * tbbHistogram = tbbOutputter.result_;
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (tbbHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, unsigned(tbbHistogram[bucketIndex]),
bucketSize);
exit(1);
}
}
// output speedup
printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n",
numberOfThreads,
threadedElapsedTime,
fastSerialElapsedTime / threadedElapsedTime,
100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads);
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do tbb> ******************************
// ===============================================================
// ===============================================================
// ********************** < do openmp> ***************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with openmp\n");
// for each number of threads
for (const unsigned int numberOfThreads :
numberOfThreadsArray) {
// set the number of threads for openmp
omp_set_num_threads(numberOfThreads);
vector<unsigned int> ompHistogram(numberOfBuckets, 0);
// start timing
tic = high_resolution_clock::now();
#pragma omp parallel for
for(unsigned int i = 0; i < input.size(); ++i) {
#pragma omp atomic update
ompHistogram[input[i]/bucketSize] += 1;
}
// stop timing
toc = high_resolution_clock::now();
const double threadedElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (ompHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, ompHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("%3u : time %8.2e speedup %8.2e (%%%5.1f of ideal)\n",
numberOfThreads,
threadedElapsedTime,
fastSerialElapsedTime / threadedElapsedTime,
100. * fastSerialElapsedTime / threadedElapsedTime / numberOfThreads);
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do openmp> ***************************
// ===============================================================
// ===============================================================
// ********************** < do cuda> *****************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with cuda\n");
// we will repeat the computation for each of the numbers of threads
vector<unsigned int> threadsPerBlockArray;
threadsPerBlockArray.push_back(32);
threadsPerBlockArray.push_back(64);
threadsPerBlockArray.push_back(128);
threadsPerBlockArray.push_back(256);
threadsPerBlockArray.push_back(512);
printf("performing calculations with cuda\n");
// for each number of threads per block
for (const unsigned int numberOfThreadsPerBlock :
threadsPerBlockArray) {
vector<unsigned int> cudaHistogram(numberOfBuckets, 0);
// start timing
tic = high_resolution_clock::now();
// TODO: do cuda stuff
// do scalar integration with cuda for this number of threads per block
cudaDoHistogramPopulation(numberOfThreadsPerBlock,
&cudaHistogram[0]);
// stop timing
toc = high_resolution_clock::now();
const double cudaElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (cudaHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, cudaHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("%3u : time %8.2e speedup %8.2e\n",
numberOfThreadsPerBlock,
cudaElapsedTime,
fastSerialElapsedTime / cudaElapsedTime);
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do cuda> *****************************
// ===============================================================
// ===============================================================
// ********************** < do kokkos> *****************************
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
printf("performing calculations with kokkos running on %s\n",
typeid(Kokkos::DefaultExecutionSpace).name());
Kokkos::initialize();
// start timing
tic = high_resolution_clock::now();
// TODO: do kokkos stuff
// stop timing
toc = high_resolution_clock::now();
const double kokkosElapsedTime =
duration_cast<duration<double> >(toc - tic).count();
// check the answer
vector<unsigned int> kokkosHistogram(numberOfBuckets, 0);
for (unsigned int bucketIndex = 0;
bucketIndex < numberOfBuckets; ++bucketIndex) {
if (kokkosHistogram[bucketIndex] != bucketSize) {
fprintf(stderr, "bucket %u has the wrong value: %u instead of %u\n",
bucketIndex, kokkosHistogram[bucketIndex], bucketSize);
exit(1);
}
}
// output speedup
printf("kokkos : time %8.2e speedup %8.2e\n",
kokkosElapsedTime,
fastSerialElapsedTime / kokkosElapsedTime);
Kokkos::finalize();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ********************** </do kokkos> ***************************
// ===============================================================
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/hist:$Name: $:$Id: Haxis.cxx,v 1.2 2000/06/13 10:34:10 brun Exp $
// Author: Rene Brun 18/05/95
// ---------------------------------- haxis.C
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "TH1.h"
//______________________________________________________________________________
Int_t TH1::AxisChoice( Option_t *axis) const
{
char achoice = toupper(axis[0]);
if (achoice == 'X') return 1;
if (achoice == 'Y') return 2;
if (achoice == 'Z') return 3;
return 0;
}
//______________________________________________________________________________
Int_t TH1::GetNdivisions( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetNdivisions();
if (ax == 2) return fYaxis.GetNdivisions();
if (ax == 3) return fZaxis.GetNdivisions();
return 0;
}
//______________________________________________________________________________
Color_t TH1::GetAxisColor( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetAxisColor();
if (ax == 2) return fYaxis.GetAxisColor();
if (ax == 3) return fZaxis.GetAxisColor();
return 0;
}
//______________________________________________________________________________
Color_t TH1::GetLabelColor( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelColor();
if (ax == 2) return fYaxis.GetLabelColor();
if (ax == 3) return fZaxis.GetLabelColor();
return 0;
}
//______________________________________________________________________________
Style_t TH1::GetLabelFont( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelFont();
if (ax == 2) return fYaxis.GetLabelFont();
if (ax == 3) return fZaxis.GetLabelFont();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetLabelOffset( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelOffset();
if (ax == 2) return fYaxis.GetLabelOffset();
if (ax == 3) return fZaxis.GetLabelOffset();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetLabelSize( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelSize();
if (ax == 2) return fYaxis.GetLabelSize();
if (ax == 3) return fZaxis.GetLabelSize();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetTickLength( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetTickLength();
if (ax == 2) return fYaxis.GetTickLength();
if (ax == 3) return fZaxis.GetTickLength();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetTitleOffset( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetTitleOffset();
if (ax == 2) return fYaxis.GetTitleOffset();
if (ax == 3) return fZaxis.GetTitleOffset();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetTitleSize( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetTitleSize();
if (ax == 2) return fYaxis.GetTitleSize();
if (ax == 3) return fZaxis.GetTitleSize();
return 0;
}
//______________________________________________________________________________
void TH1::SetNdivisions(Int_t n, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetNdivisions(n);
if (ax == 2) fYaxis.SetNdivisions(n);
if (ax == 3) fZaxis.SetNdivisions(n);
}
//______________________________________________________________________________
void TH1::SetAxisColor(Color_t color, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetAxisColor(color);
if (ax == 2) fYaxis.SetAxisColor(color);
if (ax == 3) fZaxis.SetAxisColor(color);
}
//______________________________________________________________________________
void TH1::SetAxisRange(Axis_t xmin, Axis_t xmax, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
TAxis *theAxis = 0;
if (ax == 1) theAxis = GetXaxis();
if (ax == 2) theAxis = GetYaxis();
if (ax == 3) theAxis = GetZaxis();
Int_t bin1 = theAxis->FindFixBin(xmin);
Int_t bin2 = theAxis->FindFixBin(xmax);
theAxis->SetRange(bin1, bin2);
}
//______________________________________________________________________________
void TH1::SetLabelColor(Color_t color, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelColor(color);
if (ax == 2) fYaxis.SetLabelColor(color);
if (ax == 3) fZaxis.SetLabelColor(color);
}
//______________________________________________________________________________
void TH1::SetLabelFont(Style_t font, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelFont(font);
if (ax == 2) fYaxis.SetLabelFont(font);
if (ax == 3) fZaxis.SetLabelFont(font);
}
//______________________________________________________________________________
void TH1::SetLabelOffset(Float_t offset, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelOffset(offset);
if (ax == 2) fYaxis.SetLabelOffset(offset);
if (ax == 3) fZaxis.SetLabelOffset(offset);
}
//______________________________________________________________________________
void TH1::SetLabelSize(Float_t size, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelSize(size);
if (ax == 2) fYaxis.SetLabelSize(size);
if (ax == 3) fZaxis.SetLabelSize(size);
}
//______________________________________________________________________________
void TH1::SetTickLength(Float_t length, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetTickLength(length);
if (ax == 2) fYaxis.SetTickLength(length);
if (ax == 3) fZaxis.SetTickLength(length);
}
//______________________________________________________________________________
void TH1::SetTitleOffset(Float_t offset, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetTitleOffset(offset);
if (ax == 2) fYaxis.SetTitleOffset(offset);
if (ax == 3) fZaxis.SetTitleOffset(offset);
}
//______________________________________________________________________________
void TH1::SetTitleSize(Float_t size, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetTitleSize(size);
if (ax == 2) fYaxis.SetTitleSize(size);
if (ax == 3) fZaxis.SetTitleSize(size);
}
<commit_msg>In TH1::SetAxisRange, automatically call SetMinimum/SetMaximum in case the function is called with: -the "y" option for a 1-d histogram -the "z" option for a 2-d histogram<commit_after>// @(#)root/hist:$Name: $:$Id: Haxis.cxx,v 1.3 2000/12/13 15:13:51 brun Exp $
// Author: Rene Brun 18/05/95
// ---------------------------------- haxis.C
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "TH1.h"
//______________________________________________________________________________
Int_t TH1::AxisChoice( Option_t *axis) const
{
char achoice = toupper(axis[0]);
if (achoice == 'X') return 1;
if (achoice == 'Y') return 2;
if (achoice == 'Z') return 3;
return 0;
}
//______________________________________________________________________________
Int_t TH1::GetNdivisions( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetNdivisions();
if (ax == 2) return fYaxis.GetNdivisions();
if (ax == 3) return fZaxis.GetNdivisions();
return 0;
}
//______________________________________________________________________________
Color_t TH1::GetAxisColor( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetAxisColor();
if (ax == 2) return fYaxis.GetAxisColor();
if (ax == 3) return fZaxis.GetAxisColor();
return 0;
}
//______________________________________________________________________________
Color_t TH1::GetLabelColor( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelColor();
if (ax == 2) return fYaxis.GetLabelColor();
if (ax == 3) return fZaxis.GetLabelColor();
return 0;
}
//______________________________________________________________________________
Style_t TH1::GetLabelFont( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelFont();
if (ax == 2) return fYaxis.GetLabelFont();
if (ax == 3) return fZaxis.GetLabelFont();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetLabelOffset( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelOffset();
if (ax == 2) return fYaxis.GetLabelOffset();
if (ax == 3) return fZaxis.GetLabelOffset();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetLabelSize( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetLabelSize();
if (ax == 2) return fYaxis.GetLabelSize();
if (ax == 3) return fZaxis.GetLabelSize();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetTickLength( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetTickLength();
if (ax == 2) return fYaxis.GetTickLength();
if (ax == 3) return fZaxis.GetTickLength();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetTitleOffset( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetTitleOffset();
if (ax == 2) return fYaxis.GetTitleOffset();
if (ax == 3) return fZaxis.GetTitleOffset();
return 0;
}
//______________________________________________________________________________
Float_t TH1::GetTitleSize( Option_t *axis) const
{
Int_t ax = AxisChoice(axis);
if (ax == 1) return fXaxis.GetTitleSize();
if (ax == 2) return fYaxis.GetTitleSize();
if (ax == 3) return fZaxis.GetTitleSize();
return 0;
}
//______________________________________________________________________________
void TH1::SetNdivisions(Int_t n, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetNdivisions(n);
if (ax == 2) fYaxis.SetNdivisions(n);
if (ax == 3) fZaxis.SetNdivisions(n);
}
//______________________________________________________________________________
void TH1::SetAxisColor(Color_t color, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetAxisColor(color);
if (ax == 2) fYaxis.SetAxisColor(color);
if (ax == 3) fZaxis.SetAxisColor(color);
}
//______________________________________________________________________________
void TH1::SetAxisRange(Axis_t xmin, Axis_t xmax, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
TAxis *theAxis = 0;
if (ax == 1) theAxis = GetXaxis();
if (ax == 2) theAxis = GetYaxis();
if (ax == 3) theAxis = GetZaxis();
if (ax > fDimension) {
SetMinimum(xmin);
SetMaximum(xmax);
return;
}
Int_t bin1 = theAxis->FindFixBin(xmin);
Int_t bin2 = theAxis->FindFixBin(xmax);
theAxis->SetRange(bin1, bin2);
}
//______________________________________________________________________________
void TH1::SetLabelColor(Color_t color, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelColor(color);
if (ax == 2) fYaxis.SetLabelColor(color);
if (ax == 3) fZaxis.SetLabelColor(color);
}
//______________________________________________________________________________
void TH1::SetLabelFont(Style_t font, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelFont(font);
if (ax == 2) fYaxis.SetLabelFont(font);
if (ax == 3) fZaxis.SetLabelFont(font);
}
//______________________________________________________________________________
void TH1::SetLabelOffset(Float_t offset, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelOffset(offset);
if (ax == 2) fYaxis.SetLabelOffset(offset);
if (ax == 3) fZaxis.SetLabelOffset(offset);
}
//______________________________________________________________________________
void TH1::SetLabelSize(Float_t size, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetLabelSize(size);
if (ax == 2) fYaxis.SetLabelSize(size);
if (ax == 3) fZaxis.SetLabelSize(size);
}
//______________________________________________________________________________
void TH1::SetTickLength(Float_t length, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetTickLength(length);
if (ax == 2) fYaxis.SetTickLength(length);
if (ax == 3) fZaxis.SetTickLength(length);
}
//______________________________________________________________________________
void TH1::SetTitleOffset(Float_t offset, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetTitleOffset(offset);
if (ax == 2) fYaxis.SetTitleOffset(offset);
if (ax == 3) fZaxis.SetTitleOffset(offset);
}
//______________________________________________________________________________
void TH1::SetTitleSize(Float_t size, Option_t *axis)
{
Int_t ax = AxisChoice(axis);
if (ax == 1) fXaxis.SetTitleSize(size);
if (ax == 2) fYaxis.SetTitleSize(size);
if (ax == 3) fZaxis.SetTitleSize(size);
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2014 Michael G. Brehm
//
// 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 "stdafx.h"
#pragma warning(push, 4)
// g_break
//
// Current program break address
void* g_break = nullptr;
// g_startupinfo (main.cpp)
//
// Process startup information provided by the service
extern sys32_startup_info g_startupinfo;
// s_sysinfo
//
// Static copy of the system information; required to know allocation granularity
static SYSTEM_INFO s_sysinfo = []() -> SYSTEM_INFO {
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo;
}();
//-----------------------------------------------------------------------------
// sys_brk
//
// Sets the process program break, which is extra space reserved by a process
// to implement a heap. Specify nullptr to get the current break address
//
// Arguments:
//
// address - Address to set the program break to -- treated as a hint
uapi::long_t sys_brk(void* address)
{
MEMORY_BASIC_INFORMATION meminfo; // Information on a memory region
// NULL can be passed in as the address to retrieve the current program break
if(address == nullptr) return reinterpret_cast<uapi::long_t>(g_break);
// Create a working copy of the current break and calcuate the requested delta
intptr_t current = intptr_t(g_break);
intptr_t delta = align::up(intptr_t(address) - current, s_sysinfo.dwAllocationGranularity);
// INCREASE PROGRAM BREAK
if(delta > 0) {
// Check to see if the region at the currently set break is MEM_FREE
VirtualQuery(reinterpret_cast<void*>(current), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
if(meminfo.State == MEM_FREE) {
// Only ask for as much as is available contiguously
delta = min(delta, align::down(intptr_t(meminfo.RegionSize), s_sysinfo.dwAllocationGranularity));
// Attempt to reserve and commit the calcuated region with READWRITE access
void* result = VirtualAlloc(reinterpret_cast<void*>(current), delta, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if(result) g_break = reinterpret_cast<void*>(current + delta);
}
}
// DECREASE PROGRAM BREAK
else if(delta < 0) {
// Determine the target address, which can never be below the original program break
intptr_t target = max(intptr_t(g_startupinfo.program_break), (current + delta));
// Work backwards from the previously allocated region to release as many as possible
VirtualQuery(reinterpret_cast<void*>(current - 1), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
while(target <= intptr_t(meminfo.AllocationBase)) {
// Attempt to decommit and release the entire region
if(!VirtualFree(meminfo.AllocationBase, 0, MEM_RELEASE)) break;
// Align the current break pointer with the released region's base address
current = intptr_t(meminfo.AllocationBase);
// Get information on the next region lower in memory to check if it can be released
VirtualQuery(reinterpret_cast<void*>(current - 1), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
}
// Reset the program break to the last successfully released region base address
g_break = reinterpret_cast<void*>(current);
}
return reinterpret_cast<uapi::long_t>(g_break);
}
//-----------------------------------------------------------------------------
#pragma warning(pop)
<commit_msg>Update commentary for sys_brk<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2014 Michael G. Brehm
//
// 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 "stdafx.h"
#pragma warning(push, 4)
// g_break
//
// Current program break address
void* g_break = nullptr;
// g_startupinfo (main.cpp)
//
// Process startup information provided by the service
extern sys32_startup_info g_startupinfo;
// s_sysinfo
//
// Static copy of the system information; required to know allocation granularity
static SYSTEM_INFO s_sysinfo = []() -> SYSTEM_INFO {
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo;
}();
//-----------------------------------------------------------------------------
// sys_brk
//
// Sets the process program break, which is extra space reserved by a process
// to implement a heap. Specify nullptr to get the current break address. This
// function is not capable of returning an error code on Linux, to indicate that
// the operation could not be completed, return the previously set break address,
// the interpretation of which has been left as a runtime library detail
//
// Arguments:
//
// address - Address to set the program break to (hint)
uapi::long_t sys_brk(void* address)
{
MEMORY_BASIC_INFORMATION meminfo; // Information on a memory region
// NULL can be passed in as the address to retrieve the current program break
if(address == nullptr) return reinterpret_cast<uapi::long_t>(g_break);
// Create a working copy of the current break and calcuate the requested delta
intptr_t current = intptr_t(g_break);
intptr_t delta = align::up(intptr_t(address) - current, s_sysinfo.dwAllocationGranularity);
// INCREASE PROGRAM BREAK
if(delta > 0) {
// Check to see if the region at the currently set break is MEM_FREE
VirtualQuery(reinterpret_cast<void*>(current), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
if(meminfo.State == MEM_FREE) {
// Only ask for as much as is available contiguously
delta = min(delta, align::down(intptr_t(meminfo.RegionSize), s_sysinfo.dwAllocationGranularity));
// Attempt to reserve and commit the calcuated region with READWRITE access
void* result = VirtualAlloc(reinterpret_cast<void*>(current), delta, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if(result) g_break = reinterpret_cast<void*>(current + delta);
}
}
// DECREASE PROGRAM BREAK
else if(delta < 0) {
// Determine the target address, which can never be below the original program break
intptr_t target = max(intptr_t(g_startupinfo.program_break), (current + delta));
// Work backwards from the previously allocated region to release as many as possible
VirtualQuery(reinterpret_cast<void*>(current - 1), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
while(target <= intptr_t(meminfo.AllocationBase)) {
// Attempt to decommit and release the entire region
if(!VirtualFree(meminfo.AllocationBase, 0, MEM_RELEASE)) break;
// Align the current break pointer with the released region's base address
current = intptr_t(meminfo.AllocationBase);
// Get information on the next region lower in memory to check if it can be released
VirtualQuery(reinterpret_cast<void*>(current - 1), &meminfo, sizeof(MEMORY_BASIC_INFORMATION));
}
// Reset the program break to the last successfully released region base address
g_break = reinterpret_cast<void*>(current);
}
return reinterpret_cast<uapi::long_t>(g_break);
}
//-----------------------------------------------------------------------------
#pragma warning(pop)
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental & Ullrich Koethe 2001.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
//
// See http://www.boost.org for most recent version including documentation.
// TEST LIB
#include <boost/test/unit_test.hpp>
using boost::unit_test_framework::test_suite;
// STL
#include <vector>
#include <string>
void check_string( std::string const& s )
{
// reports 'error in "check_string": test s.substr( 0, 3 ) == "hdr" failed [actual_value != hdr]'
BOOST_CHECK_EQUAL( s.substr( 0, 3 ), "hdr" );
}
namespace {
std::string const params[] = { "hdr1 ", "hdr2", "3 " };
}
test_suite*
init_unit_test_suite( int argc, char * argv[] ) {
test_suite* test= BOOST_TEST_SUITE( "Unit test example 4" );
test->add( BOOST_PARAM_TEST_CASE( &check_string, (std::string const*)params, params+3 ), 1 );
return test;
}
// EOF
<commit_msg>comment fixed<commit_after>// (C) Copyright Gennadiy Rozental & Ullrich Koethe 2001.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
//
// See http://www.boost.org for most recent version including documentation.
// Boost.Test
#include <boost/test/unit_test.hpp>
using boost::unit_test_framework::test_suite;
// STL
#include <vector>
#include <string>
void check_string( std::string const& s )
{
// reports 'error in "check_string": test s.substr( 0, 3 ) == "hdr" failed [actual_value != hdr]'
BOOST_CHECK_EQUAL( s.substr( 0, 3 ), "hdr" );
}
namespace {
std::string const params[] = { "hdr1 ", "hdr2", "3 " };
}
test_suite*
init_unit_test_suite( int argc, char * argv[] ) {
test_suite* test= BOOST_TEST_SUITE( "Unit test example 4" );
test->add( BOOST_PARAM_TEST_CASE( &check_string, (std::string const*)params, params+3 ), 1 );
return test;
}
// EOF
<|endoftext|> |
<commit_before>#include "engine.h"
#include "component.h"
#include "object.h"
#include "yaml-cpp/yaml.h"
#include <fstream>
#include <vector>
#include <string>
#include <cstdio>
#include <ctime>
#include "SDL.h"
#include <algorithm>
#ifndef GEAR2D_VERSION
#define GEAR2D_VERSION "undefined"
#warning GEAR2D_VERSION undefined! Gear2D should be compiled with -DGEAR2D_VERSION=<version>
#endif
extern "C" {
const char * libraryversion = GEAR2D_VERSION;
}
namespace gear2d {
std::map<std::string, std::string> * engine::config;
component::factory * engine::cfactory;
object::factory * engine::ofactory;
std::map<component::type, std::set<component::base *> > * engine::components;
std::set<component::base *> * engine::removedcom;
std::set<object::id> * engine::destroyedobj;
bool engine::initialized;
bool engine::started;
std::string * engine::nextscene;
const char * engine::version() { return libraryversion; }
int engine::eventfilter(const void * _ev) {
const SDL_Event * ev = (const SDL_Event*)_ev;
switch(ev->type) {
case SDL_QUIT:
started = !(ev->type == SDL_QUIT);
return 1;
break;
default:
break;
}
return 1;
}
void engine::add(component::base * c) {
if (components == 0) {
std::cerr << "(Gear2D Engine) Initialize the engine before attaching a component to an object" << std::endl;
}
if (c == 0) return;
(*components)[c->family()].insert(c);
}
void engine::remove(component::base * c, bool rightnow) {
if (rightnow == false) removedcom->insert(c);
else {
(*components)[c->family()].erase(c);
delete c;
}
}
void engine::destroy(object::id oid) {
destroyedobj->insert(oid);
}
void engine::init(bool force) {
if (initialized == true && force == false) return;
if (config != 0) delete config;
srand(std::time(0));
SDL_InitSubSystem(SDL_INIT_EVENTTHREAD | SDL_INIT_VIDEO);
SDL_SetEventFilter((SDL_EventFilter)eventfilter);
config = new std::map<std::string, std::string>;
// erase all the components
if (components != 0) {
for (map<component::family, std::set<component::base *> >::iterator i = components->begin();
i != components->end();
i++)
{
std::set<component::base *> & com = i->second;
while (!com.empty()) {
component::base * c = *(com.begin());
if (c != 0) delete c;
com.erase(c);
}
}
}
delete components;
components = new std::map<component::family, std::set<component::base *> >;
if (removedcom != 0) delete removedcom;
removedcom = new std::set<component::base *>;
if (destroyedobj != 0) delete destroyedobj;
destroyedobj = new std::set<object::id>;
if (ofactory != 0) delete ofactory;
if (cfactory != 0) delete cfactory;
cfactory = new component::factory;
ofactory = new object::factory(*cfactory);
initialized = true;
started = false;
}
void engine::next(std::string configfile) {
*nextscene = configfile;
}
void engine::load(std::string configfile) {
std::ifstream fin(configfile.c_str());
/* initialize yaml parser */
YAML::Parser parser(fin);
YAML::Node node;
map<std::string, std::string> cfg;
/* TODO: add other yaml features */
while (parser.GetNextDocument(node)) node >> cfg;
load(cfg);
fin.close();
}
void engine::load(std::map<std::string, std::string> & cfg) {
init(true);
*config = cfg;
/* get component-search path */
std::string compath = (*config)["compath"];
if (compath == "") {
std::cerr << "(Gear2D Engine) Error locating system-wide component path." << std::endl;
}
cfactory->compath = compath;
config->erase("compath");
/* pre-load some of the components */
/* TODO: travel the compath looking for family/component */
std::vector<std::string> comlist;
if ((*config)["compreload"].size() != 0) {
split(comlist, (*config)["compreload"], ' ');
for (int i = 0; i < comlist.size(); i++) {
std::cerr << "(Gear2D Engine) Pre-loading " << comlist[i] << std::endl;
cfactory->load(comlist[i]);
}
config->erase("compreload");
}
/* load the indicated objects */
std::vector<object::type> objectlist;
split(objectlist, (*config)["objects"], ' ');
config->erase("objects");
/* The rest is added to the object factory global parameters */
ofactory->commonsig = *config;
/* and now build the pointed objects */
for (int i = 0; i < objectlist.size(); i++) {
ofactory->load(objectlist[i]);
ofactory->build(objectlist[i]);
}
if (nextscene) delete nextscene;
nextscene = new std::string("");
}
bool engine::run() {
// make sure we init
init();
int begin = 0, end = 0, dt = 0;
SDL_Event ev;
started = true;
while (started) {
dt = end - begin;
begin = SDL_GetTicks();
timediff delta = dt/1000.0f;
if (dt < 60/1000.0f) SDL_Delay(60/1000.0f - dt);
SDL_PumpEvents();
for (std::set<object::id>::iterator i = destroyedobj->begin(); i != destroyedobj->end(); i++) {
// this will push object's components to removedcom, hopefully.
delete (*i);
}
destroyedobj->clear();
/* first remove components from the running pipeline */
for (std::set<component::base *>::iterator i = removedcom->begin(); i != removedcom->end(); i++) {
component::type f = (*i)->family();
(*components)[f].erase((*i));
if (*i != 0) delete (*i);
// do not manage empty lists
if ((*components)[f].size() == 0)
components->erase(f);
}
// clear the removed list
removedcom->clear();
static char omg[200];
static std::string wm;
wm = "";
/* now update pipeline accordingly */
std::map<component::family, std::set<component::base *> >::iterator comtpit;
for (comtpit = components->begin(); comtpit != components->end(); comtpit++) {
component::family f = comtpit->first;
std::set<component::base *> & list = comtpit->second;
int b = SDL_GetTicks();
for (std::set<component::base*>::iterator comit = list.begin(); comit != list.end(); comit++) {
(*comit)->update(delta);
}
// sprintf(omg, "%s:%.4d ", comtpit->first.c_str(), SDL_GetTicks() - b);
wm += omg;
}
// sprintf(omg, "total (last): %.3d", dt);
wm += omg;
/* no components, quit the engine */
if (components->empty()) started = false;
/* shall load next scene */
if (*nextscene != "") {
load(nextscene->c_str());
started = true;
}
/* consumes all remaining events. next frame it must return empty. */
// while (SDL_PollEvent(&ev));
SDL_Delay(2);
// SDL_WM_SetCaption(wm.c_str(), 0);
end = SDL_GetTicks();
}
delete ofactory;
delete cfactory;
}
}<commit_msg>Adding compath to the common signature<commit_after>#include "engine.h"
#include "component.h"
#include "object.h"
#include "yaml-cpp/yaml.h"
#include <fstream>
#include <vector>
#include <string>
#include <cstdio>
#include <ctime>
#include "SDL.h"
#include <algorithm>
#ifndef GEAR2D_VERSION
#define GEAR2D_VERSION "undefined"
#warning GEAR2D_VERSION undefined! Gear2D should be compiled with -DGEAR2D_VERSION=<version>
#endif
extern "C" {
const char * libraryversion = GEAR2D_VERSION;
}
namespace gear2d {
std::map<std::string, std::string> * engine::config;
component::factory * engine::cfactory;
object::factory * engine::ofactory;
std::map<component::type, std::set<component::base *> > * engine::components;
std::set<component::base *> * engine::removedcom;
std::set<object::id> * engine::destroyedobj;
bool engine::initialized;
bool engine::started;
std::string * engine::nextscene;
const char * engine::version() { return libraryversion; }
int engine::eventfilter(const void * _ev) {
const SDL_Event * ev = (const SDL_Event*)_ev;
switch(ev->type) {
case SDL_QUIT:
started = !(ev->type == SDL_QUIT);
return 1;
break;
default:
break;
}
return 1;
}
void engine::add(component::base * c) {
if (components == 0) {
std::cerr << "(Gear2D Engine) Initialize the engine before attaching a component to an object" << std::endl;
}
if (c == 0) return;
(*components)[c->family()].insert(c);
}
void engine::remove(component::base * c, bool rightnow) {
if (rightnow == false) removedcom->insert(c);
else {
(*components)[c->family()].erase(c);
delete c;
}
}
void engine::destroy(object::id oid) {
destroyedobj->insert(oid);
}
void engine::init(bool force) {
if (initialized == true && force == false) return;
if (config != 0) delete config;
srand(std::time(0));
SDL_InitSubSystem(SDL_INIT_EVENTTHREAD | SDL_INIT_VIDEO);
SDL_SetEventFilter((SDL_EventFilter)eventfilter);
config = new std::map<std::string, std::string>;
// erase all the components
if (components != 0) {
for (map<component::family, std::set<component::base *> >::iterator i = components->begin();
i != components->end();
i++)
{
std::set<component::base *> & com = i->second;
while (!com.empty()) {
component::base * c = *(com.begin());
if (c != 0) delete c;
com.erase(c);
}
}
}
delete components;
components = new std::map<component::family, std::set<component::base *> >;
if (removedcom != 0) delete removedcom;
removedcom = new std::set<component::base *>;
if (destroyedobj != 0) delete destroyedobj;
destroyedobj = new std::set<object::id>;
if (ofactory != 0) delete ofactory;
if (cfactory != 0) delete cfactory;
cfactory = new component::factory;
ofactory = new object::factory(*cfactory);
initialized = true;
started = false;
}
void engine::next(std::string configfile) {
*nextscene = configfile;
}
void engine::load(std::string configfile) {
std::ifstream fin(configfile.c_str());
/* initialize yaml parser */
YAML::Parser parser(fin);
YAML::Node node;
map<std::string, std::string> cfg;
/* TODO: add other yaml features */
while (parser.GetNextDocument(node)) node >> cfg;
load(cfg);
fin.close();
}
void engine::load(std::map<std::string, std::string> & cfg) {
init(true);
*config = cfg;
/* get component-search path */
std::string compath = (*config)["compath"];
if (compath == "") {
std::cerr << "(Gear2D Engine) Error locating system-wide component path." << std::endl;
}
cfactory->compath = compath;
// config->erase("compath");
/* pre-load some of the components */
/* TODO: travel the compath looking for family/component */
std::vector<std::string> comlist;
if ((*config)["compreload"].size() != 0) {
split(comlist, (*config)["compreload"], ' ');
for (int i = 0; i < comlist.size(); i++) {
std::cerr << "(Gear2D Engine) Pre-loading " << comlist[i] << std::endl;
cfactory->load(comlist[i]);
}
config->erase("compreload");
}
/* load the indicated objects */
std::vector<object::type> objectlist;
split(objectlist, (*config)["objects"], ' ');
config->erase("objects");
/* The rest is added to the object factory global parameters */
ofactory->commonsig = *config;
/* and now build the pointed objects */
for (int i = 0; i < objectlist.size(); i++) {
ofactory->load(objectlist[i]);
ofactory->build(objectlist[i]);
}
if (nextscene) delete nextscene;
nextscene = new std::string("");
}
bool engine::run() {
// make sure we init
init();
int begin = 0, end = 0, dt = 0;
SDL_Event ev;
started = true;
while (started) {
dt = end - begin;
begin = SDL_GetTicks();
timediff delta = dt/1000.0f;
if (dt < 60/1000.0f) SDL_Delay(60/1000.0f - dt);
SDL_PumpEvents();
for (std::set<object::id>::iterator i = destroyedobj->begin(); i != destroyedobj->end(); i++) {
// this will push object's components to removedcom, hopefully.
delete (*i);
}
destroyedobj->clear();
/* first remove components from the running pipeline */
for (std::set<component::base *>::iterator i = removedcom->begin(); i != removedcom->end(); i++) {
component::type f = (*i)->family();
(*components)[f].erase((*i));
if (*i != 0) delete (*i);
// do not manage empty lists
if ((*components)[f].size() == 0)
components->erase(f);
}
// clear the removed list
removedcom->clear();
static char omg[200];
static std::string wm;
wm = "";
/* now update pipeline accordingly */
std::map<component::family, std::set<component::base *> >::iterator comtpit;
for (comtpit = components->begin(); comtpit != components->end(); comtpit++) {
component::family f = comtpit->first;
std::set<component::base *> & list = comtpit->second;
int b = SDL_GetTicks();
for (std::set<component::base*>::iterator comit = list.begin(); comit != list.end(); comit++) {
(*comit)->update(delta);
}
// sprintf(omg, "%s:%.4d ", comtpit->first.c_str(), SDL_GetTicks() - b);
wm += omg;
}
// sprintf(omg, "total (last): %.3d", dt);
wm += omg;
/* no components, quit the engine */
if (components->empty()) started = false;
/* shall load next scene */
if (*nextscene != "") {
load(nextscene->c_str());
started = true;
}
/* consumes all remaining events. next frame it must return empty. */
// while (SDL_PollEvent(&ev));
SDL_Delay(2);
// SDL_WM_SetCaption(wm.c_str(), 0);
end = SDL_GetTicks();
}
delete ofactory;
delete cfactory;
}
}<|endoftext|> |
<commit_before>#ifndef SRC_ESIEVE_HPP_
#define SRC_ESIEVE_HPP_
#include <cmath>
#include <vector>
template <typename T>
std::vector<T> esieve(const T &n) {
auto xs = std::vector<T>(n, 0);
for (T i = 2; i < n; ++i) {
if (xs[i] != 0) continue;
for (T j = i; j < n; j += i) {
xs[j] = i;
}
}
return xs;
}
std::map<uint32_t, uint32_t> compute_primes(uint32_t n) {
auto primes = std::map<uint32_t, uint32_t>();
if (n == 0) {
return primes;
}
uint32_t c = 0;
for (; n % 2 == 0; n /= 2, ++c);
if (c) {
primes[2] = c;
}
for (uint32_t f = 3; f * f <= n; f += 2) {
c = 0;
for (; n % f == 0; n /= f, ++c);
if (c) {
primes[f] = c;
}
}
if (n != 1) {
primes[n] = 1;
}
return primes;
}
#endif // SRC_ESIEVE_HPP_
<commit_msg>Fix cpplint complaints<commit_after>#ifndef SRC_ESIEVE_HPP_
#define SRC_ESIEVE_HPP_
#include <map>
#include <cmath>
#include <vector>
template <typename T>
std::vector<T> esieve(const T &n) {
auto xs = std::vector<T>(n, 0);
for (T i = 2; i < n; ++i) {
if (xs[i] != 0) continue;
for (T j = i; j < n; j += i) {
xs[j] = i;
}
}
return xs;
}
std::map<uint32_t, uint32_t> compute_primes(uint32_t n) {
auto primes = std::map<uint32_t, uint32_t>();
if (n == 0) {
return primes;
}
uint32_t c = 0;
for (; n % 2 == 0; n /= 2) {
++c;
}
if (c) {
primes[2] = c;
}
for (uint32_t f = 3; f * f <= n; f += 2) {
c = 0;
for (; n % f == 0; n /= f) {
++c;
}
if (c) {
primes[f] = c;
}
}
if (n != 1) {
primes[n] = 1;
}
return primes;
}
#endif // SRC_ESIEVE_HPP_
<|endoftext|> |
<commit_before>#include "fast++.hpp"
#include <phypp/core/main.hpp>
const char* fastpp_version = "0.1";
int phypp_main(int argc, char* argv[]) {
std::string param_file = (argc >= 2 ? argv[1] : "fast.param");
// Read input data
options_t opts;
input_state_t input;
if (!read_input(opts, input, param_file)) {
return 1;
}
// Initialize the grid
output_state_t output;
gridder_t gridder(opts, input, output);
if (!gridder.check_options()) {
return 1;
}
// Write SEDs if asked
gridder.write_seds();
// Initizalize the fitter
fitter_t fitter(opts, input, gridder, output);
// Build/read the grid and fit galaxies
if (!gridder.build_and_send(fitter)) {
return 1;
}
// Compile results
fitter.find_best_fits();
// Write output to disk
write_output(opts, input, gridder, output);
return 0;
}
<commit_msg>Set version number<commit_after>#include "fast++.hpp"
#include <phypp/core/main.hpp>
const char* fastpp_version = "1.0";
int phypp_main(int argc, char* argv[]) {
std::string param_file = (argc >= 2 ? argv[1] : "fast.param");
// Read input data
options_t opts;
input_state_t input;
if (!read_input(opts, input, param_file)) {
return 1;
}
// Initialize the grid
output_state_t output;
gridder_t gridder(opts, input, output);
if (!gridder.check_options()) {
return 1;
}
// Write SEDs if asked
gridder.write_seds();
// Initizalize the fitter
fitter_t fitter(opts, input, gridder, output);
// Build/read the grid and fit galaxies
if (!gridder.build_and_send(fitter)) {
return 1;
}
// Compile results
fitter.find_best_fits();
// Write output to disk
write_output(opts, input, gridder, output);
return 0;
}
<|endoftext|> |
<commit_before>#include "filter.h"
Image filterNoise(const Image& img) {
Domain dom = img.domain();
Image out(dom);
unsigned int matrix[] = {
1,2,1,
2,4,2,
1,2,1
};
unsigned int max = 0;
for(unsigned int k=0;k<9;k++) {
max += matrix[k];
}
for (auto it = dom.begin(), itend = dom.end(); it != itend; ++it) {
Point p = *it;
unsigned int value = 0;
for(int i=-1; i<= 1; i++) {
for(int j=-1; j<= 1; j++) {
Point q = p + Point(i,j);
if(dom.isInside(q) && img(q) > 0) {
value += matrix[(i+1)*3+(j+1)];
}
}
}
if (value >= max/2)
out.setValue(p,1);
else
out.setValue(p,0);
}
return out;
}
<commit_msg>Tabs to whitespaces<commit_after>#include "filter.h"
Image filterNoise(const Image& img) {
Domain dom = img.domain();
Image out(dom);
unsigned int matrix[] = {
1,2,1,
2,4,2,
1,2,1
};
unsigned int max = 0;
for(unsigned int k=0;k<9;k++) {
max += matrix[k];
}
for (auto it = dom.begin(), itend = dom.end(); it != itend; ++it) {
Point p = *it;
unsigned int value = 0;
for(int i=-1; i<= 1; i++) {
for(int j=-1; j<= 1; j++) {
Point q = p + Point(i,j);
if(dom.isInside(q) && img(q) > 0) {
value += matrix[(i+1)*3+(j+1)];
}
}
}
if (value >= max/2)
out.setValue(p,1);
else
out.setValue(p,0);
}
return out;
}
<|endoftext|> |
<commit_before>/*!
* \file helpers.cc
*
* \brief Helper functions (implementation)
*
* This file implements several small helper functions that do not belong to
* any other file.
*
* \author
* - responsible: Niels Lohmann <nlohmann@informatik.hu-berlin.de>
* - last changes of: \$Author: gierds $
*
* \date
* - created: 2005/11/11
* - last changed: \$Date: 2005/11/16 10:32:25 $
*
* \note This file is part of the tool BPEL2oWFN and was created during the
* project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See
* http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
* for details.
*
* \version \$Revision: 1.9 $
* - 2005-11-11 (nlohmann) Initial version.
* - 2005-11-15 (gierds) Moved commandline evaluation functions from main.cc to here.
* Added LoLA command line arguments.
* - 2005-11-16 (gierds) Added error() and cleanup() functions.
*/
#include "helpers.h"
/// The Petri Net
extern PetriNet *TheNet;
/*!
* \param a set of Petri net nodes
* \param b set of Petri net nodes
* \return union of the sets a and b
*/
set<Node *> setUnion(set<Node *> a, set<Node *> b)
{
set<Node *> result;
insert_iterator<set<Node *, less<Node *> > > res_ins(result, result.begin());
set_union(a.begin(), a.end(), b.begin(), b.end(), res_ins);
return result;
}
/*!
* \param i standard C int
* \return C++ string representing i
*/
string intToString(int i)
{
char buffer[20];
sprintf(buffer, "%d", i);
return string(buffer);
}
// --------------------- functions for command line evaluation --------------------------------
void print_help()
{
// 80 chars
// "--------------------------------------------------------------------------------"
trace("\n");
trace("BPEL2oWFN\n");
trace("---------\n");
trace("Options: \n");
trace(" -f | --file <filename> - read input from <filename>,\n");
trace(" if this parameter is omitted, input is read from\n");
trace(" STDIN\n");
trace(" -d | -dd | -ddd | -dddd | - set debug level\n");
trace(" --debug [1..4] ... some more information soon\n");
trace(" -h | --help - print this screen\n");
trace("\n");
trace("\n");
trace("output modes (choose at maximum one, default is just parsing):\n");
trace("\n");
trace(" -a | --ast - output the AST\n");
trace(" -x | --xml - output simple XML w/o any unnecessary\n");
trace(" informtion\n");
trace(" -pn | --petri-net - output the Petri Net (in LoLA style?)\n");
trace("\n");
trace("special Petri Net modes:\n");
trace("\n");
trace(" -s | --simplify - outpus a structural simplified Petri Net\n");
trace(" (implies option -pn)\n");
trace(" -ll | --low-level - generate an abstract low level Petri Net\n");
trace(" (see manual for further information)\n");
trace(" (implies option -pn)\n");
trace(" -L | --lola - output LoLA input,\n");
trace(" should not used together with -D\n");
trace(" (implies option -pn)\n");
trace(" -L2F | --lola2file - output LoLA input into file (same name as\n");
trace(" input file\n");
trace(" (implies option -L)\n");
trace(" -D | --dot - output dot input\n");
trace(" (implies option -pn)\n");
trace(" -D2F | --dot2file - output dot input into file (same name as\n");
trace(" input file\n");
trace(" (implies option -D)\n");
trace("\n");
trace("For more information see:\n");
trace(" http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel/\n");
trace("\n");
}
void parse_command_line(int argc, char* argv[])
{
if (argc > 1)
{
int argument_counter = 1;
while (argument_counter < argc)
{
char * argument_string = argv[argument_counter++];
// check for input other than stdin
if (! strcmp(argument_string, "-f") || ! strcmp(argument_string, "--file"))
{
if (argument_counter < argc)
{
filename = (std::string) argv[argument_counter++];
if (!(yyin = fopen(filename.c_str(), "r")))
{
throw Exception(FILE_NOT_FOUND, "File '" + filename + "' not found.\n");
// fprintf(stderr, " File '%s' not found.\n", filename);
trace(" File '");
trace(filename);
trace("' not found.\n");
exit(2);
}
}
else
{
print_help();
exit(1);
}
}
// select output, default is just parsing
else if (! strcmp(argument_string, "-pn") || ! strcmp(argument_string, "--petri-net")) {
// output a Petri Net
mode_petri_net = true;
}
else if (! strcmp(argument_string, "-x") || ! strcmp(argument_string, "--xml")) {
// output a pretty xml
mode_pretty_printer = true;
}
else if (! strcmp(argument_string, "-a") || ! strcmp(argument_string, "--ast")) {
// output the AST, but why anyone should want to?
mode_ast = true;
}
// simplyfy?
else if (! strcmp(argument_string, "-s") || ! strcmp(argument_string, "--simplify"))
{
mode_simplify_petri_net = true;
mode_petri_net = true;
}
// low level?
else if (! strcmp(argument_string, "-ll") || ! strcmp(argument_string, "--low-level"))
{
mode_low_level_petri_net = true;
mode_petri_net = true;
}
// generate lola output
else if (! strcmp(argument_string, "-L") || ! strcmp(argument_string, "--lola"))
{
mode_lola_petri_net = true;
mode_petri_net = true;
}
// generate lola output and write it into a file
else if (! strcmp(argument_string, "-L2F") || ! strcmp(argument_string, "--lola2file"))
{
mode_lola_petri_net = true;
mode_lola_2_file = true;
mode_petri_net = true;
}
// generate dot output
else if (! strcmp(argument_string, "-D") || ! strcmp(argument_string, "--dot"))
{
mode_dot_petri_net = true;
mode_petri_net = true;
}
// generate dot output and write it into a file
else if (! strcmp(argument_string, "-D2F") || ! strcmp(argument_string, "--dot2file"))
{
mode_dot_petri_net = true;
mode_dot_2_file = true;
mode_petri_net = true;
}
// debug
else if (! strcmp(argument_string, "-d"))
{
debug_level = TRACE_WARNINGS;
}
else if (! strcmp(argument_string, "-dd"))
{
debug_level = TRACE_INFORMATION;
}
else if (! strcmp(argument_string, "-ddd"))
{
debug_level = TRACE_DEBUG;
}
else if (! strcmp(argument_string, "-dddd"))
{
debug_level = TRACE_VERY_DEBUG;
}
else if (! strcmp(argument_string, "--debug"))
{
if (argument_counter < argc)
{
argument_string = argv[argument_counter++];
// instead of atoi we may use the stringstream class?
debug_level = atoi(argument_string);
if (debug_level < 1 || debug_level > 4) {
print_help();
exit(1);
}
}
else
{
print_help();
exit(1);
}
}
// help
else if (! strcmp(argument_string, "-h") || ! strcmp(argument_string, "-?") || ! strcmp(argument_string, "--help"))
{
print_help();
exit(1);
}
// unknown parameter
else
{
trace("Unknown option: " + ((std::string) argument_string) + "\n");
print_help();
exit(1);
}
}
// take care of the output modes
if ((mode_petri_net && mode_ast) || (mode_petri_net && mode_pretty_printer) || (mode_ast && mode_pretty_printer))
{
print_help();
exit(1);
}
}
// trace and check for some files to be created
if ( filename != "")
{
trace(TRACE_INFORMATION, "Reading BPEL from file ");
trace(TRACE_INFORMATION, (filename));
trace(TRACE_INFORMATION, "\n");
// if wanted, create a dot output file
if ( mode_dot_2_file )
{
trace(TRACE_INFORMATION, "Creating file for dot output\n");
std::string dotti_file = filename;
// try to replace .bpel through .dot
if ( dotti_file.rfind(".bpel", 0) >= (dotti_file.length() - 6) )
{
dotti_file = dotti_file.replace( (dotti_file.length() - 5), 5, ".dot");
}
else
{
dotti_file += ".dot";
}
/// set dot filename
dot_filename = dotti_file.c_str();
/// create dot file and point to it
dot_output = new std::ofstream(dotti_file.c_str(), std::ofstream::out | std::ofstream::trunc);
}
// if wanted, create a LoLA output file
if ( mode_lola_2_file )
{
trace(TRACE_INFORMATION, "Creating file for lola output\n");
std::string lola_file = filename;
// try to replace .bpel through .lola
if ( lola_file.rfind(".bpel", 0) >= (lola_file.length() - 6) )
{
lola_file = lola_file.replace( (lola_file.length() - 5), 5, ".lola");
}
else
{
lola_file += ".dot";
}
/// set dot filename
lola_filename = lola_file.c_str();
/// create dot file and point to it
lola_output = new std::ofstream(lola_file.c_str(), std::ofstream::out | std::ofstream::trunc);
}
}
// trace information about current mode
trace(TRACE_INFORMATION, "\nModus operandi:\n");
if (mode_simplify_petri_net)
{
trace(TRACE_INFORMATION, " - create structural simlified Petri Net\n");
}
else if (mode_petri_net)
{
trace(TRACE_INFORMATION, " - create Petri Net\n");
}
if (mode_low_level_petri_net)
{
trace(TRACE_INFORMATION, " --> abstract to low level\n");
}
if (mode_lola_2_file)
{
trace(TRACE_INFORMATION, " - output LoLA input of the Petri Net to file " + lola_filename + "\n");
}
else if (mode_lola_petri_net)
{
trace(TRACE_INFORMATION, " - output LoLA input of the Petri Net\n");
}
if (mode_dot_2_file)
{
trace(TRACE_INFORMATION, " - output dot representation of the Petri Net to file " + dot_filename + "\n");
}
else if (mode_dot_petri_net)
{
trace(TRACE_INFORMATION, " - output dot representation of the Petri Net\n");
}
if (mode_pretty_printer)
{
trace(TRACE_INFORMATION, " - output \"pretty\" XML\n");
}
if (mode_ast)
{
trace(TRACE_INFORMATION, " - output AST\n");
}
trace(TRACE_INFORMATION, "\n");
// don't show debug messages from flex and Bison, unless special debug mode is requested
if (debug_level == -1)
{
yydebug = 1;
yy_flex_debug = 1;
}
else
{
yydebug = 0;
yy_flex_debug = 0;
}
}
/**
* Some output in case an error has occured.
*
*/
void error()
{
trace("\nAn error has occured!\n\n");
cleanup();
trace(TRACE_WARNINGS, "-> Any output file might be in an undefinded state.\n");
exit(1);
}
/**
* Some output in case an error has occured.
* Prints out the exception's information.
*
* \param e The exception that triggered this function call.
*
*/
void error(Exception e)
{
e.info();
cleanup();
trace(TRACE_WARNINGS, "-> Any output file might be in an undefinded state.\n");
exit(e.id);
}
/**
* Cleans up.
* Afterwards we should have an almost defined state.
*
*/
void cleanup()
{
trace(TRACE_INFORMATION,"Cleaning up ...\n");
if (filename != "")
{
trace(TRACE_INFORMATION," + Closing input file: " + filename + "\n");
fclose(yyin);
}
if (lola_filename != "")
{
trace(TRACE_INFORMATION," + Closing LoLA output file: " + lola_filename + "\n");
(*lola_output) << std::flush;
((std::ofstream*)lola_output)->close();
}
if (dot_filename != "")
{
trace(TRACE_INFORMATION," + Closing dot output file: " + dot_filename + "\n");
(*dot_output) << std::flush;
((std::ofstream*)dot_output)->close();
}
if (mode_petri_net)
{
trace(TRACE_INFORMATION," + Deleting Petri Net pointer\n");
delete(TheNet);
TheNet = NULL;
}
}
<commit_msg>Added flags to switch debug mode for flex and bison.<commit_after>/*!
* \file helpers.cc
*
* \brief Helper functions (implementation)
*
* This file implements several small helper functions that do not belong to
* any other file.
*
* \author
* - responsible: Niels Lohmann <nlohmann@informatik.hu-berlin.de>
* - last changes of: \$Author: gierds $
*
* \date
* - created: 2005/11/11
* - last changed: \$Date: 2005/11/16 10:49:16 $
*
* \note This file is part of the tool BPEL2oWFN and was created during the
* project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See
* http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
* for details.
*
* \version \$Revision: 1.10 $
* - 2005-11-11 (nlohmann) Initial version.
* - 2005-11-15 (gierds) Moved commandline evaluation functions from main.cc to here.
* Added LoLA command line arguments.
* - 2005-11-16 (gierds) Added error() and cleanup() functions.
* Added extra command line parameters to debug flex and bison.
*/
#include "helpers.h"
/// The Petri Net
extern PetriNet *TheNet;
/*!
* \param a set of Petri net nodes
* \param b set of Petri net nodes
* \return union of the sets a and b
*/
set<Node *> setUnion(set<Node *> a, set<Node *> b)
{
set<Node *> result;
insert_iterator<set<Node *, less<Node *> > > res_ins(result, result.begin());
set_union(a.begin(), a.end(), b.begin(), b.end(), res_ins);
return result;
}
/*!
* \param i standard C int
* \return C++ string representing i
*/
string intToString(int i)
{
char buffer[20];
sprintf(buffer, "%d", i);
return string(buffer);
}
// --------------------- functions for command line evaluation --------------------------------
void print_help()
{
// 80 chars
// "--------------------------------------------------------------------------------"
trace("\n");
trace("BPEL2oWFN\n");
trace("---------\n");
trace("Options: \n");
trace(" -f | --file <filename> - read input from <filename>,\n");
trace(" if this parameter is omitted, input is read from\n");
trace(" STDIN\n");
trace(" -d | -dd | -ddd | -dddd | - set debug level\n");
trace(" --debug [1..4] ... some more information soon\n");
trace(" -df | --debug-flex - enable flex' debug mode\n");
trace(" -dy | --debug-yacc - enable yacc's/bison's debug mode\n");
trace(" -h | --help - print this screen\n");
trace("\n");
trace("\n");
trace("output modes (choose at maximum one, default is just parsing):\n");
trace("\n");
trace(" -a | --ast - output the AST\n");
trace(" -x | --xml - output simple XML w/o any unnecessary\n");
trace(" informtion\n");
trace(" -pn | --petri-net - output the Petri Net (in LoLA style?)\n");
trace("\n");
trace("special Petri Net modes:\n");
trace("\n");
trace(" -s | --simplify - outpus a structural simplified Petri Net\n");
trace(" (implies option -pn)\n");
trace(" -ll | --low-level - generate an abstract low level Petri Net\n");
trace(" (see manual for further information)\n");
trace(" (implies option -pn)\n");
trace(" -L | --lola - output LoLA input,\n");
trace(" should not used together with -D\n");
trace(" (implies option -pn)\n");
trace(" -L2F | --lola2file - output LoLA input into file (same name as\n");
trace(" input file\n");
trace(" (implies option -L)\n");
trace(" -D | --dot - output dot input\n");
trace(" (implies option -pn)\n");
trace(" -D2F | --dot2file - output dot input into file (same name as\n");
trace(" input file\n");
trace(" (implies option -D)\n");
trace("\n");
trace("For more information see:\n");
trace(" http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel/\n");
trace("\n");
}
void parse_command_line(int argc, char* argv[])
{
yydebug = 0;
yy_flex_debug = 0;
if (argc > 1)
{
int argument_counter = 1;
while (argument_counter < argc)
{
char * argument_string = argv[argument_counter++];
// check for input other than stdin
if (! strcmp(argument_string, "-f") || ! strcmp(argument_string, "--file"))
{
if (argument_counter < argc)
{
filename = (std::string) argv[argument_counter++];
if (!(yyin = fopen(filename.c_str(), "r")))
{
throw Exception(FILE_NOT_FOUND, "File '" + filename + "' not found.\n");
// fprintf(stderr, " File '%s' not found.\n", filename);
trace(" File '");
trace(filename);
trace("' not found.\n");
exit(2);
}
}
else
{
print_help();
exit(1);
}
}
// select output, default is just parsing
else if (! strcmp(argument_string, "-pn") || ! strcmp(argument_string, "--petri-net")) {
// output a Petri Net
mode_petri_net = true;
}
else if (! strcmp(argument_string, "-x") || ! strcmp(argument_string, "--xml")) {
// output a pretty xml
mode_pretty_printer = true;
}
else if (! strcmp(argument_string, "-a") || ! strcmp(argument_string, "--ast")) {
// output the AST, but why anyone should want to?
mode_ast = true;
}
// simplyfy?
else if (! strcmp(argument_string, "-s") || ! strcmp(argument_string, "--simplify"))
{
mode_simplify_petri_net = true;
mode_petri_net = true;
}
// low level?
else if (! strcmp(argument_string, "-ll") || ! strcmp(argument_string, "--low-level"))
{
mode_low_level_petri_net = true;
mode_petri_net = true;
}
// generate lola output
else if (! strcmp(argument_string, "-L") || ! strcmp(argument_string, "--lola"))
{
mode_lola_petri_net = true;
mode_petri_net = true;
}
// generate lola output and write it into a file
else if (! strcmp(argument_string, "-L2F") || ! strcmp(argument_string, "--lola2file"))
{
mode_lola_petri_net = true;
mode_lola_2_file = true;
mode_petri_net = true;
}
// generate dot output
else if (! strcmp(argument_string, "-D") || ! strcmp(argument_string, "--dot"))
{
mode_dot_petri_net = true;
mode_petri_net = true;
}
// generate dot output and write it into a file
else if (! strcmp(argument_string, "-D2F") || ! strcmp(argument_string, "--dot2file"))
{
mode_dot_petri_net = true;
mode_dot_2_file = true;
mode_petri_net = true;
}
// debug
else if (! strcmp(argument_string, "-d"))
{
debug_level = TRACE_WARNINGS;
}
else if (! strcmp(argument_string, "-dd"))
{
debug_level = TRACE_INFORMATION;
}
else if (! strcmp(argument_string, "-ddd"))
{
debug_level = TRACE_DEBUG;
}
else if (! strcmp(argument_string, "-dddd"))
{
debug_level = TRACE_VERY_DEBUG;
}
else if (! strcmp(argument_string, "--debug"))
{
if (argument_counter < argc)
{
argument_string = argv[argument_counter++];
// instead of atoi we may use the stringstream class?
debug_level = atoi(argument_string);
if (debug_level < 1 || debug_level > 4) {
print_help();
exit(1);
}
}
else
{
print_help();
exit(1);
}
}
// debug flex
else if (! strcmp(argument_string, "-df") || ! strcmp(argument_string, "--debug-flex"))
{
yy_flex_debug = 1;
}
// debug yacc/bison
else if (! strcmp(argument_string, "-dy") || ! strcmp(argument_string, "--debug-yacc"))
{
yydebug = 1;
}
// help
else if (! strcmp(argument_string, "-h") || ! strcmp(argument_string, "-?") || ! strcmp(argument_string, "--help"))
{
print_help();
exit(1);
}
// unknown parameter
else
{
trace("Unknown option: " + ((std::string) argument_string) + "\n");
print_help();
exit(1);
}
}
// take care of the output modes
if ((mode_petri_net && mode_ast) || (mode_petri_net && mode_pretty_printer) || (mode_ast && mode_pretty_printer))
{
print_help();
exit(1);
}
}
// trace and check for some files to be created
if ( filename != "")
{
trace(TRACE_INFORMATION, "Reading BPEL from file ");
trace(TRACE_INFORMATION, (filename));
trace(TRACE_INFORMATION, "\n");
// if wanted, create a dot output file
if ( mode_dot_2_file )
{
trace(TRACE_INFORMATION, "Creating file for dot output\n");
std::string dotti_file = filename;
// try to replace .bpel through .dot
if ( dotti_file.rfind(".bpel", 0) >= (dotti_file.length() - 6) )
{
dotti_file = dotti_file.replace( (dotti_file.length() - 5), 5, ".dot");
}
else
{
dotti_file += ".dot";
}
/// set dot filename
dot_filename = dotti_file.c_str();
/// create dot file and point to it
dot_output = new std::ofstream(dotti_file.c_str(), std::ofstream::out | std::ofstream::trunc);
}
// if wanted, create a LoLA output file
if ( mode_lola_2_file )
{
trace(TRACE_INFORMATION, "Creating file for lola output\n");
std::string lola_file = filename;
// try to replace .bpel through .lola
if ( lola_file.rfind(".bpel", 0) >= (lola_file.length() - 6) )
{
lola_file = lola_file.replace( (lola_file.length() - 5), 5, ".lola");
}
else
{
lola_file += ".dot";
}
/// set dot filename
lola_filename = lola_file.c_str();
/// create dot file and point to it
lola_output = new std::ofstream(lola_file.c_str(), std::ofstream::out | std::ofstream::trunc);
}
}
// trace information about current mode
trace(TRACE_INFORMATION, "\nModus operandi:\n");
if (mode_simplify_petri_net)
{
trace(TRACE_INFORMATION, " - create structural simlified Petri Net\n");
}
else if (mode_petri_net)
{
trace(TRACE_INFORMATION, " - create Petri Net\n");
}
if (mode_low_level_petri_net)
{
trace(TRACE_INFORMATION, " --> abstract to low level\n");
}
if (mode_lola_2_file)
{
trace(TRACE_INFORMATION, " - output LoLA input of the Petri Net to file " + lola_filename + "\n");
}
else if (mode_lola_petri_net)
{
trace(TRACE_INFORMATION, " - output LoLA input of the Petri Net\n");
}
if (mode_dot_2_file)
{
trace(TRACE_INFORMATION, " - output dot representation of the Petri Net to file " + dot_filename + "\n");
}
else if (mode_dot_petri_net)
{
trace(TRACE_INFORMATION, " - output dot representation of the Petri Net\n");
}
if (mode_pretty_printer)
{
trace(TRACE_INFORMATION, " - output \"pretty\" XML\n");
}
if (mode_ast)
{
trace(TRACE_INFORMATION, " - output AST\n");
}
if (debug_level > 0)
{
trace(TRACE_INFORMATION, " - debug level is set to " + intToString(debug_level) + "\n");
}
if (yy_flex_debug > 0)
{
trace(TRACE_INFORMATION, " - special debug mode for flex is enabled\n");
}
if (yydebug > 0)
{
trace(TRACE_INFORMATION, " - special debug mode for yacc/bison is enabled\n");
}
trace(TRACE_INFORMATION, "\n");
}
/**
* Some output in case an error has occured.
*
*/
void error()
{
trace("\nAn error has occured!\n\n");
cleanup();
trace(TRACE_WARNINGS, "-> Any output file might be in an undefinded state.\n");
exit(1);
}
/**
* Some output in case an error has occured.
* Prints out the exception's information.
*
* \param e The exception that triggered this function call.
*
*/
void error(Exception e)
{
e.info();
cleanup();
trace(TRACE_WARNINGS, "-> Any output file might be in an undefinded state.\n");
exit(e.id);
}
/**
* Cleans up.
* Afterwards we should have an almost defined state.
*
*/
void cleanup()
{
trace(TRACE_INFORMATION,"Cleaning up ...\n");
if (filename != "")
{
trace(TRACE_INFORMATION," + Closing input file: " + filename + "\n");
fclose(yyin);
}
if (lola_filename != "")
{
trace(TRACE_INFORMATION," + Closing LoLA output file: " + lola_filename + "\n");
(*lola_output) << std::flush;
((std::ofstream*)lola_output)->close();
}
if (dot_filename != "")
{
trace(TRACE_INFORMATION," + Closing dot output file: " + dot_filename + "\n");
(*dot_output) << std::flush;
((std::ofstream*)dot_output)->close();
}
if (mode_petri_net)
{
trace(TRACE_INFORMATION," + Deleting Petri Net pointer\n");
delete(TheNet);
TheNet = NULL;
}
}
<|endoftext|> |
<commit_before>/*
* The StockMap class is a hash table of any number of Stock objects,
* each with a different URI.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "hstock.hxx"
#include "stock.hxx"
#include "hashmap.hxx"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
struct StockMap {
struct pool &pool;
const StockClass &cls;
void *const class_ctx;
/**
* The maximum number of items in each stock.
*/
const unsigned limit;
/**
* The maximum number of permanent idle items in each stock.
*/
const unsigned max_idle;
struct hashmap &stocks;
StockMap(struct pool &_pool, const StockClass &_cls, void *_class_ctx,
unsigned _limit, unsigned _max_idle)
:pool(*pool_new_libc(&_pool, "hstock")),
cls(_cls), class_ctx(_class_ctx),
limit(_limit), max_idle(_max_idle),
stocks(*hashmap_new(&pool, 64)) {}
~StockMap() {
hashmap_rewind(&stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&stocks)) != nullptr) {
Stock *stock = (Stock *)pair->value;
stock_free(stock);
}
}
void Destroy() {
DeleteUnrefPool(pool, this);
}
};
/*
* stock handler
*
*/
static void
hstock_stock_empty(Stock &stock, const char *uri, void *ctx)
{
StockMap *hstock = (StockMap *)ctx;
daemon_log(5, "hstock(%p) remove empty stock(%p, '%s')\n",
(const void *)hstock, (const void *)&stock, uri);
hashmap_remove_existing(&hstock->stocks, uri, &stock);
stock_free(&stock);
}
static constexpr StockHandler hstock_stock_handler = {
.empty = hstock_stock_empty,
};
StockMap *
hstock_new(struct pool &pool, const StockClass &cls, void *class_ctx,
unsigned limit, unsigned max_idle)
{
assert(cls.item_size > sizeof(StockItem));
assert(cls.create != nullptr);
assert(cls.borrow != nullptr);
assert(cls.release != nullptr);
assert(cls.destroy != nullptr);
assert(max_idle > 0);
return NewFromPool<StockMap>(pool, pool, cls, class_ctx,
limit, max_idle);
}
void
hstock_free(StockMap *hstock)
{
hstock->Destroy();
}
void
hstock_fade_all(StockMap &hstock)
{
hashmap_rewind(&hstock.stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&hstock.stocks)) != nullptr) {
Stock &stock = *(Stock *)pair->value;
stock_fade_all(stock);
}
}
void
hstock_add_stats(const StockMap &stock, StockStats &data)
{
struct hashmap *h = &stock.stocks;
hashmap_rewind(h);
const struct hashmap_pair *p;
while ((p = hashmap_next(h)) != nullptr) {
const Stock &s = *(const Stock *)p->value;
stock_add_stats(s, data);
}
}
static Stock &
hstock_get_stock(StockMap &hstock, const char *uri)
{
Stock *stock = (Stock *)hashmap_get(&hstock.stocks, uri);
if (stock == nullptr) {
stock = stock_new(hstock.pool, hstock.cls, hstock.class_ctx,
uri, hstock.limit, hstock.max_idle,
hstock_stock_handler, &hstock);
hashmap_set(&hstock.stocks, stock_get_uri(*stock), stock);
}
return *stock;
}
void
hstock_get(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
const StockGetHandler &handler, void *handler_ctx,
struct async_operation_ref &async_ref)
{
auto &stock = hstock_get_stock(hstock, uri);
stock_get(stock, pool, info, handler, handler_ctx, async_ref);
}
StockItem *
hstock_get_now(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
GError **error_r)
{
Stock &stock = hstock_get_stock(hstock, uri);
return stock_get_now(stock, pool, info, error_r);
}
void
hstock_put(gcc_unused StockMap &hstock, gcc_unused const char *uri,
StockItem &object, bool destroy)
{
#ifndef NDEBUG
Stock *stock = (Stock *)hashmap_get(&hstock.stocks, uri);
assert(stock != nullptr);
assert(stock == object.stock);
#endif
stock_put(object, destroy);
}
<commit_msg>hstock: move code to methods<commit_after>/*
* The StockMap class is a hash table of any number of Stock objects,
* each with a different URI.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "hstock.hxx"
#include "stock.hxx"
#include "hashmap.hxx"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
struct StockMap {
struct pool &pool;
const StockClass &cls;
void *const class_ctx;
/**
* The maximum number of items in each stock.
*/
const unsigned limit;
/**
* The maximum number of permanent idle items in each stock.
*/
const unsigned max_idle;
struct hashmap &stocks;
StockMap(struct pool &_pool, const StockClass &_cls, void *_class_ctx,
unsigned _limit, unsigned _max_idle)
:pool(*pool_new_libc(&_pool, "hstock")),
cls(_cls), class_ctx(_class_ctx),
limit(_limit), max_idle(_max_idle),
stocks(*hashmap_new(&pool, 64)) {}
~StockMap() {
hashmap_rewind(&stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&stocks)) != nullptr) {
Stock *stock = (Stock *)pair->value;
stock_free(stock);
}
}
void Destroy() {
DeleteUnrefPool(pool, this);
}
void Erase(Stock &stock, const char *uri) {
hashmap_remove_existing(&stocks, uri, &stock);
stock_free(&stock);
}
void FadeAll() {
hashmap_rewind(&stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&stocks)) != nullptr) {
Stock &stock = *(Stock *)pair->value;
stock_fade_all(stock);
}
}
void AddStats(StockStats &data) const {
hashmap_rewind(&stocks);
const struct hashmap_pair *p;
while ((p = hashmap_next(&stocks)) != nullptr) {
const Stock &s = *(const Stock *)p->value;
stock_add_stats(s, data);
}
}
Stock &GetStock(const char *uri);
void Get(struct pool &caller_pool,
const char *uri, void *info,
const StockGetHandler &handler, void *handler_ctx,
struct async_operation_ref &async_ref) {
Stock &stock = GetStock(uri);
stock_get(stock, caller_pool, info, handler, handler_ctx, async_ref);
}
StockItem *GetNow(struct pool &caller_pool, const char *uri, void *info,
GError **error_r) {
Stock &stock = GetStock(uri);
return stock_get_now(stock, caller_pool, info, error_r);
}
void Put(gcc_unused const char *uri, StockItem &object, bool destroy) {
#ifndef NDEBUG
Stock *stock = (Stock *)hashmap_get(&stocks, uri);
assert(stock != nullptr);
assert(stock == object.stock);
#endif
stock_put(object, destroy);
}
};
/*
* stock handler
*
*/
static void
hstock_stock_empty(Stock &stock, const char *uri, void *ctx)
{
StockMap *hstock = (StockMap *)ctx;
daemon_log(5, "hstock(%p) remove empty stock(%p, '%s')\n",
(const void *)hstock, (const void *)&stock, uri);
hstock->Erase(stock, uri);
}
static constexpr StockHandler hstock_stock_handler = {
.empty = hstock_stock_empty,
};
StockMap *
hstock_new(struct pool &pool, const StockClass &cls, void *class_ctx,
unsigned limit, unsigned max_idle)
{
assert(cls.item_size > sizeof(StockItem));
assert(cls.create != nullptr);
assert(cls.borrow != nullptr);
assert(cls.release != nullptr);
assert(cls.destroy != nullptr);
assert(max_idle > 0);
return NewFromPool<StockMap>(pool, pool, cls, class_ctx,
limit, max_idle);
}
void
hstock_free(StockMap *hstock)
{
hstock->Destroy();
}
void
hstock_fade_all(StockMap &hstock)
{
hstock.FadeAll();
}
void
hstock_add_stats(const StockMap &stock, StockStats &data)
{
stock.AddStats(data);
}
inline Stock &
StockMap::GetStock(const char *uri)
{
Stock *stock = (Stock *)hashmap_get(&stocks, uri);
if (stock == nullptr) {
stock = stock_new(pool, cls, class_ctx,
uri, limit, max_idle,
hstock_stock_handler, this);
hashmap_set(&stocks, stock_get_uri(*stock), stock);
}
return *stock;
}
void
hstock_get(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
const StockGetHandler &handler, void *handler_ctx,
struct async_operation_ref &async_ref)
{
return hstock.Get(pool, uri, info,
handler, handler_ctx, async_ref);
}
StockItem *
hstock_get_now(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
GError **error_r)
{
return hstock.GetNow(pool, uri, info, error_r);
}
void
hstock_put(StockMap &hstock, const char *uri, StockItem &object, bool destroy)
{
hstock.Put(uri, object, destroy);
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/chip/CMSIS-proxy.h"
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
// weak definition of lowLevelInitialization0() called at the very beginning of Reset_Handler()
__attribute__ ((weak)) void lowLevelInitialization0()
{
}
/**
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*/
__attribute__ ((naked)) void Reset_Handler()
{
asm volatile
(
R"(
ldr r4, =__low_level_preinitializers_start // execute low-level preinitializers
ldr r5, =__low_level_preinitializers_end
1: cmp r4, r5
bhs 2f
ldmia r4!, {r0}
blx r0
b 1b
2:
ldr r0, =%[lowLevelInitialization0] // call lowLevelInitialization0() (PSP not set,
blx r0 // CONTROL not modified, memory not initialized)
ldr r0, =__process_stack_end // initialize PSP
msr psp, r0
movs r0, %[controlSpselMsk] // thread mode uses PSP and is privileged
msr control, r0
isb
ldr r4, =__data_initializers_start // initialize data_initializers (including .data)
ldr r5, =__data_initializers_end
)"
#ifdef __ARM_ARCH_6M__
R"(
1: cmp r4, r5 // outer loop - addresses from data_initializers
bhs 4f
ldmia r4!, {r1-r3} // r1 - start of source, r2 - start of destination,
// r3 - end of destination
b 3f
2: ldmia r1!, {r0} // inner loop - section initialization
stmia r2!, {r0}
3: cmp r2, r3
bne 2b
b 1b // go back to start
4:
)"
#else // !def __ARM_ARCH_6M__
R"(
1: cmp r4, r5 // outer loop - addresses from data_initializers
ite lo
ldmialo r4!, {r1-r3} // r1 - start of source, r2 - start of destination,
bhs 3f // r3 - end of destination
2: cmp r2, r3 // inner loop - section initialization
ittt lo
ldrlo r0, [r1], #4
strlo r0, [r2], #4
blo 2b
b 1b // go back to start
3:
)"
#endif // !def __ARM_ARCH_6M__
R"(
ldr r3, =__bss_initializers_start // initialize bss_initializers (including .bss)
ldr r4, =__bss_initializers_end
)"
#ifdef __ARM_ARCH_6M__
R"(
1: cmp r3, r4 // outer loop - addresses from bss_initializers
bhs 4f
ldmia r3!, {r0-r2} // r0 - value, r1 - start of destination, r2 - end
// of destination
b 3f
2: stmia r1!, {r0} // inner loop - section initialization
3: cmp r1, r2
bne 2b
b 1b // go back to start
4:
)"
#else // !def __ARM_ARCH_6M__
R"(
1: cmp r3, r4 // outer loop - addresses from bss_initializers
ite lo
ldmialo r3!, {r0-r2} // r0 - value, r1 - start of destination, r2 - end
bhs 3f // of destination
2: cmp r1, r2 // inner loop - section initialization
itt lo
strlo r0, [r1], #4
blo 2b
b 1b // go back to start
3:
)"
#endif // !def __ARM_ARCH_6M__
R"(
ldr r4, =__low_level_initializers_start // execute low-level initializers
ldr r5, =__low_level_initializers_end
1: cmp r4, r5
bhs 2f
ldmia r4!, {r0}
blx r0
b 1b
2:
ldr r0, =__libc_init_array // call constructors for global and static objects
blx r0
ldr r0, =main // call main()
blx r0
)"
#if CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
R"(
ldr r0, =__libc_fini_array // call destructors for global and static objects
blx r0
)"
#endif // CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
R"(
b . // on return - loop till the end of the world
.ltorg // force dumping of literal pool
)"
:: [controlSpselMsk] "i" (CONTROL_SPSEL_Msk),
[lowLevelInitialization0] "i" (lowLevelInitialization0)
);
__builtin_unreachable();
}
} // extern "C"
<commit_msg>Remove lowLevelInitialization0() call from Reset_Handler()<commit_after>/**
* \file
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/chip/CMSIS-proxy.h"
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*/
__attribute__ ((naked)) void Reset_Handler()
{
asm volatile
(
R"(
ldr r4, =__low_level_preinitializers_start // execute low-level preinitializers
ldr r5, =__low_level_preinitializers_end
1: cmp r4, r5
bhs 2f
ldmia r4!, {r0}
blx r0
b 1b
2:
ldr r0, =__process_stack_end // initialize PSP
msr psp, r0
movs r0, %[controlSpselMsk] // thread mode uses PSP and is privileged
msr control, r0
isb
ldr r4, =__data_initializers_start // initialize data_initializers (including .data)
ldr r5, =__data_initializers_end
)"
#ifdef __ARM_ARCH_6M__
R"(
1: cmp r4, r5 // outer loop - addresses from data_initializers
bhs 4f
ldmia r4!, {r1-r3} // r1 - start of source, r2 - start of destination,
// r3 - end of destination
b 3f
2: ldmia r1!, {r0} // inner loop - section initialization
stmia r2!, {r0}
3: cmp r2, r3
bne 2b
b 1b // go back to start
4:
)"
#else // !def __ARM_ARCH_6M__
R"(
1: cmp r4, r5 // outer loop - addresses from data_initializers
ite lo
ldmialo r4!, {r1-r3} // r1 - start of source, r2 - start of destination,
bhs 3f // r3 - end of destination
2: cmp r2, r3 // inner loop - section initialization
ittt lo
ldrlo r0, [r1], #4
strlo r0, [r2], #4
blo 2b
b 1b // go back to start
3:
)"
#endif // !def __ARM_ARCH_6M__
R"(
ldr r3, =__bss_initializers_start // initialize bss_initializers (including .bss)
ldr r4, =__bss_initializers_end
)"
#ifdef __ARM_ARCH_6M__
R"(
1: cmp r3, r4 // outer loop - addresses from bss_initializers
bhs 4f
ldmia r3!, {r0-r2} // r0 - value, r1 - start of destination, r2 - end
// of destination
b 3f
2: stmia r1!, {r0} // inner loop - section initialization
3: cmp r1, r2
bne 2b
b 1b // go back to start
4:
)"
#else // !def __ARM_ARCH_6M__
R"(
1: cmp r3, r4 // outer loop - addresses from bss_initializers
ite lo
ldmialo r3!, {r0-r2} // r0 - value, r1 - start of destination, r2 - end
bhs 3f // of destination
2: cmp r1, r2 // inner loop - section initialization
itt lo
strlo r0, [r1], #4
blo 2b
b 1b // go back to start
3:
)"
#endif // !def __ARM_ARCH_6M__
R"(
ldr r4, =__low_level_initializers_start // execute low-level initializers
ldr r5, =__low_level_initializers_end
1: cmp r4, r5
bhs 2f
ldmia r4!, {r0}
blx r0
b 1b
2:
ldr r0, =__libc_init_array // call constructors for global and static objects
blx r0
ldr r0, =main // call main()
blx r0
)"
#if CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
R"(
ldr r0, =__libc_fini_array // call destructors for global and static objects
blx r0
)"
#endif // CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
R"(
b . // on return - loop till the end of the world
.ltorg // force dumping of literal pool
)"
:: [controlSpselMsk] "i" (CONTROL_SPSEL_Msk)
);
__builtin_unreachable();
}
} // extern "C"
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <list>
#include <iomanip>
#include "common.h"
#include "Timer.h"
#include "Replay.h"
#include "Field.h"
extern bool playReplay;
extern int gameState;
extern Timer timer;
extern string playerName;
extern int squareSize;
extern Field field;
ReplayPoint::ReplayPoint() {}
ReplayPoint::ReplayPoint(int px, int py, int pb, long pp) {
x=px;
y=py;
button=pb;
timeSinceStart=pp;
}
void ReplayPoint::dump() {
cout <<setw(7)<<timeSinceStart<<setw(7) <<x<<setw(7)<<y<<setw(7)<<button<< endl;
}
void mouseClick(int,int,int,int);
Replay::Replay() {
recording=false;
endOfReplay=false;
}
bool Replay::isRecording() {
return recording;
}
void Replay::startRecording() {
if (!playReplay) recording=true;
}
void Replay::pauseRecording() {
if (!playReplay) recording=false;
}
void Replay::resumeRecording() {
if (!playReplay) recording=true;
}
void Replay::stopRecording() {
if (!playReplay) recording=false;
}
void Replay::deleteData() {
if (!playReplay) data.clear();
}
void Replay::recordEvent(int x, int y, int button) {
if (recording) {
// cout << "Recording event " << x << " " << y << " " << button << "." << endl;
// data.push_back(*(new ReplayPoint(x,y,button,(gameState==GAME_INITIALIZED ? 0 : timer.calculateTimeSinceStart()))));
data.push_back(*(new ReplayPoint(x,y,button,(gameState==GAME_INITIALIZED ? 0 : timer.calculateElapsedTime()))));
}
}
void Replay::writeToFile(ofstream *file) {
*file << "miny-replay-file-version: 1" << endl;
*file << playerName << endl << squareSize << endl;
*file << field.width << " " << field.height << endl;
for (int j=0;j<field.height;j++) {
for (int i=0;i<field.width;i++)
*file << field.isMine(i,j) << " ";
*file << endl;
}
*file << endl;
*file << data.size() << endl;
std::list<ReplayPoint>::iterator iter;
for (iter=data.begin(); iter!=data.end(); iter++) {
*file << (*iter).timeSinceStart << " " << (*iter).x << " " << (*iter).y << " " << (*iter).button << endl;
}
}
void Replay::readFromFile(ifstream *ifile) {
string firstString;
*ifile >> firstString;
int fileVersion;
if (firstString=="miny-replay-file-version:") {
*ifile >> fileVersion;
}
else {
fileVersion=-1;
}
switch(fileVersion) {
case -1:
cout << "Unknown replay file format. Exiting." << endl;
exit(1);
case 1:
*ifile >> playerName;
*ifile >> squareSize;
*ifile >> field.width >> field.height;
cout << "Reading mines."<<endl;
bool tmpmine;
for (int j=0;j<field.height;j++)
for (int i=0;i<field.width;i++) {
*ifile >> tmpmine;
if (tmpmine) field.setMine(i,j);
}
int count;
*ifile>>count;
cout << "Reading " << count << " events." << endl;
ReplayPoint *rp;
for (int i=0;i<count;i++) {
rp=new ReplayPoint();
*ifile >> rp->timeSinceStart >> rp->x >> rp->y >> rp->button;
data.push_back(*rp);
// cout << ".";
}
// cout << endl;
// cout << "Loaded " << data.size() << " events."<<endl;
/* while (!ifile.eof()) {
ifile >> scores[*count].name >> scores[*count].time >> scores[*count].timeStamp;
(*count)++;
if ((*count)==MAX_HS) break;
}
if (ifile.eof())
(*count)--;*/
nextPlayed=data.begin();
break;
default:
cout << "Unknown replay file version. You are probably running an old version of the"<<endl<<"game. Please upgrade to the latest version." << endl;
exit(1);
}
}
void Replay::dump() {
cout << "Dumping replay data."<<endl;
// std::mem_fun(&ReplayPoint::dump)
// std::for_each( data.begin(), data.end(), std::mem_fun(&ReplayPoint::dump));
std::list<ReplayPoint>::iterator iter;
for (iter=data.begin(); iter!=data.end(); iter++) {
(*iter).dump();
}
}
unsigned int Replay::playStep() {
// cout << "Playing step."<<endl;
cursorX=(*nextPlayed).x;
cursorY=(*nextPlayed).y;
if ((*nextPlayed).button!=-1) {
mouseClick((*nextPlayed).button,GLUT_DOWN,(*nextPlayed).x,(*nextPlayed).y);
}
std::list<ReplayPoint>::iterator next;
next=nextPlayed;
next++;
if (next==data.end()) {
return -1;
}
else {
int ret=(*(next)).timeSinceStart-timer.calculateTimeSinceStart();//-(*nextPlayed).timeSinceStart;
if (ret<0) ret=0;
nextPlayed=next;
return ret;
}
}
<commit_msg>Update Replay.cpp<commit_after>#include <iostream>
#include <fstream>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <list>
#include <iomanip>
#include "common.h"
#include "Timer.h"
#include "Replay.h"
#include "Field.h"
extern bool playReplay;
extern int gameState;
extern Timer timer;
extern string playerName;
extern int squareSize;
extern Field field;
ReplayPoint::ReplayPoint() {}
ReplayPoint::ReplayPoint(int px, int py, int pb, long pp) {
x=px;
y=py;
button=pb;
timeSinceStart=pp;
}
void ReplayPoint::dump() {
cout <<setw(7)<<timeSinceStart<<setw(7) <<x<<setw(7)<<y<<setw(7)<<button<< endl;
}
void mouseClick(int,int,int,int);
Replay::Replay() {
recording=false;
endOfReplay=false;
}
bool Replay::isRecording() {
return recording;
}
void Replay::startRecording() {
if (!playReplay) recording=true;
}
void Replay::pauseRecording() {
if (!playReplay) recording=false;
}
void Replay::resumeRecording() {
if (!playReplay) recording=true;
}
void Replay::stopRecording() {
if (!playReplay) recording=false;
}
void Replay::deleteData() {
if (!playReplay) data.clear();
}
void Replay::recordEvent(int x, int y, int button) {
if (recording) {
// cout << "Recording event " << x << " " << y << " " << button << "." << endl;
// data.push_back(*(new ReplayPoint(x,y,button,(gameState==GAME_INITIALIZED ? 0 : timer.calculateTimeSinceStart()))));
data.push_back(*(new ReplayPoint(x,y,button,(gameState==GAME_INITIALIZED ? 0 : timer.calculateElapsedTime()))));
}
}
void Replay::writeToFile(ofstream *file) {
*file << "miny-replay-file-version: 1" << endl;
*file << playerName << endl << squareSize << endl;
*file << field.width << " " << field.height << endl;
for (int j=0;j<field.height;j++) {
for (int i=0;i<field.width;i++)
*file << field.isMine(i,j) << " ";
*file << endl;
}
*file << endl;
*file << data.size() << endl;
std::list<ReplayPoint>::iterator iter;
for (iter=data.begin(); iter!=data.end(); iter++) {
*file << (*iter).timeSinceStart << " " << (*iter).x << " " << (*iter).y << " " << (*iter).button << endl;
}
}
void Replay::readFromFile(ifstream *ifile) {
string firstString;
*ifile >> firstString;
int fileVersion;
if (firstString=="miny-replay-file-version:") {
*ifile >> fileVersion;
}
else {
fileVersion=-1;
}
switch(fileVersion) {
case -1:
cout << "Unknown replay file format. Exiting." << endl;
exit(1);
case 1: {
*ifile >> playerName;
*ifile >> squareSize;
*ifile >> field.width >> field.height;
cout << "Reading mines."<<endl;
int mineCount=0;
bool tmpmine;
for (int j=0;j<field.height;j++)
for (int i=0;i<field.width;i++) {
*ifile >> tmpmine;
if (tmpmine) {
field.setMine(i,j);
mineCount++;
}
}
field.mineCount=mineCount;
int count;
*ifile>>count;
cout << "Reading " << count << " events." << endl;
ReplayPoint *rp;
for (int i=0;i<count;i++) {
rp=new ReplayPoint();
*ifile >> rp->timeSinceStart >> rp->x >> rp->y >> rp->button;
data.push_back(*rp);
// cout << ".";
}
// cout << endl;
// cout << "Loaded " << data.size() << " events."<<endl;
/* while (!ifile.eof()) {
ifile >> scores[*count].name >> scores[*count].time >> scores[*count].timeStamp;
(*count)++;
if ((*count)==MAX_HS) break;
}
if (ifile.eof())
(*count)--;*/
nextPlayed=data.begin();
break;
}
default:
cout << "Unknown replay file version. You are probably running an old version of the"<<endl<<"game. Please upgrade to the latest version." << endl;
exit(1);
}
}
void Replay::dump() {
cout << "Dumping replay data."<<endl;
// std::mem_fun(&ReplayPoint::dump)
// std::for_each( data.begin(), data.end(), std::mem_fun(&ReplayPoint::dump));
std::list<ReplayPoint>::iterator iter;
for (iter=data.begin(); iter!=data.end(); iter++) {
(*iter).dump();
}
}
unsigned int Replay::playStep() {
// cout << "Playing step."<<endl;
cursorX=(*nextPlayed).x;
cursorY=(*nextPlayed).y;
if ((*nextPlayed).button!=-1) {
mouseClick((*nextPlayed).button,GLUT_DOWN,(*nextPlayed).x,(*nextPlayed).y);
}
std::list<ReplayPoint>::iterator next;
next=nextPlayed;
next++;
if (next==data.end()) {
return -1;
}
else {
int ret=(*(next)).timeSinceStart-timer.calculateTimeSinceStart();//-(*nextPlayed).timeSinceStart;
if (ret<0) ret=0;
nextPlayed=next;
return ret;
}
}
<|endoftext|> |
<commit_before><commit_msg>put stuff in cp<commit_after>sjkdhicuha
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "addrman.h"
#include "hash.h"
#include "util.h"
#ifndef WIN32
#include <sys/stat.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/version.hpp>
#include <openssl/rand.h>
using namespace std;
using namespace boost;
unsigned int nWalletDBUpdated;
//
// CDB
//
CDBEnv bitdb;
void CDBEnv::EnvShutdown()
{
if (!fDbEnvInit)
return;
fDbEnvInit = false;
int ret = dbenv.close(0);
if (ret != 0)
LogPrintf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
if (!fMockDb)
DbEnv(0).remove(strPath.c_str(), 0);
}
CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
{
fDbEnvInit = false;
fMockDb = false;
}
CDBEnv::~CDBEnv()
{
EnvShutdown();
}
void CDBEnv::Close()
{
EnvShutdown();
}
bool CDBEnv::Open(boost::filesystem::path pathEnv_)
{
if (fDbEnvInit)
return true;
boost::this_thread::interruption_point();
pathEnv = pathEnv_;
filesystem::path pathDataDir = pathEnv;
strPath = pathDataDir.string();
filesystem::path pathLogDir = pathDataDir / "database";
filesystem::create_directory(pathLogDir);
filesystem::path pathErrorFile = pathDataDir / "db.log";
LogPrintf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (GetBoolArg("-privdb", true))
nEnvFlags |= DB_PRIVATE;
int nDbCache = GetArg("-dbcache", 25);
dbenv.set_lg_dir(pathLogDir.string().c_str());
dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
dbenv.set_lg_bsize(1048576);
dbenv.set_lg_max(10485760);
dbenv.set_lk_max_locks(10000);
dbenv.set_lk_max_objects(10000);
dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
dbenv.set_flags(DB_AUTO_COMMIT, 1);
dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
#ifdef DB_LOG_AUTO_REMOVE
dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
#endif
int ret = dbenv.open(strPath.c_str(),
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
if (ret != 0)
return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
fDbEnvInit = true;
fMockDb = false;
return true;
}
void CDBEnv::MakeMock()
{
if (fDbEnvInit)
throw runtime_error("CDBEnv::MakeMock(): already initialized");
boost::this_thread::interruption_point();
LogPrint("db", "CDBEnv::MakeMock()\n");
dbenv.set_cachesize(1, 0, 1);
dbenv.set_lg_bsize(10485760*4);
dbenv.set_lg_max(10485760);
dbenv.set_lk_max_locks(10000);
dbenv.set_lk_max_objects(10000);
dbenv.set_flags(DB_AUTO_COMMIT, 1);
#ifdef DB_LOG_IN_MEMORY
dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
#endif
int ret = dbenv.open(NULL,
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
fDbEnvInit = true;
fMockDb = true;
}
CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, NULL, 0);
if (result == 0)
return VERIFY_OK;
else if (recoverFunc == NULL)
return RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(*this, strFile);
return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
}
bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
std::vector<CDBEnv::KeyValPair >& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
u_int32_t flags = DB_SALVAGE;
if (fAggressive) flags |= DB_AGGRESSIVE;
stringstream strDump;
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
if (result == DB_VERIFY_BAD)
{
LogPrintf("Error: Salvage found errors, all data may not be recoverable.\n");
if (!fAggressive)
{
LogPrintf("Error: Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD)
{
LogPrintf("ERROR: db salvage failed: %d\n",result);
return false;
}
// Format of bdb dump is ascii lines:
// header lines...
// HEADER=END
// hexadecimal key
// hexadecimal value
// ... repeated
// DATA=END
string strLine;
while (!strDump.eof() && strLine != "HEADER=END")
getline(strDump, strLine); // Skip past header
std::string keyHex, valueHex;
while (!strDump.eof() && keyHex != "DATA=END")
{
getline(strDump, keyHex);
if (keyHex != "DATA_END")
{
getline(strDump, valueHex);
vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
}
}
return (result == 0);
}
void CDBEnv::CheckpointLSN(const std::string& strFile)
{
dbenv.txn_checkpoint(0, 0, 0);
if (fMockDb)
return;
dbenv.lsn_reset(strFile.c_str(), 0);
}
CDB::CDB(const std::string& strFilename, const char* pszMode) :
pdb(NULL), activeTxn(NULL)
{
int ret;
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
if (strFilename.empty())
return;
bool fCreate = strchr(pszMode, 'c');
unsigned int nFlags = DB_THREAD;
if (fCreate)
nFlags |= DB_CREATE;
{
LOCK(bitdb.cs_db);
if (!bitdb.Open(GetDataDir()))
throw runtime_error("env open failed");
strFile = strFilename;
++bitdb.mapFileUseCount[strFile];
pdb = bitdb.mapDb[strFile];
if (pdb == NULL)
{
pdb = new Db(&bitdb.dbenv, 0);
bool fMockDb = bitdb.IsMock();
if (fMockDb)
{
DbMpoolFile*mpf = pdb->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0)
throw runtime_error(strprintf("CDB : Failed to configure for no temp file backing for database %s", strFile));
}
ret = pdb->open(NULL, // Txn pointer
fMockDb ? NULL : strFile.c_str(), // Filename
fMockDb ? strFile.c_str() : "main", // Logical db name
DB_BTREE, // Database type
nFlags, // Flags
0);
if (ret != 0)
{
delete pdb;
pdb = NULL;
--bitdb.mapFileUseCount[strFile];
strFile = "";
throw runtime_error(strprintf("CDB : Error %d, can't open database %s", ret, strFile));
}
if (fCreate && !Exists(string("version")))
{
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(CLIENT_VERSION);
fReadOnly = fTmp;
}
bitdb.mapDb[strFile] = pdb;
}
}
}
void CDB::Close()
{
if (!pdb)
return;
if (activeTxn)
activeTxn->abort();
activeTxn = NULL;
pdb = NULL;
// Flush database activity from memory pool to disk log
unsigned int nMinutes = 0;
if (fReadOnly)
nMinutes = 1;
bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
{
LOCK(bitdb.cs_db);
--bitdb.mapFileUseCount[strFile];
}
}
void CDBEnv::CloseDb(const string& strFile)
{
{
LOCK(cs_db);
if (mapDb[strFile] != NULL)
{
// Close the database handle
Db* pdb = mapDb[strFile];
pdb->close(0);
delete pdb;
mapDb[strFile] = NULL;
}
}
}
bool CDBEnv::RemoveDb(const string& strFile)
{
this->CloseDb(strFile);
LOCK(cs_db);
int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
return (rc == 0);
}
bool CDB::Rewrite(const string& strFile, const char* pszSkip)
{
while (true)
{
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
{
// Flush log data to the dat file
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(strFile);
bool fSuccess = true;
LogPrintf("Rewriting %s...\n", strFile);
string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
CDB db(strFile.c_str(), "r");
Db* pdbCopy = new Db(&bitdb.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
strFileRes.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0)
{
LogPrintf("Cannot create database file %s\n", strFileRes);
fSuccess = false;
}
Dbc* pcursor = db.GetCursor();
if (pcursor)
while (fSuccess)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
if (ret == DB_NOTFOUND)
{
pcursor->close();
break;
}
else if (ret != 0)
{
pcursor->close();
fSuccess = false;
break;
}
if (pszSkip &&
strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
continue;
if (strncmp(&ssKey[0], "\x07version", 8) == 0)
{
// Update version:
ssValue.clear();
ssValue << CLIENT_VERSION;
}
Dbt datKey(&ssKey[0], ssKey.size());
Dbt datValue(&ssValue[0], ssValue.size());
int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
if (fSuccess)
{
db.Close();
bitdb.CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
delete pdbCopy;
}
}
if (fSuccess)
{
Db dbA(&bitdb.dbenv, 0);
if (dbA.remove(strFile.c_str(), NULL, 0))
fSuccess = false;
Db dbB(&bitdb.dbenv, 0);
if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
fSuccess = false;
}
if (!fSuccess)
LogPrintf("Rewriting of %s FAILED!\n", strFileRes);
return fSuccess;
}
}
MilliSleep(100);
}
return false;
}
void CDBEnv::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file
// on all files that are not in use
LogPrint("db", "Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
if (!fDbEnvInit)
return;
{
LOCK(cs_db);
map<string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end())
{
string strFile = (*mi).first;
int nRefCount = (*mi).second;
LogPrint("db", "%s refcount=%d\n", strFile, nRefCount);
if (nRefCount == 0)
{
// Move log data to the dat file
CloseDb(strFile);
LogPrint("db", "%s checkpoint\n", strFile);
dbenv.txn_checkpoint(0, 0, 0);
LogPrint("db", "%s detach\n", strFile);
if (!fMockDb)
dbenv.lsn_reset(strFile.c_str(), 0);
LogPrint("db", "%s closed\n", strFile);
mapFileUseCount.erase(mi++);
}
else
mi++;
}
LogPrint("db", "DBFlush(%s)%s ended %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
if (fShutdown)
{
char** listp;
if (mapFileUseCount.empty())
{
dbenv.log_archive(&listp, DB_ARCH_REMOVE);
Close();
}
}
}
}
<commit_msg>Fix syntax error in key parser<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "addrman.h"
#include "hash.h"
#include "util.h"
#ifndef WIN32
#include <sys/stat.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/version.hpp>
#include <openssl/rand.h>
using namespace std;
using namespace boost;
unsigned int nWalletDBUpdated;
//
// CDB
//
CDBEnv bitdb;
void CDBEnv::EnvShutdown()
{
if (!fDbEnvInit)
return;
fDbEnvInit = false;
int ret = dbenv.close(0);
if (ret != 0)
LogPrintf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
if (!fMockDb)
DbEnv(0).remove(strPath.c_str(), 0);
}
CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
{
fDbEnvInit = false;
fMockDb = false;
}
CDBEnv::~CDBEnv()
{
EnvShutdown();
}
void CDBEnv::Close()
{
EnvShutdown();
}
bool CDBEnv::Open(boost::filesystem::path pathEnv_)
{
if (fDbEnvInit)
return true;
boost::this_thread::interruption_point();
pathEnv = pathEnv_;
filesystem::path pathDataDir = pathEnv;
strPath = pathDataDir.string();
filesystem::path pathLogDir = pathDataDir / "database";
filesystem::create_directory(pathLogDir);
filesystem::path pathErrorFile = pathDataDir / "db.log";
LogPrintf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (GetBoolArg("-privdb", true))
nEnvFlags |= DB_PRIVATE;
int nDbCache = GetArg("-dbcache", 25);
dbenv.set_lg_dir(pathLogDir.string().c_str());
dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
dbenv.set_lg_bsize(1048576);
dbenv.set_lg_max(10485760);
dbenv.set_lk_max_locks(10000);
dbenv.set_lk_max_objects(10000);
dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
dbenv.set_flags(DB_AUTO_COMMIT, 1);
dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
#ifdef DB_LOG_AUTO_REMOVE
dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
#endif
int ret = dbenv.open(strPath.c_str(),
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
if (ret != 0)
return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
fDbEnvInit = true;
fMockDb = false;
return true;
}
void CDBEnv::MakeMock()
{
if (fDbEnvInit)
throw runtime_error("CDBEnv::MakeMock(): already initialized");
boost::this_thread::interruption_point();
LogPrint("db", "CDBEnv::MakeMock()\n");
dbenv.set_cachesize(1, 0, 1);
dbenv.set_lg_bsize(10485760*4);
dbenv.set_lg_max(10485760);
dbenv.set_lk_max_locks(10000);
dbenv.set_lk_max_objects(10000);
dbenv.set_flags(DB_AUTO_COMMIT, 1);
#ifdef DB_LOG_IN_MEMORY
dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
#endif
int ret = dbenv.open(NULL,
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
fDbEnvInit = true;
fMockDb = true;
}
CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, NULL, 0);
if (result == 0)
return VERIFY_OK;
else if (recoverFunc == NULL)
return RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(*this, strFile);
return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
}
bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
std::vector<CDBEnv::KeyValPair >& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
u_int32_t flags = DB_SALVAGE;
if (fAggressive) flags |= DB_AGGRESSIVE;
stringstream strDump;
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
if (result == DB_VERIFY_BAD)
{
LogPrintf("Error: Salvage found errors, all data may not be recoverable.\n");
if (!fAggressive)
{
LogPrintf("Error: Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD)
{
LogPrintf("ERROR: db salvage failed: %d\n",result);
return false;
}
// Format of bdb dump is ascii lines:
// header lines...
// HEADER=END
// hexadecimal key
// hexadecimal value
// ... repeated
// DATA=END
string strLine;
while (!strDump.eof() && strLine != "HEADER=END")
getline(strDump, strLine); // Skip past header
std::string keyHex, valueHex;
while (!strDump.eof() && keyHex != "DATA=END")
{
getline(strDump, keyHex);
if (keyHex != "DATA=END")
{
getline(strDump, valueHex);
vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
}
}
return (result == 0);
}
void CDBEnv::CheckpointLSN(const std::string& strFile)
{
dbenv.txn_checkpoint(0, 0, 0);
if (fMockDb)
return;
dbenv.lsn_reset(strFile.c_str(), 0);
}
CDB::CDB(const std::string& strFilename, const char* pszMode) :
pdb(NULL), activeTxn(NULL)
{
int ret;
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
if (strFilename.empty())
return;
bool fCreate = strchr(pszMode, 'c');
unsigned int nFlags = DB_THREAD;
if (fCreate)
nFlags |= DB_CREATE;
{
LOCK(bitdb.cs_db);
if (!bitdb.Open(GetDataDir()))
throw runtime_error("env open failed");
strFile = strFilename;
++bitdb.mapFileUseCount[strFile];
pdb = bitdb.mapDb[strFile];
if (pdb == NULL)
{
pdb = new Db(&bitdb.dbenv, 0);
bool fMockDb = bitdb.IsMock();
if (fMockDb)
{
DbMpoolFile*mpf = pdb->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0)
throw runtime_error(strprintf("CDB : Failed to configure for no temp file backing for database %s", strFile));
}
ret = pdb->open(NULL, // Txn pointer
fMockDb ? NULL : strFile.c_str(), // Filename
fMockDb ? strFile.c_str() : "main", // Logical db name
DB_BTREE, // Database type
nFlags, // Flags
0);
if (ret != 0)
{
delete pdb;
pdb = NULL;
--bitdb.mapFileUseCount[strFile];
strFile = "";
throw runtime_error(strprintf("CDB : Error %d, can't open database %s", ret, strFile));
}
if (fCreate && !Exists(string("version")))
{
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(CLIENT_VERSION);
fReadOnly = fTmp;
}
bitdb.mapDb[strFile] = pdb;
}
}
}
void CDB::Close()
{
if (!pdb)
return;
if (activeTxn)
activeTxn->abort();
activeTxn = NULL;
pdb = NULL;
// Flush database activity from memory pool to disk log
unsigned int nMinutes = 0;
if (fReadOnly)
nMinutes = 1;
bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
{
LOCK(bitdb.cs_db);
--bitdb.mapFileUseCount[strFile];
}
}
void CDBEnv::CloseDb(const string& strFile)
{
{
LOCK(cs_db);
if (mapDb[strFile] != NULL)
{
// Close the database handle
Db* pdb = mapDb[strFile];
pdb->close(0);
delete pdb;
mapDb[strFile] = NULL;
}
}
}
bool CDBEnv::RemoveDb(const string& strFile)
{
this->CloseDb(strFile);
LOCK(cs_db);
int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
return (rc == 0);
}
bool CDB::Rewrite(const string& strFile, const char* pszSkip)
{
while (true)
{
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
{
// Flush log data to the dat file
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(strFile);
bool fSuccess = true;
LogPrintf("Rewriting %s...\n", strFile);
string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
CDB db(strFile.c_str(), "r");
Db* pdbCopy = new Db(&bitdb.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
strFileRes.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0)
{
LogPrintf("Cannot create database file %s\n", strFileRes);
fSuccess = false;
}
Dbc* pcursor = db.GetCursor();
if (pcursor)
while (fSuccess)
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
if (ret == DB_NOTFOUND)
{
pcursor->close();
break;
}
else if (ret != 0)
{
pcursor->close();
fSuccess = false;
break;
}
if (pszSkip &&
strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
continue;
if (strncmp(&ssKey[0], "\x07version", 8) == 0)
{
// Update version:
ssValue.clear();
ssValue << CLIENT_VERSION;
}
Dbt datKey(&ssKey[0], ssKey.size());
Dbt datValue(&ssValue[0], ssValue.size());
int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
if (fSuccess)
{
db.Close();
bitdb.CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
delete pdbCopy;
}
}
if (fSuccess)
{
Db dbA(&bitdb.dbenv, 0);
if (dbA.remove(strFile.c_str(), NULL, 0))
fSuccess = false;
Db dbB(&bitdb.dbenv, 0);
if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
fSuccess = false;
}
if (!fSuccess)
LogPrintf("Rewriting of %s FAILED!\n", strFileRes);
return fSuccess;
}
}
MilliSleep(100);
}
return false;
}
void CDBEnv::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file
// on all files that are not in use
LogPrint("db", "Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
if (!fDbEnvInit)
return;
{
LOCK(cs_db);
map<string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end())
{
string strFile = (*mi).first;
int nRefCount = (*mi).second;
LogPrint("db", "%s refcount=%d\n", strFile, nRefCount);
if (nRefCount == 0)
{
// Move log data to the dat file
CloseDb(strFile);
LogPrint("db", "%s checkpoint\n", strFile);
dbenv.txn_checkpoint(0, 0, 0);
LogPrint("db", "%s detach\n", strFile);
if (!fMockDb)
dbenv.lsn_reset(strFile.c_str(), 0);
LogPrint("db", "%s closed\n", strFile);
mapFileUseCount.erase(mi++);
}
else
mi++;
}
LogPrint("db", "DBFlush(%s)%s ended %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
if (fShutdown)
{
char** listp;
if (mapFileUseCount.empty())
{
dbenv.log_archive(&listp, DB_ARCH_REMOVE);
Close();
}
}
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* $MCI Mdulo de implementao: Mdulo de teste especfico
*
* Arquivo gerado: TESTARV.C
* Letras identificadoras: TARV
*
* Nome da base de software: Exemplo de teste automatizado
* Arquivo da base de software: D:\AUTOTEST\PROJETOS\SIMPLES.BSW
*
* Projeto: Disciplinas INF 1628 / 1301
* Gestor: DI/PUC-Rio
* Autores: avs - Arndt von Staa
*
* $HA Histrico de evoluo:
* Verso Autor Data Observaes
* 3.00 avs 28/02/2003 Uniformizao da interface das funes e
* de todas as condies de retorno.
* 2.00 avs 03/08/2002 Eliminao de cdigo duplicado, reestruturao
* 1.00 avs 15/08/2001 Incio do desenvolvimento
*
* $ED Descrio do mdulo
* Este modulo contm as funes especficas para o teste do
* mdulo rvore. Ilustra como redigir um interpretador de comandos
* de teste especficos utilizando o arcabouo de teste para C.
*
* $EIU Interface com o usurio pessoa
* Comandos de teste especficos para testar o mdulo rvore:
*
* =criar - chama a funo ARV_CriarArvore( )
* =insdir <Char>
* - chama a funo ARV_InserirDireita( <Char> )
* Obs. notao: <Char> o valor do parmetro
* que se encontra no comando de teste.
*
* "=insesq" <Char>
* - chama a funo ARV_InserirEsquerda( <Char> )
* "=irpai" - chama a funo ARV_IrPai( )
* "=iresq" - chama a funo ARV_IrEsquerda( )
* "=irdir" - chama a funo ARV_IrDireita( )
* "=obter" <Char>
* - chama a funo ARV_ObterValorCorr( ) e compara
* o valor retornado com o valor <Char>
* "=destroi" - chama a funo ARV_DestruirArvore( )
*
***************************************************************************/
#include <string.h>
#include <stdio.h>
#include "TST_ESPC.H"
#include "GENERICO.H"
#include "LERPARM.H"
#include "professor.h"
/* Tabela dos nomes dos comandos de teste especficos */
/*
PRF_tpCondRet criaProf(int cpf, char *pais, int dia, int mes, int ano);
PRF_tpCondRet consultaCpfProf();
PRF_tpCondRet alteraCpfProf(int cpf);
PRF_tpCondRet mostraProf();
PRF_tpCondRet liberaProf();
*/
#define CRIAR_CMD "=criar"
#define ALTERA_CPF_CMD "=alterarCPF"
#define ALTERA_PAIS_CMD "=alterarPais"
#define ALTERA_MATRICULA_CMD "=alterarMatricula"
#define CONSULTA_CPF_CMD "=consultarCPF"
#define CONSULTA_PAIS_CMD "=consultarPais"
#define CONSULTA_MATRICULA_CMD "=consultarMatricula"
#define MOSTRAR_CMD "=mostrar"
#define LIBERAR_CMD "=liberar"
/***** Cdigo das funes exportadas pelo mdulo *****/
/***********************************************************************
*
* $FC Funo: TPRF Efetuar operaes de teste especficas para professor
*
* $ED Descrio da funo
* Efetua os diversos comandos de teste especficos para o mdulo
* rvore sendo testado.
*
* $EP Parmetros
* $P ComandoTeste - String contendo o comando
*
* $FV Valor retornado
* Ver TST_tpCondRet definido em TST_ESPC.H
*
***********************************************************************/
Prof *p = NULL;
TST_tpCondRet TST_EfetuarComando(char * ComandoTeste){
PRF_tpCondRet CondRetObtido ;
PRF_tpCondRet CondRetEsperada ;
int paramMatricula;
char paramCPF[11];
char paramPais[80];
int paramDia;
int paramMes;
int paramAno;
int valorObtido;
int valorEsperado;
char valorStringObtido[80];
char valorStringEsperado[80];
int NumLidos = -1 ;
TST_tpCondRet Ret ;
/* Testar PRF Criar professor */
if ( strcmp( ComandoTeste , CRIAR_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "isiiii" ,
¶mCPF, paramPais, ¶mDia, ¶mMes, ¶mAno,
&CondRetEsperada ) ;
if ( NumLidos != 6 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = criaProf( &p, paramMatricula, paramCPF, paramPais, paramDia, paramMes, paramAno ) ;
return TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao criar professor." );
} /* fim ativa: Testar PRF Criar professor */
/* Testar mostrar Professor */
else if ( strcmp( ComandoTeste , MOSTRAR_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "i" ,
&CondRetEsperada ) ;
if ( NumLidos != 1 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = mostraProf(p) ;
return TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao mostrar Professor." );
} /* fim ativa: Testar PRF mostrar professor */
/* Testar PRF liberar professor */
else if ( strcmp( ComandoTeste , LIBERAR_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "i" ,
&CondRetEsperada ) ;
if ( NumLidos != 1 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = liberaProf(&p) ;
return TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao liberar Professor." );
} /* fim ativa: Testar PRF liberar professor */
//------------------------------------------Consultas----------------------------------
/* Testar PRF consulta CPF professor */
else if ( strcmp( ComandoTeste , CONSULTA_CPF_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "si" ,
&valorStringEsperado,
&CondRetEsperada ) ;
if ( NumLidos != 2 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = consultaCpfProf(p, valorStringObtido) ;
Ret = TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao consultar CPF de Professor." );
if(Ret != TST_CondRetOK) return Ret;
Ret = TST_CompararString( valorStringEsperado , valorStringObtido,
"Retorno por referencia errado ao consultar CPF de Professor." );
return Ret;
} /* fim ativa: Testar PRF consulta CPF professor */
/* Testar PRF consulta Pais professor */
else if ( strcmp( ComandoTeste , CONSULTA_PAIS_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "si" ,
&valorStringEsperado,
&CondRetEsperada ) ;
if ( NumLidos != 2 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = consultaPaisProf(p, valorStringObtido) ;
Ret = TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao consultar Pais de Professor." );
if(Ret != TST_CondRetOK) return Ret;
Ret = TST_CompararString( valorStringEsperado , valorStringObtido,
"Retorno por referencia errado ao consultar Pais de Professor." );
return Ret;
} /* fim ativa: Testar PRF consulta Pais professor */
/* Testar PRF consulta Matricula professor */
else if ( strcmp( ComandoTeste , CONSULTA_MATRICULA_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "ii" ,
&valorEsperado,
&CondRetEsperada ) ;
if ( NumLidos != 2 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = consultaMatriculaProf(p, &valorObtido) ;
Ret = TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao consultar Matricula de Professor." );
if(Ret != TST_CondRetOK) return Ret;
Ret = TST_CompararInt( valorEsperado , valorObtido,
"Retorno por referencia errado ao consultar Matricula de Professor." );
return Ret;
} /* fim ativa: Testar PRF consulta Matricula professor */
//TODO inicio
/*
// As partes que devem ser alteradas esto como TODO
*/
/* Testar PRF consulta TODO professor */
// coloque o nome do define no topo do documento correspondente a sua variavel
// se no houver tal variavel crie outro define
// else if ( strcmp( ComandoTeste , CONSULTA_TODO_CMD ) == 0 )
// {
// coloque o tipo da leitura, s=string, c=char, i=inteiro
// No retire o ultimo i que j est ai.
// Coloque o nome da variavel de acordo com uma variavel no inicio da funo. Se no houver variavel, crie.
// La tem cima tem valorEsperado do tipo int, e valorStringEsperado do tipo char* (string), use o correspondente
// NumLidos = LER_LerParametros( "TODOi" ,
// &valorTODOEsperado,
// &CondRetEsperada ) ;
// if ( NumLidos != 2 )
// {
// return TST_CondRetParm ;
// } /* if */
//
//
// Chame a funo de professor que faz a consulta desta variavel
// use a variavel obtido do tipo correspondente, ou crie uma se necessario
// CondRetObtido = consultaTODOProf(p, &valorTODOObtido) ;
//
// Nome da variavel que esta tratando
// Ret = TST_CompararInt( CondRetEsperada , CondRetObtido ,
// "Retorno errado ao consultar TODO de Professor." );
// if(Ret != TST_CondRetOK) return Ret;
// novamente o mesmo nome da variavel que esta tratando aqui
// Ret = TST_CompararInt( valorEsperado , valorObtido,
// "Retorno por referencia errado ao consultar TODO de Professor." );
// return Ret;
//
// Coloque o nome desta variavel
// } /* fim ativa: Testar PRF consulta TODO professor */
//delete todos esses comentarios com // e deixe os com /* . Compare com as outras funes.
// TODO fim
// ----------------------------------------Alteras-------------------------------
/* Testar PRF alterar cpf */
else if ( strcmp( ComandoTeste , ALTERA_CPF_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "si" ,
¶mCPF , &CondRetEsperada ) ;
if ( NumLidos != 2 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = alteraCpfProf(p, paramCPF ) ;
return TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao alterar CPF." );
} /* fim ativa: Testar PRF alterar cpf */
/* Testar PRF alterar Pais */
else if ( strcmp( ComandoTeste , ALTERA_PAIS_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "si" ,
¶mPais , &CondRetEsperada ) ;
if ( NumLidos != 2 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = alteraPaisProf(p, paramPais ) ;
return TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao alterar CPF." );
} /* fim ativa: Testar PRF alterar Pais */
/* Testar PRF alterar matricula */
else if ( strcmp( ComandoTeste , ALTERA_MATRICULA_CMD ) == 0 )
{
NumLidos = LER_LerParametros( "ii" ,
¶mMatricula , &CondRetEsperada ) ;
if ( NumLidos != 2 )
{
return TST_CondRetParm ;
} /* if */
CondRetObtido = alteraMatriculaProf(p, paramMatricula ) ;
return TST_CompararInt( CondRetEsperada , CondRetObtido ,
"Retorno errado ao alterar CPF." );
} /* fim ativa: Testar ARV alterar cpf */
/* TODO inicio
/*
// As partes que devem ser alteradas esto como TODO
*/
/* Testar PRF alterar TODO */
// coloque o nome do define no topo do documento correspondente a sua variavel
// se no houver tal variavel crie outro define
// else if ( strcmp( ComandoTeste , ALTERA_TODO_CMD ) == 0 )
// {
// coloque o tipo da leitura, s=string, c=char, i=inteiro
// No retire o ultimo i que j est ai.
// Coloque o nome da variavel de acordo com uma variavel no inicio da funo. Se no houver variavel, crie.
// NumLidos = LER_LerParametros( "TODOi" ,
// ¶mTODO , &CondRetEsperada ) ;
// if ( NumLidos != 2 )
// {
// return TST_CondRetParm ;
// } /* if */
//
// Chame a funo de professor que altera a variavel deste bloco
// Essa a mesma variavel de antes
// CondRetObtido = alteraTODOProf(p, paramTODO ) ;
//
// coloque o nome da variavel que voce esta tratando
// return TST_CompararInt( CondRetEsperada , CondRetObtido ,
// "Retorno errado ao alterar TODO." );
//
// de novo o nome da variavel
// } /* fim ativa: Testar PRF alterar TODO */
//
//delete todos esses comentarios com // deixe os com /* e compare com as outras funes prontas.
// TODO fim
// */
return TST_CondRetNaoConhec ;
} /* Fim funo: TPRF Efetuar operaes de teste especficas para professor */
/********** Fim do mdulo de implementao: Mdulo de teste especfico **********/
<commit_msg>Delete TESTProf.C<commit_after><|endoftext|> |
<commit_before>#include <QCoreApplication>
#include <iostream>
#include <QString>
#include <string>
#include <newcryptograph.h>
using namespace std;
void Permutation()
{
char c;
cout << "e to encode. d to decode: ";
cin >> c;
cout << "Input string: ";
string text;
cin >> text;
//cout << text;
cout << "Input code: ";
string code;
cin >> code;
QString Qcode = QString::fromStdString(code);
QList<int> key;
for (int i=0; i < code.length(); i++)
{
key.append((int)((int)code[i]-'0'));
}
if (c == 'e')
{
QString qsw = QString::fromStdString(text);
QString answer = NewCryptograph::EncodePermutation(qsw, key);//EncodePermutation(qsw, key);
cout << answer.toStdString() << endl;
}
if (c == 'd')
{
QString qsw = QString::fromStdString(text);
QString answer = NewCryptograph::DecodePermutation(qsw, key);//DecodePermutation(qsw, key);
cout << answer.toStdString() << endl;
}
cout << "Ok" << endl;
}
void Cardano()
{
char c;
cout << "e to encode. d to decode: ";
cin >> c;
string fileName;
QString encoded;
NewCryptograph NC;
if (c == 'e')
{
cout << "String: ";
string text;
cin >> text;
encoded = NC.EncodeCardano(QString::fromStdString(text));
cout << encoded.toStdString() << endl;
cout << "Input filename: ";
cin >> fileName;
NC.SaveToFile(QString::fromStdString(fileName), encoded);
cout << "Success!" << endl;
}
if (c == 'd')
{
cout << "Input filename: ";
cin >> fileName;
encoded = NC.LoadFromFile(QString::fromStdString(fileName));
QString decode = NC.DecodeCardano(encoded);
cout << decode.toStdString() << endl;
cout << "Input filename: ";
cin >> fileName;
NC.SaveToFile(QString::fromStdString(fileName), encoded);
cout << "Success!" << endl;
}
}
int main(int argc, char *argv[])
{
while (true)
{
//Permutation();
//Cardano();
}
return 0;
}
<commit_msg>Задание 3.3. Свой вид кодирования<commit_after>#include <QCoreApplication>
#include <iostream>
#include <QString>
#include <string>
#include <newcryptograph.h>
using namespace std;
void Permutation()
{
char c;
cout << "e to encode. d to decode: ";
cin >> c;
cout << "Input string: ";
string text;
cin >> text;
//cout << text;
cout << "Input code: ";
string code;
cin >> code;
QString Qcode = QString::fromStdString(code);
QList<int> key;
for (int i=0; i < code.length(); i++)
{
key.append((int)((int)code[i]-'0'));
}
if (c == 'e')
{
QString qsw = QString::fromStdString(text);
QString answer = NewCryptograph::EncodePermutation(qsw, key);//EncodePermutation(qsw, key);
cout << answer.toStdString() << endl;
}
if (c == 'd')
{
QString qsw = QString::fromStdString(text);
QString answer = NewCryptograph::DecodePermutation(qsw, key);//DecodePermutation(qsw, key);
cout << answer.toStdString() << endl;
}
cout << "Ok" << endl;
}
void Cardano()
{
char c;
cout << "e to encode. d to decode: ";
cin >> c;
string fileName;
QString encoded;
NewCryptograph NC;
if (c == 'e')
{
cout << "String: ";
string text;
cin >> text;
encoded = NC.EncodeCardano(QString::fromStdString(text));
cout << encoded.toStdString() << endl;
cout << "Input filename: ";
cin >> fileName;
NC.SaveToFile(QString::fromStdString(fileName), encoded);
cout << "Success!" << endl;
}
if (c == 'd')
{
cout << "Input filename: ";
cin >> fileName;
encoded = NC.LoadFromFile(QString::fromStdString(fileName));
QString decode = NC.DecodeCardano(encoded);
cout << decode.toStdString() << endl;
cout << "Input filename: ";
cin >> fileName;
NC.SaveToFile(QString::fromStdString(fileName), encoded);
cout << "Success!" << endl;
}
}
void MineMethod()
{
char c;
cout << "e to encode. d to decode: ";
cin >> c;
NewCryptograph NC;
QList<int> key;
key.append(4);
key.append(2);
key.append(1);
key.append(3);
string text;
if (c == 'e')
{
cout << "Input string: ";
cin >> text;
QString encoded = NC.EncodePermutation(NC.EncodeCardano(QString::fromStdString(text)), key);
cout << encoded.toStdString();
cout << "Filename to save: ";
cin >> text;
NC.SaveToFile(QString::fromStdString(text), encoded);
}
if (c == 'd')
{
cout << "FileName: ";
cin >> text;
QString encoded = NC.LoadFromFile(QString::fromStdString(text));
QString decoded = NC.DecodeCardano(NC.DecodePermutation(encoded, key));
cout << decoded.toStdString();
}
}
int main(int argc, char *argv[])
{
while (true)
{
//Permutation();
//Cardano();
MineMethod();
}
return 0;
}
<|endoftext|> |
<commit_before>#include <uWS/uWS.h>
#include <iostream>
#include "json.hpp"
#include "PID.h"
#include <math.h>
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
std::string hasData(std::string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_last_of("]");
if (found_null != std::string::npos) {
return "";
}
else if (b1 != std::string::npos && b2 != std::string::npos) {
return s.substr(b1, b2 - b1 + 1);
}
return "";
}
int main()
{
uWS::Hub h;
PID pid;
// TODO: Initialize the pid variable.
pid.Init(0.05, 0, 0);
h.onMessage([&pid](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2')
{
auto s = hasData(std::string(data).substr(0, length));
if (s != "") {
auto j = json::parse(s);
std::string event = j[0].get<std::string>();
if (event == "telemetry") {
// j[1] is the data JSON object
double cte = std::stod(j[1]["cte"].get<std::string>());
double speed = std::stod(j[1]["speed"].get<std::string>());
double angle = std::stod(j[1]["steering_angle"].get<std::string>());
double steer_value;
/*
* TODO: Calcuate steering value here, remember the steering value is
* [-1, 1].
* NOTE: Feel free to play around with the throttle and speed. Maybe use
* another PID controller to control the speed!
*/
pid.UpdateError(cte);
steer_value = deg2rad(angle) - pid.TotalError();
if(steer_value > 1) {steer_value = 1;}
else if(steer_value < -1) {steer_value = -1;}
// DEBUG
std::cout << "CTE: " << cte << " Steering Value: " << steer_value << std::endl;
json msgJson;
msgJson["steering_angle"] = steer_value;
msgJson["throttle"] = 0.3;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
std::cout << msg << std::endl;
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1)
{
res->end(s.data(), s.length());
}
else
{
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port))
{
std::cout << "Listening to port " << port << std::endl;
}
else
{
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
<commit_msg>fix: Update control gains and comment-out unused variables<commit_after>#include <uWS/uWS.h>
#include <iostream>
#include "json.hpp"
#include "PID.h"
#include <math.h>
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
std::string hasData(std::string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_last_of("]");
if (found_null != std::string::npos) {
return "";
}
else if (b1 != std::string::npos && b2 != std::string::npos) {
return s.substr(b1, b2 - b1 + 1);
}
return "";
}
int main()
{
uWS::Hub h;
PID pid;
// TODO: Initialize the pid variable.
pid.Init(0.2, 0.002, 7);
h.onMessage([&pid](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2')
{
auto s = hasData(std::string(data).substr(0, length));
if (s != "") {
auto j = json::parse(s);
std::string event = j[0].get<std::string>();
if (event == "telemetry") {
// j[1] is the data JSON object
double cte = std::stod(j[1]["cte"].get<std::string>());
// double speed = std::stod(j[1]["speed"].get<std::string>());
// double angle = std::stod(j[1]["steering_angle"].get<std::string>());
double steer_value;
/*
* TODO: Calcuate steering value here, remember the steering value is
* [-1, 1].
* NOTE: Feel free to play around with the throttle and speed. Maybe use
* another PID controller to control the speed!
*/
pid.UpdateError(cte);
steer_value = - pid.TotalError();
if(steer_value > 1) {steer_value = 1;}
else if(steer_value < -1) {steer_value = -1;}
// DEBUG
std::cout << "CTE: " << cte << " Steering Value: " << steer_value << std::endl;
json msgJson;
msgJson["steering_angle"] = steer_value;
msgJson["throttle"] = 0.3;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
std::cout << msg << std::endl;
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1)
{
res->end(s.data(), s.length());
}
else
{
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port))
{
std::cout << "Listening to port " << port << std::endl;
}
else
{
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
<|endoftext|> |
<commit_before><commit_msg>-fsanitize=vptr: SID_ATTR_*LANGUAGE are of type SvxLanguageItem<commit_after><|endoftext|> |
<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pal.h"
#include "args.h"
#include "trace.h"
#include "deps_resolver.h"
#include "utils.h"
#include "coreclr.h"
enum StatusCode
{
// 0x80 prefix to distinguish from corehost main's error codes.
InvalidArgFailure = 0x81,
CoreClrResolveFailure = 0x82,
CoreClrBindFailure = 0x83,
CoreClrInitFailure = 0x84,
CoreClrExeFailure = 0x85,
ResolverInitFailure = 0x86,
ResolverResolveFailure = 0x87,
};
// ----------------------------------------------------------------------
// resolve_clr_path: Resolve CLR Path in priority order
//
// Description:
// Check if CoreCLR library exists in runtime servicing dir or app
// local or DOTNET_HOME directory in that order of priority. If these
// fail to locate CoreCLR, then check platform-specific search.
//
// Returns:
// "true" if path to the CoreCLR dir can be resolved in "clr_path"
// parameter. Else, returns "false" with "clr_path" unmodified.
//
bool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path)
{
const pal::string_t* dirs[] = {
&args.dotnet_runtime_servicing, // DOTNET_RUNTIME_SERVICING
&args.app_dir, // APP LOCAL
&args.dotnet_home // DOTNET_HOME
};
for (int i = 0; i < sizeof(dirs) / sizeof(dirs[0]); ++i)
{
if (dirs[i]->empty())
{
continue;
}
// App dir should contain coreclr, so skip appending path.
pal::string_t cur_dir = *dirs[i];
if (dirs[i] != &args.app_dir)
{
append_path(&cur_dir, _X("runtime"));
append_path(&cur_dir, _X("coreclr"));
}
// Found coreclr in priority order.
if (coreclr_exists_in_dir(cur_dir))
{
clr_path->assign(cur_dir);
return true;
}
}
// Use platform-specific search algorithm
pal::string_t home_dir = args.dotnet_home;
if (pal::find_coreclr(&home_dir))
{
clr_path->assign(home_dir);
return true;
}
return false;
}
int run(const arguments_t& args, const pal::string_t& clr_path)
{
// Load the deps resolver
deps_resolver_t resolver(args);
if (!resolver.valid())
{
trace::error(_X("Invalid .deps file"));
return StatusCode::ResolverInitFailure;
}
// Add packages directory
pal::string_t packages_dir = args.nuget_packages;
if (!pal::directory_exists(packages_dir))
{
(void)pal::get_default_packages_directory(&packages_dir);
}
trace::info(_X("Package directory: %s"), packages_dir.empty() ? _X("not specified") : packages_dir.c_str());
probe_paths_t probe_paths;
if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths))
{
return StatusCode::ResolverResolveFailure;
}
// Build CoreCLR properties
const char* property_keys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES",
"APP_PATHS",
"APP_NI_PATHS",
"NATIVE_DLL_SEARCH_DIRECTORIES",
"PLATFORM_RESOURCE_ROOTS",
"AppDomainCompatSwitch",
// TODO: pipe this from corehost.json
"SERVER_GC",
// Workaround: mscorlib does not resolve symlinks for AppContext.BaseDirectory dotnet/coreclr/issues/2128
"APP_CONTEXT_BASE_DIRECTORY",
};
auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa);
auto app_base_cstr = pal::to_stdstring(args.app_dir);
auto native_dirs_cstr = pal::to_stdstring(probe_paths.native);
auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture);
// Workaround for dotnet/cli Issue #488 and #652
pal::string_t server_gc;
std::string server_gc_cstr = (pal::getenv(_X("COREHOST_SERVER_GC"), &server_gc) && !server_gc.empty()) ? pal::to_stdstring(server_gc) : "1";
const char* property_values[] = {
// TRUSTED_PLATFORM_ASSEMBLIES
tpa_paths_cstr.c_str(),
// APP_PATHS
app_base_cstr.c_str(),
// APP_NI_PATHS
app_base_cstr.c_str(),
// NATIVE_DLL_SEARCH_DIRECTORIES
native_dirs_cstr.c_str(),
// PLATFORM_RESOURCE_ROOTS
culture_dirs_cstr.c_str(),
// AppDomainCompatSwitch
"UseLatestBehaviorWhenTFMNotSpecified",
// SERVER_GC
server_gc_cstr.c_str(),
// APP_CONTEXT_BASE_DIRECTORY
app_base_cstr.c_str()
};
size_t property_size = sizeof(property_keys) / sizeof(property_keys[0]);
// Bind CoreCLR
if (!coreclr::bind(clr_path))
{
trace::error(_X("Failed to bind to coreclr"));
return StatusCode::CoreClrBindFailure;
}
// Verbose logging
if (trace::is_enabled())
{
for (size_t i = 0; i < property_size; ++i)
{
pal::string_t key, val;
pal::to_palstring(property_keys[i], &key);
pal::to_palstring(property_values[i], &val);
trace::verbose(_X("Property %s = %s"), key.c_str(), val.c_str());
}
}
std::string own_path;
pal::to_stdstring(args.own_path.c_str(), &own_path);
// Initialize CoreCLR
coreclr::host_handle_t host_handle;
coreclr::domain_id_t domain_id;
auto hr = coreclr::initialize(
own_path.c_str(),
"clrhost",
property_keys,
property_values,
property_size,
&host_handle,
&domain_id);
if (!SUCCEEDED(hr))
{
trace::error(_X("Failed to initialize CoreCLR, HRESULT: 0x%X"), hr);
return StatusCode::CoreClrInitFailure;
}
if (trace::is_enabled())
{
pal::string_t arg_str;
for (int i = 0; i < args.app_argc; i++)
{
arg_str.append(args.app_argv[i]);
arg_str.append(_X(","));
}
trace::info(_X("Launch host: %s app: %s, argc: %d args: %s"), args.own_path.c_str(),
args.managed_application.c_str(), args.app_argc, arg_str.c_str());
}
// Initialize with empty strings
std::vector<std::string> argv_strs(args.app_argc);
std::vector<const char*> argv(args.app_argc);
for (int i = 0; i < args.app_argc; i++)
{
pal::to_stdstring(args.app_argv[i], &argv_strs[i]);
argv[i] = argv_strs[i].c_str();
}
std::string managed_app = pal::to_stdstring(args.managed_application);
// Execute the application
unsigned int exit_code = 1;
hr = coreclr::execute_assembly(
host_handle,
domain_id,
argv.size(),
argv.data(),
managed_app.c_str(),
&exit_code);
if (!SUCCEEDED(hr))
{
trace::error(_X("Failed to execute managed app, HRESULT: 0x%X"), hr);
return StatusCode::CoreClrExeFailure;
}
// Shut down the CoreCLR
hr = coreclr::shutdown(host_handle, domain_id);
if (!SUCCEEDED(hr))
{
trace::warning(_X("Failed to shut down CoreCLR, HRESULT: 0x%X"), hr);
}
coreclr::unload();
return exit_code;
}
SHARED_API int corehost_main(const int argc, const pal::char_t* argv[])
{
trace::setup();
// Take care of arguments
arguments_t args;
if (!parse_arguments(argc, argv, args))
{
return StatusCode::InvalidArgFailure;
}
// Resolve CLR path
pal::string_t clr_path;
if (!resolve_clr_path(args, &clr_path))
{
trace::error(_X("Could not resolve coreclr path"));
return StatusCode::CoreClrResolveFailure;
}
pal::realpath(&clr_path);
return run(args, clr_path);
}
<commit_msg>Disable server GC since it's OOMing<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pal.h"
#include "args.h"
#include "trace.h"
#include "deps_resolver.h"
#include "utils.h"
#include "coreclr.h"
enum StatusCode
{
// 0x80 prefix to distinguish from corehost main's error codes.
InvalidArgFailure = 0x81,
CoreClrResolveFailure = 0x82,
CoreClrBindFailure = 0x83,
CoreClrInitFailure = 0x84,
CoreClrExeFailure = 0x85,
ResolverInitFailure = 0x86,
ResolverResolveFailure = 0x87,
};
// ----------------------------------------------------------------------
// resolve_clr_path: Resolve CLR Path in priority order
//
// Description:
// Check if CoreCLR library exists in runtime servicing dir or app
// local or DOTNET_HOME directory in that order of priority. If these
// fail to locate CoreCLR, then check platform-specific search.
//
// Returns:
// "true" if path to the CoreCLR dir can be resolved in "clr_path"
// parameter. Else, returns "false" with "clr_path" unmodified.
//
bool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path)
{
const pal::string_t* dirs[] = {
&args.dotnet_runtime_servicing, // DOTNET_RUNTIME_SERVICING
&args.app_dir, // APP LOCAL
&args.dotnet_home // DOTNET_HOME
};
for (int i = 0; i < sizeof(dirs) / sizeof(dirs[0]); ++i)
{
if (dirs[i]->empty())
{
continue;
}
// App dir should contain coreclr, so skip appending path.
pal::string_t cur_dir = *dirs[i];
if (dirs[i] != &args.app_dir)
{
append_path(&cur_dir, _X("runtime"));
append_path(&cur_dir, _X("coreclr"));
}
// Found coreclr in priority order.
if (coreclr_exists_in_dir(cur_dir))
{
clr_path->assign(cur_dir);
return true;
}
}
// Use platform-specific search algorithm
pal::string_t home_dir = args.dotnet_home;
if (pal::find_coreclr(&home_dir))
{
clr_path->assign(home_dir);
return true;
}
return false;
}
int run(const arguments_t& args, const pal::string_t& clr_path)
{
// Load the deps resolver
deps_resolver_t resolver(args);
if (!resolver.valid())
{
trace::error(_X("Invalid .deps file"));
return StatusCode::ResolverInitFailure;
}
// Add packages directory
pal::string_t packages_dir = args.nuget_packages;
if (!pal::directory_exists(packages_dir))
{
(void)pal::get_default_packages_directory(&packages_dir);
}
trace::info(_X("Package directory: %s"), packages_dir.empty() ? _X("not specified") : packages_dir.c_str());
probe_paths_t probe_paths;
if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths))
{
return StatusCode::ResolverResolveFailure;
}
// Build CoreCLR properties
const char* property_keys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES",
"APP_PATHS",
"APP_NI_PATHS",
"NATIVE_DLL_SEARCH_DIRECTORIES",
"PLATFORM_RESOURCE_ROOTS",
"AppDomainCompatSwitch",
// TODO: pipe this from corehost.json
"SERVER_GC",
// Workaround: mscorlib does not resolve symlinks for AppContext.BaseDirectory dotnet/coreclr/issues/2128
"APP_CONTEXT_BASE_DIRECTORY",
};
auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa);
auto app_base_cstr = pal::to_stdstring(args.app_dir);
auto native_dirs_cstr = pal::to_stdstring(probe_paths.native);
auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture);
// Workaround for dotnet/cli Issue #488 and #652
pal::string_t server_gc;
std::string server_gc_cstr = (pal::getenv(_X("COREHOST_SERVER_GC"), &server_gc) && !server_gc.empty()) ? pal::to_stdstring(server_gc) : "0";
const char* property_values[] = {
// TRUSTED_PLATFORM_ASSEMBLIES
tpa_paths_cstr.c_str(),
// APP_PATHS
app_base_cstr.c_str(),
// APP_NI_PATHS
app_base_cstr.c_str(),
// NATIVE_DLL_SEARCH_DIRECTORIES
native_dirs_cstr.c_str(),
// PLATFORM_RESOURCE_ROOTS
culture_dirs_cstr.c_str(),
// AppDomainCompatSwitch
"UseLatestBehaviorWhenTFMNotSpecified",
// SERVER_GC
server_gc_cstr.c_str(),
// APP_CONTEXT_BASE_DIRECTORY
app_base_cstr.c_str()
};
size_t property_size = sizeof(property_keys) / sizeof(property_keys[0]);
// Bind CoreCLR
if (!coreclr::bind(clr_path))
{
trace::error(_X("Failed to bind to coreclr"));
return StatusCode::CoreClrBindFailure;
}
// Verbose logging
if (trace::is_enabled())
{
for (size_t i = 0; i < property_size; ++i)
{
pal::string_t key, val;
pal::to_palstring(property_keys[i], &key);
pal::to_palstring(property_values[i], &val);
trace::verbose(_X("Property %s = %s"), key.c_str(), val.c_str());
}
}
std::string own_path;
pal::to_stdstring(args.own_path.c_str(), &own_path);
// Initialize CoreCLR
coreclr::host_handle_t host_handle;
coreclr::domain_id_t domain_id;
auto hr = coreclr::initialize(
own_path.c_str(),
"clrhost",
property_keys,
property_values,
property_size,
&host_handle,
&domain_id);
if (!SUCCEEDED(hr))
{
trace::error(_X("Failed to initialize CoreCLR, HRESULT: 0x%X"), hr);
return StatusCode::CoreClrInitFailure;
}
if (trace::is_enabled())
{
pal::string_t arg_str;
for (int i = 0; i < args.app_argc; i++)
{
arg_str.append(args.app_argv[i]);
arg_str.append(_X(","));
}
trace::info(_X("Launch host: %s app: %s, argc: %d args: %s"), args.own_path.c_str(),
args.managed_application.c_str(), args.app_argc, arg_str.c_str());
}
// Initialize with empty strings
std::vector<std::string> argv_strs(args.app_argc);
std::vector<const char*> argv(args.app_argc);
for (int i = 0; i < args.app_argc; i++)
{
pal::to_stdstring(args.app_argv[i], &argv_strs[i]);
argv[i] = argv_strs[i].c_str();
}
std::string managed_app = pal::to_stdstring(args.managed_application);
// Execute the application
unsigned int exit_code = 1;
hr = coreclr::execute_assembly(
host_handle,
domain_id,
argv.size(),
argv.data(),
managed_app.c_str(),
&exit_code);
if (!SUCCEEDED(hr))
{
trace::error(_X("Failed to execute managed app, HRESULT: 0x%X"), hr);
return StatusCode::CoreClrExeFailure;
}
// Shut down the CoreCLR
hr = coreclr::shutdown(host_handle, domain_id);
if (!SUCCEEDED(hr))
{
trace::warning(_X("Failed to shut down CoreCLR, HRESULT: 0x%X"), hr);
}
coreclr::unload();
return exit_code;
}
SHARED_API int corehost_main(const int argc, const pal::char_t* argv[])
{
trace::setup();
// Take care of arguments
arguments_t args;
if (!parse_arguments(argc, argv, args))
{
return StatusCode::InvalidArgFailure;
}
// Resolve CLR path
pal::string_t clr_path;
if (!resolve_clr_path(args, &clr_path))
{
trace::error(_X("Could not resolve coreclr path"));
return StatusCode::CoreClrResolveFailure;
}
pal::realpath(&clr_path);
return run(args, clr_path);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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/browser_prefs.h"
#include "chrome/browser/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/cache_manager_host.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/google_url_tracker.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/net/dns_global.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/browser_render_process_host.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/session_startup_pref.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/browser/tab_contents/web_contents.h"
#if defined(OS_WIN) // TODO(port): whittle this down as we port
#include "chrome/browser/external_protocol_handler.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/spellchecker.h"
#include "chrome/browser/task_manager.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/bookmark_manager_view.h"
#include "chrome/browser/views/bookmark_table_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/keyword_editor_view.h"
#include "chrome/browser/views/page_info_window.h"
#endif
namespace browser {
void RegisterAllPrefs(PrefService* user_prefs, PrefService* local_state) {
// Prefs in Local State
GoogleURLTracker::RegisterPrefs(local_state);
Browser::RegisterPrefs(local_state);
CacheManagerHost::RegisterPrefs(local_state);
SafeBrowsingService::RegisterPrefs(local_state);
MetricsLog::RegisterPrefs(local_state);
MetricsService::RegisterPrefs(local_state);
browser_shutdown::RegisterPrefs(local_state);
chrome_browser_net::RegisterPrefs(local_state);
#if defined(OS_WIN) // TODO(port): whittle this down as we port
BookmarkManagerView::RegisterPrefs(local_state);
BrowserView::RegisterBrowserViewPrefs(local_state);
PageInfoWindow::RegisterPrefs(local_state);
TaskManager::RegisterPrefs(local_state);
ExternalProtocolHandler::RegisterPrefs(local_state);
#endif
// User prefs
SessionStartupPref::RegisterUserPrefs(user_prefs);
Browser::RegisterUserPrefs(user_prefs);
PasswordManager::RegisterUserPrefs(user_prefs);
chrome_browser_net::RegisterUserPrefs(user_prefs);
DownloadManager::RegisterUserPrefs(user_prefs);
SSLManager::RegisterUserPrefs(user_prefs);
#if defined(OS_WIN) // TODO(port): whittle this down as we port
BookmarkBarView::RegisterUserPrefs(user_prefs);
BookmarkTableView::RegisterUserPrefs(user_prefs);
#endif
AutofillManager::RegisterUserPrefs(user_prefs);
TabContents::RegisterUserPrefs(user_prefs);
TemplateURLPrepopulateData::RegisterUserPrefs(user_prefs);
WebContents::RegisterUserPrefs(user_prefs);
}
} // namespace browser
<commit_msg>Register more prefs on linux/mac.<commit_after>// Copyright (c) 2006-2008 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/browser_prefs.h"
#include "chrome/browser/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/cache_manager_host.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/external_protocol_handler.h"
#include "chrome/browser/google_url_tracker.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/net/dns_global.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/browser_render_process_host.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/session_startup_pref.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/browser/tab_contents/web_contents.h"
#if defined(OS_WIN) // TODO(port): whittle this down as we port
#include "chrome/browser/task_manager.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/bookmark_manager_view.h"
#include "chrome/browser/views/bookmark_table_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/keyword_editor_view.h"
#include "chrome/browser/views/page_info_window.h"
#endif
namespace browser {
void RegisterAllPrefs(PrefService* user_prefs, PrefService* local_state) {
// Prefs in Local State
Browser::RegisterPrefs(local_state);
CacheManagerHost::RegisterPrefs(local_state);
ExternalProtocolHandler::RegisterPrefs(local_state);
GoogleURLTracker::RegisterPrefs(local_state);
MetricsLog::RegisterPrefs(local_state);
MetricsService::RegisterPrefs(local_state);
SafeBrowsingService::RegisterPrefs(local_state);
browser_shutdown::RegisterPrefs(local_state);
chrome_browser_net::RegisterPrefs(local_state);
#if defined(OS_WIN) // TODO(port): whittle this down as we port
BookmarkManagerView::RegisterPrefs(local_state);
BrowserView::RegisterBrowserViewPrefs(local_state);
PageInfoWindow::RegisterPrefs(local_state);
TaskManager::RegisterPrefs(local_state);
#endif
// User prefs
SessionStartupPref::RegisterUserPrefs(user_prefs);
Browser::RegisterUserPrefs(user_prefs);
PasswordManager::RegisterUserPrefs(user_prefs);
chrome_browser_net::RegisterUserPrefs(user_prefs);
DownloadManager::RegisterUserPrefs(user_prefs);
SSLManager::RegisterUserPrefs(user_prefs);
#if defined(OS_WIN) // TODO(port): whittle this down as we port
BookmarkBarView::RegisterUserPrefs(user_prefs);
BookmarkTableView::RegisterUserPrefs(user_prefs);
#endif
AutofillManager::RegisterUserPrefs(user_prefs);
TabContents::RegisterUserPrefs(user_prefs);
TemplateURLPrepopulateData::RegisterUserPrefs(user_prefs);
WebContents::RegisterUserPrefs(user_prefs);
}
} // namespace browser
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// QA checker that compares a number with an average value plus or minus
// a width
//*-- Author : Yves Schutz (SUBATECH)
//////////////////////////////////////////////////////////////////////////////
// --- ROOT system ---
#include "TDatime.h"
#include "TFolder.h"
// --- Standard library ---
#include <iostream.h>
// --- AliRoot header files ---
#include "AliPHOSQAMeanChecker.h"
#include "AliPHOSQAAlarm.h"
ClassImp(AliPHOSQAMeanChecker)
//____________________________________________________________________________
AliPHOSQAMeanChecker::AliPHOSQAMeanChecker(const char * name) : AliPHOSQAChecker(name,"")
{
// ctor
SetTitle("checks against average value +/- width") ;
}
//____________________________________________________________________________
AliPHOSQAMeanChecker::AliPHOSQAMeanChecker(const char * name, Float_t mean, Float_t rms) : AliPHOSQAChecker(name,"")
{
// ctor
SetTitle("checks against average value +/- width") ;
fMean = mean ;
fRms = rms ;
}
//____________________________________________________________________________
AliPHOSQAMeanChecker::~AliPHOSQAMeanChecker()
{
// dtor
}
//____________________________________________________________________________
TString AliPHOSQAMeanChecker::CheckingOperation()
{
// The user defined checking operation
// Return a non empty string in case the check was not satisfied
TString rv ;
Float_t checked = 0. ;
if ( (fCheckable->HasA() == "I") && (fCheckable->HasA() == "F") ) {
Error("CheckingOperation", "checker %s says you got the wrong checkable %s \n
or the checkable has no value !", GetName(), fCheckable->GetName()) ;
} else {
checked = fCheckable->GetValue();
if (checked < fMean-fRms || checked > fMean+fRms) {
char * tempo = new char[110] ;
sprintf(tempo, "-->Checkable : %s :: Checker : %s :: Message : %f outside bond %f +/- %f\n",
fCheckable->GetName(), GetName(), checked, fMean, fRms) ;
rv = tempo ;
delete [] tempo ;
}
}
return rv ;
}
//____________________________________________________________________________
void AliPHOSQAMeanChecker::Print()
{
// print the name
Info("Print", "Checker : %s : %s : Mean = %f Rms = %f", GetName(), GetTitle(), fMean, fRms) ;
}
<commit_msg>Typo corrected<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// QA checker that compares a number with an average value plus or minus
// a width
//*-- Author : Yves Schutz (SUBATECH)
//////////////////////////////////////////////////////////////////////////////
// --- ROOT system ---
#include "TDatime.h"
#include "TFolder.h"
// --- Standard library ---
#include <iostream.h>
// --- AliRoot header files ---
#include "AliPHOSQAMeanChecker.h"
#include "AliPHOSQAAlarm.h"
ClassImp(AliPHOSQAMeanChecker)
//____________________________________________________________________________
AliPHOSQAMeanChecker::AliPHOSQAMeanChecker(const char * name) : AliPHOSQAChecker(name,"")
{
// ctor
SetTitle("checks against average value +/- width") ;
}
//____________________________________________________________________________
AliPHOSQAMeanChecker::AliPHOSQAMeanChecker(const char * name, Float_t mean, Float_t rms) : AliPHOSQAChecker(name,"")
{
// ctor
SetTitle("checks against average value +/- width") ;
fMean = mean ;
fRms = rms ;
}
//____________________________________________________________________________
AliPHOSQAMeanChecker::~AliPHOSQAMeanChecker()
{
// dtor
}
//____________________________________________________________________________
TString AliPHOSQAMeanChecker::CheckingOperation()
{
// The user defined checking operation
// Return a non empty string in case the check was not satisfied
TString rv ;
Float_t checked = 0. ;
if ( (fCheckable->HasA() == "I") && (fCheckable->HasA() == "F") ) {
Error("CheckingOperation", "checker %s says you got the wrong checkable %s \n or the checkable has no value !", GetName(), fCheckable->GetName()) ;
} else {
checked = fCheckable->GetValue();
if (checked < fMean-fRms || checked > fMean+fRms) {
char * tempo = new char[110] ;
sprintf(tempo, "-->Checkable : %s :: Checker : %s :: Message : %f outside bond %f +/- %f\n",
fCheckable->GetName(), GetName(), checked, fMean, fRms) ;
rv = tempo ;
delete [] tempo ;
}
}
return rv ;
}
//____________________________________________________________________________
void AliPHOSQAMeanChecker::Print()
{
// print the name
Info("Print", "Checker : %s : %s : Mean = %f Rms = %f", GetName(), GetTitle(), fMean, fRms) ;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "addrinfo.h"
#include "tcpsocketimpl.h"
#include "tcpserverimpl.h"
#include "cxxtools/tcpserver.h"
#include "cxxtools/tcpsocket.h"
#include "cxxtools/systemerror.h"
#include "cxxtools/ioerror.h"
#include "cxxtools/log.h"
#include "config.h"
#include <cerrno>
#include <cstring>
#include <cassert>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
log_define("cxxtools.net.tcp")
namespace {
void formatIp(const sockaddr_storage& addr, std::string& str)
{
#ifndef HAVE_INET_NTOP
static cxxtools::Mutex monitor;
cxxtools::MutexLock lock(monitor);
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
const char* p = inet_ntoa(sa->sin_addr);
if (p)
str = p;
else
str.clear();
#else
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
char strbuf[INET6_ADDRSTRLEN + 1];
const char* p = inet_ntop(sa->sin_family, &sa->sin_addr, strbuf, sizeof(strbuf));
str = (p == 0 ? "-" : strbuf);
#endif
}
}
namespace cxxtools {
namespace net {
TcpSocketImpl::TcpSocketImpl(TcpSocket& socket)
: IODeviceImpl(socket)
, _socket(socket)
, _isConnected(false)
, _timeout(Selectable::WaitInfinite)
{
}
TcpSocketImpl::~TcpSocketImpl()
{
assert(_pfd == 0);
}
void TcpSocketImpl::close()
{
log_debug("close socket " << _fd);
IODeviceImpl::close();
_isConnected = false;
}
std::string TcpSocketImpl::getSockAddr() const
{
return "";
}
void TcpSocketImpl::connect(const std::string& ipaddr, unsigned short int port)
{
log_debug("connect to " << ipaddr << " port " << port);
this->beginConnect(ipaddr, port);
this->endConnect();
}
bool TcpSocketImpl::beginConnect(const std::string& ipaddr, unsigned short int port)
{
log_debug("begin connect to " << ipaddr << " port " << port);
AddrInfo ai(ipaddr, port);
log_debug("checking address information");
for (AddrInfo::const_iterator it = ai.begin(); it != ai.end(); ++it)
{
int fd = ::socket(it->ai_family, SOCK_STREAM, 0);
if (fd < 0)
continue;
IODeviceImpl::open(fd, true);
std::memmove(&_peeraddr, it->ai_addr, it->ai_addrlen);
log_debug("created socket " << _fd << " max: " << FD_SETSIZE);
if( ::connect(this->fd(), it->ai_addr, it->ai_addrlen) == 0 )
{
_isConnected = true;
log_debug("connected successfuly");
return true;
}
if(errno != EINPROGRESS)
{
close();
throw SystemError("connect failed");
}
log_debug("connect in progress");
memmove(&_peeraddr, it->ai_addr, it->ai_addrlen);
return false;
}
throw SystemError("invalid address information");
}
void TcpSocketImpl::endConnect()
{
log_debug("ending connect");
if(_pfd)
{
_pfd->events &= ~POLLOUT;
}
if( ! _isConnected )
{
try
{
pollfd pfd;
pfd.fd = this->fd();
pfd.revents = 0;
pfd.events = POLLOUT;
bool ret = this->wait(_timeout, pfd);
if(false == ret)
{
throw IOTimeout();
}
int sockerr;
socklen_t optlen = sizeof(sockerr);
if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 )
{
throw SystemError("getsockopt");
}
if(sockerr != 0)
{
throw SystemError("connect");
}
_isConnected = true;
}
catch(...)
{
close();
throw;
}
}
}
void TcpSocketImpl::accept(TcpServer& server)
{
socklen_t peeraddr_len = sizeof(_peeraddr);
log_debug( "accept " << server.impl().fd() );
_fd = ::accept(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len);
if( _fd < 0 )
throw SystemError("accept");
//TODO ECONNABORTED EINTR EPERM
_isConnected = true;
log_debug( "accepted " << server.impl().fd() << " => " << _fd );
}
/*
size_t TcpSocketImpl::beginRead(char* buffer, size_t n, bool& eof)
{
return 0;
}
size_t TcpSocketImpl::endRead(bool& eof)
{
return 0;
}
size_t TcpSocketImpl::read(char* buffer, size_t count, bool& eof)
{
return 0;
}
size_t TcpSocketImpl::beginWrite(const char* buffer, size_t n)
{
return 0;
}
size_t TcpSocketImpl::endWrite()
{
return 0;
}
size_t TcpSocketImpl::write(const char* buffer, size_t count)
{
return 0;
}
*/
void TcpSocketImpl::initWait(pollfd& pfd)
{
IODeviceImpl::initWait(pfd);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd.events = POLLOUT;
}
}
std::size_t TcpSocketImpl::initializePoll(pollfd* pfd, std::size_t pollSize)
{
assert(pfd != 0);
assert(pollSize >= 1);
log_debug("TcpSocketImpl::initializePoll " << pollSize);
std::size_t ret = IODeviceImpl::initializePoll(pfd, pollSize);
assert(ret == 1);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd->events = POLLOUT;
}
return ret;
}
bool TcpSocketImpl::checkPollEvent()
{
assert(_pfd != 0);
log_debug("checkPollEvent " << _pfd->revents);
if( _pfd->revents & POLLOUT )
{
if( ! _isConnected )
{
_socket.connected.send(_socket);
return true;
}
}
return IODeviceImpl::checkPollEvent();
}
} // namespace net
} // namespace cxxtools
<commit_msg>keep POLLOUT after endConnect when write is scheduled<commit_after>/*
* Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "addrinfo.h"
#include "tcpsocketimpl.h"
#include "tcpserverimpl.h"
#include "cxxtools/tcpserver.h"
#include "cxxtools/tcpsocket.h"
#include "cxxtools/systemerror.h"
#include "cxxtools/ioerror.h"
#include "cxxtools/log.h"
#include "config.h"
#include <cerrno>
#include <cstring>
#include <cassert>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
log_define("cxxtools.net.tcp")
namespace {
void formatIp(const sockaddr_storage& addr, std::string& str)
{
#ifndef HAVE_INET_NTOP
static cxxtools::Mutex monitor;
cxxtools::MutexLock lock(monitor);
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
const char* p = inet_ntoa(sa->sin_addr);
if (p)
str = p;
else
str.clear();
#else
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
char strbuf[INET6_ADDRSTRLEN + 1];
const char* p = inet_ntop(sa->sin_family, &sa->sin_addr, strbuf, sizeof(strbuf));
str = (p == 0 ? "-" : strbuf);
#endif
}
}
namespace cxxtools {
namespace net {
TcpSocketImpl::TcpSocketImpl(TcpSocket& socket)
: IODeviceImpl(socket)
, _socket(socket)
, _isConnected(false)
, _timeout(Selectable::WaitInfinite)
{
}
TcpSocketImpl::~TcpSocketImpl()
{
assert(_pfd == 0);
}
void TcpSocketImpl::close()
{
log_debug("close socket " << _fd);
IODeviceImpl::close();
_isConnected = false;
}
std::string TcpSocketImpl::getSockAddr() const
{
return "";
}
void TcpSocketImpl::connect(const std::string& ipaddr, unsigned short int port)
{
log_debug("connect to " << ipaddr << " port " << port);
this->beginConnect(ipaddr, port);
this->endConnect();
}
bool TcpSocketImpl::beginConnect(const std::string& ipaddr, unsigned short int port)
{
log_debug("begin connect to " << ipaddr << " port " << port);
AddrInfo ai(ipaddr, port);
log_debug("checking address information");
for (AddrInfo::const_iterator it = ai.begin(); it != ai.end(); ++it)
{
int fd = ::socket(it->ai_family, SOCK_STREAM, 0);
if (fd < 0)
continue;
IODeviceImpl::open(fd, true);
std::memmove(&_peeraddr, it->ai_addr, it->ai_addrlen);
log_debug("created socket " << _fd << " max: " << FD_SETSIZE);
if( ::connect(this->fd(), it->ai_addr, it->ai_addrlen) == 0 )
{
_isConnected = true;
log_debug("connected successfuly");
return true;
}
if(errno != EINPROGRESS)
{
close();
throw SystemError("connect failed");
}
log_debug("connect in progress");
memmove(&_peeraddr, it->ai_addr, it->ai_addrlen);
return false;
}
throw SystemError("invalid address information");
}
void TcpSocketImpl::endConnect()
{
log_debug("ending connect");
if(_pfd && ! _socket.wbuf())
{
_pfd->events &= ~POLLOUT;
}
if( ! _isConnected )
{
try
{
pollfd pfd;
pfd.fd = this->fd();
pfd.revents = 0;
pfd.events = POLLOUT;
bool ret = this->wait(_timeout, pfd);
if(false == ret)
{
throw IOTimeout();
}
int sockerr;
socklen_t optlen = sizeof(sockerr);
if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 )
{
throw SystemError("getsockopt");
}
if(sockerr != 0)
{
throw SystemError("connect");
}
_isConnected = true;
}
catch(...)
{
close();
throw;
}
}
}
void TcpSocketImpl::accept(TcpServer& server)
{
socklen_t peeraddr_len = sizeof(_peeraddr);
log_debug( "accept " << server.impl().fd() );
_fd = ::accept(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len);
if( _fd < 0 )
throw SystemError("accept");
//TODO ECONNABORTED EINTR EPERM
_isConnected = true;
log_debug( "accepted " << server.impl().fd() << " => " << _fd );
}
/*
size_t TcpSocketImpl::beginRead(char* buffer, size_t n, bool& eof)
{
return 0;
}
size_t TcpSocketImpl::endRead(bool& eof)
{
return 0;
}
size_t TcpSocketImpl::read(char* buffer, size_t count, bool& eof)
{
return 0;
}
size_t TcpSocketImpl::beginWrite(const char* buffer, size_t n)
{
return 0;
}
size_t TcpSocketImpl::endWrite()
{
return 0;
}
size_t TcpSocketImpl::write(const char* buffer, size_t count)
{
return 0;
}
*/
void TcpSocketImpl::initWait(pollfd& pfd)
{
IODeviceImpl::initWait(pfd);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd.events = POLLOUT;
}
}
std::size_t TcpSocketImpl::initializePoll(pollfd* pfd, std::size_t pollSize)
{
assert(pfd != 0);
assert(pollSize >= 1);
log_debug("TcpSocketImpl::initializePoll " << pollSize);
std::size_t ret = IODeviceImpl::initializePoll(pfd, pollSize);
assert(ret == 1);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd->events = POLLOUT;
}
return ret;
}
bool TcpSocketImpl::checkPollEvent()
{
assert(_pfd != 0);
log_debug("checkPollEvent " << _pfd->revents);
if( _pfd->revents & POLLOUT )
{
if( ! _isConnected )
{
_socket.connected.send(_socket);
return true;
}
}
return IODeviceImpl::checkPollEvent();
}
} // namespace net
} // namespace cxxtools
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#ifdef HAVE_ACCEPT4
#include <sys/types.h>
#include <sys/socket.h>
#endif
#include "tcpsocketimpl.h"
#include "tcpserverimpl.h"
#include "cxxtools/net/tcpserver.h"
#include "cxxtools/net/tcpsocket.h"
#include "cxxtools/systemerror.h"
#include "cxxtools/ioerror.h"
#include "cxxtools/log.h"
#include "config.h"
#include "error.h"
#include <cerrno>
#include <cstring>
#include <cassert>
#include <fcntl.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
log_define("cxxtools.net.tcpsocket.impl")
namespace {
void formatIp(const sockaddr_storage& addr, std::string& str)
{
#ifdef HAVE_INET_NTOP
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
char strbuf[INET6_ADDRSTRLEN + 1];
const char* p = inet_ntop(sa->sin_family, &sa->sin_addr, strbuf, sizeof(strbuf));
str = (p == 0 ? "-" : strbuf);
#else
static cxxtools::Mutex monitor;
cxxtools::MutexLock lock(monitor);
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
const char* p = inet_ntoa(sa->sin_addr);
if (p)
str = p;
else
str.clear();
#endif
}
}
namespace cxxtools {
namespace net {
TcpSocketImpl::TcpSocketImpl(TcpSocket& socket)
: IODeviceImpl(socket)
, _socket(socket)
, _isConnected(false)
{
}
TcpSocketImpl::~TcpSocketImpl()
{
assert(_pfd == 0);
}
void TcpSocketImpl::close()
{
log_debug("close socket " << _fd);
IODeviceImpl::close();
_isConnected = false;
}
std::string TcpSocketImpl::getSockAddr() const
{
struct sockaddr_storage addr;
socklen_t slen = sizeof(addr);
if (::getsockname(fd(), reinterpret_cast<struct sockaddr*>(&addr), &slen) < 0)
throw SystemError("getsockname");
std::string ret;
formatIp(addr, ret);
return ret;
}
std::string TcpSocketImpl::getPeerAddr() const
{
std::string ret;
formatIp(_peeraddr, ret);
return ret;
}
void TcpSocketImpl::connect(const AddrInfo& addrInfo)
{
log_debug("connect");
this->beginConnect(addrInfo);
this->endConnect();
}
int TcpSocketImpl::checkConnect()
{
log_trace("checkConnect");
int sockerr;
socklen_t optlen = sizeof(sockerr);
// check for socket error
if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 )
{
// getsockopt failed
int e = errno;
close();
throw SystemError(e, "getsockopt");
}
if (sockerr == 0)
{
log_debug("connected successfully");
_isConnected = true;
}
return sockerr;
}
void TcpSocketImpl::checkPendingError()
{
if (_connectResult.second)
{
std::pair<int, const char*> p = _connectResult;
_connectResult = std::pair<int, const char*>(0, 0);
if (p.first)
{
throw IOError(getErrnoString(p.first, p.second).c_str());
}
else
{
throw IOError("invalid address information");
}
}
}
std::pair<int, const char*> TcpSocketImpl::tryConnect()
{
log_trace("tryConnect");
assert(_fd == -1);
if (_addrInfoPtr == _addrInfo.impl()->end())
{
log_debug("no more address informations");
return std::pair<int, const char*>(0, "invalid address information");
}
while (true)
{
int fd;
while (true)
{
log_debug("create socket");
fd = ::socket(_addrInfoPtr->ai_family, SOCK_STREAM, 0);
if (fd >= 0)
break;
if (++_addrInfoPtr == _addrInfo.impl()->end())
return std::pair<int, const char*>(errno, "socket");
}
IODeviceImpl::open(fd, true, false);
std::memmove(&_peeraddr, _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen);
log_debug("created socket " << _fd << " max: " << FD_SETSIZE);
if( ::connect(this->fd(), _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen) == 0 )
{
_isConnected = true;
log_debug("connected successfully");
break;
}
if (errno == EINPROGRESS)
{
log_debug("connect in progress");
break;
}
close();
if (++_addrInfoPtr == _addrInfo.impl()->end())
return std::pair<int, const char*>(errno, "connect");
}
return std::pair<int, const char*>(0, 0);
}
bool TcpSocketImpl::beginConnect(const AddrInfo& addrInfo)
{
log_trace("begin connect");
assert(!_isConnected);
_addrInfo = addrInfo;
_addrInfoPtr = _addrInfo.impl()->begin();
_connectResult = tryConnect();
checkPendingError();
return _isConnected;
}
void TcpSocketImpl::endConnect()
{
log_trace("ending connect");
if(_pfd && ! _socket.wbuf())
{
_pfd->events &= ~POLLOUT;
}
checkPendingError();
if( _isConnected )
return;
try
{
while (true)
{
pollfd pfd;
pfd.fd = this->fd();
pfd.revents = 0;
pfd.events = POLLOUT;
log_debug("wait " << timeout() << " ms");
bool avail = this->wait(this->timeout(), pfd);
if (avail)
{
// something has happened
int sockerr = checkConnect();
if (_isConnected)
return;
if (++_addrInfoPtr == _addrInfo.impl()->end())
{
// no more addrInfo - propagate error
throw IOError(getErrnoString(sockerr, "connect").c_str());
}
}
else if (++_addrInfoPtr == _addrInfo.impl()->end())
{
log_debug("timeout");
throw IOTimeout();
}
close();
_connectResult = tryConnect();
if (_isConnected)
return;
checkPendingError();
}
}
catch(...)
{
close();
throw;
}
}
void TcpSocketImpl::accept(const TcpServer& server, bool closeOnExec)
{
socklen_t peeraddr_len = sizeof(_peeraddr);
log_debug( "accept " << server.impl().fd() );
#ifdef HAVE_ACCEPT4
int fd = SOCK_NONBLOCK;
if (closeOnExec)
fd |= SOCK_CLOEXEC;
_fd = ::accept4(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len, SOCK_NONBLOCK | SOCK_CLOEXEC);
#else
_fd = ::accept(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len);
#endif
if( _fd < 0 )
throw SystemError("accept");
#ifdef HAVE_ACCEPT4
IODeviceImpl::open(_fd, false, false);
#else
IODeviceImpl::open(_fd, true, closeOnExec);
#endif
//TODO ECONNABORTED EINTR EPERM
_isConnected = true;
log_debug( "accepted " << server.impl().fd() << " => " << _fd );
}
void TcpSocketImpl::initWait(pollfd& pfd)
{
IODeviceImpl::initWait(pfd);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd.events = POLLOUT;
}
}
std::size_t TcpSocketImpl::initializePoll(pollfd* pfd, std::size_t pollSize)
{
assert(pfd != 0);
assert(pollSize >= 1);
log_debug("TcpSocketImpl::initializePoll " << pollSize << "; fd=" << _fd);
std::size_t ret = IODeviceImpl::initializePoll(pfd, pollSize);
assert(ret == 1);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd->events = POLLOUT;
}
return ret;
}
bool TcpSocketImpl::checkPollEvent(pollfd& pfd)
{
log_debug("checkPollEvent " << pfd.revents);
if( _isConnected )
return IODeviceImpl::checkPollEvent(pfd);
if ( pfd.revents & POLLERR )
{
AddrInfoImpl::const_iterator ptr = _addrInfoPtr;
if (++ptr == _addrInfo.impl()->end())
{
// not really connected but error
// end of addrinfo list means that no working addrinfo was found
log_debug("no more addrinfos found");
_socket.connected.send(_socket);
return true;
}
else
{
_addrInfoPtr = ptr;
close();
_connectResult = tryConnect();
if (_isConnected || _connectResult.second)
{
// immediate success or error
log_debug("connected successfully");
_socket.connected.send(_socket);
}
else
// by closing the previous file handle _pfd is set to 0.
// creating a new socket in tryConnect may also change the value of fd.
initializePoll(&pfd, 1);
return _isConnected;
}
}
else if( pfd.revents & POLLOUT )
{
int sockerr = checkConnect();
if (_isConnected)
{
_socket.connected.send(_socket);
return true;
}
// something went wrong - look for next addrInfo
log_debug("sockerr is " << sockerr << " try next");
if (++_addrInfoPtr == _addrInfo.impl()->end())
{
// no more addrInfo - propagate error
_connectResult = std::pair<int, const char*>(sockerr, "connect");
_socket.connected.send(_socket);
return true;
}
_connectResult = tryConnect();
if (_isConnected)
{
_socket.connected.send(_socket);
return true;
}
}
return false;
}
} // namespace net
} // namespace cxxtools
<commit_msg>accept gets a inherit flag instead of closeOnExec; forgot to fix that in tcpsocketimpl.cpp<commit_after>/*
* Copyright (C) 2009 Marc Boris Duerner, Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#ifdef HAVE_ACCEPT4
#include <sys/types.h>
#include <sys/socket.h>
#endif
#include "tcpsocketimpl.h"
#include "tcpserverimpl.h"
#include "cxxtools/net/tcpserver.h"
#include "cxxtools/net/tcpsocket.h"
#include "cxxtools/systemerror.h"
#include "cxxtools/ioerror.h"
#include "cxxtools/log.h"
#include "config.h"
#include "error.h"
#include <cerrno>
#include <cstring>
#include <cassert>
#include <fcntl.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
log_define("cxxtools.net.tcpsocket.impl")
namespace {
void formatIp(const sockaddr_storage& addr, std::string& str)
{
#ifdef HAVE_INET_NTOP
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
char strbuf[INET6_ADDRSTRLEN + 1];
const char* p = inet_ntop(sa->sin_family, &sa->sin_addr, strbuf, sizeof(strbuf));
str = (p == 0 ? "-" : strbuf);
#else
static cxxtools::Mutex monitor;
cxxtools::MutexLock lock(monitor);
const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr);
const char* p = inet_ntoa(sa->sin_addr);
if (p)
str = p;
else
str.clear();
#endif
}
}
namespace cxxtools {
namespace net {
TcpSocketImpl::TcpSocketImpl(TcpSocket& socket)
: IODeviceImpl(socket)
, _socket(socket)
, _isConnected(false)
{
}
TcpSocketImpl::~TcpSocketImpl()
{
assert(_pfd == 0);
}
void TcpSocketImpl::close()
{
log_debug("close socket " << _fd);
IODeviceImpl::close();
_isConnected = false;
}
std::string TcpSocketImpl::getSockAddr() const
{
struct sockaddr_storage addr;
socklen_t slen = sizeof(addr);
if (::getsockname(fd(), reinterpret_cast<struct sockaddr*>(&addr), &slen) < 0)
throw SystemError("getsockname");
std::string ret;
formatIp(addr, ret);
return ret;
}
std::string TcpSocketImpl::getPeerAddr() const
{
std::string ret;
formatIp(_peeraddr, ret);
return ret;
}
void TcpSocketImpl::connect(const AddrInfo& addrInfo)
{
log_debug("connect");
this->beginConnect(addrInfo);
this->endConnect();
}
int TcpSocketImpl::checkConnect()
{
log_trace("checkConnect");
int sockerr;
socklen_t optlen = sizeof(sockerr);
// check for socket error
if( ::getsockopt(this->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0 )
{
// getsockopt failed
int e = errno;
close();
throw SystemError(e, "getsockopt");
}
if (sockerr == 0)
{
log_debug("connected successfully");
_isConnected = true;
}
return sockerr;
}
void TcpSocketImpl::checkPendingError()
{
if (_connectResult.second)
{
std::pair<int, const char*> p = _connectResult;
_connectResult = std::pair<int, const char*>(0, 0);
if (p.first)
{
throw IOError(getErrnoString(p.first, p.second).c_str());
}
else
{
throw IOError("invalid address information");
}
}
}
std::pair<int, const char*> TcpSocketImpl::tryConnect()
{
log_trace("tryConnect");
assert(_fd == -1);
if (_addrInfoPtr == _addrInfo.impl()->end())
{
log_debug("no more address informations");
return std::pair<int, const char*>(0, "invalid address information");
}
while (true)
{
int fd;
while (true)
{
log_debug("create socket");
fd = ::socket(_addrInfoPtr->ai_family, SOCK_STREAM, 0);
if (fd >= 0)
break;
if (++_addrInfoPtr == _addrInfo.impl()->end())
return std::pair<int, const char*>(errno, "socket");
}
IODeviceImpl::open(fd, true, false);
std::memmove(&_peeraddr, _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen);
log_debug("created socket " << _fd << " max: " << FD_SETSIZE);
if( ::connect(this->fd(), _addrInfoPtr->ai_addr, _addrInfoPtr->ai_addrlen) == 0 )
{
_isConnected = true;
log_debug("connected successfully");
break;
}
if (errno == EINPROGRESS)
{
log_debug("connect in progress");
break;
}
close();
if (++_addrInfoPtr == _addrInfo.impl()->end())
return std::pair<int, const char*>(errno, "connect");
}
return std::pair<int, const char*>(0, 0);
}
bool TcpSocketImpl::beginConnect(const AddrInfo& addrInfo)
{
log_trace("begin connect");
assert(!_isConnected);
_addrInfo = addrInfo;
_addrInfoPtr = _addrInfo.impl()->begin();
_connectResult = tryConnect();
checkPendingError();
return _isConnected;
}
void TcpSocketImpl::endConnect()
{
log_trace("ending connect");
if(_pfd && ! _socket.wbuf())
{
_pfd->events &= ~POLLOUT;
}
checkPendingError();
if( _isConnected )
return;
try
{
while (true)
{
pollfd pfd;
pfd.fd = this->fd();
pfd.revents = 0;
pfd.events = POLLOUT;
log_debug("wait " << timeout() << " ms");
bool avail = this->wait(this->timeout(), pfd);
if (avail)
{
// something has happened
int sockerr = checkConnect();
if (_isConnected)
return;
if (++_addrInfoPtr == _addrInfo.impl()->end())
{
// no more addrInfo - propagate error
throw IOError(getErrnoString(sockerr, "connect").c_str());
}
}
else if (++_addrInfoPtr == _addrInfo.impl()->end())
{
log_debug("timeout");
throw IOTimeout();
}
close();
_connectResult = tryConnect();
if (_isConnected)
return;
checkPendingError();
}
}
catch(...)
{
close();
throw;
}
}
void TcpSocketImpl::accept(const TcpServer& server, bool inherit)
{
socklen_t peeraddr_len = sizeof(_peeraddr);
log_debug( "accept " << server.impl().fd() );
#ifdef HAVE_ACCEPT4
int fd = SOCK_NONBLOCK;
if (!inherit)
fd |= SOCK_CLOEXEC;
_fd = ::accept4(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len, SOCK_NONBLOCK | SOCK_CLOEXEC);
#else
_fd = ::accept(server.impl().fd(), reinterpret_cast <struct sockaddr*>(&_peeraddr), &peeraddr_len);
#endif
if( _fd < 0 )
throw SystemError("accept");
#ifdef HAVE_ACCEPT4
IODeviceImpl::open(_fd, false, false);
#else
IODeviceImpl::open(_fd, true, inherit);
#endif
//TODO ECONNABORTED EINTR EPERM
_isConnected = true;
log_debug( "accepted " << server.impl().fd() << " => " << _fd );
}
void TcpSocketImpl::initWait(pollfd& pfd)
{
IODeviceImpl::initWait(pfd);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd.events = POLLOUT;
}
}
std::size_t TcpSocketImpl::initializePoll(pollfd* pfd, std::size_t pollSize)
{
assert(pfd != 0);
assert(pollSize >= 1);
log_debug("TcpSocketImpl::initializePoll " << pollSize << "; fd=" << _fd);
std::size_t ret = IODeviceImpl::initializePoll(pfd, pollSize);
assert(ret == 1);
if( ! _isConnected )
{
log_debug("not connected, setting POLLOUT ");
pfd->events = POLLOUT;
}
return ret;
}
bool TcpSocketImpl::checkPollEvent(pollfd& pfd)
{
log_debug("checkPollEvent " << pfd.revents);
if( _isConnected )
return IODeviceImpl::checkPollEvent(pfd);
if ( pfd.revents & POLLERR )
{
AddrInfoImpl::const_iterator ptr = _addrInfoPtr;
if (++ptr == _addrInfo.impl()->end())
{
// not really connected but error
// end of addrinfo list means that no working addrinfo was found
log_debug("no more addrinfos found");
_socket.connected.send(_socket);
return true;
}
else
{
_addrInfoPtr = ptr;
close();
_connectResult = tryConnect();
if (_isConnected || _connectResult.second)
{
// immediate success or error
log_debug("connected successfully");
_socket.connected.send(_socket);
}
else
// by closing the previous file handle _pfd is set to 0.
// creating a new socket in tryConnect may also change the value of fd.
initializePoll(&pfd, 1);
return _isConnected;
}
}
else if( pfd.revents & POLLOUT )
{
int sockerr = checkConnect();
if (_isConnected)
{
_socket.connected.send(_socket);
return true;
}
// something went wrong - look for next addrInfo
log_debug("sockerr is " << sockerr << " try next");
if (++_addrInfoPtr == _addrInfo.impl()->end())
{
// no more addrInfo - propagate error
_connectResult = std::pair<int, const char*>(sockerr, "connect");
_socket.connected.send(_socket);
return true;
}
_connectResult = tryConnect();
if (_isConnected)
{
_socket.connected.send(_socket);
return true;
}
}
return false;
}
} // namespace net
} // namespace cxxtools
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "app/app_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_WIN)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll";
#elif defined(OS_MACOSX)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin";
#elif defined(OS_LINUX)
static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so";
#endif
using npapi_test::kTestCompleteCookie;
using npapi_test::kTestCompleteSuccess;
// Helper class pepper NPAPI tests.
class PepperTester : public NPAPITesterBase {
protected:
PepperTester() : NPAPITesterBase(kPepperTestPluginName) {}
virtual void SetUp() {
// TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox.
launch_arguments_.AppendSwitch(switches::kNoSandbox);
launch_arguments_.AppendSwitch(switches::kInternalPepper);
launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin);
// Use Mesa software renderer so it can run on testbots without any
// graphics hardware.
launch_arguments_.AppendSwitchWithValue(switches::kUseGL, "osmesa");
NPAPITesterBase::SetUp();
}
};
// Test that a pepper 3d plugin loads and renders.
// TODO(alokp): Enable the test after making sure it works on all platforms
// and buildbots have OpenGL support.
#if defined(OS_WIN)
TEST_F(PepperTester, Pepper3D) {
const FilePath dir(FILE_PATH_LITERAL("pepper"));
const FilePath file(FILE_PATH_LITERAL("pepper_3d.html"));
GURL url = ui_test_utils::GetTestUrl(dir, file);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
WaitForFinish("pepper_3d", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
#endif
<commit_msg>Marked Pepper3D test as FAILS since it is failing on buildbots but passes on trybots. BUG=46662 TBR=apatrick@chromium.org Review URL: http://codereview.chromium.org/3072006<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "app/app_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_WIN)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll";
#elif defined(OS_MACOSX)
static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin";
#elif defined(OS_LINUX)
static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so";
#endif
using npapi_test::kTestCompleteCookie;
using npapi_test::kTestCompleteSuccess;
// Helper class pepper NPAPI tests.
class PepperTester : public NPAPITesterBase {
protected:
PepperTester() : NPAPITesterBase(kPepperTestPluginName) {}
virtual void SetUp() {
// TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox.
launch_arguments_.AppendSwitch(switches::kNoSandbox);
launch_arguments_.AppendSwitch(switches::kInternalPepper);
launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin);
// Use Mesa software renderer so it can run on testbots without any
// graphics hardware.
launch_arguments_.AppendSwitchWithValue(switches::kUseGL, "osmesa");
NPAPITesterBase::SetUp();
}
};
// Test that a pepper 3d plugin loads and renders.
// TODO(alokp): Enable the test after making sure it works on all platforms
// and buildbots have OpenGL support.
#if defined(OS_WIN)
// Marked as FAILS (46662): failing on buildbots but passes on trybots.
TEST_F(PepperTester, FAILS_Pepper3D) {
const FilePath dir(FILE_PATH_LITERAL("pepper"));
const FilePath file(FILE_PATH_LITERAL("pepper_3d.html"));
GURL url = ui_test_utils::GetTestUrl(dir, file);
ASSERT_NO_FATAL_FAILURE(NavigateToURL(url));
WaitForFinish("pepper_3d", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_max_timeout_ms());
}
#endif
<|endoftext|> |
<commit_before>#include "PowerUp.hpp"
// Implementation headers
#include "Ghost.hpp"
#include "client.hpp"
static void setScared(Ghost*, std::map<GameSprite*, ActorMovement*> &,
AnimationFilm*);
static void ScaredToNormal(Ghost *ghost,
std::map<GameSprite*, ActorMovement*> &akmovs,
AnimationFilm *film);
struct GhostRevertTaskData : public TaskData {
_pcoca *pkoka;
}; // struct GhostRevertTaskData
struct GhostRevertTask : public Task {
void operator()(TaskData *);
Task &operator++(void);
GhostRevertTask(timestamp_t time); ~GhostRevertTask(void);
}; // struct GhostRevertTask
void powerup_coca(Sprite *p, Sprite *stoocker, void *c) {
if (p->IsVisible()) if (c) {
_pcoca *pkoka = CAST(_pcoca*, c);
p->SetVisibility(false); // powerup
// Change ghosts' status, animation film and anim delay
AnimationFilm *scared_film = pkoka->filmhold->
GetFilm("snailyeat");
std::map<GameSprite*, ActorMovement*> &akmovs =
*pkoka->akmovs;
setScared(pkoka->ghost->stalker, akmovs, scared_film);
setScared(pkoka->ghost->random, akmovs, scared_film);
setScared(pkoka->ghost->retard, akmovs, scared_film);
setScared(pkoka->ghost->kieken, akmovs, scared_film);
GhostRevertTaskData *grtd = new GhostRevertTaskData;
grtd->pkoka = pkoka;
pkoka->sch->_register(
new GhostRevertTask(getCurrentTime() + 5000),
grtd);
}
} // powerup_coca
static void setScared(Ghost *ghost,
std::map<GameSprite*, ActorMovement*> &akmovs,
AnimationFilm *film)
{
if(ghost->GetState() == NORMAL) {
ghost->SetState(SCARED);
ghost->setFilm(film);
akmovs[ghost]->setDelay(25);
}
} // setScared
static void ScaredToNormal(Ghost *ghost,
std::map<GameSprite*, ActorMovement*> &akmovs,
AnimationFilm *film)
{
if(ghost->GetState() == SCARED) {
ghost->SetState(NORMAL);
ghost->setFilm(film);
akmovs[ghost]->setDelay(15);
}
}
GhostRevertTask::GhostRevertTask(timestamp_t time) :
Task(time, false) { }
GhostRevertTask::~GhostRevertTask(void) { }
void GhostRevertTask::operator()(TaskData *d) {
db("Task Data");
_pcoca *pkoka = dynamic_cast<GhostRevertTaskData*>(d)->pkoka;
// Change ghosts' status, animation film and anim delay
AnimationFilm *_film = pkoka->filmhold->
GetFilm("snaily");
AnimationFilm *l_film = pkoka->filmhold->
GetFilm("snailyl");
AnimationFilm *d_film = pkoka->filmhold->
GetFilm("snailyd");
AnimationFilm *b_film = pkoka->filmhold->
GetFilm("snailyb");
std::map<GameSprite*, ActorMovement*> &akmovs =
*pkoka->akmovs;
ScaredToNormal(pkoka->ghost->stalker, akmovs, _film);
ScaredToNormal(pkoka->ghost->random, akmovs, d_film);
ScaredToNormal(pkoka->ghost->retard, akmovs, b_film);
ScaredToNormal(pkoka->ghost->kieken, akmovs, l_film);
} // GhostRevertTask::()
Task &GhostRevertTask::operator++(void) { return *this; }
void Ghost_collision_callback(Sprite *ghost, Sprite *pacman, void *c) {
Ghost* gs = dynamic_cast<Ghost*>(ghost);
if(gs->GetState() == SCARED) { if (c) {
// It gets called : D
_gcoca *gkoka = CAST(_gcoca*, c);
AnimationFilm *retreat_film = gkoka->filmhold->
GetFilm("snailyate");
std::map<GameSprite*, ActorMovement*> &akmovs =
*gkoka->akmovs;
gs->SetState(RETREAT);
gs->setFilm(retreat_film);
akmovs[gs]->setDelay(17);
CollisionChecker::Singleton()->Cancel(gkoka->left_right, gs);
CollisionChecker::Singleton()->Register(gkoka->down, gs);
} else
db("Warning: Useless pacman-ghost callback");
}
} // collision_callback
void ghost_uneating_callback(Sprite *waypoint, Sprite *_ghost, void *c) {
} // ghost_uneating_callback
<commit_msg>haha assertion times<commit_after>#include "PowerUp.hpp"
// Implementation headers
#include "Ghost.hpp"
#include "client.hpp"
static void setScared(Ghost*, std::map<GameSprite*, ActorMovement*> &,
AnimationFilm*);
static void ScaredToNormal(Ghost *ghost,
std::map<GameSprite*, ActorMovement*> &akmovs,
AnimationFilm *film);
struct GhostRevertTaskData : public TaskData {
_pcoca *pkoka;
}; // struct GhostRevertTaskData
struct GhostRevertTask : public Task {
void operator()(TaskData *);
Task &operator++(void);
GhostRevertTask(timestamp_t time); ~GhostRevertTask(void);
}; // struct GhostRevertTask
void powerup_coca(Sprite *p, Sprite *stoocker, void *c) {
if (p->IsVisible()) if (c) {
_pcoca *pkoka = CAST(_pcoca*, c);
p->SetVisibility(false); // powerup
// Change ghosts' status, animation film and anim delay
AnimationFilm *scared_film = pkoka->filmhold->
GetFilm("snailyeat");
std::map<GameSprite*, ActorMovement*> &akmovs =
*pkoka->akmovs;
setScared(pkoka->ghost->stalker, akmovs, scared_film);
setScared(pkoka->ghost->random, akmovs, scared_film);
setScared(pkoka->ghost->retard, akmovs, scared_film);
setScared(pkoka->ghost->kieken, akmovs, scared_film);
GhostRevertTaskData *grtd = new GhostRevertTaskData;
grtd->pkoka = pkoka;
pkoka->sch->_register(
new GhostRevertTask(getCurrentTime() + 5000),
grtd);
}
} // powerup_coca
static void setScared(Ghost *ghost,
std::map<GameSprite*, ActorMovement*> &akmovs,
AnimationFilm *film)
{
if(ghost->GetState() == NORMAL) {
ghost->SetState(SCARED);
ghost->setFilm(film);
akmovs[ghost]->setDelay(25);
}
} // setScared
static void ScaredToNormal(Ghost *ghost,
std::map<GameSprite*, ActorMovement*> &akmovs,
AnimationFilm *film)
{
if(ghost->GetState() == SCARED) {
ghost->SetState(NORMAL);
ghost->setFilm(film);
akmovs[ghost]->setDelay(15);
}
}
GhostRevertTask::GhostRevertTask(timestamp_t time) :
Task(time, false) { }
GhostRevertTask::~GhostRevertTask(void) { }
void GhostRevertTask::operator()(TaskData *d) {
db("Task Data");
_pcoca *pkoka = dynamic_cast<GhostRevertTaskData*>(d)->pkoka;
// Change ghosts' status, animation film and anim delay
AnimationFilm *_film = pkoka->filmhold->
GetFilm("snaily");
AnimationFilm *l_film = pkoka->filmhold->
GetFilm("snailyl");
AnimationFilm *d_film = pkoka->filmhold->
GetFilm("snailyd");
AnimationFilm *b_film = pkoka->filmhold->
GetFilm("snailyb");
std::map<GameSprite*, ActorMovement*> &akmovs =
*pkoka->akmovs;
ScaredToNormal(pkoka->ghost->stalker, akmovs, _film);
ScaredToNormal(pkoka->ghost->random, akmovs, d_film);
ScaredToNormal(pkoka->ghost->retard, akmovs, b_film);
ScaredToNormal(pkoka->ghost->kieken, akmovs, l_film);
} // GhostRevertTask::()
Task &GhostRevertTask::operator++(void) { return *this; }
void Ghost_collision_callback(Sprite *ghost, Sprite *pacman, void *c) {
Ghost* gs = dynamic_cast<Ghost*>(ghost);
if(gs->GetState() == SCARED) { if (c) {
// It gets called : D
_gcoca *gkoka = CAST(_gcoca*, c);
AnimationFilm *retreat_film = gkoka->filmhold->
GetFilm("snailyate");
std::map<GameSprite*, ActorMovement*> &akmovs =
*gkoka->akmovs;
gs->SetState(RETREAT);
gs->setFilm(retreat_film);
akmovs[gs]->setDelay(17);
CollisionChecker::Singleton()->Cancel(gkoka->left_right, gs);
CollisionChecker::Singleton()->Register(gkoka->down, gs);
} else
db("Warning: Useless pacman-ghost callback");
}
} // collision_callback
void ghost_uneating_callback(Sprite *waypoint, Sprite *_ghost, void *c) {
Ghost* gs = dynamic_cast<Ghost*>(_ghost);
if(gs->GetState() == RETREAT) if(c){
AnimationFilm *film;
_gcoca *gkoka = CAST(_gcoca*, c);
if(gs == gkoka->ghost->stalker)
film = gkoka->filmhold->GetFilm("snaily");
else if(gs == gkoka->ghost->random)
film = gkoka->filmhold->GetFilm("snailyl");
else if(gs == gkoka->ghost->retard)
film = gkoka->filmhold->GetFilm("snailyd");
else film = gkoka->filmhold->GetFilm("snailyb");
gs->SetState(NORMAL);
gs->setFilm(film);
(*gkoka->akmovs)[gs]->pressed(ActorMovement::UP, getCurrentTime());
CollisionChecker::Singleton()->Cancel(gkoka->down, gs);
CollisionChecker::Singleton()->Register(gkoka->left_right, gs);
}
} // ghost_uneating_callback
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "kangaru/kangaru.hpp"
/**
* This example explains advanced use of kangaru and it's components.
* It covers overriding services
*/
using std::cout;
using std::endl;
struct Wand {
virtual void doTrick() = 0;
};
struct MagicWand : Wand {
void doTrick() override {
cout << "It's doing magic tricks!" << endl;
}
};
struct FireWand : MagicWand {
void doTrick() override {
cout << "It's doing fire tricks!" << endl;
}
};
struct LavaWand : FireWand {
void doTrick() override {
cout << "It's doing lava tricks!" << endl;
}
};
struct Trickster {
Trickster(Wand& _wand) : wand{_wand} {}
void doTrick() {
wand.doTrick();
}
private:
Wand& wand;
};
struct Wizard {
Wizard(MagicWand& _wand) : wand{_wand} {}
void doTrick() {
wand.doTrick();
}
private:
MagicWand& wand;
};
struct FireMage {
FireMage(FireWand& _wand) : wand{_wand} {}
void doTrick() {
wand.doTrick();
}
private:
FireWand& wand;
};
struct MagicWandService;
struct WandService : kgr::AbstractService<Wand>, kgr::Default<MagicWandService> {};
struct MagicWandService : kgr::SingleService<MagicWand>, kgr::Overrides<WandService> {};
struct FireWandService : kgr::SingleService<FireWand>, kgr::Overrides<MagicWandService> {};
struct LavaWandService : kgr::SingleService<LavaWand>, kgr::Overrides<FireWandService, MagicWandService> {};
struct TricksterService : kgr::Service<Trickster, kgr::Dependency<WandService>> {};
struct WizardService : kgr::Service<Wizard, kgr::Dependency<MagicWandService>> {};
struct FireMageService : kgr::Service<FireMage, kgr::Dependency<FireWandService>> {};
int main()
{
kgr::Container container;
// Here, because of the default service type of WandService, MagicWandService is chosen.
// MagicWand is the first, because it's the highest non-abstract service in the hierarchy.
// If WandService didn't had that default service type, it would be a runtime error.
container.service<WandService>();
// FireWand is the second, because it's the second service in the hierarchy.
container.service<FireWandService>();
// LavaWand is the last, because it's the last service in the hierarchy.
container.service<LavaWandService>();
auto trickster = container.service<TricksterService>();
auto wizard = container.service<WizardService>();
auto fireMage = container.service<FireMageService>();
// The trickster will show "It's doing magic tricks!"
// because the only service that overrides Wand is MagicWand.
// Even if another service is overriding MagicWand, it does not overrides Wand.
trickster.doTrick();
// The trickster will show "It's doing lava tricks!"
// because LavaWand overrides MagicWand, which was the Wizard's dependency.
// Even if FireWand is overriding MagicWand, LavaWand is lower in the hierarchy,
// which grants it priority.
// A misconfigured hierarchy may lead to incorrect result. Invert instance calls and see by yourself.
wizard.doTrick();
// The trickster will show "It's doing lava tricks!"
// because LavaWand is overriding FireWand.
fireMage.doTrick();
return 0;
}
<commit_msg>added spaces<commit_after>#include <iostream>
#include <string>
#include "kangaru/kangaru.hpp"
/**
* This example explains advanced use of kangaru and it's components.
* It covers overriding services
*/
using std::cout;
using std::endl;
struct Wand {
virtual void doTrick() = 0;
};
struct MagicWand : Wand {
void doTrick() override {
cout << "It's doing magic tricks!" << endl;
}
};
struct FireWand : MagicWand {
void doTrick() override {
cout << "It's doing fire tricks!" << endl;
}
};
struct LavaWand : FireWand {
void doTrick() override {
cout << "It's doing lava tricks!" << endl;
}
};
struct Trickster {
Trickster(Wand& _wand) : wand{_wand} {}
void doTrick() {
wand.doTrick();
}
private:
Wand& wand;
};
struct Wizard {
Wizard(MagicWand& _wand) : wand{_wand} {}
void doTrick() {
wand.doTrick();
}
private:
MagicWand& wand;
};
struct FireMage {
FireMage(FireWand& _wand) : wand{_wand} {}
void doTrick() {
wand.doTrick();
}
private:
FireWand& wand;
};
struct MagicWandService;
struct WandService : kgr::AbstractService<Wand>, kgr::Default<MagicWandService> {};
struct MagicWandService : kgr::SingleService<MagicWand>, kgr::Overrides<WandService> {};
struct FireWandService : kgr::SingleService<FireWand>, kgr::Overrides<MagicWandService> {};
struct LavaWandService : kgr::SingleService<LavaWand>, kgr::Overrides<FireWandService, MagicWandService> {};
struct TricksterService : kgr::Service<Trickster, kgr::Dependency<WandService>> {};
struct WizardService : kgr::Service<Wizard, kgr::Dependency<MagicWandService>> {};
struct FireMageService : kgr::Service<FireMage, kgr::Dependency<FireWandService>> {};
int main()
{
kgr::Container container;
// Here, because of the default service type of WandService, MagicWandService is chosen.
// MagicWand is the first, because it's the highest non-abstract service in the hierarchy.
// If WandService didn't had that default service type, it would be a runtime error.
container.service<WandService>();
// FireWand is the second, because it's the second service in the hierarchy.
container.service<FireWandService>();
// LavaWand is the last, because it's the last service in the hierarchy.
container.service<LavaWandService>();
auto trickster = container.service<TricksterService>();
auto wizard = container.service<WizardService>();
auto fireMage = container.service<FireMageService>();
// The trickster will show "It's doing magic tricks!"
// because the only service that overrides Wand is MagicWand.
// Even if another service is overriding MagicWand, it does not overrides Wand.
trickster.doTrick();
// The trickster will show "It's doing lava tricks!"
// because LavaWand overrides MagicWand, which was the Wizard's dependency.
// Even if FireWand is overriding MagicWand, LavaWand is lower in the hierarchy,
// which grants it priority.
// A misconfigured hierarchy may lead to incorrect result. Invert instance calls and see by yourself.
wizard.doTrick();
// The trickster will show "It's doing lava tricks!"
// because LavaWand is overriding FireWand.
fireMage.doTrick();
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/test:$Id$
// Author: Rene Brun 19/01/97
////////////////////////////////////////////////////////////////////////
//
// A simple example with a ROOT tree
// =================================
//
// This program creates :
// - a ROOT file
// - a tree
// Additional arguments can be passed to the program to control the flow
// of execution. (see comments describing the arguments in the code).
// Event nevent comp split fill
// All arguments are optional. Default is:
// Event 400 1 1 1
//
// In this example, the tree consists of one single "super branch"
// The statement ***tree->Branch("event", &event, 64000,split);*** below
// will parse the structure described in Event.h and will make
// a new branch for each data member of the class if split is set to 1.
// - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
// fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
// - 3 branches corresponding to the members of the subobject EventHeader.
// - one branch for each data member of the class Track of TClonesArray.
// - one branch for the TRefArray of high Pt tracks
// - one branch for the TRefArray of muon tracks
// - one branch for the reference pointer to the last track
// - one branch for the object fH (histogram of class TH1F).
//
// if split = 0 only one single branch is created and the complete event
// is serialized in one single buffer.
// if split = -2 the event is split using the old TBranchObject mechanism
// if split = -1 the event is streamed using the old TBranchObject mechanism
// if split > 0 the event is split using the new TBranchElement mechanism.
//
// if comp = 0 no compression at all.
// if comp = 1 event is compressed.
// if comp = 2 same as 1. In addition branches with floats in the TClonesArray
// are also compressed.
// The 4th argument fill can be set to 0 if one wants to time
// the percentage of time spent in creating the event structure and
// not write the event in the file.
// In this example, one loops over nevent events.
// The branch "event" is created at the first event.
// The branch address is set for all other events.
// For each event, the event header is filled and ntrack tracks
// are generated and added to the TClonesArray list.
// For each event the event histogram is saved as well as the list
// of all tracks.
//
// The two TRefArray contain only references to the original tracks owned by
// the TClonesArray fTracks.
//
// The number of events can be given as the first argument to the program.
// By default 400 events are generated.
// The compression option can be activated/deactivated via the second argument.
//
// ---Running/Linking instructions----
// This program consists of the following files and procedures.
// - Event.h event class description
// - Event.C event class implementation
// - MainEvent.C the main program to demo this class might be used (this file)
// - EventCint.C the CINT dictionary for the event and Track classes
// this file is automatically generated by rootcint (see Makefile),
// when the class definition in Event.h is modified.
//
// ---Analyzing the Event.root file with the interactive root
// example of a simple session
// Root > TFile f("Event.root")
// Root > T.Draw("fNtrack") //histogram the number of tracks per event
// Root > T.Draw("fPx") //histogram fPx for all tracks in all events
// Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
// //scatter-plot for x versus y of first point of each track
// Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram
//
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "Event.h"
//______________________________________________________________________________
int main(int argc, char **argv)
{
Int_t nevent = 400; // by default create 400 events
Int_t comp = 1; // by default file is compressed
Int_t split = 1; // by default, split Event in sub branches
Int_t write = 1; // by default the tree is filled
Int_t hfill = 0; // by default histograms are not filled
Int_t read = 0;
Int_t arg4 = 1;
Int_t arg5 = 600; //default number of tracks per event
Int_t netf = 0;
Int_t punzip = 0;
if (argc > 1) nevent = atoi(argv[1]);
if (argc > 2) comp = atoi(argv[2]);
if (argc > 3) split = atoi(argv[3]);
if (argc > 4) arg4 = atoi(argv[4]);
if (argc > 5) arg5 = atoi(argv[5]);
if (arg4 == 0) { write = 0; hfill = 0; read = 1;}
if (arg4 == 1) { write = 1; hfill = 0;}
if (arg4 == 2) { write = 0; hfill = 0;}
if (arg4 == 10) { write = 0; hfill = 1;}
if (arg4 == 11) { write = 1; hfill = 1;}
if (arg4 == 20) { write = 0; read = 1;} //read sequential
if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping
if (arg4 == 25) { write = 0; read = 2;} //read random
if (arg4 >= 30) { netf = 1; } //use TNetFile
if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential
if (arg4 == 35) { write = 0; read = 2;} //netfile + read random
if (arg4 == 36) { write = 1; } //netfile + write sequential
Int_t branchStyle = 1; //new style by default
if (split < 0) {branchStyle = 0; split = -1-split;}
TFile *hfile;
TTree *tree;
Event *event = 0;
// Fill event, header and tracks with some random numbers
// Create a timer object to benchmark this loop
TStopwatch timer;
timer.Start();
Long64_t nb = 0;
Int_t ev;
Int_t bufsize;
Double_t told = 0;
Double_t tnew = 0;
Int_t printev = 100;
if (arg5 < 100) printev = 1000;
if (arg5 < 10) printev = 10000;
// Read case
if (read) {
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root");
} else
hfile = new TFile("Event.root");
tree = (TTree*)hfile->Get("T");
TBranch *branch = tree->GetBranch("event");
branch->SetAddress(&event);
Int_t nentries = (Int_t)tree->GetEntries();
nevent = TMath::Min(nevent,nentries);
if (read == 1) { //read sequential
//by setting the read cache to -1 we set it to the AutoFlush value when writing
Int_t cachesize = -1;
if (punzip) tree->SetParallelUnzip();
tree->SetCacheSize(cachesize);
tree->SetCacheLearnEntries(1); //one entry is sufficient to learn
tree->SetCacheEntryRange(0,nevent);
for (ev = 0; ev < nevent; ev++) {
tree->LoadTree(ev); //this call is required when using the cache
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
told=tnew;
timer.Continue();
}
nb += tree->GetEntry(ev); //read complete event in memory
}
} else { //read random
Int_t evrandom;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) cout<<"event="<<ev<<endl;
evrandom = Int_t(nevent*gRandom->Rndm(1));
nb += tree->GetEntry(evrandom); //read complete event in memory
}
}
} else {
// Write case
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
} else
hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
hfile->SetCompressionLevel(comp);
// Create histogram to show write_time in function of time
Float_t curtime = -0.5;
Int_t ntime = nevent/printev;
TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
HistogramManager *hm = 0;
if (hfill) {
TDirectory *hdir = new TDirectory("histograms", "all histograms");
hm = new HistogramManager(hdir);
}
// Create a ROOT Tree and one superbranch
tree = new TTree("T","An example of a ROOT tree");
tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
tree->SetCacheSize(10000000); //set a 10 MBytes cache (useless when writing local files)
bufsize = 64000;
if (split) bufsize /= 4;
event = new Event();
TTree::SetBranchStyle(branchStyle);
TBranch *branch = tree->Branch("event", &event, bufsize,split);
branch->SetAutoDelete(kFALSE);
if(split >= 0 && branchStyle) tree->BranchRef();
Float_t ptmin = 1;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
htime->Fill(curtime,tnew-told);
curtime += 1;
told=tnew;
timer.Continue();
}
event->Build(ev, arg5, ptmin);
if (write) nb += tree->Fill(); //fill the tree
if(write) tree->OptimizeBaskets(100000);
if (hm) hm->Hfill(event); //fill histograms
}
if (write) {
hfile = tree->GetCurrentFile(); //just in case we switched to a new file
hfile->Write();
tree->Print();
}
}
// Stop timer and print results
timer.Stop();
Float_t mbytes = 0.000001*nb;
Double_t rtime = timer.RealTime();
Double_t ctime = timer.CpuTime();
printf("\n%d events and %lld bytes processed.\n",nevent,nb);
printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
if (read) {
tree->PrintCacheStats();
printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
} else {
printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
//printf("file compression factor = %f\n",hfile.GetCompressionFactor());
}
hfile->Close();
return 0;
}
<commit_msg>Remove inadvertent part of revison 38509<commit_after>// @(#)root/test:$Id$
// Author: Rene Brun 19/01/97
////////////////////////////////////////////////////////////////////////
//
// A simple example with a ROOT tree
// =================================
//
// This program creates :
// - a ROOT file
// - a tree
// Additional arguments can be passed to the program to control the flow
// of execution. (see comments describing the arguments in the code).
// Event nevent comp split fill
// All arguments are optional. Default is:
// Event 400 1 1 1
//
// In this example, the tree consists of one single "super branch"
// The statement ***tree->Branch("event", &event, 64000,split);*** below
// will parse the structure described in Event.h and will make
// a new branch for each data member of the class if split is set to 1.
// - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
// fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
// - 3 branches corresponding to the members of the subobject EventHeader.
// - one branch for each data member of the class Track of TClonesArray.
// - one branch for the TRefArray of high Pt tracks
// - one branch for the TRefArray of muon tracks
// - one branch for the reference pointer to the last track
// - one branch for the object fH (histogram of class TH1F).
//
// if split = 0 only one single branch is created and the complete event
// is serialized in one single buffer.
// if split = -2 the event is split using the old TBranchObject mechanism
// if split = -1 the event is streamed using the old TBranchObject mechanism
// if split > 0 the event is split using the new TBranchElement mechanism.
//
// if comp = 0 no compression at all.
// if comp = 1 event is compressed.
// if comp = 2 same as 1. In addition branches with floats in the TClonesArray
// are also compressed.
// The 4th argument fill can be set to 0 if one wants to time
// the percentage of time spent in creating the event structure and
// not write the event in the file.
// In this example, one loops over nevent events.
// The branch "event" is created at the first event.
// The branch address is set for all other events.
// For each event, the event header is filled and ntrack tracks
// are generated and added to the TClonesArray list.
// For each event the event histogram is saved as well as the list
// of all tracks.
//
// The two TRefArray contain only references to the original tracks owned by
// the TClonesArray fTracks.
//
// The number of events can be given as the first argument to the program.
// By default 400 events are generated.
// The compression option can be activated/deactivated via the second argument.
//
// ---Running/Linking instructions----
// This program consists of the following files and procedures.
// - Event.h event class description
// - Event.C event class implementation
// - MainEvent.C the main program to demo this class might be used (this file)
// - EventCint.C the CINT dictionary for the event and Track classes
// this file is automatically generated by rootcint (see Makefile),
// when the class definition in Event.h is modified.
//
// ---Analyzing the Event.root file with the interactive root
// example of a simple session
// Root > TFile f("Event.root")
// Root > T.Draw("fNtrack") //histogram the number of tracks per event
// Root > T.Draw("fPx") //histogram fPx for all tracks in all events
// Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
// //scatter-plot for x versus y of first point of each track
// Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram
//
// Look also in the same directory at the following macros:
// - eventa.C an example how to read the tree
// - eventb.C how to read events conditionally
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "Event.h"
//______________________________________________________________________________
int main(int argc, char **argv)
{
Int_t nevent = 400; // by default create 400 events
Int_t comp = 1; // by default file is compressed
Int_t split = 1; // by default, split Event in sub branches
Int_t write = 1; // by default the tree is filled
Int_t hfill = 0; // by default histograms are not filled
Int_t read = 0;
Int_t arg4 = 1;
Int_t arg5 = 600; //default number of tracks per event
Int_t netf = 0;
Int_t punzip = 0;
if (argc > 1) nevent = atoi(argv[1]);
if (argc > 2) comp = atoi(argv[2]);
if (argc > 3) split = atoi(argv[3]);
if (argc > 4) arg4 = atoi(argv[4]);
if (argc > 5) arg5 = atoi(argv[5]);
if (arg4 == 0) { write = 0; hfill = 0; read = 1;}
if (arg4 == 1) { write = 1; hfill = 0;}
if (arg4 == 2) { write = 0; hfill = 0;}
if (arg4 == 10) { write = 0; hfill = 1;}
if (arg4 == 11) { write = 1; hfill = 1;}
if (arg4 == 20) { write = 0; read = 1;} //read sequential
if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping
if (arg4 == 25) { write = 0; read = 2;} //read random
if (arg4 >= 30) { netf = 1; } //use TNetFile
if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential
if (arg4 == 35) { write = 0; read = 2;} //netfile + read random
if (arg4 == 36) { write = 1; } //netfile + write sequential
Int_t branchStyle = 1; //new style by default
if (split < 0) {branchStyle = 0; split = -1-split;}
TFile *hfile;
TTree *tree;
Event *event = 0;
// Fill event, header and tracks with some random numbers
// Create a timer object to benchmark this loop
TStopwatch timer;
timer.Start();
Long64_t nb = 0;
Int_t ev;
Int_t bufsize;
Double_t told = 0;
Double_t tnew = 0;
Int_t printev = 100;
if (arg5 < 100) printev = 1000;
if (arg5 < 10) printev = 10000;
// Read case
if (read) {
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root");
} else
hfile = new TFile("Event.root");
tree = (TTree*)hfile->Get("T");
TBranch *branch = tree->GetBranch("event");
branch->SetAddress(&event);
Int_t nentries = (Int_t)tree->GetEntries();
nevent = TMath::Min(nevent,nentries);
if (read == 1) { //read sequential
//by setting the read cache to -1 we set it to the AutoFlush value when writing
Int_t cachesize = -1;
if (punzip) tree->SetParallelUnzip();
tree->SetCacheSize(cachesize);
tree->SetCacheLearnEntries(1); //one entry is sufficient to learn
tree->SetCacheEntryRange(0,nevent);
for (ev = 0; ev < nevent; ev++) {
tree->LoadTree(ev); //this call is required when using the cache
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
told=tnew;
timer.Continue();
}
nb += tree->GetEntry(ev); //read complete event in memory
}
} else { //read random
Int_t evrandom;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) cout<<"event="<<ev<<endl;
evrandom = Int_t(nevent*gRandom->Rndm(1));
nb += tree->GetEntry(evrandom); //read complete event in memory
}
}
} else {
// Write case
// Create a new ROOT binary machine independent file.
// Note that this file may contain any kind of ROOT objects, histograms,
// pictures, graphics objects, detector geometries, tracks, events, etc..
// This file is now becoming the current directory.
if (netf) {
hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
} else
hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
hfile->SetCompressionLevel(comp);
// Create histogram to show write_time in function of time
Float_t curtime = -0.5;
Int_t ntime = nevent/printev;
TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
HistogramManager *hm = 0;
if (hfill) {
TDirectory *hdir = new TDirectory("histograms", "all histograms");
hm = new HistogramManager(hdir);
}
// Create a ROOT Tree and one superbranch
tree = new TTree("T","An example of a ROOT tree");
tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
tree->SetCacheSize(10000000); //set a 10 MBytes cache (useless when writing local files)
bufsize = 64000;
if (split) bufsize /= 4;
event = new Event();
TTree::SetBranchStyle(branchStyle);
TBranch *branch = tree->Branch("event", &event, bufsize,split);
branch->SetAutoDelete(kFALSE);
if(split >= 0 && branchStyle) tree->BranchRef();
Float_t ptmin = 1;
for (ev = 0; ev < nevent; ev++) {
if (ev%printev == 0) {
tnew = timer.RealTime();
printf("event:%d, rtime=%f s\n",ev,tnew-told);
htime->Fill(curtime,tnew-told);
curtime += 1;
told=tnew;
timer.Continue();
}
event->Build(ev, arg5, ptmin);
if (write) nb += tree->Fill(); //fill the tree
if (hm) hm->Hfill(event); //fill histograms
}
if (write) {
hfile = tree->GetCurrentFile(); //just in case we switched to a new file
hfile->Write();
tree->Print();
}
}
// Stop timer and print results
timer.Stop();
Float_t mbytes = 0.000001*nb;
Double_t rtime = timer.RealTime();
Double_t ctime = timer.CpuTime();
printf("\n%d events and %lld bytes processed.\n",nevent,nb);
printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
if (read) {
tree->PrintCacheStats();
printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
} else {
printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
//printf("file compression factor = %f\n",hfile.GetCompressionFactor());
}
hfile->Close();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include "TestBlock.hpp"
#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>
#include <nix/Exception.hpp>
#include <ctime>
using namespace std;
using namespace nix;
using namespace valid;
void TestBlock::setUp() {
startup_time = time(NULL);
file = File::open("test_block.h5", FileMode::Overwrite);
section = file.createSection("foo_section", "metadata");
block = file.createBlock("block_one", "dataset");
block_other = file.createBlock("block_two", "dataset");
block_null = nullptr;
}
void TestBlock::tearDown() {
file.close();
}
void TestBlock::testValidate() {
valid::Result result = validate(block);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}
void TestBlock::testId() {
CPPUNIT_ASSERT(block.id().size() == 36);
}
void TestBlock::testName() {
CPPUNIT_ASSERT(block.name() == "block_one");
}
void TestBlock::testType() {
CPPUNIT_ASSERT(block.type() == "dataset");
string typ = util::createId();
block.type(typ);
CPPUNIT_ASSERT(block.type() == typ);
}
void TestBlock::testDefinition() {
string def = util::createId();
block.definition(def);
CPPUNIT_ASSERT(*block.definition() == def);
}
void TestBlock::testMetadataAccess() {
CPPUNIT_ASSERT(!block.metadata());
block.metadata(section);
CPPUNIT_ASSERT(block.metadata());
// test none-unsetter
block.metadata(none);
CPPUNIT_ASSERT(!block.metadata());
// test deleter removing link too
block.metadata(section);
file.deleteSection(section.id());
CPPUNIT_ASSERT(!block.metadata());
// re-create section
section = file.createSection("foo_section", "metadata");
}
void TestBlock::testSourceAccess() {
vector<string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" };
CPPUNIT_ASSERT(block.sourceCount() == 0);
CPPUNIT_ASSERT(block.sources().size() == 0);
CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
vector<string> ids;
for (auto it = names.begin(); it != names.end(); it++) {
Source src = block.createSource(*it, "channel");
CPPUNIT_ASSERT(src.name() == *it);
ids.push_back(src.id());
}
CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"),
DuplicateName);
CPPUNIT_ASSERT(block.sourceCount() == names.size());
CPPUNIT_ASSERT(block.sources().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); it++) {
Source src = block.getSource(*it);
CPPUNIT_ASSERT(block.hasSource(*it) == true);
CPPUNIT_ASSERT(src.id() == *it);
block.deleteSource(*it);
}
CPPUNIT_ASSERT(block.sourceCount() == 0);
CPPUNIT_ASSERT(block.sources().size() == 0);
CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
}
void TestBlock::testDataArrayAccess() {
vector<string> names = { "data_array_a", "data_array_b", "data_array_c",
"data_array_d", "data_array_e" };
CPPUNIT_ASSERT(block.dataArrayCount() == 0);
CPPUNIT_ASSERT(block.dataArrays().size() == 0);
CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);
vector<string> ids;
for (const auto &name : names) {
DataArray data_array = block.createDataArray(name,
"channel",
DataType::Double,
nix::NDSize({ 0 }));
CPPUNIT_ASSERT(data_array.name() == name);
CPPUNIT_ASSERT(data_array.type() == "channel");
ids.push_back(data_array.id());
}
CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })),
DuplicateName);
CPPUNIT_ASSERT(block.dataArrayCount() == names.size());
CPPUNIT_ASSERT(block.dataArrays().size() == names.size());
for (const auto &name : names) {
DataArray da_name = block.getDataArray(name);
CPPUNIT_ASSERT(da_name);
DataArray da_id = block.getDataArray(da_name.id());
CPPUNIT_ASSERT(da_id);
CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name());
}
vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel"));
CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size());
filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c"));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size());
if (filteredArrays.size() > 0) {
boost::optional<std::string> name = filteredArrays[0].name();
CPPUNIT_ASSERT(name && *name == "data_array_c");
}
for (auto it = ids.begin(); it != ids.end(); it++) {
DataArray data_array = block.getDataArray(*it);
CPPUNIT_ASSERT(block.hasDataArray(*it) == true);
CPPUNIT_ASSERT(data_array.id() == *it);
block.deleteDataArray(*it);
}
CPPUNIT_ASSERT(block.dataArrayCount() == 0);
CPPUNIT_ASSERT(block.dataArrays().size() == 0);
CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);
}
void TestBlock::testTagAccess() {
vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
vector<string> array_names = { "data_array_a", "data_array_b", "data_array_c",
"data_array_d", "data_array_e" };
vector<DataArray> refs;
for (const auto &name : array_names) {
refs.push_back(block.createDataArray(name,
"reference",
DataType::Double,
nix::NDSize({ 0 })));
}
CPPUNIT_ASSERT(block.tagCount() == 0);
CPPUNIT_ASSERT(block.tags().size() == 0);
CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
vector<string> ids;
for (auto it = names.begin(); it != names.end(); ++it) {
Tag tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4});
tag.references(refs);
CPPUNIT_ASSERT(tag.name() == *it);
ids.push_back(tag.id());
}
CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}),
DuplicateName);
CPPUNIT_ASSERT(block.tagCount() == names.size());
CPPUNIT_ASSERT(block.tags().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); ++it) {
Tag tag = block.getTag(*it);
CPPUNIT_ASSERT(block.hasTag(*it) == true);
CPPUNIT_ASSERT(tag.id() == *it);
block.deleteTag(*it);
}
CPPUNIT_ASSERT(block.tagCount() == 0);
CPPUNIT_ASSERT(block.tags().size() == 0);
CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
}
void TestBlock::testMultiTagAccess() {
vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
// create a valid positions data array below
typedef boost::multi_array<double, 3>::index index;
DataArray positions = block.createDataArray("array_one",
"testdata",
DataType::Double,
nix::NDSize({ 3, 4, 2 }));
boost::multi_array<double, 3> A(boost::extents[3][4][2]);
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
positions.setData(A);
CPPUNIT_ASSERT(block.multiTagCount() == 0);
CPPUNIT_ASSERT(block.multiTags().size() == 0);
CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
vector<string> ids;
for (auto it = names.begin(); it != names.end(); it++) {
MultiTag tag = block.createMultiTag(*it, "segment", positions);
CPPUNIT_ASSERT(tag.name() == *it);
ids.push_back(tag.id());
}
CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions),
DuplicateName);
CPPUNIT_ASSERT(block.multiTagCount() == names.size());
CPPUNIT_ASSERT(block.multiTags().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); it++) {
MultiTag tag = block.getMultiTag(*it);
CPPUNIT_ASSERT(block.hasMultiTag(*it) == true);
CPPUNIT_ASSERT(tag.id() == *it);
block.deleteMultiTag(*it);
}
CPPUNIT_ASSERT(block.multiTagCount() == 0);
CPPUNIT_ASSERT(block.multiTags().size() == 0);
CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
}
void TestBlock::testOperators() {
CPPUNIT_ASSERT(block_null == false);
CPPUNIT_ASSERT(block_null == none);
CPPUNIT_ASSERT(block != false);
CPPUNIT_ASSERT(block != none);
CPPUNIT_ASSERT(block == block);
CPPUNIT_ASSERT(block != block_other);
block_other = block;
CPPUNIT_ASSERT(block == block_other);
block_other = none;
CPPUNIT_ASSERT(block_null == false);
CPPUNIT_ASSERT(block_null == none);
}
void TestBlock::testCreatedAt() {
CPPUNIT_ASSERT(block.createdAt() >= startup_time);
time_t past_time = time(NULL) - 10000000;
block.forceCreatedAt(past_time);
CPPUNIT_ASSERT(block.createdAt() == past_time);
}
void TestBlock::testUpdatedAt() {
CPPUNIT_ASSERT(block.updatedAt() >= startup_time);
}
<commit_msg>[test] Block: source access: cleanup + extend<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include "TestBlock.hpp"
#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>
#include <nix/Exception.hpp>
#include <ctime>
using namespace std;
using namespace nix;
using namespace valid;
void TestBlock::setUp() {
startup_time = time(NULL);
file = File::open("test_block.h5", FileMode::Overwrite);
section = file.createSection("foo_section", "metadata");
block = file.createBlock("block_one", "dataset");
block_other = file.createBlock("block_two", "dataset");
block_null = nullptr;
}
void TestBlock::tearDown() {
file.close();
}
void TestBlock::testValidate() {
valid::Result result = validate(block);
CPPUNIT_ASSERT(result.getErrors().size() == 0);
CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}
void TestBlock::testId() {
CPPUNIT_ASSERT(block.id().size() == 36);
}
void TestBlock::testName() {
CPPUNIT_ASSERT(block.name() == "block_one");
}
void TestBlock::testType() {
CPPUNIT_ASSERT(block.type() == "dataset");
string typ = util::createId();
block.type(typ);
CPPUNIT_ASSERT(block.type() == typ);
}
void TestBlock::testDefinition() {
string def = util::createId();
block.definition(def);
CPPUNIT_ASSERT(*block.definition() == def);
}
void TestBlock::testMetadataAccess() {
CPPUNIT_ASSERT(!block.metadata());
block.metadata(section);
CPPUNIT_ASSERT(block.metadata());
// test none-unsetter
block.metadata(none);
CPPUNIT_ASSERT(!block.metadata());
// test deleter removing link too
block.metadata(section);
file.deleteSection(section.id());
CPPUNIT_ASSERT(!block.metadata());
// re-create section
section = file.createSection("foo_section", "metadata");
}
void TestBlock::testSourceAccess() {
vector<string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" };
CPPUNIT_ASSERT(block.sourceCount() == 0);
CPPUNIT_ASSERT(block.sources().size() == 0);
CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
CPPUNIT_ASSERT(!block.hasSource("invalid_id"));
vector<string> ids;
for (const auto &name : names) {
Source src = block.createSource(name, "channel");
CPPUNIT_ASSERT(src.name() == name);
CPPUNIT_ASSERT(block.hasSource(name));
CPPUNIT_ASSERT(block.hasSource(src));
ids.push_back(src.id());
}
CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"),
DuplicateName);
CPPUNIT_ASSERT(block.sourceCount() == names.size());
CPPUNIT_ASSERT(block.sources().size() == names.size());
for (const auto &id : ids) {
Source src = block.getSource(id);
CPPUNIT_ASSERT(block.hasSource(id) == true);
CPPUNIT_ASSERT(src.id() == id);
block.deleteSource(id);
}
CPPUNIT_ASSERT(block.sourceCount() == 0);
CPPUNIT_ASSERT(block.sources().size() == 0);
CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
}
void TestBlock::testDataArrayAccess() {
vector<string> names = { "data_array_a", "data_array_b", "data_array_c",
"data_array_d", "data_array_e" };
CPPUNIT_ASSERT(block.dataArrayCount() == 0);
CPPUNIT_ASSERT(block.dataArrays().size() == 0);
CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);
vector<string> ids;
for (const auto &name : names) {
DataArray data_array = block.createDataArray(name,
"channel",
DataType::Double,
nix::NDSize({ 0 }));
CPPUNIT_ASSERT(data_array.name() == name);
CPPUNIT_ASSERT(data_array.type() == "channel");
ids.push_back(data_array.id());
}
CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })),
DuplicateName);
CPPUNIT_ASSERT(block.dataArrayCount() == names.size());
CPPUNIT_ASSERT(block.dataArrays().size() == names.size());
for (const auto &name : names) {
DataArray da_name = block.getDataArray(name);
CPPUNIT_ASSERT(da_name);
DataArray da_id = block.getDataArray(da_name.id());
CPPUNIT_ASSERT(da_id);
CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name());
}
vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel"));
CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size());
filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c"));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size());
if (filteredArrays.size() > 0) {
boost::optional<std::string> name = filteredArrays[0].name();
CPPUNIT_ASSERT(name && *name == "data_array_c");
}
for (auto it = ids.begin(); it != ids.end(); it++) {
DataArray data_array = block.getDataArray(*it);
CPPUNIT_ASSERT(block.hasDataArray(*it) == true);
CPPUNIT_ASSERT(data_array.id() == *it);
block.deleteDataArray(*it);
}
CPPUNIT_ASSERT(block.dataArrayCount() == 0);
CPPUNIT_ASSERT(block.dataArrays().size() == 0);
CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);
}
void TestBlock::testTagAccess() {
vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
vector<string> array_names = { "data_array_a", "data_array_b", "data_array_c",
"data_array_d", "data_array_e" };
vector<DataArray> refs;
for (const auto &name : array_names) {
refs.push_back(block.createDataArray(name,
"reference",
DataType::Double,
nix::NDSize({ 0 })));
}
CPPUNIT_ASSERT(block.tagCount() == 0);
CPPUNIT_ASSERT(block.tags().size() == 0);
CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
vector<string> ids;
for (auto it = names.begin(); it != names.end(); ++it) {
Tag tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4});
tag.references(refs);
CPPUNIT_ASSERT(tag.name() == *it);
ids.push_back(tag.id());
}
CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}),
DuplicateName);
CPPUNIT_ASSERT(block.tagCount() == names.size());
CPPUNIT_ASSERT(block.tags().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); ++it) {
Tag tag = block.getTag(*it);
CPPUNIT_ASSERT(block.hasTag(*it) == true);
CPPUNIT_ASSERT(tag.id() == *it);
block.deleteTag(*it);
}
CPPUNIT_ASSERT(block.tagCount() == 0);
CPPUNIT_ASSERT(block.tags().size() == 0);
CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
}
void TestBlock::testMultiTagAccess() {
vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
// create a valid positions data array below
typedef boost::multi_array<double, 3>::index index;
DataArray positions = block.createDataArray("array_one",
"testdata",
DataType::Double,
nix::NDSize({ 3, 4, 2 }));
boost::multi_array<double, 3> A(boost::extents[3][4][2]);
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
positions.setData(A);
CPPUNIT_ASSERT(block.multiTagCount() == 0);
CPPUNIT_ASSERT(block.multiTags().size() == 0);
CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
vector<string> ids;
for (auto it = names.begin(); it != names.end(); it++) {
MultiTag tag = block.createMultiTag(*it, "segment", positions);
CPPUNIT_ASSERT(tag.name() == *it);
ids.push_back(tag.id());
}
CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions),
DuplicateName);
CPPUNIT_ASSERT(block.multiTagCount() == names.size());
CPPUNIT_ASSERT(block.multiTags().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); it++) {
MultiTag tag = block.getMultiTag(*it);
CPPUNIT_ASSERT(block.hasMultiTag(*it) == true);
CPPUNIT_ASSERT(tag.id() == *it);
block.deleteMultiTag(*it);
}
CPPUNIT_ASSERT(block.multiTagCount() == 0);
CPPUNIT_ASSERT(block.multiTags().size() == 0);
CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
}
void TestBlock::testOperators() {
CPPUNIT_ASSERT(block_null == false);
CPPUNIT_ASSERT(block_null == none);
CPPUNIT_ASSERT(block != false);
CPPUNIT_ASSERT(block != none);
CPPUNIT_ASSERT(block == block);
CPPUNIT_ASSERT(block != block_other);
block_other = block;
CPPUNIT_ASSERT(block == block_other);
block_other = none;
CPPUNIT_ASSERT(block_null == false);
CPPUNIT_ASSERT(block_null == none);
}
void TestBlock::testCreatedAt() {
CPPUNIT_ASSERT(block.createdAt() >= startup_time);
time_t past_time = time(NULL) - 10000000;
block.forceCreatedAt(past_time);
CPPUNIT_ASSERT(block.createdAt() == past_time);
}
void TestBlock::testUpdatedAt() {
CPPUNIT_ASSERT(block.updatedAt() >= startup_time);
}
<|endoftext|> |
<commit_before>#include "editor.h"
#include <qwt_plot.h>
#include <qwt_plot_canvas.h>
#include <qwt_scale_map.h>
#include <qwt_plot_shapeitem.h>
#include <qevent.h>
class Overlay: public QwtPlotOverlay
{
public:
Overlay( QWidget *parent, Editor *editor ):
QwtPlotOverlay( parent ),
d_editor( editor )
{
switch( editor->mode() )
{
case Editor::NoMask:
{
setMaskMode( QwtPlotOverlay::NoMask );
setRenderMode( QwtPlotOverlay::AutoRenderMode );
break;
}
case Editor::Mask:
{
setMaskMode( QwtPlotOverlay::MaskHint );
setRenderMode( QwtPlotOverlay::AutoRenderMode );
break;
}
case Editor::AlphaMask:
{
setMaskMode( QwtPlotOverlay::AlphaMask );
setRenderMode( QwtPlotOverlay::AutoRenderMode );
break;
}
case Editor::AlphaMaskRedraw:
{
setMaskMode( QwtPlotOverlay::AlphaMask );
setRenderMode( QwtPlotOverlay::DrawOverlay );
break;
}
case Editor::AlphaMaskCopyMask:
{
setMaskMode( QwtPlotOverlay::AlphaMask );
setRenderMode( QwtPlotOverlay::CopyAlphaMask );
break;
}
}
}
protected:
virtual void drawOverlay( QPainter *painter ) const
{
d_editor->drawOverlay( painter );
}
virtual QRegion maskHint() const
{
return d_editor->maskHint();
}
private:
Editor *d_editor;
};
Editor::Editor( QwtPlot* plot ):
QObject( plot ),
d_isEnabled( false ),
d_overlay( NULL ),
d_mode( Mask )
{
setEnabled( true );
}
Editor::~Editor()
{
delete d_overlay;
}
QwtPlot *Editor::plot()
{
return qobject_cast<QwtPlot *>( parent() );
}
const QwtPlot *Editor::plot() const
{
return qobject_cast<const QwtPlot *>( parent() );
}
void Editor::setMode( Mode mode )
{
d_mode = mode;
}
Editor::Mode Editor::mode() const
{
return d_mode;
}
void Editor::setEnabled( bool on )
{
if ( on == d_isEnabled )
return;
QwtPlot *plot = qobject_cast<QwtPlot *>( parent() );
if ( plot )
{
d_isEnabled = on;
if ( on )
{
plot->canvas()->installEventFilter( this );
}
else
{
plot->canvas()->removeEventFilter( this );
delete d_overlay;
d_overlay = NULL;
}
}
}
bool Editor::isEnabled() const
{
return d_isEnabled;
}
bool Editor::eventFilter( QObject* object, QEvent* event )
{
QwtPlot *plot = qobject_cast<QwtPlot *>( parent() );
if ( plot && object == plot->canvas() )
{
switch( event->type() )
{
case QEvent::MouseButtonPress:
{
const QMouseEvent* mouseEvent =
dynamic_cast<QMouseEvent* >( event );
if ( d_overlay == NULL &&
mouseEvent->button() == Qt::LeftButton )
{
const bool accepted = pressed( mouseEvent->pos() );
if ( accepted )
{
d_overlay = new Overlay( plot->canvas(), this );
d_overlay->updateOverlay();
d_overlay->show();
}
}
break;
}
case QEvent::MouseMove:
{
if ( d_overlay )
{
const QMouseEvent* mouseEvent =
dynamic_cast< QMouseEvent* >( event );
const bool accepted = moved( mouseEvent->pos() );
if ( accepted )
d_overlay->updateOverlay();
}
break;
}
case QEvent::MouseButtonRelease:
{
const QMouseEvent* mouseEvent =
static_cast<QMouseEvent* >( event );
if ( d_overlay && mouseEvent->button() == Qt::LeftButton )
{
released( mouseEvent->pos() );
delete d_overlay;
d_overlay = NULL;
}
break;
}
default:
break;
}
return false;
}
return QObject::eventFilter( object, event );
}
bool Editor::pressed( const QPoint& pos )
{
d_editedItem = itemAt( pos );
if ( d_editedItem )
{
d_currentPos = pos;
setItemVisible( d_editedItem, false );
return true;
}
return false; // don't accept the position
}
bool Editor::moved( const QPoint& pos )
{
if ( plot() == NULL )
return false;
const QwtScaleMap xMap = plot()->canvasMap( d_editedItem->xAxis() );
const QwtScaleMap yMap = plot()->canvasMap( d_editedItem->yAxis() );
const QPointF p1 = QwtScaleMap::invTransform( xMap, yMap, d_currentPos );
const QPointF p2 = QwtScaleMap::invTransform( xMap, yMap, pos );
d_editedItem->setShape( d_editedItem->shape().translated( p2 - p1 ) );
d_currentPos = pos;
return true;
}
void Editor::released( const QPoint& pos )
{
Q_UNUSED( pos );
if ( d_editedItem )
{
raiseItem( d_editedItem );
setItemVisible( d_editedItem, true );
}
}
QwtPlotShapeItem* Editor::itemAt( const QPoint& pos ) const
{
const QwtPlot *plot = this->plot();
if ( plot == NULL )
return NULL;
// translate pos into the plot coordinates
double coords[ QwtPlot::axisCnt ];
coords[ QwtPlot::xBottom ] =
plot->canvasMap( QwtPlot::xBottom ).invTransform( pos.x() );
coords[ QwtPlot::xTop ] =
plot->canvasMap( QwtPlot::xTop ).invTransform( pos.x() );
coords[ QwtPlot::yLeft ] =
plot->canvasMap( QwtPlot::yLeft ).invTransform( pos.y() );
coords[ QwtPlot::yRight ] =
plot->canvasMap( QwtPlot::yRight ).invTransform( pos.y() );
QwtPlotItemList items = plot->itemList();
for ( int i = items.size() - 1; i >= 0; i-- )
{
QwtPlotItem *item = items[ i ];
if ( item->isVisible() &&
item->rtti() == QwtPlotItem::Rtti_PlotShape )
{
QwtPlotShapeItem *shapeItem = static_cast<QwtPlotShapeItem *>( item );
const QPointF p( coords[ item->xAxis() ], coords[ item->yAxis() ] );
if ( shapeItem->boundingRect().contains( p )
&& shapeItem->shape().contains( p ) )
{
return shapeItem;
}
}
}
return NULL;
}
QRegion Editor::maskHint() const
{
return maskHint( d_editedItem );
}
QRegion Editor::maskHint( QwtPlotShapeItem *shapeItem ) const
{
const QwtPlot *plot = this->plot();
if ( plot == NULL || shapeItem == NULL )
return QRegion();
const QwtScaleMap xMap = plot->canvasMap( shapeItem->xAxis() );
const QwtScaleMap yMap = plot->canvasMap( shapeItem->yAxis() );
QRect rect = QwtScaleMap::transform( xMap, yMap,
shapeItem->shape().boundingRect() ).toRect();
const int m = 5; // some margin for the pen
return rect.adjusted( -m, -m, m, m );
}
void Editor::drawOverlay( QPainter* painter ) const
{
const QwtPlot *plot = this->plot();
if ( plot == NULL || d_editedItem == NULL )
return;
const QwtScaleMap xMap = plot->canvasMap( d_editedItem->xAxis() );
const QwtScaleMap yMap = plot->canvasMap( d_editedItem->yAxis() );
painter->setRenderHint( QPainter::Antialiasing,
d_editedItem->testRenderHint( QwtPlotItem::RenderAntialiased ) );
d_editedItem->draw( painter, xMap, yMap,
plot->canvas()->contentsRect() );
}
void Editor::raiseItem( QwtPlotShapeItem *shapeItem )
{
const QwtPlot *plot = this->plot();
if ( plot == NULL || shapeItem == NULL )
return;
const QwtPlotItemList items = plot->itemList();
for ( int i = items.size() - 1; i >= 0; i-- )
{
QwtPlotItem *item = items[ i ];
if ( shapeItem == item )
return;
if ( item->isVisible() &&
item->rtti() == QwtPlotItem::Rtti_PlotShape )
{
shapeItem->setZ( item->z() + 1 );
return;
}
}
}
void Editor::setItemVisible( QwtPlotShapeItem *item, bool on )
{
if ( plot() == NULL || item == NULL || item->isVisible() == on )
return;
const bool doAutoReplot = plot()->autoReplot();
plot()->setAutoReplot( false );
item->setVisible( on );
plot()->setAutoReplot( doAutoReplot );
/*
Avoid replot with a full repaint of the canvas.
For special combinations - f.e. using the
raster paint engine on a remote display -
this makes a difference.
*/
QwtPlotCanvas *canvas =
qobject_cast<QwtPlotCanvas *>( plot()->canvas() );
if ( canvas )
canvas->invalidateBackingStore();
plot()->canvas()->update( maskHint( item ) );
}
<commit_msg>modified for Qt < 4.6<commit_after>#include "editor.h"
#include <qwt_plot.h>
#include <qwt_plot_canvas.h>
#include <qwt_scale_map.h>
#include <qwt_plot_shapeitem.h>
#include <qevent.h>
class Overlay: public QwtPlotOverlay
{
public:
Overlay( QWidget *parent, Editor *editor ):
QwtPlotOverlay( parent ),
d_editor( editor )
{
switch( editor->mode() )
{
case Editor::NoMask:
{
setMaskMode( QwtPlotOverlay::NoMask );
setRenderMode( QwtPlotOverlay::AutoRenderMode );
break;
}
case Editor::Mask:
{
setMaskMode( QwtPlotOverlay::MaskHint );
setRenderMode( QwtPlotOverlay::AutoRenderMode );
break;
}
case Editor::AlphaMask:
{
setMaskMode( QwtPlotOverlay::AlphaMask );
setRenderMode( QwtPlotOverlay::AutoRenderMode );
break;
}
case Editor::AlphaMaskRedraw:
{
setMaskMode( QwtPlotOverlay::AlphaMask );
setRenderMode( QwtPlotOverlay::DrawOverlay );
break;
}
case Editor::AlphaMaskCopyMask:
{
setMaskMode( QwtPlotOverlay::AlphaMask );
setRenderMode( QwtPlotOverlay::CopyAlphaMask );
break;
}
}
}
protected:
virtual void drawOverlay( QPainter *painter ) const
{
d_editor->drawOverlay( painter );
}
virtual QRegion maskHint() const
{
return d_editor->maskHint();
}
private:
Editor *d_editor;
};
Editor::Editor( QwtPlot* plot ):
QObject( plot ),
d_isEnabled( false ),
d_overlay( NULL ),
d_mode( Mask )
{
setEnabled( true );
}
Editor::~Editor()
{
delete d_overlay;
}
QwtPlot *Editor::plot()
{
return qobject_cast<QwtPlot *>( parent() );
}
const QwtPlot *Editor::plot() const
{
return qobject_cast<const QwtPlot *>( parent() );
}
void Editor::setMode( Mode mode )
{
d_mode = mode;
}
Editor::Mode Editor::mode() const
{
return d_mode;
}
void Editor::setEnabled( bool on )
{
if ( on == d_isEnabled )
return;
QwtPlot *plot = qobject_cast<QwtPlot *>( parent() );
if ( plot )
{
d_isEnabled = on;
if ( on )
{
plot->canvas()->installEventFilter( this );
}
else
{
plot->canvas()->removeEventFilter( this );
delete d_overlay;
d_overlay = NULL;
}
}
}
bool Editor::isEnabled() const
{
return d_isEnabled;
}
bool Editor::eventFilter( QObject* object, QEvent* event )
{
QwtPlot *plot = qobject_cast<QwtPlot *>( parent() );
if ( plot && object == plot->canvas() )
{
switch( event->type() )
{
case QEvent::MouseButtonPress:
{
const QMouseEvent* mouseEvent =
dynamic_cast<QMouseEvent* >( event );
if ( d_overlay == NULL &&
mouseEvent->button() == Qt::LeftButton )
{
const bool accepted = pressed( mouseEvent->pos() );
if ( accepted )
{
d_overlay = new Overlay( plot->canvas(), this );
d_overlay->updateOverlay();
d_overlay->show();
}
}
break;
}
case QEvent::MouseMove:
{
if ( d_overlay )
{
const QMouseEvent* mouseEvent =
dynamic_cast< QMouseEvent* >( event );
const bool accepted = moved( mouseEvent->pos() );
if ( accepted )
d_overlay->updateOverlay();
}
break;
}
case QEvent::MouseButtonRelease:
{
const QMouseEvent* mouseEvent =
static_cast<QMouseEvent* >( event );
if ( d_overlay && mouseEvent->button() == Qt::LeftButton )
{
released( mouseEvent->pos() );
delete d_overlay;
d_overlay = NULL;
}
break;
}
default:
break;
}
return false;
}
return QObject::eventFilter( object, event );
}
bool Editor::pressed( const QPoint& pos )
{
d_editedItem = itemAt( pos );
if ( d_editedItem )
{
d_currentPos = pos;
setItemVisible( d_editedItem, false );
return true;
}
return false; // don't accept the position
}
bool Editor::moved( const QPoint& pos )
{
if ( plot() == NULL )
return false;
const QwtScaleMap xMap = plot()->canvasMap( d_editedItem->xAxis() );
const QwtScaleMap yMap = plot()->canvasMap( d_editedItem->yAxis() );
const QPointF p1 = QwtScaleMap::invTransform( xMap, yMap, d_currentPos );
const QPointF p2 = QwtScaleMap::invTransform( xMap, yMap, pos );
#if QT_VERSION >= 0x040600
const QPainterPath shape = d_editedItem->shape().translated( p2 - p1 );
#else
const double dx = p2.x() - p1.x();
const double dy = p2.y() - p1.y();
QPainterPath shape = d_editedItem->shape();
for ( int i = 0; i < shape.elementCount(); i++ )
{
const QPainterPath::Element &el = shape.elementAt( i );
shape.setElementPositionAt( i, el.x + dx, el.y + dy );
}
#endif
d_editedItem->setShape( shape );
d_currentPos = pos;
return true;
}
void Editor::released( const QPoint& pos )
{
Q_UNUSED( pos );
if ( d_editedItem )
{
raiseItem( d_editedItem );
setItemVisible( d_editedItem, true );
}
}
QwtPlotShapeItem* Editor::itemAt( const QPoint& pos ) const
{
const QwtPlot *plot = this->plot();
if ( plot == NULL )
return NULL;
// translate pos into the plot coordinates
double coords[ QwtPlot::axisCnt ];
coords[ QwtPlot::xBottom ] =
plot->canvasMap( QwtPlot::xBottom ).invTransform( pos.x() );
coords[ QwtPlot::xTop ] =
plot->canvasMap( QwtPlot::xTop ).invTransform( pos.x() );
coords[ QwtPlot::yLeft ] =
plot->canvasMap( QwtPlot::yLeft ).invTransform( pos.y() );
coords[ QwtPlot::yRight ] =
plot->canvasMap( QwtPlot::yRight ).invTransform( pos.y() );
QwtPlotItemList items = plot->itemList();
for ( int i = items.size() - 1; i >= 0; i-- )
{
QwtPlotItem *item = items[ i ];
if ( item->isVisible() &&
item->rtti() == QwtPlotItem::Rtti_PlotShape )
{
QwtPlotShapeItem *shapeItem = static_cast<QwtPlotShapeItem *>( item );
const QPointF p( coords[ item->xAxis() ], coords[ item->yAxis() ] );
if ( shapeItem->boundingRect().contains( p )
&& shapeItem->shape().contains( p ) )
{
return shapeItem;
}
}
}
return NULL;
}
QRegion Editor::maskHint() const
{
return maskHint( d_editedItem );
}
QRegion Editor::maskHint( QwtPlotShapeItem *shapeItem ) const
{
const QwtPlot *plot = this->plot();
if ( plot == NULL || shapeItem == NULL )
return QRegion();
const QwtScaleMap xMap = plot->canvasMap( shapeItem->xAxis() );
const QwtScaleMap yMap = plot->canvasMap( shapeItem->yAxis() );
QRect rect = QwtScaleMap::transform( xMap, yMap,
shapeItem->shape().boundingRect() ).toRect();
const int m = 5; // some margin for the pen
return rect.adjusted( -m, -m, m, m );
}
void Editor::drawOverlay( QPainter* painter ) const
{
const QwtPlot *plot = this->plot();
if ( plot == NULL || d_editedItem == NULL )
return;
const QwtScaleMap xMap = plot->canvasMap( d_editedItem->xAxis() );
const QwtScaleMap yMap = plot->canvasMap( d_editedItem->yAxis() );
painter->setRenderHint( QPainter::Antialiasing,
d_editedItem->testRenderHint( QwtPlotItem::RenderAntialiased ) );
d_editedItem->draw( painter, xMap, yMap,
plot->canvas()->contentsRect() );
}
void Editor::raiseItem( QwtPlotShapeItem *shapeItem )
{
const QwtPlot *plot = this->plot();
if ( plot == NULL || shapeItem == NULL )
return;
const QwtPlotItemList items = plot->itemList();
for ( int i = items.size() - 1; i >= 0; i-- )
{
QwtPlotItem *item = items[ i ];
if ( shapeItem == item )
return;
if ( item->isVisible() &&
item->rtti() == QwtPlotItem::Rtti_PlotShape )
{
shapeItem->setZ( item->z() + 1 );
return;
}
}
}
void Editor::setItemVisible( QwtPlotShapeItem *item, bool on )
{
if ( plot() == NULL || item == NULL || item->isVisible() == on )
return;
const bool doAutoReplot = plot()->autoReplot();
plot()->setAutoReplot( false );
item->setVisible( on );
plot()->setAutoReplot( doAutoReplot );
/*
Avoid replot with a full repaint of the canvas.
For special combinations - f.e. using the
raster paint engine on a remote display -
this makes a difference.
*/
QwtPlotCanvas *canvas =
qobject_cast<QwtPlotCanvas *>( plot()->canvas() );
if ( canvas )
canvas->invalidateBackingStore();
plot()->canvas()->update( maskHint( item ) );
}
<|endoftext|> |
<commit_before>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <string>
#include <sstream>
// Patch for std::to_string() issue
// See here: http://stackoverflow.com/questions/12975341/to-string-is-not-a-member-of-std-says-so-g
namespace patch
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
#include<iostream>
using namespace Rcpp;
using namespace arma;
//' @export
// [[Rcpp::export]]
arma::vec assoc(arma::mat gen, arma::colvec y){
// Initialize output list
arma::vec outputList(gen.n_rows);
// Split regression into each row of the gen file
// meaning each SNP is regressed seperately.
for(uword i = 0; i < gen.n_rows; i++){
arma::rowvec geno_row = gen.row(i);
arma::vec geno = geno_row.t();
arma::vec X((geno.n_elem / 3), 1, fill::zeros);
for(uword j = 0; j < geno.n_elem; j+=3){
X(j/3) = 0*geno(j) + 1*geno(j+1) + 2*geno(j+2);
}
arma::mat X2(X.n_elem, 2);
X2.col(0) = vec(X.n_elem, fill::ones);
X2.col(1) = X;
arma::colvec coef = arma::solve(X2, y);
arma::colvec resid = y - X2*coef;
int n = X2.n_rows, k = X2.n_cols;
double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) );
// std.error of estimate
arma::colvec stderrest = arma::sqrt( sig2 * arma::diagvec( arma::inv(arma::trans(X2)*X2)) );
arma::mat output(coef.n_elem, 2);
output.col(0) = coef;
output.col(1) = stderrest;
double t = output(1,0) / output(1,1);
std::string name = patch::to_string(i);
outputList[i] = t;
}
return outputList;
}
<commit_msg>deal with singular matrices<commit_after>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <string>
#include <sstream>
// Patch for std::to_string() issue
// See here: http://stackoverflow.com/questions/12975341/to-string-is-not-a-member-of-std-says-so-g
namespace patch
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
#include<iostream>
using namespace Rcpp;
using namespace arma;
//' @export
// [[Rcpp::export]]
arma::vec assoc(arma::mat gen, arma::colvec y){
// Initialize output as a vector.
arma::vec outputList(gen.n_rows);
// Split regression into each row of the gen file
// meaning each SNP is regressed seperately.
for(uword i = 0; i < gen.n_rows; i++){
arma::rowvec geno_row = gen.row(i);
arma::vec geno = geno_row.t();
arma::vec X((geno.n_elem / 3), 1, fill::zeros);
for(uword j = 0; j < geno.n_elem; j+=3){
X(j/3) = 0*geno(j) + 1*geno(j+1) + 2*geno(j+2);
}
arma::mat X2(X.n_elem, 2);
X2.col(0) = vec(X.n_elem, fill::ones);
X2.col(1) = X;
arma::colvec coef = arma::solve(X2, y);
arma::colvec resid = y - X2*coef;
int n = X2.n_rows, k = X2.n_cols;
double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) );
// std.error of estimate
arma::colvec stderrest = arma::sqrt( sig2 * arma::diagvec( arma::pinv(arma::trans(X2)*X2)) );
arma::mat output(coef.n_elem, 2);
output.col(0) = coef;
output.col(1) = stderrest;
double t = output(1,0) / output(1,1);
std::string name = patch::to_string(i);
outputList[i] = t;
}
return outputList;
}
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>
#include <silicium/transform_if_initialized.hpp>
#include <silicium/empty.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/memory_source.hpp>
#include <silicium/transforming_source.hpp>
#include <silicium/for_each.hpp>
#include <boost/unordered_map.hpp>
#include <unordered_map>
namespace bf
{
enum class command
{
ptr_increment,
ptr_decrement,
value_increment,
value_decrement,
write,
read,
begin_loop,
end_loop
};
boost::optional<command> detect_command(char c)
{
switch (c)
{
case '>': return command::ptr_increment;
case '<': return command::ptr_decrement;
case '+': return command::value_increment;
case '-': return command::value_decrement;
case '.': return command::write;
case ',': return command::read;
case '[': return command::begin_loop;
case ']': return command::end_loop;
default: return boost::none;
}
}
template <class Source>
auto scan(Source &&source)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::conditional_transformer<command, typename std::decay<Source>::type, boost::optional<command>(*)(char)>
#endif
{
return Si::transform_if_initialized(std::forward<Source>(source), detect_command);
}
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
# define SILICIUM_CAPTURE(x) = (x)
#else
# define SILICIUM_CAPTURE(x)
#endif
template <class CommandRange>
typename CommandRange::const_iterator find_loop_begin(
CommandRange const &program,
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> &cached_loop_pairs,
typename CommandRange::const_iterator const end_)
{
using std::begin;
auto cached = cached_loop_pairs.find(std::distance(program.begin(), end_));
if (cached != end(cached_loop_pairs))
{
return cached->second;
}
std::size_t current_depth = 0;
auto i = end_;
for (;;)
{
assert(i != begin(program));
--i;
if (*i == command::end_loop)
{
++current_depth;
}
else if (*i == command::begin_loop)
{
if (current_depth == 0)
{
break;
}
--current_depth;
}
}
assert(current_depth == 0);
cached_loop_pairs.insert(std::make_pair(std::distance(program.begin(), end_), i));
return i;
}
template <class CommandRange>
typename CommandRange::const_iterator find_loop_end(
CommandRange const &program,
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> &cached_loop_pairs,
typename CommandRange::const_iterator const begin)
{
using std::end;
auto cached = cached_loop_pairs.find(std::distance(program.begin(), begin));
if (cached != end(cached_loop_pairs))
{
return cached->second;
}
std::size_t current_depth = 0;
auto i = begin;
for (;; ++i)
{
assert(i != end(program));
if (*i == command::begin_loop)
{
++current_depth;
}
else if (*i == command::end_loop)
{
if (current_depth == 0)
{
break;
}
--current_depth;
}
}
assert(current_depth == 0);
cached_loop_pairs.insert(std::make_pair(std::distance(program.begin(), begin), i));
return i;
}
template <class Input, class CommandRange, class MemoryRange>
auto execute(Input &&input, CommandRange const &program, MemoryRange &memory, std::size_t original_pointer)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::coroutine_observable<char>
#endif
{
return Si::make_coroutine<char>([
input SILICIUM_CAPTURE(std::forward<Input>(input)),
program,
&memory,
original_pointer
](Si::yield_context<char> &yield) mutable
{
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> loop_pairs;
auto pointer = original_pointer;
auto pc = boost::begin(program);
for (; pc != boost::end(program);)
{
switch (*pc)
{
case command::ptr_increment:
++pointer;
if (pointer == boost::size(memory))
{
pointer = 0;
}
++pc;
break;
case command::ptr_decrement:
if (pointer == 0)
{
pointer = boost::size(memory) - 1;
}
else
{
--pointer;
}
++pc;
break;
case command::value_increment:
++memory[pointer];
++pc;
break;
case command::value_decrement:
--memory[pointer];
++pc;
break;
case command::write:
yield(static_cast<char>(memory[pointer]));
++pc;
break;
case command::read:
{
auto in = yield.get_one(input);
if (!in)
{
return;
}
memory[pointer] = *in;
++pc;
break;
}
case command::begin_loop:
if (memory[pointer])
{
++pc;
}
else
{
pc = find_loop_end(program, loop_pairs, pc) + 1;
}
break;
case command::end_loop:
if (memory[pointer])
{
pc = find_loop_begin(program, loop_pairs, pc) + 1;
}
else
{
++pc;
}
break;
}
}
});
}
}
BOOST_AUTO_TEST_CASE(bf_empty)
{
Si::empty<char> input;
std::array<char, 1> memory{{}};
auto interpreter = bf::execute(input, boost::iterator_range<bf::command const *>(), memory, 0);
auto done = Si::for_each(std::move(interpreter), [](char output)
{
boost::ignore_unused_variable_warning(output);
BOOST_FAIL("no output expected");
});
done.start();
}
namespace
{
template <class CharSource>
std::vector<bf::command> scan_all(CharSource code)
{
std::vector<bf::command> result;
auto decoded = Si::make_transforming_source<boost::optional<bf::command>>(code, bf::detect_command);
for (;;)
{
auto cmd = Si::get(decoded);
if (!cmd)
{
break;
}
if (*cmd)
{
result.emplace_back(**cmd);
}
}
return result;
}
}
BOOST_AUTO_TEST_CASE(bf_hello_world)
{
std::string const hello_world = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
std::array<char, 100> memory{ {} };
Si::empty<char> input;
auto interpreter = bf::execute(input, scan_all(Si::make_container_source(hello_world)), memory, 0);
std::string printed;
auto done = Si::for_each(std::move(interpreter), [&printed](char output)
{
printed.push_back(output);
});
done.start();
BOOST_CHECK_EQUAL("Hello World!\n", printed);
}
<commit_msg>replace char with uint8_t to avoid dangerous overflows<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>
#include <silicium/transform_if_initialized.hpp>
#include <silicium/empty.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/memory_source.hpp>
#include <silicium/transforming_source.hpp>
#include <silicium/for_each.hpp>
#include <boost/unordered_map.hpp>
#include <unordered_map>
namespace bf
{
enum class command
{
ptr_increment,
ptr_decrement,
value_increment,
value_decrement,
write,
read,
begin_loop,
end_loop
};
boost::optional<command> detect_command(char c)
{
switch (c)
{
case '>': return command::ptr_increment;
case '<': return command::ptr_decrement;
case '+': return command::value_increment;
case '-': return command::value_decrement;
case '.': return command::write;
case ',': return command::read;
case '[': return command::begin_loop;
case ']': return command::end_loop;
default: return boost::none;
}
}
template <class Source>
auto scan(Source &&source)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::conditional_transformer<command, typename std::decay<Source>::type, boost::optional<command>(*)(char)>
#endif
{
return Si::transform_if_initialized(std::forward<Source>(source), detect_command);
}
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
# define SILICIUM_CAPTURE(x) = (x)
#else
# define SILICIUM_CAPTURE(x)
#endif
template <class CommandRange>
typename CommandRange::const_iterator find_loop_begin(
CommandRange const &program,
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> &cached_loop_pairs,
typename CommandRange::const_iterator const end_)
{
using std::begin;
auto cached = cached_loop_pairs.find(std::distance(program.begin(), end_));
if (cached != end(cached_loop_pairs))
{
return cached->second;
}
std::size_t current_depth = 0;
auto i = end_;
for (;;)
{
assert(i != begin(program));
--i;
if (*i == command::end_loop)
{
++current_depth;
}
else if (*i == command::begin_loop)
{
if (current_depth == 0)
{
break;
}
--current_depth;
}
}
assert(current_depth == 0);
cached_loop_pairs.insert(std::make_pair(std::distance(program.begin(), end_), i));
return i;
}
template <class CommandRange>
typename CommandRange::const_iterator find_loop_end(
CommandRange const &program,
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> &cached_loop_pairs,
typename CommandRange::const_iterator const begin)
{
using std::end;
auto cached = cached_loop_pairs.find(std::distance(program.begin(), begin));
if (cached != end(cached_loop_pairs))
{
return cached->second;
}
std::size_t current_depth = 0;
auto i = begin;
for (;; ++i)
{
assert(i != end(program));
if (*i == command::begin_loop)
{
++current_depth;
}
else if (*i == command::end_loop)
{
if (current_depth == 0)
{
break;
}
--current_depth;
}
}
assert(current_depth == 0);
cached_loop_pairs.insert(std::make_pair(std::distance(program.begin(), begin), i));
return i;
}
template <class Input, class CommandRange, class MemoryRange>
auto execute(Input &&input, CommandRange const &program, MemoryRange &memory, std::size_t original_pointer)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::coroutine_observable<boost::uint8_t>
#endif
{
return Si::make_coroutine<boost::uint8_t>([
input SILICIUM_CAPTURE(std::forward<Input>(input)),
program,
&memory,
original_pointer
](Si::yield_context<boost::uint8_t> &yield) mutable
{
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> loop_pairs;
auto pointer = original_pointer;
auto pc = boost::begin(program);
for (; pc != boost::end(program);)
{
switch (*pc)
{
case command::ptr_increment:
++pointer;
if (pointer == boost::size(memory))
{
pointer = 0;
}
++pc;
break;
case command::ptr_decrement:
if (pointer == 0)
{
pointer = boost::size(memory) - 1;
}
else
{
--pointer;
}
++pc;
break;
case command::value_increment:
++memory[pointer];
++pc;
break;
case command::value_decrement:
--memory[pointer];
++pc;
break;
case command::write:
yield(static_cast<char>(memory[pointer]));
++pc;
break;
case command::read:
{
auto in = yield.get_one(input);
if (!in)
{
return;
}
memory[pointer] = *in;
++pc;
break;
}
case command::begin_loop:
if (memory[pointer])
{
++pc;
}
else
{
pc = find_loop_end(program, loop_pairs, pc) + 1;
}
break;
case command::end_loop:
if (memory[pointer])
{
pc = find_loop_begin(program, loop_pairs, pc) + 1;
}
else
{
++pc;
}
break;
}
}
});
}
}
BOOST_AUTO_TEST_CASE(bf_empty)
{
Si::empty<boost::uint8_t> input;
std::array<boost::uint8_t, 1> memory{ {} };
auto interpreter = bf::execute(input, boost::iterator_range<bf::command const *>(), memory, 0);
auto done = Si::for_each(std::move(interpreter), [](boost::uint8_t output)
{
boost::ignore_unused_variable_warning(output);
BOOST_FAIL("no output expected");
});
done.start();
}
namespace
{
template <class CharSource>
std::vector<bf::command> scan_all(CharSource code)
{
std::vector<bf::command> result;
auto decoded = Si::make_transforming_source<boost::optional<bf::command>>(code, bf::detect_command);
for (;;)
{
auto cmd = Si::get(decoded);
if (!cmd)
{
break;
}
if (*cmd)
{
result.emplace_back(**cmd);
}
}
return result;
}
}
BOOST_AUTO_TEST_CASE(bf_hello_world)
{
std::string const hello_world = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
std::array<boost::uint8_t, 100> memory{ {} };
Si::empty<boost::uint8_t> input;
auto interpreter = bf::execute(input, scan_all(Si::make_container_source(hello_world)), memory, 0);
std::string printed;
auto done = Si::for_each(std::move(interpreter), [&printed](boost::uint8_t output)
{
printed.push_back(output);
});
done.start();
BOOST_CHECK_EQUAL("Hello World!\n", printed);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true;
else if (flags.at(i).at(k) == 'l')
isL = true;
else if (flags.at(i).at(k) == 'R')
isR = true;
}
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
vector<int> directoryIndex;
bool directoryInArgv = false;
for (int i = 1; i < argc; ++i) {
if (isDirectory(argv[i])) {
directoryInArgv = true;
break;
}
else {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
}
}
if (!directoryInArgv) {
if (errno == lsWithFlags(".", flags)) {
return errno;
}
}
else {
for (int i = 0; i < argc; ++i) {
if (isDirectory(argv[i])) {
directories.push_back(argv[i]);
directoryIndex.push_back(i);
}
}
for (int i = 0; i < directories.size(); ++i) {
flags.clear();
for (int k = directoryIndex.at(i); (i + 1) < directoryIndex.size() &&
k != directoryIndex.at(i + 1); ++k) {
if (argv[k][0] == '-') {
flags.push_back(argv[k]);
}
}
if (errno == lsWithFlags(directories.at(i), flags) {
return errno;
}
}
}
}
}
<commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true;
else if (flags.at(i).at(k) == 'l')
isL = true;
else if (flags.at(i).at(k) == 'R')
isR = true;
}
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
vector<int> directoryIndex;
bool directoryInArgv = false;
for (int i = 1; i < argc; ++i) {
if (isDirectory(argv[i])) {
directoryInArgv = true;
break;
}
else {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
}
}
if (!directoryInArgv) {
if (errno == lsWithFlags(".", flags)) {
return errno;
}
}
else {
for (int i = 0; i < argc; ++i) {
if (isDirectory(argv[i])) {
directories.push_back(argv[i]);
directoryIndex.push_back(i);
}
}
for (unsigned int i = 0; i < directories.size(); ++i) {
flags.clear();
for (unsigned int k = directoryIndex.at(i); (i + 1) < directoryIndex.size() &&
k != directoryIndex.at(i + 1); ++k) {
if (argv[k][0] == '-') {
flags.push_back(argv[k]);
}
}
if (errno == lsWithFlags(directories.at(i), flags) {
return errno;
}
}
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace std;
using namespace boost;
//next three bools used for ease of access to flags
bool hasa = false; //holds flag for a
bool hasl = false; //holds flag for l
bool hasR = false; //hold flag for R
bool compareNoCase(const string& s1, const string& s2)
{ //takes care of capital letter comparisons
return strcasecmp( s1.c_str(), s2.c_str() ) <= 0;
}
void make_strings(int size, char** parse, vector<string> &give)
{ //converts char** argv into vector of strings for easier use
for(int i = 1; i < size; ++i)
{
give.push_back(string(parse[i]));
}
}
void identify(const vector<string> &commands, vector<int> &dirs , bool &cond)
{
for(unsigned int i = 0; i < commands.size(); ++i)
{
if(commands.at(i).at(0) == '-')
{
for(unsigned int j = 1; j < commands.at(i).size(); ++j)
{
if((commands.at(i).at(j) == 'a') && !hasa)
{
hasa = true;
}
else if((commands.at(i).at(j) == 'l') && !hasl)
{
hasl = true;
}
else if((commands.at(i).at(j) == 'R') && !hasR)
{
hasR = true;
}
else if((commands.at(i).at(j) != 'R') && (commands.at(i).at(j) != 'a') && (commands.at(i).at(j) != 'l'))
{
cond = false;
}
}
} //this function identifies where the directories are in the command line
else
{
dirs.push_back(i+1);
} //determines what the flags are, and checks if they are all valid
}
}
void getfiles(vector<string> &currfiles, char** argv, const unsigned int &loc) //this function gets all the files and directories
{ //from whatever directory it is pointed to, and stores them in a vector of strings
DIR *currdir;
struct dirent *files;
errno = 0;
if(NULL == (currdir = opendir(argv[loc])))
{
perror("There was an error with opendir() ");
exit(1);
}
while(NULL != (files = readdir(currdir)))
{
currfiles.push_back(string(files->d_name));
}
if(errno != 0)
{
perror("There was an error with readdir() ");
exit(1);
}
if(-1 == closedir(currdir))
{
perror("There was an error with closedir() ");
exit(1);
}
sort(currfiles.begin(), currfiles.end(), compareNoCase);
}
void outputnorm(vector<string> &display)
{ //outputs the files/directories based on a flag
if(hasa)
{
for(unsigned int i = 0; i < display.size(); ++i)
{
cout << display.at(i) << " ";
}
}
else
{
for(unsigned int i = 0; i < display.size(); ++i)
{
if(display.at(i).at(0) != '.')
{
cout << display.at(i) << " ";
}
}
}
cout << endl;
}
void withouthidden(const vector<string> &take, vector<string> &give)
{ //replaces the vector of strings without the hidden files
for(unsigned int i = 0; i < take.size(); ++i)
{
if(take.at(i).at(0) != '.')
{
give.push_back(take.at(i));
}
}
sort(give.begin(), give.end(), compareNoCase);
}
void getpath(const vector<string> &take, vector<string> &give, vector<string> &org, unsigned int place)
{ //gets you the absolute path
for(unsigned int i = 0; i < take.size(); ++i)
{
char *ptr = new char[1024];
if(NULL == (getcwd(ptr, 1024)))
{
perror("There was an error with getcwd() ");
exit(1);
}
strcat(ptr, "/");
strcat(ptr, org.at(place).c_str());
strcat(ptr, "/");
strcat(ptr, take.at(i).c_str());
give.push_back(string(ptr));
delete []ptr;
}
}
void outputl(vector<string> &files, vector<string> &org, unsigned int place)
{
struct passwd *userid;
struct group *groupid;
struct stat status;
vector<string> path;
getpath(files, path, org, place);
for(unsigned int i = 0; i < path.size(); ++i)
{
if(-1 == (stat(path.at(i).c_str(), &status)))
{
perror("There was an error with stat() ");
exit(1);
}
else
{
if(S_IFDIR & status.st_mode)
{
cout << 'd';
}
else if(S_ISLNK(status.st_mode))
{
cout << 'l';
}
else
{
cout << '-';
}
cout << ((S_IRUSR & status.st_mode) ? 'r' : '-');
cout << ((S_IWUSR & status.st_mode) ? 'w' : '-');
cout << ((S_IXUSR & status.st_mode) ? 'x' : '-');
cout << ((S_IRGRP & status.st_mode) ? 'r' : '-');
cout << ((S_IWGRP & status.st_mode) ? 'w' : '-');
cout << ((S_IXGRP & status.st_mode) ? 'x' : '-');
cout << ((S_IROTH & status.st_mode) ? 'r' : '-');
cout << ((S_IWOTH & status.st_mode) ? 'w' : '-');
cout << ((S_IXOTH & status.st_mode) ? 'x' : '-');
cout << ' ' << status.st_nlink << ' ';
if(NULL == (userid = getpwuid(status.st_uid)))
{
perror("There was an error with getpwuid() ");
exit(1);
}
else
{
cout << userid->pw_name << ' ';
}
if(NULL == (groupid = getgrgid(status.st_gid)))
{
perror("There was an error with getgrdid() ");
exit(1);
}
else
{
cout << groupid->gr_name << ' ';
}
cout << status.st_size << ' ';
struct tm *tm;
char timebuf[15];
if(NULL == (tm = localtime(&(status.st_mtime))))
{
perror("There was an error with localtime() ");
exit(1);
}
else
{
strftime(timebuf, 15, "%b %d %H:%M", tm);
cout << timebuf << ' ';
}
cout << files.at(i);
}
cout << endl;
}
}
int main(int argc, char **argv)
{
vector<string> commands;
vector<int> directories;
vector<string> dirfiles;
bool okay = true;
make_strings(argc, argv, commands); //first change all inputs into strings
identify(commands, directories, okay); //organize and get all the info
if(okay) //if no errors in flag, proceed to output
{
if(directories.size() > 0) //if directories were specified, come here
{
for(unsigned int i = 0; i < directories.size(); ++i)
{
getfiles(dirfiles, argv, directories.at(i));
if(directories.size() > 1)
{
cout << commands.at(directories.at(i)-1) << ": " << endl;
}
if(!hasl && !hasR) //if no l or R flag, simple case, do this
{
outputnorm(dirfiles);
}
else if(hasl && !hasR)
{
if(hasa)
{
outputl(dirfiles, commands, directories.at(i)-1);
}
else
{
vector<string> temp;
withouthidden(dirfiles, temp);
vector<string> look;
outputl(temp, commands, directories.at(i)-1);
}
}
if(directories.size() > 1)
{
cout << commands.at(directories.at(i)-1) << ": " << endl;
}
dirfiles.clear();
}
}
else //if no directory was specified, implied current directory, manually pass in . directory
{
char *temp[1];
temp[0] = new char('.');
getfiles(dirfiles, temp, 0);
if(!hasl && !hasR) //if no l or R flag, simple case, do this
{
outputnorm(dirfiles);
}
else if(hasl && !hasR)
{
vector<string> quick;
quick.push_back(".");
if(hasa)
{
outputl(dirfiles, quick, 0);
}
else
{
vector<string> temp;
withouthidden(dirfiles, temp);
outputl(temp, quick, 0);
}
}
delete temp[0];
}
}
else
{
cout << "Error: flag not recognized or valid. " << endl;
}
return 0;
}
<commit_msg>completely done with -a and -l<commit_after>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace std;
using namespace boost;
//next three bools used for ease of access to flags
bool hasa = false; //holds flag for a
bool hasl = false; //holds flag for l
bool hasR = false; //hold flag for R
bool compareNoCase(const string& s1, const string& s2)
{ //takes care of capital letter comparisons
return strcasecmp( s1.c_str(), s2.c_str() ) <= 0;
}
void make_strings(int size, char** parse, vector<string> &give)
{ //converts char** argv into vector of strings for easier use
for(int i = 1; i < size; ++i)
{
give.push_back(string(parse[i]));
}
}
void identify(const vector<string> &commands, vector<int> &dirs , bool &cond)
{
for(unsigned int i = 0; i < commands.size(); ++i)
{
if(commands.at(i).at(0) == '-')
{
for(unsigned int j = 1; j < commands.at(i).size(); ++j)
{
if((commands.at(i).at(j) == 'a') && !hasa)
{
hasa = true;
}
else if((commands.at(i).at(j) == 'l') && !hasl)
{
hasl = true;
}
else if((commands.at(i).at(j) == 'R') && !hasR)
{
hasR = true;
}
else if((commands.at(i).at(j) != 'R') && (commands.at(i).at(j) != 'a') && (commands.at(i).at(j) != 'l'))
{
cond = false;
}
}
} //this function identifies where the directories are in the command line
else
{
dirs.push_back(i+1);
} //determines what the flags are, and checks if they are all valid
}
}
void getfiles(vector<string> &currfiles, char** argv, const unsigned int &loc) //this function gets all the files and directories
{ //from whatever directory it is pointed to, and stores them in a vector of strings
DIR *currdir;
struct dirent *files;
errno = 0;
if(NULL == (currdir = opendir(argv[loc])))
{
perror("There was an error with opendir() ");
exit(1);
}
while(NULL != (files = readdir(currdir)))
{
currfiles.push_back(string(files->d_name));
}
if(errno != 0)
{
perror("There was an error with readdir() ");
exit(1);
}
if(-1 == closedir(currdir))
{
perror("There was an error with closedir() ");
exit(1);
}
sort(currfiles.begin(), currfiles.end(), compareNoCase);
}
void outputnorm(vector<string> &display)
{ //outputs the files/directories based on a flag
if(hasa)
{
for(unsigned int i = 0; i < display.size(); ++i)
{
cout << display.at(i) << " ";
}
}
else
{
for(unsigned int i = 0; i < display.size(); ++i)
{
if(display.at(i).at(0) != '.')
{
cout << display.at(i) << " ";
}
}
}
cout << endl;
}
void withouthidden(const vector<string> &take, vector<string> &give)
{ //replaces the vector of strings without the hidden files
for(unsigned int i = 0; i < take.size(); ++i)
{
if(take.at(i).at(0) != '.')
{
give.push_back(take.at(i));
}
}
sort(give.begin(), give.end(), compareNoCase);
}
void getpath(const vector<string> &take, vector<string> &give, vector<string> &org, unsigned int place)
{ //gets you the absolute path
for(unsigned int i = 0; i < take.size(); ++i)
{
char *ptr = new char[1024];
if(NULL == (getcwd(ptr, 1024)))
{
perror("There was an error with getcwd() ");
exit(1);
}
strcat(ptr, "/");
strcat(ptr, org.at(place).c_str());
strcat(ptr, "/");
strcat(ptr, take.at(i).c_str());
give.push_back(string(ptr));
delete []ptr;
}
}
void outputl(vector<string> &files, vector<string> &org, unsigned int place)
{
struct passwd *userid;
struct group *groupid;
struct stat status;
vector<string> path;
getpath(files, path, org, place);
int total = 0;
for(unsigned int i = 0; i < path.size(); ++i)
{
if(-1 == (stat(path.at(i).c_str(), &status)))
{
perror("There was an error with stat() ");
exit(1);
}
else
{
total += status.st_blocks;
}
}
cout << "Total: " << total/2 << endl;
for(unsigned int i = 0; i < path.size(); ++i)
{
if(-1 == (stat(path.at(i).c_str(), &status)))
{
perror("There was an error with stat() ");
exit(1);
}
else
{
if(S_IFDIR & status.st_mode)
{
cout << 'd';
}
else if(S_ISLNK(status.st_mode))
{
cout << 'l';
}
else
{
cout << '-';
}
cout << ((S_IRUSR & status.st_mode) ? 'r' : '-');
cout << ((S_IWUSR & status.st_mode) ? 'w' : '-');
cout << ((S_IXUSR & status.st_mode) ? 'x' : '-');
cout << ((S_IRGRP & status.st_mode) ? 'r' : '-');
cout << ((S_IWGRP & status.st_mode) ? 'w' : '-');
cout << ((S_IXGRP & status.st_mode) ? 'x' : '-');
cout << ((S_IROTH & status.st_mode) ? 'r' : '-');
cout << ((S_IWOTH & status.st_mode) ? 'w' : '-');
cout << ((S_IXOTH & status.st_mode) ? 'x' : '-');
cout << ' ' << status.st_nlink << ' ';
if(NULL == (userid = getpwuid(status.st_uid)))
{
perror("There was an error with getpwuid() ");
exit(1);
}
else
{
cout << userid->pw_name << ' ';
}
if(NULL == (groupid = getgrgid(status.st_gid)))
{
perror("There was an error with getgrdid() ");
exit(1);
}
else
{
cout << groupid->gr_name << ' ';
}
cout << status.st_size << ' ';
struct tm *tm;
char timebuf[15];
if(NULL == (tm = localtime(&(status.st_mtime))))
{
perror("There was an error with localtime() ");
exit(1);
}
else
{
strftime(timebuf, 15, "%b %d %H:%M", tm);
cout << timebuf << ' ';
}
cout << files.at(i);
}
cout << endl;
}
}
int main(int argc, char **argv)
{
vector<string> commands;
vector<int> directories;
vector<string> dirfiles;
bool okay = true;
make_strings(argc, argv, commands); //first change all inputs into strings
identify(commands, directories, okay); //organize and get all the info
if(okay) //if no errors in flag, proceed to output
{
if(directories.size() > 0) //if directories were specified, come here
{
for(unsigned int i = 0; i < directories.size(); ++i)
{
getfiles(dirfiles, argv, directories.at(i));
if(directories.size() > 1)
{
cout << commands.at(directories.at(i)-1) << ": " << endl;
}
if(!hasl && !hasR) //if no l or R flag, simple case, do this
{
outputnorm(dirfiles);
}
else if(hasl && !hasR)
{
if(hasa)
{
outputl(dirfiles, commands, directories.at(i)-1);
}
else
{
vector<string> temp;
withouthidden(dirfiles, temp);
vector<string> look;
outputl(temp, commands, directories.at(i)-1);
}
}
if(directories.size() > 1)
{
cout << commands.at(directories.at(i)-1) << ": " << endl;
}
dirfiles.clear();
}
}
else //if no directory was specified, implied current directory, manually pass in . directory
{
char *temp[1];
temp[0] = new char('.');
getfiles(dirfiles, temp, 0);
if(!hasl && !hasR) //if no l or R flag, simple case, do this
{
outputnorm(dirfiles);
}
else if(hasl && !hasR)
{
vector<string> quick;
quick.push_back(".");
if(hasa)
{
outputl(dirfiles, quick, 0);
}
else
{
vector<string> temp;
withouthidden(dirfiles, temp);
outputl(temp, quick, 0);
}
}
delete temp[0];
}
}
else
{
cout << "Error: flag not recognized or valid. " << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>
#include <vector>
#include <queue>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
void parse_flags(const int argc, char* argv[], bool& flag_a,
bool& flag_l, bool& flag_R, queue<string> &q_dirs)
{
unsigned count = argc;
for(int i = count - 1; i != 0; --i)
{
if(argv[i][0] == '-')
{
if(argv[i][1] == '\0')
{
cout << "Error: invalid flag" << endl;
exit(1);
}
for(int j = 1; argv[i][j] != '\0'; ++j)
{
if (argv[i][j] == 'a')
{
flag_a = true;
}
else if(argv[i][j] == 'l')
{
flag_l = true;
}
else if(argv[i][j] == 'R')
{
flag_R = true;
}
}
}
else
{
q_dirs.push(argv[i]);
}
}
}
void get_perm(struct stat &info, string& perm)
{
if(S_ISREG(info.st_mode)) perm[0] = '-';
else if(S_ISDIR(info.st_mode)) perm[0] = 'd';
else if(S_ISBLK(info.st_mode)) perm[0] = 'b';
else if(S_ISCHR(info.st_mode)) perm[0] = 'c';
else if(S_ISLNK(info.st_mode)) perm[0] = 'l';
if(S_IRUSR & info.st_mode) perm[1] = 'r';
if(S_IWUSR & info.st_mode) perm[2] = 'w';
if(S_IXUSR & info.st_mode) perm[3] = 'x';
if(S_IRGRP & info.st_mode) perm[4] = 'r';
if(S_IWGRP & info.st_mode) perm[5] = 'w';
if(S_IXGRP & info.st_mode) perm[6] = 'x';
if(S_IROTH & info.st_mode) perm[7] = 'r';
if(S_IWOTH & info.st_mode) perm[8] = 'w';
if(S_IXOTH & info.st_mode) perm[9] = 'x';
}
void get_usrgrp(struct stat &info, string& usr, string& grp)
{
struct passwd *user;
if(!(user = getpwuid(info.st_uid)))
{
perror("getpwuid()");
}
struct group *gp;
if(!(gp = getgrgid(info.st_gid)))
{
perror("getgrgid()");
}
usr = user->pw_name;
grp = gp->gr_name;
}
int calc_total_block(vector<string>& v_files, string& path_curr)
{
int total = 0;
for(int i = 0; i < v_files.size(); ++i)
{
struct stat info;
if(-1 == stat((path_curr + "/" + (v_files[i])).c_str(), &info))
{
perror("stat()");
}
total += info.st_blocks;
}
return total/2;
}
void print_long(vector<string>& v_files, string& path_curr)
{
int total = calc_total_block(v_files, path_curr);
cout << "total " << total << endl;
for(int i = 0; i < v_files.size(); ++i)
{
struct stat info;
if(-1 == stat((path_curr + "/" + (v_files[i])).c_str(), &info))
{
perror("stat()");
exit(1);
}
string perm = "----------";
string usr;
string grp;
get_perm(info,perm);
get_usrgrp(info,usr,grp);
string time = ctime(&info.st_mtime);
time = time.substr(4,time.length() - 13);
cout << right;
cout << perm << " ";
cout << right;
cout << setw(2) << info.st_nlink << " ";
cout << left;
cout << setw(3) << usr << " ";
cout << left;
cout << setw(3) << grp << " ";
cout << right;
cout << setw(4) << info.st_size << " ";
cout << right;
cout << setw(6) << time << " ";
cout << left;
cout << setw(3) << v_files[i] << endl;
}
}
bool ignore_case(const string &x, const string &y)
{
if(tolower(x[0]) < tolower(y[0])) return true;
else if (tolower(x[0]) > tolower(y[0])) return false;
return x < y;
}
void do_recursive(queue<string> &q_dirs, vector<string> &v_files, string &path_curr)
{
if(!v_files.empty())
{
for(int i = v_files.size() - 1; i != 0; --i)
{
struct stat info;
if(-1 == stat((path_curr + "/" + (v_files[i])).c_str(), &info))
{
perror("stat()");
exit(1);
}
if(info.st_mode & S_IFDIR)
{
q_dirs.push(path_curr + "/" + v_files[i]);
}
}
}
}
int main(int argc, char* argv[])
{
if(argc < 1)
{
cout << "Error: No arguments passed in." << endl;
exit(1);
}
else
{
bool flag_a = false;
bool flag_l = false;
bool flag_R = false;
queue<string> q_dirs;
vector<string> v_files;
parse_flags(argc, argv, flag_a, flag_l, flag_R, q_dirs);
//lets ls check cwd without having to pass .
if(q_dirs.empty()) q_dirs.push(".");
while(!q_dirs.empty())
{
string path_curr = q_dirs.front();
DIR *dirp;
if(NULL == (dirp = opendir(q_dirs.front().c_str())))
{
perror("opendir()");
exit(1);
}
struct dirent *files;
errno = 0;
while(NULL != (files = readdir(dirp)))
{
if(files->d_name[0] == '.' && flag_a == false)
{
continue;
}
v_files.push_back(files->d_name);
}
//alphabetize
sort(v_files.begin(), v_files.end(), ignore_case);
if(flag_R)
{
cout << path_curr << ":" << endl;
do_recursive(q_dirs, v_files, path_curr);
}
if(!flag_l)
{
for(vector<string>::iterator it = v_files.begin(); it != v_files.end(); ++it)
{
cout << *it << " ";
}
}
if(flag_l)
{
print_long(v_files, path_curr);
}
q_dirs.pop();
if(errno != 0)
{
perror("readdir()");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp))
{
perror("closedir()");
exit(1);
}
}
}
return 0;
}
<commit_msg>added colors<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>
#include <vector>
#include <queue>
#include <iomanip>
#include <algorithm>
#include <string>
#define blue "\033[1;34m"
#define green "\033[1;32m"
#define gray "\033[;40m"
#define no_c "\033[m"
using namespace std;
void parse_flags(const int argc, char* argv[], bool& flag_a,
bool& flag_l, bool& flag_R, queue<string> &q_dirs)
{
unsigned count = argc;
for(int i = count - 1; i != 0; --i)
{
if(argv[i][0] == '-')
{
if(argv[i][1] == '\0')
{
cout << "Error: invalid flag" << endl;
exit(1);
}
for(int j = 1; argv[i][j] != '\0'; ++j)
{
if (argv[i][j] == 'a')
{
flag_a = true;
}
else if(argv[i][j] == 'l')
{
flag_l = true;
}
else if(argv[i][j] == 'R')
{
flag_R = true;
}
}
}
else
{
q_dirs.push(argv[i]);
}
}
}
void get_perm(struct stat &info, string& perm)
{
if(S_ISREG(info.st_mode)) perm[0] = '-';
else if(S_ISDIR(info.st_mode)) perm[0] = 'd';
else if(S_ISBLK(info.st_mode)) perm[0] = 'b';
else if(S_ISCHR(info.st_mode)) perm[0] = 'c';
else if(S_ISLNK(info.st_mode)) perm[0] = 'l';
if(S_IRUSR & info.st_mode) perm[1] = 'r';
if(S_IWUSR & info.st_mode) perm[2] = 'w';
if(S_IXUSR & info.st_mode) perm[3] = 'x';
if(S_IRGRP & info.st_mode) perm[4] = 'r';
if(S_IWGRP & info.st_mode) perm[5] = 'w';
if(S_IXGRP & info.st_mode) perm[6] = 'x';
if(S_IROTH & info.st_mode) perm[7] = 'r';
if(S_IWOTH & info.st_mode) perm[8] = 'w';
if(S_IXOTH & info.st_mode) perm[9] = 'x';
}
void get_usrgrp(struct stat &info, string& usr, string& grp)
{
struct passwd *user;
if(!(user = getpwuid(info.st_uid)))
{
perror("getpwuid()");
}
struct group *gp;
if(!(gp = getgrgid(info.st_gid)))
{
perror("getgrgid()");
}
usr = user->pw_name;
grp = gp->gr_name;
}
int calc_total_block(vector<string>& v_files, string& path_curr)
{
int total = 0;
for(int i = 0; i < v_files.size(); ++i)
{
struct stat info;
if(-1 == stat((path_curr + "/" + (v_files[i])).c_str(), &info))
{
perror("stat()");
}
total += info.st_blocks;
}
return total/2;
}
void print_long(vector<string>& v_files, string& path_curr)
{
int total = calc_total_block(v_files, path_curr);
cout << "total " << total << endl;
for(int i = 0; i < v_files.size(); ++i)
{
struct stat info;
if(-1 == stat((path_curr + "/" + (v_files[i])).c_str(), &info))
{
perror("stat()");
//exit(1);
}
string perm = "----------";
string usr;
string grp;
get_perm(info,perm);
get_usrgrp(info,usr,grp);
string time = ctime(&info.st_mtime);
time = time.substr(4,time.length() - 13);
cout << right;
cout << perm << " ";
cout << right;
cout << setw(2) << info.st_nlink << " ";
cout << left;
cout << setw(3) << usr << " ";
cout << left;
cout << setw(3) << grp << " ";
cout << right;
cout << setw(4) << info.st_size << " ";
cout << right;
cout << setw(10) << time << " ";
cout << left;
if(v_files[i][0] == '.')
{
if(S_ISDIR(info.st_mode))
{
cout << gray << blue << setw(3) << v_files[i] << no_c << endl;
}
else if((S_IXUSR & info.st_mode) || (S_IXGRP & info.st_mode) ||
(S_IXOTH & info.st_mode))
{
cout << gray << green << setw(3) << v_files[i] << no_c << endl;
}
else
{
cout << gray << setw(3) << v_files[i] << no_c << endl;
}
}
else if(S_ISDIR(info.st_mode))
{
cout << blue << setw(3) << v_files[i] << no_c << endl;
}
else if((S_IXUSR & info.st_mode) || (S_IXGRP & info.st_mode) ||
(S_IXOTH & info.st_mode))
{
cout << green << setw(3) << v_files[i] << no_c << endl;
}
else
{
cout << setw(3) << v_files[i] << no_c << endl;
}
}
}
bool ignore_case(const string &x, const string &y)
{
if(tolower(x[0]) < tolower(y[0])) return true;
else if (tolower(x[0]) > tolower(y[0])) return false;
return x < y;
}
void do_recursive(queue<string> &q_dirs, vector<string> &v_files, string &path_curr)
{
if(!v_files.empty())
{
for(unsigned i = 0; i < v_files.size(); ++i)
{
struct stat info;
if(-1 == stat((path_curr + "/" + v_files[i]).c_str(), &info))
{
perror("stat()");
//exit(1);
}
if(S_ISDIR(info.st_mode)) //&& !((v_files[i][0] == '\0' ))))
{
q_dirs.push(path_curr + "/" + v_files[i]);
}
//else
//{
//q_dirs.push(path_curr + v_files[i]);
//}
}
}
}
int main(int argc, char* argv[])
{
if(argc < 1)
{
cout << "Error: No arguments passed in." << endl;
exit(1);
}
else
{
bool flag_a = false;
bool flag_l = false;
bool flag_R = false;
queue<string> q_dirs;
vector<string> v_files;
parse_flags(argc, argv, flag_a, flag_l, flag_R, q_dirs);
//lets ls check cwd without having to pass .
if(q_dirs.empty()) q_dirs.push(".");
while(!q_dirs.empty())
{
string path_curr = q_dirs.front();
DIR *dirp;
if(NULL == (dirp = opendir(q_dirs.front().c_str())))
{
perror("opendir()");
exit(1);
}
struct dirent *files;
errno = 0;
while(NULL != (files = readdir(dirp)))
{
if(files->d_name[0] == '.' && flag_a == false)
{
continue;
}
v_files.push_back(files->d_name);
}
//alphabetize
sort(v_files.begin(), v_files.end(), ignore_case);
q_dirs.pop();
if(flag_R)
{
cout << path_curr << ":" << endl;
do_recursive(q_dirs, v_files, path_curr);
}
if(!flag_l)
{
for(int i =0; i < v_files.size(); ++i)
{
struct stat for_color;
if(-1 == stat((path_curr+"/"+(v_files[i])).c_str(), &for_color))
{
perror("stat()");
}
if(v_files[i][0] == '.')
{
if(S_ISDIR(for_color.st_mode))
{
cout << gray << blue << v_files[i] << no_c << " ";
}
else if((S_IXUSR & for_color.st_mode) || (S_IXGRP & for_color.st_mode) ||
(S_IXOTH & for_color.st_mode))
{
cout << gray << green << v_files[i] << no_c << " ";
}
else
{
cout << gray << v_files[i] << no_c << endl;
}
}
else if(S_ISDIR(for_color.st_mode))
{
cout << blue << v_files[i] << no_c << " ";
}
else if((S_IXUSR & for_color.st_mode) || (S_IXGRP & for_color.st_mode) ||
(S_IXOTH & for_color.st_mode))
{
cout << green << v_files[i] << no_c << " ";
}
else
{
cout << v_files[i] << " ";
}
}
if(flag_R)
{
if(!q_dirs.empty()) cout << endl;
}
}
if(flag_l)
{
print_long(v_files, path_curr);
}
//q_dirs.pop();
if(errno != 0)
{
perror("readdir()");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp))
{
perror("closedir()");
exit(1);
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include <targetPAL.h>
#include <corlib_native.h>
#include "sys_dev_gpio_native_target.h"
#include "nf_rt_events_native.h"
#include "sys_dev_gpio_native.h"
// just make it shorter and readable
typedef Library_sys_dev_gpio_native_System_Device_Gpio_PinValue PinValue;
// declared here as external
// the implementation will be moved here when Windows.Devices.Gpio is removed
extern void Gpio_Interupt_ISR(GPIO_PIN pinNumber, bool pinState, void *pArg);
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read___SystemDeviceGpioPinValue(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
bool pinValue;
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
NANOCLR_CHECK_HRESULT(Read(pThis, pinValue));
stack.SetResult_I4(pinValue);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Toggle___VOID(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// check if object has been disposed
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[FIELD___pinMode].NumericByRefConst().s4;
// sanity check for drive mode set to output so we don't mess up writing to an input pin
if (driveMode >= GpioPinDriveMode_Output)
{
CPU_GPIO_TogglePinState(pinNumber);
// fire event, only if there are callbacks registered
if (pThis[FIELD___callbacks].Dereference() != NULL)
{
PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)CPU_GPIO_GetPinState(pinNumber));
}
}
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::DisposeNative___VOID(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// set pin to input to save power
// clear interrupts
// releases the pin
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, 0);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::
NativeIsPinModeSupported___BOOLEAN__SystemDeviceGpioPinMode(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;
// Return value to the managed application
stack.SetResult_Boolean(CPU_GPIO_DriveModeSupported(pinNumber, driveMode));
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetPinMode___VOID__SystemDeviceGpioPinMode(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;
NANOCLR_CHECK_HRESULT(SetPinMode(pThis, driveMode));
// protect this from GC so that the callback is where it's supposed to
CLR_RT_ProtectFromGC gc(*pThis);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDebounceTimeout___VOID(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_UINT64 debounceTimeoutMilsec;
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(pThis[FIELD___debounceTimeout], debounceTimeoutMilsec));
// developer note:
// the following call will FAIL if the pin hasn't been previously setup as input
// that's OK because the debounce timeout will be eventually set when the pin is configured
CPU_GPIO_SetPinDebounce(pinNumber, debounceTimeoutMilsec);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::WriteNative___VOID__SystemDeviceGpioPinValue(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
GpioPinValue state;
CLR_RT_HeapBlock *pinValue;
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// check if object has been disposed
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
// get PinValue object from parameter
pinValue = stack.Arg1().Dereference();
// access value field inside PinValue
state = (GpioPinValue)pinValue[PinValue::FIELD___value].NumericByRef().u1;
NANOCLR_CHECK_HRESULT(Write(pThis, state));
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// check if object has been disposed
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
// get pin number and take the port and pad references from that one
int16_t pinNumber = pThis[FIELD___pinNumber].NumericByRefConst().s4;
// get alternate function argument
int32_t alternateFunction = stack.Arg1().NumericByRef().s4;
CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, alternateFunction);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeInit___BOOLEAN__I4(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
GPIO_PIN pinNumber = (GPIO_PIN)stack.Arg1().NumericByRef().s4;
// Return value to the managed application
stack.SetResult_Boolean(CPU_GPIO_ReservePin(pinNumber, true));
}
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::ExtractDebounceTimeSpanValue(
CLR_RT_HeapBlock &timeSpanValue,
CLR_UINT64 &value)
{
NANOCLR_HEADER();
{
// debounceTimeout field its a TimeSpan, which is a primitive type stored as an heap block, therefore needs to
// be accessed indirectly
CLR_INT64 *debounceValue = Library_corlib_native_System_TimeSpan::GetValuePtr(timeSpanValue);
FAULT_ON_NULL(debounceValue);
value = *(CLR_UINT64 *)debounceValue / TIME_CONVERSION__TO_MILLISECONDS;
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::SetPinMode(
CLR_RT_HeapBlock *gpioPin,
GpioPinDriveMode pinMode)
{
NANOCLR_HEADER();
bool validPin;
CLR_UINT64 debounceTimeoutMilsec;
bool callbacksRegistered = false;
GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4;
if (pinMode >= (int)GpioPinDriveMode_Output)
{
validPin = CPU_GPIO_EnableOutputPin(pinNumber, GpioPinValue_Low, pinMode);
}
else
{
NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(gpioPin[FIELD___debounceTimeout], debounceTimeoutMilsec));
// flag to determine if there are any callbacks registered in managed code
// this is use to determine if there is any need to setup and process INT handler
callbacksRegistered = (gpioPin[FIELD___callbacks].Dereference() != NULL);
validPin = CPU_GPIO_EnableInputPin(
pinNumber,
debounceTimeoutMilsec,
callbacksRegistered ? Gpio_Interupt_ISR : NULL,
NULL,
GPIO_INT_EDGE_BOTH,
pinMode);
}
if (validPin)
{
// all good, store pin mode in managed field
gpioPin[FIELD___pinMode].NumericByRef().s4 = pinMode;
}
else
{
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Write(CLR_RT_HeapBlock *gpioPin, GpioPinValue pinValue)
{
GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4;
GpioPinDriveMode driveMode = (GpioPinDriveMode)gpioPin[FIELD___pinMode].NumericByRefConst().s4;
// sanity check for drive mode set to output so we don't mess up writing to an input pin
if ((driveMode >= GpioPinDriveMode_Output))
{
CPU_GPIO_SetPinState(pinNumber, pinValue);
// fire event if there are callbacks registered
if (gpioPin[FIELD___callbacks].Dereference() != NULL)
{
PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)pinValue);
}
}
else
{
return CLR_E_INVALID_PARAMETER;
}
return S_OK;
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read(CLR_RT_HeapBlock *gpioPin, bool &pinValue)
{
GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4;
pinValue = CPU_GPIO_GetPinState(pinNumber);
return S_OK;
}
<commit_msg>Fix System.Device GpioPin.Read (#1898)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include <targetPAL.h>
#include <corlib_native.h>
#include "sys_dev_gpio_native_target.h"
#include "nf_rt_events_native.h"
#include "sys_dev_gpio_native.h"
// just make it shorter and readable
typedef Library_sys_dev_gpio_native_System_Device_Gpio_PinValue PinValue;
// declared here as external
// the implementation will be moved here when Windows.Devices.Gpio is removed
extern void Gpio_Interupt_ISR(GPIO_PIN pinNumber, bool pinState, void *pArg);
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read___SystemDeviceGpioPinValue(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
CLR_RT_TypeDef_Index gpioPinTypeDef;
CLR_RT_HeapBlock *hbObj;
bool pinValue;
CLR_RT_HeapBlock &top = stack.PushValue();
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
NANOCLR_CHECK_HRESULT(Read(pThis, pinValue));
// find <GpioPin> type definition, don't bother checking the result as it exists for sure
g_CLR_RT_TypeSystem.FindTypeDef("GpioPin", "System.Device.Gpio", gpioPinTypeDef);
// create an instance of <GpioPin>
NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, gpioPinTypeDef));
// dereference the object in order to reach its fields
hbObj = top.Dereference();
hbObj[Library_sys_dev_gpio_native_System_Device_Gpio_PinValue::FIELD___value].NumericByRef().u1 = pinValue;
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Toggle___VOID(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// check if object has been disposed
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[FIELD___pinMode].NumericByRefConst().s4;
// sanity check for drive mode set to output so we don't mess up writing to an input pin
if (driveMode >= GpioPinDriveMode_Output)
{
CPU_GPIO_TogglePinState(pinNumber);
// fire event, only if there are callbacks registered
if (pThis[FIELD___callbacks].Dereference() != NULL)
{
PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)CPU_GPIO_GetPinState(pinNumber));
}
}
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::DisposeNative___VOID(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// set pin to input to save power
// clear interrupts
// releases the pin
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, 0);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::
NativeIsPinModeSupported___BOOLEAN__SystemDeviceGpioPinMode(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;
// Return value to the managed application
stack.SetResult_Boolean(CPU_GPIO_DriveModeSupported(pinNumber, driveMode));
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetPinMode___VOID__SystemDeviceGpioPinMode(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;
NANOCLR_CHECK_HRESULT(SetPinMode(pThis, driveMode));
// protect this from GC so that the callback is where it's supposed to
CLR_RT_ProtectFromGC gc(*pThis);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDebounceTimeout___VOID(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_UINT64 debounceTimeoutMilsec;
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4;
NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(pThis[FIELD___debounceTimeout], debounceTimeoutMilsec));
// developer note:
// the following call will FAIL if the pin hasn't been previously setup as input
// that's OK because the debounce timeout will be eventually set when the pin is configured
CPU_GPIO_SetPinDebounce(pinNumber, debounceTimeoutMilsec);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::WriteNative___VOID__SystemDeviceGpioPinValue(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
GpioPinValue state;
CLR_RT_HeapBlock *pinValue;
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// check if object has been disposed
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
// get PinValue object from parameter
pinValue = stack.Arg1().Dereference();
// access value field inside PinValue
state = (GpioPinValue)pinValue[PinValue::FIELD___value].NumericByRef().u1;
NANOCLR_CHECK_HRESULT(Write(pThis, state));
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
CLR_RT_HeapBlock *pThis = stack.This();
FAULT_ON_NULL(pThis);
// check if object has been disposed
if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0)
{
NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);
}
// get pin number and take the port and pad references from that one
int16_t pinNumber = pThis[FIELD___pinNumber].NumericByRefConst().s4;
// get alternate function argument
int32_t alternateFunction = stack.Arg1().NumericByRef().s4;
CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, alternateFunction);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeInit___BOOLEAN__I4(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
{
GPIO_PIN pinNumber = (GPIO_PIN)stack.Arg1().NumericByRef().s4;
// Return value to the managed application
stack.SetResult_Boolean(CPU_GPIO_ReservePin(pinNumber, true));
}
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::ExtractDebounceTimeSpanValue(
CLR_RT_HeapBlock &timeSpanValue,
CLR_UINT64 &value)
{
NANOCLR_HEADER();
{
// debounceTimeout field its a TimeSpan, which is a primitive type stored as an heap block, therefore needs to
// be accessed indirectly
CLR_INT64 *debounceValue = Library_corlib_native_System_TimeSpan::GetValuePtr(timeSpanValue);
FAULT_ON_NULL(debounceValue);
value = *(CLR_UINT64 *)debounceValue / TIME_CONVERSION__TO_MILLISECONDS;
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::SetPinMode(
CLR_RT_HeapBlock *gpioPin,
GpioPinDriveMode pinMode)
{
NANOCLR_HEADER();
bool validPin;
CLR_UINT64 debounceTimeoutMilsec;
bool callbacksRegistered = false;
GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4;
if (pinMode >= (int)GpioPinDriveMode_Output)
{
validPin = CPU_GPIO_EnableOutputPin(pinNumber, GpioPinValue_Low, pinMode);
}
else
{
NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(gpioPin[FIELD___debounceTimeout], debounceTimeoutMilsec));
// flag to determine if there are any callbacks registered in managed code
// this is use to determine if there is any need to setup and process INT handler
callbacksRegistered = (gpioPin[FIELD___callbacks].Dereference() != NULL);
validPin = CPU_GPIO_EnableInputPin(
pinNumber,
debounceTimeoutMilsec,
callbacksRegistered ? Gpio_Interupt_ISR : NULL,
NULL,
GPIO_INT_EDGE_BOTH,
pinMode);
}
if (validPin)
{
// all good, store pin mode in managed field
gpioPin[FIELD___pinMode].NumericByRef().s4 = pinMode;
}
else
{
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Write(CLR_RT_HeapBlock *gpioPin, GpioPinValue pinValue)
{
GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4;
GpioPinDriveMode driveMode = (GpioPinDriveMode)gpioPin[FIELD___pinMode].NumericByRefConst().s4;
// sanity check for drive mode set to output so we don't mess up writing to an input pin
if ((driveMode >= GpioPinDriveMode_Output))
{
CPU_GPIO_SetPinState(pinNumber, pinValue);
// fire event if there are callbacks registered
if (gpioPin[FIELD___callbacks].Dereference() != NULL)
{
PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)pinValue);
}
}
else
{
return CLR_E_INVALID_PARAMETER;
}
return S_OK;
}
HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read(CLR_RT_HeapBlock *gpioPin, bool &pinValue)
{
GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4;
pinValue = CPU_GPIO_GetPinState(pinNumber);
return S_OK;
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <net/inet4>
#include <service>
#include <net/ws/websocket.hpp>
void handle_ws(net::WebSocket_ptr ws)
{
static std::map<int, net::WebSocket_ptr> websockets;
static int idx = 0;
// nullptr means the WS attempt failed
if(not ws) {
printf("WS failed\n");
return;
}
printf("WS Connected: %s\n", ws->to_string().c_str());
// Write a welcome message
ws->write("Welcome");
ws->write(ws->to_string());
// Setup echo reply
ws->on_read = [ws = ws.get()](auto msg) {
auto str = msg->as_text();
printf("WS Recv: %s\n", str.c_str());
ws->write(str);
};
websockets[idx] = std::move(ws);
// Notify on close
websockets[idx]->on_close = [key = idx](auto code) {
printf("WS Closing (%u) %s\n", code, websockets[key]->to_string().c_str());
};
idx++;
}
#include <net/http/server.hpp>
#include <memdisk>
std::unique_ptr<http::Server> server;
void Service::start()
{
// Retreive the stack (configured from outside)
auto& inet = net::Inet4::stack<0>();
Expects(inet.is_configured());
// Init the memdisk
auto& disk = fs::memdisk();
disk.init_fs([] (auto err, auto&) {
Expects(not err);
});
// Retreive the HTML page from the disk
auto file = disk.fs().read_file("/index.html");
Expects(file.is_valid());
Chunk html{file.data(), file.size()};
// Create a HTTP Server and setup request handling
server = std::make_unique<http::Server>(inet.tcp());
server->on_request([html] (auto req, auto rw)
{
// We only support get
if(req->method() != http::GET) {
rw->write_header(http::Not_Found);
return;
}
// Serve HTML on /
if(req->uri() == "/") {
rw->write(html);
}
// WebSockets go here
else if(req->uri() == "/ws") {
auto ws = net::WebSocket::upgrade(*req, *rw);
handle_ws(std::move(ws));
}
else {
rw->write_header(http::Not_Found);
}
});
// Start listening on port 80
server->listen(80);
}
<commit_msg>fix panic on close or 2+ connections<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <net/inet4>
#include <service>
#include <net/ws/websocket.hpp>
void handle_ws(net::WebSocket_ptr ws)
{
static std::map<int, net::WebSocket_ptr> websockets;
static int idx = 0;
// nullptr means the WS attempt failed
if(not ws) {
printf("WS failed\n");
return;
}
printf("WS Connected: %s\n", ws->to_string().c_str());
// Write a welcome message
ws->write("Welcome");
ws->write(ws->to_string());
// Setup echo reply
ws->on_read = [ws = ws.get()](auto msg) {
auto str = msg->as_text();
printf("WS Recv: %s\n", str.c_str());
ws->write(str);
};
ws->on_close = [ws = ws.get()](auto code) {
// Notify on close
printf("WS Closing (%u) %s\n", code, ws->to_string().c_str());
};
websockets[idx++] = std::move(ws);
}
#include <net/http/server.hpp>
#include <memdisk>
std::unique_ptr<http::Server> server;
void Service::start()
{
// Retreive the stack (configured from outside)
auto& inet = net::Inet4::stack<0>();
Expects(inet.is_configured());
// Init the memdisk
auto& disk = fs::memdisk();
disk.init_fs([] (auto err, auto&) {
Expects(not err);
});
// Retreive the HTML page from the disk
auto file = disk.fs().read_file("/index.html");
Expects(file.is_valid());
Chunk html{file.data(), file.size()};
// Create a HTTP Server and setup request handling
server = std::make_unique<http::Server>(inet.tcp());
server->on_request([html] (auto req, auto rw)
{
// We only support get
if(req->method() != http::GET) {
rw->write_header(http::Not_Found);
return;
}
// Serve HTML on /
if(req->uri() == "/") {
rw->write(html);
}
// WebSockets go here
else if(req->uri() == "/ws") {
auto ws = net::WebSocket::upgrade(*req, *rw);
handle_ws(std::move(ws));
}
else {
rw->write_header(http::Not_Found);
}
});
// Start listening on port 80
server->listen(80);
}
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2001.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
//! @file
//! @brief Floating point comparison tolerance manipulators
//!
//! This file defines several manipulators for floating point comparison. These
//! manipulators are intended to be used with BOOST_TEST.
// ***************************************************************************
#ifndef BOOST_TEST_TOOLS_DETAIL_TOLERANCE_MANIP_HPP_012705GER
#define BOOST_TEST_TOOLS_DETAIL_TOLERANCE_MANIP_HPP_012705GER
// Boost Test
#include <boost/test/tools/detail/fwd.hpp>
#include <boost/test/tools/detail/indirections.hpp>
#include <boost/test/tools/fpc_tolerance.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace test_tools {
namespace tt_detail {
// ************************************************************************** //
// ************** fpc tolerance manipulator ************** //
// ************************************************************************** //
template<typename FPT>
struct tolerance_manip {
explicit tolerance_manip( FPT const & tol ) : m_value( tol ) {}
FPT m_value;
};
//____________________________________________________________________________//
struct tolerance_manip_delay {};
template<typename FPT>
inline tolerance_manip<FPT>
operator%( FPT v, tolerance_manip_delay const& )
{
BOOST_STATIC_ASSERT_MSG( (fpc::tolerance_based<FPT>::value),
"tolerance should be specified using a floating points type" );
return tolerance_manip<FPT>( FPT(v / 100) );
}
//____________________________________________________________________________//
template<typename E, typename FPT>
inline assertion_result
operator<<(assertion_evaluate_t<E> const& ae, tolerance_manip<FPT> const& tol)
{
local_fpc_tolerance<FPT> lt( tol.m_value );
return ae.m_e.evaluate();
}
//____________________________________________________________________________//
template<typename FPT>
inline int
operator<<( unit_test::lazy_ostream const&, tolerance_manip<FPT> const& ) { return 0; }
//____________________________________________________________________________//
template<typename FPT>
inline check_type
operator<<( assertion_type const& /*at*/, tolerance_manip<FPT> const& ) { return CHECK_BUILT_ASSERTION; }
//____________________________________________________________________________//
} // namespace tt_detail
/*! Tolerance manipulator
*
* These functions return a manipulator that can be used in conjunction with BOOST_TEST
* in order to specify the tolerance with which floating point comparisons are made.
*/
template<typename FPT>
inline tt_detail::tolerance_manip<FPT>
tolerance( FPT v )
{
BOOST_STATIC_ASSERT_MSG( (fpc::tolerance_based<FPT>::value),
"tolerance only for floating points" );
return tt_detail::tolerance_manip<FPT>( v );
}
//____________________________________________________________________________//
//! @overload tolerance( FPT v )
template<typename FPT>
inline tt_detail::tolerance_manip<FPT>
tolerance( fpc::percent_tolerance_t<FPT> v )
{
BOOST_STATIC_ASSERT_MSG( (fpc::tolerance_based<FPT>::value),
"tolerance only for floating points" );
return tt_detail::tolerance_manip<FPT>( static_cast<FPT>(v.m_value / 100) );
}
//____________________________________________________________________________//
//! @overload tolerance( FPT v )
inline tt_detail::tolerance_manip_delay
tolerance()
{
return tt_detail::tolerance_manip_delay();
}
//____________________________________________________________________________//
} // namespace test_tools
} // namespace boost
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_TOOLS_DETAIL_TOLERANCE_MANIP_HPP_012705GER
<commit_msg>Revert "slightly improved error message"<commit_after>// (C) Copyright Gennadiy Rozental 2001.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
//! @file
//! @brief Floating point comparison tolerance manipulators
//!
//! This file defines several manipulators for floating point comparison. These
//! manipulators are intended to be used with BOOST_TEST.
// ***************************************************************************
#ifndef BOOST_TEST_TOOLS_DETAIL_TOLERANCE_MANIP_HPP_012705GER
#define BOOST_TEST_TOOLS_DETAIL_TOLERANCE_MANIP_HPP_012705GER
// Boost Test
#include <boost/test/tools/detail/fwd.hpp>
#include <boost/test/tools/detail/indirections.hpp>
#include <boost/test/tools/fpc_tolerance.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace test_tools {
namespace tt_detail {
// ************************************************************************** //
// ************** fpc tolerance manipulator ************** //
// ************************************************************************** //
template<typename FPT>
struct tolerance_manip {
explicit tolerance_manip( FPT const & tol ) : m_value( tol ) {}
FPT m_value;
};
//____________________________________________________________________________//
struct tolerance_manip_delay {};
template<typename FPT>
inline tolerance_manip<FPT>
operator%( FPT v, tolerance_manip_delay const& )
{
BOOST_STATIC_ASSERT_MSG( (fpc::tolerance_based<FPT>::value),
"tolerance only for floating points" );
return tolerance_manip<FPT>( FPT(v / 100) );
}
//____________________________________________________________________________//
template<typename E, typename FPT>
inline assertion_result
operator<<(assertion_evaluate_t<E> const& ae, tolerance_manip<FPT> const& tol)
{
local_fpc_tolerance<FPT> lt( tol.m_value );
return ae.m_e.evaluate();
}
//____________________________________________________________________________//
template<typename FPT>
inline int
operator<<( unit_test::lazy_ostream const&, tolerance_manip<FPT> const& ) { return 0; }
//____________________________________________________________________________//
template<typename FPT>
inline check_type
operator<<( assertion_type const& /*at*/, tolerance_manip<FPT> const& ) { return CHECK_BUILT_ASSERTION; }
//____________________________________________________________________________//
} // namespace tt_detail
/*! Tolerance manipulator
*
* These functions return a manipulator that can be used in conjunction with BOOST_TEST
* in order to specify the tolerance with which floating point comparisons are made.
*/
template<typename FPT>
inline tt_detail::tolerance_manip<FPT>
tolerance( FPT v )
{
BOOST_STATIC_ASSERT_MSG( (fpc::tolerance_based<FPT>::value),
"tolerance only for floating points" );
return tt_detail::tolerance_manip<FPT>( v );
}
//____________________________________________________________________________//
//! @overload tolerance( FPT v )
template<typename FPT>
inline tt_detail::tolerance_manip<FPT>
tolerance( fpc::percent_tolerance_t<FPT> v )
{
BOOST_STATIC_ASSERT_MSG( (fpc::tolerance_based<FPT>::value),
"tolerance only for floating points" );
return tt_detail::tolerance_manip<FPT>( static_cast<FPT>(v.m_value / 100) );
}
//____________________________________________________________________________//
//! @overload tolerance( FPT v )
inline tt_detail::tolerance_manip_delay
tolerance()
{
return tt_detail::tolerance_manip_delay();
}
//____________________________________________________________________________//
} // namespace test_tools
} // namespace boost
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_TOOLS_DETAIL_TOLERANCE_MANIP_HPP_012705GER
<|endoftext|> |
<commit_before>/*
* Copyright 2011,
* Olivier Stasse, CNRS
*
* CNRS
*
* This file is part of sot-core.
* sot-core is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#define ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#include <vector>
#include <map>
#include <string>
#include <sot/core/api.hh>
namespace dynamicgraph {
namespace sot {
class SOT_CORE_EXPORT NamedVector
{
private:
std::string name_;
std::vector<double> values_;
public:
NamedVector() {};
~NamedVector() {};
const std::string & getName()
{ return name_;}
void setName(const std::string & aname)
{ name_ = aname;}
const std::vector<double> & getValues()
{ return values_;}
void setValues(std::vector<double> values)
{ values_ = values;}
};
typedef NamedVector SensorValues;
typedef NamedVector ControlValues;
class SOT_CORE_EXPORT AbstractSotExternalInterface
{
public:
AbstractSotExternalInterface(){};
virtual ~AbstractSotExternalInterface(){};
virtual void setupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void nominalSetSensors(std::map<std::string, SensorValues> &sensorsIn)=0;
virtual void cleanupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void getControl(std::map<std::string,ControlValues> &)=0;
};
}
}
typedef dynamicgraph::sot::AbstractSotExternalInterface * createSotExternalInterface_t();
typedef void destroySotExternalInterface_t (dynamicgraph::sot::AbstractSotExternalInterface *);
#endif
<commit_msg>Add const in the controller interface, remove useless semi-colon<commit_after>/*
* Copyright 2011,
* Olivier Stasse, CNRS
*
* CNRS
*
* This file is part of sot-core.
* sot-core is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#define ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#include <vector>
#include <map>
#include <string>
#include <sot/core/api.hh>
namespace dynamicgraph {
namespace sot {
class SOT_CORE_EXPORT NamedVector
{
private:
std::string name_;
std::vector<double> values_;
public:
NamedVector() {}
~NamedVector() {}
const std::string & getName() const
{ return name_;}
void setName(const std::string & aname)
{ name_ = aname;}
const std::vector<double> & getValues() const
{ return values_;}
void setValues(const std::vector<double> & values)
{ values_ = values;}
};
typedef NamedVector SensorValues;
typedef NamedVector ControlValues;
class SOT_CORE_EXPORT AbstractSotExternalInterface
{
public:
AbstractSotExternalInterface(){}
virtual ~AbstractSotExternalInterface(){}
virtual void setupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void nominalSetSensors(std::map<std::string, SensorValues> &sensorsIn)=0;
virtual void cleanupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void getControl(std::map<std::string,ControlValues> &)=0;
};
}
}
typedef dynamicgraph::sot::AbstractSotExternalInterface * createSotExternalInterface_t();
typedef void destroySotExternalInterface_t (dynamicgraph::sot::AbstractSotExternalInterface *);
#endif
<|endoftext|> |
<commit_before>int main(int argc, char *argv[])
{
// Reads from the file build/version_number the new version
// number and generates the header base/inc/RVersion.h.
// To be executed as CINT script by build/unix/makeversion.sh.
//
// Author: Fons Rademakers 11/10/99
const char *in = "build/version_number";
FILE *fp = fopen(in, "r");
if (!fp) {
printf("%s: can not open input file %s\n", argv[0], in);
exit(1);
}
char vers[32];
fgets(vers, sizeof(vers), fp);
if (vers[strlen(vers)-1] == '\n') vers[strlen(vers)-1] = 0;
fclose(fp);
const char *out = "base/inc/RVersion.h";
FILE *fp = fopen(out, "w");
if (!fp) {
printf("%s: can not open output file %s\n", argv[0], out);
exit(1);
}
fprintf(fp, "#ifndef ROOT_RVersion\n");
fprintf(fp, "#define ROOT_RVersion\n\n");
fprintf(fp, "/* Version information automatically generated by installer. */\n\n");
fprintf(fp, "/*\n");
fprintf(fp, " * These macros can be used in the following way:\n");
fprintf(fp, " *\n");
fprintf(fp, " * #if ROOT_VERSION_CODE >= ROOT_VERSION(2,23,4)\n");
fprintf(fp, " * #include <newheader.h>\n");
fprintf(fp, " * #else\n");
fprintf(fp, " * #include <oldheader.h>\n");
fprintf(fp, " * #endif\n");
fprintf(fp, " *\n");
fprintf(fp, "*/\n\n");
int xx, yy, zz;
sscanf(vers, "%d.%d/%d", &xx, &yy, &zz);
int vers_code = (xx << 16) + (yy << 8) + zz;
fprintf(fp, "#define ROOT_RELEASE \"%s\"\n", vers);
fprintf(fp, "#define ROOT_VERSION_CODE %d\n", vers_code);
fprintf(fp, "#define ROOT_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))\n");
fprintf(fp, "\n#endif\n");
fclose(fp);
exit(0);
}
<commit_msg>write in RVersion.h the ROOT_RELEASE_DATE and ROOT_RELEASE_TIME macros.<commit_after>int main(int argc, char *argv[])
{
// Reads from the file build/version_number the new version
// number and generates the header base/inc/RVersion.h.
// To be executed as CINT script by build/unix/makeversion.sh.
//
// Author: Fons Rademakers 11/10/99
const char *in = "build/version_number";
FILE *fp = fopen(in, "r");
if (!fp) {
printf("%s: can not open input file %s\n", argv[0], in);
exit(1);
}
char vers[32];
fgets(vers, sizeof(vers), fp);
if (vers[strlen(vers)-1] == '\n') vers[strlen(vers)-1] = 0;
fclose(fp);
const char *out = "base/inc/RVersion.h";
FILE *fp = fopen(out, "w");
if (!fp) {
printf("%s: can not open output file %s\n", argv[0], out);
exit(1);
}
fprintf(fp, "#ifndef ROOT_RVersion\n");
fprintf(fp, "#define ROOT_RVersion\n\n");
fprintf(fp, "/* Version information automatically generated by installer. */\n\n");
fprintf(fp, "/*\n");
fprintf(fp, " * These macros can be used in the following way:\n");
fprintf(fp, " *\n");
fprintf(fp, " * #if ROOT_VERSION_CODE >= ROOT_VERSION(2,23,4)\n");
fprintf(fp, " * #include <newheader.h>\n");
fprintf(fp, " * #else\n");
fprintf(fp, " * #include <oldheader.h>\n");
fprintf(fp, " * #endif\n");
fprintf(fp, " *\n");
fprintf(fp, "*/\n\n");
int xx, yy, zz;
sscanf(vers, "%d.%d/%d", &xx, &yy, &zz);
int vers_code = (xx << 16) + (yy << 8) + zz;
fprintf(fp, "#define ROOT_RELEASE \"%s\"\n", vers);
fprintf(fp, "#define ROOT_RELEASE_DATE \"%s\"\n", __DATE__);
fprintf(fp, "#define ROOT_RELEASE_TIME \"%s\"\n", __TIME__);
fprintf(fp, "#define ROOT_VERSION_CODE %d\n", vers_code);
fprintf(fp, "#define ROOT_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))\n");
fprintf(fp, "\n#endif\n");
fclose(fp);
exit(0);
}
<|endoftext|> |
<commit_before><commit_msg>Convert SV_DECL_PTRARR to std::vector<commit_after><|endoftext|> |
<commit_before>// https://leetcode.com/problems/word-break/
/*
Given a string s and a dictionary of words dict, determine if s can be segmented into a
space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
*/
#include <string>
#include <unordered_set>
using std::string;
using std::unordered_set;
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
return backTrack(s, 0, 0, wordDict, s.length());
}
private:
bool backTrack(string s, unsigned offset, unsigned pos, unordered_set<string>& d, size_t len) {
if (pos == len) return false;
string sub = s.substr(offset, pos + 1 - offset);
if (d.find(sub) != d.end()) {
if (pos == len - 1) return true;
else return backTrack(s, offset, pos + 1, d, len) || backTrack(s, pos + 1, pos + 1, d, len);
}
return backTrack(s, offset, pos + 1, d, len);
}
};
<commit_msg>:art: try to make word break better and fail<commit_after>// https://leetcode.com/problems/word-break/
/*
Given a string s and a dictionary of words dict, determine if s can be segmented into a
space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
*/
#include <string>
#include <vector>
#include <utility>
#include <unordered_set>
#include <unordered_map>
using std::pair;
using std::string;
using std::vector;
using std::unordered_set;
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
return backTrack(s, 0, 0, wordDict, s.length());
}
private:
vector<pair<unsigned, unsigned>> m_words;
bool backTrack(string s, unsigned offset, unsigned pos, unordered_set<string>& d, size_t len) {
if (pos == len) {
if (m_words.size() > offset) {
auto const& p = m_words.back(); m_words.pop_back();
return backTrack(s, p.first, p.second + 1, d, len);
} else {
return false;
}
}
string sub = s.substr(offset, pos + 1 - offset);
if (d.find(sub) != d.end()) {
if (pos == len - 1) return true;
else {
m_words.push_back(std::make_pair(offset, pos));
return backTrack(s, pos + 1, pos + 1, d, len);
}
}
return backTrack(s, offset, pos + 1, d, len);
}
};
<|endoftext|> |
<commit_before>/*******************************************************************************
* c7a/api/write.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com>
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_API_WRITE_HEADER
#define C7A_API_WRITE_HEADER
#include <c7a/api/action_node.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/core/stage_builder.hpp>
#include <fstream>
#include <string>
namespace c7a {
namespace api {
//! \addtogroup api Interface
//! \{
template <typename ValueType, typename ParentDIARef>
class WriteNode : public ActionNode
{
static const bool debug = false;
public:
using Super = ActionNode;
using Super::result_file_;
using Super::context_;
WriteNode(const ParentDIARef& parent,
const std::string& path_out,
StatsNode* stats_node)
: ActionNode(parent.ctx(), { parent.node() }, "Write", stats_node),
path_out_(path_out),
file_(path_out_),
emit_(file_)
{
sLOG << "Creating write node.";
auto pre_op_fn = [=](ValueType input) {
PreOp(input);
};
// close the function stack with our pre op and register it at parent
// node for output
auto lop_chain = parent.stack().push(pre_op_fn).emit();
parent.node()->RegisterChild(lop_chain);
}
void PreOp(ValueType input) {
emit_(input);
}
//! Closes the output file
void Execute() override {
sLOG << "closing file" << path_out_;
emit_.Close();
}
void Dispose() override { }
/*!
* Returns "[WriteNode]" and its id as a string.
* \return "[WriteNode]"
*/
std::string ToString() override {
return "[WriteNode] Id:" + result_file_.ToString();
}
protected:
//! OutputEmitter let's you write to files. Each element is written
//! using ostream.
class OutputEmitter
{
public:
explicit OutputEmitter(std::ofstream& file)
: out_(file) { }
//! write item out using ostream formatting / serialization.
void operator () (const ValueType& v) {
out_ << v;
}
//! Flushes and closes the block (cannot be undone)
//! No further emitt operations can be done afterwards.
void Close() {
assert(!closed_);
closed_ = true;
out_.close();
}
//! Writes the data to the target without closing the emitter
void Flush() {
out_.flush();
}
private:
//! output stream
std::ofstream& out_;
//! whether the output stream is closed.
bool closed_ = false;
};
private:
//! Path of the output file.
std::string path_out_;
//! File to write to
std::ofstream file_;
//! Emitter to file
OutputEmitter emit_;
};
template <typename ValueType, typename Stack>
void DIARef<ValueType, Stack>::WriteToFileSystem(
const std::string& filepath) const {
using WriteResultNode = WriteNode<ValueType, DIARef>;
StatsNode* stats_node = AddChildStatsNode("Write", "Action");
auto shared_node =
std::make_shared<WriteResultNode>(*this,
filepath,
stats_node);
core::StageBuilder().RunScope(shared_node.get());
}
//! \}
} // namespace api
} // namespace c7a
#endif // !C7A_API_WRITE_HEADER
/******************************************************************************/
<commit_msg>remove outputemitter<commit_after>/*******************************************************************************
* c7a/api/write.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com>
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_API_WRITE_HEADER
#define C7A_API_WRITE_HEADER
#include <c7a/api/action_node.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/core/stage_builder.hpp>
#include <fstream>
#include <string>
namespace c7a {
namespace api {
//! \addtogroup api Interface
//! \{
template <typename ValueType, typename ParentDIARef>
class WriteNode : public ActionNode
{
static const bool debug = false;
public:
using Super = ActionNode;
using Super::result_file_;
using Super::context_;
WriteNode(const ParentDIARef& parent,
const std::string& path_out,
StatsNode* stats_node)
: ActionNode(parent.ctx(), { parent.node() }, "Write", stats_node),
path_out_(path_out),
file_(path_out_)
{
sLOG << "Creating write node.";
auto pre_op_fn = [=](ValueType input) {
PreOp(input);
};
// close the function stack with our pre op and register it at parent
// node for output
auto lop_chain = parent.stack().push(pre_op_fn).emit();
parent.node()->RegisterChild(lop_chain);
}
void PreOp(ValueType input) {
file_ << input;
}
//! Closes the output file
void Execute() override {
sLOG << "closing file" << path_out_;
file_.close();
}
void Dispose() override { }
/*!
* Returns "[WriteNode]" and its id as a string.
* \return "[WriteNode]"
*/
std::string ToString() override {
return "[WriteNode] Id:" + result_file_.ToString();
}
private:
//! Path of the output file.
std::string path_out_;
//! File to write to
std::ofstream file_;
};
template <typename ValueType, typename Stack>
void DIARef<ValueType, Stack>::WriteToFileSystem(
const std::string& filepath) const {
using WriteResultNode = WriteNode<ValueType, DIARef>;
StatsNode* stats_node = AddChildStatsNode("Write", "Action");
auto shared_node =
std::make_shared<WriteResultNode>(*this,
filepath,
stats_node);
core::StageBuilder().RunScope(shared_node.get());
}
//! \}
} // namespace api
} // namespace c7a
#endif // !C7A_API_WRITE_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>// Copyright (C) 2017 Rob Caelers <rob.caelers@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "os/BeaconScanner.hpp"
#ifdef CONFIG_BT_ENABLED
#include "bt.h"
#include "esp_bt_main.h"
#include "esp_log.h"
#include "os/Task.hpp"
static const char tag[] = "BLE";
using namespace os;
static esp_ble_scan_params_t ble_scan_params = {
.scan_type = BLE_SCAN_TYPE_PASSIVE,
.own_addr_type = BLE_ADDR_TYPE_PUBLIC,
.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL,
.scan_interval = 0x10,
.scan_window = 0x10,
};
BeaconScanner::BeaconScanner()
: task("beaconscanner_task", std::bind(&BeaconScanner::bt_task, this))
{
}
BeaconScanner::~BeaconScanner()
{
}
void
BeaconScanner::gap_event_handler_static(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
BeaconScanner::instance().gap_event_handler(event, param);
}
void
BeaconScanner::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
switch (event)
{
case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
{
ESP_LOGI(tag, "Scan param set complete, start scanning.");
esp_ble_gap_start_scanning(scan_duration);
break;
}
case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
if (param->scan_start_cmpl.status != ESP_BT_STATUS_SUCCESS)
{
ESP_LOGE(tag, "Scan start failed.");
}
else
{
ESP_LOGI(tag, "Scan start successfully.");
}
break;
case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
if (param->scan_stop_cmpl.status != ESP_BT_STATUS_SUCCESS)
{
ESP_LOGE(tag, "Scan stop failed.");
}
else
{
ESP_LOGI(tag, "Scan stop successfully.");
}
break;
case ESP_GAP_BLE_SCAN_RESULT_EVT:
{
esp_ble_gap_cb_param_t *scan_result = (esp_ble_gap_cb_param_t *)param;
switch (scan_result->scan_rst.search_evt)
{
case ESP_GAP_SEARCH_INQ_RES_EVT:
{
static uint8_t ibeacon_prefix[] =
{
0x02, 0x01, 0x00, 0x1A, 0xFF, 0x4C, 0x00, 0x02, 0x15
};
uint8_t *addr = scan_result->scan_rst.bda;
scan_result->scan_rst.ble_adv[2] = 0x00;
for (int i = 0; i < sizeof(ibeacon_prefix); i++) {
if (scan_result->scan_rst.ble_adv[i] != ibeacon_prefix[i]) {
return;
}
}
char mac[18];
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
signal_scan_result(ScanResult(scan_result->scan_rst.rssi, mac));
break;
}
case ESP_GAP_SEARCH_INQ_CMPL_EVT: {
ESP_LOGI(tag, "Scan completed, restarting.");
signal_scan_complete();
xEventGroupSetBits(event_group, RESTART_BIT);
break;
}
default:
ESP_LOGI(tag, "Unhandled scan result %d.", scan_result->scan_rst.search_evt);
break;
}
break;
}
default:
break;
}
}
void
BeaconScanner::init()
{
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BTDM);
esp_bluedroid_init();
esp_bluedroid_enable();
event_group = xEventGroupCreate();
}
void
BeaconScanner::deinit()
{
esp_bluedroid_disable();
esp_bluedroid_deinit();
esp_bt_controller_disable(ESP_BT_MODE_BTDM);
esp_bt_controller_deinit();
}
void
BeaconScanner::start()
{
xEventGroupWaitBits(event_group, READY_BIT, false, true, portMAX_DELAY);
esp_ble_gap_register_callback(gap_event_handler_static);
esp_ble_gap_set_scan_params(&ble_scan_params);
}
void
BeaconScanner::stop()
{
esp_ble_gap_stop_scanning();
}
// TODO: remove this BLE stack restart workaround once ESP-IDF BLE is stable
void
BeaconScanner::bt_task()
{
init();
xEventGroupSetBits(event_group, READY_BIT);
while (1)
{
xEventGroupWaitBits(event_group, RESTART_BIT, true, true, portMAX_DELAY);
// TODO: stop/start during re-init may not be safe.
esp_bluedroid_disable();
esp_bluedroid_enable();
esp_ble_gap_register_callback(gap_event_handler_static);
esp_ble_gap_set_scan_params(&ble_scan_params);
}
}
os::Signal<void()> &
BeaconScanner::scan_complete_signal()
{
return signal_scan_complete;
}
os::Signal<void(os::BeaconScanner::ScanResult)> &
BeaconScanner::scan_result_signal()
{
return signal_scan_result;
}
#endif
<commit_msg>Use new ESP-IDF bluetooth API<commit_after>// Copyright (C) 2017 Rob Caelers <rob.caelers@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "os/BeaconScanner.hpp"
#ifdef CONFIG_BT_ENABLED
#include "bt.h"
#include "esp_bt_main.h"
#include "esp_log.h"
#include "os/Task.hpp"
static const char tag[] = "BLE";
using namespace os;
static esp_ble_scan_params_t ble_scan_params = {
.scan_type = BLE_SCAN_TYPE_PASSIVE,
.own_addr_type = BLE_ADDR_TYPE_PUBLIC,
.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL,
.scan_interval = 0x10,
.scan_window = 0x10,
};
BeaconScanner::BeaconScanner()
: task("beaconscanner_task", std::bind(&BeaconScanner::bt_task, this))
{
}
BeaconScanner::~BeaconScanner()
{
}
void
BeaconScanner::gap_event_handler_static(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
BeaconScanner::instance().gap_event_handler(event, param);
}
void
BeaconScanner::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
switch (event)
{
case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
{
ESP_LOGI(tag, "Scan param set complete, start scanning.");
esp_ble_gap_start_scanning(scan_duration);
break;
}
case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
if (param->scan_start_cmpl.status != ESP_BT_STATUS_SUCCESS)
{
ESP_LOGE(tag, "Scan start failed.");
}
else
{
ESP_LOGI(tag, "Scan start successfully.");
}
break;
case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
if (param->scan_stop_cmpl.status != ESP_BT_STATUS_SUCCESS)
{
ESP_LOGE(tag, "Scan stop failed.");
}
else
{
ESP_LOGI(tag, "Scan stop successfully.");
}
break;
case ESP_GAP_BLE_SCAN_RESULT_EVT:
{
esp_ble_gap_cb_param_t *scan_result = (esp_ble_gap_cb_param_t *)param;
switch (scan_result->scan_rst.search_evt)
{
case ESP_GAP_SEARCH_INQ_RES_EVT:
{
static uint8_t ibeacon_prefix[] =
{
0x02, 0x01, 0x00, 0x1A, 0xFF, 0x4C, 0x00, 0x02, 0x15
};
uint8_t *addr = scan_result->scan_rst.bda;
scan_result->scan_rst.ble_adv[2] = 0x00;
for (int i = 0; i < sizeof(ibeacon_prefix); i++) {
if (scan_result->scan_rst.ble_adv[i] != ibeacon_prefix[i]) {
return;
}
}
char mac[18];
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
signal_scan_result(ScanResult(scan_result->scan_rst.rssi, mac));
break;
}
case ESP_GAP_SEARCH_INQ_CMPL_EVT: {
ESP_LOGI(tag, "Scan completed, restarting.");
signal_scan_complete();
xEventGroupSetBits(event_group, RESTART_BIT);
break;
}
default:
ESP_LOGI(tag, "Unhandled scan result %d.", scan_result->scan_rst.search_evt);
break;
}
break;
}
default:
break;
}
}
void
BeaconScanner::init()
{
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BTDM);
esp_bluedroid_init();
esp_bluedroid_enable();
event_group = xEventGroupCreate();
}
void
BeaconScanner::deinit()
{
esp_bluedroid_disable();
esp_bluedroid_deinit();
esp_bt_controller_disable();
esp_bt_controller_deinit();
}
void
BeaconScanner::start()
{
xEventGroupWaitBits(event_group, READY_BIT, false, true, portMAX_DELAY);
esp_ble_gap_register_callback(gap_event_handler_static);
esp_ble_gap_set_scan_params(&ble_scan_params);
}
void
BeaconScanner::stop()
{
esp_ble_gap_stop_scanning();
}
// TODO: remove this BLE stack restart workaround once ESP-IDF BLE is stable
void
BeaconScanner::bt_task()
{
init();
xEventGroupSetBits(event_group, READY_BIT);
while (1)
{
xEventGroupWaitBits(event_group, RESTART_BIT, true, true, portMAX_DELAY);
// TODO: stop/start during re-init may not be safe.
esp_bluedroid_disable();
esp_bluedroid_enable();
esp_ble_gap_register_callback(gap_event_handler_static);
esp_ble_gap_set_scan_params(&ble_scan_params);
}
}
os::Signal<void()> &
BeaconScanner::scan_complete_signal()
{
return signal_scan_complete;
}
os::Signal<void(os::BeaconScanner::ScanResult)> &
BeaconScanner::scan_result_signal()
{
return signal_scan_result;
}
#endif
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
//#include <atomic>
namespace libbirch {
/**
* Atomic value.
*
* @tparam Value type.
*
* The implementation uses OpenMP atomics as opposed to std::atomic. The
* advantage of this is ensured memory model consistency and the organic
* disabling of atomics when OpenMP, and thus multithreading, is
* disabled (this can improve performance significantly for single threading).
* The disadvantage is that OpenMP atomics do not support
* compare-and-swap/compare-and-exchange, only swap/exchange, which requires
* some clunkier client code, especially for read-write locks.
*
* Atomic provides the default constructor, copy and move constructors, copy
* and move assignment operators, in order to be trivially copyable and so
* a mappable type for the purposes of OpenMP. These constructors and
* operators *do not* behave atomically, however.
*
* @internal An alternative implementation, in comments, uses std::atomic.
*/
template<class T>
class Atomic {
public:
/**
* Default constructor. Initializes the value, not necessarily atomically.
*/
Atomic() = default;
/**
* Constructor.
*
* @param value Initial value.
*
* Initializes the value, atomically.
*/
explicit Atomic(const T& value) {
store(value);
}
/**
* Load the value, atomically.
*/
T load() const {
//return this->value.load();
T value;
#pragma omp atomic read
value = this->value;
return value;
}
/**
* Store the value, atomically.
*/
void store(const T& value) {
//return this->value.store(value);
#pragma omp atomic write
this->value = value;
}
/**
* Exchange the value with another, atomically.
*
* @param value New value.
*
* @return Old value.
*/
T exchange(const T& value) {
//return this->value.exchange(value);
T old;
#pragma omp atomic capture
{
old = this->value;
this->value = value;
}
return old;
}
/**
* Apply a mask, with bitwise `and`, and return the previous value,
* atomically.
*
* @param m Mask.
*
* @return Previous value.
*/
T exchangeAnd(const T& value) {
//return this->value.fetch_and(value);
T old;
#pragma omp atomic capture
{
old = this->value;
this->value &= value;
}
return old;
}
/**
* Apply a mask, with bitwise `or`, and return the previous value,
* atomically.
*
* @param m Mask.
*
* @return Previous value.
*/
T exchangeOr(const T& value) {
//return this->value.fetch_or(value);
T old;
#pragma omp atomic capture
{
old = this->value;
this->value |= value;
}
return old;
}
/**
* Apply a mask, with bitwise `and`, atomically.
*
* @param m Mask.
*/
void maskAnd(const T& value) {
//this->value &= value;
#pragma omp atomic update
this->value &= value;
}
/**
* Apply a mask, with bitwise `or`, atomically.
*
* @param m Mask.
*/
void maskOr(const T& value) {
//this->value |= value;
#pragma omp atomic update
this->value |= value;
}
/**
* Increment the value by one, atomically, but without capturing the
* current value.
*/
void increment() {
//++value;
#pragma omp atomic update
++value;
}
/**
* Decrement the value by one, atomically, but without capturing the
* current value.
*/
void decrement() {
//--value;
#pragma omp atomic update
--value;
}
/**
* Add to the value, atomically, but without capturing the current value.
*/
template<class U>
void add(const U& value) {
//this->value += value;
#pragma omp atomic update
this->value += value;
}
/**
* Subtract from the value, atomically, but without capturing the current
* value.
*/
template<class U>
void subtract(const U& value) {
//this->value -= value;
#pragma omp atomic update
this->value -= value;
}
template<class U>
T operator+=(const U& value) {
//return this->value += value;
T result;
#pragma omp atomic capture
result = this->value += value;
return result;
}
template<class U>
T operator-=(const U& value) {
//return this->value -= value;
T result;
#pragma omp atomic capture
result = this->value -= value;
return result;
}
T operator++() {
//return ++this->value;
T value;
#pragma omp atomic capture
value = ++this->value;
return value;
}
T operator++(int) {
//return this->value++;
T value;
#pragma omp atomic capture
value = this->value++;
return value;
}
T operator--() {
//return --this->value;
T value;
#pragma omp atomic capture
value = --this->value;
return value;
}
T operator--(int) {
//return this->value--;
T value;
#pragma omp atomic capture
value = this->value--;
return value;
}
private:
/**
* Value.
*/
T value;
//std::atomic<T> value;
};
}
<commit_msg>Added macros to choose between std::atomic and OpenMP implementation of libbirch::Atomic. Changed to std::atomic for now, due to segfaults on macOS with OpenMP implementation.<commit_after>/**
* @file
*/
#pragma once
/**
* @def LIBBIRCH_ATOMIC_OPENMP
*
* Set to true for libbirch::Atomic to be based on std::atomic, or false to use
* OpenMP instead.
*
* The advantage of the OpenMP implementation is assured memory model
* consistency and the organic disabling of atomics when OpenMP, and thus
* multithreading, is disabled (this can improve performance significantly for
* single threading). The disadvantage is that OpenMP atomics do not support
* compare-and-swap/compare-and-exchange, only swap/exchange, which requires
* some clunkier client code, especially for read-write locks.
*
* The alternative implementation use std::atomic.
*
* Atomic provides the default constructor, copy and move constructors, copy
* and move assignment operators, in order to be trivially copyable and so
* a mappable type for the purposes of OpenMP. These constructors and
* operators *do not* behave atomically, however.
*/
#ifndef HAVE_OMP_H
/* this looks like it's backwards, but when OpenMP is disabled, enabling the
* OpenMP implementation has the effect of replacing atomic operations with
* regular operations, which is faster */
#define LIBBIRCH_ATOMIC_OPENMP 1
#else
/* otherwise the default is to disable the OpenMP implementation at this
* stage, as unfortunately seeing segfaults in recent versions on macOS;
* further review required */
#define LIBBIRCH_ATOMIC_OPENMP 0
#endif
#if !LIBBIRCH_ATOMIC_OPENMP
#include <atomic>
#endif
namespace libbirch {
/**
* Atomic value.
*
* @tparam Value type.
*/
template<class T>
class Atomic {
public:
/**
* Default constructor. Initializes the value, not necessarily atomically.
*/
Atomic() = default;
/**
* Constructor.
*
* @param value Initial value.
*
* Initializes the value, atomically.
*/
explicit Atomic(const T& value) {
store(value);
}
/**
* Load the value, atomically.
*/
T load() const {
T value;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic read seq_cst
value = this->value;
#else
value = this->value.load();
#endif
return value;
}
/**
* Store the value, atomically.
*/
void store(const T& value) {
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic write seq_cst
this->value = value;
#else
this->value.store(value);
#endif
}
/**
* Exchange the value with another, atomically.
*
* @param value New value.
*
* @return Old value.
*/
T exchange(const T& value) {
T old;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
{
old = this->value;
this->value = value;
}
#else
old = this->value.exchange(value);
#endif
return old;
}
/**
* Apply a mask, with bitwise `and`, and return the previous value,
* atomically.
*
* @param m Mask.
*
* @return Previous value.
*/
T exchangeAnd(const T& value) {
T old;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
{
old = this->value;
this->value &= value;
}
#else
old = this->value.fetch_and(value);
#endif
return old;
}
/**
* Apply a mask, with bitwise `or`, and return the previous value,
* atomically.
*
* @param m Mask.
*
* @return Previous value.
*/
T exchangeOr(const T& value) {
T old;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
{
old = this->value;
this->value |= value;
}
#else
old = this->value.fetch_or(value);
#endif
return old;
}
/**
* Apply a mask, with bitwise `and`, atomically.
*
* @param m Mask.
*/
void maskAnd(const T& value) {
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic update seq_cst
#endif
this->value &= value;
}
/**
* Apply a mask, with bitwise `or`, atomically.
*
* @param m Mask.
*/
void maskOr(const T& value) {
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic update seq_cst
#endif
this->value |= value;
}
/**
* Increment the value by one, atomically, but without capturing the
* current value.
*/
void increment() {
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic update seq_cst
#endif
++value;
}
/**
* Decrement the value by one, atomically, but without capturing the
* current value.
*/
void decrement() {
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic update seq_cst
#endif
--value;
}
/**
* Add to the value, atomically, but without capturing the current value.
*/
template<class U>
void add(const U& value) {
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic update seq_cst
#endif
this->value += value;
}
/**
* Subtract from the value, atomically, but without capturing the current
* value.
*/
template<class U>
void subtract(const U& value) {
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic update seq_cst
#endif
this->value -= value;
}
template<class U>
T operator+=(const U& value) {
T result;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
#endif
result = this->value += value;
return result;
}
template<class U>
T operator-=(const U& value) {
T result;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
#endif
result = this->value -= value;
return result;
}
T operator++() {
T value;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
#endif
value = ++this->value;
return value;
}
T operator++(int) {
T value;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
#endif
value = this->value++;
return value;
}
T operator--() {
T value;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
#endif
value = --this->value;
return value;
}
T operator--(int) {
T value;
#if LIBBIRCH_ATOMIC_OPENMP
#pragma omp atomic capture seq_cst
#endif
value = this->value--;
return value;
}
private:
/**
* Value.
*/
#if LIBBIRCH_ATOMIC_OPENMP
T value;
#else
std::atomic<T> value;
#endif
};
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2014 *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <memory>
#include <new>
#include <utility>
#include "caf/none.hpp"
#include "caf/unit.hpp"
#include "caf/config.hpp"
#include "caf/deep_to_string.hpp"
#include "caf/detail/safe_equal.hpp"
#include "caf/detail/scope_guard.hpp"
namespace caf {
/// A C++17 compatible `optional` implementation.
template <class T>
class optional {
public:
/// Typdef for `T`.
using type = T;
/// Creates an instance without value.
optional(const none_t& = none) : m_valid(false) {
// nop
}
/// Creates an valid instance from `value`.
template <class U,
class E = typename std::enable_if<
std::is_convertible<U, T>::value
>::type>
optional(U x) : m_valid(false) {
cr(std::move(x));
}
optional(const optional& other) : m_valid(false) {
if (other.m_valid) {
cr(other.m_value);
}
}
optional(optional&& other)
noexcept(std::is_nothrow_move_constructible<T>::value)
: m_valid(false) {
if (other.m_valid) {
cr(std::move(other.m_value));
}
}
~optional() {
destroy();
}
optional& operator=(const optional& other) {
if (m_valid) {
if (other.m_valid) m_value = other.m_value;
else destroy();
}
else if (other.m_valid) {
cr(other.m_value);
}
return *this;
}
optional& operator=(optional&& other)
noexcept(std::is_nothrow_destructible<T>::value &&
std::is_nothrow_move_assignable<T>::value) {
if (m_valid) {
if (other.m_valid) m_value = std::move(other.m_value);
else destroy();
}
else if (other.m_valid) {
cr(std::move(other.m_value));
}
return *this;
}
/// Checks whether this object contains a value.
explicit operator bool() const {
return m_valid;
}
/// Checks whether this object does not contain a value.
bool operator!() const {
return !m_valid;
}
/// Returns the value.
T& operator*() {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value.
const T& operator*() const {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value.
const T* operator->() const {
CAF_ASSERT(m_valid);
return &m_value;
}
/// Returns the value.
T* operator->() {
CAF_ASSERT(m_valid);
return &m_value;
}
/// Returns the value.
T& value() {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value.
const T& value() const {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value if `m_valid`, otherwise returns `default_value`.
const T& value_or(const T& default_value) const {
return m_valid ? value() : default_value;
}
private:
void destroy() {
if (m_valid) {
m_value.~T();
m_valid = false;
}
}
template <class V>
void cr(V&& x) {
CAF_ASSERT(!m_valid);
m_valid = true;
new (std::addressof(m_value)) T(std::forward<V>(x));
}
bool m_valid;
union { T m_value; };
};
/// Template specialization to allow `optional` to hold a reference
/// rather than an actual value with minimal overhead.
template <class T>
class optional<T&> {
public:
using type = T;
optional(const none_t& = none) : m_value(nullptr) {
// nop
}
optional(T& x) : m_value(&x) {
// nop
}
optional(T* x) : m_value(x) {
// nop
}
optional(const optional& other) = default;
optional& operator=(const optional& other) = default;
explicit operator bool() const {
return m_value != nullptr;
}
bool operator!() const {
return !m_value;
}
T& operator*() {
CAF_ASSERT(m_value);
return *m_value;
}
const T& operator*() const {
CAF_ASSERT(m_value);
return *m_value;
}
T* operator->() {
CAF_ASSERT(m_value);
return m_value;
}
const T* operator->() const {
CAF_ASSERT(m_value);
return m_value;
}
T& value() {
CAF_ASSERT(m_value);
return *m_value;
}
const T& value() const {
CAF_ASSERT(m_value);
return *m_value;
}
const T& value_or(const T& default_value) const {
if (m_value)
return value();
return default_value;
}
private:
T* m_value;
};
template <>
class optional<void> {
public:
using type = unit_t;
optional(none_t = none) : m_value(false) {
// nop
}
optional(unit_t) : m_value(true) {
// nop
}
optional(const optional& other) = default;
optional& operator=(const optional& other) = default;
explicit operator bool() const {
return m_value;
}
bool operator!() const {
return !m_value;
}
private:
bool m_value;
};
template <class Inspector, class T>
typename std::enable_if<Inspector::reads_state,
typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
return x ? f(true, *x) : f(false);
}
template <class T>
struct optional_inspect_helper {
bool& enabled;
T& storage;
template <class Inspector>
friend typename Inspector::result_type inspect(Inspector& f,
optional_inspect_helper& x) {
return x.enabled ? f(x.storage) : f();
}
};
template <class Inspector, class T>
typename std::enable_if<Inspector::writes_state,
typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
bool flag = false;
typename optional<T>::type tmp{};
optional_inspect_helper<T> helper{flag, tmp};
auto guard = detail::make_scope_guard([&] {
if (flag)
x = std::move(tmp);
else
x = none;
});
return f(flag, helper);
}
/// @relates optional
template <class T>
std::string to_string(const optional<T>& x) {
return x ? "*" + deep_to_string(*x) : "none";
}
// -- [X.Y.8] comparison with optional ----------------------------------------
/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const optional<T>& rhs) {
return static_cast<bool>(lhs) == static_cast<bool>(rhs)
&& (!lhs || *lhs == *rhs);
}
/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const optional<T>& rhs) {
return !(lhs == rhs);
}
/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const optional<T>& rhs) {
return static_cast<bool>(rhs) && (!lhs || *lhs < *rhs);
}
/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const optional<T>& rhs) {
return !(rhs < lhs);
}
/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const optional<T>& rhs) {
return !(lhs < rhs);
}
/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const optional<T>& rhs) {
return rhs < lhs;
}
// -- [X.Y.9] comparison with none_t (aka. nullopt_t) -------------------------
/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, none_t) {
return !lhs;
}
/// @relates optional
template <class T>
bool operator==(none_t, const optional<T>& rhs) {
return !rhs;
}
/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, none_t) {
return static_cast<bool>(lhs);
}
/// @relates optional
template <class T>
bool operator!=(none_t, const optional<T>& rhs) {
return static_cast<bool>(rhs);
}
/// @relates optional
template <class T>
bool operator<(const optional<T>&, none_t) {
return false;
}
/// @relates optional
template <class T>
bool operator<(none_t, const optional<T>& rhs) {
return static_cast<bool>(rhs);
}
/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, none_t) {
return !lhs;
}
/// @relates optional
template <class T>
bool operator<=(none_t, const optional<T>&) {
return true;
}
/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, none_t) {
return static_cast<bool>(lhs);
}
/// @relates optional
template <class T>
bool operator>(none_t, const optional<T>&) {
return false;
}
/// @relates optional
template <class T>
bool operator>=(const optional<T>&, none_t) {
return true;
}
/// @relates optional
template <class T>
bool operator>=(none_t, const optional<T>&) {
return true;
}
// -- [X.Y.10] comparison with value type ------------------------------------
/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const T& rhs) {
return lhs && *lhs == rhs;
}
/// @relates optional
template <class T>
bool operator==(const T& lhs, const optional<T>& rhs) {
return rhs && lhs == *rhs;
}
/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const T& rhs) {
return !lhs || !(*lhs == rhs);
}
/// @relates optional
template <class T>
bool operator!=(const T& lhs, const optional<T>& rhs) {
return !rhs || !(lhs == *rhs);
}
/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const T& rhs) {
return !lhs || *lhs < rhs;
}
/// @relates optional
template <class T>
bool operator<(const T& lhs, const optional<T>& rhs) {
return rhs && lhs < *rhs;
}
/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const T& rhs) {
return !lhs || !(rhs < *lhs);
}
/// @relates optional
template <class T>
bool operator<=(const T& lhs, const optional<T>& rhs) {
return rhs && !(rhs < lhs);
}
/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const T& rhs) {
return lhs && rhs < *lhs;
}
/// @relates optional
template <class T>
bool operator>(const T& lhs, const optional<T>& rhs) {
return !rhs || *rhs < lhs;
}
/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const T& rhs) {
return lhs && !(*lhs < rhs);
}
/// @relates optional
template <class T>
bool operator>=(const T& lhs, const optional<T>& rhs) {
return !rhs || !(lhs < *rhs);
}
} // namespace caf
<commit_msg>Add move_if_optional utility function<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2014 *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <memory>
#include <new>
#include <utility>
#include "caf/none.hpp"
#include "caf/unit.hpp"
#include "caf/config.hpp"
#include "caf/deep_to_string.hpp"
#include "caf/detail/safe_equal.hpp"
#include "caf/detail/scope_guard.hpp"
namespace caf {
/// A C++17 compatible `optional` implementation.
template <class T>
class optional {
public:
/// Typdef for `T`.
using type = T;
/// Creates an instance without value.
optional(const none_t& = none) : m_valid(false) {
// nop
}
/// Creates an valid instance from `value`.
template <class U,
class E = typename std::enable_if<
std::is_convertible<U, T>::value
>::type>
optional(U x) : m_valid(false) {
cr(std::move(x));
}
optional(const optional& other) : m_valid(false) {
if (other.m_valid) {
cr(other.m_value);
}
}
optional(optional&& other)
noexcept(std::is_nothrow_move_constructible<T>::value)
: m_valid(false) {
if (other.m_valid) {
cr(std::move(other.m_value));
}
}
~optional() {
destroy();
}
optional& operator=(const optional& other) {
if (m_valid) {
if (other.m_valid) m_value = other.m_value;
else destroy();
}
else if (other.m_valid) {
cr(other.m_value);
}
return *this;
}
optional& operator=(optional&& other)
noexcept(std::is_nothrow_destructible<T>::value &&
std::is_nothrow_move_assignable<T>::value) {
if (m_valid) {
if (other.m_valid) m_value = std::move(other.m_value);
else destroy();
}
else if (other.m_valid) {
cr(std::move(other.m_value));
}
return *this;
}
/// Checks whether this object contains a value.
explicit operator bool() const {
return m_valid;
}
/// Checks whether this object does not contain a value.
bool operator!() const {
return !m_valid;
}
/// Returns the value.
T& operator*() {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value.
const T& operator*() const {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value.
const T* operator->() const {
CAF_ASSERT(m_valid);
return &m_value;
}
/// Returns the value.
T* operator->() {
CAF_ASSERT(m_valid);
return &m_value;
}
/// Returns the value.
T& value() {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value.
const T& value() const {
CAF_ASSERT(m_valid);
return m_value;
}
/// Returns the value if `m_valid`, otherwise returns `default_value`.
const T& value_or(const T& default_value) const {
return m_valid ? value() : default_value;
}
private:
void destroy() {
if (m_valid) {
m_value.~T();
m_valid = false;
}
}
template <class V>
void cr(V&& x) {
CAF_ASSERT(!m_valid);
m_valid = true;
new (std::addressof(m_value)) T(std::forward<V>(x));
}
bool m_valid;
union { T m_value; };
};
/// Template specialization to allow `optional` to hold a reference
/// rather than an actual value with minimal overhead.
template <class T>
class optional<T&> {
public:
using type = T;
optional(const none_t& = none) : m_value(nullptr) {
// nop
}
optional(T& x) : m_value(&x) {
// nop
}
optional(T* x) : m_value(x) {
// nop
}
optional(const optional& other) = default;
optional& operator=(const optional& other) = default;
explicit operator bool() const {
return m_value != nullptr;
}
bool operator!() const {
return !m_value;
}
T& operator*() {
CAF_ASSERT(m_value);
return *m_value;
}
const T& operator*() const {
CAF_ASSERT(m_value);
return *m_value;
}
T* operator->() {
CAF_ASSERT(m_value);
return m_value;
}
const T* operator->() const {
CAF_ASSERT(m_value);
return m_value;
}
T& value() {
CAF_ASSERT(m_value);
return *m_value;
}
const T& value() const {
CAF_ASSERT(m_value);
return *m_value;
}
const T& value_or(const T& default_value) const {
if (m_value)
return value();
return default_value;
}
private:
T* m_value;
};
template <>
class optional<void> {
public:
using type = unit_t;
optional(none_t = none) : m_value(false) {
// nop
}
optional(unit_t) : m_value(true) {
// nop
}
optional(const optional& other) = default;
optional& operator=(const optional& other) = default;
explicit operator bool() const {
return m_value;
}
bool operator!() const {
return !m_value;
}
private:
bool m_value;
};
template <class Inspector, class T>
typename std::enable_if<Inspector::reads_state,
typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
return x ? f(true, *x) : f(false);
}
template <class T>
struct optional_inspect_helper {
bool& enabled;
T& storage;
template <class Inspector>
friend typename Inspector::result_type inspect(Inspector& f,
optional_inspect_helper& x) {
return x.enabled ? f(x.storage) : f();
}
};
template <class Inspector, class T>
typename std::enable_if<Inspector::writes_state,
typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
bool flag = false;
typename optional<T>::type tmp{};
optional_inspect_helper<T> helper{flag, tmp};
auto guard = detail::make_scope_guard([&] {
if (flag)
x = std::move(tmp);
else
x = none;
});
return f(flag, helper);
}
/// @relates optional
template <class T>
std::string to_string(const optional<T>& x) {
return x ? "*" + deep_to_string(*x) : "none";
}
/// Returns an rvalue to the value managed by `x`.
/// @relates optional
template <class T>
T&& move_if_optional(optional<T>& x) {
return std::move(*x);
}
/// Returns `*x`.
/// @relates optional
template <class T>
T& move_if_optional(T* x) {
return *x;
}
// -- [X.Y.8] comparison with optional ----------------------------------------
/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const optional<T>& rhs) {
return static_cast<bool>(lhs) == static_cast<bool>(rhs)
&& (!lhs || *lhs == *rhs);
}
/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const optional<T>& rhs) {
return !(lhs == rhs);
}
/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const optional<T>& rhs) {
return static_cast<bool>(rhs) && (!lhs || *lhs < *rhs);
}
/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const optional<T>& rhs) {
return !(rhs < lhs);
}
/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const optional<T>& rhs) {
return !(lhs < rhs);
}
/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const optional<T>& rhs) {
return rhs < lhs;
}
// -- [X.Y.9] comparison with none_t (aka. nullopt_t) -------------------------
/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, none_t) {
return !lhs;
}
/// @relates optional
template <class T>
bool operator==(none_t, const optional<T>& rhs) {
return !rhs;
}
/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, none_t) {
return static_cast<bool>(lhs);
}
/// @relates optional
template <class T>
bool operator!=(none_t, const optional<T>& rhs) {
return static_cast<bool>(rhs);
}
/// @relates optional
template <class T>
bool operator<(const optional<T>&, none_t) {
return false;
}
/// @relates optional
template <class T>
bool operator<(none_t, const optional<T>& rhs) {
return static_cast<bool>(rhs);
}
/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, none_t) {
return !lhs;
}
/// @relates optional
template <class T>
bool operator<=(none_t, const optional<T>&) {
return true;
}
/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, none_t) {
return static_cast<bool>(lhs);
}
/// @relates optional
template <class T>
bool operator>(none_t, const optional<T>&) {
return false;
}
/// @relates optional
template <class T>
bool operator>=(const optional<T>&, none_t) {
return true;
}
/// @relates optional
template <class T>
bool operator>=(none_t, const optional<T>&) {
return true;
}
// -- [X.Y.10] comparison with value type ------------------------------------
/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const T& rhs) {
return lhs && *lhs == rhs;
}
/// @relates optional
template <class T>
bool operator==(const T& lhs, const optional<T>& rhs) {
return rhs && lhs == *rhs;
}
/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const T& rhs) {
return !lhs || !(*lhs == rhs);
}
/// @relates optional
template <class T>
bool operator!=(const T& lhs, const optional<T>& rhs) {
return !rhs || !(lhs == *rhs);
}
/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const T& rhs) {
return !lhs || *lhs < rhs;
}
/// @relates optional
template <class T>
bool operator<(const T& lhs, const optional<T>& rhs) {
return rhs && lhs < *rhs;
}
/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const T& rhs) {
return !lhs || !(rhs < *lhs);
}
/// @relates optional
template <class T>
bool operator<=(const T& lhs, const optional<T>& rhs) {
return rhs && !(rhs < lhs);
}
/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const T& rhs) {
return lhs && rhs < *lhs;
}
/// @relates optional
template <class T>
bool operator>(const T& lhs, const optional<T>& rhs) {
return !rhs || *rhs < lhs;
}
/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const T& rhs) {
return lhs && !(*lhs < rhs);
}
/// @relates optional
template <class T>
bool operator>=(const T& lhs, const optional<T>& rhs) {
return !rhs || !(lhs < *rhs);
}
} // namespace caf
<|endoftext|> |
<commit_before>/*
* This file is part of the Shiboken Python Bindings Generator project.
*
* Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: PySide team <contact@pyside.org>
*
* This program 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. 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.
*
* As a special exception to the GNU Lesser General Public License
* version 2.1, the object code form of a "work that uses the Library"
* may incorporate material from a header file that is part of the
* Library. You may distribute such object code under terms of your
* choice, provided that the incorporated material (i) does not exceed
* more than 5% of the total size of the Library; and (ii) is limited to
* numerical parameters, data structure layouts, accessors, macros,
* inline functions and templates.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <QMetaMethod>
#include <QDebug>
#include <QEvent>
#include <autodecref.h>
#include <gilstate.h>
#include "globalreceiver.h"
#include "typeresolver.h"
#include "signalmanager.h"
#include "weakref.h"
#define RECEIVER_DESTROYED_SLOT_NAME "__receiverDestroyed__(QObject*)"
namespace PySide
{
class DynamicSlotData
{
public:
DynamicSlotData(int id, PyObject* callback);
void addRef(const QObject* o);
void decRef(const QObject* o);
void clear();
bool hasRefTo(const QObject* o) const;
int refCount() const;
int id() const;
PyObject* callback() const;
~DynamicSlotData();
private:
int m_id;
PyObject* m_callback;
QSet<const QObject*> m_refs;
};
}
using namespace PySide;
DynamicSlotData::DynamicSlotData(int id, PyObject* callback)
: m_id(id)
{
m_callback = callback;
Py_INCREF(callback);
}
void DynamicSlotData::addRef(const QObject *o)
{
m_refs.insert(o);
}
void DynamicSlotData::decRef(const QObject *o)
{
m_refs.remove(o);
}
int DynamicSlotData::refCount() const
{
return m_refs.size();
}
PyObject* DynamicSlotData::callback() const
{
return m_callback;
}
int DynamicSlotData::id() const
{
return m_id;
}
bool DynamicSlotData::hasRefTo(const QObject *o) const
{
return m_refs.contains(o);
}
void DynamicSlotData::clear()
{
m_refs.clear();
}
DynamicSlotData::~DynamicSlotData()
{
Py_DECREF(m_callback);
}
GlobalReceiver::GlobalReceiver()
: m_metaObject("GlobalReceiver", &QObject::staticMetaObject)
{
//slot used to be notifyed of object destrouction
m_metaObject.addSlot(RECEIVER_DESTROYED_SLOT_NAME);
}
GlobalReceiver::~GlobalReceiver()
{
foreach(DynamicSlotData* data, m_slotReceivers) {
data->clear();
delete data;
}
}
void GlobalReceiver::connectNotify(QObject* source, int slotId)
{
if (m_slotReceivers.contains(slotId)) {
m_slotReceivers[slotId]->addRef(source);
}
}
void GlobalReceiver::disconnectNotify(QObject* source, int slotId)
{
if (m_slotReceivers.contains(slotId)) {
QObject::disconnect(source, SIGNAL(destroyed(QObject*)), this, "1"RECEIVER_DESTROYED_SLOT_NAME);
DynamicSlotData *data = m_slotReceivers[slotId];
data->decRef(source);
if (data->refCount() == 0) {
removeSlot(slotId);
}
}
}
const QMetaObject* GlobalReceiver::metaObject() const
{
return &m_metaObject;
}
void GlobalReceiver::addSlot(const char* slot, PyObject* callback)
{
m_metaObject.addSlot(slot);
int slotId = m_metaObject.indexOfSlot(slot);
if (!m_slotReceivers.contains(slotId)) {
m_slotReceivers[slotId] = new DynamicSlotData(slotId, callback);
}
bool isShortCircuit = true;
for (int i = 0; slot[i]; ++i) {
if (slot[i] == '(') {
isShortCircuit = false;
break;
}
}
if (isShortCircuit)
m_shortCircuitSlots << slotId;
Q_ASSERT(slotId >= QObject::staticMetaObject.methodCount());
}
void GlobalReceiver::removeSlot(int slotId)
{
if (m_slotReceivers.contains(slotId)) {
delete m_slotReceivers.take(slotId);
m_metaObject.removeSlot(slotId);
m_shortCircuitSlots.remove(slotId);
}
}
bool GlobalReceiver::hasConnectionWith(const QObject *object)
{
QHash<int, DynamicSlotData*>::iterator i = m_slotReceivers.begin();
while(i != m_slotReceivers.end()) {
if (i.value()->hasRefTo(object)) {
return true;
}
i++;
}
return false;
}
int GlobalReceiver::qt_metacall(QMetaObject::Call call, int id, void** args)
{
Q_ASSERT(call == QMetaObject::InvokeMetaMethod);
Q_ASSERT(id >= QObject::staticMetaObject.methodCount());
QMetaMethod slot = m_metaObject.method(id);
Q_ASSERT(slot.methodType() == QMetaMethod::Slot);
if (strcmp(slot.signature(), RECEIVER_DESTROYED_SLOT_NAME) == 0) {
QObject *arg = *(QObject**)args[1];
QHash<int, DynamicSlotData*>::iterator i = m_slotReceivers.begin();
while(i != m_slotReceivers.end()) {
if (i.value()->hasRefTo(arg)) {
disconnectNotify(arg, i.key());
break;
}
i++;
}
return -1;
}
DynamicSlotData* data = m_slotReceivers.value(id);
if (!data) {
qWarning() << "Unknown global slot, id:" << id;
return -1;
}
Shiboken::GilState gil;
int numArgs;
PyObject* retval = 0;
PyObject* callback = data->callback();
if (m_shortCircuitSlots.contains(id)) {
retval = PyObject_CallObject(callback, reinterpret_cast<PyObject*>(args[1]));
} else {
QList<QByteArray> paramTypes = slot.parameterTypes();
numArgs = paramTypes.count();
Shiboken::AutoDecRef preparedArgs(PyTuple_New(paramTypes.count()));
for (int i = 0, max = paramTypes.count(); i < max; ++i) {
PyObject* arg = Shiboken::TypeResolver::get(paramTypes[i].constData())->toPython(args[i+1]);
PyTuple_SET_ITEM(preparedArgs.object(), i, arg);
}
retval = PyObject_CallObject(callback, preparedArgs);
}
if (!retval)
qWarning() << "Error calling slot" << m_metaObject.method(id).signature();
else
Py_DECREF(retval);
return -1;
}
<commit_msg>Header fixes<commit_after>/*
* This file is part of the Shiboken Python Bindings Generator project.
*
* Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: PySide team <contact@pyside.org>
*
* This program 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. 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.
*
* As a special exception to the GNU Lesser General Public License
* version 2.1, the object code form of a "work that uses the Library"
* may incorporate material from a header file that is part of the
* Library. You may distribute such object code under terms of your
* choice, provided that the incorporated material (i) does not exceed
* more than 5% of the total size of the Library; and (ii) is limited to
* numerical parameters, data structure layouts, accessors, macros,
* inline functions and templates.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "globalreceiver.h"
#include <QMetaMethod>
#include <QDebug>
#include <QEvent>
#include <autodecref.h>
#include <gilstate.h>
#include "typeresolver.h"
#include "signalmanager.h"
#define RECEIVER_DESTROYED_SLOT_NAME "__receiverDestroyed__(QObject*)"
namespace PySide
{
class DynamicSlotData
{
public:
DynamicSlotData(int id, PyObject* callback);
void addRef(const QObject* o);
void decRef(const QObject* o);
void clear();
bool hasRefTo(const QObject* o) const;
int refCount() const;
int id() const;
PyObject* callback() const;
~DynamicSlotData();
private:
int m_id;
PyObject* m_callback;
QSet<const QObject*> m_refs;
};
}
using namespace PySide;
DynamicSlotData::DynamicSlotData(int id, PyObject* callback)
: m_id(id)
{
m_callback = callback;
Py_INCREF(callback);
}
void DynamicSlotData::addRef(const QObject *o)
{
m_refs.insert(o);
}
void DynamicSlotData::decRef(const QObject *o)
{
m_refs.remove(o);
}
int DynamicSlotData::refCount() const
{
return m_refs.size();
}
PyObject* DynamicSlotData::callback() const
{
return m_callback;
}
int DynamicSlotData::id() const
{
return m_id;
}
bool DynamicSlotData::hasRefTo(const QObject *o) const
{
return m_refs.contains(o);
}
void DynamicSlotData::clear()
{
m_refs.clear();
}
DynamicSlotData::~DynamicSlotData()
{
Py_DECREF(m_callback);
}
GlobalReceiver::GlobalReceiver()
: m_metaObject("GlobalReceiver", &QObject::staticMetaObject)
{
//slot used to be notifyed of object destrouction
m_metaObject.addSlot(RECEIVER_DESTROYED_SLOT_NAME);
}
GlobalReceiver::~GlobalReceiver()
{
foreach(DynamicSlotData* data, m_slotReceivers) {
data->clear();
delete data;
}
}
void GlobalReceiver::connectNotify(QObject* source, int slotId)
{
if (m_slotReceivers.contains(slotId)) {
m_slotReceivers[slotId]->addRef(source);
}
}
void GlobalReceiver::disconnectNotify(QObject* source, int slotId)
{
if (m_slotReceivers.contains(slotId)) {
QObject::disconnect(source, SIGNAL(destroyed(QObject*)), this, "1"RECEIVER_DESTROYED_SLOT_NAME);
DynamicSlotData *data = m_slotReceivers[slotId];
data->decRef(source);
if (data->refCount() == 0) {
removeSlot(slotId);
}
}
}
const QMetaObject* GlobalReceiver::metaObject() const
{
return &m_metaObject;
}
void GlobalReceiver::addSlot(const char* slot, PyObject* callback)
{
m_metaObject.addSlot(slot);
int slotId = m_metaObject.indexOfSlot(slot);
if (!m_slotReceivers.contains(slotId)) {
m_slotReceivers[slotId] = new DynamicSlotData(slotId, callback);
}
bool isShortCircuit = true;
for (int i = 0; slot[i]; ++i) {
if (slot[i] == '(') {
isShortCircuit = false;
break;
}
}
if (isShortCircuit)
m_shortCircuitSlots << slotId;
Q_ASSERT(slotId >= QObject::staticMetaObject.methodCount());
}
void GlobalReceiver::removeSlot(int slotId)
{
if (m_slotReceivers.contains(slotId)) {
delete m_slotReceivers.take(slotId);
m_metaObject.removeSlot(slotId);
m_shortCircuitSlots.remove(slotId);
}
}
bool GlobalReceiver::hasConnectionWith(const QObject *object)
{
QHash<int, DynamicSlotData*>::iterator i = m_slotReceivers.begin();
while(i != m_slotReceivers.end()) {
if (i.value()->hasRefTo(object)) {
return true;
}
i++;
}
return false;
}
int GlobalReceiver::qt_metacall(QMetaObject::Call call, int id, void** args)
{
Q_ASSERT(call == QMetaObject::InvokeMetaMethod);
Q_ASSERT(id >= QObject::staticMetaObject.methodCount());
QMetaMethod slot = m_metaObject.method(id);
Q_ASSERT(slot.methodType() == QMetaMethod::Slot);
if (strcmp(slot.signature(), RECEIVER_DESTROYED_SLOT_NAME) == 0) {
QObject *arg = *(QObject**)args[1];
QHash<int, DynamicSlotData*>::iterator i = m_slotReceivers.begin();
while(i != m_slotReceivers.end()) {
if (i.value()->hasRefTo(arg)) {
disconnectNotify(arg, i.key());
break;
}
i++;
}
return -1;
}
DynamicSlotData* data = m_slotReceivers.value(id);
if (!data) {
qWarning() << "Unknown global slot, id:" << id;
return -1;
}
Shiboken::GilState gil;
int numArgs;
PyObject* retval = 0;
PyObject* callback = data->callback();
if (m_shortCircuitSlots.contains(id)) {
retval = PyObject_CallObject(callback, reinterpret_cast<PyObject*>(args[1]));
} else {
QList<QByteArray> paramTypes = slot.parameterTypes();
numArgs = paramTypes.count();
Shiboken::AutoDecRef preparedArgs(PyTuple_New(paramTypes.count()));
for (int i = 0, max = paramTypes.count(); i < max; ++i) {
PyObject* arg = Shiboken::TypeResolver::get(paramTypes[i].constData())->toPython(args[i+1]);
PyTuple_SET_ITEM(preparedArgs.object(), i, arg);
}
retval = PyObject_CallObject(callback, preparedArgs);
}
if (!retval)
qWarning() << "Error calling slot" << m_metaObject.method(id).signature();
else
Py_DECREF(retval);
return -1;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <graphene/chain/database.hpp>
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/market_evaluator.hpp>
#include <graphene/chain/vesting_balance_object.hpp>
#include <graphene/chain/witness_object.hpp>
namespace graphene { namespace chain {
/**
* This method dumps the state of the blockchain in a semi-human readable form for the
* purpose of tracking down funds and mismatches in currency allocation
*/
void database::debug_dump()
{
const auto& db = *this;
const asset_dynamic_data_object& core_asset_data = db.get_core_asset().dynamic_asset_data_id(db);
const auto& balance_index = db.get_index_type<account_balance_index>().indices();
const simple_index<account_statistics_object>& statistics_index = db.get_index_type<simple_index<account_statistics_object>>();
map<asset_id_type,share_type> total_balances;
map<asset_id_type,share_type> total_debts;
share_type core_in_orders;
share_type reported_core_in_orders;
for( const account_balance_object& a : balance_index )
{
// idump(("balance")(a));
total_balances[a.asset_type] += a.balance;
}
for( const account_statistics_object& s : statistics_index )
{
// idump(("statistics")(s));
reported_core_in_orders += s.total_core_in_orders;
}
for( const limit_order_object& o : db.get_index_type<limit_order_index>().indices() )
{
idump(("limit_order")(o));
auto for_sale = o.amount_for_sale();
if( for_sale.asset_id == asset_id_type() ) core_in_orders += for_sale.amount;
total_balances[for_sale.asset_id] += for_sale.amount;
}
for( const call_order_object& o : db.get_index_type<call_order_index>().indices() )
{
idump(("call_order")(o));
auto col = o.get_collateral();
if( col.asset_id == asset_id_type() ) core_in_orders += col.amount;
total_balances[col.asset_id] += col.amount;
total_debts[o.get_debt().asset_id] += o.get_debt().amount;
}
for( const asset_object& asset_obj : db.get_index_type<asset_index>().indices() )
{
total_balances[asset_obj.id] += asset_obj.dynamic_asset_data_id(db).accumulated_fees;
total_balances[asset_id_type()] += asset_obj.dynamic_asset_data_id(db).fee_pool;
// edump((total_balances[asset_obj.id])(asset_obj.dynamic_asset_data_id(db).current_supply ) );
}
if( total_balances[asset_id_type()].value != core_asset_data.current_supply.value )
{
edump( (total_balances[asset_id_type()].value)(core_asset_data.current_supply.value ));
}
edump((core_in_orders)(reported_core_in_orders));
/*
const auto& vbidx = db.get_index_type<simple_index<vesting_balance_object>>();
for( const auto& s : vbidx )
{
// idump(("vesting_balance")(s));
}
*/
}
} }
<commit_msg>remove extra spam<commit_after>/*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <graphene/chain/database.hpp>
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/market_evaluator.hpp>
#include <graphene/chain/vesting_balance_object.hpp>
#include <graphene/chain/witness_object.hpp>
namespace graphene { namespace chain {
/**
* This method dumps the state of the blockchain in a semi-human readable form for the
* purpose of tracking down funds and mismatches in currency allocation
*/
void database::debug_dump()
{
const auto& db = *this;
const asset_dynamic_data_object& core_asset_data = db.get_core_asset().dynamic_asset_data_id(db);
const auto& balance_index = db.get_index_type<account_balance_index>().indices();
const simple_index<account_statistics_object>& statistics_index = db.get_index_type<simple_index<account_statistics_object>>();
map<asset_id_type,share_type> total_balances;
map<asset_id_type,share_type> total_debts;
share_type core_in_orders;
share_type reported_core_in_orders;
for( const account_balance_object& a : balance_index )
{
// idump(("balance")(a));
total_balances[a.asset_type] += a.balance;
}
for( const account_statistics_object& s : statistics_index )
{
// idump(("statistics")(s));
reported_core_in_orders += s.total_core_in_orders;
}
for( const limit_order_object& o : db.get_index_type<limit_order_index>().indices() )
{
// idump(("limit_order")(o));
auto for_sale = o.amount_for_sale();
if( for_sale.asset_id == asset_id_type() ) core_in_orders += for_sale.amount;
total_balances[for_sale.asset_id] += for_sale.amount;
}
for( const call_order_object& o : db.get_index_type<call_order_index>().indices() )
{
// idump(("call_order")(o));
auto col = o.get_collateral();
if( col.asset_id == asset_id_type() ) core_in_orders += col.amount;
total_balances[col.asset_id] += col.amount;
total_debts[o.get_debt().asset_id] += o.get_debt().amount;
}
for( const asset_object& asset_obj : db.get_index_type<asset_index>().indices() )
{
total_balances[asset_obj.id] += asset_obj.dynamic_asset_data_id(db).accumulated_fees;
total_balances[asset_id_type()] += asset_obj.dynamic_asset_data_id(db).fee_pool;
// edump((total_balances[asset_obj.id])(asset_obj.dynamic_asset_data_id(db).current_supply ) );
}
if( total_balances[asset_id_type()].value != core_asset_data.current_supply.value )
{
edump( (total_balances[asset_id_type()].value)(core_asset_data.current_supply.value ));
}
edump((core_in_orders)(reported_core_in_orders));
/*
const auto& vbidx = db.get_index_type<simple_index<vesting_balance_object>>();
for( const auto& s : vbidx )
{
// idump(("vesting_balance")(s));
}
*/
}
} }
<|endoftext|> |
<commit_before>/**
* @file Global.hpp
* @brief Global class prototype.
* @author zer0
* @date 2017-02-16
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_CONTAINER_GLOBAL_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_CONTAINER_GLOBAL_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/pattern/Singleton2.hpp>
#include <libtbag/container/Pointer.hpp>
#include <unordered_map>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace container {
/**
* Global class prototype.
*
* @author zer0
* @date 2017-02-16
*/
class TBAG_API Global : public pattern::Singleton2<Global>
{
public:
SINGLETON2_PROTOTYPE(Global);
public:
struct Object
{
virtual int type() = 0;
};
public:
using Key = container::Pointer<void>;
using Shared = std::shared_ptr<Object>;
using Weak = std::weak_ptr<Object>;
using Map = std::unordered_map<Key, Shared, typename Key::Hash, typename Key::EqualTo>;
private:
Map _map;
public:
// @formatter:off
inline bool empty () const TBAG_NOEXCEPT_EXPR(TBAG_NOEXCEPT_EXPR(_map.empty ())) { return _map.empty (); }
inline std::size_t size () const TBAG_NOEXCEPT_EXPR(TBAG_NOEXCEPT_EXPR(_map.size ())) { return _map.size (); }
inline std::size_t max_size() const TBAG_NOEXCEPT_EXPR(TBAG_NOEXCEPT_EXPR(_map.max_size())) { return _map.max_size(); }
// @formatter:on
public:
// @formatter:off
inline void clear() { _map.clear(); }
// @formatter:on
public:
inline Map::iterator begin() { return _map.begin(); }
inline Map::iterator end() { return _map.end(); }
public:
template <typename UpObject = Object>
std::weak_ptr<UpObject> find(Object & h)
{
auto itr = _map.find(Key(&h));
if (itr != _map.end()) {
return std::weak_ptr<UpObject>(std::static_pointer_cast<UpObject>(itr->second));
}
return std::weak_ptr<UpObject>();
}
bool erase(Object & h)
{
return _map.erase(Key(&h)) == 1U;
}
Weak insert(Shared h)
{
auto itr = _map.insert(Map::value_type(Key(h.get()), h));
if (itr.second) {
return Weak(itr.first->second);
}
return Weak();
}
public:
/** Create(new) & insert handle. */
template <typename UpObject, typename ... Args>
inline std::shared_ptr<typename remove_cr<UpObject>::type> newObject(Args && ... args)
{
typedef typename remove_cr<UpObject>::type ResultObjectType;
Shared obj(new (std::nothrow) UpObject(std::forward<Args>(args) ...));
return std::static_pointer_cast<ResultObjectType, Object>(insert(obj).lock());
}
};
} // namespace container
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_CONTAINER_GLOBAL_HPP__
<commit_msg>Include missing header.<commit_after>/**
* @file Global.hpp
* @brief Global class prototype.
* @author zer0
* @date 2017-02-16
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_CONTAINER_GLOBAL_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_CONTAINER_GLOBAL_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/pattern/Singleton2.hpp>
#include <libtbag/container/Pointer.hpp>
#include <memory>
#include <unordered_map>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace container {
/**
* Global class prototype.
*
* @author zer0
* @date 2017-02-16
*/
class TBAG_API Global : public pattern::Singleton2<Global>
{
public:
SINGLETON2_PROTOTYPE(Global);
public:
struct Object
{
virtual int type() = 0;
};
public:
using Key = container::Pointer<void>;
using Shared = std::shared_ptr<Object>;
using Weak = std::weak_ptr<Object>;
using Map = std::unordered_map<Key, Shared, typename Key::Hash, typename Key::EqualTo>;
private:
Map _map;
public:
// @formatter:off
inline bool empty () const TBAG_NOEXCEPT_EXPR(TBAG_NOEXCEPT_EXPR(_map.empty ())) { return _map.empty (); }
inline std::size_t size () const TBAG_NOEXCEPT_EXPR(TBAG_NOEXCEPT_EXPR(_map.size ())) { return _map.size (); }
inline std::size_t max_size() const TBAG_NOEXCEPT_EXPR(TBAG_NOEXCEPT_EXPR(_map.max_size())) { return _map.max_size(); }
// @formatter:on
public:
// @formatter:off
inline void clear() { _map.clear(); }
// @formatter:on
public:
inline Map::iterator begin() { return _map.begin(); }
inline Map::iterator end() { return _map.end(); }
public:
template <typename UpObject = Object>
std::weak_ptr<UpObject> find(Object & h)
{
auto itr = _map.find(Key(&h));
if (itr != _map.end()) {
return std::weak_ptr<UpObject>(std::static_pointer_cast<UpObject>(itr->second));
}
return std::weak_ptr<UpObject>();
}
bool erase(Object & h)
{
return _map.erase(Key(&h)) == 1U;
}
Weak insert(Shared h)
{
auto itr = _map.insert(Map::value_type(Key(h.get()), h));
if (itr.second) {
return Weak(itr.first->second);
}
return Weak();
}
public:
/** Create(new) & insert handle. */
template <typename UpObject, typename ... Args>
inline std::shared_ptr<typename remove_cr<UpObject>::type> newObject(Args && ... args)
{
typedef typename remove_cr<UpObject>::type ResultObjectType;
Shared obj(new (std::nothrow) UpObject(std::forward<Args>(args) ...));
return std::static_pointer_cast<ResultObjectType, Object>(insert(obj).lock());
}
};
} // namespace container
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_CONTAINER_GLOBAL_HPP__
<|endoftext|> |
<commit_before>#include "tag.h"
#include <errno.h>
#include <string.h>
#include <node_buffer.h>
#include "taglib.h"
#include "bufferstream.h"
using namespace node_taglib;
using namespace v8;
using namespace node;
namespace node_taglib {
static suseconds_t now()
{
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_usec;
}
static Persistent<FunctionTemplate> TagTemplate;
void Tag::Initialize(Handle<Object> target)
{
HandleScope scope;
TagTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New());
TagTemplate->InstanceTemplate()->SetInternalFieldCount(1);
TagTemplate->SetClassName(String::NewSymbol("Tag"));
NODE_SET_PROTOTYPE_METHOD(TagTemplate, "save", AsyncSaveTag);
NODE_SET_PROTOTYPE_METHOD(TagTemplate, "saveSync", SyncSaveTag);
NODE_SET_PROTOTYPE_METHOD(TagTemplate, "isEmpty", IsEmpty);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("title"), GetTitle, SetTitle);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("album"), GetAlbum, SetAlbum);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("comment"), GetComment, SetComment);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("artist"), GetArtist, SetArtist);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("track"), GetTrack, SetTrack);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("year"), GetYear, SetYear);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("genre"), GetGenre, SetGenre);
target->Set(String::NewSymbol("Tag"), TagTemplate->GetFunction());
NODE_SET_METHOD(target, "tag", AsyncTag);
NODE_SET_METHOD(target, "tagSync", SyncTag);
}
Tag::Tag(TagLib::FileRef * ffileRef) : tag(ffileRef->tag()), fileRef(ffileRef) { }
Tag::~Tag() {
if (fileRef)
delete fileRef;
fileRef = NULL;
tag = NULL;
}
inline Tag * unwrapTag(const AccessorInfo& info) {
return ObjectWrap::Unwrap<Tag>(info.Holder());
}
Handle<Value> Tag::GetTitle(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->title()));
}
void Tag::SetTitle(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setTitle(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetArtist(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->artist()));
}
void Tag::SetArtist(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setArtist(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetAlbum(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->album()));
}
void Tag::SetAlbum(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setAlbum(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetComment(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->comment()));
}
void Tag::SetComment(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setComment(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetTrack(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(Integer::New(unwrapTag(info)->tag->track()));
}
void Tag::SetTrack(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setTrack(value->IntegerValue());
}
Handle<Value> Tag::GetYear(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(Integer::New(unwrapTag(info)->tag->year()));
}
void Tag::SetYear(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setYear(value->IntegerValue());
}
Handle<Value> Tag::GetGenre(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->genre()));
}
void Tag::SetGenre(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setGenre(NodeStringToTagLibString(value));
}
Handle<Value> Tag::IsEmpty(const Arguments &args) {
HandleScope scope;
Tag *t = ObjectWrap::Unwrap<Tag>(args.This());
return Boolean::New(t->tag->isEmpty());
}
Handle<Value> Tag::SyncSaveTag(const Arguments &args) {
HandleScope scope;
Tag *t = ObjectWrap::Unwrap<Tag>(args.This());
assert(t->fileRef);
bool success = t->fileRef->save();
if (success)
return Undefined();
else
return ThrowException(String::Concat(
String::New("Failed to save file: "),
String::New(t->fileRef->file()->name())
));
}
Handle<Value> Tag::SyncTag(const Arguments &args) {
HandleScope scope;
TagLib::FileRef *f = 0;
int error = 0;
if (args.Length() >= 1 && args[0]->IsString()) {
String::Utf8Value path(args[0]->ToString());
if ((error = CreateFileRefPath(*path, &f))) {
Local<String> fn = String::Concat(args[0]->ToString(), Local<String>::Cast(String::New(": ", -1)));
return ThrowException(String::Concat(fn, ErrorToString(error)));
}
}
else if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
if (args.Length() < 2 || !args[1]->IsString())
return ThrowException(String::New("Expected string 'format' as second argument"));
if ((error = CreateFileRef(new BufferStream(args[0]->ToObject()), NodeStringToTagLibString(args[1]->ToString()), &f))) {
return ThrowException(ErrorToString(error));
}
}
else {
return ThrowException(String::New("Expected string or buffer as first argument"));
}
Tag * tag = new Tag(f);
Handle<Object> inst = TagTemplate->InstanceTemplate()->NewInstance();
tag->Wrap(inst);
return scope.Close(inst);
}
v8::Handle<v8::Value> Tag::AsyncTag(const v8::Arguments &args) {
HandleScope scope;
if (args.Length() < 1) {
return ThrowException(String::New("Expected string or buffer as first argument"));
}
if (args[0]->IsString()) {
if (args.Length() < 2 || !args[1]->IsFunction())
return ThrowException(String::New("Expected callback function as second argument"));
}
else if (Buffer::HasInstance(args[0])) {
if (args.Length() < 2 || !args[1]->IsString())
return ThrowException(String::New("Expected string 'format' as second argument"));
if (args.Length() < 3 || !args[2]->IsFunction())
return ThrowException(String::New("Expected callback function as third argument"));
}
else {
return ThrowException(String::New("Expected string or buffer as first argument"));
}
AsyncBaton *baton = new AsyncBaton;
baton->request.data = baton;
baton->path = 0;
baton->tag = NULL;
baton->error = 0;
if (args[0]->IsString()) {
String::Utf8Value path(args[0]->ToString());
baton->path = strdup(*path);
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1]));
}
else {
baton->format = NodeStringToTagLibString(args[1]->ToString());
baton->stream = new BufferStream(args[0]->ToObject());
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2]));
}
uv_queue_work(uv_default_loop(), &baton->request, Tag::AsyncTagReadDo, (uv_after_work_cb)Tag::AsyncTagReadAfter);
return Undefined();
}
void Tag::AsyncTagReadDo(uv_work_t *req) {
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
TagLib::FileRef *f;
if (baton->path) {
baton->error = node_taglib::CreateFileRefPath(baton->path, &f);
}
else {
assert(baton->stream);
baton->error = node_taglib::CreateFileRef(baton->stream, baton->format, &f);
}
if (baton->error == 0) {
baton->tag = new Tag(f);
}
}
void Tag::AsyncTagReadAfter(uv_work_t *req) {
HandleScope scope;
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
if (baton->error) {
Local<Object> error = Object::New();
error->Set(String::New("code"), Integer::New(baton->error));
error->Set(String::New("message"), ErrorToString(baton->error));
Handle<Value> argv[] = { error, Null() };
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
}
else {
Persistent<Object> inst = Persistent<Object>::New(TagTemplate->InstanceTemplate()->NewInstance());
baton->tag->Wrap(inst);
Handle<Value> argv[] = { Null(), inst };
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
}
baton->callback.Dispose();
delete baton->path;
delete baton;
}
v8::Handle<v8::Value> Tag::AsyncSaveTag(const v8::Arguments &args) {
HandleScope scope;
if (args.Length() >= 1 && !args[0]->IsFunction())
return ThrowException(String::New("Expected callback function as first argument"));
Local<Function> callback = Local<Function>::Cast(args[0]);
Tag *t = ObjectWrap::Unwrap<Tag>(args.This());
AsyncBaton *baton = new AsyncBaton;
baton->request.data = baton;
baton->tag = t;
baton->callback = Persistent<Function>::New(callback);
baton->error = 1;
uv_queue_work(uv_default_loop(), &baton->request, Tag::AsyncSaveTagDo, (uv_after_work_cb)Tag::AsyncSaveTagAfter);
return Undefined();
}
void Tag::AsyncSaveTagDo(uv_work_t *req) {
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
assert(baton->tag->fileRef);
baton->error = !baton->tag->fileRef->save();
}
void Tag::AsyncSaveTagAfter(uv_work_t *req) {
HandleScope scope;
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
if (baton->error) {
Local<Object> error = Object::New();
error->Set(String::New("message"), String::New("Failed to save file"));
error->Set(String::New("path"), String::New(baton->tag->fileRef->file()->name()));
Handle<Value> argv[] = { error };
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
}
else {
Handle<Value> argv[] = { Null() };
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
}
baton->callback.Dispose();
delete baton;
}
}
<commit_msg>Get rid of unused function now()<commit_after>#include "tag.h"
#include <errno.h>
#include <string.h>
#include <node_buffer.h>
#include "taglib.h"
#include "bufferstream.h"
using namespace node_taglib;
using namespace v8;
using namespace node;
namespace node_taglib {
static Persistent<FunctionTemplate> TagTemplate;
void Tag::Initialize(Handle<Object> target)
{
HandleScope scope;
TagTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New());
TagTemplate->InstanceTemplate()->SetInternalFieldCount(1);
TagTemplate->SetClassName(String::NewSymbol("Tag"));
NODE_SET_PROTOTYPE_METHOD(TagTemplate, "save", AsyncSaveTag);
NODE_SET_PROTOTYPE_METHOD(TagTemplate, "saveSync", SyncSaveTag);
NODE_SET_PROTOTYPE_METHOD(TagTemplate, "isEmpty", IsEmpty);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("title"), GetTitle, SetTitle);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("album"), GetAlbum, SetAlbum);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("comment"), GetComment, SetComment);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("artist"), GetArtist, SetArtist);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("track"), GetTrack, SetTrack);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("year"), GetYear, SetYear);
TagTemplate->InstanceTemplate()->SetAccessor(String::New("genre"), GetGenre, SetGenre);
target->Set(String::NewSymbol("Tag"), TagTemplate->GetFunction());
NODE_SET_METHOD(target, "tag", AsyncTag);
NODE_SET_METHOD(target, "tagSync", SyncTag);
}
Tag::Tag(TagLib::FileRef * ffileRef) : tag(ffileRef->tag()), fileRef(ffileRef) { }
Tag::~Tag() {
if (fileRef)
delete fileRef;
fileRef = NULL;
tag = NULL;
}
inline Tag * unwrapTag(const AccessorInfo& info) {
return ObjectWrap::Unwrap<Tag>(info.Holder());
}
Handle<Value> Tag::GetTitle(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->title()));
}
void Tag::SetTitle(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setTitle(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetArtist(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->artist()));
}
void Tag::SetArtist(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setArtist(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetAlbum(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->album()));
}
void Tag::SetAlbum(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setAlbum(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetComment(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->comment()));
}
void Tag::SetComment(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setComment(NodeStringToTagLibString(value));
}
Handle<Value> Tag::GetTrack(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(Integer::New(unwrapTag(info)->tag->track()));
}
void Tag::SetTrack(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setTrack(value->IntegerValue());
}
Handle<Value> Tag::GetYear(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(Integer::New(unwrapTag(info)->tag->year()));
}
void Tag::SetYear(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setYear(value->IntegerValue());
}
Handle<Value> Tag::GetGenre(Local<String> property, const AccessorInfo& info) {
HandleScope scope;
return scope.Close(TagLibStringToString(unwrapTag(info)->tag->genre()));
}
void Tag::SetGenre(Local<String> property, Local<Value> value, const AccessorInfo& info) {
HandleScope scope;
unwrapTag(info)->tag->setGenre(NodeStringToTagLibString(value));
}
Handle<Value> Tag::IsEmpty(const Arguments &args) {
HandleScope scope;
Tag *t = ObjectWrap::Unwrap<Tag>(args.This());
return Boolean::New(t->tag->isEmpty());
}
Handle<Value> Tag::SyncSaveTag(const Arguments &args) {
HandleScope scope;
Tag *t = ObjectWrap::Unwrap<Tag>(args.This());
assert(t->fileRef);
bool success = t->fileRef->save();
if (success)
return Undefined();
else
return ThrowException(String::Concat(
String::New("Failed to save file: "),
String::New(t->fileRef->file()->name())
));
}
Handle<Value> Tag::SyncTag(const Arguments &args) {
HandleScope scope;
TagLib::FileRef *f = 0;
int error = 0;
if (args.Length() >= 1 && args[0]->IsString()) {
String::Utf8Value path(args[0]->ToString());
if ((error = CreateFileRefPath(*path, &f))) {
Local<String> fn = String::Concat(args[0]->ToString(), Local<String>::Cast(String::New(": ", -1)));
return ThrowException(String::Concat(fn, ErrorToString(error)));
}
}
else if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
if (args.Length() < 2 || !args[1]->IsString())
return ThrowException(String::New("Expected string 'format' as second argument"));
if ((error = CreateFileRef(new BufferStream(args[0]->ToObject()), NodeStringToTagLibString(args[1]->ToString()), &f))) {
return ThrowException(ErrorToString(error));
}
}
else {
return ThrowException(String::New("Expected string or buffer as first argument"));
}
Tag * tag = new Tag(f);
Handle<Object> inst = TagTemplate->InstanceTemplate()->NewInstance();
tag->Wrap(inst);
return scope.Close(inst);
}
v8::Handle<v8::Value> Tag::AsyncTag(const v8::Arguments &args) {
HandleScope scope;
if (args.Length() < 1) {
return ThrowException(String::New("Expected string or buffer as first argument"));
}
if (args[0]->IsString()) {
if (args.Length() < 2 || !args[1]->IsFunction())
return ThrowException(String::New("Expected callback function as second argument"));
}
else if (Buffer::HasInstance(args[0])) {
if (args.Length() < 2 || !args[1]->IsString())
return ThrowException(String::New("Expected string 'format' as second argument"));
if (args.Length() < 3 || !args[2]->IsFunction())
return ThrowException(String::New("Expected callback function as third argument"));
}
else {
return ThrowException(String::New("Expected string or buffer as first argument"));
}
AsyncBaton *baton = new AsyncBaton;
baton->request.data = baton;
baton->path = 0;
baton->tag = NULL;
baton->error = 0;
if (args[0]->IsString()) {
String::Utf8Value path(args[0]->ToString());
baton->path = strdup(*path);
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1]));
}
else {
baton->format = NodeStringToTagLibString(args[1]->ToString());
baton->stream = new BufferStream(args[0]->ToObject());
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2]));
}
uv_queue_work(uv_default_loop(), &baton->request, Tag::AsyncTagReadDo, (uv_after_work_cb)Tag::AsyncTagReadAfter);
return Undefined();
}
void Tag::AsyncTagReadDo(uv_work_t *req) {
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
TagLib::FileRef *f;
if (baton->path) {
baton->error = node_taglib::CreateFileRefPath(baton->path, &f);
}
else {
assert(baton->stream);
baton->error = node_taglib::CreateFileRef(baton->stream, baton->format, &f);
}
if (baton->error == 0) {
baton->tag = new Tag(f);
}
}
void Tag::AsyncTagReadAfter(uv_work_t *req) {
HandleScope scope;
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
if (baton->error) {
Local<Object> error = Object::New();
error->Set(String::New("code"), Integer::New(baton->error));
error->Set(String::New("message"), ErrorToString(baton->error));
Handle<Value> argv[] = { error, Null() };
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
}
else {
Persistent<Object> inst = Persistent<Object>::New(TagTemplate->InstanceTemplate()->NewInstance());
baton->tag->Wrap(inst);
Handle<Value> argv[] = { Null(), inst };
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
}
baton->callback.Dispose();
delete baton->path;
delete baton;
}
v8::Handle<v8::Value> Tag::AsyncSaveTag(const v8::Arguments &args) {
HandleScope scope;
if (args.Length() >= 1 && !args[0]->IsFunction())
return ThrowException(String::New("Expected callback function as first argument"));
Local<Function> callback = Local<Function>::Cast(args[0]);
Tag *t = ObjectWrap::Unwrap<Tag>(args.This());
AsyncBaton *baton = new AsyncBaton;
baton->request.data = baton;
baton->tag = t;
baton->callback = Persistent<Function>::New(callback);
baton->error = 1;
uv_queue_work(uv_default_loop(), &baton->request, Tag::AsyncSaveTagDo, (uv_after_work_cb)Tag::AsyncSaveTagAfter);
return Undefined();
}
void Tag::AsyncSaveTagDo(uv_work_t *req) {
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
assert(baton->tag->fileRef);
baton->error = !baton->tag->fileRef->save();
}
void Tag::AsyncSaveTagAfter(uv_work_t *req) {
HandleScope scope;
AsyncBaton *baton = static_cast<AsyncBaton*>(req->data);
if (baton->error) {
Local<Object> error = Object::New();
error->Set(String::New("message"), String::New("Failed to save file"));
error->Set(String::New("path"), String::New(baton->tag->fileRef->file()->name()));
Handle<Value> argv[] = { error };
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
}
else {
Handle<Value> argv[] = { Null() };
baton->callback->Call(Context::GetCurrent()->Global(), 1, argv);
}
baton->callback.Dispose();
delete baton;
}
}
<|endoftext|> |
<commit_before>#ifndef _FALCON_TUPLE_TUPLE_COMPOSE_HPP
#define _FALCON_TUPLE_TUPLE_COMPOSE_HPP
#include <tuple>
#include <type_traits>
#include <falcon/tuple/tuple_apply.hpp>
#include <falcon/type_traits/cv_selector.hpp>
#include <falcon/tuple/parameter_index.hpp>
namespace falcon {
template <std::size_t _I, std::size_t _N, typename _Function,
typename _Tuple, typename _TupleArgs, typename _Indexes
>
struct __tuple_compose_base
{
typedef typename match_cv_qualifiers<
_Tuple,
typename std::tuple_element<
_I,
typename std::remove_cv<_Tuple>::type
>::type
>::type __func_type;
typedef __tuple_compose_base<
_I+1, _N,
_Function, _Tuple,
_TupleArgs, _Indexes
> __impl;
template<typename... _Args>
struct _Result_type
{
typedef typename __impl:: template _Result_type<
_Args...,
decltype(tuple_apply<__func_type&>(
_Indexes(), std::declval<__func_type&>(), std::declval<_TupleArgs&>()
))
>::__type __type;
};
typedef typename _Result_type<>::__type __result_type;
template<typename... _Args>
constexpr static __result_type
__call(_Function& __func, _Tuple& __t,
_TupleArgs& __targs, _Args&&... __args)
{
return __impl::__call(__func, __t, __targs,
std::forward<_Args>(__args)...,
tuple_apply<__func_type&>(_Indexes(),
std::get<_I>(__t),
__targs));
}
};
template <std::size_t _N, typename _Function,
typename _Tuple, typename _TupleArgs, typename _Indexes
>
struct __tuple_compose_base<_N, _N, _Function, _Tuple, _TupleArgs, _Indexes>
{
template<typename... _Args>
struct _Result_type
{
typedef decltype(std::declval<_Function&>()(std::declval<_Args&&>()...)) __type;
};
template<typename... _Args>
constexpr static decltype(std::declval<_Function&>()(std::declval<_Args&&>()...))
__call(_Function& __func, _Tuple&,
_TupleArgs&, _Args&&... __args)
{
return __func(std::forward<_Args>(__args)...);
}
};
template <typename _OperationsForSize,
typename _Operations, typename _Function, typename _ArgElements,
typename _Indexes = typename build_tuple_index<_ArgElements>::type
>
struct __tuple_compose
: __tuple_compose_base<
0, std::tuple_size<_Operations>::value, _Function,
_Operations, _ArgElements,
_Indexes
>
{};
/**
* \brief Call functors on tuple
*
* \param _Indexes... indexes arguments of @p targs
* \param func functor for the results of @p t
* \param t tuple functor
* \param targs tuple arguments for each element of @p t
*
* \code
* int answer = (tuple_compose(parameter_index<0,2>(),
* f, std::forward_as_tuple(g1,g2,g3),
* std::forward_as_tuple(x,y,z));
* \endcode
* is equivalent to
* \code
* int temp1 = g1(x,z);
* int temp2 = g2(x,z);
* int temp3 = g3(x,z);
* int answer = f(temp1,temp2,temp3);
* \endcode
* @{
*/
template <typename _Function, typename _Operations,
typename _ArgElements, std::size_t... _Indexes>
constexpr typename __tuple_compose<
_Operations, _Operations, _Function, _ArgElements,
parameter_index<_Indexes...>
>::__result_type
tuple_compose(const parameter_index<_Indexes...>&, _Function __func,
_Operations& __t, _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Operations, _Function, _ArgElements,
parameter_index<_Indexes...>
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements, std::size_t... _Indexes>
constexpr typename __tuple_compose<
_Operations, const _Operations, _Function, _ArgElements,
parameter_index<_Indexes...>
>::__result_type
tuple_compose(const parameter_index<_Indexes...>&, _Function __func,
const _Operations& __t, _ArgElements& __targs)
{
return __tuple_compose<
_Operations, const _Operations, _Function, _ArgElements,
parameter_index<_Indexes...>
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements, std::size_t... _Indexes>
constexpr typename __tuple_compose<
_Operations, _Operations, _Function, const _ArgElements,
parameter_index<_Indexes...>
>::__result_type
tuple_compose(const parameter_index<_Indexes...>&, _Function __func,
_Operations& __t, const _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Operations, _Function, const _ArgElements,
parameter_index<_Indexes...>
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements, std::size_t... _Indexes>
constexpr typename __tuple_compose<
_Operations, const _Operations, _Function, const _ArgElements,
parameter_index<_Indexes...>
>::__result_type
tuple_compose(const parameter_index<_Indexes...>&, _Function __func,
const _Operations& __t, const _ArgElements& __targs)
{
return __tuple_compose<
_Operations, const _Operations, _Function, const _ArgElements,
parameter_index<_Indexes...>
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations>
constexpr typename __tuple_compose<
_Operations, _Operations, _Function, const std::tuple<>
>::__result_type
tuple_compose(_Function __func, _Operations& __t)
{
return __tuple_compose<
_Operations, _Operations, _Function, const std::tuple<>
>::__call(__func, __t, std::tuple<>());
}
template <typename _Function, typename _Operations>
constexpr typename __tuple_compose<
_Operations, const _Operations, _Function, const std::tuple<>
>::__result_type
tuple_compose(_Function __func, const _Operations& __t)
{
return __tuple_compose<
_Operations, const _Operations, _Function, const std::tuple<>
>::__call(__func, __t, std::tuple<>());
}
template <typename _Function, typename _Operations,
typename _ArgElements>
constexpr typename __tuple_compose<
_Operations, _Operations, _Function, _ArgElements
>::__result_type
tuple_compose(_Function __func, _Operations& __t, _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Operations, _Function, _ArgElements
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements>
constexpr typename __tuple_compose<
_Operations, const _Operations, _Function, _ArgElements
>::__result_type
tuple_compose(_Function __func, const _Operations& __t, _ArgElements& __targs)
{
return __tuple_compose<
_Operations, const _Operations, _Function, _ArgElements
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements>
constexpr typename __tuple_compose<
_Operations, _Operations, _Function, const _ArgElements
>::__result_type
tuple_compose(_Function __func, _Operations& __t, const _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Operations, _Function, const _ArgElements
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements>
constexpr typename __tuple_compose<
_Operations, const _Operations, _Function, const _ArgElements
>::__result_type
tuple_compose(_Function __func, const _Operations& __t, const _ArgElements& __targs)
{
return __tuple_compose<
_Operations, const _Operations, _Function, const _ArgElements
>::__call(__func, __t, __targs);
}
//@}
}
#endif<commit_msg>fixing bug<commit_after>#ifndef _FALCON_TUPLE_TUPLE_COMPOSE_HPP
#define _FALCON_TUPLE_TUPLE_COMPOSE_HPP
#include <tuple>
#include <type_traits>
#include <falcon/tuple/tuple_apply.hpp>
#include <falcon/type_traits/cv_selector.hpp>
namespace falcon {
template <std::size_t _I, std::size_t _N, typename _Function,
typename _Tuple, typename _TupleArgs, typename _Indexes
>
struct __tuple_compose_base
{
typedef typename match_cv_qualifiers<
_Tuple,
typename std::tuple_element<
_I,
typename std::remove_cv<_Tuple>::type
>::type
>::type __func_type;
typedef __tuple_compose_base<
_I+1, _N,
_Function, _Tuple,
_TupleArgs, _Indexes
> __impl;
template<typename... _Args>
struct _Result_type
{
typedef typename __impl:: template _Result_type<
_Args...,
decltype(tuple_apply<__func_type&>(
_Indexes(), std::declval<__func_type&>(), std::declval<_TupleArgs&>()
))
>::__type __type;
};
typedef typename _Result_type<>::__type __result_type;
template<typename... _Args>
constexpr static typename _Result_type<_Args...>::__type
__call(_Function& __func, _Tuple& __t, _TupleArgs& __targs, _Args&&... __args)
{
return __impl::__call(__func, __t, __targs,
std::forward<_Args>(__args)...,
tuple_apply<__func_type&>(_Indexes(),
std::get<_I>(__t),
__targs));
}
};
template <std::size_t _N, typename _Function,
typename _Tuple, typename _TupleArgs, typename _Indexes
>
struct __tuple_compose_base<_N, _N, _Function, _Tuple, _TupleArgs, _Indexes>
{
template<typename... _Args>
struct _Result_type
{
typedef decltype(std::declval<_Function&>()(std::declval<_Args&&>()...)) __type;
};
template<typename... _Args>
constexpr static typename _Result_type<_Args...>::__type
__call(_Function& __func, _Tuple&, _TupleArgs&, _Args&&... __args)
{ return __func(std::forward<_Args>(__args)...); }
};
template <typename _Operations,
typename _Function, typename _ArgElements,
typename _Indexes = typename build_tuple_index<_ArgElements>::type
>
struct __tuple_compose
: __tuple_compose_base<
0, std::tuple_size<_Operations>::value, _Function,
_Operations, _ArgElements,
_Indexes
>
{};
/**
* \brief Call functors on tuple
*
* \param _Indexes... indexes arguments of @p targs
* \param func functor for the results of @p t
* \param t tuple functor
* \param targs tuple arguments for each element of @p t
*
* \code
* int answer = (tuple_compose(parameter_index<0,2>(),
* f, std::forward_as_tuple(g1,g2,g3),
* std::forward_as_tuple(x,y,z));
* \endcode
* is equivalent to
* \code
* int temp1 = g1(x,z);
* int temp2 = g2(x,z);
* int temp3 = g3(x,z);
* int answer = f(temp1,temp2,temp3);
* \endcode
* @{
*/
template <typename _Function, typename _Operations,
typename _ArgElements, std::size_t... _Indexes>
constexpr typename __tuple_compose<
_Operations, _Function, _ArgElements,
parameter_index<_Indexes...>
>::__result_type
tuple_compose(const parameter_index<_Indexes...>&, _Function __func,
_Operations __t, _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Function, _ArgElements,
parameter_index<_Indexes...>
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements, std::size_t... _Indexes>
constexpr typename __tuple_compose<
_Operations, _Function, const _ArgElements,
parameter_index<_Indexes...>
>::__result_type
tuple_compose(const parameter_index<_Indexes...>&, _Function __func,
_Operations __t, const _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Function, const _ArgElements,
parameter_index<_Indexes...>
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations>
constexpr typename __tuple_compose<
_Operations, _Function, const std::tuple<>
>::__result_type
tuple_compose(_Function __func, _Operations __t)
{
return __tuple_compose<
_Operations, _Function, const std::tuple<>
>::__call(__func, __t, std::tuple<>());
}
template <typename _Function, typename _Operations,
typename _ArgElements>
constexpr typename __tuple_compose<
_Operations, _Function, _ArgElements
>::__result_type
tuple_compose(_Function __func, _Operations __t, _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Function, _ArgElements
>::__call(__func, __t, __targs);
}
template <typename _Function, typename _Operations,
typename _ArgElements>
constexpr typename __tuple_compose<
_Operations, _Function, const _ArgElements
>::__result_type
tuple_compose(_Function __func, _Operations __t, const _ArgElements& __targs)
{
return __tuple_compose<
_Operations, _Function, const _ArgElements
>::__call(__func, __t, __targs);
}
//@}
}
#endif<|endoftext|> |
<commit_before>#include <cassert>
#include <functional>
#include <iostream>
#include <type_traits>
#include <unordered_map>
#include "vm.h"
const int STACK_SIZE = 1024;
enum offset {
return_address = 0,
enclosing_frame = 1,
declaration_frame = 2,
local = 3
};
void pl0::execute(const bytecode & code, int entry_addr) {
int pc = 0;
int *stack = new int[STACK_SIZE];
int *bp = stack;
int *sp = bp + offset::declaration_frame;
auto resolve = [&](int dist) -> int* {
int *fp = bp;
while (dist > 0) {
fp = reinterpret_cast<int*>(fp[offset::declaration_frame]);
dist--;
}
return fp;
};
auto push = [&](auto value) -> void {
if constexpr (std::is_pointer_v<decltype(value)>) {
*++sp = reinterpret_cast<int>(value);
} else {
*++sp = value;
}
};
auto pop = [&]() -> int {
return *sp--;
};
const std::unordered_map<opt, std::function<int(int, int)>> bifunctors = {
{ opt::ADD, std::plus<int>() },
{ opt::SUB, std::minus<int>() },
{ opt::DIV, std::divides<int>() },
{ opt::MUL, std::multiplies<int>() },
{ opt::LE, std::less<int>() },
{ opt::LEQ, std::less_equal<int>() },
{ opt::GE, std::greater<int>() },
{ opt::GEQ, std::greater_equal<int>() },
{ opt::EQ, std::equal_to<int>() },
{ opt::NEQ, std::not_equal_to<int>() }
};
while (pc < code.size()) {
const instruction & ins = code[pc];
pc++;
switch (std::get<0>(ins)) {
case opcode::LIT:
push(std::get<2>(ins));
break;
case opcode::LOD:
push(resolve(std::get<1>(ins))[offset::local + std::get<2>(ins)]);
break;
case opcode::STO:
resolve(std::get<1>(ins))[offset::local + std::get<2>(ins)] = pop();
break;
case opcode::CAL:
push(pc);
push(bp);
push(resolve(std::get<1>(ins)));
bp = sp - 3;
pc = std::get<2>(ins);
break;
case opcode::INT:
sp += std::get<2>(ins);
break;
case opcode::JMP:
pc = std::get<2>(ins);
break;
case opcode::JPC:
if (pop()) pc = std::get<2>(ins);
break;
case opcode::OPR:
if (std::get<2>(ins) == *opt::ODD) {
push(pop() % 2);
} else if (std::get<2>(ins) == *opt::READ) {
int tmp;
std::cin >> tmp;
push(tmp);
} else if (std::get<2>(ins) == *opt::WRITE) {
std::cout << pop() << '\n';
} else if (std::get<2>(ins) == *opt::RET) {
sp = bp + offset::enclosing_frame;
bp = reinterpret_cast<int*>(pop());
pc = pop();
} else {
int rhs = pop(), lhs = pop();
bifunctors.find(opt(std::get<2>(ins)))->second(lhs, rhs);
}
break;
}
}
}
<commit_msg>Fix comparision between signed and unsigned.<commit_after>#include <cassert>
#include <functional>
#include <iostream>
#include <type_traits>
#include <unordered_map>
#include "vm.h"
const int STACK_SIZE = 1024;
enum offset {
return_address = 0,
enclosing_frame = 1,
declaration_frame = 2,
local = 3
};
void pl0::execute(const bytecode & code, int entry_addr) {
int pc = 0;
int *stack = new int[STACK_SIZE];
int *bp = stack;
int *sp = bp + offset::declaration_frame;
auto resolve = [&](int dist) -> int* {
int *fp = bp;
while (dist > 0) {
fp = reinterpret_cast<int*>(fp[offset::declaration_frame]);
dist--;
}
return fp;
};
auto push = [&](auto value) -> void {
if constexpr (std::is_pointer_v<decltype(value)>) {
*++sp = reinterpret_cast<int>(value);
} else {
*++sp = value;
}
};
auto pop = [&]() -> int {
return *sp--;
};
const std::unordered_map<opt, std::function<int(int, int)>> bifunctors = {
{ opt::ADD, std::plus<int>() },
{ opt::SUB, std::minus<int>() },
{ opt::DIV, std::divides<int>() },
{ opt::MUL, std::multiplies<int>() },
{ opt::LE, std::less<int>() },
{ opt::LEQ, std::less_equal<int>() },
{ opt::GE, std::greater<int>() },
{ opt::GEQ, std::greater_equal<int>() },
{ opt::EQ, std::equal_to<int>() },
{ opt::NEQ, std::not_equal_to<int>() }
};
int codelen = static_cast<int>(code.size());
while (pc < codelen) {
const instruction & ins = code[pc];
pc++;
switch (std::get<0>(ins)) {
case opcode::LIT:
push(std::get<2>(ins));
break;
case opcode::LOD:
push(resolve(std::get<1>(ins))[offset::local + std::get<2>(ins)]);
break;
case opcode::STO:
resolve(std::get<1>(ins))[offset::local + std::get<2>(ins)] = pop();
break;
case opcode::CAL:
push(pc);
push(bp);
push(resolve(std::get<1>(ins)));
bp = sp - 3;
pc = std::get<2>(ins);
break;
case opcode::INT:
sp += std::get<2>(ins);
break;
case opcode::JMP:
pc = std::get<2>(ins);
break;
case opcode::JPC:
if (pop()) pc = std::get<2>(ins);
break;
case opcode::OPR:
if (std::get<2>(ins) == *opt::ODD) {
push(pop() % 2);
} else if (std::get<2>(ins) == *opt::READ) {
int tmp;
std::cin >> tmp;
push(tmp);
} else if (std::get<2>(ins) == *opt::WRITE) {
std::cout << pop() << '\n';
} else if (std::get<2>(ins) == *opt::RET) {
sp = bp + offset::enclosing_frame;
bp = reinterpret_cast<int*>(pop());
pc = pop();
} else {
int rhs = pop(), lhs = pop();
bifunctors.find(opt(std::get<2>(ins)))->second(lhs, rhs);
}
break;
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <vector>
#include <map>
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/error/en.h"
#include "rapidjson/stringbuffer.h"
#include "acmacs-base/read-file.hh"
// ----------------------------------------------------------------------
// Forward declarations
// ----------------------------------------------------------------------
namespace json_writer
{
template <typename RW> class writer;
class key;
}
template <typename RW, typename T> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, const std::vector<T>&);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, const char*);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, std::string);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, double);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, int);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, size_t);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, bool);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, const std::map<std::string, std::vector<std::string>>&);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, json_writer::key);
// ======================================================================
namespace json_writer
{
template <typename RW> class writer : public RW // JsonWriterT
{
public:
inline writer(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {}
inline operator std::string() const { return mBuffer.GetString(); }
inline std::string keyword() const { return mKeyword; }
private:
rapidjson::StringBuffer mBuffer;
std::string mKeyword;
};
// template <> inline writer<rapidjson::PrettyWriter<rapidjson::StringBuffer>>::writer(std::string aKeyword)
// : rapidjson::PrettyWriter<rapidjson::StringBuffer>(mBuffer), mKeyword(aKeyword)
// {
// SetIndent(' ', 1);
// }
// ----------------------------------------------------------------------
enum _StartArray { start_array };
enum _EndArray { end_array };
enum _StartObject { start_object };
enum _EndObject { end_object };
class key
{
public:
inline key(const char* v) : value(v) {}
inline key(std::string v) : value(v) {}
inline key(char v) : value(1, v) {}
inline operator const char*() const { return value.c_str(); }
private:
std::string value;
};
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
namespace _internal
{
// void_t is a C++17 feature
template<class ...> using void_t = void; // http://stackoverflow.com/questions/26513095/void-t-can-implement-concepts
template <typename T, typename = void> struct castable_to_char : public std::false_type {};
template <typename T> struct castable_to_char<T, void_t<decltype(static_cast<char>(std::declval<T>()))>> : public std::true_type {};
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
template <typename Key, typename Value> class _if_not_empty
{
public:
inline _if_not_empty(Key&& aKey, Value&& aValue) : mKey(aKey), mValue(aValue) {}
template <typename RW> friend inline writer<RW>& operator <<(writer<RW>& aWriter, const _if_not_empty<Key, Value>& data)
{
if (!data.mValue.empty())
aWriter << data.mKey << data.mValue;
return aWriter;
}
private:
Key mKey;
Value mValue;
};
template <typename Key, typename Value> inline auto if_not_empty(Key&& aKey, Value&& aValue) { return _if_not_empty<Key, Value>(std::forward<Key>(aKey), std::forward<Value>(aValue)); }
template <typename Value> inline auto if_not_empty(const char* aKey, Value&& aValue) { return _if_not_empty<key, Value>(key(aKey), std::forward<Value>(aValue)); }
// ----------------------------------------------------------------------
template <typename Key, typename Value> class _if_non_negative
{
public:
inline _if_non_negative(Key&& aKey, Value&& aValue) : mKey(aKey), mValue(aValue) {}
template <typename RW> friend inline writer<RW>& operator <<(writer<RW>& aWriter, const _if_non_negative<Key, Value>& data)
{
if (data.mValue >= 0.0)
aWriter << data.mKey << data.mValue;
return aWriter;
}
private:
Key mKey;
Value mValue;
};
template <typename Key, typename Value> inline auto if_non_negative(Key&& aKey, Value&& aValue) { return _if_non_negative<Key, Value>(std::forward<Key>(aKey), std::forward<Value>(aValue)); }
template <typename Value> inline auto if_non_negative(const char* aKey, Value&& aValue) { return _if_non_negative<key, Value>(key(aKey), std::forward<Value>(aValue)); }
} // namespace json_writer
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_StartArray) { aWriter.StartArray(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_EndArray) { aWriter.EndArray(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_StartObject) { aWriter.StartObject(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_EndObject) { aWriter.EndObject(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const char* s) { aWriter.String(s, static_cast<unsigned>(strlen(s))); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, std::string s) { aWriter.String(s.c_str(), static_cast<unsigned>(s.size())); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, int value) { aWriter.Int(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, size_t value) { aWriter.Uint64(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, bool value) { aWriter.Bool(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, double value) { aWriter.Double(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::key value) { aWriter.Key(value); return aWriter; }
template <typename RW, typename T> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const std::vector<T>& aList)
{
aWriter << json_writer::start_array;
for (const auto& e: aList)
aWriter << e;
return aWriter << json_writer::end_array;
}
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const std::vector<std::vector<std::string>>& list_list_strings)
{
aWriter << json_writer::start_array;
for (const auto& e: list_list_strings)
aWriter << e;
return aWriter << json_writer::end_array;
}
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const std::map<std::string, std::vector<std::string>>& map_list_strings)
{
aWriter << json_writer::start_object;
for (const auto& e: map_list_strings)
aWriter << json_writer::key(e.first) << e.second;
return aWriter << json_writer::end_object;
}
template <typename RW, typename Key, typename std::enable_if<json_writer::_internal::castable_to_char<Key>{}>::type* = nullptr>
inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, Key aKey)
{
const char k = static_cast<char>(aKey);
aWriter.Key(&k, 1, false);
return aWriter;
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
namespace json_writer
{
template <typename V> inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint)
{
writer<rapidjson::PrettyWriter<rapidjson::StringBuffer>> aWriter(keyword);
aWriter.SetIndent(' ', static_cast<unsigned int>(indent));
aWriter << value;
std::string result = aWriter;
if (insert_emacs_indent_hint && result[0] == '{') {
const std::string ind(indent - 1, ' ');
result.insert(1, ind + "\"_\": \"-*- js-indent-level: " + std::to_string(indent) + " -*-\",");
}
return result;
}
template <typename V> inline std::string compact_json(const V& aValue, std::string keyword)
{
writer<rapidjson::Writer<rapidjson::StringBuffer>> aWriter(keyword);
return aWriter << aValue;
}
template <typename V> inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true)
{
if (indent)
return pretty_json(value, keyword, indent, insert_emacs_indent_hint);
else
return compact_json(value, keyword);
}
// ----------------------------------------------------------------------
template <typename V> inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true, bool force_compression = false)
{
acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint), force_compression);
}
} // namespace json_writer
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>json_writer if_not_zero and if_not_one predicates added<commit_after>#pragma once
#include <string>
#include <vector>
#include <map>
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/error/en.h"
#include "rapidjson/stringbuffer.h"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/float.hh"
// ----------------------------------------------------------------------
// Forward declarations
// ----------------------------------------------------------------------
namespace json_writer
{
template <typename RW> class writer;
class key;
}
template <typename RW, typename T> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, const std::vector<T>&);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, const char*);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, std::string);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, double);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, int);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, size_t);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, bool);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, const std::map<std::string, std::vector<std::string>>&);
template <typename RW> json_writer::writer<RW>& operator <<(json_writer::writer<RW>&, json_writer::key);
// ======================================================================
namespace json_writer
{
template <typename RW> class writer : public RW // JsonWriterT
{
public:
inline writer(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {}
inline operator std::string() const { return mBuffer.GetString(); }
inline std::string keyword() const { return mKeyword; }
private:
rapidjson::StringBuffer mBuffer;
std::string mKeyword;
};
// template <> inline writer<rapidjson::PrettyWriter<rapidjson::StringBuffer>>::writer(std::string aKeyword)
// : rapidjson::PrettyWriter<rapidjson::StringBuffer>(mBuffer), mKeyword(aKeyword)
// {
// SetIndent(' ', 1);
// }
// ----------------------------------------------------------------------
enum _StartArray { start_array };
enum _EndArray { end_array };
enum _StartObject { start_object };
enum _EndObject { end_object };
class key
{
public:
inline key(const char* v) : value(v) {}
inline key(std::string v) : value(v) {}
inline key(char v) : value(1, v) {}
inline operator const char*() const { return value.c_str(); }
private:
std::string value;
};
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
namespace _internal
{
// void_t is a C++17 feature
template<class ...> using void_t = void; // http://stackoverflow.com/questions/26513095/void-t-can-implement-concepts
template <typename T, typename = void> struct castable_to_char : public std::false_type {};
template <typename T> struct castable_to_char<T, void_t<decltype(static_cast<char>(std::declval<T>()))>> : public std::true_type {};
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
template <typename Key, typename Value> class _if_not_empty
{
public:
inline _if_not_empty(Key&& aKey, Value&& aValue) : mKey(aKey), mValue(aValue) {}
template <typename RW> friend inline writer<RW>& operator <<(writer<RW>& aWriter, const _if_not_empty<Key, Value>& data)
{
if (!data.mValue.empty())
aWriter << data.mKey << data.mValue;
return aWriter;
}
private:
Key mKey;
Value mValue;
};
template <typename Key, typename Value> inline auto if_not_empty(Key&& aKey, Value&& aValue) { return _if_not_empty<Key, Value>(std::forward<Key>(aKey), std::forward<Value>(aValue)); }
template <typename Value> inline auto if_not_empty(const char* aKey, Value&& aValue) { return _if_not_empty<key, Value>(key(aKey), std::forward<Value>(aValue)); }
// ----------------------------------------------------------------------
template <typename Key, typename Value> class _if_non_negative
{
public:
inline _if_non_negative(Key&& aKey, Value&& aValue) : mKey(aKey), mValue(aValue) {}
template <typename RW> friend inline writer<RW>& operator <<(writer<RW>& aWriter, const _if_non_negative<Key, Value>& data)
{
if (data.mValue >= 0.0)
aWriter << data.mKey << data.mValue;
return aWriter;
}
private:
Key mKey;
Value mValue;
};
template <typename Key, typename Value> inline auto if_non_negative(Key&& aKey, Value&& aValue) { return _if_non_negative<Key, Value>(std::forward<Key>(aKey), std::forward<Value>(aValue)); }
template <typename Value> inline auto if_non_negative(const char* aKey, Value&& aValue) { return _if_non_negative<key, Value>(key(aKey), std::forward<Value>(aValue)); }
// ----------------------------------------------------------------------
template <typename Key, typename Value> class _if_not
{
public:
inline _if_not(Key&& aKey, Value&& aValue, bool aPred) : mKey(aKey), mValue(aValue), mPred(aPred) {}
inline _if_not(Key&& aKey, Value aValue, bool aPred) : mKey(aKey), mValue(aValue), mPred(aPred) {}
template <typename RW> friend inline writer<RW>& operator <<(writer<RW>& aWriter, const _if_not<Key, Value>& data)
{
if (!data.mPred)
aWriter << data.mKey << data.mValue;
return aWriter;
}
private:
Key mKey;
Value mValue;
bool mPred;
};
template <typename Key> inline auto if_not_zero(Key&& aKey, double aValue) { return _if_not<Key, double>(std::forward<Key>(aKey), aValue, float_zero(aValue)); }
inline auto if_not_zero(const char* aKey, double aValue) { return _if_not<key, double>(key(aKey), aValue, float_zero(aValue)); }
template <typename Key> inline auto if_not_one(Key&& aKey, double aValue) { return _if_not<Key, double>(std::forward<Key>(aKey), aValue, float_equal(aValue, 1.0)); }
inline auto if_not_one(const char* aKey, double aValue) { return _if_not<key, double>(key(aKey), aValue, float_equal(aValue, 1.0)); }
} // namespace json_writer
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_StartArray) { aWriter.StartArray(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_EndArray) { aWriter.EndArray(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_StartObject) { aWriter.StartObject(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::_EndObject) { aWriter.EndObject(); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const char* s) { aWriter.String(s, static_cast<unsigned>(strlen(s))); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, std::string s) { aWriter.String(s.c_str(), static_cast<unsigned>(s.size())); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, int value) { aWriter.Int(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, size_t value) { aWriter.Uint64(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, bool value) { aWriter.Bool(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, double value) { aWriter.Double(value); return aWriter; }
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, json_writer::key value) { aWriter.Key(value); return aWriter; }
template <typename RW, typename T> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const std::vector<T>& aList)
{
aWriter << json_writer::start_array;
for (const auto& e: aList)
aWriter << e;
return aWriter << json_writer::end_array;
}
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const std::vector<std::vector<std::string>>& list_list_strings)
{
aWriter << json_writer::start_array;
for (const auto& e: list_list_strings)
aWriter << e;
return aWriter << json_writer::end_array;
}
template <typename RW> inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, const std::map<std::string, std::vector<std::string>>& map_list_strings)
{
aWriter << json_writer::start_object;
for (const auto& e: map_list_strings)
aWriter << json_writer::key(e.first) << e.second;
return aWriter << json_writer::end_object;
}
template <typename RW, typename Key, typename std::enable_if<json_writer::_internal::castable_to_char<Key>{}>::type* = nullptr>
inline json_writer::writer<RW>& operator <<(json_writer::writer<RW>& aWriter, Key aKey)
{
const char k = static_cast<char>(aKey);
aWriter.Key(&k, 1, false);
return aWriter;
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
namespace json_writer
{
template <typename V> inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint)
{
writer<rapidjson::PrettyWriter<rapidjson::StringBuffer>> aWriter(keyword);
aWriter.SetIndent(' ', static_cast<unsigned int>(indent));
aWriter << value;
std::string result = aWriter;
if (insert_emacs_indent_hint && result[0] == '{') {
const std::string ind(indent - 1, ' ');
result.insert(1, ind + "\"_\": \"-*- js-indent-level: " + std::to_string(indent) + " -*-\",");
}
return result;
}
template <typename V> inline std::string compact_json(const V& aValue, std::string keyword)
{
writer<rapidjson::Writer<rapidjson::StringBuffer>> aWriter(keyword);
return aWriter << aValue;
}
template <typename V> inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true)
{
if (indent)
return pretty_json(value, keyword, indent, insert_emacs_indent_hint);
else
return compact_json(value, keyword);
}
// ----------------------------------------------------------------------
template <typename V> inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true, bool force_compression = false)
{
acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint), force_compression);
}
} // namespace json_writer
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include <sstream>
#include "tink/util/status.h"
// placeholder_google3_status_header, please ignore
using ::std::ostream;
namespace crypto {
namespace tink {
namespace util {
namespace {
const Status& GetCancelled() {
static const Status status(::crypto::tink::util::error::CANCELLED, "");
return status;
}
const Status& GetUnknown() {
static const Status status(::crypto::tink::util::error::UNKNOWN, "");
return status;
}
} // namespace
// placeholder_implicit_type_conversion, please ignore
Status::Status() : code_(::crypto::tink::util::error::OK), message_("") {
}
Status::Status(::crypto::tink::util::error::Code error,
const std::string& error_message)
: code_(error), message_(error_message) {
if (code_ == ::crypto::tink::util::error::OK) {
message_.clear();
}
}
Status& Status::operator=(const Status& other) {
code_ = other.code_;
message_ = other.message_;
return *this;
}
const Status& Status::CANCELLED = GetCancelled();
const Status& Status::UNKNOWN = GetUnknown();
const Status& Status::OK = Status();
std::string Status::ToString() const {
if (code_ == ::crypto::tink::util::error::OK) {
return "OK";
}
std::ostringstream oss;
oss << code_ << ": " << message_;
return oss.str();
}
std::string ErrorCodeString(crypto::tink::util::error::Code error) {
switch (error) {
case crypto::tink::util::error::OK:
return "OK";
case crypto::tink::util::error::CANCELLED:
return "CANCELLED";
case crypto::tink::util::error::UNKNOWN:
return "UNKNOWN";
case crypto::tink::util::error::INVALID_ARGUMENT:
return "INVALID_ARGUMENT";
case crypto::tink::util::error::DEADLINE_EXCEEDED:
return "DEADLINE_EXCEEDED";
case crypto::tink::util::error::NOT_FOUND:
return "NOT_FOUND";
case crypto::tink::util::error::ALREADY_EXISTS:
return "ALREADY_EXISTS";
case crypto::tink::util::error::PERMISSION_DENIED:
return "PERMISSION_DENIED";
case crypto::tink::util::error::RESOURCE_EXHAUSTED:
return "RESOURCE_EXHAUSTED";
case crypto::tink::util::error::FAILED_PRECONDITION:
return "FAILED_PRECONDITION";
case crypto::tink::util::error::ABORTED:
return "ABORTED";
case crypto::tink::util::error::OUT_OF_RANGE:
return "OUT_OF_RANGE";
case crypto::tink::util::error::UNIMPLEMENTED:
return "UNIMPLEMENTED";
case crypto::tink::util::error::INTERNAL:
return "INTERNAL";
case crypto::tink::util::error::UNAVAILABLE:
return "UNAVAILABLE";
case crypto::tink::util::error::DATA_LOSS:
return "DATA_LOSS";
}
// Avoid using a "default" in the switch, so that the compiler can
// give us a warning, but still provide a fallback here.
return std::to_string(error);
}
extern ostream& operator<<(ostream& os, crypto::tink::util::error::Code code) {
os << ErrorCodeString(code);
return os;
}
extern ostream& operator<<(ostream& os, const Status& other) {
os << other.ToString();
return os;
}
} // namespace util
} // namespace tink
} // namespace crypto
<commit_msg>Internal change<commit_after>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#include <sstream>
#include "tink/util/status.h"
// placeholder_google3_status_header, please ignore
using ::std::ostream;
namespace crypto {
namespace tink {
namespace util {
namespace {
const Status& GetCancelled() {
static const Status status(::crypto::tink::util::error::CANCELLED, "");
return status;
}
const Status& GetUnknown() {
static const Status status(::crypto::tink::util::error::UNKNOWN, "");
return status;
}
} // namespace
// Keep synchronized with google3/third_party/tink/copybara/cc.bara.sky
#ifndef __APPLE__
Status::Status(const ::util::Status& status)
: code_(::crypto::tink::util::error::OK) {
if (status.ok()) return;
code_ = static_cast<::crypto::tink::util::error::Code>(
::util::RetrieveErrorCode(status));
message_ = std::string(status.message());
}
Status::operator ::util::Status() const {
if (ok()) return ::util::OkStatus();
return ::util::Status(static_cast<absl::StatusCode>(code_), message_);
}
#endif
// end of block in sync with google3/third_party/tink/copybara/cc.bara.sky
Status::Status() : code_(::crypto::tink::util::error::OK), message_("") {
}
Status::Status(::crypto::tink::util::error::Code error,
const std::string& error_message)
: code_(error), message_(error_message) {
if (code_ == ::crypto::tink::util::error::OK) {
message_.clear();
}
}
Status& Status::operator=(const Status& other) {
code_ = other.code_;
message_ = other.message_;
return *this;
}
const Status& Status::CANCELLED = GetCancelled();
const Status& Status::UNKNOWN = GetUnknown();
const Status& Status::OK = Status();
std::string Status::ToString() const {
if (code_ == ::crypto::tink::util::error::OK) {
return "OK";
}
std::ostringstream oss;
oss << code_ << ": " << message_;
return oss.str();
}
std::string ErrorCodeString(crypto::tink::util::error::Code error) {
switch (error) {
case crypto::tink::util::error::OK:
return "OK";
case crypto::tink::util::error::CANCELLED:
return "CANCELLED";
case crypto::tink::util::error::UNKNOWN:
return "UNKNOWN";
case crypto::tink::util::error::INVALID_ARGUMENT:
return "INVALID_ARGUMENT";
case crypto::tink::util::error::DEADLINE_EXCEEDED:
return "DEADLINE_EXCEEDED";
case crypto::tink::util::error::NOT_FOUND:
return "NOT_FOUND";
case crypto::tink::util::error::ALREADY_EXISTS:
return "ALREADY_EXISTS";
case crypto::tink::util::error::PERMISSION_DENIED:
return "PERMISSION_DENIED";
case crypto::tink::util::error::RESOURCE_EXHAUSTED:
return "RESOURCE_EXHAUSTED";
case crypto::tink::util::error::FAILED_PRECONDITION:
return "FAILED_PRECONDITION";
case crypto::tink::util::error::ABORTED:
return "ABORTED";
case crypto::tink::util::error::OUT_OF_RANGE:
return "OUT_OF_RANGE";
case crypto::tink::util::error::UNIMPLEMENTED:
return "UNIMPLEMENTED";
case crypto::tink::util::error::INTERNAL:
return "INTERNAL";
case crypto::tink::util::error::UNAVAILABLE:
return "UNAVAILABLE";
case crypto::tink::util::error::DATA_LOSS:
return "DATA_LOSS";
}
// Avoid using a "default" in the switch, so that the compiler can
// give us a warning, but still provide a fallback here.
return std::to_string(error);
}
extern ostream& operator<<(ostream& os, crypto::tink::util::error::Code code) {
os << ErrorCodeString(code);
return os;
}
extern ostream& operator<<(ostream& os, const Status& other) {
os << other.ToString();
return os;
}
} // namespace util
} // namespace tink
} // namespace crypto
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "test_light.hpp"
namespace {
bool starts_with(const std::string& str, const std::string& search) {
return std::mismatch(search.begin(), search.end(), str.begin()).first == search.end();
}
} //end of anonymous namespace
TEMPLATE_TEST_CASE_2("timed/1", "[fast][serial]", Z, float, double) {
std::stringstream buffer;
auto* old = std::cout.rdbuf(buffer.rdbuf());
etl::fast_vector<Z, 3> a({1.0, -2.0, 3.0});
etl::fast_vector<Z, 3> b;
b = timed(a + a);
auto text = buffer.str();
std::cout.rdbuf(old);
REQUIRE_DIRECT(starts_with(text, "timed(=): (V[3] + V[3]) took "));
REQUIRE_EQUALS(std::string(text.end() - 3, text.end() - 1), "ns");
REQUIRE_EQUALS(b[0], 2.0);
}
TEMPLATE_TEST_CASE_2("timed/2", "[dyn][serial]", Z, float, double) {
std::stringstream buffer;
auto* old = std::cout.rdbuf(buffer.rdbuf());
etl::dyn_vector<Z> a(10000);
etl::dyn_vector<Z> b(10000);
a = 1.0;
b = 0.0;
b = timed(a + b);
auto text = buffer.str();
std::cout.rdbuf(old);
REQUIRE_DIRECT(starts_with(text, "timed(=): (V[10000] + V[10000]) took "));
REQUIRE_EQUALS(std::string(text.end() - 3, text.end() - 1), "ns");
REQUIRE_EQUALS(b[0], 2.0);
}
TEMPLATE_TEST_CASE_2("timed/3", "[dyn][serial]", Z, float, double) {
std::stringstream buffer;
auto* old = std::cout.rdbuf(buffer.rdbuf());
etl::dyn_vector<Z> a(10000);
etl::dyn_vector<Z> b(10000);
a = 1.0;
b = etl::timed_res<etl::milliseconds>(a + a);
auto text = buffer.str();
std::cout.rdbuf(old);
REQUIRE_DIRECT(starts_with(text, "timed(=): (V[10000] + V[10000]) took "));
REQUIRE_EQUALS(std::string(text.end() - 3, text.end() - 1), "ms");
REQUIRE_EQUALS(b[0], 2.0);
}
<commit_msg>Fix the fixed test<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "test_light.hpp"
namespace {
bool starts_with(const std::string& str, const std::string& search) {
return std::mismatch(search.begin(), search.end(), str.begin()).first == search.end();
}
} //end of anonymous namespace
TEMPLATE_TEST_CASE_2("timed/1", "[fast][serial]", Z, float, double) {
std::stringstream buffer;
auto* old = std::cout.rdbuf(buffer.rdbuf());
etl::fast_vector<Z, 3> a({1.0, -2.0, 3.0});
etl::fast_vector<Z, 3> b;
b = timed(a + a);
auto text = buffer.str();
std::cout.rdbuf(old);
REQUIRE_DIRECT(starts_with(text, "timed(=): (V[3] + V[3]) took "));
REQUIRE_EQUALS(std::string(text.end() - 3, text.end() - 1), "ns");
REQUIRE_EQUALS(b[0], 2.0);
}
TEMPLATE_TEST_CASE_2("timed/2", "[dyn][serial]", Z, float, double) {
std::stringstream buffer;
auto* old = std::cout.rdbuf(buffer.rdbuf());
etl::dyn_vector<Z> a(10000);
etl::dyn_vector<Z> b(10000);
a = 1.0;
b = 2.0;
b = timed(a + b);
auto text = buffer.str();
std::cout.rdbuf(old);
REQUIRE_DIRECT(starts_with(text, "timed(=): (V[10000] + V[10000]) took "));
REQUIRE_EQUALS(std::string(text.end() - 3, text.end() - 1), "ns");
REQUIRE_EQUALS(b[0], 3.0);
}
TEMPLATE_TEST_CASE_2("timed/3", "[dyn][serial]", Z, float, double) {
std::stringstream buffer;
auto* old = std::cout.rdbuf(buffer.rdbuf());
etl::dyn_vector<Z> a(10000);
etl::dyn_vector<Z> b(10000);
a = 1.0;
b = etl::timed_res<etl::milliseconds>(a + a);
auto text = buffer.str();
std::cout.rdbuf(old);
REQUIRE_DIRECT(starts_with(text, "timed(=): (V[10000] + V[10000]) took "));
REQUIRE_EQUALS(std::string(text.end() - 3, text.end() - 1), "ms");
REQUIRE_EQUALS(b[0], 2.0);
}
<|endoftext|> |
<commit_before>/*
* test-uart.cpp
*
* Copyright (c) 2017 Lix N. Paulian (lix@paulian.net)
*
* 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.
*
* Created on: 16 Jun 2017 (LNP)
*/
#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/diag/trace.h>
#include <cmsis-plus/posix-io/file-descriptors-manager.h>
#include "uart-drv.h"
#include "io.h"
extern "C"
{
UART_HandleTypeDef huart6;
}
using namespace os;
using namespace os::rtos;
// Static manager
os::posix::file_descriptors_manager descriptors_manager
{ 8 };
#define TX_BUFFER_SIZE 200
#define RX_BUFFER_SIZE 200
#define TEST_ROUNDS 10
#define WRITE_READ_ROUNDS 10
uint8_t tx_buffer[TX_BUFFER_SIZE];
uint8_t rx_buffer[RX_BUFFER_SIZE];
static ssize_t
targeted_read (int filedes, char *buffer, size_t expected_size);
driver::uart uart6
{ "uart6", &huart6, nullptr, nullptr, TX_BUFFER_SIZE, RX_BUFFER_SIZE };
void
HAL_UART_TxCpltCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_tx_event ();
}
}
void
HAL_UART_RxCpltCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_rx_event (false);
}
}
void
HAL_UART_RxHalfCpltCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_rx_event (true);
}
}
void
HAL_UART_ErrorCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_rx_event (false);
}
}
/**
* @brief This is a test function that exercises the UART driver.
*/
void
test_uart (void)
{
int fd, count;
char text[] =
{ "The quick brown fox jumps over the lazy dog 1234567890\r\n" };
char text_end[] =
{ "---------\r\n" };
char buffer[100];
#ifdef M717
// configure the MPI interface
mpi_ctrl mpi
{};
/* set to RS232 */
mpi.init_pins ();
mpi.rs485 (false);
mpi.shutdown (false);
mpi.half_duplex (false);
#endif
for (int i = 0; i < TEST_ROUNDS; i++)
{
// open the serial device
if ((fd = open ("/dev/uart6", 0)) < 0)
{
trace::printf ("Error at open\n");
}
else
{
// get serial port parameters
struct termios tios;
if (uart6.do_tcgetattr (&tios) < 0)
{
trace::printf ("Error getting serial port parameters\n");
}
else
{
trace::printf (
"Serial port parameters: "
"%d baud, %d bits, %d stop bit(s), %s parity\r\n",
tios.c_ispeed,
(tios.c_cflag & CSIZE) == CS7 ? 7 :
(tios.c_cflag & CSIZE) == CS8 ? 8 : 9,
tios.c_cflag & CSTOPB ? 2 : 1,
tios.c_cflag & PARENB ?
tios.c_cflag & PARODD ? "odd" : "even" : "no");
}
for (int j = 0; j < WRITE_READ_ROUNDS; j++)
{
// send text
if ((count = write (fd, text, strlen (text))) < 0)
{
trace::printf ("Error at write (%d)\n", j);
break;
}
// read text
count = targeted_read (fd, buffer, strlen (text));
if (count > 0)
{
buffer[count] = '\0';
trace::printf ("%s", buffer);
}
else
{
trace::printf ("Error reading data\n");
}
}
// send separating dashes
if ((count = write (fd, text_end, strlen (text_end))) < 0)
{
trace::printf ("Error at write end text\n");
break;
}
// read separating dashes
count = targeted_read (fd, buffer, strlen (text_end));
if (count > 0)
{
buffer[count] = '\0';
trace::printf ("%s", buffer);
}
else
{
trace::printf ("Error reading separator\n");
}
// close the serial device
if ((close (fd)) < 0)
{
trace::printf ("Error at close\n");
break;
}
}
}
}
/**
* @brief This function waits to read a known amount of bytes before returning.
* @param fd: file descriptor.
* @param buffer: buffer to return data into.
* @param expected_size: the expected number of characters to wait for.
* @return The number of characters read or an error if negative.
*/
static ssize_t
targeted_read (int fd, char *buffer, size_t expected_size)
{
int count, total = 0;
do
{
if ((count = read (fd, buffer + total, expected_size - total)) < 0)
{
break;
}
total += count;
}
while (total < (int) expected_size);
return total;
}
<commit_msg>Show handshake state<commit_after>/*
* test-uart.cpp
*
* Copyright (c) 2017 Lix N. Paulian (lix@paulian.net)
*
* 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.
*
* Created on: 16 Jun 2017 (LNP)
*/
#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/diag/trace.h>
#include <cmsis-plus/posix-io/file-descriptors-manager.h>
#include "uart-drv.h"
#include "io.h"
extern "C"
{
UART_HandleTypeDef huart6;
}
using namespace os;
using namespace os::rtos;
// Static manager
os::posix::file_descriptors_manager descriptors_manager
{ 8 };
#define TX_BUFFER_SIZE 200
#define RX_BUFFER_SIZE 200
#define TEST_ROUNDS 10
#define WRITE_READ_ROUNDS 10
uint8_t tx_buffer[TX_BUFFER_SIZE];
uint8_t rx_buffer[RX_BUFFER_SIZE];
static ssize_t
targeted_read (int filedes, char *buffer, size_t expected_size);
driver::uart uart6
{ "uart6", &huart6, nullptr, nullptr, TX_BUFFER_SIZE, RX_BUFFER_SIZE };
void
HAL_UART_TxCpltCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_tx_event ();
}
}
void
HAL_UART_RxCpltCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_rx_event (false);
}
}
void
HAL_UART_RxHalfCpltCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_rx_event (true);
}
}
void
HAL_UART_ErrorCallback (UART_HandleTypeDef *huart)
{
if (huart->Instance == huart6.Instance)
{
uart6.cb_rx_event (false);
}
}
/**
* @brief This is a test function that exercises the UART driver.
*/
void
test_uart (void)
{
int fd, count;
char text[] =
{ "The quick brown fox jumps over the lazy dog 1234567890\r\n" };
char text_end[] =
{ "---------\r\n" };
char buffer[100];
#ifdef M717
// configure the MPI interface
mpi_ctrl mpi
{ };
/* set to RS232 */
mpi.init_pins ();
mpi.rs485 (false);
mpi.shutdown (false);
mpi.half_duplex (false);
#endif
for (int i = 0; i < TEST_ROUNDS; i++)
{
// open the serial device
if ((fd = open ("/dev/uart6", 0)) < 0)
{
trace::printf ("Error at open\n");
}
else
{
// get serial port parameters
struct termios tios;
if (uart6.do_tcgetattr (&tios) < 0)
{
trace::printf ("Error getting serial port parameters\n");
}
else
{
trace::printf (
"Serial port parameters: "
"%d baud, %d bits, %d stop bit(s), %s parity, flow control %s\r\n",
tios.c_ispeed,
(tios.c_cflag & CSIZE) == CS7 ? 7 :
(tios.c_cflag & CSIZE) == CS8 ? 8 : 9,
tios.c_cflag & CSTOPB ? 2 : 1,
tios.c_cflag & PARENB ?
tios.c_cflag & PARODD ? "odd" : "even" : "no",
(tios.c_cflag & CRTSCTS) == CRTSCTS ? "RTS/CTS" :
(tios.c_cflag & CRTSCTS) == CCTS_OFLOW ? "CTS" :
(tios.c_cflag & CRTSCTS) == CRTS_IFLOW ? "RTS" : "none");
}
for (int j = 0; j < WRITE_READ_ROUNDS; j++)
{
// send text
if ((count = write (fd, text, strlen (text))) < 0)
{
trace::printf ("Error at write (%d)\n", j);
break;
}
// read text
count = targeted_read (fd, buffer, strlen (text));
if (count > 0)
{
buffer[count] = '\0';
trace::printf ("%s", buffer);
}
else
{
trace::printf ("Error reading data\n");
}
}
// send separating dashes
if ((count = write (fd, text_end, strlen (text_end))) < 0)
{
trace::printf ("Error at write end text\n");
break;
}
// read separating dashes
count = targeted_read (fd, buffer, strlen (text_end));
if (count > 0)
{
buffer[count] = '\0';
trace::printf ("%s", buffer);
}
else
{
trace::printf ("Error reading separator\n");
}
// close the serial device
if ((close (fd)) < 0)
{
trace::printf ("Error at close\n");
break;
}
}
}
}
/**
* @brief This function waits to read a known amount of bytes before returning.
* @param fd: file descriptor.
* @param buffer: buffer to return data into.
* @param expected_size: the expected number of characters to wait for.
* @return The number of characters read or an error if negative.
*/
static ssize_t
targeted_read (int fd, char *buffer, size_t expected_size)
{
int count, total = 0;
do
{
if ((count = read (fd, buffer + total, expected_size - total)) < 0)
{
break;
}
total += count;
}
while (total < (int) expected_size);
return total;
}
<|endoftext|> |
<commit_before>#include <map>
#include <string>
#include "memdb/schema.h"
#include "base/all.h"
using namespace base;
using namespace mdb;
using namespace std;
TEST(value, types) {
Value v;
EXPECT_EQ(v.get_kind(), Value::UNKNOWN);
v.set_i32(1987);
EXPECT_EQ(v.get_kind(), Value::I32);
EXPECT_EQ(v.get_i32(), 1987);
EXPECT_LT(Value(43), Value(48));
EXPECT_LT(Value(43000000LL), Value(48000000LL));
EXPECT_EQ(Value(43000000LL).get_kind(), Value::I64);
EXPECT_EQ(Value(43000000LL).get_i64(), 43000000LL);
EXPECT_EQ(Value("hi").get_str(), "hi");
EXPECT_EQ(Value(), Value());
}
TEST(value, insert_into_map) {
map<string, Value> row;
insert_into_map(row, string("id"), Value(2));
row["name"] = Value("alice");
// check for overwriting, use valgrind to detect memory leak
row["name"] = Value("bob");
}
<commit_msg>minor fix on 64bit linux<commit_after>#include <map>
#include <string>
#include "memdb/schema.h"
#include "base/all.h"
using namespace base;
using namespace mdb;
using namespace std;
TEST(value, types) {
Value v;
EXPECT_EQ(v.get_kind(), Value::UNKNOWN);
v.set_i32(1987);
EXPECT_EQ(v.get_kind(), Value::I32);
EXPECT_EQ(v.get_i32(), 1987);
EXPECT_LT(Value(43), Value(48));
EXPECT_LT(Value((i64) 43000000), Value((i64) 48000000));
EXPECT_EQ(Value((i64) 43000000).get_kind(), Value::I64);
EXPECT_EQ(Value((i64) 43000000).get_i64(), (i64) 43000000);
EXPECT_EQ(Value("hi").get_str(), "hi");
EXPECT_EQ(Value(), Value());
}
TEST(value, insert_into_map) {
map<string, Value> row;
insert_into_map(row, string("id"), Value(2));
row["name"] = Value("alice");
// check for overwriting, use valgrind to detect memory leak
row["name"] = Value("bob");
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "gtest/gtest.h"
#include "xtensor/xnpy.hpp"
#include "xtensor/xarray.hpp"
#include <fstream>
#include <cstdint>
namespace xt
{
TEST(xnpy, load)
{
xarray<double> darr = {{{ 0.29731723, 0.04380157, 0.94748308},
{ 0.85020643, 0.52958618, 0.0598172 },
{ 0.77253259, 0.47564231, 0.70274005}},
{{ 0.85998447, 0.61160158, 0.44432939},
{ 0.25506765, 0.97420976, 0.15455842},
{ 0.05873659, 0.66191764, 0.01448838}},
{{ 0.175919 , 0.13850365, 0.94059426},
{ 0.79941809, 0.5124432 , 0.51364796},
{ 0.25721979, 0.41608858, 0.06255319}}};
xarray<bool> barr = {{{ 0, 0, 1},
{ 1, 1, 0},
{ 1, 0, 1}},
{{ 1, 1, 0},
{ 0, 1, 0},
{ 0, 1, 0}},
{{ 0, 0, 1},
{ 1, 1, 1},
{ 0, 0, 0}}};
xarray<int> iarr1d = {3, 4, 5, 6, 7};
auto darr_loaded = load_npy<double>("files/xnpy_files/double.npy");
EXPECT_TRUE(all(isclose(darr, darr_loaded)));
std::ifstream dstream("files/xnpy_files/double.npy");
auto darr_loaded_stream = load_npy<double>(dstream);
EXPECT_TRUE(all(isclose(darr, darr_loaded_stream)))
<< "Loading double numpy array from stream failed";
dstream.close();
auto barr_loaded = load_npy<bool>("files/xnpy_files/bool.npy");
EXPECT_TRUE(all(equal(barr, barr_loaded)));
std::ifstream bstream("files/xnpy_files/bool.npy");
auto barr_loaded_stream = load_npy<bool>(bstream);
EXPECT_TRUE(all(isclose(barr, barr_loaded_stream)))
<< "Loading boolean numpy array from stream failed";
bstream.close();
auto dfarr_loaded = load_npy<double, layout_type::column_major>("files/xnpy_files/double_fortran.npy");
EXPECT_TRUE(all(isclose(darr, dfarr_loaded)));
auto iarr1d_loaded = load_npy<int>("files/xnpy_files/int.npy");
EXPECT_TRUE(all(equal(iarr1d, iarr1d_loaded)));
}
bool compare_binary_files(std::string fn1, std::string fn2)
{
std::ifstream stream1(fn1, std::ios::in | std::ios::binary);
std::vector<uint8_t> fn1_contents((std::istreambuf_iterator<char>(stream1)),
std::istreambuf_iterator<char>());
std::ifstream stream2(fn2, std::ios::in | std::ios::binary);
std::vector<uint8_t> fn2_contents((std::istreambuf_iterator<char>(stream2)),
std::istreambuf_iterator<char>());
return std::equal(fn1_contents.begin(), fn1_contents.end(), fn2_contents.begin()) &&
fn1_contents.size() == fn2_contents.size();
}
std::string get_filename(int n)
{
std::string filename = "files/xnpy_files/test_dump_" + std::to_string(n) + ".npy";
return filename;
}
std::string read_file(const std::string& name)
{
return (std::stringstream() << std::ifstream(name).rdbuf()).str();
}
TEST(xnpy, dump)
{
std::string filename = get_filename(0);
xarray<bool> barr = {{{0, 0, 1},
{1, 1, 0},
{1, 0, 1}},
{{1, 1, 0},
{0, 1, 0},
{0, 1, 0}},
{{0, 0, 1},
{1, 1, 1},
{0, 0, 0}}};
xtensor<uint64_t, 1> ularr = {12ul, 14ul, 16ul, 18ul, 1234321ul};
dump_npy(filename, barr);
std::string compare_name = "files/xnpy_files/bool.npy";
if (barr.layout() == layout_type::column_major)
{
compare_name = "files/xnpy_files/bool_fortran.npy";
}
EXPECT_TRUE(compare_binary_files(filename, compare_name));
std::string barr_str = dump_npy(barr);
std::string barr_disk = read_file(compare_name);
EXPECT_EQ(barr_str, barr_disk) << "Dumping boolean numpy file to string failed";
std::remove(filename.c_str());
filename = get_filename(1);
dump_npy(filename, ularr);
auto ularrcpy = load_npy<uint64_t>(filename);
EXPECT_TRUE(all(equal(ularr, ularrcpy)));
compare_name = "files/xnpy_files/unsignedlong.npy";
if (barr.layout() == layout_type::column_major)
{
compare_name = "files/xnpy_files/unsignedlong_fortran.npy";
}
EXPECT_TRUE(compare_binary_files(filename, compare_name));
std::string ularr_str = dump_npy(ularr);
std::string ularr_disk = read_file(compare_name);
EXPECT_EQ(ularr_str, ularr_disk) << "Dumping boolean numpy file to string failed";
std::remove(filename.c_str());
}
TEST(xnpy, xfunction_cast)
{
// compilation test, cf: https://github.com/QuantStack/xtensor/issues/1070
auto dc = cast<char>(load_npy<double>("files/xnpy_files/double.npy"));
EXPECT_EQ(dc(0, 0), 0);
xarray<char> adc = dc;
EXPECT_EQ(adc(0, 0), 0);
}
}
<commit_msg>Updates implementation of tests to satisfy tests on CI under VS<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "gtest/gtest.h"
#include "xtensor/xnpy.hpp"
#include "xtensor/xarray.hpp"
#include <fstream>
#include <cstdint>
namespace xt
{
TEST(xnpy, load)
{
xarray<double> darr = {{{ 0.29731723, 0.04380157, 0.94748308},
{ 0.85020643, 0.52958618, 0.0598172 },
{ 0.77253259, 0.47564231, 0.70274005}},
{{ 0.85998447, 0.61160158, 0.44432939},
{ 0.25506765, 0.97420976, 0.15455842},
{ 0.05873659, 0.66191764, 0.01448838}},
{{ 0.175919 , 0.13850365, 0.94059426},
{ 0.79941809, 0.5124432 , 0.51364796},
{ 0.25721979, 0.41608858, 0.06255319}}};
xarray<bool> barr = {{{ 0, 0, 1},
{ 1, 1, 0},
{ 1, 0, 1}},
{{ 1, 1, 0},
{ 0, 1, 0},
{ 0, 1, 0}},
{{ 0, 0, 1},
{ 1, 1, 1},
{ 0, 0, 0}}};
xarray<int> iarr1d = {3, 4, 5, 6, 7};
auto darr_loaded = load_npy<double>("files/xnpy_files/double.npy");
EXPECT_TRUE(all(isclose(darr, darr_loaded)));
std::ifstream dstream("files/xnpy_files/double.npy");
auto darr_loaded_stream = load_npy<double>(dstream);
EXPECT_TRUE(all(isclose(darr, darr_loaded_stream)))
<< "Loading double numpy array from stream failed";
dstream.close();
auto barr_loaded = load_npy<bool>("files/xnpy_files/bool.npy");
EXPECT_TRUE(all(equal(barr, barr_loaded)));
std::ifstream bstream("files/xnpy_files/bool.npy");
auto barr_loaded_stream = load_npy<bool>(bstream);
EXPECT_TRUE(all(equal(barr, barr_loaded_stream)))
<< "Loading boolean numpy array from stream failed";
bstream.close();
auto dfarr_loaded = load_npy<double, layout_type::column_major>("files/xnpy_files/double_fortran.npy");
EXPECT_TRUE(all(isclose(darr, dfarr_loaded)));
auto iarr1d_loaded = load_npy<int>("files/xnpy_files/int.npy");
EXPECT_TRUE(all(equal(iarr1d, iarr1d_loaded)));
}
bool compare_binary_files(std::string fn1, std::string fn2)
{
std::ifstream stream1(fn1, std::ios::in | std::ios::binary);
std::vector<uint8_t> fn1_contents((std::istreambuf_iterator<char>(stream1)),
std::istreambuf_iterator<char>());
std::ifstream stream2(fn2, std::ios::in | std::ios::binary);
std::vector<uint8_t> fn2_contents((std::istreambuf_iterator<char>(stream2)),
std::istreambuf_iterator<char>());
return std::equal(fn1_contents.begin(), fn1_contents.end(), fn2_contents.begin()) &&
fn1_contents.size() == fn2_contents.size();
}
std::string get_filename(int n)
{
std::string filename = "files/xnpy_files/test_dump_" + std::to_string(n) + ".npy";
return filename;
}
std::string read_file(const std::string& name)
{
return static_cast<std::stringstream const&>(std::stringstream() << std::ifstream(name).rdbuf()).str();
}
TEST(xnpy, dump)
{
std::string filename = get_filename(0);
xarray<bool> barr = {{{0, 0, 1},
{1, 1, 0},
{1, 0, 1}},
{{1, 1, 0},
{0, 1, 0},
{0, 1, 0}},
{{0, 0, 1},
{1, 1, 1},
{0, 0, 0}}};
xtensor<uint64_t, 1> ularr = {12ul, 14ul, 16ul, 18ul, 1234321ul};
dump_npy(filename, barr);
std::string compare_name = "files/xnpy_files/bool.npy";
if (barr.layout() == layout_type::column_major)
{
compare_name = "files/xnpy_files/bool_fortran.npy";
}
EXPECT_TRUE(compare_binary_files(filename, compare_name));
std::string barr_str = dump_npy(barr);
std::string barr_disk = read_file(compare_name);
EXPECT_EQ(barr_str, barr_disk) << "Dumping boolean numpy file to string failed";
std::remove(filename.c_str());
filename = get_filename(1);
dump_npy(filename, ularr);
auto ularrcpy = load_npy<uint64_t>(filename);
EXPECT_TRUE(all(equal(ularr, ularrcpy)));
compare_name = "files/xnpy_files/unsignedlong.npy";
if (barr.layout() == layout_type::column_major)
{
compare_name = "files/xnpy_files/unsignedlong_fortran.npy";
}
EXPECT_TRUE(compare_binary_files(filename, compare_name));
std::string ularr_str = dump_npy(ularr);
std::string ularr_disk = read_file(compare_name);
EXPECT_EQ(ularr_str, ularr_disk) << "Dumping boolean numpy file to string failed";
std::remove(filename.c_str());
}
TEST(xnpy, xfunction_cast)
{
// compilation test, cf: https://github.com/QuantStack/xtensor/issues/1070
auto dc = cast<char>(load_npy<double>("files/xnpy_files/double.npy"));
EXPECT_EQ(dc(0, 0), 0);
xarray<char> adc = dc;
EXPECT_EQ(adc(0, 0), 0);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_ANDROID)
#include "bin/socket.h"
#include <errno.h> // NOLINT
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
namespace dart {
namespace bin {
Socket::Socket(intptr_t fd)
: ReferenceCounted(),
fd_(fd),
isolate_port_(Dart_GetMainPortId()),
port_(ILLEGAL_PORT),
udp_receive_buffer_(NULL) {}
void Socket::SetClosedFd() {
fd_ = kClosedFd;
}
static intptr_t Create(const RawAddr& addr) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.ss.ss_family, SOCK_STREAM, 0));
if (fd < 0) {
return -1;
}
if (!FDUtils::SetCloseOnExec(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return fd;
}
static intptr_t Connect(intptr_t fd, const RawAddr& addr) {
intptr_t result = TEMP_FAILURE_RETRY(
connect(fd, &addr.addr, SocketAddress::GetAddrLength(addr)));
if ((result == 0) || (errno == EINPROGRESS)) {
return fd;
}
FDUtils::SaveErrorAndClose(fd);
return -1;
}
intptr_t Socket::CreateConnect(const RawAddr& addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
}
if (!FDUtils::SetNonBlocking(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return Connect(fd, addr);
}
intptr_t Socket::CreateBindConnect(const RawAddr& addr,
const RawAddr& source_addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
}
intptr_t result = TEMP_FAILURE_RETRY(
bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(source_addr)));
if ((result != 0) && (errno != EINPROGRESS)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return Connect(fd, addr);
}
intptr_t Socket::CreateBindDatagram(const RawAddr& addr,
bool reuseAddress,
bool reusePort,
int ttl) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.addr.sa_family, SOCK_DGRAM, IPPROTO_UDP));
if (fd < 0) {
return -1;
}
if (!FDUtils::SetCloseOnExec(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
if (reuseAddress) {
int optval = 1;
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
}
if (reusePort) {
// ignore reusePort - not supported on this platform.
Log::PrintErr(
"Dart Socket ERROR: %s:%d: `reusePort` not supported for "
"Android." __FILE__,
__LINE__);
}
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)));
if (NO_RETRY_EXPECTED(
bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
if (!FDUtils::SetNonBlocking(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return fd;
}
intptr_t ServerSocket::CreateBindListen(const RawAddr& addr,
intptr_t backlog,
bool v6_only) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.ss.ss_family, SOCK_STREAM, 0));
if (fd < 0) {
return -1;
}
if (!FDUtils::SetCloseOnExec(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
int optval = 1;
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
if (addr.ss.ss_family == AF_INET6) {
optval = v6_only ? 1 : 0;
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)));
}
if (NO_RETRY_EXPECTED(
bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
// Test for invalid socket port 65535 (some browsers disallow it).
if ((SocketAddress::GetAddrPort(addr)) == 0 &&
(SocketBase::GetPort(fd) == 65535)) {
// Don't close the socket until we have created a new socket, ensuring
// that we do not get the bad port number again.
intptr_t new_fd = CreateBindListen(addr, backlog, v6_only);
FDUtils::SaveErrorAndClose(fd);
return new_fd;
}
if (NO_RETRY_EXPECTED(listen(fd, backlog > 0 ? backlog : SOMAXCONN)) != 0) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
if (!FDUtils::SetNonBlocking(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return fd;
}
bool ServerSocket::StartAccept(intptr_t fd) {
USE(fd);
return true;
}
static bool IsTemporaryAcceptError(int error) {
// On Android a number of protocol errors should be treated as EAGAIN.
// These are the ones for TCP/IP.
return (error == EAGAIN) || (error == ENETDOWN) || (error == EPROTO) ||
(error == ENOPROTOOPT) || (error == EHOSTDOWN) || (error == ENONET) ||
(error == EHOSTUNREACH) || (error == EOPNOTSUPP) ||
(error == ENETUNREACH);
}
intptr_t ServerSocket::Accept(intptr_t fd) {
intptr_t socket;
struct sockaddr clientaddr;
socklen_t addrlen = sizeof(clientaddr);
socket = TEMP_FAILURE_RETRY(accept(fd, &clientaddr, &addrlen));
if (socket == -1) {
if (IsTemporaryAcceptError(errno)) {
// We need to signal to the caller that this is actually not an
// error. We got woken up from the poll on the listening socket,
// but there is no connection ready to be accepted.
ASSERT(kTemporaryFailure != -1);
socket = kTemporaryFailure;
}
} else {
if (!FDUtils::SetCloseOnExec(socket)) {
FDUtils::SaveErrorAndClose(socket);
return -1;
}
if (!FDUtils::SetNonBlocking(socket)) {
FDUtils::SaveErrorAndClose(socket);
return -1;
}
}
return socket;
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_ANDROID)
<commit_msg>missing include for android<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_ANDROID)
#include "bin/socket.h"
#include <errno.h> // NOLINT
#include "bin/fdutils.h"
#include "bin/log.h"
#include "platform/signal_blocker.h"
namespace dart {
namespace bin {
Socket::Socket(intptr_t fd)
: ReferenceCounted(),
fd_(fd),
isolate_port_(Dart_GetMainPortId()),
port_(ILLEGAL_PORT),
udp_receive_buffer_(NULL) {}
void Socket::SetClosedFd() {
fd_ = kClosedFd;
}
static intptr_t Create(const RawAddr& addr) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.ss.ss_family, SOCK_STREAM, 0));
if (fd < 0) {
return -1;
}
if (!FDUtils::SetCloseOnExec(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return fd;
}
static intptr_t Connect(intptr_t fd, const RawAddr& addr) {
intptr_t result = TEMP_FAILURE_RETRY(
connect(fd, &addr.addr, SocketAddress::GetAddrLength(addr)));
if ((result == 0) || (errno == EINPROGRESS)) {
return fd;
}
FDUtils::SaveErrorAndClose(fd);
return -1;
}
intptr_t Socket::CreateConnect(const RawAddr& addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
}
if (!FDUtils::SetNonBlocking(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return Connect(fd, addr);
}
intptr_t Socket::CreateBindConnect(const RawAddr& addr,
const RawAddr& source_addr) {
intptr_t fd = Create(addr);
if (fd < 0) {
return fd;
}
intptr_t result = TEMP_FAILURE_RETRY(
bind(fd, &source_addr.addr, SocketAddress::GetAddrLength(source_addr)));
if ((result != 0) && (errno != EINPROGRESS)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return Connect(fd, addr);
}
intptr_t Socket::CreateBindDatagram(const RawAddr& addr,
bool reuseAddress,
bool reusePort,
int ttl) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.addr.sa_family, SOCK_DGRAM, IPPROTO_UDP));
if (fd < 0) {
return -1;
}
if (!FDUtils::SetCloseOnExec(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
if (reuseAddress) {
int optval = 1;
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
}
if (reusePort) {
// ignore reusePort - not supported on this platform.
Log::PrintErr(
"Dart Socket ERROR: %s:%d: `reusePort` not supported for "
"Android." __FILE__,
__LINE__);
}
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)));
if (NO_RETRY_EXPECTED(
bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
if (!FDUtils::SetNonBlocking(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return fd;
}
intptr_t ServerSocket::CreateBindListen(const RawAddr& addr,
intptr_t backlog,
bool v6_only) {
intptr_t fd;
fd = NO_RETRY_EXPECTED(socket(addr.ss.ss_family, SOCK_STREAM, 0));
if (fd < 0) {
return -1;
}
if (!FDUtils::SetCloseOnExec(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
int optval = 1;
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
if (addr.ss.ss_family == AF_INET6) {
optval = v6_only ? 1 : 0;
VOID_NO_RETRY_EXPECTED(
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)));
}
if (NO_RETRY_EXPECTED(
bind(fd, &addr.addr, SocketAddress::GetAddrLength(addr))) < 0) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
// Test for invalid socket port 65535 (some browsers disallow it).
if ((SocketAddress::GetAddrPort(addr)) == 0 &&
(SocketBase::GetPort(fd) == 65535)) {
// Don't close the socket until we have created a new socket, ensuring
// that we do not get the bad port number again.
intptr_t new_fd = CreateBindListen(addr, backlog, v6_only);
FDUtils::SaveErrorAndClose(fd);
return new_fd;
}
if (NO_RETRY_EXPECTED(listen(fd, backlog > 0 ? backlog : SOMAXCONN)) != 0) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
if (!FDUtils::SetNonBlocking(fd)) {
FDUtils::SaveErrorAndClose(fd);
return -1;
}
return fd;
}
bool ServerSocket::StartAccept(intptr_t fd) {
USE(fd);
return true;
}
static bool IsTemporaryAcceptError(int error) {
// On Android a number of protocol errors should be treated as EAGAIN.
// These are the ones for TCP/IP.
return (error == EAGAIN) || (error == ENETDOWN) || (error == EPROTO) ||
(error == ENOPROTOOPT) || (error == EHOSTDOWN) || (error == ENONET) ||
(error == EHOSTUNREACH) || (error == EOPNOTSUPP) ||
(error == ENETUNREACH);
}
intptr_t ServerSocket::Accept(intptr_t fd) {
intptr_t socket;
struct sockaddr clientaddr;
socklen_t addrlen = sizeof(clientaddr);
socket = TEMP_FAILURE_RETRY(accept(fd, &clientaddr, &addrlen));
if (socket == -1) {
if (IsTemporaryAcceptError(errno)) {
// We need to signal to the caller that this is actually not an
// error. We got woken up from the poll on the listening socket,
// but there is no connection ready to be accepted.
ASSERT(kTemporaryFailure != -1);
socket = kTemporaryFailure;
}
} else {
if (!FDUtils::SetCloseOnExec(socket)) {
FDUtils::SaveErrorAndClose(socket);
return -1;
}
if (!FDUtils::SetNonBlocking(socket)) {
FDUtils::SaveErrorAndClose(socket);
return -1;
}
}
return socket;
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_ANDROID)
<|endoftext|> |
<commit_before>//! @Alan
//!
//! Exercise 11.3:
//! Write your own version of the word-counting program.
//!
//! Exercise 11.4:
//! Extend your program to ignore case and punctuation.
//! For example, “example.” “example,” and “Example” should
//! all increment the same counter.
//!
#include <iostream>
#include <map>
#include <string>
#include <cctype>
#include <algorithm>
void remove_punct(std::string &s)
{
auto iter = s.begin();
while(iter != s.end())
{
if(std::ispunct(*iter))
{
iter = s.erase(iter);
}
else
++ iter;
}
}
//! Exercise 11.4
void word_count_pro(std::map<std::string, int> &m)
{
std::string word;
while(std::cin >> word)
{
for(auto& ch : word) ch = std::tolower(ch);
remove_punct(word);
++m[word];
for (const auto &e : m)
std::cout << e.first << " : " << e.second <<"\n";
}
}
//! Exercise 11.3
void ex11_3()
{
std::map<std::string, std::size_t> word_count;
std::string word;
while(std::cin >> word)
{
++word_count[word];
for (const auto &elem : word_count)
std::cout << elem.first << " : " << elem.second <<"\n";
}
}
int main()
{
std::map<std::string, int> m;
word_count_pro(m);
return 0;
}
<commit_msg>fix bug<commit_after>//! @Alan
//!
//! Exercise 11.3:
//! Write your own version of the word-counting program.
//!
//! Exercise 11.4:
//! Extend your program to ignore case and punctuation.
//! For example, “example.” “example,” and “Example” should
//! all increment the same counter.
//!
#include <iostream>
#include <map>
#include <string>
#include <cctype>
#include <algorithm>
//! Exercise 11.4
void word_count_pro(std::map<std::string, int> &m)
{
std::string word;
while(std::cin >> word)
{
for(auto& ch : word) ch = std::tolower(ch);
//! Erase-remove idiom
//! http://en.wikipedia.org/wiki/Erase-remove_idiom
word.erase(std::remove_if(word.begin(), word.end(), ispunct), word.end());
++m[word];
for (const auto &e : m)
std::cout << e.first << " : " << e.second <<"\n";
}
}
//! Exercise 11.3
void ex11_3()
{
std::map<std::string, std::size_t> word_count;
std::string word;
while(std::cin >> word)
{
++word_count[word];
for (const auto &elem : word_count)
std::cout << elem.first << " : " << elem.second <<"\n";
}
}
int main()
{
std::map<std::string, int> m;
word_count_pro(m);
return 0;
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2015 University of Central Florida's Computer Software Engineering
Scalable & Secure Systems (CSE - S3) Lab
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 <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <fstream>
#include <iostream>
#include "connection.h"
#define MAXDATASIZE 100
/************************************************************************
* Temp struct holder for results
************************************************************************/
/** Used to hold result before parsing into objects **/
struct ResultHolder {
char metaDataPacket[MESSAGE_SIZE];
char resultPacket[MESSAGE_SIZE];
};
/*************************************************************************
* Private Helper Functions *
*************************************************************************/
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
/**
* Builds a network packet with the passed in parameters.
* This network packet is necessary to send data across sockets.
* @param type The type of command being passed.
* @param command The command being sent to the server
* @return a CommandPacket containing the information to be sent across the socket.
*/
CommandPacket buildPacket(CommandType type, std::string command) {
CommandPacket commandPacket;
// command needs to be made into char[]
strncpy(commandPacket.message, command.c_str(), sizeof(commandPacket.message));
commandPacket.message[sizeof(commandPacket.message) -1] = 0;
commandPacket.commandType = type;
commandPacket.terminator = THE_TERMINATOR;
return commandPacket;
}
/**
* Parses result packet and builds a vector of ResultRow s
* @param packet The result packet to parse
* @return a vector<ResultRow> containing the parsed data
*/
std::vector<libomdb::ResultRow> parseData(ResultPacket packet) {
std::vector<libomdb::ResultRow> rows;
// Each of the columns is 64bits, packet.resultSize is number of bytes
// 8 bits to a byte, so 8 bytes per column, therefore number of columns
// is packet.resultSize / 8
uint32_t rowSizeInBytes = packet.rowLen * 8;
uint32_t numberOfRows = (packet.resultSize / rowSizeInBytes);
uint64_t* dataPointer = &packet.data[0];
for (uint i = 0; i < numberOfRows; ++i) {
libomdb::ResultRow row;
for (uint j = 0; j < packet.rowLen; ++i) {
int64_t* col = new int64_t;
memcpy(col, dataPointer, 8); //Move the next 8 bytes into col
row.push_back(*col);
delete(col); // TODO: Do I need this?
dataPointer += 2; // Move pointer up 8 bytes. dataPointer++ moves 4 bytes?
}
rows.push_back(row);
}
return rows;
}
/**
* Parses a ResultMetaDataPacket and builds a list of MetaDataColumns which is
* the core of the ResultMetaData class.
* @param packet
* @return A vector<MetaDataColumn> describing a result set
*/
std::vector<libomdb::MetaDataColumn> parseMetaData(ResultMetaDataPacket packet) {
std::vector<libomdb::MetaDataColumn> metaDataColumns;
for (uint i = 0; i < packet.numColumns; ++i) {
libomdb::MetaDataColumn column;
column.label = std::string(packet.columns[i].name);
column.sqlType = packet.columns[i].type;
}
return metaDataColumns;
}
/**
* Parses a ResultHolder and builds a CommandResult from the contents
* @param result The ResultHolder to parse
* @return A CommandResult with parsed data
*/
libomdb::CommandResult parseCommandResult(ResultHolder result) {
//ResultMetaDataPacket metaDataPacket = DeserializeResultMetaDataPacket(result.metaDataPacket);
ResultPacket packet = DeserializeResultPacket(result.resultPacket);
libomdb::CommandResult commandResult;
commandResult.isSuccess = packet.status == ResultStatus::OK;
commandResult.numAffected = packet.resultSize; // TODO: Confirm with neil
return commandResult;
}
/**
* TODO: Add error checking
*/
libomdb::Result parseQueryResult(ResultHolder holder) {
ResultMetaDataPacket resultMetaDataPacket =
DeserializeResultMetaDataPacket(holder.metaDataPacket);
ResultPacket resultPacket = DeserializeResultPacket(holder.resultPacket);
// Build result object;
std::vector<libomdb::ResultRow> rows = parseData(resultPacket);
std::vector<libomdb::MetaDataColumn> metaDataColumns =
parseMetaData(resultMetaDataPacket);
libomdb::ResultMetaData metaData =
libomdb::ResultMetaData::buildResultMetaDataObject(metaDataColumns);
return libomdb::Result::buildResultObject(rows, metaData);
}
/**
* Sends message across the socket passed in
* @param message The message to send to the server
* @param socket The file descriptor of the listening socket
*/
ResultHolder sendMessage(CommandPacket packet, int socket) {
// Need to convert message to c string in order to send it.
char message[MESSAGE_SIZE];
memcpy(message, &packet, sizeof(packet));
std::cout << "Message being sent: " << message <<std::endl;
// const char* c_message = message.c_str();
std::cout << "Attempting to send message to socket" << socket << std::endl;
int bytes_sent = send(socket, message, sizeof message, 0);
std::cout<< "Bytes sent: " << bytes_sent << std::endl;
if (bytes_sent == -1) {
perror("send");
ResultHolder emptyHolder;
return emptyHolder;
}
// Wait for receipt of message;
/*
* Results will now come in this order:
* 1.) ResultMetaDataPacket
* 2.) ResultPacket
*
* Build a struct containing both and return it.
*/
ResultHolder holder;
int bytes_recieved = recv(socket, holder.metaDataPacket, sizeof(holder.metaDataPacket), 0);
std::cout << "Bytes relieved: " << bytes_recieved << std::endl;
if (bytes_recieved == -1) {
perror("recv");
ResultHolder emptyHolder;
return emptyHolder;
}
// Now receive result packet
bytes_recieved = recv(socket, holder.resultPacket, sizeof(holder.resultPacket), 0);
if (bytes_recieved == -1) {
perror("recv");
ResultHolder emptyHolder;
return emptyHolder;
}
return holder;
}
/*************************************************************************
* ConnectionMetaData Implementations *
*************************************************************************/
libomdb::ConnectionMetaData::ConnectionMetaData(std::string dbName, bool isValid)
:m_databaseName(dbName), m_isValid(isValid) {}
std::string libomdb::ConnectionMetaData::getDbName() {
return this->m_databaseName;
}
bool libomdb::ConnectionMetaData::isValid() {
return this->m_isValid;
}
/*************************************************************************
* Connection Implementations *
*************************************************************************/
libomdb::Connection libomdb::Connection::buildConnectionObj(uint16_t socket, char* buffer) {
ConnectionPacket packet = DeserializeConnectionPacket(buffer);
libomdb::ConnectionMetaData* connectionMetaData = new libomdb::ConnectionMetaData(packet.name, true);
return *new libomdb::Connection(socket, *connectionMetaData);
}
// TODO: Break up this monstrosity.
libomdb::Connection libomdb::Connection::connect(std::string hostname,
uint16_t port,
std::string db) {
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
// Convert hostname to c string
const char* connection_ip = hostname.c_str();
//Convert port to c string.
const char* port_string = std::to_string(port).c_str();
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(connection_ip, port_string,
&hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %d\n", rv);
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return errorConnection();
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return errorConnection();
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
return errorConnection();
}
buf[numbytes] = '\0';
printf("client: received '%s'\n",buf);
std::string dbConnectString = "k:"+db;
const char* dbString = dbConnectString.c_str();
// Sending the name of the database to the server.
int bytesSent = send(sockfd, dbString, dbConnectString.length(), 0);
if (bytesSent == -1) {
perror("send");
return errorConnection();
}
int bytesReceived = recv(sockfd, buf, MAXDATASIZE -1, 0);
if (bytesReceived == -1) {
perror("recv");
return errorConnection();
}
buf[bytesReceived] = '\0';
printf("client received response from server: %s\n", buf);
return libomdb::Connection::buildConnectionObj(sockfd, buf);
}
void libomdb::Connection::disconnect() {
close(this->m_socket_fd);
}
libomdb::CommandResult libomdb::Connection::executeCommand(std::string command) {
CommandPacket packet = buildPacket(CommandType::DB_COMMAND, command);
return parseCommandResult(sendMessage(packet, this->m_socket_fd));
}
libomdb::Result libomdb::Connection::executeQuery(std::string query) {
CommandPacket packet = buildPacket(CommandType::SQL_STATEMENT, query);
return parseQueryResult(sendMessage(packet, this->m_socket_fd));
}
libomdb::ConnectionMetaData libomdb::Connection::getMetaData() {
return this->m_metaData;
}
void libomdb::Connection::setMetaData(libomdb::ConnectionMetaData data) {
this->m_metaData = data;
}
libomdb::Connection::Connection(uint64_t socket_fd, ConnectionMetaData metaData)
:m_metaData(metaData), m_socket_fd(socket_fd) {}<commit_msg>Updated pointer arithmetic<commit_after>/*
The MIT License (MIT)
Copyright (c) 2015 University of Central Florida's Computer Software Engineering
Scalable & Secure Systems (CSE - S3) Lab
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 <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <fstream>
#include <iostream>
#include "connection.h"
#define MAXDATASIZE 100
/************************************************************************
* Temp struct holder for results
************************************************************************/
/** Used to hold result before parsing into objects **/
struct ResultHolder {
char metaDataPacket[MESSAGE_SIZE];
char resultPacket[MESSAGE_SIZE];
};
/*************************************************************************
* Private Helper Functions *
*************************************************************************/
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
/**
* Builds a network packet with the passed in parameters.
* This network packet is necessary to send data across sockets.
* @param type The type of command being passed.
* @param command The command being sent to the server
* @return a CommandPacket containing the information to be sent across the socket.
*/
CommandPacket buildPacket(CommandType type, std::string command) {
CommandPacket commandPacket;
// command needs to be made into char[]
strncpy(commandPacket.message, command.c_str(), sizeof(commandPacket.message));
commandPacket.message[sizeof(commandPacket.message) -1] = 0;
commandPacket.commandType = type;
commandPacket.terminator = THE_TERMINATOR;
return commandPacket;
}
/**
* Parses result packet and builds a vector of ResultRow s
* @param packet The result packet to parse
* @return a vector<ResultRow> containing the parsed data
*/
std::vector<libomdb::ResultRow> parseData(ResultPacket packet) {
std::vector<libomdb::ResultRow> rows;
// Each of the columns is 64bits, packet.resultSize is number of bytes
// 8 bits to a byte, so 8 bytes per column, therefore number of columns
// is packet.resultSize / 8
uint32_t rowSizeInBytes = packet.rowLen * 8;
uint32_t numberOfRows = (packet.resultSize / rowSizeInBytes);
uint64_t* dataPointer = &packet.data[0];
// data is char* so data[0] is 1 byte
// so dataPointer++ moves up only one byte
for (uint i = 0; i < numberOfRows; ++i) {
libomdb::ResultRow row;
for (uint j = 0; j < packet.rowLen; ++i) {
int64_t* col = new int64_t;
memcpy(col, dataPointer, 8); //Move the next 8 bytes into col
row.push_back(*col);
delete(col); // TODO: Do I need this?
dataPointer += 8; // Move pointer up 8 bytes. dataPointer++ moves 1 byte
}
rows.push_back(row);
}
return rows;
}
/**
* Parses a ResultMetaDataPacket and builds a list of MetaDataColumns which is
* the core of the ResultMetaData class.
* @param packet
* @return A vector<MetaDataColumn> describing a result set
*/
std::vector<libomdb::MetaDataColumn> parseMetaData(ResultMetaDataPacket packet) {
std::vector<libomdb::MetaDataColumn> metaDataColumns;
for (uint i = 0; i < packet.numColumns; ++i) {
libomdb::MetaDataColumn column;
column.label = std::string(packet.columns[i].name);
column.sqlType = packet.columns[i].type;
}
return metaDataColumns;
}
/**
* Parses a ResultHolder and builds a CommandResult from the contents
* @param result The ResultHolder to parse
* @return A CommandResult with parsed data
*/
libomdb::CommandResult parseCommandResult(ResultHolder result) {
//ResultMetaDataPacket metaDataPacket = DeserializeResultMetaDataPacket(result.metaDataPacket);
ResultPacket packet = DeserializeResultPacket(result.resultPacket);
libomdb::CommandResult commandResult;
commandResult.isSuccess = packet.status == ResultStatus::OK;
commandResult.numAffected = packet.resultSize; // TODO: Confirm with neil
return commandResult;
}
/**
* TODO: Add error checking
*/
libomdb::Result parseQueryResult(ResultHolder holder) {
ResultMetaDataPacket resultMetaDataPacket =
DeserializeResultMetaDataPacket(holder.metaDataPacket);
ResultPacket resultPacket = DeserializeResultPacket(holder.resultPacket);
// Build result object;
std::vector<libomdb::ResultRow> rows = parseData(resultPacket);
std::vector<libomdb::MetaDataColumn> metaDataColumns =
parseMetaData(resultMetaDataPacket);
libomdb::ResultMetaData metaData =
libomdb::ResultMetaData::buildResultMetaDataObject(metaDataColumns);
return libomdb::Result::buildResultObject(rows, metaData);
}
/**
* Sends message across the socket passed in
* @param message The message to send to the server
* @param socket The file descriptor of the listening socket
*/
ResultHolder sendMessage(CommandPacket packet, int socket) {
// Need to convert message to c string in order to send it.
char message[MESSAGE_SIZE];
memcpy(message, &packet, sizeof(packet));
std::cout << "Message being sent: " << message <<std::endl;
// const char* c_message = message.c_str();
std::cout << "Attempting to send message to socket" << socket << std::endl;
int bytes_sent = send(socket, message, sizeof message, 0);
std::cout<< "Bytes sent: " << bytes_sent << std::endl;
if (bytes_sent == -1) {
perror("send");
ResultHolder emptyHolder;
return emptyHolder;
}
// Wait for receipt of message;
/*
* Results will now come in this order:
* 1.) ResultMetaDataPacket
* 2.) ResultPacket
*
* Build a struct containing both and return it.
*/
ResultHolder holder;
int bytes_recieved = recv(socket, holder.metaDataPacket, sizeof(holder.metaDataPacket), 0);
std::cout << "Bytes relieved: " << bytes_recieved << std::endl;
if (bytes_recieved == -1) {
perror("recv");
ResultHolder emptyHolder;
return emptyHolder;
}
// Now receive result packet
bytes_recieved = recv(socket, holder.resultPacket, sizeof(holder.resultPacket), 0);
if (bytes_recieved == -1) {
perror("recv");
ResultHolder emptyHolder;
return emptyHolder;
}
return holder;
}
/*************************************************************************
* ConnectionMetaData Implementations *
*************************************************************************/
libomdb::ConnectionMetaData::ConnectionMetaData(std::string dbName, bool isValid)
:m_databaseName(dbName), m_isValid(isValid) {}
std::string libomdb::ConnectionMetaData::getDbName() {
return this->m_databaseName;
}
bool libomdb::ConnectionMetaData::isValid() {
return this->m_isValid;
}
/*************************************************************************
* Connection Implementations *
*************************************************************************/
libomdb::Connection libomdb::Connection::buildConnectionObj(uint16_t socket, char* buffer) {
ConnectionPacket packet = DeserializeConnectionPacket(buffer);
libomdb::ConnectionMetaData* connectionMetaData = new libomdb::ConnectionMetaData(packet.name, true);
return *new libomdb::Connection(socket, *connectionMetaData);
}
// TODO: Break up this monstrosity.
libomdb::Connection libomdb::Connection::connect(std::string hostname,
uint16_t port,
std::string db) {
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
// Convert hostname to c string
const char* connection_ip = hostname.c_str();
//Convert port to c string.
const char* port_string = std::to_string(port).c_str();
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(connection_ip, port_string,
&hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %d\n", rv);
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return errorConnection();
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return errorConnection();
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
return errorConnection();
}
buf[numbytes] = '\0';
printf("client: received '%s'\n",buf);
std::string dbConnectString = "k:"+db;
const char* dbString = dbConnectString.c_str();
// Sending the name of the database to the server.
int bytesSent = send(sockfd, dbString, dbConnectString.length(), 0);
if (bytesSent == -1) {
perror("send");
return errorConnection();
}
int bytesReceived = recv(sockfd, buf, MAXDATASIZE -1, 0);
if (bytesReceived == -1) {
perror("recv");
return errorConnection();
}
buf[bytesReceived] = '\0';
printf("client received response from server: %s\n", buf);
return libomdb::Connection::buildConnectionObj(sockfd, buf);
}
void libomdb::Connection::disconnect() {
close(this->m_socket_fd);
}
libomdb::CommandResult libomdb::Connection::executeCommand(std::string command) {
CommandPacket packet = buildPacket(CommandType::DB_COMMAND, command);
return parseCommandResult(sendMessage(packet, this->m_socket_fd));
}
libomdb::Result libomdb::Connection::executeQuery(std::string query) {
CommandPacket packet = buildPacket(CommandType::SQL_STATEMENT, query);
return parseQueryResult(sendMessage(packet, this->m_socket_fd));
}
libomdb::ConnectionMetaData libomdb::Connection::getMetaData() {
return this->m_metaData;
}
void libomdb::Connection::setMetaData(libomdb::ConnectionMetaData data) {
this->m_metaData = data;
}
libomdb::Connection::Connection(uint64_t socket_fd, ConnectionMetaData metaData)
:m_metaData(metaData), m_socket_fd(socket_fd) {}<|endoftext|> |
<commit_before>#include "ocu.h"
#include <cuda.h>
#include <nvrtc.h>
#ifdef __USE_CUDA__
ocu_args_d_t& getOcu(void)
{
static bool bInit = false;
static ocu_args_d_t ocu;
if (bInit == true) return ocu;
bInit = true;
CUresult err = cuInit(0);
LOG_CU_RESULT(err);
CUdevice dev = 0;
CUcontext ctxt;
CUstream stream;
err = cuCtxCreate(&ctxt, CU_CTX_SCHED_BLOCKING_SYNC, dev);
LOG_CU_RESULT(err);
char name[1024];
int proc_count = 0;
int thread_count = 0;
int cap_major = 0, cap_minor = 0;
cuDeviceGetName(name, sizeof(name), dev);
cuDeviceGetAttribute(&cap_major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev);
cuDeviceGetAttribute(&cap_minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev);
cuDeviceGetAttribute(&proc_count, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, dev);
cuDeviceGetAttribute(&thread_count, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, dev);
LogError("CUDA Adapter:%s Ver%d.%d MP %d Core %d)\r\n", name, cap_major, cap_minor, proc_count, thread_count);
/*
char* source = nullptr;
size_t src_size = 0;
ReadSourceFromFile("clguetzli/clguetzli.cl", &source, &src_size);
nvrtcProgram prog;
const char *opts[] = { "-arch=compute_30", "-default-device", "-G", "-I\"./\"", "--fmad=false" };
nvrtcCreateProgram(&prog, source, "clguetzli.cl", 0, NULL, NULL);
nvrtcResult compile_result;// = nvrtcCompileProgram(prog, 3, opts);
if (NVRTC_SUCCESS != compile_result)
{
// Obtain compilation log from the program.
size_t logSize = 0;
nvrtcGetProgramLogSize(prog, &logSize);
char *log = new char[logSize];
nvrtcGetProgramLog(prog, log);
LogError("BuildInfo:\r\n%s\r\n", log);
delete[] log;
}
delete[] source;
// Obtain PTX from the program.
size_t ptxSize = 0;
nvrtcGetPTXSize(prog, &ptxSize);
char *ptx = new char[ptxSize];
nvrtcGetPTX(prog, ptx);
*/
char* ptx = nullptr;
size_t src_size = 0;
#ifdef _WIN64
ReadSourceFromFile("clguetzli/clguetzli.cu.ptx64", &ptx, &src_size);
#else
ReadSourceFromFile("clguetzli/clguetzli.cu.ptx32", &ptx, &src_size);
#endif
CUmodule mod;
CUjit_option jit_options[2];
void *jit_optvals[2];
jit_options[0] = CU_JIT_CACHE_MODE;
jit_optvals[0] = (void*)(uintptr_t)CU_JIT_CACHE_OPTION_CA;
err = cuModuleLoadDataEx(&mod, ptx, 1, jit_options, jit_optvals);
LOG_CU_RESULT(err);
delete[] ptx;
cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTION], mod, "clConvolutionEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONX], mod, "clConvolutionXEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONY], mod, "clConvolutionYEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_SQUARESAMPLE], mod, "clSquareSampleEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_OPSINDYNAMICSIMAGE], mod, "clOpsinDynamicsImageEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_MASKHIGHINTENSITYCHANGE], mod, "clMaskHighIntensityChangeEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTOR], mod, "clEdgeDetectorMapEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_BLOCKDIFFMAP], mod, "clBlockDiffMapEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTORLOWFREQ], mod, "clEdgeDetectorLowFreqEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_DIFFPRECOMPUTE], mod, "clDiffPrecomputeEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_SCALEIMAGE], mod, "clScaleImageEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_AVERAGE5X5], mod, "clAverage5x5Ex");
cuModuleGetFunction(&ocu.kernel[KERNEL_MINSQUAREVAL], mod, "clMinSquareValEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_DOMASK], mod, "clDoMaskEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_COMBINECHANNELS], mod, "clCombineChannelsEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_UPSAMPLESQUAREROOT], mod, "clUpsampleSquareRootEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_REMOVEBORDER], mod, "clRemoveBorderEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_ADDBORDER], mod, "clAddBorderEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_COMPUTEBLOCKZEROINGORDER], mod, "clComputeBlockZeroingOrderEx");
cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_SHARED);
cuCtxSetSharedMemConfig(CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE);
cuStreamCreate(&stream, 0);
ocu.dev = dev;
ocu.commandQueue = stream;
ocu.mod = mod;
ocu.ctxt = ctxt;
return ocu;
}
ocu_args_d_t::ocu_args_d_t()
: dev(0)
, commandQueue(NULL)
, mod(NULL)
, ctxt(NULL)
{
}
ocu_args_d_t::~ocu_args_d_t()
{
cuModuleUnload(mod);
cuCtxDestroy(ctxt);
// cuStreamDestroy(commandQueue);
}
cu_mem ocu_args_d_t::allocMem(size_t s, const void *init)
{
cu_mem mem;
cuMemAlloc(&mem, s);
if (init)
{
cuMemcpyHtoDAsync(mem, init, s, commandQueue);
}
else
{
cuMemsetD8Async(mem, 0, s, commandQueue);
}
return mem;
}
ocu_channels ocu_args_d_t::allocMemChannels(size_t s, const void *c0, const void *c1, const void *c2)
{
const void *c[3] = { c0, c1, c2 };
ocu_channels img;
for (int i = 0; i < 3; i++)
{
img.ch[i] = allocMem(s, c[i]);
}
return img;
}
void ocu_args_d_t::releaseMemChannels(ocu_channels &rgb)
{
for (int i = 0; i < 3; i++)
{
cuMemFree(rgb.ch[i]);
rgb.ch[i] = NULL;
}
}
const char* TranslateCUDAError(CUresult errorCode)
{
switch (errorCode)
{
case CUDA_SUCCESS: return "CUDA_SUCCESS";
case CUDA_ERROR_INVALID_VALUE: return "CUDA_ERROR_INVALID_VALUE";
case CUDA_ERROR_OUT_OF_MEMORY: return "CUDA_ERROR_OUT_OF_MEMORY";
case CUDA_ERROR_NOT_INITIALIZED: return "CUDA_ERROR_NOT_INITIALIZED";
case CUDA_ERROR_DEINITIALIZED: return "CUDA_ERROR_DEINITIALIZED";
case CUDA_ERROR_PROFILER_DISABLED: return "CUDA_ERROR_PROFILER_DISABLED";
case CUDA_ERROR_PROFILER_NOT_INITIALIZED: return "CUDA_ERROR_PROFILER_NOT_INITIALIZED";
case CUDA_ERROR_PROFILER_ALREADY_STARTED: return "CUDA_ERROR_PROFILER_ALREADY_STARTED";
case CUDA_ERROR_PROFILER_ALREADY_STOPPED: return "CUDA_ERROR_PROFILER_ALREADY_STOPPED";
case CUDA_ERROR_NO_DEVICE: return "CUDA_ERROR_NO_DEVICE";
case CUDA_ERROR_INVALID_DEVICE: return "CUDA_ERROR_INVALID_DEVICE";
case CUDA_ERROR_INVALID_IMAGE: return "CUDA_ERROR_INVALID_IMAGE";
case CUDA_ERROR_INVALID_CONTEXT: return "CUDA_ERROR_INVALID_CONTEXT";
case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "CUDA_ERROR_CONTEXT_ALREADY_CURRENT";
case CUDA_ERROR_MAP_FAILED: return "CUDA_ERROR_MAP_FAILED";
case CUDA_ERROR_UNMAP_FAILED: return "CUDA_ERROR_UNMAP_FAILED";
case CUDA_ERROR_ARRAY_IS_MAPPED: return "CUDA_ERROR_ARRAY_IS_MAPPED";
case CUDA_ERROR_ALREADY_MAPPED: return "CUDA_ERROR_ALREADY_MAPPED";
case CUDA_ERROR_NO_BINARY_FOR_GPU: return "CUDA_ERROR_NO_BINARY_FOR_GPU";
case CUDA_ERROR_ALREADY_ACQUIRED: return "CUDA_ERROR_ALREADY_ACQUIRED";
case CUDA_ERROR_NOT_MAPPED: return "CUDA_ERROR_NOT_MAPPED";
case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "CUDA_ERROR_NOT_MAPPED_AS_ARRAY";
case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "CUDA_ERROR_NOT_MAPPED_AS_POINTER";
case CUDA_ERROR_ECC_UNCORRECTABLE: return "CUDA_ERROR_ECC_UNCORRECTABLE";
case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUDA_ERROR_UNSUPPORTED_LIMIT";
case CUDA_ERROR_CONTEXT_ALREADY_IN_USE: return "CUDA_ERROR_CONTEXT_ALREADY_IN_USE";
case CUDA_ERROR_PEER_ACCESS_UNSUPPORTED: return "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED";
case CUDA_ERROR_INVALID_PTX: return "CUDA_ERROR_INVALID_PTX";
case CUDA_ERROR_INVALID_GRAPHICS_CONTEXT: return "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT";
case CUDA_ERROR_NVLINK_UNCORRECTABLE: return "CUDA_ERROR_NVLINK_UNCORRECTABLE";
case CUDA_ERROR_INVALID_SOURCE: return "CUDA_ERROR_INVALID_SOURCE";
case CUDA_ERROR_FILE_NOT_FOUND: return "CUDA_ERROR_FILE_NOT_FOUND";
case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND";
case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED";
case CUDA_ERROR_OPERATING_SYSTEM: return "CUDA_ERROR_OPERATING_SYSTEM";
case CUDA_ERROR_INVALID_HANDLE: return "CUDA_ERROR_INVALID_HANDLE";
case CUDA_ERROR_NOT_FOUND: return "CUDA_ERROR_NOT_FOUND";
case CUDA_ERROR_NOT_READY: return "CUDA_ERROR_NOT_READY";
case CUDA_ERROR_ILLEGAL_ADDRESS: return "CUDA_ERROR_ILLEGAL_ADDRESS";
case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES";
case CUDA_ERROR_LAUNCH_TIMEOUT: return "CUDA_ERROR_LAUNCH_TIMEOUT";
case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING";
case CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED: return "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED";
case CUDA_ERROR_PEER_ACCESS_NOT_ENABLED: return "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED";
case CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE: return "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE";
case CUDA_ERROR_CONTEXT_IS_DESTROYED: return "CUDA_ERROR_CONTEXT_IS_DESTROYED";
case CUDA_ERROR_ASSERT: return "CUDA_ERROR_ASSERT";
case CUDA_ERROR_TOO_MANY_PEERS: return "CUDA_ERROR_TOO_MANY_PEERS";
case CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED";
case CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED";
case CUDA_ERROR_HARDWARE_STACK_ERROR: return "CUDA_ERROR_HARDWARE_STACK_ERROR";
case CUDA_ERROR_ILLEGAL_INSTRUCTION: return "CUDA_ERROR_ILLEGAL_INSTRUCTION";
case CUDA_ERROR_MISALIGNED_ADDRESS: return "CUDA_ERROR_MISALIGNED_ADDRESS";
case CUDA_ERROR_INVALID_ADDRESS_SPACE: return "CUDA_ERROR_INVALID_ADDRESS_SPACE";
case CUDA_ERROR_INVALID_PC: return "CUDA_ERROR_INVALID_PC";
case CUDA_ERROR_LAUNCH_FAILED: return "CUDA_ERROR_LAUNCH_FAILED";
case CUDA_ERROR_NOT_PERMITTED: return "CUDA_ERROR_NOT_PERMITTED";
case CUDA_ERROR_NOT_SUPPORTED: return "CUDA_ERROR_NOT_SUPPORTED";
case CUDA_ERROR_UNKNOWN: return "CUDA_ERROR_UNKNOWN";
default: return "CUDA_ERROR_UNKNOWN";
}
}
#endif<commit_msg>修正命令行提示,Max Thread Per MP和SP是不一样的概念<commit_after>#include "ocu.h"
#include <cuda.h>
#include <nvrtc.h>
#ifdef __USE_CUDA__
ocu_args_d_t& getOcu(void)
{
static bool bInit = false;
static ocu_args_d_t ocu;
if (bInit == true) return ocu;
bInit = true;
CUresult err = cuInit(0);
LOG_CU_RESULT(err);
CUdevice dev = 0;
CUcontext ctxt;
CUstream stream;
err = cuCtxCreate(&ctxt, CU_CTX_SCHED_BLOCKING_SYNC, dev);
LOG_CU_RESULT(err);
char name[1024];
int proc_count = 0;
int thread_count = 0;
int cap_major = 0, cap_minor = 0;
cuDeviceGetName(name, sizeof(name), dev);
cuDeviceGetAttribute(&cap_major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev);
cuDeviceGetAttribute(&cap_minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev);
cuDeviceGetAttribute(&proc_count, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, dev);
cuDeviceGetAttribute(&thread_count, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, dev);
LogError("CUDA Adapter:%s Ver%d.%d MP %d MaxThread Per MP %d)\r\n", name, cap_major, cap_minor, proc_count, thread_count);
/*
char* source = nullptr;
size_t src_size = 0;
ReadSourceFromFile("clguetzli/clguetzli.cl", &source, &src_size);
nvrtcProgram prog;
const char *opts[] = { "-arch=compute_30", "-default-device", "-G", "-I\"./\"", "--fmad=false" };
nvrtcCreateProgram(&prog, source, "clguetzli.cl", 0, NULL, NULL);
nvrtcResult compile_result;// = nvrtcCompileProgram(prog, 3, opts);
if (NVRTC_SUCCESS != compile_result)
{
// Obtain compilation log from the program.
size_t logSize = 0;
nvrtcGetProgramLogSize(prog, &logSize);
char *log = new char[logSize];
nvrtcGetProgramLog(prog, log);
LogError("BuildInfo:\r\n%s\r\n", log);
delete[] log;
}
delete[] source;
// Obtain PTX from the program.
size_t ptxSize = 0;
nvrtcGetPTXSize(prog, &ptxSize);
char *ptx = new char[ptxSize];
nvrtcGetPTX(prog, ptx);
*/
char* ptx = nullptr;
size_t src_size = 0;
#ifdef _WIN64
ReadSourceFromFile("clguetzli/clguetzli.cu.ptx64", &ptx, &src_size);
#else
ReadSourceFromFile("clguetzli/clguetzli.cu.ptx32", &ptx, &src_size);
#endif
CUmodule mod;
CUjit_option jit_options[2];
void *jit_optvals[2];
jit_options[0] = CU_JIT_CACHE_MODE;
jit_optvals[0] = (void*)(uintptr_t)CU_JIT_CACHE_OPTION_CA;
err = cuModuleLoadDataEx(&mod, ptx, 1, jit_options, jit_optvals);
LOG_CU_RESULT(err);
delete[] ptx;
cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTION], mod, "clConvolutionEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONX], mod, "clConvolutionXEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONY], mod, "clConvolutionYEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_SQUARESAMPLE], mod, "clSquareSampleEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_OPSINDYNAMICSIMAGE], mod, "clOpsinDynamicsImageEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_MASKHIGHINTENSITYCHANGE], mod, "clMaskHighIntensityChangeEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTOR], mod, "clEdgeDetectorMapEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_BLOCKDIFFMAP], mod, "clBlockDiffMapEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTORLOWFREQ], mod, "clEdgeDetectorLowFreqEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_DIFFPRECOMPUTE], mod, "clDiffPrecomputeEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_SCALEIMAGE], mod, "clScaleImageEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_AVERAGE5X5], mod, "clAverage5x5Ex");
cuModuleGetFunction(&ocu.kernel[KERNEL_MINSQUAREVAL], mod, "clMinSquareValEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_DOMASK], mod, "clDoMaskEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_COMBINECHANNELS], mod, "clCombineChannelsEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_UPSAMPLESQUAREROOT], mod, "clUpsampleSquareRootEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_REMOVEBORDER], mod, "clRemoveBorderEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_ADDBORDER], mod, "clAddBorderEx");
cuModuleGetFunction(&ocu.kernel[KERNEL_COMPUTEBLOCKZEROINGORDER], mod, "clComputeBlockZeroingOrderEx");
cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_SHARED);
cuCtxSetSharedMemConfig(CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE);
cuStreamCreate(&stream, 0);
ocu.dev = dev;
ocu.commandQueue = stream;
ocu.mod = mod;
ocu.ctxt = ctxt;
return ocu;
}
ocu_args_d_t::ocu_args_d_t()
: dev(0)
, commandQueue(NULL)
, mod(NULL)
, ctxt(NULL)
{
}
ocu_args_d_t::~ocu_args_d_t()
{
cuModuleUnload(mod);
cuCtxDestroy(ctxt);
// cuStreamDestroy(commandQueue);
}
cu_mem ocu_args_d_t::allocMem(size_t s, const void *init)
{
cu_mem mem;
cuMemAlloc(&mem, s);
if (init)
{
cuMemcpyHtoDAsync(mem, init, s, commandQueue);
}
else
{
cuMemsetD8Async(mem, 0, s, commandQueue);
}
return mem;
}
ocu_channels ocu_args_d_t::allocMemChannels(size_t s, const void *c0, const void *c1, const void *c2)
{
const void *c[3] = { c0, c1, c2 };
ocu_channels img;
for (int i = 0; i < 3; i++)
{
img.ch[i] = allocMem(s, c[i]);
}
return img;
}
void ocu_args_d_t::releaseMemChannels(ocu_channels &rgb)
{
for (int i = 0; i < 3; i++)
{
cuMemFree(rgb.ch[i]);
rgb.ch[i] = NULL;
}
}
const char* TranslateCUDAError(CUresult errorCode)
{
switch (errorCode)
{
case CUDA_SUCCESS: return "CUDA_SUCCESS";
case CUDA_ERROR_INVALID_VALUE: return "CUDA_ERROR_INVALID_VALUE";
case CUDA_ERROR_OUT_OF_MEMORY: return "CUDA_ERROR_OUT_OF_MEMORY";
case CUDA_ERROR_NOT_INITIALIZED: return "CUDA_ERROR_NOT_INITIALIZED";
case CUDA_ERROR_DEINITIALIZED: return "CUDA_ERROR_DEINITIALIZED";
case CUDA_ERROR_PROFILER_DISABLED: return "CUDA_ERROR_PROFILER_DISABLED";
case CUDA_ERROR_PROFILER_NOT_INITIALIZED: return "CUDA_ERROR_PROFILER_NOT_INITIALIZED";
case CUDA_ERROR_PROFILER_ALREADY_STARTED: return "CUDA_ERROR_PROFILER_ALREADY_STARTED";
case CUDA_ERROR_PROFILER_ALREADY_STOPPED: return "CUDA_ERROR_PROFILER_ALREADY_STOPPED";
case CUDA_ERROR_NO_DEVICE: return "CUDA_ERROR_NO_DEVICE";
case CUDA_ERROR_INVALID_DEVICE: return "CUDA_ERROR_INVALID_DEVICE";
case CUDA_ERROR_INVALID_IMAGE: return "CUDA_ERROR_INVALID_IMAGE";
case CUDA_ERROR_INVALID_CONTEXT: return "CUDA_ERROR_INVALID_CONTEXT";
case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "CUDA_ERROR_CONTEXT_ALREADY_CURRENT";
case CUDA_ERROR_MAP_FAILED: return "CUDA_ERROR_MAP_FAILED";
case CUDA_ERROR_UNMAP_FAILED: return "CUDA_ERROR_UNMAP_FAILED";
case CUDA_ERROR_ARRAY_IS_MAPPED: return "CUDA_ERROR_ARRAY_IS_MAPPED";
case CUDA_ERROR_ALREADY_MAPPED: return "CUDA_ERROR_ALREADY_MAPPED";
case CUDA_ERROR_NO_BINARY_FOR_GPU: return "CUDA_ERROR_NO_BINARY_FOR_GPU";
case CUDA_ERROR_ALREADY_ACQUIRED: return "CUDA_ERROR_ALREADY_ACQUIRED";
case CUDA_ERROR_NOT_MAPPED: return "CUDA_ERROR_NOT_MAPPED";
case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "CUDA_ERROR_NOT_MAPPED_AS_ARRAY";
case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "CUDA_ERROR_NOT_MAPPED_AS_POINTER";
case CUDA_ERROR_ECC_UNCORRECTABLE: return "CUDA_ERROR_ECC_UNCORRECTABLE";
case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUDA_ERROR_UNSUPPORTED_LIMIT";
case CUDA_ERROR_CONTEXT_ALREADY_IN_USE: return "CUDA_ERROR_CONTEXT_ALREADY_IN_USE";
case CUDA_ERROR_PEER_ACCESS_UNSUPPORTED: return "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED";
case CUDA_ERROR_INVALID_PTX: return "CUDA_ERROR_INVALID_PTX";
case CUDA_ERROR_INVALID_GRAPHICS_CONTEXT: return "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT";
case CUDA_ERROR_NVLINK_UNCORRECTABLE: return "CUDA_ERROR_NVLINK_UNCORRECTABLE";
case CUDA_ERROR_INVALID_SOURCE: return "CUDA_ERROR_INVALID_SOURCE";
case CUDA_ERROR_FILE_NOT_FOUND: return "CUDA_ERROR_FILE_NOT_FOUND";
case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND";
case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED";
case CUDA_ERROR_OPERATING_SYSTEM: return "CUDA_ERROR_OPERATING_SYSTEM";
case CUDA_ERROR_INVALID_HANDLE: return "CUDA_ERROR_INVALID_HANDLE";
case CUDA_ERROR_NOT_FOUND: return "CUDA_ERROR_NOT_FOUND";
case CUDA_ERROR_NOT_READY: return "CUDA_ERROR_NOT_READY";
case CUDA_ERROR_ILLEGAL_ADDRESS: return "CUDA_ERROR_ILLEGAL_ADDRESS";
case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES";
case CUDA_ERROR_LAUNCH_TIMEOUT: return "CUDA_ERROR_LAUNCH_TIMEOUT";
case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING";
case CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED: return "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED";
case CUDA_ERROR_PEER_ACCESS_NOT_ENABLED: return "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED";
case CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE: return "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE";
case CUDA_ERROR_CONTEXT_IS_DESTROYED: return "CUDA_ERROR_CONTEXT_IS_DESTROYED";
case CUDA_ERROR_ASSERT: return "CUDA_ERROR_ASSERT";
case CUDA_ERROR_TOO_MANY_PEERS: return "CUDA_ERROR_TOO_MANY_PEERS";
case CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED";
case CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED";
case CUDA_ERROR_HARDWARE_STACK_ERROR: return "CUDA_ERROR_HARDWARE_STACK_ERROR";
case CUDA_ERROR_ILLEGAL_INSTRUCTION: return "CUDA_ERROR_ILLEGAL_INSTRUCTION";
case CUDA_ERROR_MISALIGNED_ADDRESS: return "CUDA_ERROR_MISALIGNED_ADDRESS";
case CUDA_ERROR_INVALID_ADDRESS_SPACE: return "CUDA_ERROR_INVALID_ADDRESS_SPACE";
case CUDA_ERROR_INVALID_PC: return "CUDA_ERROR_INVALID_PC";
case CUDA_ERROR_LAUNCH_FAILED: return "CUDA_ERROR_LAUNCH_FAILED";
case CUDA_ERROR_NOT_PERMITTED: return "CUDA_ERROR_NOT_PERMITTED";
case CUDA_ERROR_NOT_SUPPORTED: return "CUDA_ERROR_NOT_SUPPORTED";
case CUDA_ERROR_UNKNOWN: return "CUDA_ERROR_UNKNOWN";
default: return "CUDA_ERROR_UNKNOWN";
}
}
#endif<|endoftext|> |
<commit_before>/***********************************************************************
filename: ItemView.cpp
created: Sat May 24 2014
author: Timotei Dolean <timotei21@gmail.com>
purpose: Implementation of the base class for all item model-based views.
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/views/ItemView.h"
namespace CEGUI
{
//----------------------------------------------------------------------------//
ViewRenderingState::ViewRenderingState() :
d_isDirty(true)
{
}
//----------------------------------------------------------------------------//
ViewRenderingState::~ViewRenderingState()
{
}
//----------------------------------------------------------------------------//
ItemView::ItemView(const String& type, const String& name) :
Window(type, name),
d_itemModel(0),
d_eventChildrenAddedConnection(0),
d_eventChildrenRemovedConnection(0)
{
}
//----------------------------------------------------------------------------//
ItemView::~ItemView()
{
disconnectModelEvents();
}
//----------------------------------------------------------------------------//
void ItemView::setModel(ItemModel* item_model)
{
if (item_model == d_itemModel)
return;
if (d_itemModel != 0)
{
disconnectModelEvents();
}
d_itemModel = item_model;
connectToModelEvents(d_itemModel);
getRenderingState()->d_isDirty = true;
}
//----------------------------------------------------------------------------//
void ItemView::connectToModelEvents(ItemModel* d_itemModel)
{
d_eventChildrenAddedConnection = d_itemModel->subscribeEvent(ItemModel::EventChildrenAdded,
&ItemView::onChildrenAdded, this);
d_eventChildrenRemovedConnection = d_itemModel->subscribeEvent(ItemModel::EventChildrenRemoved,
&ItemView::onChildrenRemoved, this);
}
//----------------------------------------------------------------------------//
bool ItemView::onChildrenAdded(const EventArgs& args)
{
getRenderingState()->d_isDirty = true;
return true;
}
//----------------------------------------------------------------------------//
bool ItemView::onChildrenRemoved(const EventArgs& args)
{
getRenderingState()->d_isDirty = true;
return true;
}
//----------------------------------------------------------------------------//
void ItemView::disconnectModelEvents()
{
if (d_eventChildrenAddedConnection != 0)
d_eventChildrenAddedConnection->disconnect();
if (d_eventChildrenRemovedConnection != 0)
d_eventChildrenRemovedConnection->disconnect();
}
}
<commit_msg>Invalidate the view when model changed<commit_after>/***********************************************************************
filename: ItemView.cpp
created: Sat May 24 2014
author: Timotei Dolean <timotei21@gmail.com>
purpose: Implementation of the base class for all item model-based views.
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/views/ItemView.h"
namespace CEGUI
{
//----------------------------------------------------------------------------//
ViewRenderingState::ViewRenderingState() :
d_isDirty(true)
{
}
//----------------------------------------------------------------------------//
ViewRenderingState::~ViewRenderingState()
{
}
//----------------------------------------------------------------------------//
ItemView::ItemView(const String& type, const String& name) :
Window(type, name),
d_itemModel(0),
d_eventChildrenAddedConnection(0),
d_eventChildrenRemovedConnection(0)
{
}
//----------------------------------------------------------------------------//
ItemView::~ItemView()
{
disconnectModelEvents();
}
//----------------------------------------------------------------------------//
void ItemView::setModel(ItemModel* item_model)
{
if (item_model == d_itemModel)
return;
if (d_itemModel != 0)
{
disconnectModelEvents();
}
d_itemModel = item_model;
connectToModelEvents(d_itemModel);
getRenderingState()->d_isDirty = true;
}
//----------------------------------------------------------------------------//
void ItemView::connectToModelEvents(ItemModel* d_itemModel)
{
d_eventChildrenAddedConnection = d_itemModel->subscribeEvent(ItemModel::EventChildrenAdded,
&ItemView::onChildrenAdded, this);
d_eventChildrenRemovedConnection = d_itemModel->subscribeEvent(ItemModel::EventChildrenRemoved,
&ItemView::onChildrenRemoved, this);
}
//----------------------------------------------------------------------------//
bool ItemView::onChildrenAdded(const EventArgs& args)
{
getRenderingState()->d_isDirty = true;
invalidate(false);
return true;
}
//----------------------------------------------------------------------------//
bool ItemView::onChildrenRemoved(const EventArgs& args)
{
getRenderingState()->d_isDirty = true;
invalidate(false);
return true;
}
//----------------------------------------------------------------------------//
void ItemView::disconnectModelEvents()
{
if (d_eventChildrenAddedConnection != 0)
d_eventChildrenAddedConnection->disconnect();
if (d_eventChildrenRemovedConnection != 0)
d_eventChildrenRemovedConnection->disconnect();
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Version.h"
#include "D435iCamera.h"
#include "Visualizer.h"
#include <librealsense2/rs.h>
#include <librealsense2/rs.hpp>
#include <librealsense2/rsutil.h>
#include <librealsense2/hpp/rs_pipeline.hpp>
/** RealSense SDK2 Cross-Platform Depth Camera Backend **/
namespace ark {
D435iCamera::D435iCamera():
last_ts_g(0), kill(false) {
//Setup camera
//TODO: Make read from config file
rs2::context ctx;
device = ctx.query_devices().front();
width = 640;
height = 480;
//Setup configuration
config.enable_stream(RS2_STREAM_DEPTH,-1,width, height,RS2_FORMAT_Z16,30);
config.enable_stream(RS2_STREAM_INFRARED, 1, width, height, RS2_FORMAT_Y8, 30);
config.enable_stream(RS2_STREAM_INFRARED, 2, width, height, RS2_FORMAT_Y8, 30);
config.enable_stream(RS2_STREAM_COLOR, -1, width, height, RS2_FORMAT_RGB8, 30);
motion_config.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F,250);
motion_config.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F,200);
imu_rate=200; //setting imu_rate to be the gyro rate since we are using the gyro timestamps
//Need to get the depth sensor specifically as it is the one that controls the sync funciton
depth_sensor = new rs2::depth_sensor(device.first<rs2::depth_sensor>());
scale = depth_sensor->get_option(RS2_OPTION_DEPTH_UNITS);
rs2::sensor color_sensor = device.query_sensors()[1];
color_sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE,false);
}
D435iCamera::~D435iCamera() {
try {
kill=true;
imuReaderThread_.join();
pipe->stop();
if(depth_sensor){
delete depth_sensor;
depth_sensor=nullptr;
}
}
catch (...) {}
}
void D435iCamera::start(){
//enable sync
//depth_sensor->set_option(RS2_OPTION_INTER_CAM_SYNC_MODE,1);
//depth_sensor->set_option(RS2_OPTION_EMITTER_ENABLED, 1.f);
//start streaming
pipe = std::make_shared<rs2::pipeline>();
rs2::pipeline_profile selection = pipe->start(config);
//get the depth intrinsics (needed for projection to 3d)
auto depthStream = selection.get_stream(RS2_STREAM_DEPTH)
.as<rs2::video_stream_profile>();
depthIntrinsics = depthStream.get_intrinsics();
motion_pipe = std::make_shared<rs2::pipeline>();
rs2::pipeline_profile selection_motion = motion_pipe->start(motion_config);
if (RS2_API_MAJOR_VERSION > 2 || RS2_API_MAJOR_VERSION == 2 && RS2_API_MINOR_VERSION >= 22) {
auto dev = selection.get_device();
auto sensors = dev.query_sensors();
auto dev_motion = selection_motion.get_device();
auto sensors_motion = dev_motion.query_sensors();
int global_time_option = -1;
string match = "Global Time Enabled";
for (int i = 0; i < rs2_option::RS2_OPTION_COUNT; i++) {
if (!strcmp(rs2_option_to_string((rs2_option)i), match.c_str())) {
global_time_option = i;
break;
}
}
if (global_time_option == -1) {
cout << "Couldn't find Global Time Enabled Option" << endl;
}
for (auto sensor: sensors) {
sensor.set_option((rs2_option)global_time_option, false);
}
for (auto sensor: sensors_motion) {
sensor.set_option((rs2_option)global_time_option, false);
}
}
imuReaderThread_ = std::thread(&D435iCamera::imuReader, this);
}
void D435iCamera::imuReader(){
while(!kill){
auto frames = motion_pipe->wait_for_frames();
auto fa = frames.first(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F)
.as<rs2::motion_frame>();
auto fg = frames.first(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F)
.as<rs2::motion_frame>();
double ts_g = fg.get_timestamp();
if(ts_g != last_ts_g){
last_ts_g=ts_g;
// std::cout << "GYRO: " << ts_g / 1e2 << std::endl;
// Get gyro measures
rs2_vector gyro_data = fg.get_motion_data();
// Get the timestamp of the current frame
double ts_a = fa.get_timestamp();
//std::cout << "ACCEL: " << ts_a << std::endl;
// Get accelerometer measures
rs2_vector accel_data = fa.get_motion_data();
ImuPair imu_out { double(ts_g)*1e6, //convert to nanoseconds, for some reason gyro timestamp is in centiseconds
Eigen::Vector3d(gyro_data.x,gyro_data.y,gyro_data.z),
Eigen::Vector3d(accel_data.x,accel_data.y,accel_data.z)};
imu_queue_.enqueue(imu_out);
}
}
}
bool D435iCamera::getImuToTime(double timestamp, std::vector<ImuPair>& data_out){
ImuPair imu_data;
imu_data.timestamp=0;
while((imu_data.timestamp+1e9/imu_rate)<timestamp){
if(imu_queue_.try_dequeue(&imu_data)){
data_out.push_back(imu_data);
}
}
return true;
};
const std::string D435iCamera::getModelName() const {
return "RealSense";
}
cv::Size D435iCamera::getImageSize() const
{
return cv::Size(width,height);
}
void D435iCamera::update(MultiCameraFrame & frame) {
try {
// Ensure the frame has space for all images
frame.images_.resize(5);
// Get frames from camera
auto frames = pipe->wait_for_frames();
auto infrared = frames.get_infrared_frame(1);
auto infrared2 = frames.get_infrared_frame(2);
auto depth = frames.get_depth_frame();
auto color = frames.get_color_frame();
// Store ID for later
frame.frameId_ = depth.get_frame_number();
if(depth.supports_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)){
frame.timestamp_= depth.get_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)*1e3;
//std::cout << "Image: " << std::fixed << frame.timestamp_/1e3 << std::endl;
}else{
std::cout << "No Metadata" << std::endl;
}
// Convert infrared frame to opencv
if (frame.images_[0].empty()) frame.images_[0] = cv::Mat(cv::Size(width,height), CV_8UC1);
std::memcpy( frame.images_[0].data, infrared.get_data(),width * height);
if (frame.images_[1].empty()) frame.images_[1] = cv::Mat(cv::Size(width,height), CV_8UC1);
std::memcpy( frame.images_[1].data, infrared2.get_data(),width * height);
if (frame.images_[2].empty()) frame.images_[2] = cv::Mat(cv::Size(width,height), CV_32FC3);
project(depth, frame.images_[2]);
frame.images_[2] = frame.images_[2]*scale; //depth is in mm by default
if (frame.images_[3].empty()) frame.images_[3] = cv::Mat(cv::Size(width,height), CV_8UC3);
std::memcpy( frame.images_[3].data, color.get_data(),3 * width * height);
if (frame.images_[4].empty()) frame.images_[4] = cv::Mat(cv::Size(width,height), CV_16UC1);
// 16 bits = 2 bytes
std::memcpy(frame.images_[4].data, depth.get_data(),width * height * 2);
} catch (std::runtime_error e) {
// Try reconnecting
badInputFlag = true;
pipe->stop();
printf("Couldn't connect to camera, retrying in 0.5s...\n");
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
//query_intrinsics();
pipe->start(config);
badInputFlag = false;
return;
}
}
// project depth map to xyz coordinates directly (faster and minimizes distortion, but will not be aligned to RGB/IR)
void D435iCamera::project(const rs2::frame & depth_frame, cv::Mat & xyz_map) {
const uint16_t * depth_data = (const uint16_t *)depth_frame.get_data();
rs2_intrinsics * dIntrin = &depthIntrinsics;
const uint16_t * srcPtr;
cv::Vec3f * destPtr;
float srcPixel[2], destXYZ[3];
for (int r = 0; r < height; ++r)
{
srcPtr = depth_data + r * dIntrin->width;
destPtr = xyz_map.ptr<Vec3f>(r);
srcPixel[1] = r;
for (int c = 0; c < width; ++c)
{
if (srcPtr[c] == 0) {
memset(&destPtr[c], 0, 3 * sizeof(float));
continue;
}
srcPixel[0] = c;
rs2_deproject_pixel_to_point(destXYZ, dIntrin, srcPixel, srcPtr[c]);
memcpy(&destPtr[c], destXYZ, 3 * sizeof(float));
}
}
}
const rs2_intrinsics &D435iCamera::getDepthIntrinsics() {
return depthIntrinsics;
}
double D435iCamera::getDepthScale() {
return scale;
}
}
<commit_msg>fixed whitespace<commit_after>#include "stdafx.h"
#include "Version.h"
#include "D435iCamera.h"
#include "Visualizer.h"
#include <librealsense2/rs.h>
#include <librealsense2/rs.hpp>
#include <librealsense2/rsutil.h>
#include <librealsense2/hpp/rs_pipeline.hpp>
/** RealSense SDK2 Cross-Platform Depth Camera Backend **/
namespace ark {
D435iCamera::D435iCamera():
last_ts_g(0), kill(false) {
//Setup camera
//TODO: Make read from config file
rs2::context ctx;
device = ctx.query_devices().front();
width = 640;
height = 480;
//Setup configuration
config.enable_stream(RS2_STREAM_DEPTH,-1,width, height,RS2_FORMAT_Z16,30);
config.enable_stream(RS2_STREAM_INFRARED, 1, width, height, RS2_FORMAT_Y8, 30);
config.enable_stream(RS2_STREAM_INFRARED, 2, width, height, RS2_FORMAT_Y8, 30);
config.enable_stream(RS2_STREAM_COLOR, -1, width, height, RS2_FORMAT_RGB8, 30);
motion_config.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F,250);
motion_config.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F,200);
imu_rate=200; //setting imu_rate to be the gyro rate since we are using the gyro timestamps
//Need to get the depth sensor specifically as it is the one that controls the sync funciton
depth_sensor = new rs2::depth_sensor(device.first<rs2::depth_sensor>());
scale = depth_sensor->get_option(RS2_OPTION_DEPTH_UNITS);
rs2::sensor color_sensor = device.query_sensors()[1];
color_sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE,false);
}
D435iCamera::~D435iCamera() {
try {
kill=true;
imuReaderThread_.join();
pipe->stop();
if(depth_sensor){
delete depth_sensor;
depth_sensor=nullptr;
}
}
catch (...) {}
}
void D435iCamera::start(){
//enable sync
//depth_sensor->set_option(RS2_OPTION_INTER_CAM_SYNC_MODE,1);
//depth_sensor->set_option(RS2_OPTION_EMITTER_ENABLED, 1.f);
//start streaming
pipe = std::make_shared<rs2::pipeline>();
rs2::pipeline_profile selection = pipe->start(config);
//get the depth intrinsics (needed for projection to 3d)
auto depthStream = selection.get_stream(RS2_STREAM_DEPTH)
.as<rs2::video_stream_profile>();
depthIntrinsics = depthStream.get_intrinsics();
motion_pipe = std::make_shared<rs2::pipeline>();
rs2::pipeline_profile selection_motion = motion_pipe->start(motion_config);
if (RS2_API_MAJOR_VERSION > 2 || RS2_API_MAJOR_VERSION == 2 && RS2_API_MINOR_VERSION >= 22) {
auto dev = selection.get_device();
auto sensors = dev.query_sensors();
auto dev_motion = selection_motion.get_device();
auto sensors_motion = dev_motion.query_sensors();
int global_time_option = -1;
string match = "Global Time Enabled";
for (int i = 0; i < rs2_option::RS2_OPTION_COUNT; i++) {
if (!strcmp(rs2_option_to_string((rs2_option)i), match.c_str())) {
global_time_option = i;
break;
}
}
if (global_time_option == -1) {
cout << "Couldn't find Global Time Enabled Option" << endl;
}
for (auto sensor: sensors) {
sensor.set_option((rs2_option)global_time_option, false);
}
for (auto sensor: sensors_motion) {
sensor.set_option((rs2_option)global_time_option, false);
}
}
imuReaderThread_ = std::thread(&D435iCamera::imuReader, this);
}
void D435iCamera::imuReader(){
while(!kill){
auto frames = motion_pipe->wait_for_frames();
auto fa = frames.first(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F)
.as<rs2::motion_frame>();
auto fg = frames.first(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F)
.as<rs2::motion_frame>();
double ts_g = fg.get_timestamp();
if(ts_g != last_ts_g){
last_ts_g=ts_g;
// std::cout << "GYRO: " << ts_g / 1e2 << std::endl;
// Get gyro measures
rs2_vector gyro_data = fg.get_motion_data();
// Get the timestamp of the current frame
double ts_a = fa.get_timestamp();
//std::cout << "ACCEL: " << ts_a << std::endl;
// Get accelerometer measures
rs2_vector accel_data = fa.get_motion_data();
ImuPair imu_out { double(ts_g)*1e6, //convert to nanoseconds, for some reason gyro timestamp is in centiseconds
Eigen::Vector3d(gyro_data.x,gyro_data.y,gyro_data.z),
Eigen::Vector3d(accel_data.x,accel_data.y,accel_data.z)};
imu_queue_.enqueue(imu_out);
}
}
}
bool D435iCamera::getImuToTime(double timestamp, std::vector<ImuPair>& data_out){
ImuPair imu_data;
imu_data.timestamp=0;
while((imu_data.timestamp+1e9/imu_rate)<timestamp){
if(imu_queue_.try_dequeue(&imu_data)){
data_out.push_back(imu_data);
}
}
return true;
};
const std::string D435iCamera::getModelName() const {
return "RealSense";
}
cv::Size D435iCamera::getImageSize() const
{
return cv::Size(width,height);
}
void D435iCamera::update(MultiCameraFrame & frame) {
try {
// Ensure the frame has space for all images
frame.images_.resize(5);
// Get frames from camera
auto frames = pipe->wait_for_frames();
auto infrared = frames.get_infrared_frame(1);
auto infrared2 = frames.get_infrared_frame(2);
auto depth = frames.get_depth_frame();
auto color = frames.get_color_frame();
// Store ID for later
frame.frameId_ = depth.get_frame_number();
if(depth.supports_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)){
frame.timestamp_= depth.get_frame_metadata(RS2_FRAME_METADATA_SENSOR_TIMESTAMP)*1e3;
//std::cout << "Image: " << std::fixed << frame.timestamp_/1e3 << std::endl;
}else{
std::cout << "No Metadata" << std::endl;
}
// Convert infrared frame to opencv
if (frame.images_[0].empty()) frame.images_[0] = cv::Mat(cv::Size(width,height), CV_8UC1);
std::memcpy( frame.images_[0].data, infrared.get_data(),width * height);
if (frame.images_[1].empty()) frame.images_[1] = cv::Mat(cv::Size(width,height), CV_8UC1);
std::memcpy( frame.images_[1].data, infrared2.get_data(),width * height);
if (frame.images_[2].empty()) frame.images_[2] = cv::Mat(cv::Size(width,height), CV_32FC3);
project(depth, frame.images_[2]);
frame.images_[2] = frame.images_[2]*scale; //depth is in mm by default
if (frame.images_[3].empty()) frame.images_[3] = cv::Mat(cv::Size(width,height), CV_8UC3);
std::memcpy( frame.images_[3].data, color.get_data(),3 * width * height);
if (frame.images_[4].empty()) frame.images_[4] = cv::Mat(cv::Size(width,height), CV_16UC1);
// 16 bits = 2 bytes
std::memcpy(frame.images_[4].data, depth.get_data(),width * height * 2);
} catch (std::runtime_error e) {
// Try reconnecting
badInputFlag = true;
pipe->stop();
printf("Couldn't connect to camera, retrying in 0.5s...\n");
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
//query_intrinsics();
pipe->start(config);
badInputFlag = false;
return;
}
}
// project depth map to xyz coordinates directly (faster and minimizes distortion, but will not be aligned to RGB/IR)
void D435iCamera::project(const rs2::frame & depth_frame, cv::Mat & xyz_map) {
const uint16_t * depth_data = (const uint16_t *)depth_frame.get_data();
rs2_intrinsics * dIntrin = &depthIntrinsics;
const uint16_t * srcPtr;
cv::Vec3f * destPtr;
float srcPixel[2], destXYZ[3];
for (int r = 0; r < height; ++r)
{
srcPtr = depth_data + r * dIntrin->width;
destPtr = xyz_map.ptr<Vec3f>(r);
srcPixel[1] = r;
for (int c = 0; c < width; ++c)
{
if (srcPtr[c] == 0) {
memset(&destPtr[c], 0, 3 * sizeof(float));
continue;
}
srcPixel[0] = c;
rs2_deproject_pixel_to_point(destXYZ, dIntrin, srcPixel, srcPtr[c]);
memcpy(&destPtr[c], destXYZ, 3 * sizeof(float));
}
}
}
const rs2_intrinsics &D435iCamera::getDepthIntrinsics() {
return depthIntrinsics;
}
double D435iCamera::getDepthScale() {
return scale;
}
}
<|endoftext|> |
<commit_before><commit_msg>adjust also RPN reference tokens, tdf#91842 and probably others<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tphfedit.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2004-08-23 09:35:08 $
*
* 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 SC_TPHFEDIT_HXX
#define SC_TPHFEDIT_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVX_PAGEITEM_HXX //autogen
#include <svx/pageitem.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx" // wegen enum SvxNumType
#endif
#ifndef SC_POPMENU_HXX
#include "popmenu.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
//===================================================================
class ScHeaderEditEngine;
class ScPatternAttr;
class EditView;
class EditTextObject;
class SvxFieldItem;
class ScAccessibleEditObject;
class ScEditWindow;
SC_DLLPUBLIC ScEditWindow* GetScEditWindow (); //CHINA001
enum ScEditWindowLocation
{
Left,
Center,
Right
};
class SC_DLLPUBLIC ScEditWindow : public Control
{
public:
ScEditWindow( Window* pParent, const ResId& rResId, ScEditWindowLocation eLoc );
~ScEditWindow();
void SetFont( const ScPatternAttr& rPattern );
void SetText( const EditTextObject& rTextObject );
EditTextObject* CreateTextObject();
void SetCharAttriutes();
void InsertField( const SvxFieldItem& rFld );
void SetNumType(SvxNumType eNumType);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();
inline ScHeaderEditEngine* GetEditEngine() const {return pEdEngine;}
protected:
virtual void Paint( const Rectangle& rRec );
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 Command( const CommandEvent& rCEvt );
virtual void GetFocus();
virtual void LoseFocus();
private:
ScHeaderEditEngine* pEdEngine;
EditView* pEdView;
ScEditWindowLocation eLocation;
com::sun::star::uno::WeakReference< ::com::sun::star::accessibility::XAccessible > xAcc;
ScAccessibleEditObject* pAcc;
};
//===================================================================
class SC_DLLPUBLIC ScExtIButton : public ImageButton
{
private:
Timer aTimer;
ScPopupMenu* pPopupMenu;
Link aMLink;
USHORT nSelected;
SC_DLLPRIVATE DECL_LINK( TimerHdl, Timer*);
// void DrawArrow();
protected:
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt);
virtual void Click();
virtual void StartPopup();
public:
ScExtIButton(Window* pParent, const ResId& rResId );
void SetPopupMenu(ScPopupMenu* pPopUp);
USHORT GetSelected();
void SetMenuHdl( const Link& rLink ) { aMLink = rLink; }
const Link& GetMenuHdl() const { return aMLink; }
virtual long PreNotify( NotifyEvent& rNEvt );
};
//===================================================================
//CHINA001
//CHINA001 class ScHFEditPage : public SfxTabPage
//CHINA001 {
//CHINA001 public:
//CHINA001 virtual BOOL FillItemSet ( SfxItemSet& rCoreSet );
//CHINA001 virtual void Reset ( const SfxItemSet& rCoreSet );
//CHINA001
//CHINA001 void SetNumType(SvxNumType eNumType);
//CHINA001
//CHINA001 protected:
//CHINA001 ScHFEditPage( Window* pParent,
//CHINA001 USHORT nResId,
//CHINA001 const SfxItemSet& rCoreSet,
//CHINA001 USHORT nWhich );
//CHINA001 virtual ~ScHFEditPage();
//CHINA001
//CHINA001 private:
//CHINA001 FixedText aFtLeft;
//CHINA001 ScEditWindow aWndLeft;
//CHINA001 FixedText aFtCenter;
//CHINA001 ScEditWindow aWndCenter;
//CHINA001 FixedText aFtRight;
//CHINA001 ScEditWindow aWndRight;
//CHINA001 ImageButton aBtnText;
//CHINA001 ScExtIButton aBtnFile;
//CHINA001 ImageButton aBtnTable;
//CHINA001 ImageButton aBtnPage;
//CHINA001 ImageButton aBtnLastPage;
//CHINA001 ImageButton aBtnDate;
//CHINA001 ImageButton aBtnTime;
//CHINA001 FixedLine aFlInfo;
//CHINA001 FixedInfo aFtInfo;
//CHINA001 ScPopupMenu aPopUpFile;
//CHINA001
//CHINA001 USHORT nWhich;
//CHINA001 String aCmdArr[6];
//CHINA001
//CHINA001 private:
//CHINA001 #ifdef _TPHFEDIT_CXX
//CHINA001 void FillCmdArr();
//CHINA001 DECL_LINK( ClickHdl, ImageButton* );
//CHINA001 DECL_LINK( MenuHdl, ScExtIButton* );
//CHINA001 #endif
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScRightHeaderEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScRightHeaderEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScLeftHeaderEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScLeftHeaderEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScRightFooterEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScRightFooterEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScLeftFooterEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScLeftFooterEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
#endif // SC_TPHFEDIT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.346); FILE MERGED 2005/09/05 15:05:59 rt 1.10.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tphfedit.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:58:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_TPHFEDIT_HXX
#define SC_TPHFEDIT_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVX_PAGEITEM_HXX //autogen
#include <svx/pageitem.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx" // wegen enum SvxNumType
#endif
#ifndef SC_POPMENU_HXX
#include "popmenu.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
//===================================================================
class ScHeaderEditEngine;
class ScPatternAttr;
class EditView;
class EditTextObject;
class SvxFieldItem;
class ScAccessibleEditObject;
class ScEditWindow;
SC_DLLPUBLIC ScEditWindow* GetScEditWindow (); //CHINA001
enum ScEditWindowLocation
{
Left,
Center,
Right
};
class SC_DLLPUBLIC ScEditWindow : public Control
{
public:
ScEditWindow( Window* pParent, const ResId& rResId, ScEditWindowLocation eLoc );
~ScEditWindow();
void SetFont( const ScPatternAttr& rPattern );
void SetText( const EditTextObject& rTextObject );
EditTextObject* CreateTextObject();
void SetCharAttriutes();
void InsertField( const SvxFieldItem& rFld );
void SetNumType(SvxNumType eNumType);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();
inline ScHeaderEditEngine* GetEditEngine() const {return pEdEngine;}
protected:
virtual void Paint( const Rectangle& rRec );
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 Command( const CommandEvent& rCEvt );
virtual void GetFocus();
virtual void LoseFocus();
private:
ScHeaderEditEngine* pEdEngine;
EditView* pEdView;
ScEditWindowLocation eLocation;
com::sun::star::uno::WeakReference< ::com::sun::star::accessibility::XAccessible > xAcc;
ScAccessibleEditObject* pAcc;
};
//===================================================================
class SC_DLLPUBLIC ScExtIButton : public ImageButton
{
private:
Timer aTimer;
ScPopupMenu* pPopupMenu;
Link aMLink;
USHORT nSelected;
SC_DLLPRIVATE DECL_LINK( TimerHdl, Timer*);
// void DrawArrow();
protected:
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt);
virtual void Click();
virtual void StartPopup();
public:
ScExtIButton(Window* pParent, const ResId& rResId );
void SetPopupMenu(ScPopupMenu* pPopUp);
USHORT GetSelected();
void SetMenuHdl( const Link& rLink ) { aMLink = rLink; }
const Link& GetMenuHdl() const { return aMLink; }
virtual long PreNotify( NotifyEvent& rNEvt );
};
//===================================================================
//CHINA001
//CHINA001 class ScHFEditPage : public SfxTabPage
//CHINA001 {
//CHINA001 public:
//CHINA001 virtual BOOL FillItemSet ( SfxItemSet& rCoreSet );
//CHINA001 virtual void Reset ( const SfxItemSet& rCoreSet );
//CHINA001
//CHINA001 void SetNumType(SvxNumType eNumType);
//CHINA001
//CHINA001 protected:
//CHINA001 ScHFEditPage( Window* pParent,
//CHINA001 USHORT nResId,
//CHINA001 const SfxItemSet& rCoreSet,
//CHINA001 USHORT nWhich );
//CHINA001 virtual ~ScHFEditPage();
//CHINA001
//CHINA001 private:
//CHINA001 FixedText aFtLeft;
//CHINA001 ScEditWindow aWndLeft;
//CHINA001 FixedText aFtCenter;
//CHINA001 ScEditWindow aWndCenter;
//CHINA001 FixedText aFtRight;
//CHINA001 ScEditWindow aWndRight;
//CHINA001 ImageButton aBtnText;
//CHINA001 ScExtIButton aBtnFile;
//CHINA001 ImageButton aBtnTable;
//CHINA001 ImageButton aBtnPage;
//CHINA001 ImageButton aBtnLastPage;
//CHINA001 ImageButton aBtnDate;
//CHINA001 ImageButton aBtnTime;
//CHINA001 FixedLine aFlInfo;
//CHINA001 FixedInfo aFtInfo;
//CHINA001 ScPopupMenu aPopUpFile;
//CHINA001
//CHINA001 USHORT nWhich;
//CHINA001 String aCmdArr[6];
//CHINA001
//CHINA001 private:
//CHINA001 #ifdef _TPHFEDIT_CXX
//CHINA001 void FillCmdArr();
//CHINA001 DECL_LINK( ClickHdl, ImageButton* );
//CHINA001 DECL_LINK( MenuHdl, ScExtIButton* );
//CHINA001 #endif
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScRightHeaderEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScRightHeaderEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScLeftHeaderEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScLeftHeaderEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScRightFooterEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScRightFooterEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
//CHINA001
//CHINA001 //===================================================================
//CHINA001
//CHINA001 class ScLeftFooterEditPage : public ScHFEditPage
//CHINA001 {
//CHINA001 public:
//CHINA001 static SfxTabPage* Create( Window* pParent, const SfxItemSet& rCoreSet );
//CHINA001 static USHORT* GetRanges();
//CHINA001
//CHINA001 private:
//CHINA001 ScLeftFooterEditPage( Window* pParent, const SfxItemSet& rSet );
//CHINA001 };
#endif // SC_TPHFEDIT_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: cellsh4.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-02-03 12:50:49 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#ifdef WNT
#pragma optimize ("", off)
#endif
// INCLUDE ---------------------------------------------------------------
#include <sfx2/request.hxx>
#include "cellsh.hxx"
#include "tabvwsh.hxx"
#include "global.hxx"
#include "scmod.hxx"
#include "inputhdl.hxx"
#include "inputwin.hxx"
#include "document.hxx"
#include "sc.hrc"
//------------------------------------------------------------------
#define IS_AVAILABLE(WhichId,ppItem) \
(pReqArgs->GetItemState((WhichId), TRUE, ppItem ) == SFX_ITEM_SET)
void ScCellShell::ExecuteCursor( SfxRequest& rReq )
{
ScViewData* pData = GetViewData();
ScTabViewShell* pTabViewShell = pData->GetViewShell();
const SfxItemSet* pReqArgs = rReq.GetArgs();
USHORT nSlotId = rReq.GetSlot();
short nRepeat = 1;
BOOL bSel = FALSE;
BOOL bKeep = FALSE;
if ( pReqArgs != NULL )
{
const SfxPoolItem* pItem;
if( IS_AVAILABLE( FN_PARAM_1, &pItem ) )
nRepeat = ((const SfxInt16Item*)pItem)->GetValue();
if( IS_AVAILABLE( FN_PARAM_2, &pItem ) )
bSel = ((const SfxBoolItem*)pItem)->GetValue();
}
else
{
// evaluate locked selection mode
USHORT nLocked = pTabViewShell->GetLockedModifiers();
if ( nLocked & KEY_SHIFT )
bSel = TRUE; // EXT
else if ( nLocked & KEY_MOD1 )
{
// ADD mode: keep the selection, start a new block when marking with shift again
bKeep = TRUE;
pTabViewShell->SetNewStartIfMarking();
}
}
short nRTLSign = 1;
if ( pData->GetDocument()->IsLayoutRTL( pData->GetTabNo() ) )
{
//! evaluate cursor movement option?
nRTLSign = -1;
}
// einmal extra, damit der Cursor bei ExecuteInputDirect nicht zuoft gemalt wird:
pTabViewShell->HideAllCursors();
//OS: einmal fuer alle wird doch reichen!
pTabViewShell->ExecuteInputDirect();
switch ( nSlotId )
{
case SID_CURSORDOWN:
pTabViewShell->MoveCursorRel( 0, nRepeat, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKDOWN:
pTabViewShell->MoveCursorArea( 0, nRepeat, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORUP:
pTabViewShell->MoveCursorRel( 0, -nRepeat, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKUP:
pTabViewShell->MoveCursorArea( 0, -nRepeat, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORLEFT:
pTabViewShell->MoveCursorRel( -nRepeat * nRTLSign, 0, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKLEFT:
pTabViewShell->MoveCursorArea( -nRepeat * nRTLSign, 0, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORRIGHT:
pTabViewShell->MoveCursorRel( nRepeat * nRTLSign, 0, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKRIGHT:
pTabViewShell->MoveCursorArea( nRepeat * nRTLSign, 0, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORPAGEDOWN:
pTabViewShell->MoveCursorPage( 0, nRepeat, SC_FOLLOW_FIX, bSel, bKeep );
break;
case SID_CURSORPAGEUP:
pTabViewShell->MoveCursorPage( 0, -nRepeat, SC_FOLLOW_FIX, bSel, bKeep );
break;
case SID_CURSORPAGERIGHT_: //XXX !!!
pTabViewShell->MoveCursorPage( nRepeat, 0, SC_FOLLOW_FIX, bSel, bKeep );
break;
case SID_CURSORPAGELEFT_: //XXX !!!
pTabViewShell->MoveCursorPage( -nRepeat, 0, SC_FOLLOW_FIX, bSel, bKeep );
break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (Cursor)");
return;
}
pTabViewShell->ShowAllCursors();
rReq.AppendItem( SfxInt16Item(FN_PARAM_1, nRepeat) );
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, bSel) );
rReq.Done();
}
void ScCellShell::GetStateCursor( SfxItemSet& rSet )
{
}
void ScCellShell::ExecuteCursorSel( SfxRequest& rReq )
{
const SfxItemSet* pReqArgs = rReq.GetArgs();
USHORT nSlotId = rReq.GetSlot();
short nRepeat = 1;
if ( pReqArgs != NULL )
{
const SfxPoolItem* pItem;
if( IS_AVAILABLE( FN_PARAM_1, &pItem ) )
nRepeat = ((const SfxInt16Item*)pItem)->GetValue();
}
switch ( nSlotId )
{
case SID_CURSORDOWN_SEL: rReq.SetSlot( SID_CURSORDOWN ); break;
case SID_CURSORBLKDOWN_SEL: rReq.SetSlot( SID_CURSORBLKDOWN ); break;
case SID_CURSORUP_SEL: rReq.SetSlot( SID_CURSORUP ); break;
case SID_CURSORBLKUP_SEL: rReq.SetSlot( SID_CURSORBLKUP ); break;
case SID_CURSORLEFT_SEL: rReq.SetSlot( SID_CURSORLEFT ); break;
case SID_CURSORBLKLEFT_SEL: rReq.SetSlot( SID_CURSORBLKLEFT ); break;
case SID_CURSORRIGHT_SEL: rReq.SetSlot( SID_CURSORRIGHT ); break;
case SID_CURSORBLKRIGHT_SEL: rReq.SetSlot( SID_CURSORBLKRIGHT ); break;
case SID_CURSORPAGEDOWN_SEL: rReq.SetSlot( SID_CURSORPAGEDOWN ); break;
case SID_CURSORPAGEUP_SEL: rReq.SetSlot( SID_CURSORPAGEUP ); break;
case SID_CURSORPAGERIGHT_SEL: rReq.SetSlot( SID_CURSORPAGERIGHT_ ); break;
case SID_CURSORPAGELEFT_SEL: rReq.SetSlot( SID_CURSORPAGELEFT_ ); break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (CursorSel)");
return;
}
rReq.AppendItem( SfxInt16Item(FN_PARAM_1, nRepeat ) );
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, TRUE) );
ExecuteSlot( rReq, GetInterface() );
}
void ScCellShell::ExecuteMove( SfxRequest& rReq )
{
ScTabViewShell* pTabViewShell = GetViewData()->GetViewShell();
USHORT nSlotId = rReq.GetSlot();
if(nSlotId != SID_CURSORTOPOFSCREEN && nSlotId != SID_CURSORENDOFSCREEN)
pTabViewShell->ExecuteInputDirect();
switch ( nSlotId )
{
case SID_NEXT_TABLE:
case SID_NEXT_TABLE_SEL:
pTabViewShell->SelectNextTab( 1, (nSlotId == SID_NEXT_TABLE_SEL) );
break;
case SID_PREV_TABLE:
case SID_PREV_TABLE_SEL:
pTabViewShell->SelectNextTab( -1, (nSlotId == SID_PREV_TABLE_SEL) );
break;
// Cursorbewegungen in Bloecken gehen nicht von Basic aus,
// weil das ScSbxRange-Objekt bei Eingaben die Markierung veraendert
case SID_NEXT_UNPROTECT:
pTabViewShell->FindNextUnprot( FALSE, !rReq.IsAPI() );
break;
case SID_PREV_UNPROTECT:
pTabViewShell->FindNextUnprot( TRUE, !rReq.IsAPI() );
break;
case SID_CURSORENTERUP:
if (rReq.IsAPI())
pTabViewShell->MoveCursorRel( 0, -1, SC_FOLLOW_LINE, FALSE );
else
pTabViewShell->MoveCursorEnter( TRUE );
break;
case SID_CURSORENTERDOWN:
if (rReq.IsAPI())
pTabViewShell->MoveCursorRel( 0, 1, SC_FOLLOW_LINE, FALSE );
else
pTabViewShell->MoveCursorEnter( FALSE );
break;
case SID_SELECT_COL:
pTabViewShell->MarkColumns();
break;
case SID_SELECT_ROW:
pTabViewShell->MarkRows();
break;
case SID_SELECT_NONE:
pTabViewShell->Unmark();
break;
case SID_ALIGNCURSOR:
pTabViewShell->AlignToCursor( GetViewData()->GetCurX(), GetViewData()->GetCurY(), SC_FOLLOW_JUMP );
break;
case SID_MARKDATAAREA:
pTabViewShell->MarkDataArea();
break;
case SID_MARKARRAYFORMULA:
pTabViewShell->MarkMatrixFormula();
break;
case SID_SETINPUTMODE:
SC_MOD()->SetInputMode( SC_INPUT_TABLE );
break;
case SID_FOCUS_INPUTLINE:
{
ScInputHandler* pHdl = SC_MOD()->GetInputHdl( pTabViewShell );
if (pHdl)
{
ScInputWindow* pWin = pHdl->GetInputWindow();
if (pWin)
pWin->SwitchToTextWin();
}
}
break;
case SID_CURSORTOPOFSCREEN:
pTabViewShell->MoveCursorScreen( 0, -1, SC_FOLLOW_LINE, FALSE );
break;
case SID_CURSORENDOFSCREEN:
pTabViewShell->MoveCursorScreen( 0, 1, SC_FOLLOW_LINE, FALSE );
break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (Cursor)");
return;
}
rReq.Done();
}
void ScCellShell::ExecutePageSel( SfxRequest& rReq )
{
ScTabViewShell* pTabViewShell = GetViewData()->GetViewShell();
USHORT nSlotId = rReq.GetSlot();
switch ( nSlotId )
{
case SID_CURSORHOME_SEL: rReq.SetSlot( SID_CURSORHOME ); break;
case SID_CURSOREND_SEL: rReq.SetSlot( SID_CURSOREND ); break;
case SID_CURSORTOPOFFILE_SEL: rReq.SetSlot( SID_CURSORTOPOFFILE ); break;
case SID_CURSORENDOFFILE_SEL: rReq.SetSlot( SID_CURSORENDOFFILE ); break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (ExecutePageSel)");
return;
}
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, TRUE) );
ExecuteSlot( rReq, GetInterface() );
}
void ScCellShell::ExecutePage( SfxRequest& rReq )
{
ScTabViewShell* pTabViewShell = GetViewData()->GetViewShell();
const SfxItemSet* pReqArgs = rReq.GetArgs();
USHORT nSlotId = rReq.GetSlot();
BOOL bSel = FALSE;
BOOL bKeep = FALSE;
if ( pReqArgs != NULL )
{
const SfxPoolItem* pItem;
if( IS_AVAILABLE( FN_PARAM_2, &pItem ) )
bSel = ((const SfxBoolItem*)pItem)->GetValue();
}
else
{
// evaluate locked selection mode
USHORT nLocked = pTabViewShell->GetLockedModifiers();
if ( nLocked & KEY_SHIFT )
bSel = TRUE; // EXT
else if ( nLocked & KEY_MOD1 )
{
// ADD mode: keep the selection, start a new block when marking with shift again
bKeep = TRUE;
pTabViewShell->SetNewStartIfMarking();
}
}
pTabViewShell->ExecuteInputDirect();
switch ( nSlotId )
{
case SID_CURSORHOME:
pTabViewShell->MoveCursorEnd( -1, 0, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSOREND:
pTabViewShell->MoveCursorEnd( 1, 0, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORTOPOFFILE:
pTabViewShell->MoveCursorEnd( -1, -1, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORENDOFFILE:
pTabViewShell->MoveCursorEnd( 1, 1, SC_FOLLOW_JUMP, bSel, bKeep );
break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (ExecutePage)");
return;
}
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, bSel) );
rReq.Done();
}
<commit_msg>INTEGRATION: CWS rowlimit (1.6.12); FILE MERGED 2004/03/03 21:36:21 er 1.6.12.2: #i1967# type correctness 2004/02/26 16:49:25 jmarmion 1.6.12.1: #i1967# step 5 changes<commit_after>/*************************************************************************
*
* $RCSfile: cellsh4.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:58:42 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#ifdef WNT
#pragma optimize ("", off)
#endif
// INCLUDE ---------------------------------------------------------------
#include <sfx2/request.hxx>
#include "cellsh.hxx"
#include "tabvwsh.hxx"
#include "global.hxx"
#include "scmod.hxx"
#include "inputhdl.hxx"
#include "inputwin.hxx"
#include "document.hxx"
#include "sc.hrc"
//------------------------------------------------------------------
#define IS_AVAILABLE(WhichId,ppItem) \
(pReqArgs->GetItemState((WhichId), TRUE, ppItem ) == SFX_ITEM_SET)
void ScCellShell::ExecuteCursor( SfxRequest& rReq )
{
ScViewData* pData = GetViewData();
ScTabViewShell* pTabViewShell = pData->GetViewShell();
const SfxItemSet* pReqArgs = rReq.GetArgs();
USHORT nSlotId = rReq.GetSlot();
SCsCOLROW nRepeat = 1;
BOOL bSel = FALSE;
BOOL bKeep = FALSE;
if ( pReqArgs != NULL )
{
const SfxPoolItem* pItem;
if( IS_AVAILABLE( FN_PARAM_1, &pItem ) )
nRepeat = static_cast<SCsCOLROW>(((const SfxInt16Item*)pItem)->GetValue());
if( IS_AVAILABLE( FN_PARAM_2, &pItem ) )
bSel = ((const SfxBoolItem*)pItem)->GetValue();
}
else
{
// evaluate locked selection mode
USHORT nLocked = pTabViewShell->GetLockedModifiers();
if ( nLocked & KEY_SHIFT )
bSel = TRUE; // EXT
else if ( nLocked & KEY_MOD1 )
{
// ADD mode: keep the selection, start a new block when marking with shift again
bKeep = TRUE;
pTabViewShell->SetNewStartIfMarking();
}
}
SCsCOLROW nRTLSign = 1;
if ( pData->GetDocument()->IsLayoutRTL( pData->GetTabNo() ) )
{
//! evaluate cursor movement option?
nRTLSign = -1;
}
// einmal extra, damit der Cursor bei ExecuteInputDirect nicht zuoft gemalt wird:
pTabViewShell->HideAllCursors();
//OS: einmal fuer alle wird doch reichen!
pTabViewShell->ExecuteInputDirect();
switch ( nSlotId )
{
case SID_CURSORDOWN:
pTabViewShell->MoveCursorRel( 0, nRepeat, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKDOWN:
pTabViewShell->MoveCursorArea( 0, nRepeat, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORUP:
pTabViewShell->MoveCursorRel( 0, -nRepeat, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKUP:
pTabViewShell->MoveCursorArea( 0, -nRepeat, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORLEFT:
pTabViewShell->MoveCursorRel( static_cast<SCsCOL>(-nRepeat * nRTLSign), 0, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKLEFT:
pTabViewShell->MoveCursorArea( static_cast<SCsCOL>(-nRepeat * nRTLSign), 0, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORRIGHT:
pTabViewShell->MoveCursorRel( static_cast<SCsCOL>(nRepeat * nRTLSign), 0, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORBLKRIGHT:
pTabViewShell->MoveCursorArea( static_cast<SCsCOL>(nRepeat * nRTLSign), 0, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORPAGEDOWN:
pTabViewShell->MoveCursorPage( 0, nRepeat, SC_FOLLOW_FIX, bSel, bKeep );
break;
case SID_CURSORPAGEUP:
pTabViewShell->MoveCursorPage( 0, -nRepeat, SC_FOLLOW_FIX, bSel, bKeep );
break;
case SID_CURSORPAGERIGHT_: //XXX !!!
pTabViewShell->MoveCursorPage( static_cast<SCsCOL>(nRepeat), 0, SC_FOLLOW_FIX, bSel, bKeep );
break;
case SID_CURSORPAGELEFT_: //XXX !!!
pTabViewShell->MoveCursorPage( static_cast<SCsCOL>(-nRepeat), 0, SC_FOLLOW_FIX, bSel, bKeep );
break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (Cursor)");
return;
}
pTabViewShell->ShowAllCursors();
rReq.AppendItem( SfxInt16Item(FN_PARAM_1, static_cast<sal_Int16>(nRepeat)) );
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, bSel) );
rReq.Done();
}
void ScCellShell::GetStateCursor( SfxItemSet& rSet )
{
}
void ScCellShell::ExecuteCursorSel( SfxRequest& rReq )
{
const SfxItemSet* pReqArgs = rReq.GetArgs();
USHORT nSlotId = rReq.GetSlot();
short nRepeat = 1;
if ( pReqArgs != NULL )
{
const SfxPoolItem* pItem;
if( IS_AVAILABLE( FN_PARAM_1, &pItem ) )
nRepeat = ((const SfxInt16Item*)pItem)->GetValue();
}
switch ( nSlotId )
{
case SID_CURSORDOWN_SEL: rReq.SetSlot( SID_CURSORDOWN ); break;
case SID_CURSORBLKDOWN_SEL: rReq.SetSlot( SID_CURSORBLKDOWN ); break;
case SID_CURSORUP_SEL: rReq.SetSlot( SID_CURSORUP ); break;
case SID_CURSORBLKUP_SEL: rReq.SetSlot( SID_CURSORBLKUP ); break;
case SID_CURSORLEFT_SEL: rReq.SetSlot( SID_CURSORLEFT ); break;
case SID_CURSORBLKLEFT_SEL: rReq.SetSlot( SID_CURSORBLKLEFT ); break;
case SID_CURSORRIGHT_SEL: rReq.SetSlot( SID_CURSORRIGHT ); break;
case SID_CURSORBLKRIGHT_SEL: rReq.SetSlot( SID_CURSORBLKRIGHT ); break;
case SID_CURSORPAGEDOWN_SEL: rReq.SetSlot( SID_CURSORPAGEDOWN ); break;
case SID_CURSORPAGEUP_SEL: rReq.SetSlot( SID_CURSORPAGEUP ); break;
case SID_CURSORPAGERIGHT_SEL: rReq.SetSlot( SID_CURSORPAGERIGHT_ ); break;
case SID_CURSORPAGELEFT_SEL: rReq.SetSlot( SID_CURSORPAGELEFT_ ); break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (CursorSel)");
return;
}
rReq.AppendItem( SfxInt16Item(FN_PARAM_1, nRepeat ) );
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, TRUE) );
ExecuteSlot( rReq, GetInterface() );
}
void ScCellShell::ExecuteMove( SfxRequest& rReq )
{
ScTabViewShell* pTabViewShell = GetViewData()->GetViewShell();
USHORT nSlotId = rReq.GetSlot();
if(nSlotId != SID_CURSORTOPOFSCREEN && nSlotId != SID_CURSORENDOFSCREEN)
pTabViewShell->ExecuteInputDirect();
switch ( nSlotId )
{
case SID_NEXT_TABLE:
case SID_NEXT_TABLE_SEL:
pTabViewShell->SelectNextTab( 1, (nSlotId == SID_NEXT_TABLE_SEL) );
break;
case SID_PREV_TABLE:
case SID_PREV_TABLE_SEL:
pTabViewShell->SelectNextTab( -1, (nSlotId == SID_PREV_TABLE_SEL) );
break;
// Cursorbewegungen in Bloecken gehen nicht von Basic aus,
// weil das ScSbxRange-Objekt bei Eingaben die Markierung veraendert
case SID_NEXT_UNPROTECT:
pTabViewShell->FindNextUnprot( FALSE, !rReq.IsAPI() );
break;
case SID_PREV_UNPROTECT:
pTabViewShell->FindNextUnprot( TRUE, !rReq.IsAPI() );
break;
case SID_CURSORENTERUP:
if (rReq.IsAPI())
pTabViewShell->MoveCursorRel( 0, -1, SC_FOLLOW_LINE, FALSE );
else
pTabViewShell->MoveCursorEnter( TRUE );
break;
case SID_CURSORENTERDOWN:
if (rReq.IsAPI())
pTabViewShell->MoveCursorRel( 0, 1, SC_FOLLOW_LINE, FALSE );
else
pTabViewShell->MoveCursorEnter( FALSE );
break;
case SID_SELECT_COL:
pTabViewShell->MarkColumns();
break;
case SID_SELECT_ROW:
pTabViewShell->MarkRows();
break;
case SID_SELECT_NONE:
pTabViewShell->Unmark();
break;
case SID_ALIGNCURSOR:
pTabViewShell->AlignToCursor( GetViewData()->GetCurX(), GetViewData()->GetCurY(), SC_FOLLOW_JUMP );
break;
case SID_MARKDATAAREA:
pTabViewShell->MarkDataArea();
break;
case SID_MARKARRAYFORMULA:
pTabViewShell->MarkMatrixFormula();
break;
case SID_SETINPUTMODE:
SC_MOD()->SetInputMode( SC_INPUT_TABLE );
break;
case SID_FOCUS_INPUTLINE:
{
ScInputHandler* pHdl = SC_MOD()->GetInputHdl( pTabViewShell );
if (pHdl)
{
ScInputWindow* pWin = pHdl->GetInputWindow();
if (pWin)
pWin->SwitchToTextWin();
}
}
break;
case SID_CURSORTOPOFSCREEN:
pTabViewShell->MoveCursorScreen( 0, -1, SC_FOLLOW_LINE, FALSE );
break;
case SID_CURSORENDOFSCREEN:
pTabViewShell->MoveCursorScreen( 0, 1, SC_FOLLOW_LINE, FALSE );
break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (Cursor)");
return;
}
rReq.Done();
}
void ScCellShell::ExecutePageSel( SfxRequest& rReq )
{
ScTabViewShell* pTabViewShell = GetViewData()->GetViewShell();
USHORT nSlotId = rReq.GetSlot();
switch ( nSlotId )
{
case SID_CURSORHOME_SEL: rReq.SetSlot( SID_CURSORHOME ); break;
case SID_CURSOREND_SEL: rReq.SetSlot( SID_CURSOREND ); break;
case SID_CURSORTOPOFFILE_SEL: rReq.SetSlot( SID_CURSORTOPOFFILE ); break;
case SID_CURSORENDOFFILE_SEL: rReq.SetSlot( SID_CURSORENDOFFILE ); break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (ExecutePageSel)");
return;
}
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, TRUE) );
ExecuteSlot( rReq, GetInterface() );
}
void ScCellShell::ExecutePage( SfxRequest& rReq )
{
ScTabViewShell* pTabViewShell = GetViewData()->GetViewShell();
const SfxItemSet* pReqArgs = rReq.GetArgs();
USHORT nSlotId = rReq.GetSlot();
BOOL bSel = FALSE;
BOOL bKeep = FALSE;
if ( pReqArgs != NULL )
{
const SfxPoolItem* pItem;
if( IS_AVAILABLE( FN_PARAM_2, &pItem ) )
bSel = ((const SfxBoolItem*)pItem)->GetValue();
}
else
{
// evaluate locked selection mode
USHORT nLocked = pTabViewShell->GetLockedModifiers();
if ( nLocked & KEY_SHIFT )
bSel = TRUE; // EXT
else if ( nLocked & KEY_MOD1 )
{
// ADD mode: keep the selection, start a new block when marking with shift again
bKeep = TRUE;
pTabViewShell->SetNewStartIfMarking();
}
}
pTabViewShell->ExecuteInputDirect();
switch ( nSlotId )
{
case SID_CURSORHOME:
pTabViewShell->MoveCursorEnd( -1, 0, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSOREND:
pTabViewShell->MoveCursorEnd( 1, 0, SC_FOLLOW_JUMP, bSel, bKeep );
break;
case SID_CURSORTOPOFFILE:
pTabViewShell->MoveCursorEnd( -1, -1, SC_FOLLOW_LINE, bSel, bKeep );
break;
case SID_CURSORENDOFFILE:
pTabViewShell->MoveCursorEnd( 1, 1, SC_FOLLOW_JUMP, bSel, bKeep );
break;
default:
DBG_ERROR("Unbekannte Message bei ViewShell (ExecutePage)");
return;
}
rReq.AppendItem( SfxBoolItem(FN_PARAM_2, bSel) );
rReq.Done();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbfunc2.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:54:33 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include "dbfunc.hxx"
#include "docsh.hxx"
#include "global.hxx"
#include "document.hxx"
#include "sc.hrc"
#include "globstr.hrc"
// STATIC DATA -----------------------------------------------------------
#ifdef WNT
#pragma optimize ( "", off )
#endif
//==================================================================
class ScDrawLayer;
class ScChartCollection;
// wg. CLOOKs in dbfunc4:
USHORT DoUpdateCharts( ScAddress aPos, ScDocument* pDoc,
Window* pActiveWin, BOOL bAllCharts );
void ScDBFunc::UpdateCharts( BOOL bAllCharts )
{
USHORT nFound = 0;
ScViewData* pViewData = GetViewData();
ScDocument* pDoc = pViewData->GetDocument();
if ( pDoc->GetDrawLayer() )
nFound = DoUpdateCharts( ScAddress( pViewData->GetCurX(),
pViewData->GetCurY(),
pViewData->GetTabNo()),
pDoc,
GetActiveWin(),
bAllCharts );
if ( !nFound && !bAllCharts )
ErrorMessage(STR_NOCHARTATCURSOR);
}
<commit_msg>INTEGRATION: CWS dr48 (1.2.176); FILE MERGED 2006/05/23 16:50:04 nn 1.2.176.1: #133060# DoUpdateCharts: static member<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbfunc2.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-07-10 14:09:45 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include "dbfunc.hxx"
#include "docsh.hxx"
#include "global.hxx"
#include "document.hxx"
#include "sc.hrc"
#include "globstr.hrc"
// STATIC DATA -----------------------------------------------------------
#ifdef WNT
#pragma optimize ( "", off )
#endif
//==================================================================
class ScDrawLayer;
class ScChartCollection;
void ScDBFunc::UpdateCharts( BOOL bAllCharts )
{
USHORT nFound = 0;
ScViewData* pViewData = GetViewData();
ScDocument* pDoc = pViewData->GetDocument();
if ( pDoc->GetDrawLayer() )
nFound = DoUpdateCharts( ScAddress( pViewData->GetCurX(),
pViewData->GetCurY(),
pViewData->GetTabNo()),
pDoc,
GetActiveWin(),
bAllCharts );
if ( !nFound && !bAllCharts )
ErrorMessage(STR_NOCHARTATCURSOR);
}
<|endoftext|> |
<commit_before><commit_msg>remove unnecessary check<commit_after><|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/test/ui_test_utils.h"
#include "base/json_reader.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/dom_operation_notification_details.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#if defined(TOOLKIT_VIEWS)
#include "views/focus/accelerator_handler.h"
#endif
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace ui_test_utils {
namespace {
// Used to block until a navigation completes.
class NavigationNotificationObserver : public NotificationObserver {
public:
NavigationNotificationObserver(NavigationController* controller,
int number_of_navigations)
: navigation_started_(false),
navigations_completed_(0),
number_of_navigations_(number_of_navigations) {
registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
Source<NavigationController>(controller));
registrar_.Add(this, NotificationType::LOAD_START,
Source<NavigationController>(controller));
registrar_.Add(this, NotificationType::LOAD_STOP,
Source<NavigationController>(controller));
RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::NAV_ENTRY_COMMITTED ||
type == NotificationType::LOAD_START) {
navigation_started_ = true;
} else if (type == NotificationType::LOAD_STOP) {
if (navigation_started_ &&
++navigations_completed_ == number_of_navigations_) {
navigation_started_ = false;
MessageLoopForUI::current()->Quit();
}
}
}
private:
NotificationRegistrar registrar_;
// If true the navigation has started.
bool navigation_started_;
// The number of navigations that have been completed.
int navigations_completed_;
// The number of navigations to wait for.
int number_of_navigations_;
DISALLOW_COPY_AND_ASSIGN(NavigationNotificationObserver);
};
class DOMOperationObserver : public NotificationObserver {
public:
explicit DOMOperationObserver(RenderViewHost* render_view_host) {
registrar_.Add(this, NotificationType::DOM_OPERATION_RESPONSE,
Source<RenderViewHost>(render_view_host));
RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::DOM_OPERATION_RESPONSE);
Details<DomOperationNotificationDetails> dom_op_details(details);
response_ = dom_op_details->json();
MessageLoopForUI::current()->Quit();
}
std::string response() const { return response_; }
private:
NotificationRegistrar registrar_;
std::string response_;
DISALLOW_COPY_AND_ASSIGN(DOMOperationObserver);
};
// DownloadsCompleteObserver waits for a given number of downloads to complete.
// Example usage:
//
// ui_test_utils::NavigateToURL(browser(), zip_url);
// DownloadsCompleteObserver wait_on_download(
// browser()->profile()->GetDownloadManager(), 1);
// /* |zip_url| download will be complete by this line. */
//
class DownloadsCompleteObserver : public DownloadManager::Observer,
public DownloadItem::Observer {
public:
explicit DownloadsCompleteObserver(DownloadManager* download_manager,
size_t wait_count)
: download_manager_(download_manager),
wait_count_(wait_count),
waiting_(false) {
download_manager_->AddObserver(this);
}
// CheckAllDownloadsComplete will be called when the DownloadManager
// fires it's ModelChanged() call, and also when incomplete downloads
// fire their OnDownloadUpdated().
bool CheckAllDownloadsComplete() {
if (downloads_.size() < wait_count_)
return false;
bool still_waiting = false;
std::vector<DownloadItem*>::iterator it = downloads_.begin();
for (; it != downloads_.end(); ++it) {
// We always remove ourselves as an observer, then re-add if the download
// isn't complete. This is to avoid having to track which downloads we
// are currently observing. Removing has no effect if we are not currently
// an observer.
(*it)->RemoveObserver(this);
if ((*it)->state() != DownloadItem::COMPLETE) {
(*it)->AddObserver(this);
still_waiting = true;
}
}
if (still_waiting)
return false;
download_manager_->RemoveObserver(this);
// waiting_ will have been set if not all downloads were complete on first
// pass below in SetDownloads().
if (waiting_)
MessageLoopForUI::current()->Quit();
return true;
}
// DownloadItem::Observer
virtual void OnDownloadUpdated(DownloadItem* download) {
if (download->state() == DownloadItem::COMPLETE) {
CheckAllDownloadsComplete();
}
}
virtual void OnDownloadOpened(DownloadItem* download) {}
// DownloadManager::Observer
virtual void ModelChanged() {
download_manager_->GetDownloads(this, L"");
}
virtual void SetDownloads(std::vector<DownloadItem*>& downloads) {
downloads_ = downloads;
if (CheckAllDownloadsComplete())
return;
if (!waiting_) {
waiting_ = true;
ui_test_utils::RunMessageLoop();
}
}
private:
// The observed download manager.
DownloadManager* download_manager_;
// The current downloads being tracked.
std::vector<DownloadItem*> downloads_;
// The number of downloads to wait on completing.
size_t wait_count_;
// Whether an internal message loop has been started and must be quit upon
// all downloads completing.
bool waiting_;
DISALLOW_COPY_AND_ASSIGN(DownloadsCompleteObserver);
};
// Used to block until an application modal dialog is shown.
class AppModalDialogObserver : public NotificationObserver {
public:
AppModalDialogObserver() {}
AppModalDialog* WaitForAppModalDialog() {
registrar_.Add(this, NotificationType::APP_MODAL_DIALOG_SHOWN,
NotificationService::AllSources());
dialog_ = NULL;
ui_test_utils::RunMessageLoop();
DCHECK(dialog_);
return dialog_;
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::APP_MODAL_DIALOG_SHOWN) {
registrar_.Remove(this, NotificationType::APP_MODAL_DIALOG_SHOWN,
NotificationService::AllSources());
dialog_ = Source<AppModalDialog>(source).ptr();
MessageLoopForUI::current()->Quit();
} else {
NOTREACHED();
}
}
private:
NotificationRegistrar registrar_;
AppModalDialog* dialog_;
DISALLOW_COPY_AND_ASSIGN(AppModalDialogObserver);
};
template <class T>
class SimpleNotificationObserver : public NotificationObserver {
public:
SimpleNotificationObserver(NotificationType notification_type,
T* source) {
registrar_.Add(this, notification_type, Source<T>(source));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(SimpleNotificationObserver);
};
} // namespace
void RunMessageLoop() {
MessageLoopForUI* loop = MessageLoopForUI::current();
bool did_allow_task_nesting = loop->NestableTasksAllowed();
loop->SetNestableTasksAllowed(true);
#if defined(TOOLKIT_VIEWS)
views::AcceleratorHandler handler;
loop->Run(&handler);
#elif defined(OS_LINUX)
loop->Run(NULL);
#else
loop->Run();
#endif
loop->SetNestableTasksAllowed(did_allow_task_nesting);
}
bool GetCurrentTabTitle(const Browser* browser, string16* title) {
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return false;
NavigationEntry* last_entry = tab_contents->controller().GetActiveEntry();
if (!last_entry)
return false;
title->assign(last_entry->title());
return true;
}
bool WaitForNavigationInCurrentTab(Browser* browser) {
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return false;
WaitForNavigation(&tab_contents->controller());
return true;
}
bool WaitForNavigationsInCurrentTab(Browser* browser,
int number_of_navigations) {
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return false;
WaitForNavigations(&tab_contents->controller(), number_of_navigations);
return true;
}
void WaitForNavigation(NavigationController* controller) {
WaitForNavigations(controller, 1);
}
void WaitForNavigations(NavigationController* controller,
int number_of_navigations) {
NavigationNotificationObserver observer(controller, number_of_navigations);
}
void WaitForNewTab(Browser* browser) {
SimpleNotificationObserver<Browser>
new_tab_observer(NotificationType::TAB_ADDED, browser);
}
void WaitForLoadStop(NavigationController* controller) {
SimpleNotificationObserver<NavigationController>
new_tab_observer(NotificationType::LOAD_STOP, controller);
}
void NavigateToURL(Browser* browser, const GURL& url) {
NavigateToURLBlockUntilNavigationsComplete(browser, url, 1);
}
void NavigateToURLBlockUntilNavigationsComplete(Browser* browser,
const GURL& url,
int number_of_navigations) {
NavigationController* controller =
&browser->GetSelectedTabContents()->controller();
browser->OpenURL(url, GURL(), CURRENT_TAB, PageTransition::TYPED);
WaitForNavigations(controller, number_of_navigations);
}
Value* ExecuteJavaScript(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& original_script) {
// TODO(jcampan): we should make the domAutomationController not require an
// automation id.
std::wstring script = L"window.domAutomationController.setAutomationId(0);" +
original_script;
render_view_host->ExecuteJavascriptInWebFrame(frame_xpath, script);
DOMOperationObserver dom_op_observer(render_view_host);
std::string json = dom_op_observer.response();
// Wrap |json| in an array before deserializing because valid JSON has an
// array or an object as the root.
json.insert(0, "[");
json.append("]");
scoped_ptr<Value> root_val(JSONReader::Read(json, true));
if (!root_val->IsType(Value::TYPE_LIST))
return NULL;
ListValue* list = static_cast<ListValue*>(root_val.get());
Value* result;
if (!list || !list->GetSize() ||
!list->Remove(0, &result)) // Remove gives us ownership of the value.
return NULL;
return result;
}
bool ExecuteJavaScriptAndExtractInt(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& script,
int* result) {
DCHECK(result);
scoped_ptr<Value> value(ExecuteJavaScript(render_view_host, frame_xpath,
script));
if (!value.get())
return false;
return value->GetAsInteger(result);
}
bool ExecuteJavaScriptAndExtractBool(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& script,
bool* result) {
DCHECK(result);
scoped_ptr<Value> value(ExecuteJavaScript(render_view_host, frame_xpath,
script));
if (!value.get())
return false;
return value->GetAsBoolean(result);
}
bool ExecuteJavaScriptAndExtractString(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& script,
std::string* result) {
DCHECK(result);
scoped_ptr<Value> value(ExecuteJavaScript(render_view_host, frame_xpath,
script));
if (!value.get())
return false;
return value->GetAsString(result);
}
GURL GetTestUrl(const std::wstring& dir, const std::wstring file) {
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.Append(FilePath::FromWStringHack(dir));
path = path.Append(FilePath::FromWStringHack(file));
return net::FilePathToFileURL(path);
}
void WaitForDownloadCount(DownloadManager* download_manager, size_t count) {
DownloadsCompleteObserver download_observer(download_manager, count);
}
AppModalDialog* WaitForAppModalDialog() {
AppModalDialogObserver observer;
return observer.WaitForAppModalDialog();
}
void CrashTab(TabContents* tab) {
RenderProcessHost* rph = tab->render_view_host()->process();
base::KillProcess(rph->process().handle(), 0, false);
SimpleNotificationObserver<RenderProcessHost>
crash_observer(NotificationType::RENDERER_PROCESS_CLOSED, rph);
}
void WaitForFocusChange(RenderViewHost* rvh) {
SimpleNotificationObserver<RenderViewHost>
focus_observer(NotificationType::FOCUS_CHANGED_IN_PAGE, rvh);
}
void WaitForFocusInBrowser(Browser* browser) {
SimpleNotificationObserver<Browser>
focus_observer(NotificationType::FOCUS_RETURNED_TO_BROWSER,
browser);
}
} // namespace ui_test_utils
<commit_msg>Coverity: Initialize dialog_ in the constructor.<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/test/ui_test_utils.h"
#include <vector>
#include "base/json_reader.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/dom_operation_notification_details.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#if defined(TOOLKIT_VIEWS)
#include "views/focus/accelerator_handler.h"
#endif
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace ui_test_utils {
namespace {
// Used to block until a navigation completes.
class NavigationNotificationObserver : public NotificationObserver {
public:
NavigationNotificationObserver(NavigationController* controller,
int number_of_navigations)
: navigation_started_(false),
navigations_completed_(0),
number_of_navigations_(number_of_navigations) {
registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
Source<NavigationController>(controller));
registrar_.Add(this, NotificationType::LOAD_START,
Source<NavigationController>(controller));
registrar_.Add(this, NotificationType::LOAD_STOP,
Source<NavigationController>(controller));
RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::NAV_ENTRY_COMMITTED ||
type == NotificationType::LOAD_START) {
navigation_started_ = true;
} else if (type == NotificationType::LOAD_STOP) {
if (navigation_started_ &&
++navigations_completed_ == number_of_navigations_) {
navigation_started_ = false;
MessageLoopForUI::current()->Quit();
}
}
}
private:
NotificationRegistrar registrar_;
// If true the navigation has started.
bool navigation_started_;
// The number of navigations that have been completed.
int navigations_completed_;
// The number of navigations to wait for.
int number_of_navigations_;
DISALLOW_COPY_AND_ASSIGN(NavigationNotificationObserver);
};
class DOMOperationObserver : public NotificationObserver {
public:
explicit DOMOperationObserver(RenderViewHost* render_view_host) {
registrar_.Add(this, NotificationType::DOM_OPERATION_RESPONSE,
Source<RenderViewHost>(render_view_host));
RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::DOM_OPERATION_RESPONSE);
Details<DomOperationNotificationDetails> dom_op_details(details);
response_ = dom_op_details->json();
MessageLoopForUI::current()->Quit();
}
std::string response() const { return response_; }
private:
NotificationRegistrar registrar_;
std::string response_;
DISALLOW_COPY_AND_ASSIGN(DOMOperationObserver);
};
// DownloadsCompleteObserver waits for a given number of downloads to complete.
// Example usage:
//
// ui_test_utils::NavigateToURL(browser(), zip_url);
// DownloadsCompleteObserver wait_on_download(
// browser()->profile()->GetDownloadManager(), 1);
// /* |zip_url| download will be complete by this line. */
//
class DownloadsCompleteObserver : public DownloadManager::Observer,
public DownloadItem::Observer {
public:
explicit DownloadsCompleteObserver(DownloadManager* download_manager,
size_t wait_count)
: download_manager_(download_manager),
wait_count_(wait_count),
waiting_(false) {
download_manager_->AddObserver(this);
}
// CheckAllDownloadsComplete will be called when the DownloadManager
// fires it's ModelChanged() call, and also when incomplete downloads
// fire their OnDownloadUpdated().
bool CheckAllDownloadsComplete() {
if (downloads_.size() < wait_count_)
return false;
bool still_waiting = false;
std::vector<DownloadItem*>::iterator it = downloads_.begin();
for (; it != downloads_.end(); ++it) {
// We always remove ourselves as an observer, then re-add if the download
// isn't complete. This is to avoid having to track which downloads we
// are currently observing. Removing has no effect if we are not currently
// an observer.
(*it)->RemoveObserver(this);
if ((*it)->state() != DownloadItem::COMPLETE) {
(*it)->AddObserver(this);
still_waiting = true;
}
}
if (still_waiting)
return false;
download_manager_->RemoveObserver(this);
// waiting_ will have been set if not all downloads were complete on first
// pass below in SetDownloads().
if (waiting_)
MessageLoopForUI::current()->Quit();
return true;
}
// DownloadItem::Observer
virtual void OnDownloadUpdated(DownloadItem* download) {
if (download->state() == DownloadItem::COMPLETE) {
CheckAllDownloadsComplete();
}
}
virtual void OnDownloadOpened(DownloadItem* download) {}
// DownloadManager::Observer
virtual void ModelChanged() {
download_manager_->GetDownloads(this, L"");
}
virtual void SetDownloads(std::vector<DownloadItem*>& downloads) {
downloads_ = downloads;
if (CheckAllDownloadsComplete())
return;
if (!waiting_) {
waiting_ = true;
ui_test_utils::RunMessageLoop();
}
}
private:
// The observed download manager.
DownloadManager* download_manager_;
// The current downloads being tracked.
std::vector<DownloadItem*> downloads_;
// The number of downloads to wait on completing.
size_t wait_count_;
// Whether an internal message loop has been started and must be quit upon
// all downloads completing.
bool waiting_;
DISALLOW_COPY_AND_ASSIGN(DownloadsCompleteObserver);
};
// Used to block until an application modal dialog is shown.
class AppModalDialogObserver : public NotificationObserver {
public:
AppModalDialogObserver() : dialog_(NULL) {}
AppModalDialog* WaitForAppModalDialog() {
registrar_.Add(this, NotificationType::APP_MODAL_DIALOG_SHOWN,
NotificationService::AllSources());
dialog_ = NULL;
ui_test_utils::RunMessageLoop();
DCHECK(dialog_);
return dialog_;
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::APP_MODAL_DIALOG_SHOWN) {
registrar_.Remove(this, NotificationType::APP_MODAL_DIALOG_SHOWN,
NotificationService::AllSources());
dialog_ = Source<AppModalDialog>(source).ptr();
MessageLoopForUI::current()->Quit();
} else {
NOTREACHED();
}
}
private:
NotificationRegistrar registrar_;
AppModalDialog* dialog_;
DISALLOW_COPY_AND_ASSIGN(AppModalDialogObserver);
};
template <class T>
class SimpleNotificationObserver : public NotificationObserver {
public:
SimpleNotificationObserver(NotificationType notification_type,
T* source) {
registrar_.Add(this, notification_type, Source<T>(source));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(SimpleNotificationObserver);
};
} // namespace
void RunMessageLoop() {
MessageLoopForUI* loop = MessageLoopForUI::current();
bool did_allow_task_nesting = loop->NestableTasksAllowed();
loop->SetNestableTasksAllowed(true);
#if defined(TOOLKIT_VIEWS)
views::AcceleratorHandler handler;
loop->Run(&handler);
#elif defined(OS_LINUX)
loop->Run(NULL);
#else
loop->Run();
#endif
loop->SetNestableTasksAllowed(did_allow_task_nesting);
}
bool GetCurrentTabTitle(const Browser* browser, string16* title) {
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return false;
NavigationEntry* last_entry = tab_contents->controller().GetActiveEntry();
if (!last_entry)
return false;
title->assign(last_entry->title());
return true;
}
bool WaitForNavigationInCurrentTab(Browser* browser) {
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return false;
WaitForNavigation(&tab_contents->controller());
return true;
}
bool WaitForNavigationsInCurrentTab(Browser* browser,
int number_of_navigations) {
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return false;
WaitForNavigations(&tab_contents->controller(), number_of_navigations);
return true;
}
void WaitForNavigation(NavigationController* controller) {
WaitForNavigations(controller, 1);
}
void WaitForNavigations(NavigationController* controller,
int number_of_navigations) {
NavigationNotificationObserver observer(controller, number_of_navigations);
}
void WaitForNewTab(Browser* browser) {
SimpleNotificationObserver<Browser>
new_tab_observer(NotificationType::TAB_ADDED, browser);
}
void WaitForLoadStop(NavigationController* controller) {
SimpleNotificationObserver<NavigationController>
new_tab_observer(NotificationType::LOAD_STOP, controller);
}
void NavigateToURL(Browser* browser, const GURL& url) {
NavigateToURLBlockUntilNavigationsComplete(browser, url, 1);
}
void NavigateToURLBlockUntilNavigationsComplete(Browser* browser,
const GURL& url,
int number_of_navigations) {
NavigationController* controller =
&browser->GetSelectedTabContents()->controller();
browser->OpenURL(url, GURL(), CURRENT_TAB, PageTransition::TYPED);
WaitForNavigations(controller, number_of_navigations);
}
Value* ExecuteJavaScript(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& original_script) {
// TODO(jcampan): we should make the domAutomationController not require an
// automation id.
std::wstring script = L"window.domAutomationController.setAutomationId(0);" +
original_script;
render_view_host->ExecuteJavascriptInWebFrame(frame_xpath, script);
DOMOperationObserver dom_op_observer(render_view_host);
std::string json = dom_op_observer.response();
// Wrap |json| in an array before deserializing because valid JSON has an
// array or an object as the root.
json.insert(0, "[");
json.append("]");
scoped_ptr<Value> root_val(JSONReader::Read(json, true));
if (!root_val->IsType(Value::TYPE_LIST))
return NULL;
ListValue* list = static_cast<ListValue*>(root_val.get());
Value* result;
if (!list || !list->GetSize() ||
!list->Remove(0, &result)) // Remove gives us ownership of the value.
return NULL;
return result;
}
bool ExecuteJavaScriptAndExtractInt(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& script,
int* result) {
DCHECK(result);
scoped_ptr<Value> value(ExecuteJavaScript(render_view_host, frame_xpath,
script));
if (!value.get())
return false;
return value->GetAsInteger(result);
}
bool ExecuteJavaScriptAndExtractBool(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& script,
bool* result) {
DCHECK(result);
scoped_ptr<Value> value(ExecuteJavaScript(render_view_host, frame_xpath,
script));
if (!value.get())
return false;
return value->GetAsBoolean(result);
}
bool ExecuteJavaScriptAndExtractString(RenderViewHost* render_view_host,
const std::wstring& frame_xpath,
const std::wstring& script,
std::string* result) {
DCHECK(result);
scoped_ptr<Value> value(ExecuteJavaScript(render_view_host, frame_xpath,
script));
if (!value.get())
return false;
return value->GetAsString(result);
}
GURL GetTestUrl(const std::wstring& dir, const std::wstring file) {
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.Append(FilePath::FromWStringHack(dir));
path = path.Append(FilePath::FromWStringHack(file));
return net::FilePathToFileURL(path);
}
void WaitForDownloadCount(DownloadManager* download_manager, size_t count) {
DownloadsCompleteObserver download_observer(download_manager, count);
}
AppModalDialog* WaitForAppModalDialog() {
AppModalDialogObserver observer;
return observer.WaitForAppModalDialog();
}
void CrashTab(TabContents* tab) {
RenderProcessHost* rph = tab->render_view_host()->process();
base::KillProcess(rph->process().handle(), 0, false);
SimpleNotificationObserver<RenderProcessHost>
crash_observer(NotificationType::RENDERER_PROCESS_CLOSED, rph);
}
void WaitForFocusChange(RenderViewHost* rvh) {
SimpleNotificationObserver<RenderViewHost>
focus_observer(NotificationType::FOCUS_CHANGED_IN_PAGE, rvh);
}
void WaitForFocusInBrowser(Browser* browser) {
SimpleNotificationObserver<Browser>
focus_observer(NotificationType::FOCUS_RETURNED_TO_BROWSER,
browser);
}
} // namespace ui_test_utils
<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include <memory> // unique_ptr
#include <set>
#include <utility> // pair
#include <sdd/sdd.hh>
#include "mc/live.hh"
#include "mc/post.hh"
#include "mc/pre.hh"
#include "mc/work.hh"
namespace pnmc { namespace mc {
namespace chrono = std::chrono;
typedef sdd::conf1 sdd_conf;
typedef sdd::SDD<sdd_conf> SDD;
typedef sdd::homomorphism<sdd_conf> homomorphism;
using sdd::Composition;
using sdd::Fixpoint;
using sdd::Sum;
using sdd::ValuesFunction;
/*------------------------------------------------------------------------------------------------*/
struct mk_order_visitor
: public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>>
{
// Place: base case of the recursion, there's no more possible nested hierarchies.
std::pair<std::string, sdd::order_builder<sdd_conf>>
operator()(const pn::place* p)
const noexcept
{
return make_pair(p->id, sdd::order_builder<sdd_conf>());
}
// Hierarchy.
std::pair<std::string, sdd::order_builder<sdd_conf>>
operator()(const pn::module_node& m)
const noexcept
{
sdd::order_builder<sdd_conf> ob;
for (const auto& h : m.nested)
{
const auto res = boost::apply_visitor(mk_order_visitor(), *h);
ob.push(res.first, res.second);
}
return make_pair(m.id , ob);
}
};
/*------------------------------------------------------------------------------------------------*/
sdd::order<sdd_conf>
mk_order(const pn::net& net)
{
if (net.modules)
{
return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(), *net.modules).second);
}
else
{
sdd::order_builder<sdd_conf> ob;
for (const auto& place : net.places())
{
ob.push(place.id);
}
return sdd::order<sdd_conf>(ob);
}
}
/*------------------------------------------------------------------------------------------------*/
SDD
initial_state(const sdd::order<sdd_conf>& order, const pn::net& net)
{
return SDD(order, [&](const std::string& id)
-> sdd::values::flat_set<unsigned int>
{
return {net.places().find(id)->marking};
});
}
/*------------------------------------------------------------------------------------------------*/
homomorphism
transition_relation( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o
, const pn::net& net, boost::dynamic_bitset<>& transitions_bitset)
{
chrono::time_point<chrono::system_clock> start;
chrono::time_point<chrono::system_clock> end;
std::size_t elapsed;
start = chrono::system_clock::now();
std::set<homomorphism> operands;
operands.insert(sdd::Id<sdd_conf>());
for (const auto& transition : net.transitions())
{
homomorphism h_t = sdd::Id<sdd_conf>();
if (conf.compute_dead_transitions)
{
if (not transition.post.empty())
{
const auto f = ValuesFunction<sdd_conf>( o, transition.post.begin()->first
, live(transition.index, transitions_bitset));
h_t = sdd::carrier(o, transition.post.begin()->first, f);
}
}
// post actions.
for (const auto& arc : transition.post)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, post(arc.second));
h_t = Composition(h_t, sdd::carrier(o, arc.first, f));
}
// pre actions.
for (const auto& arc : transition.pre)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre(arc.second));
h_t = Composition(h_t, sdd::carrier(o, arc.first, f));
}
operands.insert(h_t);
}
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Transition relation time: " << elapsed << "s" << std::endl;
}
start = chrono::system_clock::now();
const auto res = sdd::rewrite(Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend())), o);
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Rewrite time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
SDD
state_space( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, SDD m
, homomorphism h)
{
chrono::time_point<chrono::system_clock> start = chrono::system_clock::now();
const auto res = h(o, m);
chrono::time_point<chrono::system_clock> end = chrono::system_clock::now();
const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "State space computation time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
void
work(const conf::pnmc_configuration& conf, const pn::net& net)
{
auto manager = sdd::manager<sdd_conf>::init();
boost::dynamic_bitset<> transitions_bitset(net.transitions().size());
const sdd::order<sdd_conf>& o = mk_order(net);
if (conf.show_order)
{
std::cout << o << std::endl;
}
const SDD m0 = initial_state(o, net);
const homomorphism h = transition_relation(conf, o, net, transitions_bitset);
if (conf.show_relation)
{
std::cout << h << std::endl;
}
const SDD m = state_space(conf, o, m0, h);
const auto n = sdd::count_combinations(m);
long double n_prime = n.template convert_to<long double>();
std::cout << n_prime << " states" << std::endl;
if (conf.compute_dead_transitions)
{
std::deque<std::string> dead_transitions;
for (auto i = 0; i < net.transitions().size(); ++i)
{
if (not transitions_bitset[i])
{
dead_transitions.push_back(net.get_transition_by_index(i).id);
}
}
std::cout << dead_transitions.size() << " dead transitions." << std::endl;
if (not dead_transitions.empty())
{
std::copy( dead_transitions.cbegin(), std::prev(dead_transitions.cend())
, std::ostream_iterator<std::string>(std::cout, ","));
std::cout << *std::prev(dead_transitions.cend());
}
}
if (conf.show_hash_tables_stats)
{
std::cout << manager << std::endl;
}
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::mc
<commit_msg>Improve output of dead transitions.<commit_after>#include <chrono>
#include <iostream>
#include <memory> // unique_ptr
#include <set>
#include <utility> // pair
#include <sdd/sdd.hh>
#include "mc/live.hh"
#include "mc/post.hh"
#include "mc/pre.hh"
#include "mc/work.hh"
namespace pnmc { namespace mc {
namespace chrono = std::chrono;
typedef sdd::conf1 sdd_conf;
typedef sdd::SDD<sdd_conf> SDD;
typedef sdd::homomorphism<sdd_conf> homomorphism;
using sdd::Composition;
using sdd::Fixpoint;
using sdd::Sum;
using sdd::ValuesFunction;
/*------------------------------------------------------------------------------------------------*/
struct mk_order_visitor
: public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>>
{
// Place: base case of the recursion, there's no more possible nested hierarchies.
std::pair<std::string, sdd::order_builder<sdd_conf>>
operator()(const pn::place* p)
const noexcept
{
return make_pair(p->id, sdd::order_builder<sdd_conf>());
}
// Hierarchy.
std::pair<std::string, sdd::order_builder<sdd_conf>>
operator()(const pn::module_node& m)
const noexcept
{
sdd::order_builder<sdd_conf> ob;
for (const auto& h : m.nested)
{
const auto res = boost::apply_visitor(mk_order_visitor(), *h);
ob.push(res.first, res.second);
}
return make_pair(m.id , ob);
}
};
/*------------------------------------------------------------------------------------------------*/
sdd::order<sdd_conf>
mk_order(const pn::net& net)
{
if (net.modules)
{
return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(), *net.modules).second);
}
else
{
sdd::order_builder<sdd_conf> ob;
for (const auto& place : net.places())
{
ob.push(place.id);
}
return sdd::order<sdd_conf>(ob);
}
}
/*------------------------------------------------------------------------------------------------*/
SDD
initial_state(const sdd::order<sdd_conf>& order, const pn::net& net)
{
return SDD(order, [&](const std::string& id)
-> sdd::values::flat_set<unsigned int>
{
return {net.places().find(id)->marking};
});
}
/*------------------------------------------------------------------------------------------------*/
homomorphism
transition_relation( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o
, const pn::net& net, boost::dynamic_bitset<>& transitions_bitset)
{
chrono::time_point<chrono::system_clock> start;
chrono::time_point<chrono::system_clock> end;
std::size_t elapsed;
start = chrono::system_clock::now();
std::set<homomorphism> operands;
operands.insert(sdd::Id<sdd_conf>());
for (const auto& transition : net.transitions())
{
homomorphism h_t = sdd::Id<sdd_conf>();
if (conf.compute_dead_transitions)
{
if (not transition.post.empty())
{
const auto f = ValuesFunction<sdd_conf>( o, transition.post.begin()->first
, live(transition.index, transitions_bitset));
h_t = sdd::carrier(o, transition.post.begin()->first, f);
}
}
// post actions.
for (const auto& arc : transition.post)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, post(arc.second));
h_t = Composition(h_t, sdd::carrier(o, arc.first, f));
}
// pre actions.
for (const auto& arc : transition.pre)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre(arc.second));
h_t = Composition(h_t, sdd::carrier(o, arc.first, f));
}
operands.insert(h_t);
}
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Transition relation time: " << elapsed << "s" << std::endl;
}
start = chrono::system_clock::now();
const auto res = sdd::rewrite(Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend())), o);
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Rewrite time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
SDD
state_space( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, SDD m
, homomorphism h)
{
chrono::time_point<chrono::system_clock> start = chrono::system_clock::now();
const auto res = h(o, m);
chrono::time_point<chrono::system_clock> end = chrono::system_clock::now();
const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "State space computation time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
void
work(const conf::pnmc_configuration& conf, const pn::net& net)
{
auto manager = sdd::manager<sdd_conf>::init();
boost::dynamic_bitset<> transitions_bitset(net.transitions().size());
const sdd::order<sdd_conf>& o = mk_order(net);
if (conf.show_order)
{
std::cout << o << std::endl;
}
const SDD m0 = initial_state(o, net);
const homomorphism h = transition_relation(conf, o, net, transitions_bitset);
if (conf.show_relation)
{
std::cout << h << std::endl;
}
const SDD m = state_space(conf, o, m0, h);
const auto n = sdd::count_combinations(m);
std::cout << n.template convert_to<long double>() << " states" << std::endl;
if (conf.compute_dead_transitions)
{
std::deque<std::string> dead_transitions;
for (auto i = 0; i < net.transitions().size(); ++i)
{
if (not transitions_bitset[i])
{
dead_transitions.push_back(net.get_transition_by_index(i).id);
}
}
if (not dead_transitions.empty())
{
std::cout << dead_transitions.size() << " dead transition(s): ";
std::copy( dead_transitions.cbegin(), std::prev(dead_transitions.cend())
, std::ostream_iterator<std::string>(std::cout, ","));
std::cout << *std::prev(dead_transitions.cend()) << std::endl;
}
else
{
std::cout << "No dead transitions" << std::endl;
}
}
if (conf.show_hash_tables_stats)
{
std::cout << manager << std::endl;
}
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::mc
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <poll.h>
#include "tcp.h"
/******************
* tcp crap
*/
int tcp_read(int sd, char *buf, int len) {
struct pollfd pfd;
pfd.fd = sd;
pfd.events = POLLIN | POLLHUP | POLLRDHUP | POLLNVAL | POLLERR;
while (len > 0) {
if (poll(&pfd, 1, -1) < 0)
return -1;
if (!(pfd.revents & POLLIN))
return -1;
/*
* although we turn on the MSG_DONTWAIT flag, we don't expect
* receivng an EAGAIN, as we polled on the socket, so there
* should be data waiting for us.
*/
int got = ::recv( sd, buf, len, MSG_DONTWAIT );
if (got <= 0) {
//char buf[100];
//generic_dout(0) << "tcp_read socket " << sd << " returned " << got
//<< " errno " << errno << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
return -1;
}
len -= got;
buf += got;
//generic_dout(DBL) << "tcp_read got " << got << ", " << len << " left" << dendl;
}
return len;
}
int tcp_write(int sd, const char *buf, int len) {
struct pollfd pfd;
pfd.fd = sd;
pfd.events = POLLOUT | POLLHUP | POLLRDHUP | POLLNVAL | POLLERR;
if (poll(&pfd, 1, -1) < 0)
return -1;
if (!(pfd.revents & POLLOUT))
return -1;
//generic_dout(DBL) << "tcp_write writing " << len << dendl;
assert(len > 0);
while (len > 0) {
int did = ::send( sd, buf, len, MSG_NOSIGNAL );
if (did < 0) {
//generic_dout(1) << "tcp_write error did = " << did << " errno " << errno << " " << strerror(errno) << dendl;
//generic_derr(1) << "tcp_write error did = " << did << " errno " << errno << " " << strerror(errno) << dendl;
return did;
}
len -= did;
buf += did;
//generic_dout(DBL) << "tcp_write did " << did << ", " << len << " left" << dendl;
}
return 0;
}
int tcp_hostlookup(char *str, sockaddr_in& ta)
{
char *host = str;
char *port = 0;
for (int i=0; str[i]; i++) {
if (str[i] == ':') {
port = str+i+1;
str[i] = 0;
break;
}
}
if (!port) {
cerr << "addr '" << str << "' doesn't look like 'host:port'" << std::endl;
return -1;
}
//cout << "host '" << host << "' port '" << port << "'" << std::endl;
int iport = atoi(port);
struct hostent *myhostname = gethostbyname( host );
if (!myhostname) {
cerr << "host " << host << " not found" << std::endl;
return -1;
}
memset(&ta, 0, sizeof(ta));
//cout << "addrtype " << myhostname->h_addrtype << " len " << myhostname->h_length << std::endl;
ta.sin_family = myhostname->h_addrtype;
memcpy((char *)&ta.sin_addr,
myhostname->h_addr,
myhostname->h_length);
ta.sin_port = iport;
cout << "lookup '" << host << ":" << port << "' -> " << ta << std::endl;
return 0;
}
<commit_msg>msgr: fail on sd < 0<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include <poll.h>
#include "tcp.h"
/******************
* tcp crap
*/
int tcp_read(int sd, char *buf, int len) {
if (sd < 0)
return -1;
struct pollfd pfd;
pfd.fd = sd;
pfd.events = POLLIN | POLLHUP | POLLRDHUP | POLLNVAL | POLLERR;
while (len > 0) {
if (poll(&pfd, 1, -1) < 0)
return -1;
if (!(pfd.revents & POLLIN))
return -1;
/*
* although we turn on the MSG_DONTWAIT flag, we don't expect
* receivng an EAGAIN, as we polled on the socket, so there
* should be data waiting for us.
*/
int got = ::recv( sd, buf, len, MSG_DONTWAIT );
if (got <= 0) {
//char buf[100];
//generic_dout(0) << "tcp_read socket " << sd << " returned " << got
//<< " errno " << errno << " " << strerror_r(errno, buf, sizeof(buf)) << dendl;
return -1;
}
len -= got;
buf += got;
//generic_dout(DBL) << "tcp_read got " << got << ", " << len << " left" << dendl;
}
return len;
}
int tcp_write(int sd, const char *buf, int len) {
if (sd < 0)
return -1;
struct pollfd pfd;
pfd.fd = sd;
pfd.events = POLLOUT | POLLHUP | POLLRDHUP | POLLNVAL | POLLERR;
if (poll(&pfd, 1, -1) < 0)
return -1;
if (!(pfd.revents & POLLOUT))
return -1;
//generic_dout(DBL) << "tcp_write writing " << len << dendl;
assert(len > 0);
while (len > 0) {
int did = ::send( sd, buf, len, MSG_NOSIGNAL );
if (did < 0) {
//generic_dout(1) << "tcp_write error did = " << did << " errno " << errno << " " << strerror(errno) << dendl;
//generic_derr(1) << "tcp_write error did = " << did << " errno " << errno << " " << strerror(errno) << dendl;
return did;
}
len -= did;
buf += did;
//generic_dout(DBL) << "tcp_write did " << did << ", " << len << " left" << dendl;
}
return 0;
}
int tcp_hostlookup(char *str, sockaddr_in& ta)
{
char *host = str;
char *port = 0;
for (int i=0; str[i]; i++) {
if (str[i] == ':') {
port = str+i+1;
str[i] = 0;
break;
}
}
if (!port) {
cerr << "addr '" << str << "' doesn't look like 'host:port'" << std::endl;
return -1;
}
//cout << "host '" << host << "' port '" << port << "'" << std::endl;
int iport = atoi(port);
struct hostent *myhostname = gethostbyname( host );
if (!myhostname) {
cerr << "host " << host << " not found" << std::endl;
return -1;
}
memset(&ta, 0, sizeof(ta));
//cout << "addrtype " << myhostname->h_addrtype << " len " << myhostname->h_length << std::endl;
ta.sin_family = myhostname->h_addrtype;
memcpy((char *)&ta.sin_addr,
myhostname->h_addr,
myhostname->h_length);
ta.sin_port = iport;
cout << "lookup '" << host << ":" << port << "' -> " << ta << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// #include <stdio.h>
// #include <stdlib.h>
#include <ext/stdio_filebuf.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iostream>
#include <DumpFile.hh>
void message() {
std::cout << "Usage: frontend <number>" << std::endl;
}
//
// Here is the entity responsible to translating dump file
// field type names into a meaningful nanocube schema
//
struct NanoCubeSchema {
NanoCubeSchema(dumpfile::DumpFileDescription &dump_file_description):
dump_file_description(dump_file_description)
{
std::stringstream ss_dimensions_spec;
std::stringstream ss_variables_spec;
for (dumpfile::Field *field: dump_file_description.fields) {
std::string field_type_name = field->field_type.name;
std::cout << field_type_name << std::endl;
if (field_type_name.find("nc_dim_cat_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_bytes = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "categorical dimension with " << num_bytes << " bytes" << std::endl;
ss_dimensions_spec << "_c" << num_bytes;
}
else if (field_type_name.find("nc_dim_quadtree_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_levels = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "quadtree dimension with " << num_levels << " levels" << std::endl;
ss_dimensions_spec << "_q" << num_levels;
}
else if (field_type_name.find("nc_dim_time_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_bytes = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "time dimension with " << num_bytes << " bytes" << std::endl;
ss_variables_spec << "_u" << num_bytes;
}
else if (field_type_name.find("nc_var_uint_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_bytes = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "time dimension with " << num_bytes << " bytes" << std::endl;
ss_variables_spec << "_u" << num_bytes;
}
this->dimensions_spec = ss_dimensions_spec.str();
this->time_and_variables_spec = ss_variables_spec.str();
}
}
std::string dimensions_spec;
std::string time_and_variables_spec;
dumpfile::DumpFileDescription &dump_file_description;
};
//
// d stands for dimension
//
// cX = categorical, X = num bytes
// qX = quadtree, X = num levels
// tX = time, X = num bytes
//
// v stands for variable
//
// uX = unsigned int of X bytes
//
int main(int argc, char **argv)
{
// get process id
// pid_t my_pid = getpid();
// std::cout << argv[0] << " process id: " << my_pid << std::endl;
std::cout << "VERSION: " << VERSION << std::endl;
// read input file description
dumpfile::DumpFileDescription input_file_description;
std::cin >> input_file_description;
// read schema
NanoCubeSchema nc_schema(input_file_description);
std::cout << "Dimensions: " << nc_schema.dimensions_spec << std::endl;
std::cout << "Variables: " << nc_schema.time_and_variables_spec << std::endl;
//
// TODO: run some tests
//
// (1) is there a single time column
// (2) are all field types starting with nc_ prefix
//
// pipe
int pipe_one[2];
int &pipe_read_file_descriptor = pipe_one[0];
int &pipe_write_file_descriptor = pipe_one[1];
// create pipe
if(pipe(pipe_one) == -1)
{
std::cout << "Couldn't create pipe!" << std::endl;
// perror("ERROR");
exit(127);
}
// Spawn a child to run the program.
pid_t pid = fork();
if (pid == 0) { /* child process */
/* Close unused pipe */
close(pipe_write_file_descriptor);
/* both file descriptors refer to pipe_read_file_descriptor */
/* std::cin becomes the pipe read channel */
dup2(pipe_read_file_descriptor, STDIN_FILENO);
// exec new process
std::string program_name;
{
std::stringstream ss;
const char* binaries_path_ptr = std::getenv("NANOCUBE_BIN");
if (binaries_path_ptr) {
std::string binaries_path(binaries_path_ptr);
if (binaries_path.size() > 0 && binaries_path.back() != '/') {
binaries_path = binaries_path + "/";
}
ss << binaries_path;
}
else {
ss << "./";
}
ss << "nc" << nc_schema.dimensions_spec << nc_schema.time_and_variables_spec;
program_name = ss.str();
}
// child process will be replaced by this other process
// could we do thi in the main process? maybe
//execlp(program_name.c_str(), program_name.c_str(), NULL);
execv(program_name.c_str(), argv);
// failed to execute program
std::cout << "Could not find program: " << program_name << std::endl;
exit(127); /* only if execv fails */
}
else {
/* Close unused pipe */
// close(pipe_read_file_descriptor);
/* Attach pipe write file to stdout */
// dup2(pipe_write_file_descriptor, STDOUT_FILENO);
// std::ostream &os = std::cout;
// int posix_handle = ::_fileno(::fopen("test.txt", "r"));
// output stream
__gnu_cxx::stdio_filebuf<char> filebuf(pipe_write_file_descriptor, std::ios::out);
std::ostream os(&filebuf); // 1
// std::ofdstream pipe_output_stream(pipe_write_file_descriptor);
// restream the schema
os << input_file_description;
// pipe_output_stream << input_file_description;
// signal that data is going to come
os << std::endl;
// pipe_output_stream << std::endl;
// write everything coming from stdin to child process
const int BUFFER_SIZE = 4095;
char buffer[BUFFER_SIZE + 1];
while (1) {
std::cin.read(buffer,BUFFER_SIZE);
if (!std::cin) {
int gcount = std::cin.gcount();
if (gcount > 0) {
// std::string st(&buffer[0], &buffer[gcount]);
// std::replace( st.begin(), st.end(), '\n', 'L');
// std::out << "server writes > " << st << std::endl;
os.write(buffer, gcount);
}
break;
}
else {
os.write(buffer, BUFFER_SIZE);
// std::string st(&buffer[0], &buffer[BUFFER_SIZE]);
// std::replace( st.begin(), st.end(), '\n', 'L');
// std::cerr << "server writes > " << st << std::endl;
}
}
// clear
os.flush();
//
// std::cerr << "Waiting for child process to finish" << std::endl;
// done writing on the pipe
close(pipe_write_file_descriptor);
//
waitpid(pid,0,0); /* wait for child to exit */
}
return 0;
}
#if 0
int number;
try
{
if (argc < 2) throw std::exception();
number = std::stoi(argv[1]);
}
catch(std::exception &e)
{
message();
exit(0);
}
/*Spawn a child to run the program.*/
// pid_t pid=fork();
// if (pid==0) { /* child process */
std::string program_name;
{
std::stringstream ss;
ss << "/Users/lauro/tests/fork-exec/backend_" << number;
program_name = ss.str();
}
static char *other_argv[] = {"backend", NULL};
// child process will be replaced by this other process
// could we do thi in the main process? maybe
execv(program_name.c_str(), other_argv);
// failed to execute program
std::cout << "Could not find program: " << program_name << std::endl;
exit(127); /* only if execv fails */
// }
// else { /* pid!=0; parent process */
// waitpid(pid,0,0); /* wait for child to exit */
// }
return 0;
#endif
/*<@>
<@> ******** Program output: ********
<@> Foo is my name.
<@> */
<commit_msg>more portable, if less efficient, version of pipe redirection<commit_after>#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iostream>
#include <DumpFile.hh>
void message() {
std::cout << "Usage: frontend <number>" << std::endl;
}
//
// Here is the entity responsible to translating dump file
// field type names into a meaningful nanocube schema
//
struct NanoCubeSchema {
NanoCubeSchema(dumpfile::DumpFileDescription &dump_file_description):
dump_file_description(dump_file_description)
{
std::stringstream ss_dimensions_spec;
std::stringstream ss_variables_spec;
for (dumpfile::Field *field: dump_file_description.fields) {
std::string field_type_name = field->field_type.name;
std::cout << field_type_name << std::endl;
if (field_type_name.find("nc_dim_cat_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_bytes = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "categorical dimension with " << num_bytes << " bytes" << std::endl;
ss_dimensions_spec << "_c" << num_bytes;
}
else if (field_type_name.find("nc_dim_quadtree_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_levels = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "quadtree dimension with " << num_levels << " levels" << std::endl;
ss_dimensions_spec << "_q" << num_levels;
}
else if (field_type_name.find("nc_dim_time_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_bytes = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "time dimension with " << num_bytes << " bytes" << std::endl;
ss_variables_spec << "_u" << num_bytes;
}
else if (field_type_name.find("nc_var_uint_") == 0) {
auto pos = field_type_name.begin() + field_type_name.rfind('_');
int num_bytes = std::stoi(std::string(pos+1,field_type_name.end()));
std::cout << "time dimension with " << num_bytes << " bytes" << std::endl;
ss_variables_spec << "_u" << num_bytes;
}
this->dimensions_spec = ss_dimensions_spec.str();
this->time_and_variables_spec = ss_variables_spec.str();
}
}
std::string dimensions_spec;
std::string time_and_variables_spec;
dumpfile::DumpFileDescription &dump_file_description;
};
//
// d stands for dimension
//
// cX = categorical, X = num bytes
// qX = quadtree, X = num levels
// tX = time, X = num bytes
//
// v stands for variable
//
// uX = unsigned int of X bytes
//
int main(int argc, char **argv)
{
// get process id
// pid_t my_pid = getpid();
// std::cout << argv[0] << " process id: " << my_pid << std::endl;
std::cout << "VERSION: " << VERSION << std::endl;
// read input file description
dumpfile::DumpFileDescription input_file_description;
std::cin >> input_file_description;
// read schema
NanoCubeSchema nc_schema(input_file_description);
std::cout << "Dimensions: " << nc_schema.dimensions_spec << std::endl;
std::cout << "Variables: " << nc_schema.time_and_variables_spec << std::endl;
//
// TODO: run some tests
//
// (1) is there a single time column
// (2) are all field types starting with nc_ prefix
//
// pipe
int pipe_one[2];
int &pipe_read_file_descriptor = pipe_one[0];
int &pipe_write_file_descriptor = pipe_one[1];
// create pipe
if(pipe(pipe_one) == -1)
{
std::cout << "Couldn't create pipe!" << std::endl;
// perror("ERROR");
exit(127);
}
// Spawn a child to run the program.
pid_t pid = fork();
if (pid == 0) { /* child process */
/* Close unused pipe */
close(pipe_write_file_descriptor);
/* both file descriptors refer to pipe_read_file_descriptor */
/* std::cin becomes the pipe read channel */
dup2(pipe_read_file_descriptor, STDIN_FILENO);
// exec new process
std::string program_name;
{
std::stringstream ss;
const char* binaries_path_ptr = std::getenv("NANOCUBE_BIN");
if (binaries_path_ptr) {
std::string binaries_path(binaries_path_ptr);
if (binaries_path.size() > 0 && binaries_path.back() != '/') {
binaries_path = binaries_path + "/";
}
ss << binaries_path;
}
else {
ss << "./";
}
ss << "nc" << nc_schema.dimensions_spec << nc_schema.time_and_variables_spec;
program_name = ss.str();
}
// child process will be replaced by this other process
// could we do thi in the main process? maybe
//execlp(program_name.c_str(), program_name.c_str(), NULL);
execv(program_name.c_str(), argv);
// failed to execute program
std::cout << "Could not find program: " << program_name << std::endl;
exit(127); /* only if execv fails */
}
else {
std::stringstream ss;
ss << input_file_description;
ss << std::endl;
std::string contents = ss.str();
FILE *f = fdopen(pipe_write_file_descriptor, "w");
fwrite((void*) contents.c_str(),1 , contents.size(), f);
// write everything coming from stdin to child process
const int BUFFER_SIZE = 4095;
char buffer[BUFFER_SIZE + 1];
while (1) {
std::cin.read(buffer,BUFFER_SIZE);
if (!std::cin) {
int gcount = std::cin.gcount();
if (gcount > 0) {
fwrite((void*) buffer, 1, gcount, f);
}
break;
}
else {
fwrite((void*) buffer, 1, BUFFER_SIZE, f);
}
}
// clear
fflush(f);
//
// std::cerr << "Waiting for child process to finish" << std::endl;
// done writing on the pipe
fclose(f);
close(pipe_write_file_descriptor);
//
waitpid(pid,0,0); /* wait for child to exit */
}
return 0;
}
#if 0
int number;
try
{
if (argc < 2) throw std::exception();
number = std::stoi(argv[1]);
}
catch(std::exception &e)
{
message();
exit(0);
}
/*Spawn a child to run the program.*/
// pid_t pid=fork();
// if (pid==0) { /* child process */
std::string program_name;
{
std::stringstream ss;
ss << "/Users/lauro/tests/fork-exec/backend_" << number;
program_name = ss.str();
}
static char *other_argv[] = {"backend", NULL};
// child process will be replaced by this other process
// could we do thi in the main process? maybe
execv(program_name.c_str(), other_argv);
// failed to execute program
std::cout << "Could not find program: " << program_name << std::endl;
exit(127); /* only if execv fails */
// }
// else { /* pid!=0; parent process */
// waitpid(pid,0,0); /* wait for child to exit */
// }
return 0;
#endif
/*<@>
<@> ******** Program output: ********
<@> Foo is my name.
<@> */
<|endoftext|> |
<commit_before>/***********************************************************************
query.cpp - Implements the Query class.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the CREDITS
file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "query.h"
#include "connection.h"
namespace mysqlpp {
Query::Query(const Query& q) :
std::ostream(0),
OptionalExceptions(q.throw_exceptions()),
Lockable(q.locked()),
def(q.def),
conn_(q.conn_),
success_(q.success_)
{
init(&sbuffer_);
}
Query&
Query::operator=(const Query& rhs)
{
set_exceptions(rhs.throw_exceptions());
set_lock(rhs.locked());
def = rhs.def;
conn_ = rhs.conn_;
success_ = rhs.success_;
return *this;
}
my_ulonglong Query::affected_rows() const
{
return conn_->affected_rows();
}
std::string Query::error()
{
return conn_->error();
}
bool Query::exec(const std::string& str)
{
success_ = !mysql_real_query(&conn_->mysql_, str.c_str(),
static_cast<unsigned long>(str.length()));
if (!success_ && throw_exceptions()) {
throw BadQuery(error());
}
else {
return success_;
}
}
ResNSel Query::execute(const char* str)
{
success_ = false;
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return ResNSel();
}
}
success_ = !mysql_query(&conn_->mysql_, str);
unlock();
if (success_) {
return ResNSel(conn_);
}
else {
if (throw_exceptions()) {
throw BadQuery(error());
}
else {
return ResNSel();
}
}
}
#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.
ResNSel Query::execute(SQLQueryParms& p)
{
query_reset r = parse_elems_.size() ? DONT_RESET : RESET_QUERY;
return execute(str(p, r).c_str());
}
#endif // !defined(DOXYGEN_IGNORE)
std::string Query::info()
{
return conn_->info();
}
my_ulonglong Query::insert_id()
{
return conn_->insert_id();
}
bool Query::lock()
{
return conn_->lock();
}
bool Query::more_results()
{
#if MYSQL_VERSION_ID > 41000 // only in MySQL v4.1 +
return mysql_more_results(&conn_->mysql_);
#else
return false;
#endif
}
void Query::parse()
{
std::string str = "";
char num[4];
std::string name;
char *s, *s0;
s0 = s = preview_char();
while (*s) {
if (*s == '%') {
// Following might be a template parameter declaration...
s++;
if (*s == '%') {
// Doubled percent sign, so insert literal percent sign.
str += *s++;
}
else if (isdigit(*s)) {
// Number following percent sign, so it signifies a
// positional parameter. First step: find position
// value, up to 3 digits long.
num[0] = *s;
s++;
if (isdigit(*s)) {
num[1] = *s;
num[2] = 0;
s++;
if (isdigit(*s)) {
num[2] = *s;
num[3] = 0;
s++;
}
else {
num[2] = 0;
}
}
else {
num[1] = 0;
}
short int n = atoi(num);
// Look for option character following position value.
char option = ' ';
if (*s == 'q' || *s == 'Q' || *s == 'r' || *s == 'R') {
option = *s++;
}
// Is it a named parameter?
if (*s == ':') {
// Save all alphanumeric and underscore characters
// following colon as parameter name.
s++;
for (/* */; isalnum(*s) || *s == '_'; ++s) {
name += *s;
}
// Eat trailing colon, if it's present.
if (*s == ':') {
s++;
}
// Update maps that translate parameter name to
// number and vice versa.
if (n >= static_cast<short>(parsed_names_.size())) {
parsed_names_.insert(parsed_names_.end(),
static_cast<std::vector<std::string>::size_type>(
n + 1) - parsed_names_.size(),
std::string());
}
parsed_names_[n] = name;
parsed_nums_[name] = n;
}
// Finished parsing parameter; save it.
parse_elems_.push_back(SQLParseElement(str, option, char(n)));
str = "";
name = "";
}
else {
// Insert literal percent sign, because sign didn't
// precede a valid parameter string; this allows users
// to play a little fast and loose with the rules,
// avoiding a double percent sign here.
str += '%';
}
}
else {
// Regular character, so just copy it.
str += *s++;
}
}
parse_elems_.push_back(SQLParseElement(str, ' ', -1));
delete[] s0;
}
SQLString*
Query::pprepare(char option, SQLString& S, bool replace)
{
if (S.processed) {
return &S;
}
if (option == 'r' || (option == 'q' && S.is_string)) {
char *s = new char[S.size() * 2 + 1];
mysql_real_escape_string(&conn_->mysql_, s, S.c_str(),
static_cast<unsigned long>(S.size()));
SQLString *ss = new SQLString("'");
*ss += s;
*ss += "'";
delete[] s;
if (replace) {
S = *ss;
S.processed = true;
delete ss;
return &S;
}
else {
return ss;
}
}
else if (option == 'R' || (option == 'Q' && S.is_string)) {
SQLString *ss = new SQLString("'" + S + "'");
if (replace) {
S = *ss;
S.processed = true;
delete ss;
return &S;
}
else {
return ss;
}
}
else {
if (replace) {
S.processed = true;
}
return &S;
}
}
char* Query::preview_char()
{
*this << std::ends;
size_t length = sbuffer_.str().size();
char* s = new char[length + 1];
strncpy(s, sbuffer_.str().c_str(), length);
s[length] = '\0';
return s;
}
void Query::proc(SQLQueryParms& p)
{
sbuffer_.str("");
char num;
SQLString* ss;
SQLQueryParms* c;
for (std::vector<SQLParseElement>::iterator i = parse_elems_.begin();
i != parse_elems_.end(); ++i) {
dynamic_cast<std::ostream&>(*this) << i->before;
num = i->num;
if (num != -1) {
if (num < static_cast<int>(p.size()))
c = &p;
else if (num < static_cast<int>(def.size()))
c = &def;
else {
*this << " ERROR";
throw BadParamCount(
"Not enough parameters to fill the template.");
}
ss = pprepare(i->option, (*c)[num], c->bound());
dynamic_cast<std::ostream&>(*this) << *ss;
if (!c->bound()) {
// Returned pointer is to dynamically allocated object,
// so it's our responsibility to release it. (The other
// possibility is that pprepare() simply overwrote
// (*c)[num], instead of allocating new memory.)
delete ss;
}
}
}
}
void Query::reset()
{
seekp(0);
clear();
sbuffer_.str("");
parse_elems_.clear();
def.clear();
}
Result Query::store(const char* str)
{
success_ = false;
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return Result();
}
}
success_ = !mysql_query(&conn_->mysql_, str);
if (success_) {
MYSQL_RES* res = mysql_store_result(&conn_->mysql_);
if (res) {
unlock();
return Result(res, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
// Notice that we do not throw an exception if we just get a null
// result set, but no error. This happens when using store() on a
// query that may not return results. Obviously it's better to use
// exec*() in this situation, but it's not outright illegal, and
// sometimes you have to do it.
if (conn_->errnum() && throw_exceptions()) {
throw BadQuery(error());
}
else {
return Result();
}
}
#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.
Result Query::store(SQLQueryParms& p)
{
query_reset r = parse_elems_.size() ? DONT_RESET : RESET_QUERY;
return store(str(p, r).c_str());
}
#endif // !defined(DOXYGEN_IGNORE)
Result Query::store_next()
{
#if MYSQL_VERSION_ID > 41000 // only in MySQL v4.1 +
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return Result();
}
}
int ret;
if ((ret = mysql_next_result(&conn_->mysql_)) == 0) {
// There are more results, so return next result set.
MYSQL_RES* res = mysql_store_result(&conn_->mysql_);
unlock();
if (res) {
return Result(res, throw_exceptions());
}
else {
// Result set is null, but throw an exception only i it is
// null because of some error. If not, it's just an empty
// result set, which is harmless. We return an empty result
// set if exceptions are disabled, as well.
if (conn_->errnum() && throw_exceptions()) {
throw BadQuery(error());
}
else {
return Result();
}
}
}
else {
// No more results, or some other error occurred.
unlock();
if (throw_exceptions()) {
if (ret > 0) {
throw BadQuery(error());
}
else {
throw EndOfResultSets();
}
}
else {
return Result();
}
}
#else
return store();
#endif // MySQL v4.1+
}
std::string Query::str(SQLQueryParms& p)
{
if (!parse_elems_.empty()) {
proc(p);
}
*this << std::ends;
return sbuffer_.str();
}
std::string Query::str(SQLQueryParms& p, query_reset r)
{
std::string tmp = str(p);
if (r == RESET_QUERY) {
reset();
}
return tmp;
}
bool Query::success()
{
return success_ && conn_->success();
}
void Query::unlock()
{
conn_->unlock();
}
ResUse Query::use(const char* str)
{
success_ = false;
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return ResUse();
}
}
success_ = !mysql_query(&conn_->mysql_, str);
if (success_) {
MYSQL_RES* res = mysql_use_result(&conn_->mysql_);
if (res) {
unlock();
return ResUse(res, conn_, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_exceptions()) {
throw BadQuery(error());
}
else {
return ResUse();
}
}
#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.
ResUse Query::use(SQLQueryParms& p)
{
query_reset r = parse_elems_.size() ? DONT_RESET : RESET_QUERY;
return use(str(p, r).c_str());
}
#endif // !defined(DOXYGEN_IGNORE)
} // end namespace mysqlpp
<commit_msg>Query was mistakenly deleting string objects not allocated on the heap in some instances when handling template queries. resetdb in particular wasn't actually working correctly.<commit_after>/***********************************************************************
query.cpp - Implements the Query class.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the CREDITS
file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "query.h"
#include "connection.h"
namespace mysqlpp {
Query::Query(const Query& q) :
std::ostream(0),
OptionalExceptions(q.throw_exceptions()),
Lockable(q.locked()),
def(q.def),
conn_(q.conn_),
success_(q.success_)
{
init(&sbuffer_);
}
Query&
Query::operator=(const Query& rhs)
{
set_exceptions(rhs.throw_exceptions());
set_lock(rhs.locked());
def = rhs.def;
conn_ = rhs.conn_;
success_ = rhs.success_;
return *this;
}
my_ulonglong Query::affected_rows() const
{
return conn_->affected_rows();
}
std::string Query::error()
{
return conn_->error();
}
bool Query::exec(const std::string& str)
{
success_ = !mysql_real_query(&conn_->mysql_, str.c_str(),
static_cast<unsigned long>(str.length()));
if (!success_ && throw_exceptions()) {
throw BadQuery(error());
}
else {
return success_;
}
}
ResNSel Query::execute(const char* str)
{
success_ = false;
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return ResNSel();
}
}
success_ = !mysql_query(&conn_->mysql_, str);
unlock();
if (success_) {
return ResNSel(conn_);
}
else {
if (throw_exceptions()) {
throw BadQuery(error());
}
else {
return ResNSel();
}
}
}
#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.
ResNSel Query::execute(SQLQueryParms& p)
{
query_reset r = parse_elems_.size() ? DONT_RESET : RESET_QUERY;
return execute(str(p, r).c_str());
}
#endif // !defined(DOXYGEN_IGNORE)
std::string Query::info()
{
return conn_->info();
}
my_ulonglong Query::insert_id()
{
return conn_->insert_id();
}
bool Query::lock()
{
return conn_->lock();
}
bool Query::more_results()
{
#if MYSQL_VERSION_ID > 41000 // only in MySQL v4.1 +
return mysql_more_results(&conn_->mysql_);
#else
return false;
#endif
}
void Query::parse()
{
std::string str = "";
char num[4];
std::string name;
char *s, *s0;
s0 = s = preview_char();
while (*s) {
if (*s == '%') {
// Following might be a template parameter declaration...
s++;
if (*s == '%') {
// Doubled percent sign, so insert literal percent sign.
str += *s++;
}
else if (isdigit(*s)) {
// Number following percent sign, so it signifies a
// positional parameter. First step: find position
// value, up to 3 digits long.
num[0] = *s;
s++;
if (isdigit(*s)) {
num[1] = *s;
num[2] = 0;
s++;
if (isdigit(*s)) {
num[2] = *s;
num[3] = 0;
s++;
}
else {
num[2] = 0;
}
}
else {
num[1] = 0;
}
short int n = atoi(num);
// Look for option character following position value.
char option = ' ';
if (*s == 'q' || *s == 'Q' || *s == 'r' || *s == 'R') {
option = *s++;
}
// Is it a named parameter?
if (*s == ':') {
// Save all alphanumeric and underscore characters
// following colon as parameter name.
s++;
for (/* */; isalnum(*s) || *s == '_'; ++s) {
name += *s;
}
// Eat trailing colon, if it's present.
if (*s == ':') {
s++;
}
// Update maps that translate parameter name to
// number and vice versa.
if (n >= static_cast<short>(parsed_names_.size())) {
parsed_names_.insert(parsed_names_.end(),
static_cast<std::vector<std::string>::size_type>(
n + 1) - parsed_names_.size(),
std::string());
}
parsed_names_[n] = name;
parsed_nums_[name] = n;
}
// Finished parsing parameter; save it.
parse_elems_.push_back(SQLParseElement(str, option, char(n)));
str = "";
name = "";
}
else {
// Insert literal percent sign, because sign didn't
// precede a valid parameter string; this allows users
// to play a little fast and loose with the rules,
// avoiding a double percent sign here.
str += '%';
}
}
else {
// Regular character, so just copy it.
str += *s++;
}
}
parse_elems_.push_back(SQLParseElement(str, ' ', -1));
delete[] s0;
}
SQLString*
Query::pprepare(char option, SQLString& S, bool replace)
{
if (S.processed) {
return &S;
}
if (option == 'r' || (option == 'q' && S.is_string)) {
char *s = new char[S.size() * 2 + 1];
mysql_real_escape_string(&conn_->mysql_, s, S.c_str(),
static_cast<unsigned long>(S.size()));
SQLString *ss = new SQLString("'");
*ss += s;
*ss += "'";
delete[] s;
if (replace) {
S = *ss;
S.processed = true;
delete ss;
return &S;
}
else {
return ss;
}
}
else if (option == 'R' || (option == 'Q' && S.is_string)) {
SQLString *ss = new SQLString("'" + S + "'");
if (replace) {
S = *ss;
S.processed = true;
delete ss;
return &S;
}
else {
return ss;
}
}
else {
if (replace) {
S.processed = true;
}
return &S;
}
}
char* Query::preview_char()
{
*this << std::ends;
size_t length = sbuffer_.str().size();
char* s = new char[length + 1];
strncpy(s, sbuffer_.str().c_str(), length);
s[length] = '\0';
return s;
}
void Query::proc(SQLQueryParms& p)
{
sbuffer_.str("");
for (std::vector<SQLParseElement>::iterator i = parse_elems_.begin();
i != parse_elems_.end(); ++i) {
dynamic_cast<std::ostream&>(*this) << i->before;
int num = i->num;
if (num != -1) {
SQLQueryParms* c;
if (num < p.size()) {
c = &p;
}
else if (num < def.size()) {
c = &def;
}
else {
*this << " ERROR";
throw BadParamCount(
"Not enough parameters to fill the template.");
}
SQLString& param = (*c)[num];
SQLString* ss = pprepare(i->option, param, c->bound());
dynamic_cast<std::ostream&>(*this) << *ss;
if (ss != ¶m) {
// pprepare() returned a new string object instead of
// updating param in place, so we need to delete it.
delete ss;
}
}
}
}
void Query::reset()
{
seekp(0);
clear();
sbuffer_.str("");
parse_elems_.clear();
def.clear();
}
Result Query::store(const char* str)
{
success_ = false;
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return Result();
}
}
success_ = !mysql_query(&conn_->mysql_, str);
if (success_) {
MYSQL_RES* res = mysql_store_result(&conn_->mysql_);
if (res) {
unlock();
return Result(res, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
// Notice that we do not throw an exception if we just get a null
// result set, but no error. This happens when using store() on a
// query that may not return results. Obviously it's better to use
// exec*() in this situation, but it's not outright illegal, and
// sometimes you have to do it.
if (conn_->errnum() && throw_exceptions()) {
throw BadQuery(error());
}
else {
return Result();
}
}
#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.
Result Query::store(SQLQueryParms& p)
{
query_reset r = parse_elems_.size() ? DONT_RESET : RESET_QUERY;
return store(str(p, r).c_str());
}
#endif // !defined(DOXYGEN_IGNORE)
Result Query::store_next()
{
#if MYSQL_VERSION_ID > 41000 // only in MySQL v4.1 +
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return Result();
}
}
int ret;
if ((ret = mysql_next_result(&conn_->mysql_)) == 0) {
// There are more results, so return next result set.
MYSQL_RES* res = mysql_store_result(&conn_->mysql_);
unlock();
if (res) {
return Result(res, throw_exceptions());
}
else {
// Result set is null, but throw an exception only i it is
// null because of some error. If not, it's just an empty
// result set, which is harmless. We return an empty result
// set if exceptions are disabled, as well.
if (conn_->errnum() && throw_exceptions()) {
throw BadQuery(error());
}
else {
return Result();
}
}
}
else {
// No more results, or some other error occurred.
unlock();
if (throw_exceptions()) {
if (ret > 0) {
throw BadQuery(error());
}
else {
throw EndOfResultSets();
}
}
else {
return Result();
}
}
#else
return store();
#endif // MySQL v4.1+
}
std::string Query::str(SQLQueryParms& p)
{
if (!parse_elems_.empty()) {
proc(p);
}
*this << std::ends;
return sbuffer_.str();
}
std::string Query::str(SQLQueryParms& p, query_reset r)
{
std::string tmp = str(p);
if (r == RESET_QUERY) {
reset();
}
return tmp;
}
bool Query::success()
{
return success_ && conn_->success();
}
void Query::unlock()
{
conn_->unlock();
}
ResUse Query::use(const char* str)
{
success_ = false;
if (lock()) {
if (throw_exceptions()) {
throw LockFailed();
}
else {
return ResUse();
}
}
success_ = !mysql_query(&conn_->mysql_, str);
if (success_) {
MYSQL_RES* res = mysql_use_result(&conn_->mysql_);
if (res) {
unlock();
return ResUse(res, conn_, throw_exceptions());
}
}
unlock();
// One of the mysql_* calls failed, so decide how we should fail.
if (throw_exceptions()) {
throw BadQuery(error());
}
else {
return ResUse();
}
}
#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.
ResUse Query::use(SQLQueryParms& p)
{
query_reset r = parse_elems_.size() ? DONT_RESET : RESET_QUERY;
return use(str(p, r).c_str());
}
#endif // !defined(DOXYGEN_IGNORE)
} // end namespace mysqlpp
<|endoftext|> |
<commit_before>#include "ofxDmx.h"
#include "ofMain.h"
#define DMX_PRO_HEADER_SIZE 4
#define DMX_PRO_START_MSG 0x7E
#define DMX_START_CODE 0
#define DMX_START_CODE_SIZE 1
#define DMX_PRO_SEND_PACKET 6 // "periodically send a DMX packet" mode
#define DMX_PRO_END_SIZE 1
#define DMX_PRO_END_MSG 0xE7
ofxDmx::ofxDmx()
:connected(false)
,needsUpdate(false) {
}
ofxDmx::~ofxDmx() {
serial.close();
connected = false;
}
bool ofxDmx::connect(int device, unsigned int channels) {
serial.enumerateDevices();
connected = serial.setup(device, 57600);
setChannels(channels);
return connected;
}
bool ofxDmx::connect(string device, unsigned int channels) {
serial.enumerateDevices();
connected = serial.setup(device.c_str(), 57600);
setChannels(channels);
return connected;
}
bool ofxDmx::isConnected() {
return connected;
}
void ofxDmx::disconnect() {
serial.close();
}
void ofxDmx::setChannels(unsigned int channels) {
levels.resize(ofClamp(channels, 24, 512));
}
void ofxDmx::update(bool force) {
if(needsUpdate || force) {
needsUpdate = false;
unsigned int dataSize = levels.size() + DMX_START_CODE_SIZE;
unsigned int packetSize = DMX_PRO_HEADER_SIZE + dataSize + DMX_PRO_END_SIZE;
vector<unsigned char> packet(packetSize);
// header
packet[0] = DMX_PRO_START_MSG;
packet[1] = DMX_PRO_SEND_PACKET;
packet[2] = dataSize & 0xff; // data length lsb
packet[3] = (dataSize >> 8) & 0xff; // data length msb
// data
packet[4] = DMX_START_CODE; // first data byte
copy(levels.begin(), levels.end(), packet.begin() + 5);
// end
packet[packetSize - 1] = DMX_PRO_END_MSG;
serial.writeBytes(&packet[0], packetSize);
#ifdef OFXDMX_SPEW
cout << "@" << ofGetSystemTime() << endl;
for(int i = 0; i < packetSize; i++) {
cout << setw(2) << hex << (int) packet[i];
if((i + 1) % 8 == 0) {
cout << endl;
}
}
#endif
}
}
bool ofxDmx::badChannel(unsigned int channel) {
if(channel > levels.size()) {
ofLogError() << "Channel " + ofToString(channel) + " is out of bounds. Only " + ofToString(levels.size()) + " channels are available.";
return true;
}
if(channel == 0) {
ofLogError() << "Channel 0 does not exist. DMX channels start at 1.";
return true;
}
return false;
}
void ofxDmx::setLevel(unsigned int channel, unsigned char level) {
if(badChannel(channel)) {
return;
}
channel--; // convert from 1-initial to 0-initial
if(level != levels[channel]) {
levels[channel] = level;
needsUpdate = true;
}
}
void ofxDmx::clear() {
for (int i = 0; i < levels.size(); i++) {
levels[i] = 0;
}
}
unsigned char ofxDmx::getLevel(unsigned int channel) {
if(badChannel(channel)) {
return 0;
}
channel--; // convert from 1-initial to 0-initial
return levels[channel];
}
<commit_msg>Reset the bool connected to false in the method disconnect().<commit_after>#include "ofxDmx.h"
#include "ofMain.h"
#define DMX_PRO_HEADER_SIZE 4
#define DMX_PRO_START_MSG 0x7E
#define DMX_START_CODE 0
#define DMX_START_CODE_SIZE 1
#define DMX_PRO_SEND_PACKET 6 // "periodically send a DMX packet" mode
#define DMX_PRO_END_SIZE 1
#define DMX_PRO_END_MSG 0xE7
ofxDmx::ofxDmx()
:connected(false)
,needsUpdate(false) {
}
ofxDmx::~ofxDmx() {
serial.close();
connected = false;
}
bool ofxDmx::connect(int device, unsigned int channels) {
serial.enumerateDevices();
connected = serial.setup(device, 57600);
setChannels(channels);
return connected;
}
bool ofxDmx::connect(string device, unsigned int channels) {
serial.enumerateDevices();
connected = serial.setup(device.c_str(), 57600);
setChannels(channels);
return connected;
}
bool ofxDmx::isConnected() {
return connected;
}
void ofxDmx::disconnect() {
serial.close();
connected = false;
}
void ofxDmx::setChannels(unsigned int channels) {
levels.resize(ofClamp(channels, 24, 512));
}
void ofxDmx::update(bool force) {
if(needsUpdate || force) {
needsUpdate = false;
unsigned int dataSize = levels.size() + DMX_START_CODE_SIZE;
unsigned int packetSize = DMX_PRO_HEADER_SIZE + dataSize + DMX_PRO_END_SIZE;
vector<unsigned char> packet(packetSize);
// header
packet[0] = DMX_PRO_START_MSG;
packet[1] = DMX_PRO_SEND_PACKET;
packet[2] = dataSize & 0xff; // data length lsb
packet[3] = (dataSize >> 8) & 0xff; // data length msb
// data
packet[4] = DMX_START_CODE; // first data byte
copy(levels.begin(), levels.end(), packet.begin() + 5);
// end
packet[packetSize - 1] = DMX_PRO_END_MSG;
serial.writeBytes(&packet[0], packetSize);
#ifdef OFXDMX_SPEW
cout << "@" << ofGetSystemTime() << endl;
for(int i = 0; i < packetSize; i++) {
cout << setw(2) << hex << (int) packet[i];
if((i + 1) % 8 == 0) {
cout << endl;
}
}
#endif
}
}
bool ofxDmx::badChannel(unsigned int channel) {
if(channel > levels.size()) {
ofLogError() << "Channel " + ofToString(channel) + " is out of bounds. Only " + ofToString(levels.size()) + " channels are available.";
return true;
}
if(channel == 0) {
ofLogError() << "Channel 0 does not exist. DMX channels start at 1.";
return true;
}
return false;
}
void ofxDmx::setLevel(unsigned int channel, unsigned char level) {
if(badChannel(channel)) {
return;
}
channel--; // convert from 1-initial to 0-initial
if(level != levels[channel]) {
levels[channel] = level;
needsUpdate = true;
}
}
void ofxDmx::clear() {
for (int i = 0; i < levels.size(); i++) {
levels[i] = 0;
}
}
unsigned char ofxDmx::getLevel(unsigned int channel) {
if(badChannel(channel)) {
return 0;
}
channel--; // convert from 1-initial to 0-initial
return levels[channel];
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016-2017 deepstreamHub GmbH
*
* 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 <cstdlib>
#include <cstring>
#include <message.hpp>
#include <parser.h>
#include <parser.hpp>
#include <scope_guard.hpp>
#include <use.hpp>
#include <cassert>
bool is_header_token(enum deepstream_token token)
{
int min_event_num = TOKEN_A_A;
return token >= min_event_num;
}
deepstream_parser_state::deepstream_parser_state(const char* p, std::size_t sz):
buffer_(p),
buffer_size_(sz),
tokenizing_header_(true),
offset_(0)
{
assert(buffer_);
}
int deepstream_parser_handle(
deepstream::parser::State* p_state, deepstream_token token,
const char* text, std::size_t textlen)
{
assert( p_state );
return p_state->handle_token(token, text, textlen);
}
int deepstream_parser_state::handle_token(
deepstream_token token, const char* text, std::size_t textlen)
{
assert( text );
assert( textlen > 0 );
assert( token != TOKEN_EOF || *text == '\0' );
assert( token != TOKEN_EOF || textlen == 1 );
assert( token != TOKEN_EOF || offset_ + textlen == buffer_size_ + 1 );
assert( token == TOKEN_EOF || offset_ + textlen <= buffer_size_ );
assert( token == TOKEN_EOF || !std::memcmp(buffer_+offset_, text, textlen));
assert( messages_.size() <= offset_ );
assert( errors_.size() <= offset_ );
DEEPSTREAM_ON_EXIT([this, textlen] () {
this->offset_ += textlen;
} );
if(token == TOKEN_UNKNOWN)
handle_error(token, text, textlen);
else if(token == TOKEN_EOF)
{
assert(offset_ == buffer_size_);
if(!tokenizing_header_)
handle_error(token, text, textlen);
}
else if(token == TOKEN_PAYLOAD)
handle_payload(token, text, textlen);
else if(token == TOKEN_MESSAGE_SEPARATOR)
handle_message_separator(token, text, textlen);
else if( is_header_token(token) )
handle_header(token, text, textlen);
else
{
assert(0);
}
return token;
}
void deepstream_parser_state::handle_error(
deepstream_token token, const char*, std::size_t textlen)
{
using deepstream::parser::Error;
assert( token == TOKEN_EOF || token == TOKEN_UNKNOWN );
assert( textlen > 0 || (textlen == 0 && token == EOF) );
DEEPSTREAM_ON_EXIT( [this] () {
this->tokenizing_header_ = true; // reset parser status on exit
} );
if( token == TOKEN_EOF )
{
assert( !tokenizing_header_ );
assert( !messages_.empty() );
messages_.pop_back();
errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_EOF);
}
if( token == TOKEN_UNKNOWN && tokenizing_header_ )
{
errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_TOKEN);
}
if( token == TOKEN_UNKNOWN && !tokenizing_header_ )
{
assert( !messages_.empty() );
std::size_t msg_start = messages_.back().offset();
std::size_t msg_size = messages_.back().size();
messages_.pop_back();
assert( msg_start + msg_size == offset_ );
errors_.emplace_back(
msg_start, msg_size+textlen, Error::CORRUPT_MESSAGE);
}
}
#define DS_ADD_MSG(...) \
do { \
messages_.emplace_back(buffer_, offset_, textlen, __VA_ARGS__); \
} while(false)
void deepstream_parser_state::handle_header(
deepstream_token token, const char*, std::size_t textlen)
{
using deepstream::Topic;
using deepstream::Action;
DEEPSTREAM_ON_EXIT( [this] () {
this->tokenizing_header_ = false;
} );
switch(token)
{
// avoid compiler warnings [-Wswitch]
case TOKEN_EOF:
case TOKEN_UNKNOWN:
case TOKEN_PAYLOAD:
case TOKEN_MESSAGE_SEPARATOR:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
assert(0);
#pragma clang diagnostic pop
break;
case TOKEN_A_A:
DS_ADD_MSG(Topic::AUTH, Action::REQUEST, true);
break;
case TOKEN_A_E_IAD:
DS_ADD_MSG(Topic::AUTH, Action::ERROR_INVALID_AUTH_DATA, true);
break;
case TOKEN_A_E_TMAA:
DS_ADD_MSG(Topic::AUTH, Action::ERROR_TOO_MANY_AUTH_ATTEMPTS);
break;
case TOKEN_A_REQ:
DS_ADD_MSG(Topic::AUTH, Action::REQUEST);
break;
case TOKEN_E_A_L:
DS_ADD_MSG(Topic::EVENT, Action::LISTEN, true);
break;
case TOKEN_E_A_S:
DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE, true);
break;
case TOKEN_E_L:
DS_ADD_MSG(Topic::EVENT, Action::LISTEN);
break;
case TOKEN_E_S:
DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE);
break;
case TOKEN_E_US:
DS_ADD_MSG(Topic::EVENT, Action::UNSUBSCRIBE);
break;
}
}
void deepstream_parser_state::handle_payload(
deepstream_token token, const char* text, std::size_t textlen)
{
using namespace deepstream::parser;
assert( token == TOKEN_PAYLOAD );
assert( text );
assert( textlen > 0 );
assert( text[0] == ASCII_UNIT_SEPARATOR );
assert( !messages_.empty() );
deepstream::use(token);
deepstream::use(text);
auto& msg = messages_.back();
msg.arguments_.emplace_back(offset_+1, textlen-1);
msg.size_ += textlen;
}
void deepstream_parser_state::handle_message_separator(
deepstream_token token, const char* text, std::size_t textlen)
{
using namespace deepstream::parser;
assert( token == TOKEN_MESSAGE_SEPARATOR );
assert( text );
assert( textlen == 1 );
assert( text[0] == ASCII_RECORD_SEPARATOR );
assert( !messages_.empty() );
deepstream::use(token);
deepstream::use(text);
auto& msg = messages_.back();
msg.size_ += textlen;
std::size_t msg_offset = msg.offset();
std::size_t msg_size = msg.size();
std::size_t num_args = msg.arguments_.size();
const auto& expected_num_args = msg.num_arguments();
std::size_t min_num_args = expected_num_args.first;
std::size_t max_num_args = expected_num_args.second;
if( num_args >= min_num_args && num_args <= max_num_args )
return;
messages_.pop_back();
errors_.emplace_back(
msg_offset, msg_size, Error::INVALID_NUMBER_OF_ARGUMENTS);
}
<commit_msg>Parser: reset status on message separator<commit_after>/*
* Copyright 2016-2017 deepstreamHub GmbH
*
* 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 <cstdlib>
#include <cstring>
#include <message.hpp>
#include <parser.h>
#include <parser.hpp>
#include <scope_guard.hpp>
#include <use.hpp>
#include <cassert>
bool is_header_token(enum deepstream_token token)
{
int min_event_num = TOKEN_A_A;
return token >= min_event_num;
}
deepstream_parser_state::deepstream_parser_state(const char* p, std::size_t sz):
buffer_(p),
buffer_size_(sz),
tokenizing_header_(true),
offset_(0)
{
assert(buffer_);
}
int deepstream_parser_handle(
deepstream::parser::State* p_state, deepstream_token token,
const char* text, std::size_t textlen)
{
assert( p_state );
return p_state->handle_token(token, text, textlen);
}
int deepstream_parser_state::handle_token(
deepstream_token token, const char* text, std::size_t textlen)
{
assert( text );
assert( textlen > 0 );
assert( token != TOKEN_EOF || *text == '\0' );
assert( token != TOKEN_EOF || textlen == 1 );
assert( token != TOKEN_EOF || offset_ + textlen == buffer_size_ + 1 );
assert( token == TOKEN_EOF || offset_ + textlen <= buffer_size_ );
assert( token == TOKEN_EOF || !std::memcmp(buffer_+offset_, text, textlen));
assert( messages_.size() <= offset_ );
assert( errors_.size() <= offset_ );
DEEPSTREAM_ON_EXIT([this, textlen] () {
this->offset_ += textlen;
} );
if(token == TOKEN_UNKNOWN)
handle_error(token, text, textlen);
else if(token == TOKEN_EOF)
{
assert(offset_ == buffer_size_);
if(!tokenizing_header_)
handle_error(token, text, textlen);
}
else if(token == TOKEN_PAYLOAD)
handle_payload(token, text, textlen);
else if(token == TOKEN_MESSAGE_SEPARATOR)
handle_message_separator(token, text, textlen);
else if( is_header_token(token) )
handle_header(token, text, textlen);
else
{
assert(0);
}
return token;
}
void deepstream_parser_state::handle_error(
deepstream_token token, const char*, std::size_t textlen)
{
using deepstream::parser::Error;
assert( token == TOKEN_EOF || token == TOKEN_UNKNOWN );
assert( textlen > 0 || (textlen == 0 && token == EOF) );
DEEPSTREAM_ON_EXIT( [this] () {
this->tokenizing_header_ = true; // reset parser status on exit
} );
if( token == TOKEN_EOF )
{
assert( !tokenizing_header_ );
assert( !messages_.empty() );
messages_.pop_back();
errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_EOF);
}
if( token == TOKEN_UNKNOWN && tokenizing_header_ )
{
errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_TOKEN);
}
if( token == TOKEN_UNKNOWN && !tokenizing_header_ )
{
assert( !messages_.empty() );
std::size_t msg_start = messages_.back().offset();
std::size_t msg_size = messages_.back().size();
messages_.pop_back();
assert( msg_start + msg_size == offset_ );
errors_.emplace_back(
msg_start, msg_size+textlen, Error::CORRUPT_MESSAGE);
}
}
#define DS_ADD_MSG(...) \
do { \
messages_.emplace_back(buffer_, offset_, textlen, __VA_ARGS__); \
} while(false)
void deepstream_parser_state::handle_header(
deepstream_token token, const char*, std::size_t textlen)
{
using deepstream::Topic;
using deepstream::Action;
DEEPSTREAM_ON_EXIT( [this] () {
this->tokenizing_header_ = false;
} );
switch(token)
{
// avoid compiler warnings [-Wswitch]
case TOKEN_EOF:
case TOKEN_UNKNOWN:
case TOKEN_PAYLOAD:
case TOKEN_MESSAGE_SEPARATOR:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
assert(0);
#pragma clang diagnostic pop
break;
case TOKEN_A_A:
DS_ADD_MSG(Topic::AUTH, Action::REQUEST, true);
break;
case TOKEN_A_E_IAD:
DS_ADD_MSG(Topic::AUTH, Action::ERROR_INVALID_AUTH_DATA, true);
break;
case TOKEN_A_E_TMAA:
DS_ADD_MSG(Topic::AUTH, Action::ERROR_TOO_MANY_AUTH_ATTEMPTS);
break;
case TOKEN_A_REQ:
DS_ADD_MSG(Topic::AUTH, Action::REQUEST);
break;
case TOKEN_E_A_L:
DS_ADD_MSG(Topic::EVENT, Action::LISTEN, true);
break;
case TOKEN_E_A_S:
DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE, true);
break;
case TOKEN_E_L:
DS_ADD_MSG(Topic::EVENT, Action::LISTEN);
break;
case TOKEN_E_S:
DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE);
break;
case TOKEN_E_US:
DS_ADD_MSG(Topic::EVENT, Action::UNSUBSCRIBE);
break;
}
}
void deepstream_parser_state::handle_payload(
deepstream_token token, const char* text, std::size_t textlen)
{
using namespace deepstream::parser;
assert( token == TOKEN_PAYLOAD );
assert( text );
assert( textlen > 0 );
assert( text[0] == ASCII_UNIT_SEPARATOR );
assert( !messages_.empty() );
deepstream::use(token);
deepstream::use(text);
auto& msg = messages_.back();
msg.arguments_.emplace_back(offset_+1, textlen-1);
msg.size_ += textlen;
}
void deepstream_parser_state::handle_message_separator(
deepstream_token token, const char* text, std::size_t textlen)
{
using namespace deepstream::parser;
assert( token == TOKEN_MESSAGE_SEPARATOR );
assert( text );
assert( textlen == 1 );
assert( text[0] == ASCII_RECORD_SEPARATOR );
assert( !messages_.empty() );
deepstream::use(token);
deepstream::use(text);
DEEPSTREAM_ON_EXIT( [this] () {
this->tokenizing_header_ = true;
} );
auto& msg = messages_.back();
msg.size_ += textlen;
std::size_t msg_offset = msg.offset();
std::size_t msg_size = msg.size();
std::size_t num_args = msg.arguments_.size();
const auto& expected_num_args = msg.num_arguments();
std::size_t min_num_args = expected_num_args.first;
std::size_t max_num_args = expected_num_args.second;
if( num_args >= min_num_args && num_args <= max_num_args )
return;
messages_.pop_back();
errors_.emplace_back(
msg_offset, msg_size, Error::INVALID_NUMBER_OF_ARGUMENTS);
}
<|endoftext|> |
<commit_before>#include "parser.hpp"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
using namespace std;
map<string,int> init_builtins() {
map<string,int> builtins;
const char *types[] = {"uint8", "uint16", "uint32", "uint64",
"int8", "int16", "int32", "int64",
"float32", "float64",
"time", "duration",
"string"};
const int sizes[] = {1, 2, 4, 8,
1, 2, 4, 8,
4, 8,
8, 8,
-1};
for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); ++i) {
builtins[types[i]] = sizes[i];
}
return builtins;
}
map<string,int> ROSType::builtins_(init_builtins());
void ROSType::populate(const string &type_str) {
name = type_str;
vector<string> fields;
std::string type_field;
boost::split(fields, type_str, boost::is_any_of("/"));
if (fields.size() == 1) {
pkg_name = "";
type_field = fields[0];
} else if (fields.size() == 2) {
pkg_name = fields[0];
type_field = fields[1];
} else {
throw invalid_argument("Bad type string: " + type_str);
}
static const boost::regex array_re("(.+)(\\[([0-9]*)\\])");
boost::smatch what;
if (boost::regex_search(type_field, what, array_re)) {
is_array = true;
msg_name = string(what[1].first, what[1].second);
array_type = string(what[2].first, what[2].second);
if (what.size() == 3) {
array_size = -1;
} else if (what.size() == 4) {
string size(what[3].first, what[3].second);
array_size = size.empty() ? -1 : atoi(size.c_str());
} else {
throw invalid_argument("Bad type string: " + type_str);
}
} else {
is_array = false;
msg_name = type_field;
array_type = "";
array_size = 1;
}
is_builtin = builtins_.count(msg_name) != 0;
if (is_builtin) {
type_size = builtins_[msg_name];
}
if (is_builtin) {
is_qualified = true;
base_type = msg_name;
} else if (!pkg_name.empty()) {
is_qualified = true;
base_type = pkg_name + string("/") + msg_name;
} else {
is_qualified = false;
base_type = msg_name;
}
}
void ROSMessageFields::populate(const string &msg_def) {
static const boost::regex newline_re("\\n+");
static const boost::regex whitespace_re("\\s+");
vector<string> lines;
boost::split_regex(lines, msg_def, newline_re);
int start_ind = 0;
if (boost::starts_with(lines[0], "MSG:")) {
vector<string> parts;
boost::split_regex(parts, lines[0], whitespace_re);
type_.populate(parts[1]);
start_ind = 1;
} else {
type_.name = "0-root";
type_.base_type = "0-root";
type_.msg_name = "";
type_.pkg_name = "0-root";
type_.array_type = "";
type_.is_array = false;
type_.is_qualified = true;
type_.is_builtin = false;
type_.array_size = 1;
}
boost::smatch what;
for (size_t l = start_ind; l < lines.size(); ++l) {
if (lines[l].size() == 0 ||
boost::starts_with(lines[l], "#") ||
boost::regex_match(lines[l], what, whitespace_re)) {
continue;
}
vector<string> elements;
boost::split_regex(elements, lines[l], whitespace_re);
if (elements.size() != 2) {
throw invalid_argument("Bad line in message def: %s" + lines[l]);
}
fields_.push_back(Field(elements[1]));
fields_.back().type.populate(elements[0]);
}
}
void ROSMessageFields::setFieldPkgName(int i, const std::string &pkg_name) {
ROSType &type = fields_.at(i).type;
type.pkg_name = pkg_name;
type.base_type = type.pkg_name + string("/") + type.msg_name;
type.is_qualified = true;
}
ROSTypeMap::~ROSTypeMap() {
for (map<string, ROSMessageFields*>::iterator it = type_map_.begin();
it != type_map_.end();
++it) {
delete (*it).second;
}
}
void ROSTypeMap::populate(const string &msg_def) {
// Split into disparate message type definitions
std::vector<std::string> split;
boost::regex msg_sep_re("=+\\n+");
boost::split_regex(split, msg_def, msg_sep_re);
// Parse individual message types and make map from msg_name -> qualified name
std::vector<ROSMessageFields*> types(split.size());
for (size_t i = 0; i < split.size(); ++i) {
ROSMessageFields *rmt = new ROSMessageFields();
try {
rmt->populate(split[i]);
} catch (exception &e) {
delete rmt;
throw;
}
if (!rmt->type().is_qualified) {
throw invalid_argument("Couldn't determine type in message:\n" +
split[i] + "\nFull message def is:\n" + msg_def);
}
type_map_[rmt->type().name] = rmt;
resolver_[rmt->type().msg_name].push_back(rmt->type().pkg_name);
}
for (map<string, ROSMessageFields*>::iterator it = type_map_.begin();
it != type_map_.end();
++it) {
ROSMessageFields *rmt = (*it).second;
for (int i = 0; i < rmt->nfields(); ++i) {
const ROSMessageFields::Field &field = rmt->at(i);
if (!field.type.is_qualified) {
const vector<string> qualified_names = resolver_[field.type.msg_name];
if (qualified_names.size() == 1) {
rmt->setFieldPkgName(i, qualified_names[0]);
} else {
throw invalid_argument("Multiple types for " + field.type.msg_name +
"\nMessage def: \n" + msg_def);
}
}
}
}
}
const ROSMessageFields* ROSTypeMap::getMsgFields(const string &msg_type) const {
if (type_map_.count(msg_type) != 0) {
return type_map_[msg_type];
} else {
return NULL;
}
}
ROSMessage::ROSMessage(const ROSType &type)
: bytes_(0), size_(0), type_(type) {
}
ROSMessage::~ROSMessage() {
for (map<string, vector<ROSMessage*> >::iterator it = fields_.begin();
it != fields_.end();
++it) {
for (vector<ROSMessage*>::iterator mit = (*it).second.begin();
mit != (*it).second.end();
++mit) {
delete (*mit);
}
}
}
uint32_t read_uint32(const uint8_t *bytes, int *beg) {
uint32_t val = reinterpret_cast<const uint32_t*>(bytes + *beg)[0];
*beg += 4;
return val;
}
vector<const ROSMessage*> ROSMessage::getField(const std::string key) const {
vector<const ROSMessage*> field;
if (fields_.count(key) != 0) {
field.assign(fields_[key].begin(), fields_[key].end());
}
return field;
}
void ROSMessage::populate(const ROSTypeMap &types, const uint8_t *bytes, int *beg) {
if (type_.is_builtin) {
int array_len = type_.array_size;
if (array_len == -1) {
array_len = read_uint32(bytes, beg);
}
for (int array_ind = 0; array_ind < array_len; ++array_ind) {
int elem_size = type_.type_size;
if (elem_size == -1) {
elem_size = read_uint32(bytes, beg);
}
bytes_.push_back(std::vector<uint8_t>(elem_size));
std::vector<uint8_t> &element = bytes_.back();
for (size_t i = 0; i < element.size(); ++i) {
element[i] = bytes[*beg + i];
}
*beg += elem_size;
size_ += elem_size;
}
} else {
const ROSMessageFields *mt = types.getMsgFields(type_.base_type);
if (mt == NULL) {
throw invalid_argument("Couldn't populate fields");
}
for (int i = 0; i < mt->nfields(); ++i) {
const ROSMessageFields::Field &field = mt->at(i);
int array_len = field.type.is_builtin ? 1 : field.type.array_size;
if (array_len == -1) {
array_len = read_uint32(bytes, beg);
}
for (int array_ind = 0; array_ind < array_len; ++array_ind) {
ROSMessage *msg = new ROSMessage(field.type);
fields_[field.name].push_back(msg);
// If populate throws, msg will be freed as it's in fields_
msg->populate(types, bytes, beg);
size_ += msg->size();
}
}
}
}
BagDeserializer::~BagDeserializer() {
for (map<string, ROSTypeMap*>::iterator it = type_maps_.begin();
it != type_maps_.end();
++it) {
delete (*it).second;
}
}
const ROSTypeMap* BagDeserializer::getTypeMap(const rosbag::MessageInstance &m) {
if (type_maps_.count(m.getDataType()) == 0) {
ROSTypeMap *rtm = new ROSTypeMap();
rtm->populate(m.getMessageDefinition());
type_maps_[m.getDataType()] = rtm;
}
return type_maps_[m.getDataType()];
}
void BagDeserializer::populateMsg(const ROSTypeMap &type_map,
const rosbag::MessageInstance &m,
ROSMessage *rm) {
bytes_.reset(new uint8_t[m.size()]);
ros::serialization::IStream stream(bytes_.get(), m.size());
m.write(stream);
int beg = 0;
rm->populate(type_map, bytes_.get(), &beg);
if (beg != static_cast<int>(m.size())) {
throw invalid_argument("Not all bytes were consumed while ");
}
}
ROSMessage* BagDeserializer::CreateMessage(const rosbag::MessageInstance &m) {
const ROSTypeMap *rtm = getTypeMap(m);
const ROSMessageFields *rmf = rtm->getMsgFields("0-root");
if (rmf == NULL) {
throw invalid_argument("Couldn't get root message type");
}
ROSMessage *msg = new ROSMessage(rmf->type());
try {
populateMsg(*rtm, m, msg);
} catch (std::exception &e) {
delete msg;
throw;
}
return msg;
}
<commit_msg>Touchup a few things<commit_after>#include "parser.hpp"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
using namespace std;
map<string,int> init_builtins() {
map<string,int> builtins;
const char *types[] = {"uint8", "uint16", "uint32", "uint64",
"int8", "int16", "int32", "int64",
"float32", "float64",
"time", "duration",
"string"};
const int sizes[] = {1, 2, 4, 8,
1, 2, 4, 8,
4, 8,
8, 8,
-1};
for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); ++i) {
builtins[types[i]] = sizes[i];
}
return builtins;
}
map<string,int> ROSType::builtins_(init_builtins());
void ROSType::populate(const string &type_str) {
name = type_str;
vector<string> fields;
std::string type_field;
boost::split(fields, type_str, boost::is_any_of("/"));
if (fields.size() == 1) {
pkg_name = "";
type_field = fields[0];
} else if (fields.size() == 2) {
pkg_name = fields[0];
type_field = fields[1];
} else {
throw invalid_argument("Bad type string: " + type_str);
}
static const boost::regex array_re("(.+)(\\[([0-9]*)\\])");
boost::smatch what;
if (boost::regex_search(type_field, what, array_re)) {
is_array = true;
msg_name = string(what[1].first, what[1].second);
array_type = string(what[2].first, what[2].second);
if (what.size() == 3) {
array_size = -1;
} else if (what.size() == 4) {
string size(what[3].first, what[3].second);
array_size = size.empty() ? -1 : atoi(size.c_str());
} else {
throw invalid_argument("Bad type string: " + type_str);
}
} else {
is_array = false;
msg_name = type_field;
array_type = "";
array_size = 1;
}
is_builtin = builtins_.count(msg_name) != 0;
if (is_builtin) {
type_size = builtins_[msg_name];
}
if (is_builtin) {
is_qualified = true;
base_type = msg_name;
} else if (!pkg_name.empty()) {
is_qualified = true;
base_type = pkg_name + string("/") + msg_name;
} else {
is_qualified = false;
base_type = msg_name;
}
}
void ROSMessageFields::populate(const string &msg_def) {
static const boost::regex newline_re("\\n+");
static const boost::regex whitespace_re("\\s+");
vector<string> lines;
boost::split_regex(lines, msg_def, newline_re);
int start_ind = 0;
if (boost::starts_with(lines[0], "MSG:")) {
vector<string> parts;
boost::split_regex(parts, lines[0], whitespace_re);
type_.populate(parts[1]);
start_ind = 1;
} else {
type_.name = "0-root";
type_.base_type = "0-root";
type_.msg_name = "";
type_.pkg_name = "0-root";
type_.array_type = "";
type_.is_array = false;
type_.is_qualified = true;
type_.is_builtin = false;
type_.array_size = 1;
}
boost::smatch what;
for (size_t l = start_ind; l < lines.size(); ++l) {
if (lines[l].size() == 0 || boost::starts_with(lines[l], "#")) {
continue;
}
vector<string> elements;
boost::split_regex(elements, lines[l], whitespace_re);
if (elements.size() != 2) {
throw invalid_argument("Bad line in message def: %s" + lines[l]);
}
fields_.push_back(Field(elements[1]));
fields_.back().type.populate(elements[0]);
}
}
void ROSMessageFields::setFieldPkgName(int i, const std::string &pkg_name) {
ROSType &type = fields_.at(i).type;
type.pkg_name = pkg_name;
type.base_type = type.pkg_name + string("/") + type.msg_name;
type.is_qualified = true;
}
ROSTypeMap::~ROSTypeMap() {
for (map<string, ROSMessageFields*>::iterator it = type_map_.begin();
it != type_map_.end();
++it) {
delete (*it).second;
}
}
void ROSTypeMap::populate(const string &msg_def) {
// Split into disparate message type definitions
std::vector<std::string> split;
boost::regex msg_sep_re("=+\\n+");
boost::split_regex(split, msg_def, msg_sep_re);
// Parse individual message types and make map from msg_name -> qualified name
std::vector<ROSMessageFields*> types(split.size());
for (size_t i = 0; i < split.size(); ++i) {
ROSMessageFields *rmt = new ROSMessageFields();
try {
rmt->populate(split[i]);
} catch (exception &e) {
delete rmt;
throw;
}
type_map_[rmt->type().name] = rmt;
resolver_[rmt->type().msg_name].push_back(rmt->type().pkg_name);
// If we throw, rmt will be freed because it's in type_map_
if (!rmt->type().is_qualified) {
throw invalid_argument("Couldn't determine type in message:\n" +
split[i] + "\nFull message def is:\n" + msg_def);
}
}
for (map<string, ROSMessageFields*>::iterator it = type_map_.begin();
it != type_map_.end();
++it) {
ROSMessageFields *rmt = (*it).second;
for (int i = 0; i < rmt->nfields(); ++i) {
const ROSMessageFields::Field &field = rmt->at(i);
if (!field.type.is_qualified) {
const vector<string> qualified_names = resolver_[field.type.msg_name];
if (qualified_names.size() == 1) {
rmt->setFieldPkgName(i, qualified_names[0]);
} else {
throw invalid_argument("Multiple types for " + field.type.msg_name +
"\nMessage def: \n" + msg_def);
}
}
}
}
}
const ROSMessageFields* ROSTypeMap::getMsgFields(const string &msg_type) const {
if (type_map_.count(msg_type) != 0) {
return type_map_[msg_type];
} else {
return NULL;
}
}
ROSMessage::ROSMessage(const ROSType &type)
: bytes_(0), size_(0), type_(type) {
}
ROSMessage::~ROSMessage() {
for (map<string, vector<ROSMessage*> >::iterator it = fields_.begin();
it != fields_.end();
++it) {
for (vector<ROSMessage*>::iterator mit = (*it).second.begin();
mit != (*it).second.end();
++mit) {
delete (*mit);
}
}
}
uint32_t read_uint32(const uint8_t *bytes, int *beg) {
uint32_t val = reinterpret_cast<const uint32_t*>(bytes + *beg)[0];
*beg += 4;
return val;
}
vector<const ROSMessage*> ROSMessage::getField(const std::string key) const {
vector<const ROSMessage*> field;
if (fields_.count(key) != 0) {
field.assign(fields_[key].begin(), fields_[key].end());
}
return field;
}
void ROSMessage::populate(const ROSTypeMap &types, const uint8_t *bytes, int *beg) {
if (type_.is_builtin) {
int array_len = type_.array_size;
if (array_len == -1) {
array_len = read_uint32(bytes, beg);
}
for (int array_ind = 0; array_ind < array_len; ++array_ind) {
int elem_size = type_.type_size;
if (elem_size == -1) {
elem_size = read_uint32(bytes, beg);
}
bytes_.push_back(std::vector<uint8_t>(elem_size));
std::vector<uint8_t> &element = bytes_.back();
for (size_t i = 0; i < element.size(); ++i) {
element[i] = bytes[*beg + i];
}
*beg += elem_size;
size_ += elem_size;
}
} else {
const ROSMessageFields *mt = types.getMsgFields(type_.base_type);
if (mt == NULL) {
throw invalid_argument("Couldn't populate fields");
}
for (int i = 0; i < mt->nfields(); ++i) {
const ROSMessageFields::Field &field = mt->at(i);
int array_len = field.type.is_builtin ? 1 : field.type.array_size;
if (array_len == -1) {
array_len = read_uint32(bytes, beg);
}
for (int array_ind = 0; array_ind < array_len; ++array_ind) {
ROSMessage *msg = new ROSMessage(field.type);
fields_[field.name].push_back(msg);
// If populate throws, msg will be freed as it's in fields_
msg->populate(types, bytes, beg);
size_ += msg->size();
}
}
}
}
BagDeserializer::~BagDeserializer() {
for (map<string, ROSTypeMap*>::iterator it = type_maps_.begin();
it != type_maps_.end();
++it) {
delete (*it).second;
}
}
const ROSTypeMap* BagDeserializer::getTypeMap(const rosbag::MessageInstance &m) {
if (type_maps_.count(m.getDataType()) == 0) {
ROSTypeMap *rtm = new ROSTypeMap();
rtm->populate(m.getMessageDefinition());
type_maps_[m.getDataType()] = rtm;
}
return type_maps_[m.getDataType()];
}
void BagDeserializer::populateMsg(const ROSTypeMap &type_map,
const rosbag::MessageInstance &m,
ROSMessage *rm) {
bytes_.reset(new uint8_t[m.size()]);
ros::serialization::IStream stream(bytes_.get(), m.size());
m.write(stream);
int beg = 0;
rm->populate(type_map, bytes_.get(), &beg);
if (beg != static_cast<int>(m.size())) {
throw invalid_argument("Not all bytes were consumed while reading message");
}
}
ROSMessage* BagDeserializer::CreateMessage(const rosbag::MessageInstance &m) {
const ROSTypeMap *rtm = getTypeMap(m);
const ROSMessageFields *rmf = rtm->getMsgFields("0-root");
if (rmf == NULL) {
throw invalid_argument("Couldn't get root message type");
}
ROSMessage *msg = new ROSMessage(rmf->type());
try {
populateMsg(*rtm, m, msg);
} catch (std::exception &e) {
delete msg;
throw;
}
return msg;
}
<|endoftext|> |
<commit_before>#ifndef TOML_PARSER
#define TOML_PARSER
#include "definitions.hpp"
#include "exceptions.hpp"
#include "line_operation.hpp"
#include "toml_values.hpp"
#include "parse_value.hpp"
#include <memory>
namespace toml
{
enum class LineKind
{
TABLE_TITLE, // (ex) [tablename]
ARRAY_OF_TABLE_TITLE, // (ex) [[tablename]]
KEY_VALUE, // (ex) key = value
UNKNOWN,
};
template<typename charT, typename traits, typename alloc>
inline std::basic_string<charT, traits, alloc>
remove_comment(const std::basic_string<charT, traits, alloc>& line)
{
return std::basic_string<charT, traits, alloc>(line.cbegin(),
std::find(line.cbegin(), line.cend(), '#'));
}
template<typename charT, typename traits>
std::basic_string<charT, traits>
read_line(std::basic_istream<charT, traits>& is)
{
std::basic_string<charT, traits> line;
std::getline(is, line);
return remove_indent(remove_extraneous_whitespace(remove_comment(line)));
}
template<typename charT, typename traits, typename alloc>
LineKind
determine_line_kind(const std::basic_string<charT, traits, alloc>& line)
{
if(line.front() == '[' && line.back() == ']')
{
if(line.size() >= 4)
if(line.at(1) == '[' && line.at(line.size() - 2) == ']')
return LineKind::ARRAY_OF_TABLE_TITLE;
return LineKind::TABLE_TITLE;
}
else if(std::count(line.begin(), line.end(), '=') >= 1)
{
if(line.front() == '=')
throw syntax_error<charT, traits, alloc>("line starts with = " + line);
return LineKind::KEY_VALUE;
}
else
return LineKind::UNKNOWN;// a part of multi-line value?
}
template<typename charT, typename traits, typename alloc>
std::basic_string<charT, traits, alloc>
extract_table_title(const std::basic_string<charT, traits, alloc>& line)
{
if(line.front() == '[' && line.back() == ']')
{
if(line.size() >= 4)
if(line.at(1) == '[' && line.at(line.size() - 2) == ']')
return line.substr(2, line.size()-4);
return line.substr(1, line.size()-2);
}
else
throw internal_error<charT, traits, alloc>("not table title line" + line);
}
template<typename charT, typename traits, typename alloc>
bool
is_multi_line_value(const std::basic_string<charT, traits, alloc>& line)
{
// multi-line string/string-literal, multi-line array.
// multi-line inline table(!) is ignored
if(count(line, std::basic_string<charT, traits, alloc>("\"\"\"")) == 1)
return true;
else if(count(line, std::basic_string<charT, traits, alloc>("\'\'\'")) == 1)
return true;
else if(line.front() == '[')
return !is_closed(line, '[', ']');
else
return false;
}
template<typename charT, typename traits, typename alloc>
std::pair<std::string, std::shared_ptr<value_base>>
parse_key_value(const std::basic_string<charT, traits, alloc>& line,
std::basic_istream<charT, traits>& is)
{
auto equal = std::find(line.begin(), line.end(), '=');
std::basic_string<charT, traits, alloc> key(line.cbegin(), equal);
key = remove_extraneous_whitespace(key);
std::basic_string<charT, traits, alloc> value(equal+1, line.cend());
value = remove_indent(value);
while(is_multi_line_value(value))
{
if(is.eof()) throw end_of_file("eof");
const auto additional = read_line(is);
if(additional.empty()) continue;
value += additional;
}
return std::make_pair(key, parse_value(value));
}
template<typename charT, typename traits>
std::shared_ptr<value_base>
parse_table(std::basic_istream<charT, traits>& is)
{
std::shared_ptr<value_base> retval(new table_type);
std::shared_ptr<table_type> table =
std::dynamic_pointer_cast<table_type>(retval);
while(!is.eof())
{
const auto line_head = is.tellg();
const std::basic_string<charT, traits> line = read_line(is);
if(line.empty()) continue;
LineKind kind = determine_line_kind(line);
switch(kind)
{
case LineKind::TABLE_TITLE:
{
is.seekg(line_head);
return retval;
}
case LineKind::ARRAY_OF_TABLE_TITLE:
{
is.seekg(line_head);
return retval;
}
case LineKind::KEY_VALUE:
{
try
{
const auto kv = parse_key_value(line, is);
table->value[kv.first] = kv.second;
}
catch(end_of_file& eof)
{
throw syntax_error<charT, traits,
std::allocator<charT>>("sudden eof");
}
break;
}
case LineKind::UNKNOWN:
throw syntax_error<charT, traits,
std::allocator<charT>>("unknown line: " + line);
default:
throw internal_error<charT, traits,
std::allocator<charT>>("invalid line kind");
}
}
return retval;
}
template<typename charT, typename traits>
Data parse(std::basic_istream<charT, traits>& is)
{
Data data;
while(!is.eof())
{
const std::basic_string<charT, traits> line = read_line(is);
if(line.empty()) continue;
LineKind kind = determine_line_kind(line);
switch(kind)
{
case LineKind::TABLE_TITLE:
{
data[extract_table_title(line)] = parse_table(is);
break;
}
case LineKind::ARRAY_OF_TABLE_TITLE:
{
const std::basic_string<charT, traits> table_title =
extract_table_title(line);
if(data.count(table_title) == 0)
data[table_title] = std::make_shared<array_type>();
const std::shared_ptr<array_type> array_ptr =
std::dynamic_pointer_cast<array_type>(data[table_title]);
if(!array_ptr) throw internal_error<charT, traits,
std::allocator<charT>>("dynamic_pointer_cast error");
array_ptr->value.push_back(parse_table(is));
break;
}
case LineKind::KEY_VALUE:
{
try
{
const auto kv = parse_key_value(line, is);
data[kv.first] = kv.second;
}
catch(end_of_file& eof)
{
throw syntax_error<charT, traits,
std::allocator<charT>>("sudden eof");
}
break;
}
case LineKind::UNKNOWN:
throw syntax_error<charT, traits,
std::allocator<charT>>("unknown line: " + line);
default:
throw internal_error<charT, traits,
std::allocator<charT>>("invalid line kind");
}
}
return data;
}
}//toml
#endif /* TOML_PARSER */
<commit_msg>fix remove_comment func for string including #<commit_after>#ifndef TOML_PARSER
#define TOML_PARSER
#include "definitions.hpp"
#include "exceptions.hpp"
#include "line_operation.hpp"
#include "toml_values.hpp"
#include "parse_value.hpp"
#include <memory>
namespace toml
{
enum class LineKind
{
TABLE_TITLE, // (ex) [tablename]
ARRAY_OF_TABLE_TITLE, // (ex) [[tablename]]
KEY_VALUE, // (ex) key = value
UNKNOWN,
};
// return next to the end of string
template<typename charT, typename traits, typename alloc>
typename std::basic_string<charT, traits, alloc>::const_iterator
advance_until_end_of_string(
typename std::basic_string<charT, traits, alloc>::const_iterator iter,
const typename std::basic_string<charT, traits, alloc>::const_iterator end,
const charT quat)
{
if(std::distance(iter, end) >= 6 &&
*iter == quat && *(iter+1) == quat && *(iter+2) == quat)
{
iter = iter + 3;
while(iter != end)
{
if(*iter == quat && *(iter+1) == quat && *(iter+2) == quat)
return iter+3;
else ++iter;
}
}
else
{
bool esc_flag = false;
while(iter != end)
{
if(*iter == quat && (!esc_flag)) return iter + 1;
else if(*iter == '\\')
esc_flag = true;
else
esc_flag = false;
++iter;
}
}
return iter;
}
template<typename charT, typename traits, typename alloc>
std::basic_string<charT, traits, alloc>
remove_comment(const std::basic_string<charT, traits, alloc>& line)
{
// string = "some string including \" and # case" # and this is a comment.
// [table.using."quated".title.and.includes."#".and."]".case] # comment
typename std::basic_string<charT, traits, alloc>::const_iterator
iter = line.begin();
while(iter != line.end())
{
while(*iter == ' ' || *iter == '\t'){++iter;}
if(*iter == '"')
iter = advance_until_end_of_string<charT, traits, alloc>(iter, line.end(), '"');
else if(*iter == '\'')
iter = advance_until_end_of_string<charT, traits, alloc>(iter, line.end(), '\'');
else if(*iter == '#')
break;
else ++iter;
}
return std::basic_string<charT, traits, alloc>(line.begin(), iter);
}
template<typename charT, typename traits>
std::basic_string<charT, traits>
read_line(std::basic_istream<charT, traits>& is)
{
std::basic_string<charT, traits> line;
std::getline(is, line);
return remove_indent(remove_extraneous_whitespace(remove_comment(line)));
}
template<typename charT, typename traits, typename alloc>
LineKind
determine_line_kind(const std::basic_string<charT, traits, alloc>& line)
{
if(line.front() == '[' && line.back() == ']')
{
if(line.size() >= 4)
if(line.at(1) == '[' && line.at(line.size() - 2) == ']')
return LineKind::ARRAY_OF_TABLE_TITLE;
return LineKind::TABLE_TITLE;
}
else if(std::count(line.begin(), line.end(), '=') >= 1)
{
if(line.front() == '=')
throw syntax_error<charT, traits, alloc>("line starts with = " + line);
return LineKind::KEY_VALUE;
}
else
return LineKind::UNKNOWN;// a part of multi-line value?
}
template<typename charT, typename traits, typename alloc>
std::basic_string<charT, traits, alloc>
extract_table_title(const std::basic_string<charT, traits, alloc>& line)
{
if(line.front() == '[' && line.back() == ']')
{
if(line.size() >= 4)
if(line.at(1) == '[' && line.at(line.size() - 2) == ']')
return line.substr(2, line.size()-4);
return line.substr(1, line.size()-2);
}
else
throw internal_error<charT, traits, alloc>("not table title line" + line);
}
template<typename charT, typename traits, typename alloc>
bool
is_multi_line_value(const std::basic_string<charT, traits, alloc>& line)
{
// multi-line string/string-literal, multi-line array.
// multi-line inline table(!) is ignored
if(count(line, std::basic_string<charT, traits, alloc>("\"\"\"")) == 1)
return true;
else if(count(line, std::basic_string<charT, traits, alloc>("\'\'\'")) == 1)
return true;
else if(line.front() == '[')
return !is_closed(line, '[', ']');
else
return false;
}
template<typename charT, typename traits, typename alloc>
std::pair<std::string, std::shared_ptr<value_base>>
parse_key_value(const std::basic_string<charT, traits, alloc>& line,
std::basic_istream<charT, traits>& is)
{
auto equal = std::find(line.begin(), line.end(), '=');
std::basic_string<charT, traits, alloc> key(line.cbegin(), equal);
key = remove_extraneous_whitespace(key);
std::basic_string<charT, traits, alloc> value(equal+1, line.cend());
value = remove_indent(value);
while(is_multi_line_value(value))
{
if(is.eof()) throw end_of_file("eof");
const auto additional = read_line(is);
if(additional.empty()) continue;
value += additional;
}
return std::make_pair(key, parse_value(value));
}
template<typename charT, typename traits>
std::shared_ptr<value_base>
parse_table(std::basic_istream<charT, traits>& is)
{
std::shared_ptr<value_base> retval(new table_type);
std::shared_ptr<table_type> table =
std::dynamic_pointer_cast<table_type>(retval);
while(!is.eof())
{
const auto line_head = is.tellg();
const std::basic_string<charT, traits> line = read_line(is);
if(line.empty()) continue;
LineKind kind = determine_line_kind(line);
switch(kind)
{
case LineKind::TABLE_TITLE:
{
is.seekg(line_head);
return retval;
}
case LineKind::ARRAY_OF_TABLE_TITLE:
{
is.seekg(line_head);
return retval;
}
case LineKind::KEY_VALUE:
{
try
{
const auto kv = parse_key_value(line, is);
table->value[kv.first] = kv.second;
}
catch(end_of_file& eof)
{
throw syntax_error<charT, traits,
std::allocator<charT>>("sudden eof");
}
break;
}
case LineKind::UNKNOWN:
throw syntax_error<charT, traits,
std::allocator<charT>>("unknown line: " + line);
default:
throw internal_error<charT, traits,
std::allocator<charT>>("invalid line kind");
}
}
return retval;
}
template<typename charT, typename traits>
Data parse(std::basic_istream<charT, traits>& is)
{
Data data;
while(!is.eof())
{
const std::basic_string<charT, traits> line = read_line(is);
if(line.empty()) continue;
LineKind kind = determine_line_kind(line);
switch(kind)
{
case LineKind::TABLE_TITLE:
{
data[extract_table_title(line)] = parse_table(is);
break;
}
case LineKind::ARRAY_OF_TABLE_TITLE:
{
const std::basic_string<charT, traits> table_title =
extract_table_title(line);
if(data.count(table_title) == 0)
data[table_title] = std::make_shared<array_type>();
const std::shared_ptr<array_type> array_ptr =
std::dynamic_pointer_cast<array_type>(data[table_title]);
if(!array_ptr) throw internal_error<charT, traits,
std::allocator<charT>>("dynamic_pointer_cast error");
array_ptr->value.push_back(parse_table(is));
break;
}
case LineKind::KEY_VALUE:
{
try
{
const auto kv = parse_key_value(line, is);
data[kv.first] = kv.second;
}
catch(end_of_file& eof)
{
throw syntax_error<charT, traits,
std::allocator<charT>>("sudden eof");
}
break;
}
case LineKind::UNKNOWN:
throw syntax_error<charT, traits,
std::allocator<charT>>("unknown line: " + line);
default:
throw internal_error<charT, traits,
std::allocator<charT>>("invalid line kind");
}
}
return data;
}
}//toml
#endif /* TOML_PARSER */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Mellnik
*
* 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 <boost/chrono.hpp>
#include <cryptopp/hex.h>
#include <cryptopp/osrng.h>
#include <cryptopp/whrlpool.h>
#include <cryptopp/pwdbased.h>
#include "pbkdf2.h"
Pbkdf2::Pbkdf2(const char *key, unsigned iterations, CallbackData *cData) :
h_Key(key), h_Iterations(iterations)
{
this->cData = cData;
h_Worker = PBKDF2_GENERATE;
}
Pbkdf2::Pbkdf2(const char *key, const char *hash, const char *salt, unsigned iterations, CallbackData *cData) :
h_Key(key), h_Hash(hash), h_Salt(salt), h_Iterations(iterations)
{
this->cData = cData;
h_Worker = PBKDF2_VALIDATE;
h_Equal = false;
}
Pbkdf2::~Pbkdf2()
{
delete cData;
}
void Pbkdf2::Work()
{
static const unsigned _PBKDF2_BYTE_ = 512 / 8;
boost::chrono::steady_clock::time_point start = boost::chrono::steady_clock::now();
CryptoPP::SecByteBlock byte_Derived(_PBKDF2_BYTE_);
CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::Whirlpool> pbkdf2;
if(h_Worker == PBKDF2_GENERATE)
{
CryptoPP::SecByteBlock byte_Salt(_PBKDF2_BYTE_);
CryptoPP::AutoSeededRandomPool RNG;
RNG.GenerateBlock(byte_Salt, byte_Salt.size());
CryptoPP::ArraySource(byte_Salt, byte_Salt.size(), true, new CryptoPP::HexEncoder(new CryptoPP::StringSink(h_Salt)));
pbkdf2.DeriveKey(byte_Derived, byte_Derived.size(), 0x0, reinterpret_cast<const byte *>(h_Key.data()), h_Key.size(), reinterpret_cast<const byte *>(h_Salt.data()), h_Salt.size(), h_Iterations, 0);
CryptoPP::ArraySource(byte_Derived, byte_Derived.size(), true, new CryptoPP::HexEncoder(new CryptoPP::StringSink(h_Hash)));
}
else if(h_Worker == PBKDF2_VALIDATE)
{
pbkdf2.DeriveKey(byte_Derived, byte_Derived.size(), 0x0, reinterpret_cast<const byte *>(h_Key.data()), h_Key.size(), reinterpret_cast<const byte *>(h_Salt.data()), h_Salt.size(), h_Iterations, 0);
CryptoPP::SecByteBlock byte_Validate(_PBKDF2_BYTE_);
CryptoPP::StringSource(h_Hash, true, new CryptoPP::HexDecoder(new CryptoPP::ArraySink(byte_Validate, byte_Validate.size())));
// Length-constant comparison.
unsigned diff = _PBKDF2_BYTE_ ^ _PBKDF2_BYTE_;
for(unsigned i = 0; i < _PBKDF2_BYTE_; ++i)
{
diff |= byte_Derived[i] ^ byte_Validate[i];
}
h_Equal = diff == 0;
}
boost::chrono::steady_clock::duration duraction = boost::chrono::steady_clock::now() - start;
h_ExecTime = static_cast<unsigned>(boost::chrono::duration_cast<boost::chrono::milliseconds>(duraction).count());
}<commit_msg>- fixed typo<commit_after>/*
* Copyright (C) 2014 Mellnik
*
* 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 <boost/chrono.hpp>
#include <cryptopp/hex.h>
#include <cryptopp/osrng.h>
#include <cryptopp/whrlpool.h>
#include <cryptopp/pwdbased.h>
#include "pbkdf2.h"
Pbkdf2::Pbkdf2(const char *key, unsigned iterations, CallbackData *cData) :
h_Key(key), h_Iterations(iterations)
{
this->cData = cData;
h_Worker = PBKDF2_GENERATE;
}
Pbkdf2::Pbkdf2(const char *key, const char *hash, const char *salt, unsigned iterations, CallbackData *cData) :
h_Key(key), h_Hash(hash), h_Salt(salt), h_Iterations(iterations)
{
this->cData = cData;
h_Worker = PBKDF2_VALIDATE;
h_Equal = false;
}
Pbkdf2::~Pbkdf2()
{
delete cData;
}
void Pbkdf2::Work()
{
static const unsigned _PBKDF2_BYTE_ = 512 / 8;
boost::chrono::steady_clock::time_point start = boost::chrono::steady_clock::now();
CryptoPP::SecByteBlock byte_Derived(_PBKDF2_BYTE_);
CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::Whirlpool> pbkdf2;
if(h_Worker == PBKDF2_GENERATE)
{
CryptoPP::SecByteBlock byte_Salt(_PBKDF2_BYTE_);
CryptoPP::AutoSeededRandomPool RNG;
RNG.GenerateBlock(byte_Salt, byte_Salt.size());
CryptoPP::ArraySource(byte_Salt, byte_Salt.size(), true, new CryptoPP::HexEncoder(new CryptoPP::StringSink(h_Salt)));
pbkdf2.DeriveKey(byte_Derived, byte_Derived.size(), 0x0, reinterpret_cast<const byte *>(h_Key.data()), h_Key.size(), reinterpret_cast<const byte *>(h_Salt.data()), h_Salt.size(), h_Iterations, 0);
CryptoPP::ArraySource(byte_Derived, byte_Derived.size(), true, new CryptoPP::HexEncoder(new CryptoPP::StringSink(h_Hash)));
}
else if(h_Worker == PBKDF2_VALIDATE)
{
pbkdf2.DeriveKey(byte_Derived, byte_Derived.size(), 0x0, reinterpret_cast<const byte *>(h_Key.data()), h_Key.size(), reinterpret_cast<const byte *>(h_Salt.data()), h_Salt.size(), h_Iterations, 0);
CryptoPP::SecByteBlock byte_Validate(_PBKDF2_BYTE_);
CryptoPP::StringSource(h_Hash, true, new CryptoPP::HexDecoder(new CryptoPP::ArraySink(byte_Validate, byte_Validate.size())));
// Length-constant comparison.
unsigned diff = _PBKDF2_BYTE_ ^ _PBKDF2_BYTE_;
for(unsigned i = 0; i < _PBKDF2_BYTE_; ++i)
{
diff |= byte_Derived[i] ^ byte_Validate[i];
}
h_Equal = diff == 0;
}
boost::chrono::steady_clock::duration duration = boost::chrono::steady_clock::now() - start;
h_ExecTime = static_cast<unsigned>(boost::chrono::duration_cast<boost::chrono::milliseconds>(duration).count());
}<|endoftext|> |
<commit_before>#include "perfmon.hpp"
#include "arch/arch.hpp"
#include "utils.hpp"
#include <stdarg.h>
#include "coroutine/coroutines.hpp"
/* The var list keeps track of all of the perfmon_t objects. */
intrusive_list_t<perfmon_t> &get_var_list() {
/* Getter function so that we can be sure that var_list is initialized before it is needed,
as advised by the C++ FAQ. Otherwise, a perfmon_t might be initialized before the var list
was initialized. */
static intrusive_list_t<perfmon_t> var_list;
return var_list;
}
/* Class that wraps a pthread spinlock.
TODO: This should live in the arch/ directory. */
class spinlock_t {
pthread_spinlock_t l;
public:
spinlock_t() {
pthread_spin_init(&l, PTHREAD_PROCESS_PRIVATE);
}
~spinlock_t() {
pthread_spin_destroy(&l);
}
void lock() {
int res = pthread_spin_lock(&l);
guarantee_err(res == 0, "could not lock spin lock");
}
void unlock() {
int res = pthread_spin_unlock(&l);
guarantee_err(res == 0, "could not unlock spin lock");
}
};
/* The var lock protects the var list when it is being modified. In theory, this should all work
automagically because the constructor of every perfmon_t calls get_var_lock(), causing the var lock
to be constructed before the first perfmon, so it is destroyed after the last perfmon. */
spinlock_t &get_var_lock() {
/* To avoid static initialization fiasco */
static spinlock_t lock;
return lock;
}
/* This is the function that actually gathers the stats. It is illegal to create or destroy
perfmon_t objects while a perfmon_fsm_t is active. */
void co_perfmon_visit(int thread, const std::vector<void*> &data, coro_t::multi_wait_t *multi_wait) {
coro_t::on_thread_t moving(thread);
int i = 0;
for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {
p->visit_stats(data[i++]);
}
multi_wait->notify();
}
void co_perfmon_get_stats(perfmon_stats_t *dest, perfmon_callback_t *cb) {
std::vector<void*> data;
data.reserve(get_var_list().size());
for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {
data.push_back(p->begin_stats());
}
int threads = get_num_threads();
coro_t::multi_wait_t *multi_wait = new coro_t::multi_wait_t(threads);
for (int i = 0; i < threads; i++) {
coro_t::spawn(co_perfmon_visit, i, data, multi_wait);
}
coro_t::wait();
int i = 0;
for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {
p->end_stats(data[i++], dest);
}
cb->on_perfmon_stats();
}
bool perfmon_get_stats(perfmon_stats_t *dest, perfmon_callback_t *cb) {
coro_t::spawn(co_perfmon_get_stats, dest, cb);
return false;
}
/* Constructor and destructor register and deregister the perfmon.
Right now, it is illegal to make perfmon_t objects that are not static variables, so
we don't have to worry about locking the var list. If we locked it, then we could
create and destroy perfmon_ts at runtime. */
perfmon_t::perfmon_t()
{
get_var_lock().lock();
get_var_list().push_back(this);
get_var_lock().unlock();
}
perfmon_t::~perfmon_t() {
get_var_lock().lock();
get_var_list().remove(this);
get_var_lock().unlock();
}
/* perfmon_counter_t */
perfmon_counter_t::perfmon_counter_t(std::string name)
: name(name)
{
for (int i = 0; i < MAX_THREADS; i++) values[i] = 0;
}
int64_t &perfmon_counter_t::get() {
return values[get_thread_id()];
}
void *perfmon_counter_t::begin_stats() {
return new int64_t[get_num_threads()];
}
void perfmon_counter_t::visit_stats(void *data) {
//printf("Visiting the %dth thread for the stat %s\n", get_thread_id(), name.c_str());
((int64_t *)data)[get_thread_id()] = get();
//printf("Just visited the %dth thread for the stat %s\n", get_thread_id(), name.c_str());
}
void perfmon_counter_t::end_stats(void *data, perfmon_stats_t *dest) {
int64_t value = 0;
for (int i = 0; i < get_num_threads(); i++) value += ((int64_t *)data)[i];
(*dest)[name] = format(value);
delete[] (int64_t *)data;
}
/* perfmon_sampler_t */
perfmon_sampler_t::perfmon_sampler_t(std::string name, ticks_t length, bool include_rate)
: name(name), length(length), include_rate(include_rate) { }
void perfmon_sampler_t::expire() {
ticks_t now = get_ticks();
std::deque<sample_t> &queue = values[get_thread_id()];
while (!queue.empty() && queue.front().timestamp + length < now) queue.pop_front();
}
void perfmon_sampler_t::record(value_t v) {
expire();
values[get_thread_id()].push_back(sample_t(v, get_ticks()));
}
struct perfmon_sampler_step_t {
uint64_t counts[MAX_THREADS];
perfmon_sampler_t::value_t values[MAX_THREADS], mins[MAX_THREADS], maxes[MAX_THREADS];
};
void *perfmon_sampler_t::begin_stats() {
return new perfmon_sampler_step_t;
}
void perfmon_sampler_t::visit_stats(void *data) {
perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;
expire();
d->values[get_thread_id()] = 0;
d->counts[get_thread_id()] = 0;
for (std::deque<perfmon_sampler_t::sample_t>::iterator it = values[get_thread_id()].begin();
it != values[get_thread_id()].end(); it++) {
d->values[get_thread_id()] += (*it).value;
if (d->counts[get_thread_id()] > 0) {
d->mins[get_thread_id()] = std::min(d->mins[get_thread_id()], (*it).value);
d->maxes[get_thread_id()] = std::max(d->maxes[get_thread_id()], (*it).value);
} else {
d->mins[get_thread_id()] = (*it).value;
d->maxes[get_thread_id()] = (*it).value;
}
d->counts[get_thread_id()]++;
}
}
void perfmon_sampler_t::end_stats(void *data, perfmon_stats_t *dest) {
perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;
perfmon_sampler_t::value_t value = 0;
uint64_t count = 0;
perfmon_sampler_t::value_t min = 0, max = 0; /* Initializers to make GCC shut up */
bool have_any = false;
for (int i = 0; i < get_num_threads(); i++) {
value += d->values[i];
count += d->counts[i];
if (d->counts[i]) {
if (have_any) {
min = std::min(d->mins[i], min);
max = std::max(d->maxes[i], max);
} else {
min = d->mins[i];
max = d->maxes[i];
have_any = true;
}
}
}
if (have_any) {
(*dest)[name + "_avg"] = format(value / count);
(*dest)[name + "_min"] = format(min);
(*dest)[name + "_max"] = format(max);
} else {
(*dest)[name + "_avg"] = "-";
(*dest)[name + "_min"] = "-";
(*dest)[name + "_max"] = "-";
}
if (include_rate) {
(*dest)[name + "_persec"] = format(count / ticks_to_secs(length));
}
delete d;
};
/* perfmon_function_t */
perfmon_function_t::internal_function_t::internal_function_t(perfmon_function_t *p)
: parent(p)
{
parent->funs[get_thread_id()].push_back(this);
}
perfmon_function_t::internal_function_t::~internal_function_t() {
parent->funs[get_thread_id()].remove(this);
}
void *perfmon_function_t::begin_stats() {
return reinterpret_cast<void*>(new std::string());
}
void perfmon_function_t::visit_stats(void *data) {
std::string *string = reinterpret_cast<std::string*>(data);
for (internal_function_t *f = funs[get_thread_id()].head(); f; f = funs[get_thread_id()].next(f)) {
if (string->size() > 0) (*string) += ", ";
(*string) += f->compute_stat();
}
}
void perfmon_function_t::end_stats(void *data, perfmon_stats_t *dest) {
std::string *string = reinterpret_cast<std::string*>(data);
if (string->size()) (*dest)[name] = *string;
else (*dest)[name] = "N/A";
delete string;
}
<commit_msg>Fixing race condition in coroutine-ized perfmon<commit_after>#include "perfmon.hpp"
#include "arch/arch.hpp"
#include "utils.hpp"
#include <stdarg.h>
#include "coroutine/coroutines.hpp"
/* The var list keeps track of all of the perfmon_t objects. */
intrusive_list_t<perfmon_t> &get_var_list() {
/* Getter function so that we can be sure that var_list is initialized before it is needed,
as advised by the C++ FAQ. Otherwise, a perfmon_t might be initialized before the var list
was initialized. */
static intrusive_list_t<perfmon_t> var_list;
return var_list;
}
/* Class that wraps a pthread spinlock.
TODO: This should live in the arch/ directory. */
class spinlock_t {
pthread_spinlock_t l;
public:
spinlock_t() {
pthread_spin_init(&l, PTHREAD_PROCESS_PRIVATE);
}
~spinlock_t() {
pthread_spin_destroy(&l);
}
void lock() {
int res = pthread_spin_lock(&l);
guarantee_err(res == 0, "could not lock spin lock");
}
void unlock() {
int res = pthread_spin_unlock(&l);
guarantee_err(res == 0, "could not unlock spin lock");
}
};
/* The var lock protects the var list when it is being modified. In theory, this should all work
automagically because the constructor of every perfmon_t calls get_var_lock(), causing the var lock
to be constructed before the first perfmon, so it is destroyed after the last perfmon. */
spinlock_t &get_var_lock() {
/* To avoid static initialization fiasco */
static spinlock_t lock;
return lock;
}
/* This is the function that actually gathers the stats. It is illegal to create or destroy
perfmon_t objects while perfmon_get_stats is active. */
void co_perfmon_visit(int thread, const std::vector<void*> &data, coro_t::multi_wait_t *multi_wait) {
{
coro_t::on_thread_t moving(thread);
int i = 0;
for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {
p->visit_stats(data[i++]);
}
}
multi_wait->notify();
}
void co_perfmon_get_stats(perfmon_stats_t *dest, perfmon_callback_t *cb) {
std::vector<void*> data;
data.reserve(get_var_list().size());
for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {
data.push_back(p->begin_stats());
}
int threads = get_num_threads();
coro_t::multi_wait_t *multi_wait = new coro_t::multi_wait_t(threads);
for (int i = 0; i < threads; i++) {
coro_t::spawn(co_perfmon_visit, i, data, multi_wait);
}
coro_t::wait();
int i = 0;
for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {
p->end_stats(data[i++], dest);
}
cb->on_perfmon_stats();
}
bool perfmon_get_stats(perfmon_stats_t *dest, perfmon_callback_t *cb) {
coro_t::spawn(co_perfmon_get_stats, dest, cb);
return false;
}
/* Constructor and destructor register and deregister the perfmon.
Right now, it is illegal to make perfmon_t objects that are not static variables, so
we don't have to worry about locking the var list. If we locked it, then we could
create and destroy perfmon_ts at runtime. */
perfmon_t::perfmon_t()
{
get_var_lock().lock();
get_var_list().push_back(this);
get_var_lock().unlock();
}
perfmon_t::~perfmon_t() {
get_var_lock().lock();
get_var_list().remove(this);
get_var_lock().unlock();
}
/* perfmon_counter_t */
perfmon_counter_t::perfmon_counter_t(std::string name)
: name(name)
{
for (int i = 0; i < MAX_THREADS; i++) values[i] = 0;
}
int64_t &perfmon_counter_t::get() {
return values[get_thread_id()];
}
void *perfmon_counter_t::begin_stats() {
return new int64_t[get_num_threads()];
}
void perfmon_counter_t::visit_stats(void *data) {
((int64_t *)data)[get_thread_id()] = get();
}
void perfmon_counter_t::end_stats(void *data, perfmon_stats_t *dest) {
int64_t value = 0;
for (int i = 0; i < get_num_threads(); i++) value += ((int64_t *)data)[i];
(*dest)[name] = format(value);
delete[] (int64_t *)data;
}
/* perfmon_sampler_t */
perfmon_sampler_t::perfmon_sampler_t(std::string name, ticks_t length, bool include_rate)
: name(name), length(length), include_rate(include_rate) { }
void perfmon_sampler_t::expire() {
ticks_t now = get_ticks();
std::deque<sample_t> &queue = values[get_thread_id()];
while (!queue.empty() && queue.front().timestamp + length < now) queue.pop_front();
}
void perfmon_sampler_t::record(value_t v) {
expire();
values[get_thread_id()].push_back(sample_t(v, get_ticks()));
}
struct perfmon_sampler_step_t {
uint64_t counts[MAX_THREADS];
perfmon_sampler_t::value_t values[MAX_THREADS], mins[MAX_THREADS], maxes[MAX_THREADS];
};
void *perfmon_sampler_t::begin_stats() {
return new perfmon_sampler_step_t;
}
void perfmon_sampler_t::visit_stats(void *data) {
perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;
expire();
d->values[get_thread_id()] = 0;
d->counts[get_thread_id()] = 0;
for (std::deque<perfmon_sampler_t::sample_t>::iterator it = values[get_thread_id()].begin();
it != values[get_thread_id()].end(); it++) {
d->values[get_thread_id()] += (*it).value;
if (d->counts[get_thread_id()] > 0) {
d->mins[get_thread_id()] = std::min(d->mins[get_thread_id()], (*it).value);
d->maxes[get_thread_id()] = std::max(d->maxes[get_thread_id()], (*it).value);
} else {
d->mins[get_thread_id()] = (*it).value;
d->maxes[get_thread_id()] = (*it).value;
}
d->counts[get_thread_id()]++;
}
}
void perfmon_sampler_t::end_stats(void *data, perfmon_stats_t *dest) {
perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;
perfmon_sampler_t::value_t value = 0;
uint64_t count = 0;
perfmon_sampler_t::value_t min = 0, max = 0; /* Initializers to make GCC shut up */
bool have_any = false;
for (int i = 0; i < get_num_threads(); i++) {
value += d->values[i];
count += d->counts[i];
if (d->counts[i]) {
if (have_any) {
min = std::min(d->mins[i], min);
max = std::max(d->maxes[i], max);
} else {
min = d->mins[i];
max = d->maxes[i];
have_any = true;
}
}
}
if (have_any) {
(*dest)[name + "_avg"] = format(value / count);
(*dest)[name + "_min"] = format(min);
(*dest)[name + "_max"] = format(max);
} else {
(*dest)[name + "_avg"] = "-";
(*dest)[name + "_min"] = "-";
(*dest)[name + "_max"] = "-";
}
if (include_rate) {
(*dest)[name + "_persec"] = format(count / ticks_to_secs(length));
}
delete d;
};
/* perfmon_function_t */
perfmon_function_t::internal_function_t::internal_function_t(perfmon_function_t *p)
: parent(p)
{
parent->funs[get_thread_id()].push_back(this);
}
perfmon_function_t::internal_function_t::~internal_function_t() {
parent->funs[get_thread_id()].remove(this);
}
void *perfmon_function_t::begin_stats() {
return reinterpret_cast<void*>(new std::string());
}
void perfmon_function_t::visit_stats(void *data) {
std::string *string = reinterpret_cast<std::string*>(data);
for (internal_function_t *f = funs[get_thread_id()].head(); f; f = funs[get_thread_id()].next(f)) {
if (string->size() > 0) (*string) += ", ";
(*string) += f->compute_stat();
}
}
void perfmon_function_t::end_stats(void *data, perfmon_stats_t *dest) {
std::string *string = reinterpret_cast<std::string*>(data);
if (string->size()) (*dest)[name] = *string;
else (*dest)[name] = "N/A";
delete string;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX グループ・GPT I/O 制御
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2013 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX63T/gpt.hpp"
#include "RX63T/system.hpp"
#include "RX63T/icu.hpp"
#include "common/vect.h"
/// F_PCLKA タイマーのクロックに必要なので定義が無い場合エラーにします。
#ifndef F_PCLKA
# error "gpt_io.hpp requires F_PCLKA to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief GPT I/O 制御クラス
@param[in] GPT GPTx定義クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class GPTX>
class gpt_io {
// ※必要なら、実装する
void sleep_() { }
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
gpt_io() { }
//-----------------------------------------------------------------//
/*!
@brief 機能を開始
@param[in] limit PWM カウンターのリミット
*/
//-----------------------------------------------------------------//
void start_pwm(uint16_t limit) {
uint32_t ch = GPTX::get_chanel();
// 書き込み保護を解除
switch(ch) {
case 0:
GPT::GTWP.WP0 = 0;
break;
case 1:
GPT::GTWP.WP1 = 0;
break;
case 2:
GPT::GTWP.WP2 = 0;
break;
case 3:
GPT::GTWP.WP3 = 0;
break;
case 4:
GPTB::GTWP.WP4 = 0;
break;
case 5:
GPTB::GTWP.WP5 = 0;
break;
case 6:
GPTB::GTWP.WP6 = 0;
break;
case 7:
GPTB::GTWP.WP7 = 0;
break;
}
GPTX::GTIOR.GTIOA = 0b011001;
GPTX::GTONCR = GPTX::GTONCR.OAE.b();
GPTX::GTUDC = GPTX::GTUDC.UD.b() | GPTX::GTUDC.UDF.b(); // UP カウント設定
// バッファ動作設定
switch(ch) {
case 0:
GPT::GTBDR.BD0_0 = 1; // GPT0 GTCCR バッファ動作禁止
GPT::GTBDR.BD0_1 = 1; // GPT0 GTPR バッファ動作禁止
GPT::GTBDR.BD0_2 = 1; // GPT0 GTADTR バッファ動作禁止
GPT::GTBDR.BD0_3 = 1; // GPT0 GTDV バッファ動作禁止
break;
case 1:
GPT::GTBDR.BD1_0 = 1; // GPT1 GTCCR バッファ動作禁止
GPT::GTBDR.BD1_1 = 1; // GPT1 GTPR バッファ動作禁止
GPT::GTBDR.BD1_2 = 1; // GPT1 GTADTR バッファ動作禁止
GPT::GTBDR.BD1_3 = 1; // GPT1 GTDV バッファ動作禁止
break;
case 2:
GPT::GTBDR.BD2_0 = 1; // GPT2 GTCCR バッファ動作禁止
GPT::GTBDR.BD2_1 = 1; // GPT2 GTPR バッファ動作禁止
GPT::GTBDR.BD2_2 = 1; // GPT2 GTADTR バッファ動作禁止
GPT::GTBDR.BD2_3 = 1; // GPT2 GTDV バッファ動作禁止
break;
case 3:
GPT::GTBDR.BD3_0 = 1; // GPT3 GTCCR バッファ動作禁止
GPT::GTBDR.BD3_1 = 1; // GPT3 GTPR バッファ動作禁止
GPT::GTBDR.BD3_2 = 1; // GPT3 GTADTR バッファ動作禁止
GPT::GTBDR.BD3_3 = 1; // GPT3 GTDV バッファ動作禁止
break;
case 4:
GPTB::GTBDR.BD4_0 = 1; // GPT4 GTCCR バッファ動作禁止
GPTB::GTBDR.BD4_1 = 1; // GPT4 GTPR バッファ動作禁止
GPTB::GTBDR.BD4_2 = 1; // GPT4 GTADTR バッファ動作禁止
GPTB::GTBDR.BD4_3 = 1; // GPT4 GTDV バッファ動作禁止
break;
case 5:
GPTB::GTBDR.BD5_0 = 1; // GPT5 GTCCR バッファ動作禁止
GPTB::GTBDR.BD5_1 = 1; // GPT5 GTPR バッファ動作禁止
GPTB::GTBDR.BD5_2 = 1; // GPT5 GTADTR バッファ動作禁止
GPTB::GTBDR.BD5_3 = 1; // GPT5 GTDV バッファ動作禁止
break;
case 6:
GPTB::GTBDR.BD6_0 = 1; // GPT6 GTCCR バッファ動作禁止
GPTB::GTBDR.BD6_1 = 1; // GPT6 GTPR バッファ動作禁止
GPTB::GTBDR.BD6_2 = 1; // GPT6 GTADTR バッファ動作禁止
GPTB::GTBDR.BD6_3 = 1; // GPT6 GTDV バッファ動作禁止
break;
case 7:
GPTB::GTBDR.BD7_0 = 1; // GPT7 GTCCR バッファ動作禁止
GPTB::GTBDR.BD7_1 = 1; // GPT7 GTPR バッファ動作禁止
GPTB::GTBDR.BD7_2 = 1; // GPT7 GTADTR バッファ動作禁止
GPTB::GTBDR.BD7_3 = 1; // GPT7 GTDV バッファ動作禁止
break;
}
GPTX::GTPR = limit;
GPTX::GTCCRA = 0;
// カウント開始
switch(ch) {
case 0:
GPT::GTSTR.CST0 = 1;
break;
case 1:
GPT::GTSTR.CST1 = 1;
break;
case 2:
GPT::GTSTR.CST2 = 1;
break;
case 3:
GPT::GTSTR.CST3 = 1;
break;
case 4:
GPTB::GTSTR.CST4 = 1;
break;
case 5:
GPTB::GTSTR.CST5 = 1;
break;
case 6:
GPTB::GTSTR.CST6 = 1;
break;
case 7:
GPTB::GTSTR.CST7 = 1;
break;
}
}
//-----------------------------------------------------------------//
/*!
@brief 周期レジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_r(uint16_t n) {
GPTX::GTPR = n;
}
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーAレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_a(uint16_t n) { GPTX::GTCCRA = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーBレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_b(uint16_t n) { GPTX::GTCCRB = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーCレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_c(uint16_t n) { GPTX::GTCCRC = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーDレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_d(uint16_t n) { GPTX::GTCCRD = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーEレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_e(uint16_t n) { GPTX::GTCCRE = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーFレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_f(uint16_t n) { GPTX::GTCCRF = n; }
//-----------------------------------------------------------------//
/*!
@brief A/D 変換開始要求タイミングレジスターA設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_ad_a(uint16_t n) { GPTX::GTADTRA = n; }
//-----------------------------------------------------------------//
/*!
@brief A/D 変換開始要求タイミングレジスターB設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_ad_b(uint16_t n) { GPTX::GTADTRB = n; }
};
}
<commit_msg>cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX グループ・GPT I/O 制御
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2013, 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
/// F_PCLKA タイマーのクロックに必要なので定義が無い場合エラーにします。
#ifndef F_PCLKA
# error "gpt_io.hpp requires F_PCLKA to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief GPT I/O 制御クラス
@param[in] GPT GPTx定義クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class GPT>
class gpt_io {
// ※必要なら、実装する
void sleep_() { }
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
gpt_io() { }
#if 0
//-----------------------------------------------------------------//
/*!
@brief PWM を開始
@param[in] limit PWM カウンターのリミット
*/
//-----------------------------------------------------------------//
void start_pwm(uint16_t limit) {
uint32_t ch = GPT::get_chanel();
// 書き込み保護を解除
switch(ch) {
case 0:
GPT::GTWP.WP0 = 0;
break;
case 1:
GPT::GTWP.WP1 = 0;
break;
case 2:
GPT::GTWP.WP2 = 0;
break;
case 3:
GPT::GTWP.WP3 = 0;
break;
case 4:
GPTB::GTWP.WP4 = 0;
break;
case 5:
GPTB::GTWP.WP5 = 0;
break;
case 6:
GPTB::GTWP.WP6 = 0;
break;
case 7:
GPTB::GTWP.WP7 = 0;
break;
}
GPT::GTIOR.GTIOA = 0b011001;
GPT::GTONCR = GPT::GTONCR.OAE.b();
GPT::GTUDC = GPT::GTUDC.UD.b() | GPT::GTUDC.UDF.b(); // UP カウント設定
// バッファ動作設定
switch(ch) {
case 0:
GPT::GTBDR.BD0_0 = 1; // GPT0 GTCCR バッファ動作禁止
GPT::GTBDR.BD0_1 = 1; // GPT0 GTPR バッファ動作禁止
GPT::GTBDR.BD0_2 = 1; // GPT0 GTADTR バッファ動作禁止
GPT::GTBDR.BD0_3 = 1; // GPT0 GTDV バッファ動作禁止
break;
case 1:
GPT::GTBDR.BD1_0 = 1; // GPT1 GTCCR バッファ動作禁止
GPT::GTBDR.BD1_1 = 1; // GPT1 GTPR バッファ動作禁止
GPT::GTBDR.BD1_2 = 1; // GPT1 GTADTR バッファ動作禁止
GPT::GTBDR.BD1_3 = 1; // GPT1 GTDV バッファ動作禁止
break;
case 2:
GPT::GTBDR.BD2_0 = 1; // GPT2 GTCCR バッファ動作禁止
GPT::GTBDR.BD2_1 = 1; // GPT2 GTPR バッファ動作禁止
GPT::GTBDR.BD2_2 = 1; // GPT2 GTADTR バッファ動作禁止
GPT::GTBDR.BD2_3 = 1; // GPT2 GTDV バッファ動作禁止
break;
case 3:
GPT::GTBDR.BD3_0 = 1; // GPT3 GTCCR バッファ動作禁止
GPT::GTBDR.BD3_1 = 1; // GPT3 GTPR バッファ動作禁止
GPT::GTBDR.BD3_2 = 1; // GPT3 GTADTR バッファ動作禁止
GPT::GTBDR.BD3_3 = 1; // GPT3 GTDV バッファ動作禁止
break;
case 4:
GPTB::GTBDR.BD4_0 = 1; // GPT4 GTCCR バッファ動作禁止
GPTB::GTBDR.BD4_1 = 1; // GPT4 GTPR バッファ動作禁止
GPTB::GTBDR.BD4_2 = 1; // GPT4 GTADTR バッファ動作禁止
GPTB::GTBDR.BD4_3 = 1; // GPT4 GTDV バッファ動作禁止
break;
case 5:
GPTB::GTBDR.BD5_0 = 1; // GPT5 GTCCR バッファ動作禁止
GPTB::GTBDR.BD5_1 = 1; // GPT5 GTPR バッファ動作禁止
GPTB::GTBDR.BD5_2 = 1; // GPT5 GTADTR バッファ動作禁止
GPTB::GTBDR.BD5_3 = 1; // GPT5 GTDV バッファ動作禁止
break;
case 6:
GPTB::GTBDR.BD6_0 = 1; // GPT6 GTCCR バッファ動作禁止
GPTB::GTBDR.BD6_1 = 1; // GPT6 GTPR バッファ動作禁止
GPTB::GTBDR.BD6_2 = 1; // GPT6 GTADTR バッファ動作禁止
GPTB::GTBDR.BD6_3 = 1; // GPT6 GTDV バッファ動作禁止
break;
case 7:
GPTB::GTBDR.BD7_0 = 1; // GPT7 GTCCR バッファ動作禁止
GPTB::GTBDR.BD7_1 = 1; // GPT7 GTPR バッファ動作禁止
GPTB::GTBDR.BD7_2 = 1; // GPT7 GTADTR バッファ動作禁止
GPTB::GTBDR.BD7_3 = 1; // GPT7 GTDV バッファ動作禁止
break;
}
GPT::GTPR = limit;
GPT::GTCCRA = 0;
// カウント開始
switch(ch) {
case 0:
GPT::GTSTR.CST0 = 1;
break;
case 1:
GPT::GTSTR.CST1 = 1;
break;
case 2:
GPT::GTSTR.CST2 = 1;
break;
case 3:
GPT::GTSTR.CST3 = 1;
break;
case 4:
GPTB::GTSTR.CST4 = 1;
break;
case 5:
GPTB::GTSTR.CST5 = 1;
break;
case 6:
GPTB::GTSTR.CST6 = 1;
break;
case 7:
GPTB::GTSTR.CST7 = 1;
break;
}
}
#endif
//-----------------------------------------------------------------//
/*!
@brief 周期レジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_r(uint16_t n) {
GPT::GTPR = n;
}
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーAレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_a(uint16_t n) { GPT::GTCCRA = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーBレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_b(uint16_t n) { GPT::GTCCRB = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーCレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_c(uint16_t n) { GPT::GTCCRC = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーDレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_d(uint16_t n) { GPT::GTCCRD = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーEレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_e(uint16_t n) { GPT::GTCCRE = n; }
//-----------------------------------------------------------------//
/*!
@brief コンペアキャプチャーFレジスター設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_f(uint16_t n) { GPT::GTCCRF = n; }
//-----------------------------------------------------------------//
/*!
@brief A/D 変換開始要求タイミングレジスターA設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_ad_a(uint16_t n) { GPT::GTADTRA = n; }
//-----------------------------------------------------------------//
/*!
@brief A/D 変換開始要求タイミングレジスターB設定
@param[in] n 値
*/
//-----------------------------------------------------------------//
void set_ad_b(uint16_t n) { GPT::GTADTRB = n; }
};
}
<|endoftext|> |
<commit_before>/**
* \file prastar.cc
*
*
*
* \author Seth Lemons
* \date 2008-11-19
*/
#include <assert.h>
#include <math.h>
#include <errno.h>
#include <vector>
#include <limits>
extern "C" {
#include "lockfree/include/atomic.h"
}
#include "util/timer.h"
#include "util/mutex.h"
#include "util/msg_buffer.h"
#include "prastar.h"
#include "projection.h"
#include "search.h"
#include "state.h"
using namespace std;
PRAStar::PRAStarThread::PRAStarThread(PRAStar *p, vector<PRAStarThread *> *threads, CompletionCounter* cc)
: p(p),
threads(threads),
cc(cc),
q_empty(true)
{
time_spinning = 0;
out_qs.resize(threads->size(), NULL);
completed = false;
}
PRAStar::PRAStarThread::~PRAStarThread(void) {
vector<MsgBuffer<State*> *>::iterator i;
for (i = out_qs.begin(); i != out_qs.end(); i++)
if (*i)
delete *i;
}
vector<State*> *PRAStar::PRAStarThread::get_queue(void)
{
return &q;
}
Mutex *PRAStar::PRAStarThread::get_mutex(void)
{
return &mutex;
}
void PRAStar::PRAStarThread::post_send(void *t)
{
PRAStarThread *thr = (PRAStarThread*) t;
if (thr->completed) {
thr->cc->uncomplete();
thr->completed = false;
}
thr->q_empty = false;
}
bool PRAStar::PRAStarThread::flush_sends(void)
{
unsigned int i;
bool has_sends = false;
for (i = 0; i < threads->size(); i += 1) {
if (!out_qs[i])
continue;
if (out_qs[i]) {
out_qs[i]->try_flush();
if (!out_qs[i]->is_empty())
has_sends = true;
}
}
return has_sends;
}
/**
* Flush the queue
*/
void PRAStar::PRAStarThread::flush_receives(bool has_sends)
{
// wait for either completion or more nodes to expand
if (open.empty())
mutex.lock();
else if (!mutex.try_lock())
return;
if (q_empty && !has_sends) {
if (!open.empty()) {
mutex.unlock();
return;
}
completed = true;
cc->complete();
// busy wait
mutex.unlock();
while (q_empty && !cc->is_complete() && !p->is_done())
;
mutex.lock();
// we are done, just return
if (cc->is_complete()) {
assert(q_empty);
mutex.unlock();
return;
}
}
// got some stuff on the queue, lets do duplicate detection
// and add stuff to the open list
for (unsigned int i = 0; i < q.size(); i += 1) {
State *c = q[i];
State *dup = closed.lookup(c);
if (dup){
if (dup->get_g() > c->get_g()) {
dup->update(c->get_parent(),
c->get_c(),
c->get_g());
if (dup->is_open())
open.see_update(dup);
else
open.add(dup);
}
delete c;
}
else{
open.add(c);
closed.add(c);
}
}
q.clear();
q_empty = true;
mutex.unlock();
}
void PRAStar::PRAStarThread::send_state(State *c)
{
/*
unsigned long hash = p->project->project(c);
*/
unsigned long hash =
p->use_abstraction
? p->project->project(c)
: c->hash();
unsigned int dest_tid = threads->at(hash % p->n_threads)->get_id();
bool self_add = dest_tid == this->get_id();
if (self_add) {
State *dup = closed.lookup(c);
if (dup){
if (dup->get_g() > c->get_g()) {
dup->update(c->get_parent(),
c->get_c(),
c->get_g());
if (dup->is_open())
open.see_update(dup);
else
open.add(dup);
}
delete c;
}
else{
open.add(c);
closed.add(c);
}
return;
}
// not a self add
//
// Do a buffered send, in which case we can just sit on a lock
// because there is no work to do anyway.
if (!out_qs[dest_tid]) {
Mutex *lk = threads->at(dest_tid)->get_mutex();
vector<State*> *qu = threads->at(dest_tid)->get_queue();
out_qs[dest_tid] =
new MsgBuffer<State*>(lk, qu,
post_send,
threads->at(dest_tid));
}
out_qs[dest_tid]->try_send(c);
}
State *PRAStar::PRAStarThread::take(void)
{
Timer t;
bool entered_loop = false;
t.start();
while (open.empty() || !q_empty) {
entered_loop = true;
bool has_sends = flush_sends();
flush_receives(has_sends);
if (cc->is_complete()){
p->set_done();
return NULL;
}
}
t.stop();
if (entered_loop)
time_spinning += t.get_wall_time();
State *ret = NULL;
if (!p->is_done())
ret = open.take();
return ret;
}
/**
* Run the search thread.
*/
void PRAStar::PRAStarThread::run(void){
vector<State *> *children = NULL;
while(!p->is_done()){
State *s = take();
if (s == NULL)
continue;
if (s->get_f() >= p->bound.read()) {
open.prune();
continue;
}
if (s->is_goal()) {
p->set_path(s->get_path());
}
children = p->expand(s);
for (unsigned int i = 0; i < children->size(); i += 1) {
State *c = children->at(i);
if (c->get_f() < p->bound.read())
send_state(c);
}
}
if (children)
delete children;
}
/************************************************************/
PRAStar::PRAStar(unsigned int n_threads, bool use_abst)
: n_threads(n_threads),
bound(fp_infinity),
project(NULL),
path(NULL),
use_abstraction(use_abst){
done = false;
}
PRAStar::~PRAStar(void) {
}
void PRAStar::set_done()
{
mutex.lock();
done = true;
mutex.unlock();
}
bool PRAStar::is_done()
{
return done;
}
void PRAStar::set_path(vector<State *> *p)
{
mutex.lock();
if (this->path == NULL ||
this->path->at(0)->get_g() > p->at(0)->get_g()){
this->path = p;
bound.set(p->at(0)->get_g());
}
mutex.unlock();
}
bool PRAStar::has_path()
{
bool ret;
mutex.lock();
ret = (path != NULL);
mutex.unlock();
return ret;
}
vector<State *> *PRAStar::search(Timer *timer, State *init)
{
project = init->get_domain()->get_projection();
CompletionCounter cc = CompletionCounter(n_threads);
threads.resize(n_threads, NULL);
for (unsigned int i = 0; i < n_threads; i += 1)
threads.at(i) = new PRAStarThread(this, &threads, &cc);
if (use_abstraction)
threads.at(project->project(init)%n_threads)->open.add(init);
else
threads.at(init->hash() % n_threads)->open.add(init);
for (iter = threads.begin(); iter != threads.end(); iter++) {
(*iter)->start();
}
time_spinning = 0.0;
max_open_size = 0;
avg_open_size = 0;
for (iter = threads.begin(); iter != threads.end(); iter++) {
(*iter)->join();
time_spinning += (*iter)->time_spinning;
avg_open_size += (*iter)->open.get_avg_size();
if ((*iter)->open.get_max_size() > max_open_size)
max_open_size = (*iter)->open.get_max_size();
delete *iter;
}
avg_open_size /= n_threads;
return path;
}
void PRAStar::output_stats(void)
{
cout << "time-acquiring-locks: "
<< Mutex::get_lock_acquisition_time() << endl;
cout << "time-waiting: " << time_spinning << endl;
cout << "average-open-size: " << avg_open_size << endl;
cout << "max-open-size: " << max_open_size << endl;
}
<commit_msg>Fix a minor memory leak.<commit_after>/**
* \file prastar.cc
*
*
*
* \author Seth Lemons
* \date 2008-11-19
*/
#include <assert.h>
#include <math.h>
#include <errno.h>
#include <vector>
#include <limits>
extern "C" {
#include "lockfree/include/atomic.h"
}
#include "util/timer.h"
#include "util/mutex.h"
#include "util/msg_buffer.h"
#include "prastar.h"
#include "projection.h"
#include "search.h"
#include "state.h"
using namespace std;
PRAStar::PRAStarThread::PRAStarThread(PRAStar *p, vector<PRAStarThread *> *threads, CompletionCounter* cc)
: p(p),
threads(threads),
cc(cc),
q_empty(true)
{
time_spinning = 0;
out_qs.resize(threads->size(), NULL);
completed = false;
}
PRAStar::PRAStarThread::~PRAStarThread(void) {
vector<MsgBuffer<State*> *>::iterator i;
for (i = out_qs.begin(); i != out_qs.end(); i++)
if (*i)
delete *i;
}
vector<State*> *PRAStar::PRAStarThread::get_queue(void)
{
return &q;
}
Mutex *PRAStar::PRAStarThread::get_mutex(void)
{
return &mutex;
}
void PRAStar::PRAStarThread::post_send(void *t)
{
PRAStarThread *thr = (PRAStarThread*) t;
if (thr->completed) {
thr->cc->uncomplete();
thr->completed = false;
}
thr->q_empty = false;
}
bool PRAStar::PRAStarThread::flush_sends(void)
{
unsigned int i;
bool has_sends = false;
for (i = 0; i < threads->size(); i += 1) {
if (!out_qs[i])
continue;
if (out_qs[i]) {
out_qs[i]->try_flush();
if (!out_qs[i]->is_empty())
has_sends = true;
}
}
return has_sends;
}
/**
* Flush the queue
*/
void PRAStar::PRAStarThread::flush_receives(bool has_sends)
{
// wait for either completion or more nodes to expand
if (open.empty())
mutex.lock();
else if (!mutex.try_lock())
return;
if (q_empty && !has_sends) {
if (!open.empty()) {
mutex.unlock();
return;
}
completed = true;
cc->complete();
// busy wait
mutex.unlock();
while (q_empty && !cc->is_complete() && !p->is_done())
;
mutex.lock();
// we are done, just return
if (cc->is_complete()) {
assert(q_empty);
mutex.unlock();
return;
}
}
// got some stuff on the queue, lets do duplicate detection
// and add stuff to the open list
for (unsigned int i = 0; i < q.size(); i += 1) {
State *c = q[i];
State *dup = closed.lookup(c);
if (dup){
if (dup->get_g() > c->get_g()) {
dup->update(c->get_parent(),
c->get_c(),
c->get_g());
if (dup->is_open())
open.see_update(dup);
else
open.add(dup);
}
delete c;
}
else{
open.add(c);
closed.add(c);
}
}
q.clear();
q_empty = true;
mutex.unlock();
}
void PRAStar::PRAStarThread::send_state(State *c)
{
/*
unsigned long hash = p->project->project(c);
*/
unsigned long hash =
p->use_abstraction
? p->project->project(c)
: c->hash();
unsigned int dest_tid = threads->at(hash % p->n_threads)->get_id();
bool self_add = dest_tid == this->get_id();
if (self_add) {
State *dup = closed.lookup(c);
if (dup){
if (dup->get_g() > c->get_g()) {
dup->update(c->get_parent(),
c->get_c(),
c->get_g());
if (dup->is_open())
open.see_update(dup);
else
open.add(dup);
}
delete c;
}
else{
open.add(c);
closed.add(c);
}
return;
}
// not a self add
//
// Do a buffered send, in which case we can just sit on a lock
// because there is no work to do anyway.
if (!out_qs[dest_tid]) {
Mutex *lk = threads->at(dest_tid)->get_mutex();
vector<State*> *qu = threads->at(dest_tid)->get_queue();
out_qs[dest_tid] =
new MsgBuffer<State*>(lk, qu,
post_send,
threads->at(dest_tid));
}
out_qs[dest_tid]->try_send(c);
}
State *PRAStar::PRAStarThread::take(void)
{
Timer t;
bool entered_loop = false;
t.start();
while (open.empty() || !q_empty) {
entered_loop = true;
bool has_sends = flush_sends();
flush_receives(has_sends);
if (cc->is_complete()){
p->set_done();
return NULL;
}
}
t.stop();
if (entered_loop)
time_spinning += t.get_wall_time();
State *ret = NULL;
if (!p->is_done())
ret = open.take();
return ret;
}
/**
* Run the search thread.
*/
void PRAStar::PRAStarThread::run(void){
vector<State *> *children = NULL;
while(!p->is_done()){
State *s = take();
if (s == NULL)
continue;
if (s->get_f() >= p->bound.read()) {
open.prune();
continue;
}
if (s->is_goal()) {
p->set_path(s->get_path());
}
children = p->expand(s);
for (unsigned int i = 0; i < children->size(); i += 1) {
State *c = children->at(i);
if (c->get_f() < p->bound.read())
send_state(c);
else
delete c;
}
}
if (children)
delete children;
}
/************************************************************/
PRAStar::PRAStar(unsigned int n_threads, bool use_abst)
: n_threads(n_threads),
bound(fp_infinity),
project(NULL),
path(NULL),
use_abstraction(use_abst){
done = false;
}
PRAStar::~PRAStar(void) {
}
void PRAStar::set_done()
{
mutex.lock();
done = true;
mutex.unlock();
}
bool PRAStar::is_done()
{
return done;
}
void PRAStar::set_path(vector<State *> *p)
{
mutex.lock();
if (this->path == NULL ||
this->path->at(0)->get_g() > p->at(0)->get_g()){
this->path = p;
bound.set(p->at(0)->get_g());
}
mutex.unlock();
}
bool PRAStar::has_path()
{
bool ret;
mutex.lock();
ret = (path != NULL);
mutex.unlock();
return ret;
}
vector<State *> *PRAStar::search(Timer *timer, State *init)
{
project = init->get_domain()->get_projection();
CompletionCounter cc = CompletionCounter(n_threads);
threads.resize(n_threads, NULL);
for (unsigned int i = 0; i < n_threads; i += 1)
threads.at(i) = new PRAStarThread(this, &threads, &cc);
if (use_abstraction)
threads.at(project->project(init)%n_threads)->open.add(init);
else
threads.at(init->hash() % n_threads)->open.add(init);
for (iter = threads.begin(); iter != threads.end(); iter++) {
(*iter)->start();
}
time_spinning = 0.0;
max_open_size = 0;
avg_open_size = 0;
for (iter = threads.begin(); iter != threads.end(); iter++) {
(*iter)->join();
time_spinning += (*iter)->time_spinning;
avg_open_size += (*iter)->open.get_avg_size();
if ((*iter)->open.get_max_size() > max_open_size)
max_open_size = (*iter)->open.get_max_size();
delete *iter;
}
avg_open_size /= n_threads;
return path;
}
void PRAStar::output_stats(void)
{
cout << "time-acquiring-locks: "
<< Mutex::get_lock_acquisition_time() << endl;
cout << "time-waiting: " << time_spinning << endl;
cout << "average-open-size: " << avg_open_size << endl;
cout << "max-open-size: " << max_open_size << endl;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <bitcoin/bitcoin.hpp>
#include "util.hpp"
using namespace bc;
int main(int argc, char** argv)
{
if (argc > 2)
{
std::cerr << "sx pubkey [IS_COMPRESSED]" << std::endl;
return -1;
}
int is_compressed = -1;
if (argc == 2)
{
std::string flag_str = argv[1];
boost::algorithm::to_lower(flag_str);
if (flag_str == "1" || flag_str == "true" || flag_str == "yes")
is_compressed = 1;
else if (flag_str == "0" || flag_str == "false" || flag_str == "no")
is_compressed = 0;
else
{
std::cerr << "IS_COMPRESSED should be true or false." << std::endl;
return -1;
}
}
elliptic_curve_key key;
if (!read_private_key(key, is_compressed))
return -1;
std::cout << key.public_key() << std::endl;
return 0;
}
<commit_msg>allow the ability to read a public key for conversion purposes.<commit_after>#include <iostream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <bitcoin/bitcoin.hpp>
#include "util.hpp"
using namespace bc;
int main(int argc, char** argv)
{
if (argc > 2)
{
std::cerr << "sx pubkey [IS_COMPRESSED]" << std::endl;
return -1;
}
int is_compressed = -1;
if (argc == 2)
{
std::string flag_str = argv[1];
boost::algorithm::to_lower(flag_str);
if (flag_str == "1" || flag_str == "true" || flag_str == "yes")
is_compressed = 1;
else if (flag_str == "0" || flag_str == "false" || flag_str == "no")
is_compressed = 0;
else
{
std::cerr << "IS_COMPRESSED should be true or false." << std::endl;
return -1;
}
}
std::string arg = read_stdin();
elliptic_curve_key key;
if (!read_private_key(key, arg, is_compressed))
{
// Try reading it as a public key instead.
data_chunk pubkey = decode_hex(arg);
if (pubkey.empty())
{
std::cerr << "Invalid private or public key." << std::endl;
return -1;
}
// OK, it's a public key.
if (!key.set_public_key(pubkey))
{
std::cerr << "Invalid public key." << std::endl;
return -1;
}
if (is_compressed >= 0)
key.set_compressed(is_compressed);
}
std::cout << key.public_key() << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <boost/python.hpp>
#include <boost/python/exception_translator.hpp>
#include <boost/python/numpy.hpp>
#include "cimage.h"
#include "cproc.h"
#include "gil.h"
#include "except.h"
#include "bitmap.h"
using namespace boost::python;
class BitmapWrapper : public Bitmap
, public wrapper<Bitmap>
{
public:
BitmapWrapper(std::string filepath)
: Bitmap(filepath)
{
// nop
}
numpy::ndarray data_as_ndarray() const
{
tuple shape, strides;
numpy::dtype data_type = numpy::dtype::get_builtin<uint8_t>();
shape = make_tuple(_height,
_width,
3);
strides = make_tuple(_width * 3 * sizeof(uint8_t),
3 * sizeof(uint8_t),
sizeof(uint8_t));
return numpy::from_data(_data,
data_type,
shape,
strides,
object());
}
};
class CimageWrapper
: public Cimage
, public wrapper<Cimage>
{
public:
CimageWrapper(size_t width, size_t height)
: Cimage(width, height)
{
}
public:
void info()
{
ScopedPythonGILLock gil_lock;
override f = this->get_override("info");
if (f)
f();
else
Cimage::info();
}
};
void translate_FileError(FileError const & e)
{
PyErr_SetString(PyExc_OSError, "FileError");
}
BOOST_PYTHON_MODULE(pymycpp)
{
PyEval_InitThreads();
numpy::initialize();
register_exception_translator<FileError>(&translate_FileError);
class_<CimageWrapper, boost::noncopyable>(
"Cimage", init<size_t, size_t>())
.def("width", &CimageWrapper::width)
.def("height", &CimageWrapper::height)
.def("how_many_bytes", &CimageWrapper::how_many_bytes)
.staticmethod("how_many_bytes")
.def("info", &CimageWrapper::info)
;
class_<Cproc, boost::noncopyable>(
"Cproc", init<>())
.def("run", &Cproc::run)
.def("stop", &Cproc::stop)
;
class_<BitmapWrapper, boost::noncopyable>(
"Bitmap", init<std::string>())
.def("get_width", &BitmapWrapper::get_width)
.def("get_height", &BitmapWrapper::get_height)
.def("save", &BitmapWrapper::save)
.def("data", &BitmapWrapper::data_as_ndarray)
;
}
<commit_msg>Issue #16: exposed info method overrideably to Python<commit_after>#include <boost/python.hpp>
#include <boost/python/exception_translator.hpp>
#include <boost/python/numpy.hpp>
#include "cimage.h"
#include "cproc.h"
#include "gil.h"
#include "except.h"
#include "bitmap.h"
using namespace boost::python;
class BitmapWrapper : public Bitmap
, public wrapper<Bitmap>
{
public:
BitmapWrapper(std::string filepath)
: Bitmap(filepath)
{
// nop
}
numpy::ndarray data_as_ndarray() const
{
tuple shape, strides;
numpy::dtype data_type = numpy::dtype::get_builtin<uint8_t>();
shape = make_tuple(_height,
_width,
3);
strides = make_tuple(_width * 3 * sizeof(uint8_t),
3 * sizeof(uint8_t),
sizeof(uint8_t));
return numpy::from_data(_data,
data_type,
shape,
strides,
object());
}
std::string info() const
{
if (override f = this->get_override("info"))
return f();
else
return Bitmap::info();
}
};
class CimageWrapper
: public Cimage
, public wrapper<Cimage>
{
public:
CimageWrapper(size_t width, size_t height)
: Cimage(width, height)
{
}
public:
void info()
{
ScopedPythonGILLock gil_lock;
override f = this->get_override("info");
if (f)
f();
else
Cimage::info();
}
};
void translate_FileError(FileError const & e)
{
PyErr_SetString(PyExc_OSError, "FileError");
}
BOOST_PYTHON_MODULE(pymycpp)
{
PyEval_InitThreads();
numpy::initialize();
register_exception_translator<FileError>(&translate_FileError);
class_<CimageWrapper, boost::noncopyable>(
"Cimage", init<size_t, size_t>())
.def("width", &CimageWrapper::width)
.def("height", &CimageWrapper::height)
.def("how_many_bytes", &CimageWrapper::how_many_bytes)
.staticmethod("how_many_bytes")
.def("info", &CimageWrapper::info)
;
class_<Cproc, boost::noncopyable>(
"Cproc", init<>())
.def("run", &Cproc::run)
.def("stop", &Cproc::stop)
;
class_<BitmapWrapper, boost::noncopyable>(
"Bitmap", init<std::string>())
.def("get_width", &BitmapWrapper::get_width)
.def("get_height", &BitmapWrapper::get_height)
.def("save", &BitmapWrapper::save)
.def("data", &BitmapWrapper::data_as_ndarray)
.def("info", &BitmapWrapper::info)
;
}
<|endoftext|> |
<commit_before>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
DefinedRegular *ElfSym::Bss;
DefinedRegular *ElfSym::Etext1;
DefinedRegular *ElfSym::Etext2;
DefinedRegular *ElfSym::Edata1;
DefinedRegular *ElfSym::Edata2;
DefinedRegular *ElfSym::End1;
DefinedRegular *ElfSym::End2;
DefinedRegular *ElfSym::GlobalOffsetTable;
DefinedRegular *ElfSym::MipsGp;
DefinedRegular *ElfSym::MipsGpDisp;
DefinedRegular *ElfSym::MipsLocalGp;
static uint64_t getSymVA(const SymbolBody &Body, int64_t &Addend) {
switch (Body.kind()) {
case SymbolBody::DefinedRegularKind: {
auto &D = cast<DefinedRegular>(Body);
SectionBase *IS = D.Section;
if (auto *ISB = dyn_cast_or_null<InputSectionBase>(IS))
IS = ISB->Repl;
// According to the ELF spec reference to a local symbol from outside
// the group are not allowed. Unfortunately .eh_frame breaks that rule
// and must be treated specially. For now we just replace the symbol with
// 0.
if (IS == &InputSection::Discarded)
return 0;
// This is an absolute symbol.
if (!IS)
return D.Value;
uint64_t Offset = D.Value;
// An object in an SHF_MERGE section might be referenced via a
// section symbol (as a hack for reducing the number of local
// symbols).
// Depending on the addend, the reference via a section symbol
// refers to a different object in the merge section.
// Since the objects in the merge section are not necessarily
// contiguous in the output, the addend can thus affect the final
// VA in a non-linear way.
// To make this work, we incorporate the addend into the section
// offset (and zero out the addend for later processing) so that
// we find the right object in the section.
if (D.isSection()) {
Offset += Addend;
Addend = 0;
}
const OutputSection *OutSec = IS->getOutputSection();
// In the typical case, this is actually very simple and boils
// down to adding together 3 numbers:
// 1. The address of the output section.
// 2. The offset of the input section within the output section.
// 3. The offset within the input section (this addition happens
// inside InputSection::getOffset).
//
// If you understand the data structures involved with this next
// line (and how they get built), then you have a pretty good
// understanding of the linker.
uint64_t VA = (OutSec ? OutSec->Addr : 0) + IS->getOffset(Offset);
if (D.isTls() && !Config->Relocatable) {
if (!Out::TlsPhdr)
fatal(toString(D.getFile()) +
" has an STT_TLS symbol but doesn't have an SHF_TLS section");
return VA - Out::TlsPhdr->p_vaddr;
}
return VA;
}
case SymbolBody::DefinedCommonKind:
llvm_unreachable("common are converted to bss");
case SymbolBody::SharedKind: {
auto &SS = cast<SharedSymbol>(Body);
if (SS.CopyRelSec)
return SS.CopyRelSec->getParent()->Addr + SS.CopyRelSec->OutSecOff;
if (SS.NeedsPltAddr)
return Body.getPltVA();
return 0;
}
case SymbolBody::UndefinedKind:
return 0;
case SymbolBody::LazyArchiveKind:
case SymbolBody::LazyObjectKind:
assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
return 0;
}
llvm_unreachable("invalid symbol kind");
}
SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolKind(K), IsLocal(IsLocal), NeedsPltAddr(false),
IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
IsInIgot(false), IsPreemptible(false), Type(Type), StOther(StOther),
Name(Name) {}
// Returns true if this is a weak undefined symbol.
bool SymbolBody::isUndefWeak() const {
// A note on isLazy() in the following expression: If you add a weak
// undefined symbol and then a lazy symbol to the symbol table, the
// combined result is a lazy weak symbol. isLazy is for that sitaution.
//
// Weak undefined symbols shouldn't fetch archive members (for
// compatibility with other linkers), but we still want to memorize
// that there are lazy symbols, because strong undefined symbols
// could be added later which triggers archive member fetching.
// Thus, the weak lazy symbol is a valid concept in lld.
return !isLocal() && symbol()->isWeak() && (isUndefined() || isLazy());
}
InputFile *SymbolBody::getFile() const {
if (isLocal()) {
const SectionBase *Sec = cast<DefinedRegular>(this)->Section;
// Local absolute symbols actually have a file, but that is not currently
// used. We could support that by having a mostly redundant InputFile in
// SymbolBody, or having a special absolute section if needed.
return Sec ? cast<InputSectionBase>(Sec)->File : nullptr;
}
return symbol()->File;
}
// Overwrites all attributes with Other's so that this symbol becomes
// an alias to Other. This is useful for handling some options such as
// --wrap.
void SymbolBody::copyFrom(SymbolBody *Other) {
memcpy(symbol()->Body.buffer, Other->symbol()->Body.buffer,
sizeof(Symbol::Body));
}
uint64_t SymbolBody::getVA(int64_t Addend) const {
uint64_t OutVA = getSymVA(*this, Addend);
return OutVA + Addend;
}
uint64_t SymbolBody::getGotVA() const {
return InX::Got->getVA() + getGotOffset();
}
uint64_t SymbolBody::getGotOffset() const {
return GotIndex * Target->GotEntrySize;
}
uint64_t SymbolBody::getGotPltVA() const {
if (this->IsInIgot)
return InX::IgotPlt->getVA() + getGotPltOffset();
return InX::GotPlt->getVA() + getGotPltOffset();
}
uint64_t SymbolBody::getGotPltOffset() const {
return GotPltIndex * Target->GotPltEntrySize;
}
uint64_t SymbolBody::getPltVA() const {
if (this->IsInIplt)
return InX::Iplt->getVA() + PltIndex * Target->PltEntrySize;
return InX::Plt->getVA() + Target->PltHeaderSize +
PltIndex * Target->PltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
if (const auto *C = dyn_cast<DefinedCommon>(this))
return C->Size;
if (const auto *DR = dyn_cast<DefinedRegular>(this))
return DR->Size;
if (const auto *S = dyn_cast<SharedSymbol>(this))
return S->getSize<ELFT>();
return 0;
}
OutputSection *SymbolBody::getOutputSection() const {
if (auto *S = dyn_cast<DefinedRegular>(this)) {
if (S->Section)
return S->Section->getOutputSection();
return nullptr;
}
if (auto *S = dyn_cast<SharedSymbol>(this)) {
if (S->CopyRelSec)
return S->CopyRelSec->getParent();
return nullptr;
}
if (auto *S = dyn_cast<DefinedCommon>(this)) {
if (Config->DefineCommon)
return S->Section->getParent();
return nullptr;
}
return nullptr;
}
// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
StringRef S = getName();
size_t Pos = S.find('@');
if (Pos == 0 || Pos == StringRef::npos)
return;
StringRef Verstr = S.substr(Pos + 1);
if (Verstr.empty())
return;
// Truncate the symbol name so that it doesn't include the version string.
Name = {S.data(), Pos};
// If this is not in this DSO, it is not a definition.
if (!isInCurrentDSO())
return;
// '@@' in a symbol name means the default version.
// It is usually the most recent one.
bool IsDefault = (Verstr[0] == '@');
if (IsDefault)
Verstr = Verstr.substr(1);
for (VersionDefinition &Ver : Config->VersionDefinitions) {
if (Ver.Name != Verstr)
continue;
if (IsDefault)
symbol()->VersionId = Ver.Id;
else
symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
return;
}
// It is an error if the specified version is not defined.
// Usually version script is not provided when linking executable,
// but we may still want to override a versioned symbol from DSO,
// so we do not report error in this case.
if (Config->Shared)
error(toString(getFile()) + ": symbol " + S + " has undefined version " +
Verstr);
}
Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(K, Name, IsLocal, StOther, Type) {}
template <class ELFT> bool DefinedRegular::isMipsPIC() const {
typedef typename ELFT::Ehdr Elf_Ehdr;
if (!Section || !isFunc())
return false;
auto *Sec = cast<InputSectionBase>(Section);
const Elf_Ehdr *Hdr = Sec->template getFile<ELFT>()->getObj().getHeader();
return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
(Hdr->e_flags & EF_MIPS_PIC);
}
Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {}
DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint32_t Alignment,
uint8_t StOther, uint8_t Type)
: Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
Type),
Alignment(Alignment), Size(Size) {}
// If a shared symbol is referred via a copy relocation, its alignment
// becomes part of the ABI. This function returns a symbol alignment.
// Because symbols don't have alignment attributes, we need to infer that.
template <class ELFT> uint32_t SharedSymbol::getAlignment() const {
SharedFile<ELFT> *File = getFile<ELFT>();
uint32_t SecAlign = File->getSection(getSym<ELFT>())->sh_addralign;
uint64_t SymValue = getSym<ELFT>().st_value;
uint32_t SymAlign = uint32_t(1) << countTrailingZeros(SymValue);
return std::min(SecAlign, SymAlign);
}
InputFile *Lazy::fetch() {
if (auto *S = dyn_cast<LazyArchive>(this))
return S->fetch();
return cast<LazyObject>(this)->fetch();
}
LazyArchive::LazyArchive(const llvm::object::Archive::Symbol S, uint8_t Type)
: Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {}
LazyObject::LazyObject(StringRef Name, uint8_t Type)
: Lazy(LazyObjectKind, Name, Type) {}
ArchiveFile *LazyArchive::getFile() {
return cast<ArchiveFile>(SymbolBody::getFile());
}
InputFile *LazyArchive::fetch() {
std::pair<MemoryBufferRef, uint64_t> MBInfo = getFile()->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBInfo.first.getBuffer().empty())
return nullptr;
return createObjectFile(MBInfo.first, getFile()->getName(), MBInfo.second);
}
LazyObjFile *LazyObject::getFile() {
return cast<LazyObjFile>(SymbolBody::getFile());
}
InputFile *LazyObject::fetch() { return getFile()->fetch(); }
uint8_t Symbol::computeBinding() const {
if (Config->Relocatable)
return Binding;
if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
return STB_LOCAL;
if (VersionId == VER_NDX_LOCAL && body()->isInCurrentDSO())
return STB_LOCAL;
if (Config->NoGnuUnique && Binding == STB_GNU_UNIQUE)
return STB_GLOBAL;
return Binding;
}
bool Symbol::includeInDynsym() const {
if (!Config->HasDynSymTab)
return false;
if (computeBinding() == STB_LOCAL)
return false;
if (!body()->isInCurrentDSO())
return true;
return ExportDynamic;
}
// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
SymbolBody *B = Sym->body();
std::string S;
if (B->isUndefined())
S = ": reference to ";
else if (B->isCommon())
S = ": common definition of ";
else
S = ": definition of ";
message(toString(Sym->File) + S + B->getName());
}
// Returns a symbol for an error message.
std::string lld::toString(const SymbolBody &B) {
if (Config->Demangle)
if (Optional<std::string> S = demangle(B.getName()))
return *S;
return B.getName();
}
template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64BE>() const;
<commit_msg>[LLD] Fix typo. NFC<commit_after>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
DefinedRegular *ElfSym::Bss;
DefinedRegular *ElfSym::Etext1;
DefinedRegular *ElfSym::Etext2;
DefinedRegular *ElfSym::Edata1;
DefinedRegular *ElfSym::Edata2;
DefinedRegular *ElfSym::End1;
DefinedRegular *ElfSym::End2;
DefinedRegular *ElfSym::GlobalOffsetTable;
DefinedRegular *ElfSym::MipsGp;
DefinedRegular *ElfSym::MipsGpDisp;
DefinedRegular *ElfSym::MipsLocalGp;
static uint64_t getSymVA(const SymbolBody &Body, int64_t &Addend) {
switch (Body.kind()) {
case SymbolBody::DefinedRegularKind: {
auto &D = cast<DefinedRegular>(Body);
SectionBase *IS = D.Section;
if (auto *ISB = dyn_cast_or_null<InputSectionBase>(IS))
IS = ISB->Repl;
// According to the ELF spec reference to a local symbol from outside
// the group are not allowed. Unfortunately .eh_frame breaks that rule
// and must be treated specially. For now we just replace the symbol with
// 0.
if (IS == &InputSection::Discarded)
return 0;
// This is an absolute symbol.
if (!IS)
return D.Value;
uint64_t Offset = D.Value;
// An object in an SHF_MERGE section might be referenced via a
// section symbol (as a hack for reducing the number of local
// symbols).
// Depending on the addend, the reference via a section symbol
// refers to a different object in the merge section.
// Since the objects in the merge section are not necessarily
// contiguous in the output, the addend can thus affect the final
// VA in a non-linear way.
// To make this work, we incorporate the addend into the section
// offset (and zero out the addend for later processing) so that
// we find the right object in the section.
if (D.isSection()) {
Offset += Addend;
Addend = 0;
}
const OutputSection *OutSec = IS->getOutputSection();
// In the typical case, this is actually very simple and boils
// down to adding together 3 numbers:
// 1. The address of the output section.
// 2. The offset of the input section within the output section.
// 3. The offset within the input section (this addition happens
// inside InputSection::getOffset).
//
// If you understand the data structures involved with this next
// line (and how they get built), then you have a pretty good
// understanding of the linker.
uint64_t VA = (OutSec ? OutSec->Addr : 0) + IS->getOffset(Offset);
if (D.isTls() && !Config->Relocatable) {
if (!Out::TlsPhdr)
fatal(toString(D.getFile()) +
" has an STT_TLS symbol but doesn't have an SHF_TLS section");
return VA - Out::TlsPhdr->p_vaddr;
}
return VA;
}
case SymbolBody::DefinedCommonKind:
llvm_unreachable("common are converted to bss");
case SymbolBody::SharedKind: {
auto &SS = cast<SharedSymbol>(Body);
if (SS.CopyRelSec)
return SS.CopyRelSec->getParent()->Addr + SS.CopyRelSec->OutSecOff;
if (SS.NeedsPltAddr)
return Body.getPltVA();
return 0;
}
case SymbolBody::UndefinedKind:
return 0;
case SymbolBody::LazyArchiveKind:
case SymbolBody::LazyObjectKind:
assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
return 0;
}
llvm_unreachable("invalid symbol kind");
}
SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolKind(K), IsLocal(IsLocal), NeedsPltAddr(false),
IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
IsInIgot(false), IsPreemptible(false), Type(Type), StOther(StOther),
Name(Name) {}
// Returns true if this is a weak undefined symbol.
bool SymbolBody::isUndefWeak() const {
// A note on isLazy() in the following expression: If you add a weak
// undefined symbol and then a lazy symbol to the symbol table, the
// combined result is a lazy weak symbol. isLazy is for that situation.
//
// Weak undefined symbols shouldn't fetch archive members (for
// compatibility with other linkers), but we still want to memorize
// that there are lazy symbols, because strong undefined symbols
// could be added later which triggers archive member fetching.
// Thus, the weak lazy symbol is a valid concept in lld.
return !isLocal() && symbol()->isWeak() && (isUndefined() || isLazy());
}
InputFile *SymbolBody::getFile() const {
if (isLocal()) {
const SectionBase *Sec = cast<DefinedRegular>(this)->Section;
// Local absolute symbols actually have a file, but that is not currently
// used. We could support that by having a mostly redundant InputFile in
// SymbolBody, or having a special absolute section if needed.
return Sec ? cast<InputSectionBase>(Sec)->File : nullptr;
}
return symbol()->File;
}
// Overwrites all attributes with Other's so that this symbol becomes
// an alias to Other. This is useful for handling some options such as
// --wrap.
void SymbolBody::copyFrom(SymbolBody *Other) {
memcpy(symbol()->Body.buffer, Other->symbol()->Body.buffer,
sizeof(Symbol::Body));
}
uint64_t SymbolBody::getVA(int64_t Addend) const {
uint64_t OutVA = getSymVA(*this, Addend);
return OutVA + Addend;
}
uint64_t SymbolBody::getGotVA() const {
return InX::Got->getVA() + getGotOffset();
}
uint64_t SymbolBody::getGotOffset() const {
return GotIndex * Target->GotEntrySize;
}
uint64_t SymbolBody::getGotPltVA() const {
if (this->IsInIgot)
return InX::IgotPlt->getVA() + getGotPltOffset();
return InX::GotPlt->getVA() + getGotPltOffset();
}
uint64_t SymbolBody::getGotPltOffset() const {
return GotPltIndex * Target->GotPltEntrySize;
}
uint64_t SymbolBody::getPltVA() const {
if (this->IsInIplt)
return InX::Iplt->getVA() + PltIndex * Target->PltEntrySize;
return InX::Plt->getVA() + Target->PltHeaderSize +
PltIndex * Target->PltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
if (const auto *C = dyn_cast<DefinedCommon>(this))
return C->Size;
if (const auto *DR = dyn_cast<DefinedRegular>(this))
return DR->Size;
if (const auto *S = dyn_cast<SharedSymbol>(this))
return S->getSize<ELFT>();
return 0;
}
OutputSection *SymbolBody::getOutputSection() const {
if (auto *S = dyn_cast<DefinedRegular>(this)) {
if (S->Section)
return S->Section->getOutputSection();
return nullptr;
}
if (auto *S = dyn_cast<SharedSymbol>(this)) {
if (S->CopyRelSec)
return S->CopyRelSec->getParent();
return nullptr;
}
if (auto *S = dyn_cast<DefinedCommon>(this)) {
if (Config->DefineCommon)
return S->Section->getParent();
return nullptr;
}
return nullptr;
}
// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
StringRef S = getName();
size_t Pos = S.find('@');
if (Pos == 0 || Pos == StringRef::npos)
return;
StringRef Verstr = S.substr(Pos + 1);
if (Verstr.empty())
return;
// Truncate the symbol name so that it doesn't include the version string.
Name = {S.data(), Pos};
// If this is not in this DSO, it is not a definition.
if (!isInCurrentDSO())
return;
// '@@' in a symbol name means the default version.
// It is usually the most recent one.
bool IsDefault = (Verstr[0] == '@');
if (IsDefault)
Verstr = Verstr.substr(1);
for (VersionDefinition &Ver : Config->VersionDefinitions) {
if (Ver.Name != Verstr)
continue;
if (IsDefault)
symbol()->VersionId = Ver.Id;
else
symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
return;
}
// It is an error if the specified version is not defined.
// Usually version script is not provided when linking executable,
// but we may still want to override a versioned symbol from DSO,
// so we do not report error in this case.
if (Config->Shared)
error(toString(getFile()) + ": symbol " + S + " has undefined version " +
Verstr);
}
Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(K, Name, IsLocal, StOther, Type) {}
template <class ELFT> bool DefinedRegular::isMipsPIC() const {
typedef typename ELFT::Ehdr Elf_Ehdr;
if (!Section || !isFunc())
return false;
auto *Sec = cast<InputSectionBase>(Section);
const Elf_Ehdr *Hdr = Sec->template getFile<ELFT>()->getObj().getHeader();
return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
(Hdr->e_flags & EF_MIPS_PIC);
}
Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {}
DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint32_t Alignment,
uint8_t StOther, uint8_t Type)
: Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
Type),
Alignment(Alignment), Size(Size) {}
// If a shared symbol is referred via a copy relocation, its alignment
// becomes part of the ABI. This function returns a symbol alignment.
// Because symbols don't have alignment attributes, we need to infer that.
template <class ELFT> uint32_t SharedSymbol::getAlignment() const {
SharedFile<ELFT> *File = getFile<ELFT>();
uint32_t SecAlign = File->getSection(getSym<ELFT>())->sh_addralign;
uint64_t SymValue = getSym<ELFT>().st_value;
uint32_t SymAlign = uint32_t(1) << countTrailingZeros(SymValue);
return std::min(SecAlign, SymAlign);
}
InputFile *Lazy::fetch() {
if (auto *S = dyn_cast<LazyArchive>(this))
return S->fetch();
return cast<LazyObject>(this)->fetch();
}
LazyArchive::LazyArchive(const llvm::object::Archive::Symbol S, uint8_t Type)
: Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {}
LazyObject::LazyObject(StringRef Name, uint8_t Type)
: Lazy(LazyObjectKind, Name, Type) {}
ArchiveFile *LazyArchive::getFile() {
return cast<ArchiveFile>(SymbolBody::getFile());
}
InputFile *LazyArchive::fetch() {
std::pair<MemoryBufferRef, uint64_t> MBInfo = getFile()->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBInfo.first.getBuffer().empty())
return nullptr;
return createObjectFile(MBInfo.first, getFile()->getName(), MBInfo.second);
}
LazyObjFile *LazyObject::getFile() {
return cast<LazyObjFile>(SymbolBody::getFile());
}
InputFile *LazyObject::fetch() { return getFile()->fetch(); }
uint8_t Symbol::computeBinding() const {
if (Config->Relocatable)
return Binding;
if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
return STB_LOCAL;
if (VersionId == VER_NDX_LOCAL && body()->isInCurrentDSO())
return STB_LOCAL;
if (Config->NoGnuUnique && Binding == STB_GNU_UNIQUE)
return STB_GLOBAL;
return Binding;
}
bool Symbol::includeInDynsym() const {
if (!Config->HasDynSymTab)
return false;
if (computeBinding() == STB_LOCAL)
return false;
if (!body()->isInCurrentDSO())
return true;
return ExportDynamic;
}
// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
SymbolBody *B = Sym->body();
std::string S;
if (B->isUndefined())
S = ": reference to ";
else if (B->isCommon())
S = ": common definition of ";
else
S = ": definition of ";
message(toString(Sym->File) + S + B->getName());
}
// Returns a symbol for an error message.
std::string lld::toString(const SymbolBody &B) {
if (Config->Demangle)
if (Optional<std::string> S = demangle(B.getName()))
return *S;
return B.getName();
}
template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64BE>() const;
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2018 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "random.h"
#include "crypto/sha512.h"
#include "support/cleanse.h"
#ifdef WIN32
#include "compat.h" // for Windows API
#include <wincrypt.h>
#endif
#include "serialize.h" // for begin_ptr(vec)
#include "util.h" // for LOG()
#include "utilstrencodings.h" // for GetTime()
#include <limits>
#include <stdlib.h>
#ifndef WIN32
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_GETRANDOM
#include <linux/random.h>
#include <sys/syscall.h>
#endif
#ifdef HAVE_GETENTROPY
#include <unistd.h>
#endif
#ifdef HAVE_SYSCTL_ARND
#include <sys/sysctl.h>
#endif
#include <openssl/err.h>
#include <openssl/rand.h>
static void RandFailure()
{
LOGA("Failed to read randomness, aborting\n");
abort();
}
static inline int64_t GetPerformanceCounter()
{
int64_t nCounter = 0;
#ifdef WIN32
QueryPerformanceCounter((LARGE_INTEGER *)&nCounter);
#else
timeval t;
gettimeofday(&t, nullptr);
nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec);
#endif
return nCounter;
}
#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
static std::atomic<bool> hwrand_initialized{false};
static bool rdrand_supported = false;
static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
static void RDRandInit()
{
//! When calling cpuid function #1, ecx register will have this set if RDRAND is available.
// Avoid clobbering ebx, as that is used for PIC on x86.
uint32_t eax, tmp, ecx, edx;
__asm__("mov %%ebx, %1; cpuid; mov %1, %%ebx" : "=a"(eax), "=g"(tmp), "=c"(ecx), "=d"(edx) : "a"(1));
if (ecx & CPUID_F1_ECX_RDRAND)
{
LOGA("Using RdRand as entropy source\n");
rdrand_supported = true;
}
hwrand_initialized.store(true);
}
#else
static void RDRandInit() {}
#endif
static bool GetHWRand(unsigned char *ent32)
{
#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
assert(hwrand_initialized.load(std::memory_order_relaxed));
if (rdrand_supported)
{
uint8_t ok;
// Not all assemblers support the rdrand instruction, write it in hex.
#ifdef __i386__
for (int iter = 0; iter < 4; ++iter)
{
uint32_t r1, r2;
__asm__ volatile(".byte 0x0f, 0xc7, 0xf0;" // rdrand %eax
".byte 0x0f, 0xc7, 0xf2;" // rdrand %edx
"setc %2"
: "=a"(r1), "=d"(r2), "=q"(ok)::"cc");
if (!ok)
return false;
WriteLE32(ent32 + 8 * iter, r1);
WriteLE32(ent32 + 8 * iter + 4, r2);
}
#else
uint64_t r1, r2, r3, r4;
__asm__ volatile(".byte 0x48, 0x0f, 0xc7, 0xf0, " // rdrand %rax
"0x48, 0x0f, 0xc7, 0xf3, " // rdrand %rbx
"0x48, 0x0f, 0xc7, 0xf1, " // rdrand %rcx
"0x48, 0x0f, 0xc7, 0xf2; " // rdrand %rdx
"setc %4"
: "=a"(r1), "=b"(r2), "=c"(r3), "=d"(r4), "=q"(ok)::"cc");
if (!ok)
return false;
WriteLE64(ent32, r1);
WriteLE64(ent32 + 8, r2);
WriteLE64(ent32 + 16, r3);
WriteLE64(ent32 + 24, r4);
#endif
return true;
}
#endif
return false;
}
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memory_cleanse((void *)&nCounter, sizeof(nCounter));
}
static void RandAddSeedPerfmon()
{
RandAddSeed();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
std::vector<unsigned char> vData(250000, 0);
long ret = 0;
unsigned long nSize = 0;
const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data
while (true)
{
nSize = vData.size();
ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, begin_ptr(vData), &nSize);
if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
break;
vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially
}
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(begin_ptr(vData), nSize, nSize / 100.0);
memory_cleanse(begin_ptr(vData), nSize);
LOG(RAND, "%s: %lu bytes\n", __func__, nSize);
}
else
{
static bool warned = false; // Warn only once
if (!warned)
{
LOGA("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret);
warned = true;
}
}
#endif
}
#ifndef WIN32
/** Fallback: get 32 bytes of system entropy from /dev/urandom. The most
* compatible way to get cryptographic randomness on UNIX-ish platforms.
*/
void GetDevURandom(unsigned char *ent32)
{
int f = open("/dev/urandom", O_RDONLY);
if (f == -1)
{
close(f);
RandFailure();
}
int have = 0;
do
{
ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES)
{
RandFailure();
}
have += n;
} while (have < NUM_OS_RANDOM_BYTES);
close(f);
}
#endif
/** Get 32 bytes of system entropy. */
void GetOSRand(unsigned char *ent32)
{
#ifdef WIN32
HCRYPTPROV hProvider;
int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if (!ret)
{
RandFailure();
}
ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
if (!ret)
{
RandFailure();
}
CryptReleaseContext(hProvider, 0);
#elif defined(HAVE_SYS_GETRANDOM)
/* Linux. From the getrandom(2) man page:
* "If the urandom source has been initialized, reads of up to 256 bytes
* will always return as many bytes as requested and will not be
* interrupted by signals."
*/
int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0);
if (rv != NUM_OS_RANDOM_BYTES)
{
if (rv < 0 && errno == ENOSYS)
{
/* Fallback for kernel <3.17: the return value will be -1 and errno
* ENOSYS if the syscall is not available, in that case fall back
* to /dev/urandom.
*/
GetDevURandom(ent32);
}
else
{
RandFailure();
}
}
#elif defined(HAVE_GETENTROPY)
/* On OpenBSD this can return up to 256 bytes of entropy, will return an
* error if more are requested.
* The call cannot return less than the requested number of bytes.
*/
if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0)
{
RandFailure();
}
#elif defined(HAVE_SYSCTL_ARND)
/* FreeBSD and similar. It is possible for the call to return less
* bytes than requested, so need to read in a loop.
*/
static const int name[2] = {CTL_KERN, KERN_ARND};
int have = 0;
do
{
size_t len = NUM_OS_RANDOM_BYTES - have;
if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0)
{
RandFailure();
}
have += len;
} while (have < NUM_OS_RANDOM_BYTES);
#else
GetDevURandom(ent32);
#endif
}
void GetRandBytes(unsigned char *buf, int num)
{
if (RAND_bytes(buf, num) != 1)
{
RandFailure();
}
}
void GetStrongRandBytes(unsigned char *out, int num)
{
assert(num <= 32);
CSHA512 hasher;
unsigned char buf[64];
// First source: OpenSSL's RNG
RandAddSeedPerfmon();
GetRandBytes(buf, 32);
hasher.Write(buf, 32);
// Second source: OS RNG
GetOSRand(buf);
hasher.Write(buf, 32);
// Third source: HW RNG, if available.
if (GetHWRand(buf))
{
hasher.Write(buf, 32);
}
// Produce output
hasher.Finalize(buf);
memcpy(out, buf, num);
memory_cleanse(buf, 64);
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
{
GetRandBytes((unsigned char *)&nRand, sizeof(nRand));
} while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax) { return GetRand(nMax); }
uint256 GetRandHash()
{
uint256 hash;
GetRandBytes((unsigned char *)&hash, sizeof(hash));
return hash;
}
void FastRandomContext::RandomSeed()
{
uint256 seed = GetRandHash();
rng.SetKey(seed.begin(), 32);
requires_seed = false;
}
uint256 FastRandomContext::rand256()
{
if (bytebuf_size < 32)
{
FillByteBuffer();
}
uint256 ret;
memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32);
bytebuf_size -= 32;
return ret;
}
std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
{
std::vector<unsigned char> ret(len);
if (len > 0)
{
rng.Output(&ret[0], len);
}
return ret;
}
FastRandomContext::FastRandomContext(const uint256 &seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0)
{
rng.SetKey(seed.begin(), 32);
}
bool Random_SanityCheck()
{
/* This does not measure the quality of randomness, but it does test that
* OSRandom() overwrites all 32 bytes of the output given a maximum
* number of tries.
*/
static const ssize_t MAX_TRIES = 1024;
uint8_t data[NUM_OS_RANDOM_BYTES];
bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */
int num_overwritten;
int tries = 0;
/* Loop until all bytes have been overwritten at least once, or max number tries reached */
do
{
memset(data, 0, NUM_OS_RANDOM_BYTES);
GetOSRand(data);
for (int x = 0; x < NUM_OS_RANDOM_BYTES; ++x)
{
overwritten[x] |= (data[x] != 0);
}
num_overwritten = 0;
for (int x = 0; x < NUM_OS_RANDOM_BYTES; ++x)
{
if (overwritten[x])
{
num_overwritten += 1;
}
}
tries += 1;
} while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
return (num_overwritten == NUM_OS_RANDOM_BYTES); /* If this failed, bailed out after too many tries */
}
FastRandomContext::FastRandomContext(bool fDeterministic)
: requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0)
{
if (!fDeterministic)
{
return;
}
uint256 seed;
rng.SetKey(seed.begin(), 32);
}
void RandomInit() { RDRandInit(); }
<commit_msg>Add attribute [[noreturn]] (C++11) to functions that will not return<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2018 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "random.h"
#include "crypto/sha512.h"
#include "support/cleanse.h"
#ifdef WIN32
#include "compat.h" // for Windows API
#include <wincrypt.h>
#endif
#include "serialize.h" // for begin_ptr(vec)
#include "util.h" // for LOG()
#include "utilstrencodings.h" // for GetTime()
#include <limits>
#include <stdlib.h>
#ifndef WIN32
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_GETRANDOM
#include <linux/random.h>
#include <sys/syscall.h>
#endif
#ifdef HAVE_GETENTROPY
#include <unistd.h>
#endif
#ifdef HAVE_SYSCTL_ARND
#include <sys/sysctl.h>
#endif
#include <openssl/err.h>
#include <openssl/rand.h>
[[noreturn]] static void RandFailure()
{
LOGA("Failed to read randomness, aborting\n");
std::abort();
}
static inline int64_t GetPerformanceCounter()
{
int64_t nCounter = 0;
#ifdef WIN32
QueryPerformanceCounter((LARGE_INTEGER *)&nCounter);
#else
timeval t;
gettimeofday(&t, nullptr);
nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec);
#endif
return nCounter;
}
#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
static std::atomic<bool> hwrand_initialized{false};
static bool rdrand_supported = false;
static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
static void RDRandInit()
{
//! When calling cpuid function #1, ecx register will have this set if RDRAND is available.
// Avoid clobbering ebx, as that is used for PIC on x86.
uint32_t eax, tmp, ecx, edx;
__asm__("mov %%ebx, %1; cpuid; mov %1, %%ebx" : "=a"(eax), "=g"(tmp), "=c"(ecx), "=d"(edx) : "a"(1));
if (ecx & CPUID_F1_ECX_RDRAND)
{
LOGA("Using RdRand as entropy source\n");
rdrand_supported = true;
}
hwrand_initialized.store(true);
}
#else
static void RDRandInit() {}
#endif
static bool GetHWRand(unsigned char *ent32)
{
#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
assert(hwrand_initialized.load(std::memory_order_relaxed));
if (rdrand_supported)
{
uint8_t ok;
// Not all assemblers support the rdrand instruction, write it in hex.
#ifdef __i386__
for (int iter = 0; iter < 4; ++iter)
{
uint32_t r1, r2;
__asm__ volatile(".byte 0x0f, 0xc7, 0xf0;" // rdrand %eax
".byte 0x0f, 0xc7, 0xf2;" // rdrand %edx
"setc %2"
: "=a"(r1), "=d"(r2), "=q"(ok)::"cc");
if (!ok)
return false;
WriteLE32(ent32 + 8 * iter, r1);
WriteLE32(ent32 + 8 * iter + 4, r2);
}
#else
uint64_t r1, r2, r3, r4;
__asm__ volatile(".byte 0x48, 0x0f, 0xc7, 0xf0, " // rdrand %rax
"0x48, 0x0f, 0xc7, 0xf3, " // rdrand %rbx
"0x48, 0x0f, 0xc7, 0xf1, " // rdrand %rcx
"0x48, 0x0f, 0xc7, 0xf2; " // rdrand %rdx
"setc %4"
: "=a"(r1), "=b"(r2), "=c"(r3), "=d"(r4), "=q"(ok)::"cc");
if (!ok)
return false;
WriteLE64(ent32, r1);
WriteLE64(ent32 + 8, r2);
WriteLE64(ent32 + 16, r3);
WriteLE64(ent32 + 24, r4);
#endif
return true;
}
#endif
return false;
}
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memory_cleanse((void *)&nCounter, sizeof(nCounter));
}
static void RandAddSeedPerfmon()
{
RandAddSeed();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
std::vector<unsigned char> vData(250000, 0);
long ret = 0;
unsigned long nSize = 0;
const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data
while (true)
{
nSize = vData.size();
ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, begin_ptr(vData), &nSize);
if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
break;
vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially
}
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(begin_ptr(vData), nSize, nSize / 100.0);
memory_cleanse(begin_ptr(vData), nSize);
LOG(RAND, "%s: %lu bytes\n", __func__, nSize);
}
else
{
static bool warned = false; // Warn only once
if (!warned)
{
LOGA("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret);
warned = true;
}
}
#endif
}
#ifndef WIN32
/** Fallback: get 32 bytes of system entropy from /dev/urandom. The most
* compatible way to get cryptographic randomness on UNIX-ish platforms.
*/
void GetDevURandom(unsigned char *ent32)
{
int f = open("/dev/urandom", O_RDONLY);
if (f == -1)
{
close(f);
RandFailure();
}
int have = 0;
do
{
ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES)
{
RandFailure();
}
have += n;
} while (have < NUM_OS_RANDOM_BYTES);
close(f);
}
#endif
/** Get 32 bytes of system entropy. */
void GetOSRand(unsigned char *ent32)
{
#ifdef WIN32
HCRYPTPROV hProvider;
int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if (!ret)
{
RandFailure();
}
ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
if (!ret)
{
RandFailure();
}
CryptReleaseContext(hProvider, 0);
#elif defined(HAVE_SYS_GETRANDOM)
/* Linux. From the getrandom(2) man page:
* "If the urandom source has been initialized, reads of up to 256 bytes
* will always return as many bytes as requested and will not be
* interrupted by signals."
*/
int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0);
if (rv != NUM_OS_RANDOM_BYTES)
{
if (rv < 0 && errno == ENOSYS)
{
/* Fallback for kernel <3.17: the return value will be -1 and errno
* ENOSYS if the syscall is not available, in that case fall back
* to /dev/urandom.
*/
GetDevURandom(ent32);
}
else
{
RandFailure();
}
}
#elif defined(HAVE_GETENTROPY)
/* On OpenBSD this can return up to 256 bytes of entropy, will return an
* error if more are requested.
* The call cannot return less than the requested number of bytes.
*/
if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0)
{
RandFailure();
}
#elif defined(HAVE_SYSCTL_ARND)
/* FreeBSD and similar. It is possible for the call to return less
* bytes than requested, so need to read in a loop.
*/
static const int name[2] = {CTL_KERN, KERN_ARND};
int have = 0;
do
{
size_t len = NUM_OS_RANDOM_BYTES - have;
if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0)
{
RandFailure();
}
have += len;
} while (have < NUM_OS_RANDOM_BYTES);
#else
GetDevURandom(ent32);
#endif
}
void GetRandBytes(unsigned char *buf, int num)
{
if (RAND_bytes(buf, num) != 1)
{
RandFailure();
}
}
void GetStrongRandBytes(unsigned char *out, int num)
{
assert(num <= 32);
CSHA512 hasher;
unsigned char buf[64];
// First source: OpenSSL's RNG
RandAddSeedPerfmon();
GetRandBytes(buf, 32);
hasher.Write(buf, 32);
// Second source: OS RNG
GetOSRand(buf);
hasher.Write(buf, 32);
// Third source: HW RNG, if available.
if (GetHWRand(buf))
{
hasher.Write(buf, 32);
}
// Produce output
hasher.Finalize(buf);
memcpy(out, buf, num);
memory_cleanse(buf, 64);
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
{
GetRandBytes((unsigned char *)&nRand, sizeof(nRand));
} while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax) { return GetRand(nMax); }
uint256 GetRandHash()
{
uint256 hash;
GetRandBytes((unsigned char *)&hash, sizeof(hash));
return hash;
}
void FastRandomContext::RandomSeed()
{
uint256 seed = GetRandHash();
rng.SetKey(seed.begin(), 32);
requires_seed = false;
}
uint256 FastRandomContext::rand256()
{
if (bytebuf_size < 32)
{
FillByteBuffer();
}
uint256 ret;
memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32);
bytebuf_size -= 32;
return ret;
}
std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
{
std::vector<unsigned char> ret(len);
if (len > 0)
{
rng.Output(&ret[0], len);
}
return ret;
}
FastRandomContext::FastRandomContext(const uint256 &seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0)
{
rng.SetKey(seed.begin(), 32);
}
bool Random_SanityCheck()
{
/* This does not measure the quality of randomness, but it does test that
* OSRandom() overwrites all 32 bytes of the output given a maximum
* number of tries.
*/
static const ssize_t MAX_TRIES = 1024;
uint8_t data[NUM_OS_RANDOM_BYTES];
bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */
int num_overwritten;
int tries = 0;
/* Loop until all bytes have been overwritten at least once, or max number tries reached */
do
{
memset(data, 0, NUM_OS_RANDOM_BYTES);
GetOSRand(data);
for (int x = 0; x < NUM_OS_RANDOM_BYTES; ++x)
{
overwritten[x] |= (data[x] != 0);
}
num_overwritten = 0;
for (int x = 0; x < NUM_OS_RANDOM_BYTES; ++x)
{
if (overwritten[x])
{
num_overwritten += 1;
}
}
tries += 1;
} while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
return (num_overwritten == NUM_OS_RANDOM_BYTES); /* If this failed, bailed out after too many tries */
}
FastRandomContext::FastRandomContext(bool fDeterministic)
: requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0)
{
if (!fDeterministic)
{
return;
}
uint256 seed;
rng.SetKey(seed.begin(), 32);
}
void RandomInit() { RDRandInit(); }
<|endoftext|> |
<commit_before>//
// Exponent.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Exponential.h"
Exponential::Exponential(Expression* base, Rational* exponent){
this->type = "exponential";
this->base = base;
this->exponent = exponent;
this->exde = new Integer(exponent->getDenominator());
if (exde->getValue() != 1) {
//if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1
Integer* baseAsInteger = (Integer *) base;
base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);
Integer* one = new Integer(1);
exponent->setDenominator(one);
}
this->exnu = new Integer(exponent->getNumerator());
if (canExponentiate()) {
exponentiate();
}
}
Exponential::~Exponential(){
}
bool Exponential::canExponentiate() {
this->exponent->getNumerator()
if (this->exNu == 0) {
return true;
}
if(base->type == "euler"){
return false;
}else if(base->type == "exponential"){
Exponential* ex = (Exponential *) base;
this->exponent->multiply(ex->getExponent());
Integer* numSum = new Integer (1);
ex->getExponent()->setNumerator(numSum);
return false;
// false is returned because the base itself would have already been exponentiated if it were possible
}else if(base->type == "integer"){
return true;
}else if(base->type == "logarithm"){
return false;
}else if(base->type == "nthRoot"){
nthRoot* nr = (nthRoot *) base;
Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());
//makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one
this->exponent = r;
nr->setRoot(1);
return false;
}else if(base->type == "pi"){
return false;
}else if(base->type == "rational"){
Rational* r = (Rational *) base;
if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") {
Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);
r->setNumerator(nu);
Exponential* de = new Exponential(r->geteDenominator(), this->exponent);
r->setDenominator(de);
}
}else{
cout << "type not recognized" << endl;
}
return false;
}
void Exponential::exponentiate(){
Integer* one = new Integer(1);
if (this->exNu == 0) {
return one;
}
Rational* oneRat = new Rational(1, 1);
if (this->base->type == "rational") {
Rational* ratBase = (Rational *) this->base;
Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential
Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error
Rational* newRatBase = new Rational(numAsExponential, denAsExponential);
this->base = newRatBase;
this->exponent = oneRat;
}
else {
if (this->exponent->getNumerator()==0) {
this->exponent=oneRat;
this->base=one;
}
bool toFlip = false;
if (exnu->getValue()<0) {
exnu->setValue(exnu->getValue()*-1);
toFlip = true;
//handles negative exponents
}
Expression* constantBase = 0;
if (base->type == "integer") { //fixed the problem for integers but nothing else
Integer *a = (Integer *)base;
constantBase = new Integer(a->getValue());
}
while (exponent->getNumerator()>1)
{
base->multiply(constantBase);
exponent->setNumerator(exponent->geteNumerator()->subtract(one));
}
if (toFlip) {
Integer* one = new Integer(1);
Rational* mouse = new Rational(one, base);
base = mouse;
}
}
}
Expression* Exponential::add(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) {
if (ex->getExponent()==this->exponent) {
Integer* two = new Integer(2);
this->multiply(two);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::subtract(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) {
if (ex->getExponent()==this->exponent) {
Integer* zero = new Integer(0);
this->multiply(zero);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::multiply(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
//if (this->base == ex->getBase()) {
// this->exponent->add(ex->getExponent());
//}
if (ex->base->type == this->base->type) {
if ((ex->base->type == "euler") || (ex->base->type == "pi")) {
this->exponent->add(ex->exponent);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
Expression* numToSet = r->geteNumerator();
numToSet->multiply(this);
r->setNumerator(numToSet);
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::divide(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
//if (this->base == ex->getBase()) {
// this->exponent->subtract(ex->getExponent());
//}
if (ex->base->type == this->base->type) {
if ((ex->base->type == "euler") || (ex->base->type == "pi")) {
this->exponent->subtract(ex->exponent);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
Expression* denToSet = r->geteDenominator();
denToSet->multiply(this);
r->setDenominator(denToSet);
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Rational* Exponential::getExponent() {
return exponent;
}
Expression* Exponential::getBase() {
return base;
}
Integer* Exponential::getExnu() {
return exnu;
}
Integer* Exponential::getExde() {
return exde;
}
void Exponential::setExnu(Integer* n) {
exnu = n;
}
void Exponential::setExde(Integer* n) {
exde = n;
}
void Exponential::setExponent(Rational* e) {
exponent = e;
}
void Exponential::setBase(Expression* e) {
base = e;
}
string Exponential::toString() {
stringstream str;
if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){
str << *base;
}
else if(exponent->getDenominator() == 1){
str << *base << "^" << *exponent->geteNumerator();
}else{
str << *base << "^" << *exponent;
}
return str.str();
}
ostream& Exponential::print(std::ostream& output) const{
Exponential *a = (Exponential *)this;
output << a->toString();
return output;
}
bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)
if (this->type == b->type && this->type != "logarithm") {
if (this->type == "nthRoot") {
}
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canSubtract(Expression* b){
if (this->type == b->type) {
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canMultiply(Expression* b){
if (this->type == b->type) {
return true;
}
else if (this->base->type == b->type) {
return true;
}
else if(this->type == "integer" && b->type == "rational") return true;
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canDivide(Expression* b){
if (this->type == b->type) {
return true;
}
else if (this->base->type == b->type) {
return true;
}
else if(this->type == "integer"){
if( b->type == "rational") return true;
}
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
<commit_msg>fixed errors<commit_after>//
// Exponent.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Exponential.h"
Exponential::Exponential(Expression* base, Rational* exponent){
this->type = "exponential";
this->base = base;
this->exponent = exponent;
this->exde = new Integer(exponent->getDenominator());
if (exde->getValue() != 1) {
//if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1
Integer* baseAsInteger = (Integer *) base;
base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);
Integer* one = new Integer(1);
exponent->setDenominator(one);
}
this->exnu = new Integer(exponent->getNumerator());
if (canExponentiate()) {
exponentiate();
}
}
Exponential::~Exponential(){
}
bool Exponential::canExponentiate() {
this->exponent->getNumerator();
if (this->exnu == 0) {
return true;
}
if(base->type == "euler"){
return false;
}else if(base->type == "exponential"){
Exponential* ex = (Exponential *) base;
this->exponent->multiply(ex->getExponent());
Integer* numSum = new Integer (1);
ex->getExponent()->setNumerator(numSum);
return false;
// false is returned because the base itself would have already been exponentiated if it were possible
}else if(base->type == "integer"){
return true;
}else if(base->type == "logarithm"){
return false;
}else if(base->type == "nthRoot"){
nthRoot* nr = (nthRoot *) base;
Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());
//makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one
this->exponent = r;
nr->setRoot(1);
return false;
}else if(base->type == "pi"){
return false;
}else if(base->type == "rational"){
Rational* r = (Rational *) base;
if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") {
Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);
r->setNumerator(nu);
Exponential* de = new Exponential(r->geteDenominator(), this->exponent);
r->setDenominator(de);
}
}else{
cout << "type not recognized" << endl;
}
return false;
}
void Exponential::exponentiate(){
Integer* one = new Integer(1);
if (this->exnu == 0) {
return one;
}
Rational* oneRat = new Rational(1, 1);
if (this->base->type == "rational") {
Rational* ratBase = (Rational *) this->base;
Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential
Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error
Rational* newRatBase = new Rational(numAsExponential, denAsExponential);
this->base = newRatBase;
this->exponent = oneRat;
}
else {
if (this->exponent->getNumerator()==0) {
this->exponent=oneRat;
this->base=one;
}
bool toFlip = false;
if (exnu->getValue()<0) {
exnu->setValue(exnu->getValue()*-1);
toFlip = true;
//handles negative exponents
}
Expression* constantBase = 0;
if (base->type == "integer") { //fixed the problem for integers but nothing else
Integer *a = (Integer *)base;
constantBase = new Integer(a->getValue());
}
while (exponent->getNumerator()>1)
{
base->multiply(constantBase);
exponent->setNumerator(exponent->geteNumerator()->subtract(one));
}
if (toFlip) {
Integer* one = new Integer(1);
Rational* mouse = new Rational(one, base);
base = mouse;
}
}
}
Expression* Exponential::add(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) {
if (ex->getExponent()==this->exponent) {
Integer* two = new Integer(2);
this->multiply(two);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::subtract(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if ((ex->getBase()->type == this->base->type) && ((this->base->type == "euler") || (this->base->type == "pi"))) {
if (ex->getExponent()==this->exponent) {
Integer* zero = new Integer(0);
this->multiply(zero);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::multiply(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
//if (this->base == ex->getBase()) {
// this->exponent->add(ex->getExponent());
//}
if (ex->base->type == this->base->type) {
if ((ex->base->type == "euler") || (ex->base->type == "pi")) {
this->exponent->add(ex->exponent);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
Expression* numToSet = r->geteNumerator();
numToSet->multiply(this);
r->setNumerator(numToSet);
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::divide(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
//if (this->base == ex->getBase()) {
// this->exponent->subtract(ex->getExponent());
//}
if (ex->base->type == this->base->type) {
if ((ex->base->type == "euler") || (ex->base->type == "pi")) {
this->exponent->subtract(ex->exponent);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
Expression* denToSet = r->geteDenominator();
denToSet->multiply(this);
r->setDenominator(denToSet);
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Rational* Exponential::getExponent() {
return exponent;
}
Expression* Exponential::getBase() {
return base;
}
Integer* Exponential::getExnu() {
return exnu;
}
Integer* Exponential::getExde() {
return exde;
}
void Exponential::setExnu(Integer* n) {
exnu = n;
}
void Exponential::setExde(Integer* n) {
exde = n;
}
void Exponential::setExponent(Rational* e) {
exponent = e;
}
void Exponential::setBase(Expression* e) {
base = e;
}
string Exponential::toString() {
stringstream str;
if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){
str << *base;
}
else if(exponent->getDenominator() == 1){
str << *base << "^" << *exponent->geteNumerator();
}else{
str << *base << "^" << *exponent;
}
return str.str();
}
ostream& Exponential::print(std::ostream& output) const{
Exponential *a = (Exponential *)this;
output << a->toString();
return output;
}
bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)
if (this->type == b->type && this->type != "logarithm") {
if (this->type == "nthRoot") {
}
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canSubtract(Expression* b){
if (this->type == b->type) {
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canMultiply(Expression* b){
if (this->type == b->type) {
return true;
}
else if (this->base->type == b->type) {
return true;
}
else if(this->type == "integer" && b->type == "rational") return true;
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canDivide(Expression* b){
if (this->type == b->type) {
return true;
}
else if (this->base->type == b->type) {
return true;
}
else if(this->type == "integer"){
if( b->type == "rational") return true;
}
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
<|endoftext|> |
<commit_before>#ifndef TKBIO_H
#define TKBIO_H
#include <string>
using namespace std;
namespace tkbio {
class fragment {
string _sequence;
string _cigar;
string _chromosome;
int _position;
int _flag;
vector<pair<int,char> > _mapped;
public:
fragment(const string& chromosome, int position, int flag, const string& sequence, const string& cigar);
int position() const { return _position; }
int length() const { return _length; }
char orientation() const { return (flag & 16) == 0 : '+' : '-'; }
char get_base(int position) const;
static vector<pair<int,char> > resolve_map(int position, const string& cigar, const string& sequence);
};
}
#endif
<commit_msg>recrec.hxx<commit_after>#ifndef TKBIO_H
#define TKBIO_H
#include <string>
using namespace std;
namespace tkbio {
class fragment {
string _sequence;
string _cigar;
string _chromosome;
int _position;
int _flag;
vector<pair<int,char> > _mapped;
int _position5;
int _position3;
int _max_match_span;
private:
void initialize(int position, const string& sequence, const string& cigar);
vector<pair<int,char> > get_positions() const;
public:
fragment(const string& chromosome, int position, int flag, const string& sequence, const string& cigar);
int position() const { return _position; }
int span() const { return _position3 - _position5 + 1; }
//int length() const { return _length; }
char orientation() const { return (_flag & 16) == 0 ? '+' : '-'; }
char get_base(int position) const;
static vector<pair<int,char> > resolve_map(int position, const string& cigar, const string& sequence);
};
}
#endif
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id: render.cpp 44 2005-04-22 18:53:54Z pavlenko $
#include "render.hpp"
#include "image_util.hpp"
#include "utils.hpp"
#include "symbolizer.hpp"
#include "query.hpp"
#include "feature_layer_desc.hpp"
#include "attribute_collector.hpp"
#include "property_index.hpp"
#include <algorithm>
#include <cmath>
#include <set>
namespace mapnik
{
template <typename Image>
void Renderer<Image>::render_vector_layer(datasource_p const& ds,Map const& map,
std::vector<std::string> const& namedStyles,
unsigned width,unsigned height,
const Envelope<double>& bbox,Image& image)
{
CoordTransform t(width,height,bbox);
std::vector<std::string>::const_iterator stylesIter=namedStyles.begin();
while (stylesIter!=namedStyles.end())
{
std::set<std::string> names;
attribute_collector<Feature> collector(names);
property_index<Feature> indexer(names);
query q(bbox,width,height);
double scale = 1.0/t.scale();
std::vector<rule_type*> if_rules;
std::vector<rule_type*> else_rules;
bool active_rules=false;
feature_type_style const& style=map.find_style(*stylesIter++);
const std::vector<rule_type>& rules=style.get_rules();
std::vector<rule_type>::const_iterator ruleIter=rules.begin();
while (ruleIter!=rules.end())
{
if (ruleIter->active(scale))
{
active_rules=true;
filter_ptr& filter=const_cast<filter_ptr&>(ruleIter->get_filter());
filter->accept(collector);
filter->accept(indexer);
if (ruleIter->has_else_filter())
{
else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
}
else
{
if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
}
}
++ruleIter;
}
std::set<std::string>::const_iterator namesIter=names.begin();
// push all property names
while (namesIter!=names.end())
{
q.add_property_name(*namesIter);
++namesIter;
}
//only query datasource if there are active rules
if (active_rules)
{
featureset_ptr fs=ds->features(q);
if (fs)
{
feature_ptr feature;
while ((feature = fs->next()))
{
bool do_else=true;
std::vector<rule_type*>::const_iterator itr=if_rules.begin();
while (itr!=if_rules.end())
{
const filter_ptr& filter=(*itr)->get_filter();
if (filter->pass(*feature))
{
do_else=false;
const symbolizers& symbols = (*itr)->get_symbolizers();
symbolizers::const_iterator symIter=symbols.begin();
while (symIter!=symbols.end())
{
(*symIter)->render(*feature,t,image);
++symIter;
}
}
++itr;
}
if (do_else)
{
//else filter
std::vector<rule_type*>::const_iterator itr=else_rules.begin();
while (itr != else_rules.end())
{
const symbolizers& symbols = (*itr)->get_symbolizers();
symbolizers::const_iterator symIter=symbols.begin();
while (symIter!=symbols.end())
{
(*symIter)->render(*feature,t,image);
++symIter;
}
++itr;
}
}
}
}
}
}
}
template <typename Image>
void Renderer<Image>::render_raster_layer(datasource_p const& ds,
std::vector<std::string> const& ,
unsigned width,unsigned height,
const Envelope<double>& bbox,Image& image)
{
query q(bbox,width,height);
featureset_ptr fs=ds->features(q);
if (fs)
{
feature_ptr feature;
while ((feature = fs->next()))
{
raster_ptr const& raster=feature->get_raster();
if (raster)
{
image.set_rectangle(raster->x_,raster->y_,raster->data_);
}
}
}
}
template <typename Image>
void Renderer<Image>::render(Map const& map,Image& image)
{
timer clock;
//////////////////////////////////////////////////////
Envelope<double> const& extent=map.getCurrentExtent();
std::clog<<"BBOX:"<<extent<<std::endl;
double scale=map.scale();
std::clog<<" scale="<<scale<<std::endl;
unsigned width=map.getWidth();
unsigned height=map.getHeight();
Color const& background=map.getBackground();
image.setBackground(background);
for (size_t n=0;n<map.layerCount();++n)
{
Layer const& l=map.getLayer(n);
if (l.isVisible(scale) && l.envelope().intersects(extent))
{
datasource_p const& ds=l.datasource();
if (!ds) continue;
if (ds->type() == datasource::Vector)
{
render_vector_layer(ds,map,l.styles(),width,height,extent,image);
}
else if (ds->type() == datasource::Raster)
{
render_raster_layer(ds,l.styles(),width,height,extent,image);
}
}
}
clock.stop();
}
template class Renderer<Image32>;
}
<commit_msg>removed unused files<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of vanillacoin.
*
* vanillacoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <coin/constants.hpp>
#include <coin/logger.hpp>
#include <coin/reward.hpp>
using namespace coin;
std::int64_t reward::get_proof_of_work(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
return get_proof_of_work_vanilla(height, fees, hash_previous);
}
std::int64_t reward::get_proof_of_stake(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
return get_proof_of_stake_vanilla(coin_age, bits, time, height);
}
std::int64_t reward::get_proof_of_stake_ppcoin(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
static std::int64_t coin_reward_year = constants::cent;
std::int64_t subsidy = coin_age * 33 / (365 * 33 + 8) * coin_reward_year;
log_debug(
"Reward (ppcoin) create = " << subsidy << ", coin age = " << coin_age <<
", bits = " << bits << "."
);
return subsidy;
}
std::int64_t reward::get_proof_of_work_ppcoin(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
// :TODO: get_proof_of_work_ppcoin
return -1;
}
std::int64_t reward::get_proof_of_work_vanilla(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
std::int64_t subsidy = 0;
if (height >= 136400 && height <= 136400 + 1000)
{
subsidy = 1;
}
else
{
subsidy = 0;
/**
* The maximum coin supply is 30717658.00 over 13 years
* Year 1: 15733333.00
* Year 2: 23409756.00
* Year 3: 27154646.00
* Year 4: 28981324.00
* Year 5: 29872224.00
*/
subsidy = (1111.0 * (std::pow((height + 1.0), 2.0)));
if (subsidy > 128)
{
subsidy = 128;
}
if (subsidy < 1)
{
subsidy = 1;
}
subsidy *= 1000000;
for (auto i = 50000; i <= height; i += 50000)
{
subsidy -= subsidy / 6;
}
/**
* If the subsidy is less than 8 the miner gets 8 indefinitely or
* until the money supply limit is reached.
*/
if ((subsidy / 1000000.0f) < 8.0f)
{
subsidy = 8;
subsidy *= 1000000;
}
}
/**
* Fees are destroyed to limit inflation.
*/
return subsidy;
}
std::int64_t reward::get_proof_of_stake_vanilla(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
std::int64_t coin_reward_year = constants::max_mint_proof_of_stake;
enum { yearly_block_count = 365 * 432};
coin_reward_year = 1 * constants::max_mint_proof_of_stake;
std::int64_t subsidy = coin_age * coin_reward_year / 365;
log_debug(
"Reward (vanilla) create = " << subsidy << ", coin age = " <<
coin_age << ", bits = " << bits << "."
);
return subsidy;
}
<commit_msg>PoW Reward v2 activates at block 325000.<commit_after>/*
* Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of vanillacoin.
*
* vanillacoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <coin/constants.hpp>
#include <coin/logger.hpp>
#include <coin/reward.hpp>
using namespace coin;
std::int64_t reward::get_proof_of_work(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
return get_proof_of_work_vanilla(height, fees, hash_previous);
}
std::int64_t reward::get_proof_of_stake(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
return get_proof_of_stake_vanilla(coin_age, bits, time, height);
}
std::int64_t reward::get_proof_of_stake_ppcoin(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
static std::int64_t coin_reward_year = constants::cent;
std::int64_t subsidy = coin_age * 33 / (365 * 33 + 8) * coin_reward_year;
log_debug(
"Reward (ppcoin) create = " << subsidy << ", coin age = " << coin_age <<
", bits = " << bits << "."
);
return subsidy;
}
std::int64_t reward::get_proof_of_work_ppcoin(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
// :TODO: get_proof_of_work_ppcoin
return -1;
}
std::int64_t reward::get_proof_of_work_vanilla(
const std::int32_t & height, const std::int64_t & fees,
const sha256 & hash_previous
)
{
std::int64_t subsidy = 0;
if (height >= 136400 && height <= 136400 + 1000)
{
subsidy = 1;
}
else
{
subsidy = 0;
subsidy = (1111.0 * (std::pow((height + 1.0), 2.0)));
if (subsidy > 128)
{
subsidy = 128;
}
if (subsidy < 1)
{
subsidy = 1;
}
subsidy *= 1000000;
if (height < 325000)
{
for (auto i = 50000; i <= height; i += 50000)
{
subsidy -= subsidy / 6;
}
}
else
{
for (auto i = 10000; i <= height; i += 10000)
{
subsidy -=
subsidy / 28 - ((double)(10000.0f / height) *
((double)(10000.0f / height)))
;
subsidy -= (subsidy / 28 * 4) / 28;
}
}
if ((subsidy / 1000000.0f) < 2.0f)
{
subsidy = 2;
subsidy *= 1000000;
}
}
/**
* Fees are destroyed to limit inflation.
*/
return subsidy;
}
std::int64_t reward::get_proof_of_stake_vanilla(
const std::int64_t & coin_age, const std::uint32_t & bits,
const std::uint32_t & time, const std::int32_t & height
)
{
std::int64_t coin_reward_year = constants::max_mint_proof_of_stake;
enum { yearly_block_count = 365 * 432};
coin_reward_year = 1 * constants::max_mint_proof_of_stake;
std::int64_t subsidy = coin_age * coin_reward_year / 365;
log_debug(
"Reward (vanilla) create = " << subsidy << ", coin age = " <<
coin_age << ", bits = " << bits << "."
);
return subsidy;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* 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 <sys/stat.h>
#include <sys/types.h>
#include <set>
#include "java.h"
namespace
{
FILE* createFile(const std::string package, const Node* node)
{
std::string filename = package;
size_t pos = 0;
for (;;)
{
pos = filename.find('.', pos);
if (pos == std::string::npos)
{
break;
}
filename[pos] = '/';
}
filename += "/" + node->getName() + ".java";
std::string dir;
std::string path(filename);
for (;;)
{
size_t slash = path.find("/");
if (slash == std::string::npos)
{
break;
}
dir += path.substr(0, slash);
path.erase(0, slash + 1);
mkdir(dir.c_str(), 0777);
dir += '/';
}
printf("# %s in %s\n", node->getName().c_str(), filename.c_str());
return fopen(filename.c_str(), "w");
}
} // namespace
class JavaInterface : public Java
{
// TODO: Move to Java
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (dynamic_cast<Interface*>(element))
{
// Do not process Constructor.
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
element->accept(this);
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
JavaInterface(const char* source, FILE* file, const char* indent = "es") :
Java(source, file, indent)
{
}
virtual void at(const ExceptDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public class %s extends RuntimeException {\n", node->getName().c_str());
// TODO(Shiki): Need a constructor.
printChildren(node);
writeln("}");
}
virtual void at(const Interface* node)
{
if (!currentNode)
{
currentNode = node->getParent();
}
assert(!(node->getAttr() & Interface::Supplemental) && !node->isLeaf());
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
std::string name = node->getQualifiedName();
name = getInterfaceName(name);
write("public interface %s", name.substr(name.rfind(':') + 1).c_str());
if (node->getExtends())
{
const char* separator = " extends ";
for (NodeList::iterator i = node->getExtends()->begin();
i != node->getExtends()->end();
++i)
{
if ((*i)->getName() == Node::getBaseObjectName())
{
// Do not extend from 'Object'.
continue;
}
write(separator);
separator = ", ";
(*i)->accept(this);
}
}
write(" {\n");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
writeln("// %s", (*i)->getName().c_str());
const Node* saved = currentNode;
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
currentNode = *i;
visitInterfaceElement(*i, *j);
}
currentNode = saved;
}
writeln("}");
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
write("%s", node->getName().c_str());
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
node->getSpec()->accept(this);
}
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
if (node->isTypedef(node->getParent()))
{
return;
}
writetab();
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
if (node->isTypedef(node->getParent()))
{
write(";\n");
}
}
virtual void at(const ConstDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public static final ");
node->getSpec()->accept(this);
write(" %s = ", node->getName().c_str());
node->getExp()->accept(this);
write(";\n");
}
virtual void at(const Attribute* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
Java::getter(node);
write(";\n");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
writetab();
Java::setter(node);
write(";\n");
}
}
virtual void at(const OpDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
Java::at(node);
write(";\n");
}
};
class JavaImport : public Visitor, public Formatter
{
std::string package;
const Interface* current;
bool printed;
std::string prefixedName;
std::set<std::string> importSet;
public:
JavaImport(std::string package, FILE* file, const char* indent) :
Formatter(file, indent),
package(package),
current(0)
{
}
virtual void at(const Node* node)
{
visitChildren(node);
}
virtual void at(const ScopedName* node)
{
assert(current);
Node* resolved = node->search(current);
node->check(resolved, "could not resolved %s.", node->getName().c_str());
if (dynamic_cast<Interface*>(resolved) || dynamic_cast<ExceptDcl*>(resolved))
{
if (resolved->isBaseObject())
{
return;
}
if (Module* module = dynamic_cast<Module*>(resolved->getParent()))
{
if (prefixedName != module->getPrefixedName())
{
importSet.insert(Java::getPackageName(module->getPrefixedName()) + "." + resolved->getName());
}
}
}
}
virtual void at(const Interface* node)
{
if (current)
{
return;
}
current = node;
if (Module* module = dynamic_cast<Module*>(node->getParent()))
{
prefixedName = module->getPrefixedName();
}
visitChildren(node->getExtends());
visitChildren(node);
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
current = *i;
visitChildren(*i);
}
current = node;
}
virtual void at(const Attribute* node)
{
node->getSpec()->accept(this);
visitChildren(node->getGetRaises());
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
visitChildren(node->getSetRaises());
}
}
virtual void at(const OpDcl* node)
{
node->getSpec()->accept(this);
visitChildren(node);
visitChildren(node->getRaises());
}
virtual void at(const ParamDcl* node)
{
node->getSpec()->accept(this);
}
void print()
{
if (importSet.empty())
{
return;
}
for (std::set<std::string>::iterator i = importSet.begin();
i != importSet.end();
++i)
{
write("import %s;\n", (*i).c_str());
}
write("\n");
}
};
class JavaVisitor : public Visitor
{
const char* source;
const char* indent;
std::string prefixedName;
public:
JavaVisitor(const char* source, const char* indent = "es") :
source(source),
indent(indent)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
std::string enclosed = prefixedName;
prefixedName = node->getPrefixedName();
at(static_cast<const Node*>(node));
prefixedName = enclosed;
}
virtual void at(const ExceptDcl* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
virtual void at(const Interface* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source) ||
(node->getAttr() & Interface::Supplemental))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaImport import(Java::getPackageName(prefixedName), file, indent);
import.at(node);
import.print();
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
};
void printJava(const char* source, const char* indent)
{
JavaVisitor visitor(source, indent);
getSpecification()->accept(&visitor);
}
<commit_msg>(Java) : Fix to generate exception class member fields. Regression in r1380.<commit_after>/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* 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 <sys/stat.h>
#include <sys/types.h>
#include <set>
#include "java.h"
namespace
{
FILE* createFile(const std::string package, const Node* node)
{
std::string filename = package;
size_t pos = 0;
for (;;)
{
pos = filename.find('.', pos);
if (pos == std::string::npos)
{
break;
}
filename[pos] = '/';
}
filename += "/" + node->getName() + ".java";
std::string dir;
std::string path(filename);
for (;;)
{
size_t slash = path.find("/");
if (slash == std::string::npos)
{
break;
}
dir += path.substr(0, slash);
path.erase(0, slash + 1);
mkdir(dir.c_str(), 0777);
dir += '/';
}
printf("# %s in %s\n", node->getName().c_str(), filename.c_str());
return fopen(filename.c_str(), "w");
}
} // namespace
class JavaInterface : public Java
{
// TODO: Move to Java
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (dynamic_cast<Interface*>(element))
{
// Do not process Constructor.
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
element->accept(this);
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
JavaInterface(const char* source, FILE* file, const char* indent = "es") :
Java(source, file, indent)
{
}
virtual void at(const ExceptDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public class %s extends RuntimeException {\n", node->getName().c_str());
// TODO(Shiki): Need a constructor.
printChildren(node);
writeln("}");
}
virtual void at(const Interface* node)
{
if (!currentNode)
{
currentNode = node->getParent();
}
assert(!(node->getAttr() & Interface::Supplemental) && !node->isLeaf());
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
std::string name = node->getQualifiedName();
name = getInterfaceName(name);
write("public interface %s", name.substr(name.rfind(':') + 1).c_str());
if (node->getExtends())
{
const char* separator = " extends ";
for (NodeList::iterator i = node->getExtends()->begin();
i != node->getExtends()->end();
++i)
{
if ((*i)->getName() == Node::getBaseObjectName())
{
// Do not extend from 'Object'.
continue;
}
write(separator);
separator = ", ";
(*i)->accept(this);
}
}
write(" {\n");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
writeln("// %s", (*i)->getName().c_str());
const Node* saved = currentNode;
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
currentNode = *i;
visitInterfaceElement(*i, *j);
}
currentNode = saved;
}
writeln("}");
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
write("%s", node->getName().c_str());
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
node->getSpec()->accept(this);
}
else
{
// This node is an exception class member.
writetab();
write("public ");
node->getSpec()->accept(this);
write(" %s;\n", node->getName().c_str());
}
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
if (node->isTypedef(node->getParent()))
{
return;
}
writetab();
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
if (node->isTypedef(node->getParent()))
{
write(";\n");
}
}
virtual void at(const ConstDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public static final ");
node->getSpec()->accept(this);
write(" %s = ", node->getName().c_str());
node->getExp()->accept(this);
write(";\n");
}
virtual void at(const Attribute* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
Java::getter(node);
write(";\n");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
writetab();
Java::setter(node);
write(";\n");
}
}
virtual void at(const OpDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
Java::at(node);
write(";\n");
}
};
class JavaImport : public Visitor, public Formatter
{
std::string package;
const Interface* current;
bool printed;
std::string prefixedName;
std::set<std::string> importSet;
public:
JavaImport(std::string package, FILE* file, const char* indent) :
Formatter(file, indent),
package(package),
current(0)
{
}
virtual void at(const Node* node)
{
visitChildren(node);
}
virtual void at(const ScopedName* node)
{
assert(current);
Node* resolved = node->search(current);
node->check(resolved, "could not resolved %s.", node->getName().c_str());
if (dynamic_cast<Interface*>(resolved) || dynamic_cast<ExceptDcl*>(resolved))
{
if (resolved->isBaseObject())
{
return;
}
if (Module* module = dynamic_cast<Module*>(resolved->getParent()))
{
if (prefixedName != module->getPrefixedName())
{
importSet.insert(Java::getPackageName(module->getPrefixedName()) + "." + resolved->getName());
}
}
}
}
virtual void at(const Interface* node)
{
if (current)
{
return;
}
current = node;
if (Module* module = dynamic_cast<Module*>(node->getParent()))
{
prefixedName = module->getPrefixedName();
}
visitChildren(node->getExtends());
visitChildren(node);
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
current = *i;
visitChildren(*i);
}
current = node;
}
virtual void at(const Attribute* node)
{
node->getSpec()->accept(this);
visitChildren(node->getGetRaises());
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
visitChildren(node->getSetRaises());
}
}
virtual void at(const OpDcl* node)
{
node->getSpec()->accept(this);
visitChildren(node);
visitChildren(node->getRaises());
}
virtual void at(const ParamDcl* node)
{
node->getSpec()->accept(this);
}
void print()
{
if (importSet.empty())
{
return;
}
for (std::set<std::string>::iterator i = importSet.begin();
i != importSet.end();
++i)
{
write("import %s;\n", (*i).c_str());
}
write("\n");
}
};
class JavaVisitor : public Visitor
{
const char* source;
const char* indent;
std::string prefixedName;
public:
JavaVisitor(const char* source, const char* indent = "es") :
source(source),
indent(indent)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
std::string enclosed = prefixedName;
prefixedName = node->getPrefixedName();
at(static_cast<const Node*>(node));
prefixedName = enclosed;
}
virtual void at(const ExceptDcl* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
virtual void at(const Interface* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source) ||
(node->getAttr() & Interface::Supplemental))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaImport import(Java::getPackageName(prefixedName), file, indent);
import.at(node);
import.print();
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
};
void printJava(const char* source, const char* indent)
{
JavaVisitor visitor(source, indent);
getSpecification()->accept(&visitor);
}
<|endoftext|> |
<commit_before><commit_msg>output traffic cone from camera<commit_after><|endoftext|> |
<commit_before>/*
* File: cogwheeldatachannel.cpp
*
* Author: Robert Tizzard
*
* Created on August 10, 2017
*
* Copyright 2017.
*
*/
//
// Class: CogWheelDataChannel
//
// Description: Class to provide FTP server data channel functionality.
// The channel to created and destroyed on an as needed basis and can operate
// in the default active mode where the server creates it or in passive mode
// where the server waits for a connection from the client on a specified port.
//
//
// =============
// INCLUDE FILES
// =============
#include "cogwheeldatachannel.h"
#include "cogwheelcontrolchannel.h"
#include <QtCore>
#include <QAbstractSocket>
/**
* @brief CogWheelDataChannel::CogWheelDataChannel
*
* Create data channel instance. Create a socket and
* connect up its signals and slots.
*
* @param parent parent object (not used).
*/
CogWheelDataChannel::CogWheelDataChannel(QObject *parent)
{
Q_UNUSED(parent);
emit info("Data channel created.");
m_dataChannelSocket = new QTcpSocket();
if (m_dataChannelSocket==nullptr) {
emit error("Error trying to create data channel socket.");
return;
}
connect(m_dataChannelSocket, &QTcpSocket::connected, this, &CogWheelDataChannel::connected, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::disconnected, this, &CogWheelDataChannel::disconnected, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::stateChanged, this, &CogWheelDataChannel::stateChanged, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::bytesWritten, this, &CogWheelDataChannel::bytesWritten, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::readyRead, this, &CogWheelDataChannel::readyRead, Qt::DirectConnection);
connect(m_dataChannelSocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
this, &CogWheelDataChannel::socketError, Qt::DirectConnection);
}
/**
* @brief CogWheelDataChannel::connectToClient
*
* Connect up data channel; either from server (active)
* or from client (passive).
*
* @param connection Pointer to control channel instance.
*
* @return true on sucessful connection
*/
bool CogWheelDataChannel::connectToClient(CogWheelControlChannel *connection)
{
if (m_connected) {
emit error("Data channel already connected.");
return(m_connected);
}
if (!connection->isPassive()) {
emit info("Active Mode. Connecting data channel to client ....");
m_dataChannelSocket->connectToHost(m_clientHostIP, m_clientHostPort);
m_dataChannelSocket->waitForConnected(-1);
connection->sendReplyCode(150);
} else {
emit info("Passive Mode. Waiting to connect to data channel ....");
if (m_dataChannelSocket->state() != QAbstractSocket::ConnectedState) {
waitForNewConnection(-1);
}
connection->sendReplyCode(125);
}
emit info("connected.");
m_connected=true;
m_writeBytesSize = connection->writeBytesSize();
if (m_dataChannelSocket->state() != QAbstractSocket::ConnectedState) {
emit error("Data channel did not connect. Socket Error: "+m_dataChannelSocket->errorString());
}
return(m_connected);
}
/**
* @brief CogWheelDataChannel::disconnectFromClient
*
* Disconnect data channel.
*
* @param connection Pointer to control channel instance.
*/
void CogWheelDataChannel::disconnectFromClient(CogWheelControlChannel *connection)
{
if (m_dataChannelSocket->state() == QAbstractSocket::ConnectedState) {
m_dataChannelSocket->disconnectFromHost();
m_dataChannelSocket->waitForDisconnected(-1);
connection->sendReplyCode(226);
} else {
emit error("Data channel socket not connected.");
}
m_connected=false;
}
/**
* @brief CogWheelDataChannel::setClientHostIP
*
* Set client IP address for data channel connection.
*
* @param clientIP Client IP Address.
*/
void CogWheelDataChannel::setClientHostIP(QString clientIP)
{
emit info("Data channel client IP "+clientIP);
m_clientHostIP.setAddress(clientIP);
}
/**
* @brief CogWheelDataChannel::setClientHostPort
*
* Set client port number for data channel connection.
*
* @param clientPort Client port number.
*/
void CogWheelDataChannel::setClientHostPort(quint16 clientPort)
{
emit info("Data channel client Port "+QString::number(clientPort));
m_clientHostPort = clientPort;
}
/**
* @brief CogWheelDataChannel::listenForConnection
*
* Listen for connection from client (passive mode).
*
* @param serverIP Server IP address.
*/
void CogWheelDataChannel::listenForConnection(const QString &serverIP)
{
try
{
// Pick a random port and start listening
if(listen(QHostAddress::Any)) {
emit info ("Listening for passive connect....");
setClientHostIP(serverIP);
setClientHostPort(serverPort());
}
emit passiveConnection();
m_listening=true;
}catch(QString err) {
emit error(err);
}catch(...) {
emit error("Unknown error in listenForConnection().");
}
}
/**
* @brief CogWheelDataChannel::downloadFile
*
* Download a given local file over data channel to client.
*
* @param connection Pointer to control channel instance.
* @param fileName Local file name.
*/
void CogWheelDataChannel::downloadFile(CogWheelControlChannel *connection, const QString &fileName)
{
try {
m_fileBeingTransferred = new QFile(fileName);
if (m_fileBeingTransferred==nullptr) {
emit error("QFile instance for "+fileName+" could not be created.");
return;
}
// Open the file
if(!m_fileBeingTransferred->open(QFile::ReadOnly)) {
fileTransferCleanup();
emit error("Error: File "+fileName+" could not be opened.");
return;
}
emit info("Downloading file "+fileName+".");
// Move to the requested position
if(connection->restoreFilePostion() > 0) {
emit info("Restoring previous position.");
m_fileBeingTransferred->seek(connection->restoreFilePostion());
}
m_downloadFileSize = m_fileBeingTransferred->size()-connection->restoreFilePostion();
// Send initial block of file
if (m_fileBeingTransferred->size()) {
QByteArray buffer = m_fileBeingTransferred->read(m_writeBytesSize);
m_dataChannelSocket->write(buffer);
} else {
bytesWritten(0); // File is zero length (close connection/signal success)
}
} catch(QString err) {
fileTransferCleanup();
emit error(err);
} catch(...) {
fileTransferCleanup();
emit error("Unknown error in downloadFile().");
}
}
/**
* @brief CogWheelDataChannel::uploadFile
*
* Start upload of a given remote file to server over data channel.
* The actual upload takes place using the sockets readyRead() slot
* function.
*
* @param connection Pointer to control channel instance.
* @param fileName Local destination file name.
*/
void CogWheelDataChannel::uploadFile(CogWheelControlChannel *connection, const QString &fileName)
{
m_fileBeingTransferred = new QFile(fileName);
if (m_fileBeingTransferred==nullptr) {
emit error("QFile instance for "+fileName+" could not be cretaed.");
return;
}
if(!m_fileBeingTransferred->open(QFile::Append)) {
emit error("File "+fileName+" could not be opened.");
fileTransferCleanup();
return;
}
// Truncate the file if needed
if(connection->restoreFilePostion() > 0) {
if(!m_fileBeingTransferred->resize(connection->restoreFilePostion())) {
emit error("File "+fileName+" could not be truncated.");
fileTransferCleanup();
return;
}
}
}
/**
* @brief CogWheelDataChannel::incomingConnection
*
* Handle connection from client to server for data channel
* for passive mode.
*
* @param handle Handle to socket.
*/
void CogWheelDataChannel::incomingConnection(qintptr handle)
{
emit info("--- Incoming connection for data channel --- "+QString::number(handle));
if(!m_dataChannelSocket->setSocketDescriptor(handle)){
emit error( "Error binding socket: "+m_dataChannelSocket->errorString());
} else {
emit info("Data channel socket connected for handle : "+QString::number(handle));
}
}
/**
* @brief CogWheelDataChannel::connected
*
* Data channel socket connected slot function.
*
*/
void CogWheelDataChannel::connected()
{
emit info("Data channel connected.");
}
/**
* @brief CogWheelDataChannel::disconnected
*
* Data channel socket disconnect slot function. If a
* file is being uploaded/downloaded then reset any
* related variables
*
*/
void CogWheelDataChannel::disconnected()
{
emit info("Data channel disconnected.");
m_connected=false;
if (m_fileBeingTransferred) {
qDebug() << "Clean UUUUUUUUUUUUUUUUUUUUUPPPPPPPPPPPPPPPPPP";
emit transferFinished();
}
fileTransferCleanup();
}
/**
* @brief CogWheelDataChannel::stateChanged
*
* Data channel socket state changed slot function.
*
* @param socketState New socket state.
*/
void CogWheelDataChannel::stateChanged(QAbstractSocket::SocketState socketState)
{
Q_UNUSED(socketState);
}
/**
* @brief CogWheelDataChannel::bytesWritten
*
* Data channel socket bytes written slot function. If a file
* is being downloaded subtract bytes from file size and
* when reaches zero disconnect and signal complete.
*
* @param numBytes Number of bytes written (unused).
*/
void CogWheelDataChannel::bytesWritten(qint64 numBytes)
{
if (m_fileBeingTransferred) {
m_downloadFileSize -= numBytes;
if (m_downloadFileSize==0) {
// fileTransferCleanup();
m_dataChannelSocket->disconnectFromHost();
// emit downloadFinished();
return;
}
if (!m_fileBeingTransferred->atEnd()) {
QByteArray buffer = m_fileBeingTransferred->read(m_writeBytesSize);
m_dataChannelSocket->write(buffer);
}
}
}
/**
* @brief CogWheelDataChannel::fileTransferCleanup
*
* File upload/download cleanup code. This includes
* closing any file and deleting its data.
*/
void CogWheelDataChannel::fileTransferCleanup()
{
if (m_fileBeingTransferred) {
if (m_fileBeingTransferred->isOpen()) {
m_fileBeingTransferred->close();
}
m_fileBeingTransferred->deleteLater();
m_fileBeingTransferred=nullptr;
m_downloadFileSize=0;
}
}
/**
* @brief CogWheelDataChannel::readyRead
*
* Data channel socket readyRead slot function. Used to
* perform the uploading of a file to server once it has
* been kicked off.
*
*/
void CogWheelDataChannel::readyRead()
{
if(m_fileBeingTransferred) {
m_fileBeingTransferred->write(m_dataChannelSocket->readAll());
}
}
/**
* @brief CogWheelDataChannel::socketError
*
* ata channel socket error slot function.
*
* @param socketError Socket error.
*/
void CogWheelDataChannel::socketError(QAbstractSocket::SocketError socketError)
{
emit error("Data channel socket error: "+QString::number(socketError));
}
// ============================
// CLASS PRIVATE DATA ACCESSORS
// ============================
/**
* @brief CogWheelDataChannel::isConnected
* @return
*/
bool CogWheelDataChannel::isConnected() const
{
return m_connected;
}
/**
* @brief CogWheelDataChannel::setConnected
* @param connected
*/
void CogWheelDataChannel::setConnected(bool connected)
{
m_connected = connected;
}
/**
* @brief CogWheelDataChannel::isListening
* @return
*/
bool CogWheelDataChannel::isListening() const
{
return m_listening;
}
/**
* @brief CogWheelDataChannel::setListening
* @param listening
*/
void CogWheelDataChannel::setListening(bool listening)
{
m_listening = listening;
}
/**
* @brief CogWheelDataChannel::clientHostIP
* @return
*/
QHostAddress CogWheelDataChannel::clientHostIP() const
{
return m_clientHostIP;
}
/**
* @brief CogWheelDataChannel::clientHostPort
* @return
*/
quint16 CogWheelDataChannel::clientHostPort() const
{
return m_clientHostPort;
}
<commit_msg>Small change.<commit_after>/*
* File: cogwheeldatachannel.cpp
*
* Author: Robert Tizzard
*
* Created on August 10, 2017
*
* Copyright 2017.
*
*/
//
// Class: CogWheelDataChannel
//
// Description: Class to provide FTP server data channel functionality.
// The channel to created and destroyed on an as needed basis and can operate
// in the default active mode where the server creates it or in passive mode
// where the server waits for a connection from the client on a specified port.
//
//
// =============
// INCLUDE FILES
// =============
#include "cogwheeldatachannel.h"
#include "cogwheelcontrolchannel.h"
#include <QtCore>
#include <QAbstractSocket>
/**
* @brief CogWheelDataChannel::CogWheelDataChannel
*
* Create data channel instance. Create a socket and
* connect up its signals and slots.
*
* @param parent parent object (not used).
*/
CogWheelDataChannel::CogWheelDataChannel(QObject *parent)
{
Q_UNUSED(parent);
emit info("Data channel created.");
m_dataChannelSocket = new QTcpSocket();
if (m_dataChannelSocket==nullptr) {
emit error("Error trying to create data channel socket.");
return;
}
connect(m_dataChannelSocket, &QTcpSocket::connected, this, &CogWheelDataChannel::connected, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::disconnected, this, &CogWheelDataChannel::disconnected, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::stateChanged, this, &CogWheelDataChannel::stateChanged, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::bytesWritten, this, &CogWheelDataChannel::bytesWritten, Qt::DirectConnection);
connect(m_dataChannelSocket, &QTcpSocket::readyRead, this, &CogWheelDataChannel::readyRead, Qt::DirectConnection);
connect(m_dataChannelSocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
this, &CogWheelDataChannel::socketError, Qt::DirectConnection);
}
/**
* @brief CogWheelDataChannel::connectToClient
*
* Connect up data channel; either from server (active)
* or from client (passive).
*
* @param connection Pointer to control channel instance.
*
* @return true on sucessful connection
*/
bool CogWheelDataChannel::connectToClient(CogWheelControlChannel *connection)
{
if (m_connected) {
emit error("Data channel already connected.");
return(m_connected);
}
if (!connection->isPassive()) {
emit info("Active Mode. Connecting data channel to client ....");
m_dataChannelSocket->connectToHost(m_clientHostIP, m_clientHostPort);
m_dataChannelSocket->waitForConnected(-1);
connection->sendReplyCode(150);
} else {
emit info("Passive Mode. Waiting to connect to data channel ....");
if (m_dataChannelSocket->state() != QAbstractSocket::ConnectedState) {
waitForNewConnection(-1);
}
connection->sendReplyCode(125);
}
emit info("connected.");
m_connected=true;
m_writeBytesSize = connection->writeBytesSize();
if (m_dataChannelSocket->state() != QAbstractSocket::ConnectedState) {
emit error("Data channel did not connect. Socket Error: "+m_dataChannelSocket->errorString());
}
return(m_connected);
}
/**
* @brief CogWheelDataChannel::disconnectFromClient
*
* Disconnect data channel.
*
* @param connection Pointer to control channel instance.
*/
void CogWheelDataChannel::disconnectFromClient(CogWheelControlChannel *connection)
{
if (m_dataChannelSocket->state() == QAbstractSocket::ConnectedState) {
m_dataChannelSocket->disconnectFromHost();
m_dataChannelSocket->waitForDisconnected(-1);
connection->sendReplyCode(226);
} else {
emit error("Data channel socket not connected.");
}
m_connected=false;
}
/**
* @brief CogWheelDataChannel::setClientHostIP
*
* Set client IP address for data channel connection.
*
* @param clientIP Client IP Address.
*/
void CogWheelDataChannel::setClientHostIP(QString clientIP)
{
emit info("Data channel client IP "+clientIP);
m_clientHostIP.setAddress(clientIP);
}
/**
* @brief CogWheelDataChannel::setClientHostPort
*
* Set client port number for data channel connection.
*
* @param clientPort Client port number.
*/
void CogWheelDataChannel::setClientHostPort(quint16 clientPort)
{
emit info("Data channel client Port "+QString::number(clientPort));
m_clientHostPort = clientPort;
}
/**
* @brief CogWheelDataChannel::listenForConnection
*
* Listen for connection from client (passive mode).
*
* @param serverIP Server IP address.
*/
void CogWheelDataChannel::listenForConnection(const QString &serverIP)
{
try
{
// Pick a random port and start listening
if(listen(QHostAddress::Any)) {
emit info ("Listening for passive connect....");
setClientHostIP(serverIP);
setClientHostPort(serverPort());
}
emit passiveConnection();
m_listening=true;
}catch(QString err) {
emit error(err);
}catch(...) {
emit error("Unknown error in listenForConnection().");
}
}
/**
* @brief CogWheelDataChannel::downloadFile
*
* Download a given local file over data channel to client.
*
* @param connection Pointer to control channel instance.
* @param fileName Local file name.
*/
void CogWheelDataChannel::downloadFile(CogWheelControlChannel *connection, const QString &fileName)
{
try {
m_fileBeingTransferred = new QFile(fileName);
if (m_fileBeingTransferred==nullptr) {
emit error("QFile instance for "+fileName+" could not be created.");
return;
}
// Open the file
if(!m_fileBeingTransferred->open(QFile::ReadOnly)) {
fileTransferCleanup();
emit error("Error: File "+fileName+" could not be opened.");
return;
}
emit info("Downloading file "+fileName+".");
// Move to the requested position
if(connection->restoreFilePostion() > 0) {
emit info("Restoring previous position.");
m_fileBeingTransferred->seek(connection->restoreFilePostion());
}
m_downloadFileSize = m_fileBeingTransferred->size()-connection->restoreFilePostion();
// Send initial block of file
if (m_fileBeingTransferred->size()) {
QByteArray buffer = m_fileBeingTransferred->read(m_writeBytesSize);
m_dataChannelSocket->write(buffer);
} else {
bytesWritten(0); // File is zero length (close connection/signal success)
}
} catch(QString err) {
fileTransferCleanup();
emit error(err);
} catch(...) {
fileTransferCleanup();
emit error("Unknown error in downloadFile().");
}
}
/**
* @brief CogWheelDataChannel::uploadFile
*
* Start upload of a given remote file to server over data channel.
* The actual upload takes place using the sockets readyRead() slot
* function.
*
* @param connection Pointer to control channel instance.
* @param fileName Local destination file name.
*/
void CogWheelDataChannel::uploadFile(CogWheelControlChannel *connection, const QString &fileName)
{
m_fileBeingTransferred = new QFile(fileName);
if (m_fileBeingTransferred==nullptr) {
emit error("QFile instance for "+fileName+" could not be cretaed.");
return;
}
if(!m_fileBeingTransferred->open(QFile::Append)) {
emit error("File "+fileName+" could not be opened.");
fileTransferCleanup();
return;
}
// Truncate the file if needed
if(connection->restoreFilePostion() > 0) {
if(!m_fileBeingTransferred->resize(connection->restoreFilePostion())) {
emit error("File "+fileName+" could not be truncated.");
fileTransferCleanup();
return;
}
}
}
/**
* @brief CogWheelDataChannel::incomingConnection
*
* Handle connection from client to server for data channel
* for passive mode.
*
* @param handle Handle to socket.
*/
void CogWheelDataChannel::incomingConnection(qintptr handle)
{
emit info("--- Incoming connection for data channel --- "+QString::number(handle));
if(!m_dataChannelSocket->setSocketDescriptor(handle)){
emit error( "Error binding socket: "+m_dataChannelSocket->errorString());
} else {
emit info("Data channel socket connected for handle : "+QString::number(handle));
}
}
/**
* @brief CogWheelDataChannel::connected
*
* Data channel socket connected slot function.
*
*/
void CogWheelDataChannel::connected()
{
emit info("Data channel connected.");
}
/**
* @brief CogWheelDataChannel::disconnected
*
* Data channel socket disconnect slot function. If a
* file is being uploaded/downloaded then reset any
* related variables
*
*/
void CogWheelDataChannel::disconnected()
{
emit info("Data channel disconnected.");
m_connected=false;
if (m_fileBeingTransferred) {
emit transferFinished();
}
fileTransferCleanup();
}
/**
* @brief CogWheelDataChannel::stateChanged
*
* Data channel socket state changed slot function.
*
* @param socketState New socket state.
*/
void CogWheelDataChannel::stateChanged(QAbstractSocket::SocketState socketState)
{
Q_UNUSED(socketState);
}
/**
* @brief CogWheelDataChannel::bytesWritten
*
* Data channel socket bytes written slot function. If a file
* is being downloaded subtract bytes from file size and
* when reaches zero disconnect and signal complete.
*
* @param numBytes Number of bytes written (unused).
*/
void CogWheelDataChannel::bytesWritten(qint64 numBytes)
{
if (m_fileBeingTransferred) {
m_downloadFileSize -= numBytes;
if (m_downloadFileSize==0) {
m_dataChannelSocket->disconnectFromHost();
return;
}
if (!m_fileBeingTransferred->atEnd()) {
QByteArray buffer = m_fileBeingTransferred->read(m_writeBytesSize);
m_dataChannelSocket->write(buffer);
}
}
}
/**
* @brief CogWheelDataChannel::fileTransferCleanup
*
* File upload/download cleanup code. This includes
* closing any file and deleting its data.
*/
void CogWheelDataChannel::fileTransferCleanup()
{
if (m_fileBeingTransferred) {
if (m_fileBeingTransferred->isOpen()) {
m_fileBeingTransferred->close();
}
m_fileBeingTransferred->deleteLater();
m_fileBeingTransferred=nullptr;
m_downloadFileSize=0;
}
}
/**
* @brief CogWheelDataChannel::readyRead
*
* Data channel socket readyRead slot function. Used to
* perform the uploading of a file to server once it has
* been kicked off.
*
*/
void CogWheelDataChannel::readyRead()
{
if(m_fileBeingTransferred) {
m_fileBeingTransferred->write(m_dataChannelSocket->readAll());
}
}
/**
* @brief CogWheelDataChannel::socketError
*
* ata channel socket error slot function.
*
* @param socketError Socket error.
*/
void CogWheelDataChannel::socketError(QAbstractSocket::SocketError socketError)
{
emit error("Data channel socket error: "+QString::number(socketError));
}
// ============================
// CLASS PRIVATE DATA ACCESSORS
// ============================
/**
* @brief CogWheelDataChannel::isConnected
* @return
*/
bool CogWheelDataChannel::isConnected() const
{
return m_connected;
}
/**
* @brief CogWheelDataChannel::setConnected
* @param connected
*/
void CogWheelDataChannel::setConnected(bool connected)
{
m_connected = connected;
}
/**
* @brief CogWheelDataChannel::isListening
* @return
*/
bool CogWheelDataChannel::isListening() const
{
return m_listening;
}
/**
* @brief CogWheelDataChannel::setListening
* @param listening
*/
void CogWheelDataChannel::setListening(bool listening)
{
m_listening = listening;
}
/**
* @brief CogWheelDataChannel::clientHostIP
* @return
*/
QHostAddress CogWheelDataChannel::clientHostIP() const
{
return m_clientHostIP;
}
/**
* @brief CogWheelDataChannel::clientHostPort
* @return
*/
quint16 CogWheelDataChannel::clientHostPort() const
{
return m_clientHostPort;
}
<|endoftext|> |
<commit_before>#include <memory>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include "s_rules.hh"
#include "s_closure.hh"
#include "cons_util.hh"
#include "env.hh"
#include "zs_error.hh"
#include "builtin_equal.hh"
#include "builtin_extra.hh"
#include "builtin_util.hh"
#include "printer.hh"
#include "hasher.hh"
// #include <iostream>
// #include "env.hh"
using namespace std;
namespace Procedure{
namespace {
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw zs_error("syntax-rules: the pattern is empty list\n");
return c->car();
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw zs_error("syntax-rules: the pattern is empty vector\n");
return (*v)[0];
}else{
throw zs_error("syntax-rules: informal pattern passed! (%s)\n", stringify(p.tag()));
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p,
unordered_set<Lisp_ptr> tab){
if(identifierp(p)){
if(find(begin(sr.literals()), end(sr.literals()), p) != end(sr.literals())){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw zs_error("syntax-rules error: duplicated pattern variable! (%s)\n",
identifier_symbol(p)->name().c_str());
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(), rules_(){
for(auto i : lits){
if(!identifierp(i))
throw builtin_identifier_check_failed("syntax-rules", i);
literals_.push_back(i);
}
literals_.shrink_to_fit();
for(auto i : rls){
bind_cons_list_strict
(i,
[&](Lisp_ptr pat, Lisp_ptr tmpl){
check_pattern(*this, pat);
rules_.push_back({pat, tmpl});
});
}
rules_.shrink_to_fit();
}
SyntaxRules::~SyntaxRules() = default;
static
bool try_match_1(std::unordered_map<Lisp_ptr, Lisp_ptr>& result,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form){
// cout << __func__ << endl;
// cout << "pattern " << pattern << ", form " << form << endl;
const auto ellipsis_sym = intern(vm.symtable(), "...");
if(identifierp(pattern)){
if(find(begin(sr.literals()), end(sr.literals()), pattern) != end(sr.literals())){
// literal identifier
if(!identifierp(form)) return false;
return identifier_eq(sr.env(), pattern, form_env, form);
}else{
// non-literal identifier
if(pattern != ignore_ident){
result.insert({pattern, new SyntacticClosure(form_env, nullptr, form)});
}
return true;
}
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons)
return false;
if(nullp(pattern) && nullp(form)){
return true;
}
auto p_i = begin(pattern), p_e = end(pattern);
auto f_i = begin(form), f_e = end(form);
for(; p_i && (p_i != p_e); ++p_i, (f_i ? ++f_i : f_i)){
auto p_n = next(p_i);
// checks ellipsis
if(identifierp(*p_i)
&& (p_n != p_e) && identifierp(*p_n)
&& identifier_symbol(*p_n) == ellipsis_sym){
if(p_i == begin(pattern)){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
if(!nullp(p_e.base())){
throw zs_error("syntax-rules error: '...' is appeared in a inproper list pattern!\n");
}
if(!nullp(f_e.base())){
throw zs_error("syntax-rules error: '...' is used for a inproper list form!\n");
}
result.insert({*p_i, f_i.base()});
return true;
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(result, sr, ignore_ident, *p_i, form_env, *f_i)){
return false;
}
}
// checks length
if((p_i == p_e) && (f_i == f_e)){
return try_match_1(result, sr, ignore_ident, p_i.base(), form_env, f_i.base());
}else{
return false;
}
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector)
return false;
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
auto p_i = begin(*p_v), p_e = end(*p_v);
auto f_i = begin(*f_v), f_e = end(*f_v);
for(; p_i != p_e; ++p_i, ++f_i){
auto p_n = next(p_i);
// checks ellipsis
if(identifierp(*p_i)
&& (p_n != p_e) && identifierp(*p_n)
&& identifier_symbol(*p_n) == ellipsis_sym){
if(p_i == begin(*p_v)){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
result.insert({*p_i, new Vector(f_i, f_e)});
return true;
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(result, sr, ignore_ident, *p_i, form_env, *f_i)){
return false;
}
}
// checks length
if((p_i == p_e) && (f_i == f_e)){
return true;
}else{
return false;
}
}else{
return equal_internal(pattern, form);
}
}
std::pair<Env*, Lisp_ptr> match(const SyntaxRules& sr, Lisp_ptr form, Env* form_env){
Env::map_type ret_map;
for(auto i : sr.rules()){
auto ignore_ident = pick_first(i.first);
if(try_match_1(ret_map, sr, ignore_ident, i.first, form_env, form)){
auto ret_env = sr.env()->push();
ret_env->internal_map() = ret_map;
return {ret_env, i.second};
}else{
// cleaning map
for(auto e : ret_map){
if(auto sc = e.second.get<SyntacticClosure*>()){
delete sc;
}
}
ret_map.clear();
}
}
throw zs_error("syntax-rules error: no matching pattern found!\n");
}
} // Procedure
<commit_msg>added syntax-rules expand() (not tested)<commit_after>#include <memory>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include "s_rules.hh"
#include "s_closure.hh"
#include "cons_util.hh"
#include "env.hh"
#include "zs_error.hh"
#include "builtin_equal.hh"
#include "builtin_extra.hh"
#include "builtin_util.hh"
#include "printer.hh"
#include "hasher.hh"
// #include <iostream>
// #include "env.hh"
using namespace std;
namespace Procedure{
namespace {
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw zs_error("syntax-rules: the pattern is empty list\n");
return c->car();
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw zs_error("syntax-rules: the pattern is empty vector\n");
return (*v)[0];
}else{
throw zs_error("syntax-rules: informal pattern passed! (%s)\n", stringify(p.tag()));
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p,
unordered_set<Lisp_ptr> tab){
if(identifierp(p)){
if(find(begin(sr.literals()), end(sr.literals()), p) != end(sr.literals())){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw zs_error("syntax-rules error: duplicated pattern variable! (%s)\n",
identifier_symbol(p)->name().c_str());
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(), rules_(){
for(auto i : lits){
if(!identifierp(i))
throw builtin_identifier_check_failed("syntax-rules", i);
literals_.push_back(i);
}
literals_.shrink_to_fit();
for(auto i : rls){
bind_cons_list_strict
(i,
[&](Lisp_ptr pat, Lisp_ptr tmpl){
check_pattern(*this, pat);
rules_.push_back({pat, tmpl});
});
}
rules_.shrink_to_fit();
}
SyntaxRules::~SyntaxRules() = default;
static
bool try_match_1(std::unordered_map<Lisp_ptr, Lisp_ptr>& result,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form){
// cout << __func__ << endl;
// cout << "pattern " << pattern << ", form " << form << endl;
const auto ellipsis_sym = intern(vm.symtable(), "...");
if(identifierp(pattern)){
if(find(begin(sr.literals()), end(sr.literals()), pattern) != end(sr.literals())){
// literal identifier
if(!identifierp(form)) return false;
return identifier_eq(sr.env(), pattern, form_env, form);
}else{
// non-literal identifier
if(pattern != ignore_ident){
result.insert({pattern, new SyntacticClosure(form_env, nullptr, form)});
}
return true;
}
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons)
return false;
if(nullp(pattern) && nullp(form)){
return true;
}
auto p_i = begin(pattern), p_e = end(pattern);
auto f_i = begin(form), f_e = end(form);
for(; p_i && (p_i != p_e); ++p_i, (f_i ? ++f_i : f_i)){
auto p_n = next(p_i);
// checks ellipsis
if(identifierp(*p_i)
&& (p_n != p_e) && identifierp(*p_n)
&& identifier_symbol(*p_n) == ellipsis_sym){
if(p_i == begin(pattern)){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
if(!nullp(p_e.base())){
throw zs_error("syntax-rules error: '...' is appeared in a inproper list pattern!\n");
}
if(!nullp(f_e.base())){
throw zs_error("syntax-rules error: '...' is used for a inproper list form!\n");
}
result.insert({*p_i, f_i.base()});
return true;
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(result, sr, ignore_ident, *p_i, form_env, *f_i)){
return false;
}
}
// checks length
if((p_i == p_e) && (f_i == f_e)){
return try_match_1(result, sr, ignore_ident, p_i.base(), form_env, f_i.base());
}else{
return false;
}
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector)
return false;
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
auto p_i = begin(*p_v), p_e = end(*p_v);
auto f_i = begin(*f_v), f_e = end(*f_v);
for(; p_i != p_e; ++p_i, ++f_i){
auto p_n = next(p_i);
// checks ellipsis
if(identifierp(*p_i)
&& (p_n != p_e) && identifierp(*p_n)
&& identifier_symbol(*p_n) == ellipsis_sym){
if(p_i == begin(*p_v)){
throw zs_error("syntax-rules error: '...' is appeared following the first identifier.\n");
}
result.insert({*p_i, new Vector(f_i, f_e)});
return true;
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
if(!try_match_1(result, sr, ignore_ident, *p_i, form_env, *f_i)){
return false;
}
}
// checks length
if((p_i == p_e) && (f_i == f_e)){
return true;
}else{
return false;
}
}else{
return equal_internal(pattern, form);
}
}
Lisp_ptr expand(const std::unordered_map<Lisp_ptr, Lisp_ptr>& match_obj,
const SyntaxRules& sr, Lisp_ptr tmpl){
const auto ellipsis_sym = intern(vm.symtable(), "...");
if(identifierp(tmpl)){
auto m_ret = match_obj.find(tmpl);
if(m_ret != match_obj.end()){
return m_ret->second;
}else{
return sr.env()->find(tmpl);
}
}else if(tmpl.tag() == Ptr_tag::cons){
if(nullp(tmpl)) return tmpl;
GrowList gl;
auto t_i = begin(tmpl);
for(; t_i; ++t_i){
auto t_n = next(t_i);
// check ellipsis
if(identifierp(*t_i)
&& (t_n) && identifierp(*t_n)
&& identifier_symbol(*t_n) == ellipsis_sym){
auto m_ret = match_obj.find(*t_i);
if(m_ret == match_obj.end()){
throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n");
}
if(auto m_ret_lis = m_ret->second.get<Cons*>()){
// this can be replaced directly?
for(auto i : m_ret_lis){
gl.push(i);
}
}else if(auto m_ret_vec = m_ret->second.get<Vector*>()){
for(auto i : *m_ret_vec){
gl.push(i);
}
}else{
throw zs_error("syntax-rules error: invalid template: not sequence type\n");
}
++t_i;
}else{
gl.push(expand(match_obj, sr, *t_i));
}
}
return gl.extract_with_tail(expand(match_obj, sr, t_i.base()));
}else if(tmpl.tag() == Ptr_tag::vector){
auto t_vec = tmpl.get<Vector*>();
Vector vec;
for(auto t_i = begin(*t_vec), t_e = end(*t_vec); t_i != t_e; ++t_i){
auto t_n = next(t_i);
// check ellipsis
if(identifierp(*t_i)
&& (t_n != t_e) && identifierp(*t_n)
&& identifier_symbol(*t_n) == ellipsis_sym){
auto m_ret = match_obj.find(*t_i);
if(m_ret == match_obj.end()){
throw zs_error("syntax-rules error: invalid template: followed by '...', but not bound by pattern\n");
}
if(auto m_ret_lis = m_ret->second.get<Cons*>()){
vec.insert(vec.end(), begin(m_ret_lis), end(m_ret_lis));
}else if(auto m_ret_vec = m_ret->second.get<Vector*>()){
vec.insert(vec.end(), begin(*m_ret_vec), end(*m_ret_vec));
}else{
throw zs_error("syntax-rules error: invalid template: not sequence type\n");
}
++t_i;
}else{
vec.push_back(expand(match_obj, sr, *t_i));
}
}
return new Vector(move(vec));
}else{
return tmpl;
}
}
std::pair<Env*, Lisp_ptr> match(const SyntaxRules& sr, Lisp_ptr form, Env* form_env){
Env::map_type ret_map;
for(auto i : sr.rules()){
auto ignore_ident = pick_first(i.first);
if(try_match_1(ret_map, sr, ignore_ident, i.first, form_env, form)){
// auto tmp = expand(ret_map, sr, i.second);
// cout << "expand: " << i.second << " -> " << tmp << endl;
auto ret_env = sr.env()->push();
ret_env->internal_map() = ret_map;
return {ret_env, i.second};
}else{
// cleaning map
for(auto e : ret_map){
if(auto sc = e.second.get<SyntacticClosure*>()){
delete sc;
}
}
ret_map.clear();
}
}
throw zs_error("syntax-rules error: no matching pattern found!\n");
}
} // Procedure
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.