text stringlengths 54 60.6k |
|---|
<commit_before>#include "SandboxApp.h"
#include <SpriteBatchBuffer.h>
#include <Windows.h>
#include <stb_image.h>
#include <ds_imgui.h>
#include "Material.h"
#include <ds_logpanel.h>
ds::BaseApp *app = new SandboxApp();
void my_debug(const LogLevel& level, const char* message) {
OutputDebugString(message);
OutputDebugString("\n");
logpanel::add_line(message);
}
SandboxApp::SandboxApp() : ds::BaseApp() {
_settings.screenWidth = 1680;
_settings.screenHeight = 920;
_settings.windowTitle = "Flow";
_settings.useIMGUI = true;
_settings.clearColor = ds::Color(16, 16, 16, 255);
_settings.guiToggleKey = 'O';
_gameContext = new GameContext;
logpanel::init(32);
_showScenes = false;
}
SandboxApp::~SandboxApp() {
delete _flowFieldScene;
delete _towerTestScene;
delete _gameContext->particleContext->particleSystem;
delete _gameContext->particleContext;
delete _gameContext->ambientMaterial;
delete _gameContext->instancedAmbientmaterial;
delete _gameContext;
}
// ---------------------------------------------------------------
// initialize
// ---------------------------------------------------------------
void SandboxApp::initialize() {
ds::setLogHandler(my_debug);
_gameContext->ambientMaterial = new AmbientLightningMaterial;
_gameContext->instancedAmbientmaterial = new InstancedAmbientLightningMaterial;
_gameContext->towers.init(_gameContext->ambientMaterial);
RID textureID = loadImageFromFile("content\\particles.png");
_gameContext->particleContext = particles::create_context(textureID);
_flowFieldScene = new MainGameScene(_gameContext);
_sceneListModel.add("Flowfield", _flowFieldScene);
_towerTestScene = new TowerTestScene(_gameContext);
_sceneListModel.add("TowerTest", _towerTestScene);
_particlesTestScene = new ParticlesTestScene(_gameContext);
_sceneListModel.add("Particle Test", _particlesTestScene);
//pushScene(_flowFieldScene);
//pushScene(_towerTestScene);
pushScene(_particlesTestScene);
}
// ---------------------------------------------------------------
// showMenu
// ---------------------------------------------------------------
void SandboxApp::drawTopPanel() {
gui::Value("FPS", ds::getFramesPerSecond());
if (gui::Button("Toggle Update")) {
_updateActive = !_updateActive;
}
if (!_updateActive) {
if (gui::Button("Single step")) {
doSingleStep();
}
}
if (gui::Button("Toggle Scenes")) {
_showScenes = !_showScenes;
}
}
void SandboxApp::drawLeftPanel() {
if (_showScenes) {
gui::ListBox("Scenes", _sceneListModel, 4);
gui::beginGroup();
if (gui::Button("Push")) {
if (_sceneListModel.hasSelection()) {
const SceneDescriptor& desc = _sceneListModel.get(_sceneListModel.getSelection());
DBG_LOG("selected: %s", desc.name);
popScene();
pushScene(desc.scene);
}
}
if (gui::Button("Pop")) {
popScene();
}
gui::endGroup();
}
}
void SandboxApp::drawBottomPanel() {
logpanel::draw_gui(8);
}
// ---------------------------------------------------------------
// handle events
// ---------------------------------------------------------------
void SandboxApp::handleEvents(ds::EventStream* events) {
if (events->num() > 0) {
for (uint32_t i = 0; i < events->num(); ++i) {
int type = events->getType(i);
if (type == 102) {
stopGame();
}
}
}
}
// ---------------------------------------------------------------
// update
// ---------------------------------------------------------------
void SandboxApp::update(float dt) {
}
<commit_msg>minor fix<commit_after>#include "SandboxApp.h"
#include <SpriteBatchBuffer.h>
#include <Windows.h>
#include <stb_image.h>
#include <ds_imgui.h>
#include "Material.h"
#include <ds_logpanel.h>
ds::BaseApp *app = new SandboxApp();
void my_debug(const LogLevel& level, const char* message) {
OutputDebugString(message);
OutputDebugString("\n");
logpanel::add_line(message);
}
SandboxApp::SandboxApp() : ds::BaseApp() {
_settings.screenWidth = 1680;
_settings.screenHeight = 920;
_settings.windowTitle = "Flow";
_settings.useIMGUI = true;
_settings.clearColor = ds::Color(16, 16, 16, 255);
_settings.guiToggleKey = 'O';
_gameContext = new GameContext;
logpanel::init(32);
_showScenes = false;
}
SandboxApp::~SandboxApp() {
delete _flowFieldScene;
delete _towerTestScene;
delete _gameContext->particleContext->particleSystem;
delete _gameContext->particleContext;
delete _gameContext->ambientMaterial;
delete _gameContext->instancedAmbientmaterial;
delete _gameContext;
}
// ---------------------------------------------------------------
// initialize
// ---------------------------------------------------------------
void SandboxApp::initialize() {
ds::setLogHandler(my_debug);
_gameContext->ambientMaterial = new AmbientLightningMaterial;
_gameContext->instancedAmbientmaterial = new InstancedAmbientLightningMaterial;
_gameContext->towers.init(_gameContext->ambientMaterial);
RID textureID = loadImageFromFile("content\\particles.png");
_gameContext->particleContext = particles::create_context(textureID);
_flowFieldScene = new MainGameScene(_gameContext);
_sceneListModel.add("Flowfield", _flowFieldScene);
_towerTestScene = new TowerTestScene(_gameContext);
_sceneListModel.add("TowerTest", _towerTestScene);
_particlesTestScene = new ParticlesTestScene(_gameContext);
_sceneListModel.add("Particle Test", _particlesTestScene);
//pushScene(_flowFieldScene);
//pushScene(_towerTestScene);
pushScene(_particlesTestScene);
}
// ---------------------------------------------------------------
// showMenu
// ---------------------------------------------------------------
void SandboxApp::drawTopPanel() {
gui::Value("FPS", ds::getFramesPerSecond());
if (gui::Button("Toggle Update")) {
_updateActive = !_updateActive;
}
if (!_updateActive) {
if (gui::Button("Single step")) {
doSingleStep();
}
}
if (gui::Button("Toggle Scenes")) {
_showScenes = !_showScenes;
}
}
void SandboxApp::drawLeftPanel() {
if (_showScenes) {
gui::begin("Scenes", 0);
gui::ListBox("Scenes", _sceneListModel, 4);
gui::beginGroup();
if (gui::Button("Push")) {
if (_sceneListModel.hasSelection()) {
const SceneDescriptor& desc = _sceneListModel.get(_sceneListModel.getSelection());
DBG_LOG("selected: %s", desc.name);
popScene();
pushScene(desc.scene);
}
}
if (gui::Button("Pop")) {
popScene();
}
gui::endGroup();
}
}
void SandboxApp::drawBottomPanel() {
logpanel::draw_gui(8);
}
// ---------------------------------------------------------------
// handle events
// ---------------------------------------------------------------
void SandboxApp::handleEvents(ds::EventStream* events) {
if (events->num() > 0) {
for (uint32_t i = 0; i < events->num(); ++i) {
int type = events->getType(i);
if (type == 102) {
stopGame();
}
}
}
}
// ---------------------------------------------------------------
// update
// ---------------------------------------------------------------
void SandboxApp::update(float dt) {
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/nacl/nacl_sandbox_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
namespace {
// Base url is specified in nacl_test.
const FilePath::CharType kSrpcHwHtmlFileName[] =
FILE_PATH_LITERAL("srpc_hw.html");
} // namespace
NaClSandboxTest::NaClSandboxTest() {
// Append the --test-nacl-sandbox=$TESTDLL flag before launching.
FilePath dylib_dir;
PathService::Get(base::DIR_EXE, &dylib_dir);
#if defined(OS_MACOSX)
dylib_dir = dylib_dir.AppendASCII("libnacl_security_tests.dylib");
launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir);
#elif defined(OS_WIN)
// Let the NaCl process detect if it is 64-bit or not and hack on
// the appropriate suffix to this dll.
dylib_dir = dylib_dir.AppendASCII("nacl_security_tests");
launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir);
#elif defined(OS_LINUX)
// We currently do not test the Chrome Linux SUID or seccomp sandboxes.
#endif
}
NaClSandboxTest::~NaClSandboxTest() {
}
TEST_F(NaClSandboxTest, DISABLED_NaClOuterSBTest) {
// Load a helloworld .nexe to trigger the nacl loader test.
FilePath test_file(kSrpcHwHtmlFileName);
RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}
<commit_msg>Re-enable nacl outer sandbox test using ppapi helloworld to trigger nacl.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/nacl/nacl_sandbox_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
namespace {
// Base url is specified in nacl_test.
// We just need to visit a page that will trigger the NaCl loader.
const FilePath::CharType kANaClHtmlFile[] =
FILE_PATH_LITERAL("srpc_hw_ppapi.html");
} // namespace
NaClSandboxTest::NaClSandboxTest() {
// Append the --test-nacl-sandbox=$TESTDLL flag before launching.
FilePath dylib_dir;
PathService::Get(base::DIR_EXE, &dylib_dir);
#if defined(OS_MACOSX)
dylib_dir = dylib_dir.AppendASCII("libnacl_security_tests.dylib");
launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir);
#elif defined(OS_WIN)
// Let the NaCl process detect if it is 64-bit or not and hack on
// the appropriate suffix to this dll.
dylib_dir = dylib_dir.AppendASCII("nacl_security_tests");
launch_arguments_.AppendSwitchPath(switches::kTestNaClSandbox, dylib_dir);
#elif defined(OS_LINUX)
// We currently do not test the Chrome Linux SUID or seccomp sandboxes.
#endif
}
NaClSandboxTest::~NaClSandboxTest() {
}
TEST_F(NaClSandboxTest, NaClOuterSBTest) {
// Load a helloworld .nexe to trigger the nacl loader test.
FilePath test_file(kANaClHtmlFile);
RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}
<|endoftext|> |
<commit_before>/*
Copyright 2014 Justin White
See included LICENSE file for details.
*/
#include <unistd.h>
#include <easylogging++.h>
#define ELPP_UNICODE
#define ELPP_NO_DEFAULT_LOG_FILE
#include <Game.h>
INITIALIZE_EASYLOGGINGPP
//system data
const int version = 0;
const int revision = 1;
const int width = 1280;
const int height = 720;
const std::string name = "SpaceFight";
int main(int argc, char *argv[]) {
std::string logFilename = name;
logFilename.append(".log");
// remove existing log file, easylogging++ doesn't currently support non-append logs
unlink(logFilename.c_str());
START_EASYLOGGINGPP(argc, argv);
el::Configurations logConf;
logConf.setToDefault();
logConf.setGlobally(el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %msg");
logConf.setGlobally(el::ConfigurationType::Filename, logFilename);
logConf.setGlobally(el::ConfigurationType::Enabled, "true");
logConf.setGlobally(el::ConfigurationType::ToFile, "true");
logConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");
logConf.setGlobally(el::ConfigurationType::MillisecondsWidth, "3");
logConf.set(el::Level::Debug, el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %loc %func %msg");
el::Loggers::reconfigureAllLoggers(logConf);
LOG(INFO) << name << " v" << version << "." << revision;
LOG(INFO) << "Built " << __DATE__ << " " << __TIME__;
LOG(INFO) << "GCC " << __VERSION__;
LOG(INFO) << "SFML " << SFML_VERSION_MAJOR << "." << SFML_VERSION_MINOR;
Game *game = Game::getGame();
game->init(name, width, height);
game->run();
return EXIT_SUCCESS;
}
<commit_msg>Tweak version logging, and initial size. Fits on 1366x768 Ubuntu screen now, still 16:9<commit_after>/*
Copyright 2014 Justin White
See included LICENSE file for details.
*/
#include <unistd.h>
#define ELPP_NO_DEFAULT_LOG_FILE
#include <easylogging++.h>
#include <Game.h>
INITIALIZE_EASYLOGGINGPP
//system data
const unsigned int majorVersion = 0;
const unsigned int minorVersion = 2;
const unsigned int revision = 0;
const int width = 1200;
const int height = 675;
const std::string gameName = "SpaceFight";
int main(int argc, char *argv[]) {
std::string logFilename = gameName;
logFilename.append(".log");
// remove existing log file, easylogging++ doesn't currently support non-append logs
unlink(logFilename.c_str());
START_EASYLOGGINGPP(argc, argv);
el::Configurations logConf;
logConf.setToDefault();
logConf.setGlobally(el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %msg");
logConf.setGlobally(el::ConfigurationType::Filename, logFilename);
logConf.setGlobally(el::ConfigurationType::Enabled, "true");
logConf.setGlobally(el::ConfigurationType::ToFile, "true");
logConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");
logConf.setGlobally(el::ConfigurationType::MillisecondsWidth, "3");
logConf.set(el::Level::Debug, el::ConfigurationType::Format, "%datetime{%H:%m:%s.%g} %level %loc %func %msg");
el::Loggers::reconfigureAllLoggers(logConf);
LOG(INFO) << gameName << " v" << majorVersion << "." << minorVersion << "." << revision;
LOG(INFO) << "Built " << __DATE__ << " " << __TIME__;
LOG(INFO) << "GCC " << __VERSION__;
LOG(INFO) << "SFML " << SFML_VERSION_MAJOR << "." << SFML_VERSION_MINOR;
Game *game = Game::getGame();
game->init(gameName, width, height);
game->run();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h"
#include "../log/log.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Debug output
double GetTime()
{
timespec t;
clock_gettime(CLOCK_REALTIME,&t);
double d = static_cast<double>(t.tv_nsec) / 1E9f;
d += t.tv_sec;
return d;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Parse $PATH into a vector of strings
void ParseSearchPath(vector<string>& dirs)
{
string path = getenv("PATH");
string dir = "";
for(size_t i=0; i<path.length(); i++)
{
if(path[i] == ':')
{
dirs.push_back(dir);
dir = "";
}
else
dir += path[i];
}
if(dir != "")
dirs.push_back(dir);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Filename manipulation
/**
@brief Canonicalizes a path name
*/
string CanonicalizePath(string fname)
{
char* cpath = realpath(fname.c_str(), NULL);
if(cpath == NULL)
{
LogFatal("Could not canonicalize path %s\n", fname.c_str());
return fname;
}
string str(cpath);
free(cpath);
return str;
}
/**
@brief Attempts to open a directory and returns a boolean value indicating whether it exists
*/
bool DoesDirectoryExist(string fname)
{
int hfile = open(fname.c_str(), O_RDONLY);
if(hfile < 0)
return false;
bool found = true;
struct stat buf;
if(0 != fstat(hfile, &buf))
found = false;
if(!S_ISDIR(buf.st_mode))
found = false;
close(hfile);
return found;
}
/**
@brief Attempts to open a file and returns a boolean value indicating whether it exists and is readable
*/
bool DoesFileExist(string fname)
{
int hfile = open(fname.c_str(), O_RDONLY);
if(hfile < 0)
return false;
close(hfile);
return true;
}
/**
@brief Gets the directory component of a filename
*/
string GetDirOfFile(string fname)
{
size_t pos = fname.rfind("/");
return fname.substr(0, pos);
}
/**
@brief Gets the basename component of a filename
*/
string GetBasenameOfFile(string fname)
{
size_t pos = fname.rfind("/");
return fname.substr(pos+1);
}
string GetBasenameOfFileWithoutExt(string fname)
{
size_t pos = fname.rfind("/");
string base = fname.substr(pos+1);
pos = base.rfind(".");
return base.substr(0, pos);
}
/**
@brief Find all files with the specified extension in a given directory.
The supplied extension must include the leading dot.
*/
void FindFilesByExtension(string dir, string ext, vector<string>& files)
{
DIR* hdir = opendir(dir.c_str());
if(!hdir)
LogFatal("Directory %s could not be opened\n", dir.c_str());
dirent ent;
dirent* pent;
while(0 == readdir_r(hdir, &ent, &pent))
{
if(pent == NULL)
break;
if(ent.d_name[0] == '.')
continue;
//Extension match
string fname = CanonicalizePath(dir + "/" + ent.d_name);
if(fname.find(ext) == (fname.length() - ext.length()) )
files.push_back(fname);
}
//Sort the list of files to ensure determinism
sort(files.begin(), files.end());
closedir(hdir);
}
/**
@brief Find all files whose name contains the specified substring in a given directory.
*/
void FindFilesBySubstring(string dir, string sub, vector<string>& files)
{
DIR* hdir = opendir(dir.c_str());
if(!hdir)
LogFatal("Directory %s could not be opened\n", dir.c_str());
dirent ent;
dirent* pent;
while(0 == readdir_r(hdir, &ent, &pent))
{
if(pent == NULL)
break;
if(ent.d_name[0] == '.')
continue;
//Extension match
string fname = CanonicalizePath(dir + "/" + ent.d_name);
if(fname.find(sub) != string::npos )
files.push_back(fname);
}
//Sort the list of files to ensure determinism
sort(files.begin(), files.end());
closedir(hdir);
}
/**
@brief Find all subdirectories in a given directory.
*/
void FindSubdirs(string dir, vector<string>& subdirs)
{
DIR* hdir = opendir(dir.c_str());
if(!hdir)
LogFatal("Directory %s could not be opened\n", dir.c_str());
dirent ent;
dirent* pent;
while(0 == readdir_r(hdir, &ent, &pent))
{
if(pent == NULL)
break;
if(ent.d_name[0] == '.') //don't find hidden dirs
continue;
string fname = CanonicalizePath(dir + "/" + ent.d_name);
if(!DoesDirectoryExist(fname))
continue;
subdirs.push_back(fname);
}
//Sort the list of directories to ensure determinism
sort(subdirs.begin(), subdirs.end());
closedir(hdir);
}
/**
@brief Gets the relative path of a file within a directory.
Good for printing out friendly file names etc during build.
*/
string GetRelativePathOfFile(string dir, string fname)
{
size_t pos = fname.find(dir);
if(pos == 0)
{
//Hit, remove it
return fname.substr(dir.length() + 1);
}
return fname;
}
void MakeDirectoryRecursive(string path, int mode)
{
if(!DoesDirectoryExist(path))
{
//Make the parent directory if needed
string parent = GetDirOfFile(path);
if(parent == path)
{
//relative path and we've hit the top, stop
return;
}
if(!DoesDirectoryExist(parent))
MakeDirectoryRecursive(parent, mode);
//Make the directory
if(0 != mkdir(path.c_str(), 0755))
{
//Do not fail if the directory was previously created
if( (errno == EEXIST) && DoesDirectoryExist(path) )
{}
else
LogFatal("Could not create directory %s (%s)\n", path.c_str(), strerror(errno));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hashing
/**
@brief Computes the SHA256 of a string and returns the hex hash
*/
string sha256(string str)
{
unsigned char output_buf_raw[CryptoPP::SHA256::DIGESTSIZE];
CryptoPP::SHA256().CalculateDigest(output_buf_raw, (unsigned char*)str.c_str(), str.length());
string ret;
for(int i=0; i<CryptoPP::SHA256::DIGESTSIZE; i++)
{
char buf[3];
snprintf(buf, sizeof(buf), "%02x", output_buf_raw[i] & 0xFF);
ret += buf;
}
return ret;
}
/**
@brief Computes the SHA256 of a file's contents and returns the hex hash
*/
string sha256_file(string path)
{
FILE* fp = fopen(path.c_str(), "rb");
if(!fp)
LogFatal("sha256_file: Could not open file \"%s\"\n", path.c_str());
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buf = new char[fsize + 1];
buf[fsize] = 0;
fread(buf, 1, fsize, fp);
fclose(fp);
string tmp(buf);
delete[] buf;
return sha256(tmp);
}
<commit_msg>splashcore: Do not canonicalize paths by default when searching for files<commit_after>/***********************************************************************************************************************
* *
* SPLASH build system v0.2 *
* *
* Copyright (c) 2016 Andrew D. Zonenberg *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "splashcore.h"
#include "../log/log.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Debug output
double GetTime()
{
timespec t;
clock_gettime(CLOCK_REALTIME,&t);
double d = static_cast<double>(t.tv_nsec) / 1E9f;
d += t.tv_sec;
return d;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Parse $PATH into a vector of strings
void ParseSearchPath(vector<string>& dirs)
{
string path = getenv("PATH");
string dir = "";
for(size_t i=0; i<path.length(); i++)
{
if(path[i] == ':')
{
dirs.push_back(dir);
dir = "";
}
else
dir += path[i];
}
if(dir != "")
dirs.push_back(dir);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Filename manipulation
/**
@brief Canonicalizes a path name
*/
string CanonicalizePath(string fname)
{
char* cpath = realpath(fname.c_str(), NULL);
if(cpath == NULL) //file probably does not exist
{
//LogDebug("Could not canonicalize path %s\n", fname.c_str());
return "";
}
string str(cpath);
free(cpath);
return str;
}
/**
@brief Attempts to open a directory and returns a boolean value indicating whether it exists
*/
bool DoesDirectoryExist(string fname)
{
int hfile = open(fname.c_str(), O_RDONLY);
if(hfile < 0)
return false;
bool found = true;
struct stat buf;
if(0 != fstat(hfile, &buf))
found = false;
if(!S_ISDIR(buf.st_mode))
found = false;
close(hfile);
return found;
}
/**
@brief Attempts to open a file and returns a boolean value indicating whether it exists and is readable
*/
bool DoesFileExist(string fname)
{
int hfile = open(fname.c_str(), O_RDONLY);
if(hfile < 0)
return false;
close(hfile);
return true;
}
/**
@brief Gets the directory component of a filename
*/
string GetDirOfFile(string fname)
{
size_t pos = fname.rfind("/");
return fname.substr(0, pos);
}
/**
@brief Gets the basename component of a filename
*/
string GetBasenameOfFile(string fname)
{
size_t pos = fname.rfind("/");
return fname.substr(pos+1);
}
string GetBasenameOfFileWithoutExt(string fname)
{
size_t pos = fname.rfind("/");
string base = fname.substr(pos+1);
pos = base.rfind(".");
return base.substr(0, pos);
}
/**
@brief Find all files with the specified extension in a given directory.
The supplied extension must include the leading dot.
*/
void FindFilesByExtension(string dir, string ext, vector<string>& files)
{
DIR* hdir = opendir(dir.c_str());
if(!hdir)
LogFatal("Directory %s could not be opened\n", dir.c_str());
dirent ent;
dirent* pent;
while(0 == readdir_r(hdir, &ent, &pent))
{
if(pent == NULL)
break;
if(ent.d_name[0] == '.')
continue;
//Extension match
string fname = dir + "/" + ent.d_name;
if(fname.find(ext) == (fname.length() - ext.length()) )
files.push_back(fname);
}
//Sort the list of files to ensure determinism
sort(files.begin(), files.end());
closedir(hdir);
}
/**
@brief Find all files whose name contains the specified substring in a given directory.
*/
void FindFilesBySubstring(string dir, string sub, vector<string>& files)
{
DIR* hdir = opendir(dir.c_str());
if(!hdir)
LogFatal("Directory %s could not be opened\n", dir.c_str());
dirent ent;
dirent* pent;
while(0 == readdir_r(hdir, &ent, &pent))
{
if(pent == NULL)
break;
if(ent.d_name[0] == '.')
continue;
//Extension match
string fname = dir + "/" + ent.d_name;
if(fname.find(sub) != string::npos )
files.push_back(fname);
}
//Sort the list of files to ensure determinism
sort(files.begin(), files.end());
closedir(hdir);
}
/**
@brief Find all subdirectories in a given directory.
*/
void FindSubdirs(string dir, vector<string>& subdirs)
{
DIR* hdir = opendir(dir.c_str());
if(!hdir)
LogFatal("Directory %s could not be opened\n", dir.c_str());
dirent ent;
dirent* pent;
while(0 == readdir_r(hdir, &ent, &pent))
{
if(pent == NULL)
break;
if(ent.d_name[0] == '.') //don't find hidden dirs
continue;
string fname = dir + "/" + ent.d_name;
if(!DoesDirectoryExist(fname))
continue;
subdirs.push_back(fname);
}
//Sort the list of directories to ensure determinism
sort(subdirs.begin(), subdirs.end());
closedir(hdir);
}
/**
@brief Gets the relative path of a file within a directory.
Good for printing out friendly file names etc during build.
*/
string GetRelativePathOfFile(string dir, string fname)
{
size_t pos = fname.find(dir);
if(pos == 0)
{
//Hit, remove it
return fname.substr(dir.length() + 1);
}
return fname;
}
void MakeDirectoryRecursive(string path, int mode)
{
if(!DoesDirectoryExist(path))
{
//Make the parent directory if needed
string parent = GetDirOfFile(path);
if(parent == path)
{
//relative path and we've hit the top, stop
return;
}
if(!DoesDirectoryExist(parent))
MakeDirectoryRecursive(parent, mode);
//Make the directory
if(0 != mkdir(path.c_str(), 0755))
{
//Do not fail if the directory was previously created
if( (errno == EEXIST) && DoesDirectoryExist(path) )
{}
else
LogFatal("Could not create directory %s (%s)\n", path.c_str(), strerror(errno));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hashing
/**
@brief Computes the SHA256 of a string and returns the hex hash
*/
string sha256(string str)
{
unsigned char output_buf_raw[CryptoPP::SHA256::DIGESTSIZE];
CryptoPP::SHA256().CalculateDigest(output_buf_raw, (unsigned char*)str.c_str(), str.length());
string ret;
for(int i=0; i<CryptoPP::SHA256::DIGESTSIZE; i++)
{
char buf[3];
snprintf(buf, sizeof(buf), "%02x", output_buf_raw[i] & 0xFF);
ret += buf;
}
return ret;
}
/**
@brief Computes the SHA256 of a file's contents and returns the hex hash
*/
string sha256_file(string path)
{
FILE* fp = fopen(path.c_str(), "rb");
if(!fp)
LogFatal("sha256_file: Could not open file \"%s\"\n", path.c_str());
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buf = new char[fsize + 1];
buf[fsize] = 0;
fread(buf, 1, fsize, fp);
fclose(fp);
string tmp(buf);
delete[] buf;
return sha256(tmp);
}
<|endoftext|> |
<commit_before>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "infill.h"
#include "LayerPlan.h"
#include "sliceDataStorage.h"
#include "TopSurface.h"
namespace cura
{
TopSurface::TopSurface()
{
//Do nothing. Areas stays empty.
}
void TopSurface::setAreasFromMeshAndLayerNumber(SliceMeshStorage& mesh, size_t layer_number)
{
//The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.
Polygons mesh_above;
if (layer_number < mesh.layers.size() - 1)
{
mesh_above = mesh.layers[layer_number + 1].getOutlines();
} //If this is the top-most layer, mesh_above stays empty.
if (mesh.settings.get<bool>("magic_spiralize"))
{
// when spiralizing, the model is often solid so it's no good trying to determine if there is air above or not
// in this situation, just iron the topmost of the bottom layers
if (layer_number == mesh.settings.get<size_t>("initial_bottom_layers") - 1)
{
areas = mesh.layers[layer_number].getOutlines();
}
}
else
{
areas = mesh.layers[layer_number].getOutlines().difference(mesh_above);
}
}
bool TopSurface::ironing(const SliceMeshStorage& mesh, const GCodePathConfig& line_config, LayerPlan& layer) const
{
if (areas.empty())
{
return false; //Nothing to do.
}
//Generate the lines to cover the surface.
const EFillMethod pattern = mesh.settings.get<EFillMethod>("ironing_pattern");
const bool zig_zaggify_infill = pattern == EFillMethod::ZIG_ZAG;
constexpr bool connect_polygons = false; // midway connections can make the surface less smooth
const coord_t line_spacing = mesh.settings.get<coord_t>("ironing_line_spacing");
const coord_t line_width = line_config.getLineWidth();
const size_t roofing_layer_count = std::min(mesh.settings.get<size_t>("roofing_layer_count"), mesh.settings.get<size_t>("top_layers"));
const std::vector<AngleDegrees>& top_most_skin_angles = (roofing_layer_count > 0) ? mesh.roofing_angles : mesh.skin_angles;
assert(top_most_skin_angles.size() > 0);
const AngleDegrees direction = top_most_skin_angles[layer.getLayerNr() % top_most_skin_angles.size()] + AngleDegrees(90.0); //Always perpendicular to the skin lines.
constexpr coord_t infill_overlap = 0;
constexpr int infill_multiplier = 1;
constexpr coord_t shift = 0;
const coord_t max_resolution = mesh.settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t max_deviation = mesh.settings.get<coord_t>("meshfix_maximum_deviation");
const Ratio ironing_flow = mesh.settings.get<Ratio>("ironing_flow");
coord_t ironing_inset = -mesh.settings.get<coord_t>("ironing_inset");
if (pattern == EFillMethod::ZIG_ZAG)
{
//Compensate for the outline_offset decrease that takes place when using the infill generator to generate ironing with the zigzag pattern
const Ratio width_scale = (float)mesh.settings.get<coord_t>("layer_height") / mesh.settings.get<coord_t>("infill_sparse_thickness");
ironing_inset += width_scale * line_width / 2;
//Align the edge of the ironing line with the edge of the outer wall
ironing_inset -= ironing_flow * line_width / 2;
}
else if (pattern == EFillMethod::CONCENTRIC)
{
//Counteract the outline_offset increase that takes place when using the infill generator to generate ironing with the concentric pattern
ironing_inset += line_spacing - line_width / 2;
//Align the edge of the ironing line with the edge of the outer wall
ironing_inset -= ironing_flow * line_width / 2;
}
const coord_t outline_offset = ironing_inset;
areas.offset(outline_offset);
Infill infill_generator(pattern, zig_zaggify_infill, connect_polygons, areas, line_width, line_spacing, infill_overlap, infill_multiplier, direction, layer.z - 10, shift, max_resolution, max_deviation);
VariableWidthPaths ironing_paths;
Polygons ironing_polygons;
Polygons ironing_lines;
infill_generator.generate(ironing_paths, ironing_polygons, ironing_lines, mesh.settings);
if (ironing_polygons.empty() && ironing_lines.empty())
{
return false; //Nothing to do.
}
layer.mode_skip_agressive_merge = true;
bool added = false;
if (!ironing_polygons.empty())
{
constexpr bool force_comb_retract = false;
layer.addTravel(ironing_polygons[0][0], force_comb_retract);
layer.addPolygonsByOptimizer(ironing_polygons, line_config, ZSeamConfig());
added = true;
}
if (!ironing_lines.empty())
{
if (pattern == EFillMethod::LINES || pattern == EFillMethod::ZIG_ZAG)
{
//Move to a corner of the area that is perpendicular to the ironing lines, to reduce the number of seams.
const AABB bounding_box(areas);
PointMatrix rotate(-direction + 90);
const Point center = bounding_box.getMiddle();
const Point far_away = rotate.apply(Point(0, vSize(bounding_box.max - center) * 100)); //Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre.
//Two options to start, both perpendicular to the ironing lines. Which is closer?
const Point front_side = PolygonUtils::findNearestVert(center + far_away, areas).p();
const Point back_side = PolygonUtils::findNearestVert(center - far_away, areas).p();
if (vSize2(layer.getLastPlannedPositionOrStartingPosition() - front_side) < vSize2(layer.getLastPlannedPositionOrStartingPosition() - back_side))
{
layer.addTravel(front_side);
}
else
{
layer.addTravel(back_side);
}
}
if(!mesh.settings.get<bool>("ironing_monotonic"))
{
layer.addLinesByOptimizer(ironing_lines, line_config, SpaceFillType::PolyLines);
}
else
{
const coord_t max_adjacent_distance = line_spacing * 1.1; //Lines are considered adjacent - meaning they need to be printed in monotonic order - if spaced 1 line apart, with 10% extra play.
layer.addLinesMonotonic(Polygons(), ironing_lines, line_config, SpaceFillType::PolyLines, AngleRadians(direction), max_adjacent_distance);
}
added = true;
}
layer.mode_skip_agressive_merge = false;
return added;
}
}
<commit_msg>Actually use polygon after insetting it<commit_after>//Copyright (c) 2022 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "infill.h"
#include "LayerPlan.h"
#include "sliceDataStorage.h"
#include "TopSurface.h"
namespace cura
{
TopSurface::TopSurface()
{
//Do nothing. Areas stays empty.
}
void TopSurface::setAreasFromMeshAndLayerNumber(SliceMeshStorage& mesh, size_t layer_number)
{
//The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.
Polygons mesh_above;
if (layer_number < mesh.layers.size() - 1)
{
mesh_above = mesh.layers[layer_number + 1].getOutlines();
} //If this is the top-most layer, mesh_above stays empty.
if (mesh.settings.get<bool>("magic_spiralize"))
{
// when spiralizing, the model is often solid so it's no good trying to determine if there is air above or not
// in this situation, just iron the topmost of the bottom layers
if (layer_number == mesh.settings.get<size_t>("initial_bottom_layers") - 1)
{
areas = mesh.layers[layer_number].getOutlines();
}
}
else
{
areas = mesh.layers[layer_number].getOutlines().difference(mesh_above);
}
}
bool TopSurface::ironing(const SliceMeshStorage& mesh, const GCodePathConfig& line_config, LayerPlan& layer) const
{
if (areas.empty())
{
return false; //Nothing to do.
}
//Generate the lines to cover the surface.
const EFillMethod pattern = mesh.settings.get<EFillMethod>("ironing_pattern");
const bool zig_zaggify_infill = pattern == EFillMethod::ZIG_ZAG;
constexpr bool connect_polygons = false; // midway connections can make the surface less smooth
const coord_t line_spacing = mesh.settings.get<coord_t>("ironing_line_spacing");
const coord_t line_width = line_config.getLineWidth();
const size_t roofing_layer_count = std::min(mesh.settings.get<size_t>("roofing_layer_count"), mesh.settings.get<size_t>("top_layers"));
const std::vector<AngleDegrees>& top_most_skin_angles = (roofing_layer_count > 0) ? mesh.roofing_angles : mesh.skin_angles;
assert(top_most_skin_angles.size() > 0);
const AngleDegrees direction = top_most_skin_angles[layer.getLayerNr() % top_most_skin_angles.size()] + AngleDegrees(90.0); //Always perpendicular to the skin lines.
constexpr coord_t infill_overlap = 0;
constexpr int infill_multiplier = 1;
constexpr coord_t shift = 0;
const coord_t max_resolution = mesh.settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t max_deviation = mesh.settings.get<coord_t>("meshfix_maximum_deviation");
const Ratio ironing_flow = mesh.settings.get<Ratio>("ironing_flow");
coord_t ironing_inset = -mesh.settings.get<coord_t>("ironing_inset");
if (pattern == EFillMethod::ZIG_ZAG)
{
//Compensate for the outline_offset decrease that takes place when using the infill generator to generate ironing with the zigzag pattern
const Ratio width_scale = (float)mesh.settings.get<coord_t>("layer_height") / mesh.settings.get<coord_t>("infill_sparse_thickness");
ironing_inset += width_scale * line_width / 2;
//Align the edge of the ironing line with the edge of the outer wall
ironing_inset -= ironing_flow * line_width / 2;
}
else if (pattern == EFillMethod::CONCENTRIC)
{
//Counteract the outline_offset increase that takes place when using the infill generator to generate ironing with the concentric pattern
ironing_inset += line_spacing - line_width / 2;
//Align the edge of the ironing line with the edge of the outer wall
ironing_inset -= ironing_flow * line_width / 2;
}
Polygons ironed_areas = areas.offset(ironing_inset);
Infill infill_generator(pattern, zig_zaggify_infill, connect_polygons, ironed_areas, line_width, line_spacing, infill_overlap, infill_multiplier, direction, layer.z - 10, shift, max_resolution, max_deviation);
VariableWidthPaths ironing_paths;
Polygons ironing_polygons;
Polygons ironing_lines;
infill_generator.generate(ironing_paths, ironing_polygons, ironing_lines, mesh.settings);
if (ironing_polygons.empty() && ironing_lines.empty())
{
return false; //Nothing to do.
}
layer.mode_skip_agressive_merge = true;
bool added = false;
if (!ironing_polygons.empty())
{
constexpr bool force_comb_retract = false;
layer.addTravel(ironing_polygons[0][0], force_comb_retract);
layer.addPolygonsByOptimizer(ironing_polygons, line_config, ZSeamConfig());
added = true;
}
if (!ironing_lines.empty())
{
if (pattern == EFillMethod::LINES || pattern == EFillMethod::ZIG_ZAG)
{
//Move to a corner of the area that is perpendicular to the ironing lines, to reduce the number of seams.
const AABB bounding_box(ironed_areas);
PointMatrix rotate(-direction + 90);
const Point center = bounding_box.getMiddle();
const Point far_away = rotate.apply(Point(0, vSize(bounding_box.max - center) * 100)); //Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre.
//Two options to start, both perpendicular to the ironing lines. Which is closer?
const Point front_side = PolygonUtils::findNearestVert(center + far_away, ironed_areas).p();
const Point back_side = PolygonUtils::findNearestVert(center - far_away, ironed_areas).p();
if (vSize2(layer.getLastPlannedPositionOrStartingPosition() - front_side) < vSize2(layer.getLastPlannedPositionOrStartingPosition() - back_side))
{
layer.addTravel(front_side);
}
else
{
layer.addTravel(back_side);
}
}
if(!mesh.settings.get<bool>("ironing_monotonic"))
{
layer.addLinesByOptimizer(ironing_lines, line_config, SpaceFillType::PolyLines);
}
else
{
const coord_t max_adjacent_distance = line_spacing * 1.1; //Lines are considered adjacent - meaning they need to be printed in monotonic order - if spaced 1 line apart, with 10% extra play.
layer.addLinesMonotonic(Polygons(), ironing_lines, line_config, SpaceFillType::PolyLines, AngleRadians(direction), max_adjacent_distance);
}
added = true;
}
layer.mode_skip_agressive_merge = false;
return added;
}
}
<|endoftext|> |
<commit_before>#pragma ident "$Id$"
/**
* @file WGS84Geoid.hpp
* WGS 1984 model of the geoid
*/
#ifndef GPSTK_WGS84GEOID_HPP
#define GPSTK_WGS84GEOID_HPP
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "GeoidModel.hpp"
namespace gpstk
{
/** @addtogroup geodeticgroup */
//@{
/// This class represents the geodetic model defined in NIMA
/// TR8350.2, "Department of Defense World Geodetic System 1984".
class WGS84Geoid : public GeoidModel
{
public:
/// Defined in TR8350.2, Appendix A.1
/// @return semi-major axis of Earth in meters.
virtual double a() const throw()
{ return 6378137.0; }
/// Derived from TR8350.2, Appendix A.1
/// @return semi-major axis of Earth in km.
virtual double a_km() const throw()
{ return a() / 1000.0; }
/**
* Derived from TR8350.2, Appendix A.1
* @note This parameter was in gappc as e-2, but a
* little calculator work indicates it should really be e-3.
* We'll leave it as e-3 for now.
* @return flattening (ellipsoid parameter).
*/
virtual double flattening() const throw()
{ return 0.335281066475e-3; }
/// Defined in TR8350.2, Table 3.3
/// @return eccentricity (ellipsoid parameter).
virtual double eccentricity() const throw()
{ return 8.1819190842622e-2; }
/// Defined in TR8350.2, Table 3.3
/// @return eccentricity squared (ellipsoid parameter).
virtual double eccSquared() const throw()
{ return 6.69437999014e-3; }
/// Defined in TR8350.2, 3.2.4 line 3-6, or Table 3.1
/// @return angular velocity of Earth in radians/sec.
virtual double angVelocity() const throw()
{ return 7.292115e-5; }
/// Defined in TR8350.2, Table 3.1
/// @return geocentric gravitational constant in m**3 / s**2
virtual double gm() const throw()
{ return 3986004.418e8; }
/// Derived from TR8350.2, Table 3.1
/// @return geocentric gravitational constant in km**3 / s**2
virtual double gm_km() const throw()
{ return 398600.4418; }
/// Defined in TR8350.2, 3.3.2 line 3-11
/// @return Speed of light in m/s.
virtual double c() const throw()
{ return 299792458; }
/// Derived from TR8350.2, 3.3.2 line 3-11
/// @return Speed of light in km/s
virtual double c_km() const throw()
{ return c()/1000.0; }
}; // class WGS84Geoid
//@}
} // namespace
#endif
<commit_msg>src/WGS84Geoid.hpp: Added destructor to class WGS84Geoid.<commit_after>#pragma ident "$Id$"
/**
* @file WGS84Geoid.hpp
* WGS 1984 model of the geoid
*/
#ifndef GPSTK_WGS84GEOID_HPP
#define GPSTK_WGS84GEOID_HPP
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "GeoidModel.hpp"
namespace gpstk
{
/** @addtogroup geodeticgroup */
//@{
/// This class represents the geodetic model defined in NIMA
/// TR8350.2, "Department of Defense World Geodetic System 1984".
class WGS84Geoid : public GeoidModel
{
public:
/// Defined in TR8350.2, Appendix A.1
/// @return semi-major axis of Earth in meters.
virtual double a() const throw()
{ return 6378137.0; }
/// Derived from TR8350.2, Appendix A.1
/// @return semi-major axis of Earth in km.
virtual double a_km() const throw()
{ return a() / 1000.0; }
/**
* Derived from TR8350.2, Appendix A.1
* @note This parameter was in gappc as e-2, but a
* little calculator work indicates it should really be e-3.
* We'll leave it as e-3 for now.
* @return flattening (ellipsoid parameter).
*/
virtual double flattening() const throw()
{ return 0.335281066475e-3; }
/// Defined in TR8350.2, Table 3.3
/// @return eccentricity (ellipsoid parameter).
virtual double eccentricity() const throw()
{ return 8.1819190842622e-2; }
/// Defined in TR8350.2, Table 3.3
/// @return eccentricity squared (ellipsoid parameter).
virtual double eccSquared() const throw()
{ return 6.69437999014e-3; }
/// Defined in TR8350.2, 3.2.4 line 3-6, or Table 3.1
/// @return angular velocity of Earth in radians/sec.
virtual double angVelocity() const throw()
{ return 7.292115e-5; }
/// Defined in TR8350.2, Table 3.1
/// @return geocentric gravitational constant in m**3 / s**2
virtual double gm() const throw()
{ return 3986004.418e8; }
/// Derived from TR8350.2, Table 3.1
/// @return geocentric gravitational constant in km**3 / s**2
virtual double gm_km() const throw()
{ return 398600.4418; }
/// Defined in TR8350.2, 3.3.2 line 3-11
/// @return Speed of light in m/s.
virtual double c() const throw()
{ return 299792458; }
/// Derived from TR8350.2, 3.3.2 line 3-11
/// @return Speed of light in km/s
virtual double c_km() const throw()
{ return c()/1000.0; }
/// Destructor.
virtual ~WGS84Geoid() throw() {};
}; // class WGS84Geoid
//@}
} // namespace
#endif
<|endoftext|> |
<commit_before> /**
- -* (C) Copyright 2013 King Abdullah University of Science and Technology
Authors:
Ali Charara (ali.charara@kaust.edu.sa)
David Keyes (david.keyes@kaust.edu.sa)
Hatem Ltaief (hatem.ltaief@kaust.edu.sa)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the King Abdullah University of Science and
* Technology nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
*
T *HIS 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
HOLDERS 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 <stdlib.h>
#include <stdio.h>
#include <set>
#ifdef SUPPORT_CUBLAS
#include <cublas.h>
#endif
#ifdef SUPPORT_MKL
#include <mkl_lapack.h>
#include <mkl_blas.h>
#endif
#include "kblas.h"
#include "operators.hxx"
//==============================================================================================
#ifdef SUPPORT_CUBLAS
const char* cublasGetErrorString( cublasStatus_t error )
{
switch( error ) {
case CUBLAS_STATUS_SUCCESS:
return "success";
case CUBLAS_STATUS_NOT_INITIALIZED:
return "not initialized";
case CUBLAS_STATUS_ALLOC_FAILED:
return "out of memory";
case CUBLAS_STATUS_INVALID_VALUE:
return "invalid value";
case CUBLAS_STATUS_ARCH_MISMATCH:
return "architecture mismatch";
case CUBLAS_STATUS_MAPPING_ERROR:
return "memory mapping error";
case CUBLAS_STATUS_EXECUTION_FAILED:
return "execution failed";
case CUBLAS_STATUS_INTERNAL_ERROR:
return "internal error";
default:
return "unknown CUBLAS error code";
}
}
// ----------------------------------------
// C++ function is overloaded for different error types,
// which depends on error types being enums to be differentiable.
//inline
int _kblas_error( cudaError_t err, const char* func, const char* file, int line )
{
if ( err != cudaSuccess ) {
fprintf( stderr, "CUDA runtime error: %s (%d) in %s at %s:%d\n",
cudaGetErrorString( err ), err, func, file, line );
return 0;
}
return 1;
}
// --------------------
//inline
int _kblas_error( cublasStatus_t err, const char* func, const char* file, int line )
{
if ( err != CUBLAS_STATUS_SUCCESS ) {
fprintf( stderr, "CUBLAS error: %s (%d) in %s at %s:%d\n",
cublasGetErrorString( err ), err, func, file, line );
return 0;
}
return 1;
}
#endif
#define check_error( err ) \
{if(!_kblas_error( (err), __func__, __FILE__, __LINE__ )) return 0;}
//==============================================================================================
int kblas_reg_sizes_ar[] = {32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536};//,96
std::set<int> kblas_reg_sizes(kblas_reg_sizes_ar, kblas_reg_sizes_ar + sizeof(kblas_reg_sizes_ar) / sizeof(int) );
bool REG_SIZE(int n){
return (kblas_reg_sizes.find(n) != kblas_reg_sizes.end());
}
int CLOSEST_REG_SIZE(int n){
//TODO validate input
return *(--kblas_reg_sizes.lower_bound(n));
}
//==============================================================================================
#ifdef SUPPORT_CUBLAS
void cublasXgemm( char transa, char transb, int m, int n, int k,
float alpha, const float *A, int lda,
const float *B, int ldb,
float beta, float *C, int ldc ){
cublasSgemm(transa, transb, m, n, k,
alpha, A, lda,
B, ldb,
beta, C, ldc);
}
void cublasXgemm( char transa, char transb, int m, int n, int k,
double alpha, const double *A, int lda,
const double *B, int ldb,
double beta, double *C, int ldc){
cublasDgemm(transa, transb, m, n, k,
alpha, A, lda,
B, ldb,
beta, C, ldc);
}
void cublasXgemm( char transa, char transb, int m, int n, int k,
cuComplex alpha, const cuComplex *A, int lda,
const cuComplex *B, int ldb,
cuComplex beta, cuComplex *C, int ldc){
cublasCgemm(transa, transb, m, n, k,
alpha, A, lda,
B, ldb,
beta, C, ldc);
}
void cublasXgemm( char transa, char transb, int m, int n, int k,
cuDoubleComplex alpha, const cuDoubleComplex *A, int lda,
const cuDoubleComplex *B, int ldb,
cuDoubleComplex beta, cuDoubleComplex *C, int ldc){
cublasZgemm(transa, transb, m, n, k,
alpha, A, lda,
B, ldb,
beta, C, ldc);
}
#endif
<commit_msg>cleaning up<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2016 Trevaling */
#if defined(PARTICLE)
#include "application.h"
#else
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "particle_mock.h"
#endif
#include "cellular.h"
#define META_CASE_RETURN(type) case type: return #type
const char* at_resp_type_to_str(int type)
{
switch (type)
{
META_CASE_RETURN(TYPE_UNKNOWN);
META_CASE_RETURN(TYPE_OK);
META_CASE_RETURN(TYPE_ERROR);
META_CASE_RETURN(TYPE_RING);
META_CASE_RETURN(TYPE_CONNECT);
META_CASE_RETURN(TYPE_NOCARRIER);
META_CASE_RETURN(TYPE_NODIALTONE);
META_CASE_RETURN(TYPE_BUSY);
META_CASE_RETURN(TYPE_NOANSWER);
META_CASE_RETURN(TYPE_PROMPT);
META_CASE_RETURN(TYPE_PLUS);
META_CASE_RETURN(TYPE_TEXT);
META_CASE_RETURN(TYPE_ABORTED);
default:
return "(unknown)";
}
}
/* Debug functions */
void debug_print_callback(int type, const char* buf, int len)
{
Serial.printf("[debug] callback type 0x%06x %s len %d\r\n", type, at_resp_type_to_str(type), len);
char line[1024+64];
if (sscanf(buf, "\r\n%[^\r]\r\n", line) == 1)
{
Serial.printf("<line>%s</line>\r\n", line);
}
else
{
Serial.printf("<buf>%s</buf>\r\n", buf);
}
}
/* CREG functions */
#define ATCOMMAND_SCAN(cmd) "\r\n" cmd ": %[^\r]\r\n"
bool cmd_network_registration_status_parse(const char* buf,
cmd_network_registration_status_t* p_network_registration_status)
{
char parse_buffer[64];
char* p_token;
int retval;
retval = sscanf(buf, ATCOMMAND_SCAN("+CREG"), parse_buffer);
//Serial.printf("<parse_buffer>%s</parse_buffer>\r\n", parse_buffer);
if (retval != 1)
{
return false;
}
//TODO: Check for p_token being a sane pointer or return
p_token = strtok((char*)parse_buffer, ",");
p_network_registration_status->n = strtol(p_token, NULL, 10);
p_token = strtok(NULL, ",");
p_network_registration_status->stat = strtol(p_token, NULL, 10);
p_token = strtok(NULL, ",");
if (*p_token == '"')
{
p_token++;
p_network_registration_status->lac = strtol(p_token, NULL, 16);
}
else
{
p_network_registration_status->lac = strtol(p_token, NULL, 10);
}
p_token = strtok(0, ",");
if (*p_token == '"')
{
p_token++;
p_network_registration_status->ci = strtol(p_token, NULL, 16);
}
else
{
p_network_registration_status->ci = strtol(p_token, NULL, 10);
}
p_token = strtok(0, ",");
p_network_registration_status->actstatus = strtol(p_token, NULL, 10);
return true;
}
//TODO: Investigate number and type of callbacks
int callbackCREG_set(int type, const char* buf, int len, char* creg)
{
//debug_print_callback(type, buf, len);
if (type == TYPE_PLUS)
{
/*nothing*/
}
return WAIT;
}
int callbackCREG_get(int type, const char* buf, int len,
cmd_network_registration_status_t* p_network_registration_status)
{
//debug_print_callback(type, buf, len);
if (type == TYPE_PLUS)
{
cmd_network_registration_status_parse(buf, p_network_registration_status);
}
return WAIT;
}
bool cmd_network_registration_status_get(
cmd_network_registration_status_t* p_network_registration_status)
{
int retval;
char creg_set[32] = "";
memset(p_network_registration_status, 0, sizeof(cmd_network_registration_status_t));
//TODO: Investigate ahd check the Cellular.command retval
retval = Cellular.command(callbackCREG_set, creg_set, 10000, "AT+CREG=2\r\n");
//Serial.printf("Cellular.command retval: %d\r\n", retval);
retval = Cellular.command(callbackCREG_get, p_network_registration_status, 10000, "AT+CREG?\r\n");
//Serial.printf("Cellular.command retval: %d\r\n", retval);
return retval == RESP_OK;
}
/* Parses COPS response:
[MCC:<MCC>, MNC:<MNC>, LAC:<LAC>, CI:<CI>, BSIC:<BSIC>, Arfcn:<Arfcn>, RxLev:<RxLev>
*/
bool cellular_cellular_operator_parse(const char* buf,
cellular_operator_t* p_cellular_operator)
{
if ( sscanf(buf, "\r\nMCC:%d, MNC:%d, LAC:%x, CI:%x, BSIC:%x, Arfcn:%5d, RxLev:%3d\r\n",
&p_cellular_operator->mcc,
&p_cellular_operator->mnc,
&p_cellular_operator->lac,
&p_cellular_operator->ci,
&p_cellular_operator->bsic,
&p_cellular_operator->arfcn,
&p_cellular_operator->rxlev ) > 0 )
{
return true;
}
return false;
}
int callbackCOPS(int type, const char* buf, int len,
cellular_operator_list_t* p_cellular_operator_list)
{
debug_print_callback(type, buf, len);
char line[1024+64];
if (sscanf(buf, "\r\n%[^\r]\r\n", line) != 1)
{
/* TODO: Save error */
Serial.printf("[callbackCOPS] error, cannot parse line from buffer <buf>%s</buf>\r\n", buf);
return WAIT;
}
Serial.printf("[callbackCOPS] info, 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
if (type == TYPE_PLUS)
{
/* Ignore the seldom +CIEV responses */
}
else if (type == TYPE_UNKNOWN)
{
/* +COPS response */
if (p_cellular_operator_list->len < (CELLULAR_OPERATOR_MAX-1))
{
cellular_operator_t cellular_operator;
if (cellular_cellular_operator_parse(line, &cellular_operator))
{
void* p_dest = (void *)&p_cellular_operator_list->list[p_cellular_operator_list->len];
memcpy((void *)p_dest, &cellular_operator, sizeof(cellular_operator_t));
p_cellular_operator_list->len++;
}
}
}
else if ((type == TYPE_OK) && (strcmp(line, "OK") == 0))
{
/* All responses received */
Serial.printf("Got OK from +COPS, we are done :)\r\n");
}
else
{
/* TODO: Save error */
Serial.printf("[callbackCOPS] error, unexpected response 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
}
return WAIT;
}
static inline int callbackSTRING(int type, const char* buf, int len, int* data)
{
debug_print_callback(type, buf, len);
char line[1024+64];
if (sscanf(buf, "\r\n%[^\r]\r\n", line) != 1)
{
/* TODO: Save error */
Serial.printf("[callbackSTRING] error, cannot parse line from buffer <buf>%s</buf>\r\n", buf);
return WAIT;
}
/* Accept TYPE_PLUS and TYPE_OK, do nothing */
if ((type == TYPE_PLUS) || (type == TYPE_OK))
{
Serial.printf("[callbackSTRING] info, 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
}
else
{
Serial.printf("[callbackSTRING] error, unexpected response 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
}
return WAIT;
}
bool cellular_cmd_operator_selection(
cellular_operator_list_t* p_cellular_operator_list)
{
int data;
int ret;
int final_result = false;
/* TODO: Do we really need to probe before scanning? */
Serial.printf("[ AT+COPS=? ]\r\n");
ret = Cellular.command(callbackSTRING, &data, 3*60000, "AT+COPS=?\r\n");
/* Do scan if probe went fine */
if (ret == RESP_OK)
{
Serial.printf("[ AT+COPS=5 ]\r\n");
ret = Cellular.command(callbackCOPS, p_cellular_operator_list, 3*60000, "AT+COPS=5\r\n");
if (ret == RESP_OK)
{
final_result = true;
}
}
if (final_result)
{
Serial.printf("\r\nScan complete!\r\n");
}
else
{
Serial.printf("\r\nScan incomplete! Power cycle the modem and try again.\r\n");
}
return final_result;
}
<commit_msg>ISSUE #34 Remove debug prints from cellular code<commit_after>/* Copyright (c) 2016 Trevaling */
#if defined(PARTICLE)
#include "application.h"
#else
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "particle_mock.h"
#endif
#include "cellular.h"
#define META_CASE_RETURN(type) case type: return #type
const char* at_resp_type_to_str(int type)
{
switch (type)
{
META_CASE_RETURN(TYPE_UNKNOWN);
META_CASE_RETURN(TYPE_OK);
META_CASE_RETURN(TYPE_ERROR);
META_CASE_RETURN(TYPE_RING);
META_CASE_RETURN(TYPE_CONNECT);
META_CASE_RETURN(TYPE_NOCARRIER);
META_CASE_RETURN(TYPE_NODIALTONE);
META_CASE_RETURN(TYPE_BUSY);
META_CASE_RETURN(TYPE_NOANSWER);
META_CASE_RETURN(TYPE_PROMPT);
META_CASE_RETURN(TYPE_PLUS);
META_CASE_RETURN(TYPE_TEXT);
META_CASE_RETURN(TYPE_ABORTED);
default:
return "(unknown)";
}
}
/* Debug functions */
void debug_print_callback(int type, const char* buf, int len)
{
#if 0
Serial.printf("[debug] callback type 0x%06x %s len %d\r\n", type, at_resp_type_to_str(type), len);
char line[1024+64];
if (sscanf(buf, "\r\n%[^\r]\r\n", line) == 1)
{
Serial.printf("<line>%s</line>\r\n", line);
}
else
{
Serial.printf("<buf>%s</buf>\r\n", buf);
}
#endif
}
/* CREG functions */
#define ATCOMMAND_SCAN(cmd) "\r\n" cmd ": %[^\r]\r\n"
bool cmd_network_registration_status_parse(const char* buf,
cmd_network_registration_status_t* p_network_registration_status)
{
char parse_buffer[64];
char* p_token;
int retval;
retval = sscanf(buf, ATCOMMAND_SCAN("+CREG"), parse_buffer);
//Serial.printf("<parse_buffer>%s</parse_buffer>\r\n", parse_buffer);
if (retval != 1)
{
return false;
}
//TODO: Check for p_token being a sane pointer or return
p_token = strtok((char*)parse_buffer, ",");
p_network_registration_status->n = strtol(p_token, NULL, 10);
p_token = strtok(NULL, ",");
p_network_registration_status->stat = strtol(p_token, NULL, 10);
p_token = strtok(NULL, ",");
if (*p_token == '"')
{
p_token++;
p_network_registration_status->lac = strtol(p_token, NULL, 16);
}
else
{
p_network_registration_status->lac = strtol(p_token, NULL, 10);
}
p_token = strtok(0, ",");
if (*p_token == '"')
{
p_token++;
p_network_registration_status->ci = strtol(p_token, NULL, 16);
}
else
{
p_network_registration_status->ci = strtol(p_token, NULL, 10);
}
p_token = strtok(0, ",");
p_network_registration_status->actstatus = strtol(p_token, NULL, 10);
return true;
}
//TODO: Investigate number and type of callbacks
int callbackCREG_set(int type, const char* buf, int len, char* creg)
{
//debug_print_callback(type, buf, len);
if (type == TYPE_PLUS)
{
/*nothing*/
}
return WAIT;
}
int callbackCREG_get(int type, const char* buf, int len,
cmd_network_registration_status_t* p_network_registration_status)
{
//debug_print_callback(type, buf, len);
if (type == TYPE_PLUS)
{
cmd_network_registration_status_parse(buf, p_network_registration_status);
}
return WAIT;
}
bool cmd_network_registration_status_get(
cmd_network_registration_status_t* p_network_registration_status)
{
int retval;
char creg_set[32] = "";
memset(p_network_registration_status, 0, sizeof(cmd_network_registration_status_t));
//TODO: Investigate ahd check the Cellular.command retval
retval = Cellular.command(callbackCREG_set, creg_set, 10000, "AT+CREG=2\r\n");
//Serial.printf("Cellular.command retval: %d\r\n", retval);
retval = Cellular.command(callbackCREG_get, p_network_registration_status, 10000, "AT+CREG?\r\n");
//Serial.printf("Cellular.command retval: %d\r\n", retval);
return retval == RESP_OK;
}
/* Parses COPS response:
[MCC:<MCC>, MNC:<MNC>, LAC:<LAC>, CI:<CI>, BSIC:<BSIC>, Arfcn:<Arfcn>, RxLev:<RxLev>
*/
bool cellular_cellular_operator_parse(const char* buf,
cellular_operator_t* p_cellular_operator)
{
if ( sscanf(buf, "\r\nMCC:%d, MNC:%d, LAC:%x, CI:%x, BSIC:%x, Arfcn:%5d, RxLev:%3d\r\n",
&p_cellular_operator->mcc,
&p_cellular_operator->mnc,
&p_cellular_operator->lac,
&p_cellular_operator->ci,
&p_cellular_operator->bsic,
&p_cellular_operator->arfcn,
&p_cellular_operator->rxlev ) > 0 )
{
return true;
}
return false;
}
int callbackCOPS(int type, const char* buf, int len,
cellular_operator_list_t* p_cellular_operator_list)
{
debug_print_callback(type, buf, len);
char line[1024+64];
if (sscanf(buf, "\r\n%[^\r]\r\n", line) != 1)
{
/* TODO: Save error */
Serial.printf("[callbackCOPS] error, cannot parse line from buffer <buf>%s</buf>\r\n", buf);
return WAIT;
}
Serial.printf("[callbackCOPS] info, 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
if (type == TYPE_PLUS)
{
/* Ignore the seldom +CIEV responses */
}
else if (type == TYPE_UNKNOWN)
{
/* +COPS response */
if (p_cellular_operator_list->len < (CELLULAR_OPERATOR_MAX-1))
{
cellular_operator_t cellular_operator;
if (cellular_cellular_operator_parse(line, &cellular_operator))
{
void* p_dest = (void *)&p_cellular_operator_list->list[p_cellular_operator_list->len];
memcpy((void *)p_dest, &cellular_operator, sizeof(cellular_operator_t));
p_cellular_operator_list->len++;
}
}
}
else if ((type == TYPE_OK) && (strcmp(line, "OK") == 0))
{
/* All responses received */
Serial.printf("Got OK from +COPS, we are done :)\r\n");
}
else
{
/* TODO: Save error */
Serial.printf("[callbackCOPS] error, unexpected response 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
}
return WAIT;
}
static inline int callbackSTRING(int type, const char* buf, int len, int* data)
{
debug_print_callback(type, buf, len);
char line[1024+64];
if (sscanf(buf, "\r\n%[^\r]\r\n", line) != 1)
{
/* TODO: Save error */
Serial.printf("[callbackSTRING] error, cannot parse line from buffer <buf>%s</buf>\r\n", buf);
return WAIT;
}
/* Accept TYPE_PLUS and TYPE_OK, do nothing */
if ((type == TYPE_PLUS) || (type == TYPE_OK))
{
Serial.printf("[callbackSTRING] info, 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
}
else
{
Serial.printf("[callbackSTRING] error, unexpected response 0x%06x %s line %s\r\n",
type, at_resp_type_to_str(type), line);
}
return WAIT;
}
bool cellular_cmd_operator_selection(
cellular_operator_list_t* p_cellular_operator_list)
{
int data;
int ret;
int final_result = false;
/* TODO: Do we really need to probe before scanning? */
Serial.printf("[ AT+COPS=? ]\r\n");
ret = Cellular.command(callbackSTRING, &data, 3*60000, "AT+COPS=?\r\n");
/* Do scan if probe went fine */
if (ret == RESP_OK)
{
Serial.printf("[ AT+COPS=5 ]\r\n");
ret = Cellular.command(callbackCOPS, p_cellular_operator_list, 3*60000, "AT+COPS=5\r\n");
if (ret == RESP_OK)
{
final_result = true;
}
}
if (final_result)
{
Serial.printf("\r\nScan complete!\r\n");
}
else
{
Serial.printf("\r\nScan incomplete! Power cycle the modem and try again.\r\n");
}
return final_result;
}
<|endoftext|> |
<commit_before>#include "stdsneezy.h"
#include "database.h"
#include "corporation.h"
int getAssets(int corp_id)
{
int value=0, keepernum=0;
TDatabase db(DB_SNEEZY);
TObj *o=NULL;
TRoom *room;
TMonster *keeper;
db.query("select in_room, keeper from shop where shop_nr in (select shop_nr from shopowned where corp_id=%i)", corp_id);
while(db.fetchRow()){
room=real_roomp(convertTo<int>(db["in_room"]));
keepernum=convertTo<int>(db["keeper"]);
for(TThing *tt=room->getStuff();tt;tt=tt->nextThing){
if((keeper=dynamic_cast<TMonster *>(tt)) &&
keeper->mobVnum() == keepernum){
for(TThing *t=keeper->getStuff();t;t=t->nextThing){
o=dynamic_cast<TObj *>(t);
value+=o->obj_flags.cost;
}
break;
}
}
}
return value;
}
sstring talenDisplay(int talens)
{
float t;
if(talens>1000000){
t=(int)(talens/100000);
return fmt("%.1fM") % (t/10.0);
} else if(talens > 10000){
t=(int)(talens/1000);
return fmt("%ik") % (int)t;
}
return fmt("%i") % talens;
}
void corpListing(TBeing *ch, TMonster *me)
{
TDatabase db(DB_SNEEZY);
int corp_id=0, val=0, gold=0, shopval=0;
multimap <int, sstring, std::greater<int> > m;
multimap <int, sstring, std::greater<int> >::iterator it;
db.query("select c.corp_id, c.name, sum(s.gold)+c.gold as gold, count(so.shop_nr) as shopcount from corporation c, shopowned so, shop s where c.corp_id=so.corp_id and so.shop_nr=s.shop_nr group by c.corp_id, c.name, c.gold order by gold desc");
while(db.fetchRow()){
corp_id=convertTo<int>(db["corp_id"]);
gold=convertTo<int>(db["gold"]);
shopval=convertTo<int>(db["shopcount"]) * 1000000;
val=gold+getAssets(corp_id)+shopval;
m.insert(pair<int,sstring>(val,fmt("%-2i| %s - %s talens, %s in assets") %
corp_id % db["name"] %
talenDisplay(gold) %
talenDisplay(getAssets(corp_id)+shopval)));
}
me->doTell(ch->getName(), "I know about the following corporations:");
for(it=m.begin();it!=m.end();++it)
me->doTell(ch->getName(), (*it).second);
}
void corpLogs(TBeing *ch, TMonster *me, sstring arg)
{
TDatabase db(DB_SNEEZY);
sstring buf, sb;
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
db.query("select name, action, talens, corptalens, logtime from corplog where corp_id = %i order by logtime desc", corp_id);
while(db.fetchRow()){
buf = fmt("%19.19s %12s %10s %10s Total: %s\n\r") %
db["logtime"] % db["name"] % db["action"] %
db["talens"] % db["corptalens"];
sb += buf;
}
if (ch->desc)
ch->desc->page_string(sb, SHOWNOW_NO, ALLOWREP_YES);
}
void corpSummary(TBeing *ch, TMonster *me, int corp_id)
{
TDatabase db(DB_SNEEZY);
int value=0, gold=0, shopcount=0, bank=0;
sstring buf;
if(!corp_id){
me->doTell(ch->getName(), "I don't have any information for that corporation.");
return;
}
db.query("select c.name, sum(s.gold) as gold, c.gold as bank, count(s.shop_nr) as shops from corporation c, shopowned so, shop s where c.corp_id=so.corp_id and c.corp_id=%i and so.shop_nr=s.shop_nr group by c.corp_id, c.name, c.gold order by c.corp_id", corp_id);
if(!db.fetchRow()){
me->doTell(ch->getName(), "I don't have any information for that corporation.");
return;
}
me->doTell(ch->getName(), fmt("%-3i| %s") %
corp_id % db["name"]);
bank=convertTo<int>(db["bank"]);
gold=convertTo<int>(db["gold"]);
value=getAssets(corp_id);
shopcount=convertTo<int>(db["shops"]);
me->doTell(ch->getName(), fmt("Bank Talens: %12s") %
(fmt("%i") % bank).comify());
me->doTell(ch->getName(), fmt("Talens: %12s") %
(fmt("%i") % gold).comify());
me->doTell(ch->getName(), fmt("Assets: %12s") %
(fmt("%i") % value).comify());
me->doTell(ch->getName(), fmt("Shops (x1M): %12s") %
(fmt("%i") % (shopcount*1000000)).comify());
me->doTell(ch->getName(), fmt("Total value: %12s") %
(fmt("%i") % (bank+gold+value+(shopcount * 1000000))).comify());
// officers
db.query("select name from corpaccess where corp_id=%i", corp_id);
buf="";
while(db.fetchRow()){
buf+=" ";
buf+=db["name"];
}
me->doTell(ch->getName(), fmt("Corporate officers are:%s") % buf);
// shops
db.query("select s.shop_nr, s.in_room, s.gold from shop s, shopowned so where s.shop_nr=so.shop_nr and so.corp_id=%i order by s.gold desc", corp_id);
TRoom *tr=NULL;
me->doTell(ch->getName(), "The following shops are owned by this corporation:");
while(db.fetchRow()){
if((tr=real_roomp(convertTo<int>(db["in_room"])))){
gold=convertTo<int>(db["gold"]);
me->doTell(ch->getName(), fmt("%-3s| %s with %s talens.") %
db["shop_nr"] % tr->getName() % talenDisplay(gold));
}
}
}
void corpDeposit(TBeing *ch, TMonster *me, int gold, sstring arg)
{
TDatabase db(DB_SNEEZY);
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
TCorporation corp(corp_id);
if(ch->getMoney() < gold){
me->doTell(ch->getName(), "You don't have that many talens.");
return;
}
me->doTell(ch->getName(), fmt("Ok, you are depositing %i gold.") % gold);
ch->addToMoney(-gold, GOLD_XFER);
corp.setMoney(corp.getMoney() + gold);
corp.corpLog(ch->getName(), "deposit", gold);
me->doTell(ch->getName(), fmt("Your balance is %i.") % corp.getMoney());
}
void corpWithdraw(TBeing *ch, TMonster *me, int gold, sstring arg)
{
TDatabase db(DB_SNEEZY);
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
TCorporation corp(corp_id);
int tmp=corp.getMoney();
if(tmp < gold){
me->doTell(ch->getName(), fmt("Your corporation only has %i talens.") % tmp);
return;
}
corp.setMoney(corp.getMoney() - gold);
corp.corpLog(ch->getName(), "withdrawal", -gold);
ch->addToMoney(gold, GOLD_XFER);
me->doTell(ch->getName(), fmt("Ok, here is %i talens.") % gold);
me->doTell(ch->getName(), fmt("Your balance is %i.") % (tmp-gold));
}
void corpBalance(TBeing *ch, TMonster *me, sstring arg)
{
TDatabase db(DB_SNEEZY);
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
db.query("select gold from corporation where corp_id=%i", corp_id);
db.fetchRow();
me->doTell(ch->getName(), fmt("Your balance is %s.") % db["gold"]);
}
int corporateAssistant(TBeing *ch, cmdTypeT cmd, const char *argument, TMonster *me, TObj *)
{
if(!ch || !me)
return FALSE;
TDatabase db(DB_SNEEZY);
int tmp=0;
sstring buf, arg=argument;
if(cmd==CMD_LIST){
if(arg.empty()){
// list short summary of all corporations
corpListing(ch, me);
} else if(arg.word(0) == "logs"){
corpLogs(ch, me, arg.word(1));
} else if(!arg.empty()){
// list details of a specific corporation
tmp=convertTo<int>(arg);
corpSummary(ch, me, tmp);
}
} else if(cmd==CMD_DEPOSIT){
tmp=convertTo<int>(arg);
corpDeposit(ch, me, tmp, arg.word(2));
} else if(cmd==CMD_WITHDRAW){
tmp=convertTo<int>(arg);
corpWithdraw(ch, me, tmp, arg.word(2));
} else if(cmd==CMD_BALANCE){
corpBalance(ch, me, arg);
} else
return false;
return true;
}
<commit_msg>changed output format for list to accomodate longer corp names<commit_after>#include "stdsneezy.h"
#include "database.h"
#include "corporation.h"
int getAssets(int corp_id)
{
int value=0, keepernum=0;
TDatabase db(DB_SNEEZY);
TObj *o=NULL;
TRoom *room;
TMonster *keeper;
db.query("select in_room, keeper from shop where shop_nr in (select shop_nr from shopowned where corp_id=%i)", corp_id);
while(db.fetchRow()){
room=real_roomp(convertTo<int>(db["in_room"]));
keepernum=convertTo<int>(db["keeper"]);
for(TThing *tt=room->getStuff();tt;tt=tt->nextThing){
if((keeper=dynamic_cast<TMonster *>(tt)) &&
keeper->mobVnum() == keepernum){
for(TThing *t=keeper->getStuff();t;t=t->nextThing){
o=dynamic_cast<TObj *>(t);
value+=o->obj_flags.cost;
}
break;
}
}
}
return value;
}
sstring talenDisplay(int talens)
{
float t;
if(talens>1000000){
t=(int)(talens/100000);
return fmt("%.1fM") % (t/10.0);
} else if(talens > 10000){
t=(int)(talens/1000);
return fmt("%ik") % (int)t;
}
return fmt("%i") % talens;
}
void corpListing(TBeing *ch, TMonster *me)
{
TDatabase db(DB_SNEEZY);
int corp_id=0, val=0, gold=0, shopval=0;
multimap <int, sstring, std::greater<int> > m;
multimap <int, sstring, std::greater<int> >::iterator it;
db.query("select c.corp_id, c.name, sum(s.gold)+c.gold as gold, count(so.shop_nr) as shopcount from corporation c, shopowned so, shop s where c.corp_id=so.corp_id and so.shop_nr=s.shop_nr group by c.corp_id, c.name, c.gold order by gold desc");
while(db.fetchRow()){
corp_id=convertTo<int>(db["corp_id"]);
gold=convertTo<int>(db["gold"]);
shopval=convertTo<int>(db["shopcount"]) * 1000000;
val=gold+getAssets(corp_id)+shopval;
m.insert(pair<int,sstring>(val,fmt("%-2i| %s") % corp_id % db["name"]));
m.insert(pair<int,sstring>(val,fmt(" | %s talens, %s in assets") %
talenDisplay(gold) %
talenDisplay(getAssets(corp_id)+shopval)));
}
me->doTell(ch->getName(), "I know about the following corporations:");
for(it=m.begin();it!=m.end();++it)
me->doTell(ch->getName(), (*it).second);
}
void corpLogs(TBeing *ch, TMonster *me, sstring arg)
{
TDatabase db(DB_SNEEZY);
sstring buf, sb;
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
db.query("select name, action, talens, corptalens, logtime from corplog where corp_id = %i order by logtime desc", corp_id);
while(db.fetchRow()){
buf = fmt("%19.19s %12s %10s %10s Total: %s\n\r") %
db["logtime"] % db["name"] % db["action"] %
db["talens"] % db["corptalens"];
sb += buf;
}
if (ch->desc)
ch->desc->page_string(sb, SHOWNOW_NO, ALLOWREP_YES);
}
void corpSummary(TBeing *ch, TMonster *me, int corp_id)
{
TDatabase db(DB_SNEEZY);
int value=0, gold=0, shopcount=0, bank=0;
sstring buf;
if(!corp_id){
me->doTell(ch->getName(), "I don't have any information for that corporation.");
return;
}
db.query("select c.name, sum(s.gold) as gold, c.gold as bank, count(s.shop_nr) as shops from corporation c, shopowned so, shop s where c.corp_id=so.corp_id and c.corp_id=%i and so.shop_nr=s.shop_nr group by c.corp_id, c.name, c.gold order by c.corp_id", corp_id);
if(!db.fetchRow()){
me->doTell(ch->getName(), "I don't have any information for that corporation.");
return;
}
me->doTell(ch->getName(), fmt("%-3i| %s") %
corp_id % db["name"]);
bank=convertTo<int>(db["bank"]);
gold=convertTo<int>(db["gold"]);
value=getAssets(corp_id);
shopcount=convertTo<int>(db["shops"]);
me->doTell(ch->getName(), fmt("Bank Talens: %12s") %
(fmt("%i") % bank).comify());
me->doTell(ch->getName(), fmt("Talens: %12s") %
(fmt("%i") % gold).comify());
me->doTell(ch->getName(), fmt("Assets: %12s") %
(fmt("%i") % value).comify());
me->doTell(ch->getName(), fmt("Shops (x1M): %12s") %
(fmt("%i") % (shopcount*1000000)).comify());
me->doTell(ch->getName(), fmt("Total value: %12s") %
(fmt("%i") % (bank+gold+value+(shopcount * 1000000))).comify());
// officers
db.query("select name from corpaccess where corp_id=%i", corp_id);
buf="";
while(db.fetchRow()){
buf+=" ";
buf+=db["name"];
}
me->doTell(ch->getName(), fmt("Corporate officers are:%s") % buf);
// shops
db.query("select s.shop_nr, s.in_room, s.gold from shop s, shopowned so where s.shop_nr=so.shop_nr and so.corp_id=%i order by s.gold desc", corp_id);
TRoom *tr=NULL;
me->doTell(ch->getName(), "The following shops are owned by this corporation:");
while(db.fetchRow()){
if((tr=real_roomp(convertTo<int>(db["in_room"])))){
gold=convertTo<int>(db["gold"]);
me->doTell(ch->getName(), fmt("%-3s| %s with %s talens.") %
db["shop_nr"] % tr->getName() % talenDisplay(gold));
}
}
}
void corpDeposit(TBeing *ch, TMonster *me, int gold, sstring arg)
{
TDatabase db(DB_SNEEZY);
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to deposit the money for.");
return;
}
TCorporation corp(corp_id);
if(ch->getMoney() < gold){
me->doTell(ch->getName(), "You don't have that many talens.");
return;
}
me->doTell(ch->getName(), fmt("Ok, you are depositing %i gold.") % gold);
ch->addToMoney(-gold, GOLD_XFER);
corp.setMoney(corp.getMoney() + gold);
corp.corpLog(ch->getName(), "deposit", gold);
me->doTell(ch->getName(), fmt("Your balance is %i.") % corp.getMoney());
}
void corpWithdraw(TBeing *ch, TMonster *me, int gold, sstring arg)
{
TDatabase db(DB_SNEEZY);
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
TCorporation corp(corp_id);
int tmp=corp.getMoney();
if(tmp < gold){
me->doTell(ch->getName(), fmt("Your corporation only has %i talens.") % tmp);
return;
}
corp.setMoney(corp.getMoney() - gold);
corp.corpLog(ch->getName(), "withdrawal", -gold);
ch->addToMoney(gold, GOLD_XFER);
me->doTell(ch->getName(), fmt("Ok, here is %i talens.") % gold);
me->doTell(ch->getName(), fmt("Your balance is %i.") % (tmp-gold));
}
void corpBalance(TBeing *ch, TMonster *me, sstring arg)
{
TDatabase db(DB_SNEEZY);
int corp_id=0;
db.query("select corp_id from corpaccess where lower(name)='%s'",
sstring(ch->getName()).lower().c_str());
if(arg.empty()){
if(db.fetchRow())
corp_id=convertTo<int>(db["corp_id"]);
if(db.fetchRow()){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
} else {
if(convertTo<int>(arg) == 0){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
while(db.fetchRow()){
if(convertTo<int>(db["corp_id"]) == convertTo<int>(arg)){
corp_id=convertTo<int>(arg);
break;
}
}
}
if(!corp_id){
me->doTell(ch->getName(), "You must specify the ID of the corporation you wish to withdraw the money from.");
return;
}
db.query("select gold from corporation where corp_id=%i", corp_id);
db.fetchRow();
me->doTell(ch->getName(), fmt("Your balance is %s.") % db["gold"]);
}
int corporateAssistant(TBeing *ch, cmdTypeT cmd, const char *argument, TMonster *me, TObj *)
{
if(!ch || !me)
return FALSE;
TDatabase db(DB_SNEEZY);
int tmp=0;
sstring buf, arg=argument;
if(cmd==CMD_LIST){
if(arg.empty()){
// list short summary of all corporations
corpListing(ch, me);
} else if(arg.word(0) == "logs"){
corpLogs(ch, me, arg.word(1));
} else if(!arg.empty()){
// list details of a specific corporation
tmp=convertTo<int>(arg);
corpSummary(ch, me, tmp);
}
} else if(cmd==CMD_DEPOSIT){
tmp=convertTo<int>(arg);
corpDeposit(ch, me, tmp, arg.word(2));
} else if(cmd==CMD_WITHDRAW){
tmp=convertTo<int>(arg);
corpWithdraw(ch, me, tmp, arg.word(2));
} else if(cmd==CMD_BALANCE){
corpBalance(ch, me, arg);
} else
return false;
return true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
char out [2][13];
int main() {
map<char, vector<int>> m;
string str; cin >> str;
for (int i = 0; i < 27; i++) m[str[i]].push_back(i);
char me;
vector<int> v;
for (auto it : m) {
if (it.second.size() == 2) {
me = it.first;
v = it.second;
break;
}
}
if (v[1] - v[0] == 1) {
cout << "Impossible\n";
return 0;
}
int left = v[1] - v[0] - 1;
int right = 26 - left - 1;
out[0][left/2] = me;
int cur = v[0] + 1;
int r = 0; int c = left/2 - 1;
int inc = -1;
int x = left;
while (x--) {
if (c == -1) {
r =1; c = 0; inc = 1;
}
out[r][c] = str[cur++];
c += inc;
}
r = 0; c = left / 2 + 1;
cur = v[1] + 1;
inc = 1;
while (right--) {
if (c == 13) {
r = 1; c = 12; inc = -1;
}
out[r][c] = str[cur % 27];
cur++;
c += inc;
}
for (c = 0; c < 13; c++) cout << out[0][c]; cout << endl;
for (c = 0; c < 13; c++) cout << out[1][c]; cout << endl;
return 0;
}
<commit_msg>codeforces canada cup 2016 problem c<commit_after>#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
char out [2][13];
int main() {
map<char, vector<int>> m;
string str; cin >> str;
for (int i = 0; i < 27; i++) {
m[str[i]].push_back(i);
}
char me;
vector<int> v;
for (auto it : m) {
if (it.second.size() == 2) { me = it.first; v = it.second; }
}
if (v[1] - v[0] == 1) {
cout << "Impossible\n";
return 0;
}
int left = v[1] - v[0] - 1;
int right = 26 - left - 1;
out[0][left/2] = me;
int cur = v[0] + 1;
int r = 0; int c = left/2 - 1;
int inc = -1;
int x = left;
while (x--) {
if (c == -1) {
r =1; c = 0; inc = 1;
}
out[r][c] = str[cur++];
c += inc;
}
r = 0; c = left / 2 + 1;
cur = v[1] + 1;
inc = 1;
while (right--) {
if (c == 13) {
r = 1; c = 12; inc = -1;
}
out[r][c] = str[cur % 27];
cur++;
c += inc;
}
for (r = 0; r < 2; r++) {
for (c = 0; c < 13; c++) {
cout << out[r][c];
}
cout << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "osl/process.h"
#include "rtl/strbuf.hxx"
#include "rtl/ustring.hxx"
#include "osl/thread.h"
#include "osl/file.hxx"
#include <string.h>
#if defined(SAL_W32)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif
#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif
#include "codemaker/global.hxx"
#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif
using namespace ::rtl;
using namespace ::osl;
OString getTempDir(const OString& sFileName)
{
sal_Int32 index = 0;
#ifdef SAL_UNX
if ((index=sFileName.lastIndexOf('/')) > 0)
return sFileName.copy(0, index);
#else
if ((index=sFileName.lastIndexOf('\\')) > 0)
return sFileName.copy(0, index);
#endif
return ".";
}
OString createFileNameFromType( const OString& destination,
const OString typeName,
const OString postfix,
sal_Bool bLowerCase,
const OString prefix )
{
OString type(typeName.replace('.', '/'));
if (bLowerCase)
{
type = typeName.toAsciiLowerCase();
}
sal_uInt32 length = destination.getLength();
sal_Bool withPoint = sal_False;
if (length == 0)
{
length++;
withPoint = sal_True;
}
length += prefix.getLength() + type.getLength() + postfix.getLength();
sal_Bool withSeparator = sal_False;
if (destination.getStr()[destination.getLength()] != '\\' &&
destination.getStr()[destination.getLength()] != '/' &&
type.getStr()[0] != '\\' &&
type.getStr()[0] != '/')
{
length++;
withSeparator = sal_True;
}
OStringBuffer fileNameBuf(length);
if (withPoint)
fileNameBuf.append('.');
else
fileNameBuf.append(destination.getStr(), destination.getLength());
if (withSeparator)
fileNameBuf.append("/", 1);
OString tmpStr(type);
if (!prefix.isEmpty())
{
tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
}
fileNameBuf.append(tmpStr.getStr(), tmpStr.getLength());
fileNameBuf.append(postfix.getStr(), postfix.getLength());
OString fileName(fileNameBuf.makeStringAndClear());
sal_Char token;
#ifdef SAL_UNX
fileName = fileName.replace('\\', '/');
token = '/';
#else
fileName = fileName.replace('/', '\\');
token = '\\';
#endif
OStringBuffer buffer(length);
sal_Int32 nIndex = 0;
do
{
buffer.append(fileName.getToken(0, token, nIndex).getStr());
if( nIndex == -1 )
break;
if (buffer.isEmpty() || OString(".") == buffer.getStr())
{
buffer.append(token);
continue;
}
#if defined(SAL_UNX)
if (mkdir((char*)buffer.getStr(), 0777) == -1)
#else
if (mkdir((char*)buffer.getStr()) == -1)
#endif
{
if ( errno == ENOENT )
return OString();
}
buffer.append(token);
} while( nIndex != -1 );
OUString uSysFileName;
OSL_VERIFY( FileBase::getSystemPathFromFileURL(
convertToFileUrl(fileName), uSysFileName) == FileBase::E_None );
return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());;
}
sal_Bool fileExists(const OString& fileName)
{
FILE *f= fopen(fileName.getStr(), "r");
if (f != NULL)
{
fclose(f);
return sal_True;
}
return sal_False;
}
sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
FILE *target = fopen(targetFileName.getStr(), "r");
FILE *tmp = fopen(tmpFileName.getStr(), "r");
sal_Bool bFindChanges = sal_False;
if (target != NULL && tmp != NULL)
{
sal_Char buffer1[1024+1];
sal_Char buffer2[1024+1];
sal_Int32 n1 = 0;
sal_Int32 n2 = 0;
while ( !bFindChanges && !feof(target) && !feof(tmp))
{
n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);
if ( n1 != n2 )
bFindChanges = sal_True;
else
if ( memcmp(buffer1, buffer2, n2) != 0 )
bFindChanges = sal_True;
}
}
if (target) fclose(target);
if (tmp) fclose(tmp);
return bFindChanges;
}
sal_Bool makeValidTypeFile(const OString& targetFileName, const OString& tmpFileName,
sal_Bool bFileCheck)
{
if (bFileCheck) {
if (checkFileContent(targetFileName, tmpFileName)) {
if ( !unlink(targetFileName.getStr()) )
if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
return sal_True;
} else
return removeTypeFile(tmpFileName);
} else {
if (fileExists(targetFileName))
if (!removeTypeFile(targetFileName))
return sal_False;
if ( rename(tmpFileName.getStr(), targetFileName.getStr()) ) {
if (errno == EEXIST)
return sal_True;
} else
return sal_True;
}
return sal_False;
}
sal_Bool removeTypeFile(const OString& fileName)
{
if ( !unlink(fileName.getStr()) )
return sal_True;
return sal_False;
}
static sal_Bool isFileUrl(const OString& fileName)
{
if (fileName.indexOf("file://") == 0 )
return sal_True;
return sal_False;
}
OUString convertToFileUrl(const OString& fileName)
{
if ( isFileUrl(fileName) )
{
return OStringToOUString(fileName, osl_getThreadTextEncoding());
}
OUString uUrlFileName;
OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
{
OUString uWorkingDir;
if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
{
OSL_ASSERT(false);
}
if (FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
} else
{
if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
}
return uUrlFileName;
}
//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
: m_file(NULL)
{
}
FileStream::~FileStream()
{
if ( isValid() )
osl_closeFile(m_file);
}
sal_Bool FileStream::isValid()
{
if ( m_file )
return sal_True;
return sal_False;
}
void FileStream::createTempFile(const OString& sPath)
{
OString sTmp(".");
OUString sTmpPath;
OUString sTmpName;
if (!sPath.isEmpty())
sTmp = sPath;
sTmpPath = convertToFileUrl(sTmp);
if (osl_createTempFile(sTmpPath.pData, &m_file, &sTmpName.pData) == osl_File_E_None) {
#ifdef SAL_UNX
sal_uInt64 uAttr = osl_File_Attribute_OwnWrite |
osl_File_Attribute_OwnRead |
osl_File_Attribute_GrpWrite |
osl_File_Attribute_GrpRead |
osl_File_Attribute_OthRead;
if (osl_setFileAttributes(sTmpName.pData, uAttr) != osl_File_E_None) {
m_file = NULL;
return;
}
#endif
OUString sSysTmpName;
FileBase::getSystemPathFromFileURL(sTmpName, sSysTmpName);
m_name = OUStringToOString(sSysTmpName, osl_getThreadTextEncoding());
} else
m_file = NULL;
}
void FileStream::close()
{
if ( isValid() )
{
osl_closeFile(m_file);
m_file = NULL;
m_name = OString();
}
}
bool FileStream::write(void const * buffer, sal_uInt64 size) {
while (size > 0) {
sal_uInt64 written;
if (osl_writeFile(m_file, buffer, size, &written) != osl_File_E_None) {
return false;
}
OSL_ASSERT(written <= size);
size -= written;
buffer = static_cast< char const * >(buffer) + written;
}
return true;
}
FileStream &operator<<(FileStream& o, sal_uInt32 i) {
sal_uInt64 writtenBytes;
OString s = OString::number(i);
osl_writeFile(o.m_file, s.getStr(), s.getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, char const * s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s, strlen(s), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, ::rtl::OString* s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s->getStr(), s->getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, const ::rtl::OString& s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s.getStr(), s.getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, ::rtl::OStringBuffer* s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s->getStr(), s->getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, const ::rtl::OStringBuffer& s) {
sal_uInt64 writtenBytes;
osl_writeFile(
o.m_file, s.getStr(), s.getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream & operator <<(FileStream & out, rtl::OUString const & s) {
return out << OUStringToOString(s, RTL_TEXTENCODING_UTF8);
}
CannotDumpException::~CannotDumpException() throw () {}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Write integers as signed sal_Int32<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "osl/process.h"
#include "rtl/strbuf.hxx"
#include "rtl/ustring.hxx"
#include "osl/thread.h"
#include "osl/file.hxx"
#include <string.h>
#if defined(SAL_W32)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif
#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif
#include "codemaker/global.hxx"
#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif
using namespace ::rtl;
using namespace ::osl;
OString getTempDir(const OString& sFileName)
{
sal_Int32 index = 0;
#ifdef SAL_UNX
if ((index=sFileName.lastIndexOf('/')) > 0)
return sFileName.copy(0, index);
#else
if ((index=sFileName.lastIndexOf('\\')) > 0)
return sFileName.copy(0, index);
#endif
return ".";
}
OString createFileNameFromType( const OString& destination,
const OString typeName,
const OString postfix,
sal_Bool bLowerCase,
const OString prefix )
{
OString type(typeName.replace('.', '/'));
if (bLowerCase)
{
type = typeName.toAsciiLowerCase();
}
sal_uInt32 length = destination.getLength();
sal_Bool withPoint = sal_False;
if (length == 0)
{
length++;
withPoint = sal_True;
}
length += prefix.getLength() + type.getLength() + postfix.getLength();
sal_Bool withSeparator = sal_False;
if (destination.getStr()[destination.getLength()] != '\\' &&
destination.getStr()[destination.getLength()] != '/' &&
type.getStr()[0] != '\\' &&
type.getStr()[0] != '/')
{
length++;
withSeparator = sal_True;
}
OStringBuffer fileNameBuf(length);
if (withPoint)
fileNameBuf.append('.');
else
fileNameBuf.append(destination.getStr(), destination.getLength());
if (withSeparator)
fileNameBuf.append("/", 1);
OString tmpStr(type);
if (!prefix.isEmpty())
{
tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
}
fileNameBuf.append(tmpStr.getStr(), tmpStr.getLength());
fileNameBuf.append(postfix.getStr(), postfix.getLength());
OString fileName(fileNameBuf.makeStringAndClear());
sal_Char token;
#ifdef SAL_UNX
fileName = fileName.replace('\\', '/');
token = '/';
#else
fileName = fileName.replace('/', '\\');
token = '\\';
#endif
OStringBuffer buffer(length);
sal_Int32 nIndex = 0;
do
{
buffer.append(fileName.getToken(0, token, nIndex).getStr());
if( nIndex == -1 )
break;
if (buffer.isEmpty() || OString(".") == buffer.getStr())
{
buffer.append(token);
continue;
}
#if defined(SAL_UNX)
if (mkdir((char*)buffer.getStr(), 0777) == -1)
#else
if (mkdir((char*)buffer.getStr()) == -1)
#endif
{
if ( errno == ENOENT )
return OString();
}
buffer.append(token);
} while( nIndex != -1 );
OUString uSysFileName;
OSL_VERIFY( FileBase::getSystemPathFromFileURL(
convertToFileUrl(fileName), uSysFileName) == FileBase::E_None );
return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());;
}
sal_Bool fileExists(const OString& fileName)
{
FILE *f= fopen(fileName.getStr(), "r");
if (f != NULL)
{
fclose(f);
return sal_True;
}
return sal_False;
}
sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
FILE *target = fopen(targetFileName.getStr(), "r");
FILE *tmp = fopen(tmpFileName.getStr(), "r");
sal_Bool bFindChanges = sal_False;
if (target != NULL && tmp != NULL)
{
sal_Char buffer1[1024+1];
sal_Char buffer2[1024+1];
sal_Int32 n1 = 0;
sal_Int32 n2 = 0;
while ( !bFindChanges && !feof(target) && !feof(tmp))
{
n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);
if ( n1 != n2 )
bFindChanges = sal_True;
else
if ( memcmp(buffer1, buffer2, n2) != 0 )
bFindChanges = sal_True;
}
}
if (target) fclose(target);
if (tmp) fclose(tmp);
return bFindChanges;
}
sal_Bool makeValidTypeFile(const OString& targetFileName, const OString& tmpFileName,
sal_Bool bFileCheck)
{
if (bFileCheck) {
if (checkFileContent(targetFileName, tmpFileName)) {
if ( !unlink(targetFileName.getStr()) )
if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
return sal_True;
} else
return removeTypeFile(tmpFileName);
} else {
if (fileExists(targetFileName))
if (!removeTypeFile(targetFileName))
return sal_False;
if ( rename(tmpFileName.getStr(), targetFileName.getStr()) ) {
if (errno == EEXIST)
return sal_True;
} else
return sal_True;
}
return sal_False;
}
sal_Bool removeTypeFile(const OString& fileName)
{
if ( !unlink(fileName.getStr()) )
return sal_True;
return sal_False;
}
static sal_Bool isFileUrl(const OString& fileName)
{
if (fileName.indexOf("file://") == 0 )
return sal_True;
return sal_False;
}
OUString convertToFileUrl(const OString& fileName)
{
if ( isFileUrl(fileName) )
{
return OStringToOUString(fileName, osl_getThreadTextEncoding());
}
OUString uUrlFileName;
OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
{
OUString uWorkingDir;
if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
{
OSL_ASSERT(false);
}
if (FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
} else
{
if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
}
return uUrlFileName;
}
//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
: m_file(NULL)
{
}
FileStream::~FileStream()
{
if ( isValid() )
osl_closeFile(m_file);
}
sal_Bool FileStream::isValid()
{
if ( m_file )
return sal_True;
return sal_False;
}
void FileStream::createTempFile(const OString& sPath)
{
OString sTmp(".");
OUString sTmpPath;
OUString sTmpName;
if (!sPath.isEmpty())
sTmp = sPath;
sTmpPath = convertToFileUrl(sTmp);
if (osl_createTempFile(sTmpPath.pData, &m_file, &sTmpName.pData) == osl_File_E_None) {
#ifdef SAL_UNX
sal_uInt64 uAttr = osl_File_Attribute_OwnWrite |
osl_File_Attribute_OwnRead |
osl_File_Attribute_GrpWrite |
osl_File_Attribute_GrpRead |
osl_File_Attribute_OthRead;
if (osl_setFileAttributes(sTmpName.pData, uAttr) != osl_File_E_None) {
m_file = NULL;
return;
}
#endif
OUString sSysTmpName;
FileBase::getSystemPathFromFileURL(sTmpName, sSysTmpName);
m_name = OUStringToOString(sSysTmpName, osl_getThreadTextEncoding());
} else
m_file = NULL;
}
void FileStream::close()
{
if ( isValid() )
{
osl_closeFile(m_file);
m_file = NULL;
m_name = OString();
}
}
bool FileStream::write(void const * buffer, sal_uInt64 size) {
while (size > 0) {
sal_uInt64 written;
if (osl_writeFile(m_file, buffer, size, &written) != osl_File_E_None) {
return false;
}
OSL_ASSERT(written <= size);
size -= written;
buffer = static_cast< char const * >(buffer) + written;
}
return true;
}
FileStream &operator<<(FileStream& o, sal_uInt32 i) {
sal_uInt64 writtenBytes;
OString s = OString::number((sal_Int32)i);
osl_writeFile(o.m_file, s.getStr(), s.getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, char const * s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s, strlen(s), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, ::rtl::OString* s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s->getStr(), s->getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, const ::rtl::OString& s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s.getStr(), s.getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, ::rtl::OStringBuffer* s) {
sal_uInt64 writtenBytes;
osl_writeFile(o.m_file, s->getStr(), s->getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream &operator<<(FileStream& o, const ::rtl::OStringBuffer& s) {
sal_uInt64 writtenBytes;
osl_writeFile(
o.m_file, s.getStr(), s.getLength() * sizeof(sal_Char), &writtenBytes);
return o;
}
FileStream & operator <<(FileStream & out, rtl::OUString const & s) {
return out << OUStringToOString(s, RTL_TEXTENCODING_UTF8);
}
CannotDumpException::~CannotDumpException() throw () {}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>Allow 'chrome-extension:' URLs to bypass content settings (1/2)<commit_after><|endoftext|> |
<commit_before>
#include "VM.h"
#include <libevm/VMFace.h>
#include "ExecutionEngine.h"
#include "Compiler.h"
#include "Type.h"
namespace dev
{
namespace eth
{
namespace jit
{
bytesConstRef VM::go(ExtVMFace& _ext, OnOpFunc const&, uint64_t)
{
auto module = Compiler().compile(_ext.code);
ExecutionEngine engine;
auto exitCode = engine.run(std::move(module), m_gas, &_ext);
switch (static_cast<ReturnCode>(exitCode))
{
case ReturnCode::BadJumpDestination:
BOOST_THROW_EXCEPTION(BadJumpDestination());
case ReturnCode::OutOfGas:
BOOST_THROW_EXCEPTION(OutOfGas());
case ReturnCode::StackTooSmall:
BOOST_THROW_EXCEPTION(StackTooSmall(1,0));
case ReturnCode::BadInstruction:
BOOST_THROW_EXCEPTION(BadInstruction());
}
m_output = std::move(engine.returnData);
return {m_output.data(), m_output.size()}; // TODO: This all bytesConstRef stuff sucks
}
}
}
}
<commit_msg>Improve VM code formatting<commit_after>
#include "VM.h"
#include <libevm/VMFace.h>
#include "ExecutionEngine.h"
#include "Compiler.h"
#include "Type.h"
namespace dev
{
namespace eth
{
namespace jit
{
bytesConstRef VM::go(ExtVMFace& _ext, OnOpFunc const&, uint64_t)
{
auto module = Compiler().compile(_ext.code);
ExecutionEngine engine;
auto exitCode = engine.run(std::move(module), m_gas, &_ext);
switch (static_cast<ReturnCode>(exitCode))
{
case ReturnCode::BadJumpDestination:
BOOST_THROW_EXCEPTION(BadJumpDestination());
case ReturnCode::OutOfGas:
BOOST_THROW_EXCEPTION(OutOfGas());
case ReturnCode::StackTooSmall:
BOOST_THROW_EXCEPTION(StackTooSmall(1, 0));
case ReturnCode::BadInstruction:
BOOST_THROW_EXCEPTION(BadInstruction());
}
m_output = std::move(engine.returnData);
return {m_output.data(), m_output.size()}; // TODO: This all bytesConstRef stuff sucks
}
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMersenneTwisterRandomVariateGeneratorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "vnl/vnl_sample.h"
#include "vnl/vnl_math.h"
#include "itkTimeProbe.h"
bool ComputeMeanAndVariance( const unsigned long numberOfSamples );
int itkMersenneTwisterRandomVariateGeneratorTest(int, char* [] )
{
#if __CYGWIN__
vnl_sample_reseed(0x1234abcd);
#endif
std::cout << "MersenneTwisterRandomVariateGenerator Test" << std::endl;
bool pass = true;
pass &= ComputeMeanAndVariance( 100000000UL );
pass &= ComputeMeanAndVariance( 10000000UL );
pass &= ComputeMeanAndVariance( 1000000UL );
if( pass )
{
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
bool ComputeMeanAndVariance(const unsigned long numberOfSamples)
{
std::cout << "Test mean and variance of a uniform distribution [0, 10): " << std::endl;
bool pass = true;
const double tolerance = 0.05;
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator GeneratorType;
GeneratorType::Pointer generator = GeneratorType::New();
GeneratorType::IntegerType randomSeed = 14543 ; // any number to initialize the seed.
generator->Initialize( randomSeed );
double MTsum = 0.0f;
double MTsum2 = 0.0f;
std::cout << "Compute Mean and variance with " <<
numberOfSamples << " samples... " << std::endl;
itk::TimeProbe clockMT1;
clockMT1.Start();
for(unsigned int i=0; i < numberOfSamples; i++)
{
generator->GetUniformVariate(0,10);
}
clockMT1.Stop();
for(unsigned int i=0; i < numberOfSamples; i++)
{
double variate = generator->GetUniformVariate(0,10);
MTsum += variate;
MTsum2 += variate * variate;
}
{
const double mean = MTsum / numberOfSamples;
const double variance = MTsum2 / numberOfSamples - mean * mean;
std::cout << "Mean [MersenneTwisterRandomVariateGenerator] = "
<< mean << std::endl;
std::cout << "Variance [MersenneTwisterRandomVariateGenerator] = "
<< variance << std::endl;
const double uniformVariance = 100.0/12.0;
std::cout << "Testing Mean " << std::endl;
if( vcl_abs(mean - 5) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
std::cout << "Testing Variance " << std::endl;
if( vcl_abs(variance - uniformVariance) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
}
double vnlSum = 0.0f;
double vnlSum2 = 0.0f;
std::cout << "USING VNL " << std::endl;
itk::TimeProbe clockVnl1;
clockVnl1.Start();
for(unsigned int i=0; i < numberOfSamples; i++)
{
vnl_sample_uniform(0,10);
}
clockVnl1.Stop();
for(unsigned int i=0; i < numberOfSamples; i++)
{
double variate = vnl_sample_uniform(0,10);
vnlSum += variate;
vnlSum2 += variate * variate;
}
{
const double mean = vnlSum / numberOfSamples;
const double variance = vnlSum2 / numberOfSamples - mean * mean;
std::cout << "Mean [VNL] = "
<< mean << std::endl;
std::cout << "Variance [VNL] = "
<< variance << std::endl;
const double uniformVariance = 100.0/12.0;
std::cout << "Testing Mean " << std::endl;
if( vcl_abs(mean - 5) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
std::cout << "Testing Variance " << std::endl;
if( vcl_abs(variance - uniformVariance) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
}
std::cout <<
"MersenneTwisterRandomVariateGenerator: Computing "
<< numberOfSamples << " random numbers took " <<
clockMT1.GetMeanTime() << " s" << std::endl;
std::cout <<
"vnl_sample : Computing "
<< numberOfSamples << " random numbers took " <<
clockVnl1.GetMeanTime() << " s" << std::endl;
return pass;
}
<commit_msg>ENH: reduce time of test.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMersenneTwisterRandomVariateGeneratorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "vnl/vnl_sample.h"
#include "vnl/vnl_math.h"
#include "itkTimeProbe.h"
bool ComputeMeanAndVariance( const unsigned long numberOfSamples );
int itkMersenneTwisterRandomVariateGeneratorTest(int, char* [] )
{
#if __CYGWIN__
vnl_sample_reseed(0x1234abcd);
#endif
std::cout << "MersenneTwisterRandomVariateGenerator Test" << std::endl;
bool pass = true;
pass &= ComputeMeanAndVariance( 100000UL );
pass &= ComputeMeanAndVariance( 10000UL );
if( pass )
{
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
bool ComputeMeanAndVariance(const unsigned long numberOfSamples)
{
std::cout << "Test mean and variance of a uniform distribution [0, 10): " << std::endl;
bool pass = true;
const double tolerance = 0.05;
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator GeneratorType;
GeneratorType::Pointer generator = GeneratorType::New();
GeneratorType::IntegerType randomSeed = 14543 ; // any number to initialize the seed.
generator->Initialize( randomSeed );
double MTsum = 0.0f;
double MTsum2 = 0.0f;
std::cout << "Compute Mean and variance with " <<
numberOfSamples << " samples... " << std::endl;
itk::TimeProbe clockMT1;
clockMT1.Start();
for(unsigned int i=0; i < numberOfSamples; i++)
{
generator->GetUniformVariate(0,10);
}
clockMT1.Stop();
for(unsigned int i=0; i < numberOfSamples; i++)
{
double variate = generator->GetUniformVariate(0,10);
MTsum += variate;
MTsum2 += variate * variate;
}
{
const double mean = MTsum / numberOfSamples;
const double variance = MTsum2 / numberOfSamples - mean * mean;
std::cout << "Mean [MersenneTwisterRandomVariateGenerator] = "
<< mean << std::endl;
std::cout << "Variance [MersenneTwisterRandomVariateGenerator] = "
<< variance << std::endl;
const double uniformVariance = 100.0/12.0;
std::cout << "Testing Mean " << std::endl;
if( vcl_abs(mean - 5) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
std::cout << "Testing Variance " << std::endl;
if( vcl_abs(variance - uniformVariance) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
}
double vnlSum = 0.0f;
double vnlSum2 = 0.0f;
std::cout << "USING VNL " << std::endl;
itk::TimeProbe clockVnl1;
clockVnl1.Start();
for(unsigned int i=0; i < numberOfSamples; i++)
{
vnl_sample_uniform(0,10);
}
clockVnl1.Stop();
for(unsigned int i=0; i < numberOfSamples; i++)
{
double variate = vnl_sample_uniform(0,10);
vnlSum += variate;
vnlSum2 += variate * variate;
}
{
const double mean = vnlSum / numberOfSamples;
const double variance = vnlSum2 / numberOfSamples - mean * mean;
std::cout << "Mean [VNL] = "
<< mean << std::endl;
std::cout << "Variance [VNL] = "
<< variance << std::endl;
const double uniformVariance = 100.0/12.0;
std::cout << "Testing Mean " << std::endl;
if( vcl_abs(mean - 5) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
std::cout << "Testing Variance " << std::endl;
if( vcl_abs(variance - uniformVariance) > tolerance )
{
pass = false;
std::cout << "[FAILED]" << std::endl;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
}
std::cout <<
"MersenneTwisterRandomVariateGenerator: Computing "
<< numberOfSamples << " random numbers took " <<
clockMT1.GetMeanTime() << " s" << std::endl;
std::cout <<
"vnl_sample : Computing "
<< numberOfSamples << " random numbers took " <<
clockVnl1.GetMeanTime() << " s" << std::endl;
return pass;
}
<|endoftext|> |
<commit_before>#ifndef LUNATIC_LUA_FUNCTION_HPP_INCLUDED
#define LUNATIC_LUA_FUNCTION_HPP_INCLUDED
#include "lua.hpp"
#include <cassert>
#include <string>
#include <tuple>
#include <utility>
namespace lunatic
{
// Helper templates to push values from C++ to the Lua stack.
// You can define your own specializations for other types.
template<typename T>
void push_argument(lua_State* L, T arg);
template<typename T, typename... Args>
void push_argument(lua_State* L, T first, Args&&... args)
{
push_argument(L, first);
push_argument(L, std::forward<Args>(args)...);
}
template<>
void push_argument<bool>(lua_State* L, bool arg)
{
lua_pushboolean(L, arg ? 1 : 0);
}
template<>
void push_argument<int>(lua_State* L, int arg)
{
lua_pushinteger(L, arg);
}
template<>
void push_argument<float>(lua_State* L, float arg)
{
lua_pushnumber(L, arg);
}
template<>
void push_argument<double>(lua_State* L, double arg)
{
lua_pushnumber(L, arg);
}
template<>
void push_argument<std::string>(lua_State* L, std::string arg)
{
lua_pushstring(L, arg.c_str());
}
// Helper templates to retrieve values from Lua into C++-land.
// You can define your own specializations for other types.
template<typename Ret>
Ret pop_argument(lua_State* L, int index);
template<>
bool pop_argument<bool>(lua_State* L, int index)
{
return lua_toboolean(L, index);
}
template<>
int pop_argument<int>(lua_State* L, int index)
{
return int(lua_tointeger(L, index));
}
template<>
float pop_argument<float>(lua_State* L, int index)
{
return float(lua_tonumber(L, index));
}
template<>
double pop_argument<double>(lua_State* L, int index)
{
return double(lua_tonumber(L, index));
}
template<>
std::string pop_argument<std::string>(lua_State* L, int index)
{
return lua_tostring(L, index);
}
template<typename Ret>
std::tuple<Ret> pop_arguments(lua_State* L, int index)
{
return std::make_tuple(pop_argument<Ret>(L, index));
}
template<typename Ret1, typename Ret2, typename... RetN>
std::tuple<Ret1, Ret2, RetN...> pop_arguments(lua_State* L, int index)
{
const auto head = std::make_tuple(pop_argument<Ret1>(L, index));
return std::tuple_cat(head, pop_arguments<Ret2, RetN...>(L, index + 1));
}
// Convenience base class for lua_function.
namespace detail
{
class lua_function_base
{
public:
lua_function_base(lua_State* L, const std::string& name) :
state(L), name(name) {}
lua_function_base(const lua_function_base&) = delete;
lua_function_base& operator=(const lua_function_base&) = delete;
lua_State* state;
std::string name;
protected:
void get_global_function()
{
lua_getglobal(state, name.c_str());
assert(lua_isfunction(state, -1));
}
};
}
// This class represents a Lua function that is callable from C++.
template<typename... Ret>
class lua_function;
template<typename Ret>
class lua_function<Ret> : public detail::lua_function_base
{
public:
lua_function(lua_State* L, const std::string& name) :
lua_function_base(L, name) {}
Ret operator()()
{
get_global_function();
return call_lua_func(0);
}
template<typename T>
Ret operator()(T arg)
{
get_global_function();
push_argument(state, arg);
return call_lua_func(1);
}
template<typename T, typename... Args>
Ret operator()(T first, Args&&... args)
{
get_global_function();
push_argument(state, first);
push_argument(state, std::forward<Args>(args)...);
return call_lua_func(sizeof...(Args) + 1);
}
private:
Ret call_lua_func(int num_args)
{
const auto call_ret = lua_pcall(state, num_args, 1, 0);
assert(call_ret == 0);
const auto ret = pop_argument<Ret>(state, -1);
lua_pop(state, 1);
return ret;
}
};
// This class template specialization implements support for functions
// that return multiple values.
template<typename Ret1, typename... RetN>
class lua_function<Ret1, RetN...> : public detail::lua_function_base
{
public:
lua_function(lua_State* L, const std::string& name) :
lua_function_base(L, name) {}
std::tuple<Ret1, RetN...> operator()()
{
get_global_function();
return call_lua_func(0);
}
template<typename T>
std::tuple<Ret1, RetN...> operator()(T arg)
{
get_global_function();
push_argument(state, arg);
return call_lua_func(1);
}
template<typename T, typename... Args>
std::tuple<Ret1, RetN...> operator()(T first, Args&&... args)
{
get_global_function();
push_argument(state, first);
push_argument(state, std::forward<Args>(args)...);
return call_lua_func(sizeof...(Args) + 1);
}
private:
std::tuple<Ret1, RetN...> call_lua_func(int num_args)
{
const int num_ret_values = sizeof...(RetN) + 1;
const auto call_ret = lua_pcall(state, num_args, num_ret_values, 0);
assert(call_ret == 0);
const auto ret = pop_arguments<Ret1, RetN...>(state, -num_ret_values);
lua_pop(state, num_ret_values);
return ret;
}
};
// This class template specialization implements support for functions
// that return no value.
template<>
class lua_function<void> : public detail::lua_function_base
{
public:
lua_function(lua_State* L, const std::string& name) :
lua_function_base(L, name) {}
void operator()()
{
get_global_function();
call_lua_func(0);
}
template<typename T>
void operator()(T arg)
{
get_global_function();
push_argument(state, arg);
call_lua_func(1);
}
template<typename T, typename... Args>
void operator()(T first, Args&&... args)
{
get_global_function();
push_argument(state, first);
push_argument(state, std::forward<Args>(args)...);
call_lua_func(sizeof...(Args) + 1);
}
private:
void call_lua_func(int num_args)
{
const auto call_ret = lua_pcall(state, num_args, 0, 0);
assert(call_ret == 0);
}
};
}
#endif
<commit_msg>Minor cosmetic tweak.<commit_after>#ifndef LUNATIC_LUA_FUNCTION_HPP_INCLUDED
#define LUNATIC_LUA_FUNCTION_HPP_INCLUDED
#include "lua.hpp"
#include <cassert>
#include <string>
#include <tuple>
#include <utility>
namespace lunatic
{
// Helper templates to push values from C++ to the Lua stack.
// You can define your own specializations for other types.
template<typename T>
void push_argument(lua_State* L, T arg);
template<typename T, typename... Args>
void push_argument(lua_State* L, T first, Args&&... args)
{
push_argument(L, first);
push_argument(L, std::forward<Args>(args)...);
}
template<>
void push_argument<bool>(lua_State* L, bool arg)
{
lua_pushboolean(L, arg ? 1 : 0);
}
template<>
void push_argument<int>(lua_State* L, int arg)
{
lua_pushinteger(L, arg);
}
template<>
void push_argument<float>(lua_State* L, float arg)
{
lua_pushnumber(L, arg);
}
template<>
void push_argument<double>(lua_State* L, double arg)
{
lua_pushnumber(L, arg);
}
template<>
void push_argument<std::string>(lua_State* L, std::string arg)
{
lua_pushstring(L, arg.c_str());
}
// Helper templates to retrieve values from Lua into C++-land.
// You can define your own specializations for other types.
template<typename Ret>
Ret pop_argument(lua_State* L, int index);
template<>
bool pop_argument<bool>(lua_State* L, int index)
{
return lua_toboolean(L, index);
}
template<>
int pop_argument<int>(lua_State* L, int index)
{
return int(lua_tointeger(L, index));
}
template<>
float pop_argument<float>(lua_State* L, int index)
{
return float(lua_tonumber(L, index));
}
template<>
double pop_argument<double>(lua_State* L, int index)
{
return double(lua_tonumber(L, index));
}
template<>
std::string pop_argument<std::string>(lua_State* L, int index)
{
return lua_tostring(L, index);
}
template<typename Ret>
std::tuple<Ret> pop_arguments(lua_State* L, int index)
{
return std::make_tuple(pop_argument<Ret>(L, index));
}
template<typename Ret1, typename Ret2, typename... RetN>
std::tuple<Ret1, Ret2, RetN...> pop_arguments(lua_State* L, int index)
{
const auto head = std::make_tuple(pop_argument<Ret1>(L, index));
return std::tuple_cat(head, pop_arguments<Ret2, RetN...>(L, index + 1));
}
// Convenience base class for lua_function.
namespace detail
{
class lua_function_base
{
public:
lua_function_base(lua_State* L, const std::string& name) :
state(L), name(name) {}
lua_function_base(const lua_function_base&) = delete;
lua_function_base& operator=(const lua_function_base&) = delete;
lua_State* state;
std::string name;
protected:
void get_global_function()
{
lua_getglobal(state, name.c_str());
assert(lua_isfunction(state, -1));
}
};
}
// This class represents a Lua function that is callable from C++.
template<typename... Ret>
class lua_function;
template<typename Ret>
class lua_function<Ret> : public detail::lua_function_base
{
public:
lua_function(lua_State* L, const std::string& name) :
lua_function_base(L, name) {}
Ret operator()()
{
get_global_function();
return call_lua_func(0);
}
template<typename T>
Ret operator()(T arg)
{
get_global_function();
push_argument(state, arg);
return call_lua_func(1);
}
template<typename T, typename... Args>
Ret operator()(T first, Args&&... args)
{
get_global_function();
push_argument(state, first);
push_argument(state, std::forward<Args>(args)...);
return call_lua_func(sizeof...(Args) + 1);
}
private:
Ret call_lua_func(int num_args)
{
const auto call_ret = lua_pcall(state, num_args, 1, 0);
assert(call_ret == 0);
const auto ret = pop_argument<Ret>(state, -1);
lua_pop(state, 1);
return ret;
}
};
// This class template specialization implements support for functions
// that return multiple values.
template<typename Ret1, typename... RetN>
class lua_function<Ret1, RetN...> : public detail::lua_function_base
{
public:
lua_function(lua_State* L, const std::string& name) :
lua_function_base(L, name) {}
std::tuple<Ret1, RetN...> operator()()
{
get_global_function();
return call_lua_func(0);
}
template<typename T>
std::tuple<Ret1, RetN...> operator()(T arg)
{
get_global_function();
push_argument(state, arg);
return call_lua_func(1);
}
template<typename T, typename... Args>
std::tuple<Ret1, RetN...> operator()(T first, Args&&... args)
{
get_global_function();
push_argument(state, first);
push_argument(state, std::forward<Args>(args)...);
return call_lua_func(sizeof...(Args) + 1);
}
private:
std::tuple<Ret1, RetN...> call_lua_func(int num_args)
{
const int num_ret_values = sizeof...(RetN) + 1;
const auto call_ret = lua_pcall(state, num_args, num_ret_values, 0);
assert(call_ret == 0);
const auto ret = pop_arguments<Ret1, RetN...>(state, -num_ret_values);
lua_pop(state, num_ret_values);
return ret;
}
};
// This class template specialization implements support for functions
// that return no value.
template<>
class lua_function<void> : public detail::lua_function_base
{
public:
lua_function(lua_State* L, const std::string& name) :
lua_function_base(L, name) {}
void operator()()
{
get_global_function();
call_lua_func(0);
}
template<typename T>
void operator()(T arg)
{
get_global_function();
push_argument(state, arg);
call_lua_func(1);
}
template<typename T, typename... Args>
void operator()(T first, Args&&... args)
{
get_global_function();
push_argument(state, first);
push_argument(state, std::forward<Args>(args)...);
call_lua_func(sizeof...(Args) + 1);
}
private:
void call_lua_func(int num_args)
{
const auto call_ret = lua_pcall(state, num_args, 0, 0);
assert(call_ret == 0);
}
};
}
#endif
<|endoftext|> |
<commit_before>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
#include "../src/settings/Settings.h" //Settings to generate walls with.
#include "../src/utils/polygon.h" //To create example polygons.
#include "../src/sliceDataStorage.h" //Sl
#include "../src/WallsComputation.h" //Unit under test.
namespace cura
{
/*!
* Fixture that provides a basis for testing wall computation.
*/
class WallsComputationTest : public testing::Test
{
public:
/*!
* Settings to slice with. This is linked in the walls_computation fixture.
*/
Settings settings;
/*!
* WallsComputation instance to test with. The layer index will be 100.
*/
WallsComputation walls_computation;
/*!
* Basic 10x10mm square shape to work with.
*/
Polygons square_shape;
WallsComputationTest()
: walls_computation(settings, LayerIndex(100))
{
square_shape.emplace_back();
square_shape.back().emplace_back(0, 0);
square_shape.back().emplace_back(MM2INT(10), 0);
square_shape.back().emplace_back(MM2INT(10), MM2INT(10));
square_shape.back().emplace_back(0, MM2INT(10));
//Settings for a simple 2 walls, about as basic as possible.
settings.add("alternate_extra_perimeter", "false");
settings.add("beading_strategy_type", "inward_distributed");
settings.add("fill_outline_gaps", "false");
settings.add("initial_layer_line_width_factor", "100");
settings.add("magic_spiralize", "false");
settings.add("meshfix_maximum_deviation", "0.1");
settings.add("meshfix_maximum_extrusion_area_deviation", "0.01");
settings.add("meshfix_maximum_resolution", "0.01");
settings.add("min_bead_width", "0");
settings.add("min_feature_size", "0");
settings.add("wall_0_extruder_nr", "0");
settings.add("wall_0_inset", "0");
settings.add("wall_line_count", "2");
settings.add("wall_line_width_0", "0.4");
settings.add("wall_line_width_x", "0.4");
settings.add("wall_transition_angle", "30");
settings.add("wall_transition_filter_distance", "1");
settings.add("wall_transition_length", "1");
settings.add("wall_transition_threshold", "50");
settings.add("wall_x_extruder_nr", "0");
}
};
/*!
* Tests if something is generated in the basic happy case.
*/
TEST_F(WallsComputationTest, GenerateWallsForLayerSinglePart)
{
SliceLayer layer;
layer.parts.emplace_back();
SliceLayerPart& part = layer.parts.back();
part.outline.add(square_shape);
//Run the test.
walls_computation.generateWalls(&layer);
//Verify that something was generated.
EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls.";
EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0.";
EXPECT_LE(part.print_outline.area(), square_shape.area()) << "The print outline must stay within the bounds of the original part.";
EXPECT_GT(part.inner_area.area(), 0) << "The inner area must be within the innermost wall. There are not enough walls to fill the entire part, so there is a positive inner area.";
EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}
/*!
* Tests if the inner area is properly set.
*/
TEST_F(WallsComputationTest, GenerateWallsZeroWalls)
{
settings.add("wall_line_count", "0");
SliceLayer layer;
layer.parts.emplace_back();
SliceLayerPart& part = layer.parts.back();
part.outline.add(square_shape);
//Run the test.
walls_computation.generateWalls(&layer);
//Verify that there is still an inner area, outline and parts.
EXPECT_EQ(part.inner_area.area(), square_shape.area()) << "There are no walls, so the inner area (for infill/skin) needs to be the entire part.";
EXPECT_EQ(part.print_outline.area(), square_shape.area()) << "There are no walls, so the print outline encompasses the inner area exactly.";
EXPECT_EQ(part.outline.area(), square_shape.area()) << "The outline is not modified.";
EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}
}<commit_msg>Add new setting to tests as well.<commit_after>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
#include "../src/settings/Settings.h" //Settings to generate walls with.
#include "../src/utils/polygon.h" //To create example polygons.
#include "../src/sliceDataStorage.h" //Sl
#include "../src/WallsComputation.h" //Unit under test.
namespace cura
{
/*!
* Fixture that provides a basis for testing wall computation.
*/
class WallsComputationTest : public testing::Test
{
public:
/*!
* Settings to slice with. This is linked in the walls_computation fixture.
*/
Settings settings;
/*!
* WallsComputation instance to test with. The layer index will be 100.
*/
WallsComputation walls_computation;
/*!
* Basic 10x10mm square shape to work with.
*/
Polygons square_shape;
WallsComputationTest()
: walls_computation(settings, LayerIndex(100))
{
square_shape.emplace_back();
square_shape.back().emplace_back(0, 0);
square_shape.back().emplace_back(MM2INT(10), 0);
square_shape.back().emplace_back(MM2INT(10), MM2INT(10));
square_shape.back().emplace_back(0, MM2INT(10));
//Settings for a simple 2 walls, about as basic as possible.
settings.add("alternate_extra_perimeter", "false");
settings.add("beading_strategy_type", "inward_distributed");
settings.add("fill_outline_gaps", "false");
settings.add("initial_layer_line_width_factor", "100");
settings.add("magic_spiralize", "false");
settings.add("meshfix_maximum_deviation", "0.1");
settings.add("meshfix_maximum_extrusion_area_deviation", "0.01");
settings.add("meshfix_maximum_resolution", "0.01");
settings.add("min_bead_width", "0");
settings.add("min_feature_size", "0");
settings.add("wall_0_extruder_nr", "0");
settings.add("wall_0_inset", "0");
settings.add("wall_line_count", "2");
settings.add("wall_line_width_0", "0.4");
settings.add("wall_line_width_x", "0.4");
settings.add("wall_transition_angle", "30");
settings.add("wall_transition_filter_distance", "1");
settings.add("wall_transition_length", "1");
settings.add("wall_transition_threshold", "50");
settings.add("wall_x_extruder_nr", "0");
settings.add("wall_0_lock_factor", "0.5");
}
};
/*!
* Tests if something is generated in the basic happy case.
*/
TEST_F(WallsComputationTest, GenerateWallsForLayerSinglePart)
{
SliceLayer layer;
layer.parts.emplace_back();
SliceLayerPart& part = layer.parts.back();
part.outline.add(square_shape);
//Run the test.
walls_computation.generateWalls(&layer);
//Verify that something was generated.
EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls.";
EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0.";
EXPECT_LE(part.print_outline.area(), square_shape.area()) << "The print outline must stay within the bounds of the original part.";
EXPECT_GT(part.inner_area.area(), 0) << "The inner area must be within the innermost wall. There are not enough walls to fill the entire part, so there is a positive inner area.";
EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}
/*!
* Tests if the inner area is properly set.
*/
TEST_F(WallsComputationTest, GenerateWallsZeroWalls)
{
settings.add("wall_line_count", "0");
SliceLayer layer;
layer.parts.emplace_back();
SliceLayerPart& part = layer.parts.back();
part.outline.add(square_shape);
//Run the test.
walls_computation.generateWalls(&layer);
//Verify that there is still an inner area, outline and parts.
EXPECT_EQ(part.inner_area.area(), square_shape.area()) << "There are no walls, so the inner area (for infill/skin) needs to be the entire part.";
EXPECT_EQ(part.print_outline.area(), square_shape.area()) << "There are no walls, so the print outline encompasses the inner area exactly.";
EXPECT_EQ(part.outline.area(), square_shape.area()) << "The outline is not modified.";
EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}
}<|endoftext|> |
<commit_before>#pragma once
#include "user_mark.hpp"
#include "user_mark_container.hpp"
#include "../coding/reader.hpp"
#include "../geometry/point2d.hpp"
#include "../geometry/rect2d.hpp"
#include "../base/timer.hpp"
#include "../std/string.hpp"
#include "../std/noncopyable.hpp"
#include "../std/iostream.hpp"
#include "../std/shared_ptr.hpp"
namespace anim
{
class Task;
}
class Track;
class BookmarkData
{
public:
BookmarkData()
: m_scale(-1.0)
, m_timeStamp(my::INVALID_TIME_STAMP)
{
}
BookmarkData(string const & name, string const & type,
string const & description = "", double scale = -1.0,
time_t timeStamp = my::INVALID_TIME_STAMP)
: m_name(name)
, m_description(description)
, m_type(type)
, m_scale(scale)
, m_timeStamp(timeStamp)
{
}
string const & GetName() const { return m_name; }
void SetName(const string & name) { m_name = name; }
string const & GetDescription() const { return m_description; }
void SetDescription(const string & description) { m_description = description; }
string const & GetType() const { return m_type; }
void SetType(const string & type) { m_type = type; }
double const & GetScale() const { return m_scale; }
void SetScale(double scale) { m_scale = scale; }
time_t const & GetTimeStamp() const { return m_timeStamp; }
void SetTimeStamp(const time_t & timeStamp) { m_timeStamp = timeStamp; }
private:
string m_name;
string m_description;
string m_type; ///< Now it stores bookmark color (category style).
double m_scale; ///< Viewport scale. -1.0 - is a default value (no scale set).
time_t m_timeStamp;
};
class Bookmark : public ICustomDrawable
{
BookmarkData m_data;
double m_animScaleFactor;
public:
Bookmark(m2::PointD const & ptOrg, UserMarkContainer * container)
: ICustomDrawable(ptOrg, container)
, m_animScaleFactor(1.0)
{
}
Bookmark(BookmarkData const & data,
m2::PointD const & ptOrg,
UserMarkContainer * container)
: ICustomDrawable(ptOrg, container)
, m_data(data)
, m_animScaleFactor(1.0)
{
}
void SetData(BookmarkData const & data) { m_data = data; }
BookmarkData const & GetData() { return m_data; }
virtual Type GetMarkType() const { return BOOKMARK; }
string const & GetName() const { return m_data.GetName(); }
void SetName(string const & name) { m_data.SetName(name); }
/// @return Now its a bookmark color - name of icon file
string const & GetType() const { return m_data.GetType(); }
//void SetType(string const & type) { m_type = type; }
m2::RectD GetViewport() const { return m2::RectD(GetOrg(), GetOrg()); }
string const & GetDescription() const { return m_data.GetDescription(); }
void SetDescription(string const & description) { m_data.SetDescription(description); }
/// @return my::INVALID_TIME_STAMP if bookmark has no timestamp
time_t GetTimeStamp() const { return m_data.GetTimeStamp(); }
void SetTimeStamp(time_t timeStamp) { m_data.SetTimeStamp(timeStamp); }
double GetScale() const { return m_data.GetScale(); }
void SetScale(double scale) { m_data.SetScale(scale); }
virtual graphics::DisplayList * GetDisplayList(UserMarkDLCache * cache) const;
virtual double GetAnimScaleFactor() const;
virtual m2::PointD const & GetPixelOffset() const;
shared_ptr<anim::Task> CreateAnimTask(Framework & fm);
};
class BookmarkCategory : public UserMarkContainer
{
typedef UserMarkContainer base_t;
/// @name Data
//@{
/// TODO move track into UserMarkContainer as a IDrawable custom data
vector<Track *> m_tracks;
//@}
string m_name;
/// Stores file name from which category was loaded
string m_file;
public:
BookmarkCategory(string const & name, Framework & framework);
~BookmarkCategory();
virtual Type GetType() const { return BOOKMARK_MARK; }
void ClearBookmarks();
void ClearTracks();
static string GetDefaultType();
/// @name Theese functions are called from Framework only.
//@{
void AddBookmark(m2::PointD const & ptOrg, BookmarkData const & bm);
void ReplaceBookmark(size_t index, BookmarkData const & bm);
//@}
/// @name Tracks routine.
//@{
/// @note Move semantics is used here.
void AddTrack(Track & track);
Track const * GetTrack(size_t index) const;
inline size_t GetTracksCount() const { return m_tracks.size(); }
void DeleteTrack(size_t index);
//@}
void SetName(string const & name) { m_name = name; }
string const & GetName() const { return m_name; }
string const & GetFileName() const { return m_file; }
size_t GetBookmarksCount() const;
Bookmark const * GetBookmark(size_t index) const;
Bookmark * GetBookmark(size_t index);
void DeleteBookmark(size_t index);
/// @name Theese fuctions are public for unit tests only.
/// You don't need to call them from client code.
//@{
bool LoadFromKML(ReaderPtr<Reader> const & reader);
void SaveToKML(ostream & s);
/// Uses the same file name from which was loaded, or
/// creates unique file name on first save and uses it every time.
bool SaveToKMLFile();
/// @return 0 in the case of error
static BookmarkCategory * CreateFromKMLFile(string const & file, Framework & framework);
/// Get valid file name from input (remove illegal symbols).
static string RemoveInvalidSymbols(string const & name);
/// Get unique bookmark file name from path and valid file name.
static string GenerateUniqueFileName(const string & path, string name);
//@}
protected:
virtual string GetTypeName() const { return "search-result"; }
virtual string GetActiveTypeName() const { return "search-result-active"; }
virtual UserMark * AllocateUserMark(m2::PointD const & ptOrg);
private:
bool m_blockAnimation;
};
/// <category index, bookmark index>
typedef pair<int, int> BookmarkAndCategory;
inline BookmarkAndCategory MakeEmptyBookmarkAndCategory()
{
return BookmarkAndCategory(int(-1), int(-1));
}
inline bool IsValid(BookmarkAndCategory const & bmc)
{
return (bmc.first >= 0 && bmc.second >= 0);
}
<commit_msg>Fixed missing const<commit_after>#pragma once
#include "user_mark.hpp"
#include "user_mark_container.hpp"
#include "../coding/reader.hpp"
#include "../geometry/point2d.hpp"
#include "../geometry/rect2d.hpp"
#include "../base/timer.hpp"
#include "../std/string.hpp"
#include "../std/noncopyable.hpp"
#include "../std/iostream.hpp"
#include "../std/shared_ptr.hpp"
namespace anim
{
class Task;
}
class Track;
class BookmarkData
{
public:
BookmarkData()
: m_scale(-1.0)
, m_timeStamp(my::INVALID_TIME_STAMP)
{
}
BookmarkData(string const & name, string const & type,
string const & description = "", double scale = -1.0,
time_t timeStamp = my::INVALID_TIME_STAMP)
: m_name(name)
, m_description(description)
, m_type(type)
, m_scale(scale)
, m_timeStamp(timeStamp)
{
}
string const & GetName() const { return m_name; }
void SetName(const string & name) { m_name = name; }
string const & GetDescription() const { return m_description; }
void SetDescription(const string & description) { m_description = description; }
string const & GetType() const { return m_type; }
void SetType(const string & type) { m_type = type; }
double const & GetScale() const { return m_scale; }
void SetScale(double scale) { m_scale = scale; }
time_t const & GetTimeStamp() const { return m_timeStamp; }
void SetTimeStamp(const time_t & timeStamp) { m_timeStamp = timeStamp; }
private:
string m_name;
string m_description;
string m_type; ///< Now it stores bookmark color (category style).
double m_scale; ///< Viewport scale. -1.0 - is a default value (no scale set).
time_t m_timeStamp;
};
class Bookmark : public ICustomDrawable
{
BookmarkData m_data;
double m_animScaleFactor;
public:
Bookmark(m2::PointD const & ptOrg, UserMarkContainer * container)
: ICustomDrawable(ptOrg, container)
, m_animScaleFactor(1.0)
{
}
Bookmark(BookmarkData const & data,
m2::PointD const & ptOrg,
UserMarkContainer * container)
: ICustomDrawable(ptOrg, container)
, m_data(data)
, m_animScaleFactor(1.0)
{
}
void SetData(BookmarkData const & data) { m_data = data; }
BookmarkData const & GetData() const { return m_data; }
virtual Type GetMarkType() const { return BOOKMARK; }
string const & GetName() const { return m_data.GetName(); }
void SetName(string const & name) { m_data.SetName(name); }
/// @return Now its a bookmark color - name of icon file
string const & GetType() const { return m_data.GetType(); }
//void SetType(string const & type) { m_type = type; }
m2::RectD GetViewport() const { return m2::RectD(GetOrg(), GetOrg()); }
string const & GetDescription() const { return m_data.GetDescription(); }
void SetDescription(string const & description) { m_data.SetDescription(description); }
/// @return my::INVALID_TIME_STAMP if bookmark has no timestamp
time_t GetTimeStamp() const { return m_data.GetTimeStamp(); }
void SetTimeStamp(time_t timeStamp) { m_data.SetTimeStamp(timeStamp); }
double GetScale() const { return m_data.GetScale(); }
void SetScale(double scale) { m_data.SetScale(scale); }
virtual graphics::DisplayList * GetDisplayList(UserMarkDLCache * cache) const;
virtual double GetAnimScaleFactor() const;
virtual m2::PointD const & GetPixelOffset() const;
shared_ptr<anim::Task> CreateAnimTask(Framework & fm);
};
class BookmarkCategory : public UserMarkContainer
{
typedef UserMarkContainer base_t;
/// @name Data
//@{
/// TODO move track into UserMarkContainer as a IDrawable custom data
vector<Track *> m_tracks;
//@}
string m_name;
/// Stores file name from which category was loaded
string m_file;
public:
BookmarkCategory(string const & name, Framework & framework);
~BookmarkCategory();
virtual Type GetType() const { return BOOKMARK_MARK; }
void ClearBookmarks();
void ClearTracks();
static string GetDefaultType();
/// @name Theese functions are called from Framework only.
//@{
void AddBookmark(m2::PointD const & ptOrg, BookmarkData const & bm);
void ReplaceBookmark(size_t index, BookmarkData const & bm);
//@}
/// @name Tracks routine.
//@{
/// @note Move semantics is used here.
void AddTrack(Track & track);
Track const * GetTrack(size_t index) const;
inline size_t GetTracksCount() const { return m_tracks.size(); }
void DeleteTrack(size_t index);
//@}
void SetName(string const & name) { m_name = name; }
string const & GetName() const { return m_name; }
string const & GetFileName() const { return m_file; }
size_t GetBookmarksCount() const;
Bookmark const * GetBookmark(size_t index) const;
Bookmark * GetBookmark(size_t index);
void DeleteBookmark(size_t index);
/// @name Theese fuctions are public for unit tests only.
/// You don't need to call them from client code.
//@{
bool LoadFromKML(ReaderPtr<Reader> const & reader);
void SaveToKML(ostream & s);
/// Uses the same file name from which was loaded, or
/// creates unique file name on first save and uses it every time.
bool SaveToKMLFile();
/// @return 0 in the case of error
static BookmarkCategory * CreateFromKMLFile(string const & file, Framework & framework);
/// Get valid file name from input (remove illegal symbols).
static string RemoveInvalidSymbols(string const & name);
/// Get unique bookmark file name from path and valid file name.
static string GenerateUniqueFileName(const string & path, string name);
//@}
protected:
virtual string GetTypeName() const { return "search-result"; }
virtual string GetActiveTypeName() const { return "search-result-active"; }
virtual UserMark * AllocateUserMark(m2::PointD const & ptOrg);
private:
bool m_blockAnimation;
};
/// <category index, bookmark index>
typedef pair<int, int> BookmarkAndCategory;
inline BookmarkAndCategory MakeEmptyBookmarkAndCategory()
{
return BookmarkAndCategory(int(-1), int(-1));
}
inline bool IsValid(BookmarkAndCategory const & bmc)
{
return (bmc.first >= 0 && bmc.second >= 0);
}
<|endoftext|> |
<commit_before>#include <cassert>
#include "structures/union_find.h"
using namespace theorysolver;
UnionFind::UnionFind() : nodes(), merges(), pending() {
}
UnionFind::UnionFind(unsigned int size_hint) : UnionFind() {
this->expand(size_hint);
}
UnionFind::~UnionFind() {
for (unsigned i=0; i<this->nodes.size(); i++)
delete this->nodes.at(i);
}
void UnionFind::expand(unsigned int size) {
if (size < this->nodes.size())
return;
nodes.reserve(size);
for (unsigned i=static_cast<unsigned>(this->nodes.size()); i<size; i++)
this->nodes.push_back(new uf_node(i, NULL, 0));
}
void UnionFind::merge(unsigned int tag, unsigned int i, unsigned j) {
struct uf_node *node;
if (j < i)
return this->merge(tag, j, i);
if (this->find(i) == this->find(j)) {
this->pending.push_front(std::make_pair(tag, std::make_pair(i, j)));
this->merges.push(node_or_pending_item(this->pending.begin()));
return;
}
this->expand(j+1);
node = this->nodes[j];
while (node->parent)
node = node->parent;
node->parent = this->nodes[i];
node->edge_tag = tag;
this->nodes[i]->nb_childs++;
this->merges.push(node_or_pending_item(node));
}
unsigned int UnionFind::find(unsigned int i) const {
uf_node *node;
if (i>=this->nodes.size())
return i;
node = this->nodes[i];
while (node->parent)
node = node->parent;
//this->compress(this->nodes[i], node);
return node->v;
}
std::unordered_set<int> UnionFind::get_path(unsigned int i) {
std::unordered_set<int> path;
uf_node *node;
assert(i<this->nodes.size());
node = this->nodes[i];
assert(node);
while (node->parent) {
path.insert(node->edge_tag);
node = node->parent;
}
return path;
}
void UnionFind::unmerge() {
std::list<std::pair<unsigned int, std::pair<unsigned int, unsigned int>>>::iterator it, it2;
uf_node *node;
assert(this->merges.size());
node = this->merges.top().node;
if (node) {
this->merges.pop();
node->parent = NULL;
it=this->pending.begin();
while (it!=this->pending.end()) {
it2 = ++it;
it--;
if (this->find(it->second.first) != this->find(it->second.second)) {
this->merge(it->first, it->second.first, it->second.second);
this->pending.erase(it);
break;
}
it = it2;
}
}
else {
this->pending.erase(this->merges.top().pending_item);
this->merges.pop();
}
}
unsigned UnionFind::get_max_node() const {
return static_cast<unsigned>(this->nodes.size());
}
<commit_msg>Add comments to union_find.cpp<commit_after>#include <cassert>
#include "structures/union_find.h"
using namespace theorysolver;
UnionFind::UnionFind() : nodes(), merges(), pending() {
}
UnionFind::UnionFind(unsigned int size_hint) : UnionFind() {
this->expand(size_hint);
}
UnionFind::~UnionFind() {
for (unsigned i=0; i<this->nodes.size(); i++)
delete this->nodes.at(i);
}
void UnionFind::expand(unsigned int size) {
if (size < this->nodes.size())
return;
nodes.reserve(size);
for (unsigned i=static_cast<unsigned>(this->nodes.size()); i<size; i++)
this->nodes.push_back(new uf_node(i, NULL, 0));
}
void UnionFind::merge(unsigned int tag, unsigned int i, unsigned j) {
struct uf_node *node;
if (j < i) // Make sure there is no cycle.
return this->merge(tag, j, i);
if (this->find(i) == this->find(j)) { // The two nodes are already in the same component
this->pending.push_front(std::make_pair(tag, std::make_pair(i, j)));
this->merges.push(node_or_pending_item(this->pending.begin()));
return;
}
this->expand(j+1);
node = this->nodes[j];
while (node->parent)
node = node->parent;
node->parent = this->nodes[i];
node->edge_tag = tag;
this->nodes[i]->nb_childs++;
this->merges.push(node_or_pending_item(node));
}
unsigned int UnionFind::find(unsigned int i) const {
uf_node *node;
if (i>=this->nodes.size())
return i;
node = this->nodes[i];
while (node->parent)
node = node->parent;
return node->v;
}
std::unordered_set<int> UnionFind::get_path(unsigned int i) {
std::unordered_set<int> path;
uf_node *node;
assert(i<this->nodes.size());
node = this->nodes[i];
assert(node);
while (node->parent) {
path.insert(node->edge_tag);
node = node->parent;
}
return path;
}
void UnionFind::unmerge() {
std::list<std::pair<unsigned int, std::pair<unsigned int, unsigned int>>>::iterator it, it2;
uf_node *node;
assert(this->merges.size());
node = this->merges.top().node;
if (node) { // The last merge is between different components
this->merges.pop();
node->parent = NULL;
// Apply a pending merge, if any.
it=this->pending.begin();
while (it!=this->pending.end()) {
it2 = ++it;
it--;
if (this->find(it->second.first) != this->find(it->second.second)) {
this->merge(it->first, it->second.first, it->second.second);
this->pending.erase(it);
break;
}
it = it2;
}
}
else { // The last merge is between nodes of the same component
this->pending.erase(this->merges.top().pending_item);
this->merges.pop();
}
}
unsigned UnionFind::get_max_node() const {
return static_cast<unsigned>(this->nodes.size());
}
<|endoftext|> |
<commit_before><commit_msg>ocTableRef is not in RPN<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gameitemsmodel.h"
#include "core/gluon_global.h"
#include "engine/gameproject.h"
#include <QtCore/QHash>
#include <QtCore/QByteArray>
using namespace GluonPlayer;
GameViewItem::GameViewItem(const QString &gameName, const QString &gameDescription,
const QString &projectFileName, const QString &id)
: m_gameName(gameName)
, m_gameDescription(gameDescription)
, m_projectFileName(projectFileName)
, m_id(id)
{
}
QString GameViewItem::gameName() const
{
return m_gameName;
}
QString GameViewItem::gameDescription() const
{
return m_gameDescription;
}
QString GameViewItem::projectFileName() const
{
return m_projectFileName;
}
QString GameViewItem::id() const
{
return m_id;
}
GameItemsModel::GameItemsModel( QObject* parent )
: QAbstractListModel( parent )
{
QDir m_dir;
m_dir.cd( GluonCore::Global::dataDirectory() + "/gluon/games" );
QStringList gameDirNameList;
gameDirNameList = m_dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot );
foreach( const QString& gameDirName, gameDirNameList)
{
QDir gameDir = m_dir;
gameDir.cd( gameDirName );
QStringList gluonProjectFiles = gameDir.entryList( QStringList( QString( "*%1" ).arg( GluonEngine::projectSuffix ) ) );
QString projectFileName = gameDir.absoluteFilePath( gluonProjectFiles.at( 0 ) );
if( !gluonProjectFiles.isEmpty() )
{
GluonEngine::GameProject project;
project.loadFromFile( projectFileName );
GameViewItem gameViewItem(project.name(), project.description(),
projectFileName, project.property("id").toString());
m_gameViewItems.append(gameViewItem);
}
}
QHash<int, QByteArray> roles;
roles[GameNameRole] = "gameName";
roles[GameDescriptionRole] = "gameDescription";
roles[ProjectFileNameRole] = "projectFileName";
roles[IDRole] = "id";
setRoleNames(roles);
}
QVariant GameItemsModel::data( const QModelIndex& index, int role ) const
{
if (index.row() < 0 || index.row() > m_gameViewItems.count())
return QVariant();
switch (role) {
case Qt::UserRole:
break;
case GameNameRole:
return m_gameViewItems.at( index.row() ).gameName();
case GameDescriptionRole:
return m_gameViewItems.at( index.row() ).gameDescription();
case Qt::DisplayRole:
case ProjectFileNameRole:
return m_gameViewItems.at( index.row() ).projectFileName();
case IDRole:
return m_gameViewItems.at( index.row() ).id();
default:
break;
}
return QVariant();
}
int GameItemsModel::rowCount( const QModelIndex& /* parent */ ) const
{
return m_gameViewItems.count();
}
int GameItemsModel::columnCount( const QModelIndex& /* parent */ ) const
{
return 1;
}
QVariant GameItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if( section == 0 )
{
return QString( "Game" );
}
return QAbstractItemModel::headerData( section, orientation, role );
}
#include "gameitemsmodel.moc"
<commit_msg>Make game items model handle the game bundle stuffs<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Laszlo Papp <djszapi@archlinux.us>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gameitemsmodel.h"
#include "core/gluon_global.h"
#include "engine/gameproject.h"
#include <QtCore/QHash>
#include <QtCore/QByteArray>
using namespace GluonPlayer;
GameViewItem::GameViewItem(const QString &gameName, const QString &gameDescription,
const QString &projectFileName, const QString &id)
: m_gameName(gameName)
, m_gameDescription(gameDescription)
, m_projectFileName(projectFileName)
, m_id(id)
{
}
QString GameViewItem::gameName() const
{
return m_gameName;
}
QString GameViewItem::gameDescription() const
{
return m_gameDescription;
}
QString GameViewItem::projectFileName() const
{
return m_projectFileName;
}
QString GameViewItem::id() const
{
return m_id;
}
GameItemsModel::GameItemsModel( QObject* parent )
: QAbstractListModel( parent )
{
QDir m_dir;
m_dir.cd( GluonCore::Global::dataDirectory() + "/gluon/games" );
QStringList gameDirNameList;
gameDirNameList = m_dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot );
foreach( const QString& gameDirName, gameDirNameList)
{
QDir gameDir = m_dir;
gameDir.cd( gameDirName );
QStringList gluonProjectFiles = gameDir.entryList( QStringList( GluonEngine::projectFilename ) );
if( !gluonProjectFiles.isEmpty() )
{
QString projectFileName = gameDir.absoluteFilePath( gluonProjectFiles.at( 0 ) );
GluonEngine::GameProject project;
project.loadFromFile( projectFileName );
GameViewItem gameViewItem(project.name(), project.description(),
projectFileName, project.property("id").toString());
m_gameViewItems.append(gameViewItem);
}
}
QHash<int, QByteArray> roles;
roles[GameNameRole] = "gameName";
roles[GameDescriptionRole] = "gameDescription";
roles[ProjectFileNameRole] = "projectFileName";
roles[IDRole] = "id";
setRoleNames(roles);
}
QVariant GameItemsModel::data( const QModelIndex& index, int role ) const
{
if (index.row() < 0 || index.row() > m_gameViewItems.count())
return QVariant();
switch (role) {
case Qt::UserRole:
break;
case GameNameRole:
return m_gameViewItems.at( index.row() ).gameName();
case GameDescriptionRole:
return m_gameViewItems.at( index.row() ).gameDescription();
case Qt::DisplayRole:
case ProjectFileNameRole:
return m_gameViewItems.at( index.row() ).projectFileName();
case IDRole:
return m_gameViewItems.at( index.row() ).id();
default:
break;
}
return QVariant();
}
int GameItemsModel::rowCount( const QModelIndex& /* parent */ ) const
{
return m_gameViewItems.count();
}
int GameItemsModel::columnCount( const QModelIndex& /* parent */ ) const
{
return 1;
}
QVariant GameItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if( section == 0 )
{
return QString( "Game" );
}
return QAbstractItemModel::headerData( section, orientation, role );
}
#include "gameitemsmodel.moc"
<|endoftext|> |
<commit_before>// score_main.cpp: defines a GAM to GAM annotation function
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <vector>
#include <set>
#include <subcommand.hpp>
#include "../alignment.hpp"
#include "../vg.hpp"
#include <vg/io/stream.hpp>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_score(char** argv) {
cerr << "usage: " << argv[0] << " score aln.gam " << endl;
}
int main_score(int argc, char** argv) {
if (argc == 2) {
help_score(argv);
exit(1);
}
int threads = 1;
int c;
optind = 2;
while (true) {
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "h",
long_options, &option_index);
// Detect the end of the options.
if (c == -1) break;
switch (c)
{
case 'h':
case '?':
help_score(argv);
exit(1);
break;
default:
abort ();
}
}
// We need to read the second argument first, so we can't use get_input_file with its free error checking.
string read_file_name = get_input_file_name(optind, argc, argv);
vector<size_t> mapq_counts ( 61, 0);
vector<size_t> correct_counts (61, 0);;
size_t total_read_count = 0;
function<void(Alignment&)> count_mapqs = [&](Alignment& aln) {
auto mapq = aln.mapping_quality();
if (mapq) {
total_read_count ++;
mapq_counts[mapq] ++;
if (aln.correctly_mapped()) {
correct_counts[mapq]++;
}
}
};
ifstream truth_file_in(read_file_name);
if (!truth_file_in) {
cerr << "error[vg score]: Unable to read " << read_file_name << " when looking for true reads" << endl;
exit(1);
}
//Get the mapqs
vg::io::for_each_parallel(truth_file_in, count_mapqs);
size_t accumulated_count = 0;
size_t accumulated_correct_count= 0;
float mapping_goodness_score = 0.0;
for (int i = 60 ; i >= 0 ; i-- ) {
accumulated_count += mapq_counts[i];
accumulated_correct_count += correct_counts[i];
double fraction_incorrect = accumulated_count == 0 ? 0.0 :
(float) (accumulated_count - accumulated_correct_count) / (float) accumulated_count;
fraction_incorrect = fraction_incorrect == 0.0 ? 1.0/(float)total_read_count : fraction_incorrect;
mapping_goodness_score -= log10(fraction_incorrect) * mapq_counts[i];
}
cerr << mapping_goodness_score / total_read_count << endl;
return 0;
}
// Register subcommand
static Subcommand vg_score("score", "score compared alignment", main_score);
<commit_msg>Stopped being parallel<commit_after>// score_main.cpp: defines a GAM to GAM annotation function
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <vector>
#include <set>
#include <subcommand.hpp>
#include "../alignment.hpp"
#include "../vg.hpp"
#include <vg/io/stream.hpp>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_score(char** argv) {
cerr << "usage: " << argv[0] << " score aln.gam " << endl;
}
int main_score(int argc, char** argv) {
if (argc == 2) {
help_score(argv);
exit(1);
}
int threads = 1;
int c;
optind = 2;
while (true) {
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "h",
long_options, &option_index);
// Detect the end of the options.
if (c == -1) break;
switch (c)
{
case 'h':
case '?':
help_score(argv);
exit(1);
break;
default:
abort ();
}
}
// We need to read the second argument first, so we can't use get_input_file with its free error checking.
string read_file_name = get_input_file_name(optind, argc, argv);
vector<size_t> mapq_counts ( 61, 0);
vector<size_t> correct_counts (61, 0);;
size_t total_read_count = 0;
function<void(Alignment&)> count_mapqs = [&](Alignment& aln) {
auto mapq = aln.mapping_quality();
if (mapq) {
total_read_count ++;
mapq_counts[mapq] ++;
if (aln.correctly_mapped()) {
correct_counts[mapq]++;
}
}
};
ifstream truth_file_in(read_file_name);
if (!truth_file_in) {
cerr << "error[vg score]: Unable to read " << read_file_name << " when looking for true reads" << endl;
exit(1);
}
//Get the mapqs
vg::io::for_each(truth_file_in, count_mapqs);
size_t accumulated_count = 0;
size_t accumulated_correct_count= 0;
float mapping_goodness_score = 0.0;
for (int i = 60 ; i >= 0 ; i-- ) {
accumulated_count += mapq_counts[i];
accumulated_correct_count += correct_counts[i];
double fraction_incorrect = accumulated_count == 0 ? 0.0 :
(float) (accumulated_count - accumulated_correct_count) / (float) accumulated_count;
fraction_incorrect = fraction_incorrect == 0.0 ? 1.0/(float)total_read_count : fraction_incorrect;
mapping_goodness_score -= log10(fraction_incorrect) * mapq_counts[i];
}
cerr << mapping_goodness_score / total_read_count << endl;
return 0;
}
// Register subcommand
static Subcommand vg_score("score", "score compared alignment", main_score);
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "base58.h"
#include "wallet.h"
#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace json_spirit;
extern Array createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL);
extern Value CallRPC(string args);
extern CWallet* pwalletMain;
BOOST_AUTO_TEST_SUITE(rpc_wallet_tests)
BOOST_AUTO_TEST_CASE(rpc_addmultisig)
{
LOCK(pwalletMain->cs_wallet);
rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor;
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_wallet)
{
// Test RPC calls for various wallet statistics
Value r;
LOCK2(cs_main, pwalletMain->cs_wallet);
CPubKey demoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID()));
Value retValue;
string strAccount = "walletDemoAccount";
string strPurpose = "receive";
BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
account.vchPubKey = demoPubkey;
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose);
walletdb.WriteAccount(strAccount, account);
});
CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID()));
/*********************************
* setaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount"));
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error);
BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error);
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error);
/*********************************
* listunspent
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listunspent"));
BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error);
BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []"));
BOOST_CHECK(r.get_array().empty());
/*********************************
* listreceivedbyaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error);
/*********************************
* listreceivedbyaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error);
/*********************************
* getrawchangeaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress"));
/*********************************
* getnewaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress"));
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount"));
/*********************************
* getaccountaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\""));
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount));
BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get());
/*********************************
* getaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString()));
/*********************************
* signmessage + verifymessage
*********************************/
BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage"));
BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error);
/* Should throw error because this address is not loaded in the wallet */
BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error);
/* missing arguments */
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error);
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error);
/* Illegal address */
BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error);
/* wrong address */
BOOST_CHECK(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage").get_bool() == false);
/* Correct address and signature but wrong message */
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false);
/* Correct address, message and signature*/
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true);
/*********************************
* getaddressesbyaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error);
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount));
Array arr = retValue.get_array();
BOOST_CHECK(arr.size() > 0);
BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get());
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Adding RPC tests for the following wallet related calls: getbalance, listsinceblock, listtransactions, listlockunspent, listaccounts listaddressgroupings<commit_after>// Copyright (c) 2013-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "base58.h"
#include "wallet.h"
#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace json_spirit;
extern Array createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL);
extern Value CallRPC(string args);
extern CWallet* pwalletMain;
BOOST_AUTO_TEST_SUITE(rpc_wallet_tests)
BOOST_AUTO_TEST_CASE(rpc_addmultisig)
{
LOCK(pwalletMain->cs_wallet);
rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor;
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_wallet)
{
// Test RPC calls for various wallet statistics
Value r;
LOCK2(cs_main, pwalletMain->cs_wallet);
CPubKey demoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID()));
Value retValue;
string strAccount = "walletDemoAccount";
string strPurpose = "receive";
BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
account.vchPubKey = demoPubkey;
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose);
walletdb.WriteAccount(strAccount, account);
});
CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID()));
/*********************************
* setaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount"));
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error);
BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error);
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error);
/*********************************
* getbalance
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getbalance"));
BOOST_CHECK_NO_THROW(CallRPC("getbalance " + demoAddress.ToString()));
/*********************************
* listunspent
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listunspent"));
BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error);
BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []"));
BOOST_CHECK(r.get_array().empty());
/*********************************
* listreceivedbyaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error);
/*********************************
* listreceivedbyaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error);
/*********************************
* listsinceblock
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listsinceblock"));
/*********************************
* listtransactions
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listtransactions"));
BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString()));
BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20"));
BOOST_CHECK_NO_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " 20 0"));
BOOST_CHECK_THROW(CallRPC("listtransactions " + demoAddress.ToString() + " not_int"), runtime_error);
/*********************************
* listlockunspent
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listlockunspent"));
/*********************************
* listaccounts
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listaccounts"));
/*********************************
* listaddressgroupings
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listaddressgroupings"));
/*********************************
* getrawchangeaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress"));
/*********************************
* getnewaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress"));
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount"));
/*********************************
* getaccountaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\""));
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount));
BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get());
/*********************************
* getaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString()));
/*********************************
* signmessage + verifymessage
*********************************/
BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage"));
BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error);
/* Should throw error because this address is not loaded in the wallet */
BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error);
/* missing arguments */
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error);
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error);
/* Illegal address */
BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error);
/* wrong address */
BOOST_CHECK(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage").get_bool() == false);
/* Correct address and signature but wrong message */
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false);
/* Correct address, message and signature*/
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true);
/*********************************
* getaddressesbyaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error);
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount));
Array arr = retValue.get_array();
BOOST_CHECK(arr.size() > 0);
BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get());
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//mapnik
#include <mapnik/text/placements/angle.hpp>
#include <mapnik/xml_node.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/text/placements/list.hpp>
#include <mapnik/text/placements/dummy.hpp>
namespace
{
using namespace mapnik;
double extract_angle(feature_impl const& feature,
attributes const& vars,
symbolizer_base::value_type const& angle_expression)
{
int angle = util::apply_visitor(extract_value<value_integer>(feature, vars), angle_expression) % 360;
if (angle < 0)
{
angle += 360;
}
return angle * (M_PI / 180.0);
}
symbolizer_base::value_type get_opt(xml_node const& xml, std::string const& name, double default_value = .0)
{
boost::optional<expression_ptr> expression = xml.get_opt_attr<expression_ptr>(name);
return expression ? *expression : static_cast<symbolizer_base::value_type>(default_value);
}
}
namespace mapnik
{
//text_placements_angle class
const box2d<double> text_placements_angle::empty_box;
text_placements_angle::text_placements_angle(text_placements_ptr list_placement,
symbolizer_base::value_type const& angle,
symbolizer_base::value_type const& tolerance,
symbolizer_base::value_type const& step,
boost::optional<expression_ptr> const& anchor_key)
: list_placement_(list_placement),
angle_(angle),
tolerance_(tolerance),
step_(step),
anchor_key_(anchor_key)
{
}
text_placement_info_ptr text_placements_angle::get_placement_info(double scale_factor,
feature_impl const& feature,
attributes const& vars,
symbol_cache const& sc) const
{
text_placement_info_ptr list_placement_info = list_placement_->get_placement_info(scale_factor, feature, vars, sc);
double angle = extract_angle(feature, vars, angle_);
double tolerance = extract_angle(feature, vars, tolerance_);
double step = extract_angle(feature, vars, step_);
if (step == .0)
{
step = default_step;
}
if (anchor_key_)
{
std::string anchor_key = util::apply_visitor(extract_value<std::string>(feature, vars),
static_cast<symbolizer_base::value_type>(*anchor_key_));
if (sc.contains(anchor_key))
{
symbol_cache::symbol const& sym = sc.get(anchor_key);
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, sym.box, list_placement_info);
}
else
{
return std::make_shared<text_placement_info_dummy>(this, scale_factor, 1);
}
}
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, empty_box, list_placement_info);
}
void text_placements_angle::add_expressions(expression_set & output) const
{
list_placement_->add_expressions(output);
if (is_expression(angle_)) output.insert(util::get<expression_ptr>(angle_));
if (is_expression(tolerance_)) output.insert(util::get<expression_ptr>(tolerance_));
if (is_expression(step_)) output.insert(util::get<expression_ptr>(step_));
if (anchor_key_) output.insert(*anchor_key_);
}
text_placements_ptr text_placements_angle::from_xml(xml_node const& xml, fontset_map const& fontsets, bool is_shield)
{
symbolizer_base::value_type angle = get_opt(xml, "angle");
symbolizer_base::value_type tolerance = get_opt(xml, "tolerance");
symbolizer_base::value_type step = get_opt(xml, "step", default_step);
boost::optional<expression_ptr> anchor_key = xml.get_opt_attr<expression_ptr>("anchor-key");
text_placements_ptr list_placement_ptr = text_placements_list::from_xml(xml, fontsets, is_shield);
text_placements_ptr ptr = std::make_shared<text_placements_angle>(list_placement_ptr, angle, tolerance, step, anchor_key);
ptr->defaults.from_xml(xml, fontsets, is_shield);
return ptr;
}
//text_placement_info_angle class
text_placement_info_angle::text_placement_info_angle(text_placements_angle const* parent,
feature_impl const& feature,
attributes const& vars,
double scale_factor,
double angle,
double tolerance,
double step,
box2d<double> const& box,
text_placement_info_ptr list_placement_info)
: text_placement_info(parent, scale_factor),
list_placement_info_(list_placement_info),
feature_(feature),
vars_(vars),
angle_(angle),
box_(box),
dx_(displacement(box.width(), properties.layout_defaults.dx)),
dy_(displacement(box.height(), properties.layout_defaults.dy)),
tolerance_iterator_(tolerance, 0, tolerance_function(step))
{
list_placement_info_->next();
}
void text_placement_info_angle::reset_state()
{
list_placement_info_->reset_state();
list_placement_info_->next();
tolerance_iterator_.reset();
}
bool text_placement_info_angle::try_next_angle() const
{
if (tolerance_iterator_.next())
{
double angle = angle_ + tolerance_iterator_.get();
double dx, dy;
get_point(angle, dx, dy);
properties.layout_defaults.dx = dx;
properties.layout_defaults.dy = dy;
return true;
}
return false;
}
bool text_placement_info_angle::next() const
{
if (try_next_angle())
{
return true;
}
else if (list_placement_info_->next())
{
properties = list_placement_info_->properties;
dx_ = displacement(box_.width(), properties.layout_defaults.dx);
dy_ = displacement(box_.height(), properties.layout_defaults.dy);
tolerance_iterator_.reset();
try_next_angle();
return true;
}
return false;
}
double text_placement_info_angle::displacement(double const& box_size, symbolizer_base::value_type const& displacement) const
{
double d = util::apply_visitor(extract_value<double>(feature_, vars_), displacement);
return box_size / 2.0 + d + .5;
}
void text_placement_info_angle::get_point(double angle, double &x, double &y) const
{
double corner = std::atan(dx_ / dy_);
if ((angle >= 0 && angle <= corner) || (angle >= 2 * M_PI - corner && angle <= 2 * M_PI))
{
x = -dy_ * std::tan(angle);
y = -dy_;
}
else if (angle >= corner && angle <= M_PI - corner)
{
x = -dx_;
y = dx_ * std::tan(angle - M_PI_2);
}
else if (angle >= M_PI + corner && angle <= 2 * M_PI - corner)
{
x = dx_;
y = -dy_ * std::tan(angle - M_PI_2 * 3);
}
else
{
x = dy_ * std::tan(angle - M_PI);
y = dy_;
}
}
}
<commit_msg>text placement angle: normalize angle<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//mapnik
#include <mapnik/text/placements/angle.hpp>
#include <mapnik/xml_node.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/text/placements/list.hpp>
#include <mapnik/text/placements/dummy.hpp>
namespace
{
using namespace mapnik;
double normalize_angle(double angle)
{
angle = std::fmod(angle, M_PI * 2.0);
if (angle < 0)
{
angle += M_PI * 2.0;
}
return angle;
}
double extract_angle(feature_impl const& feature,
attributes const& vars,
symbolizer_base::value_type const& angle_expression)
{
double angle = util::apply_visitor(extract_value<value_double>(feature, vars), angle_expression);
return normalize_angle(angle * (M_PI / 180.0));
}
symbolizer_base::value_type get_opt(xml_node const& xml, std::string const& name, double default_value = .0)
{
boost::optional<expression_ptr> expression = xml.get_opt_attr<expression_ptr>(name);
return expression ? *expression : static_cast<symbolizer_base::value_type>(default_value);
}
}
namespace mapnik
{
//text_placements_angle class
const box2d<double> text_placements_angle::empty_box;
text_placements_angle::text_placements_angle(text_placements_ptr list_placement,
symbolizer_base::value_type const& angle,
symbolizer_base::value_type const& tolerance,
symbolizer_base::value_type const& step,
boost::optional<expression_ptr> const& anchor_key)
: list_placement_(list_placement),
angle_(angle),
tolerance_(tolerance),
step_(step),
anchor_key_(anchor_key)
{
}
text_placement_info_ptr text_placements_angle::get_placement_info(double scale_factor,
feature_impl const& feature,
attributes const& vars,
symbol_cache const& sc) const
{
text_placement_info_ptr list_placement_info = list_placement_->get_placement_info(scale_factor, feature, vars, sc);
double angle = extract_angle(feature, vars, angle_);
double tolerance = extract_angle(feature, vars, tolerance_);
double step = extract_angle(feature, vars, step_);
if (step == .0)
{
step = default_step;
}
if (anchor_key_)
{
std::string anchor_key = util::apply_visitor(extract_value<std::string>(feature, vars),
static_cast<symbolizer_base::value_type>(*anchor_key_));
if (sc.contains(anchor_key))
{
symbol_cache::symbol const& sym = sc.get(anchor_key);
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, sym.box, list_placement_info);
}
else
{
return std::make_shared<text_placement_info_dummy>(this, scale_factor, 1);
}
}
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, empty_box, list_placement_info);
}
void text_placements_angle::add_expressions(expression_set & output) const
{
list_placement_->add_expressions(output);
if (is_expression(angle_)) output.insert(util::get<expression_ptr>(angle_));
if (is_expression(tolerance_)) output.insert(util::get<expression_ptr>(tolerance_));
if (is_expression(step_)) output.insert(util::get<expression_ptr>(step_));
if (anchor_key_) output.insert(*anchor_key_);
}
text_placements_ptr text_placements_angle::from_xml(xml_node const& xml, fontset_map const& fontsets, bool is_shield)
{
symbolizer_base::value_type angle = get_opt(xml, "angle");
symbolizer_base::value_type tolerance = get_opt(xml, "tolerance");
symbolizer_base::value_type step = get_opt(xml, "step", default_step);
boost::optional<expression_ptr> anchor_key = xml.get_opt_attr<expression_ptr>("anchor-key");
text_placements_ptr list_placement_ptr = text_placements_list::from_xml(xml, fontsets, is_shield);
text_placements_ptr ptr = std::make_shared<text_placements_angle>(list_placement_ptr, angle, tolerance, step, anchor_key);
ptr->defaults.from_xml(xml, fontsets, is_shield);
return ptr;
}
//text_placement_info_angle class
text_placement_info_angle::text_placement_info_angle(text_placements_angle const* parent,
feature_impl const& feature,
attributes const& vars,
double scale_factor,
double angle,
double tolerance,
double step,
box2d<double> const& box,
text_placement_info_ptr list_placement_info)
: text_placement_info(parent, scale_factor),
list_placement_info_(list_placement_info),
feature_(feature),
vars_(vars),
angle_(angle),
box_(box),
dx_(displacement(box.width(), properties.layout_defaults.dx)),
dy_(displacement(box.height(), properties.layout_defaults.dy)),
tolerance_iterator_(tolerance, 0, tolerance_function(step))
{
list_placement_info_->next();
}
void text_placement_info_angle::reset_state()
{
list_placement_info_->reset_state();
list_placement_info_->next();
tolerance_iterator_.reset();
}
bool text_placement_info_angle::try_next_angle() const
{
if (tolerance_iterator_.next())
{
double angle = normalize_angle(angle_ + tolerance_iterator_.get());
double dx, dy;
get_point(angle, dx, dy);
properties.layout_defaults.dx = dx;
properties.layout_defaults.dy = dy;
return true;
}
return false;
}
bool text_placement_info_angle::next() const
{
if (try_next_angle())
{
return true;
}
else if (list_placement_info_->next())
{
properties = list_placement_info_->properties;
dx_ = displacement(box_.width(), properties.layout_defaults.dx);
dy_ = displacement(box_.height(), properties.layout_defaults.dy);
tolerance_iterator_.reset();
try_next_angle();
return true;
}
return false;
}
double text_placement_info_angle::displacement(double const& box_size, symbolizer_base::value_type const& displacement) const
{
double d = util::apply_visitor(extract_value<double>(feature_, vars_), displacement);
return box_size / 2.0 + d + .5;
}
void text_placement_info_angle::get_point(double angle, double &x, double &y) const
{
double corner = std::atan(dx_ / dy_);
if ((angle >= 0 && angle <= corner) || (angle >= 2 * M_PI - corner && angle <= 2 * M_PI))
{
x = -dy_ * std::tan(angle);
y = -dy_;
}
else if (angle >= corner && angle <= M_PI - corner)
{
x = -dx_;
y = dx_ * std::tan(angle - M_PI_2);
}
else if (angle >= M_PI + corner && angle <= 2 * M_PI - corner)
{
x = dx_;
y = -dy_ * std::tan(angle - M_PI_2 * 3);
}
else
{
x = dy_ * std::tan(angle - M_PI);
y = dy_;
}
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: shape_io.cc 26 2005-03-29 19:18:59Z pavlenko $
#include "shape_io.hpp"
#include "shape.hpp"
using mapnik::datasource_exception;
const std::string shape_io::SHP = ".shp";
const std::string shape_io::DBF = ".dbf";
shape_io::shape_io(const std::string& shape_name)
: type_(shape_null),
shp_(shape_name + SHP),
dbf_(shape_name + DBF),
reclength_(0),
id_(0)
{
bool ok = (shp_.is_open() && dbf_.is_open());
if (!ok)
{
throw datasource_exception("cannot read shape file");
}
}
shape_io::~shape_io()
{
shp_.close();
dbf_.close();
}
void shape_io::move_to (int pos)
{
shp_.seek(pos);
id_ = shp_.read_xdr_integer();
reclength_ = shp_.read_xdr_integer();
type_ = shp_.read_ndr_integer();
if (shp_.is_eof()) {
id_ = 0;
reclength_ = 0;
type_ = shape_null;
}
if (type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz)
{
shp_.read_envelope(cur_extent_);
}
}
int shape_io::type() const
{
return type_;
}
const box2d<double>& shape_io::current_extent() const
{
return cur_extent_;
}
shape_file& shape_io::shp()
{
return shp_;
}
shape_file& shape_io::shx()
{
return shx_;
}
dbf_file& shape_io::dbf()
{
return dbf_;
}
geometry2d * shape_io::read_polyline()
{
using mapnik::line_string_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
geometry2d * line = new line_string_impl;
line->set_capacity(num_points + num_parts);
if (num_parts == 1)
{
line->set_capacity(num_points + 1);
record.skip(4);
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int i=1;i<num_points;++i)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
else
{
std::vector<int> parts(num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
int start,end;
for (int k=0;k<num_parts;++k)
{
start=parts[k];
if (k==num_parts-1)
end=num_points;
else
end=parts[k+1];
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int j=start+1;j<end;++j)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
}
return line;
}
geometry2d * shape_io::read_polylinem()
{
using mapnik::line_string_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
geometry2d * line = new line_string_impl;
line->set_capacity(num_points + num_parts);
if (num_parts == 1)
{
record.skip(4);
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int i=1;i<num_points;++i)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
else
{
std::vector<int> parts(num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
int start,end;
for (int k=0;k<num_parts;++k)
{
start=parts[k];
if (k==num_parts-1)
end=num_points;
else
end=parts[k+1];
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int j=start+1;j<end;++j)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
}
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return line;
}
geometry2d * shape_io::read_polylinez()
{
using mapnik::line_string_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
geometry2d * line = new line_string_impl;
line->set_capacity(num_points + num_parts);
if (num_parts == 1)
{
record.skip(4);
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int i=1;i<num_points;++i)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
else
{
std::vector<int> parts(num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
int start,end;
for (int k=0;k<num_parts;++k)
{
start=parts[k];
if (k==num_parts-1)
end=num_points;
else
end=parts[k+1];
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int j=start+1;j<end;++j)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
}
// z-range
//double z0=record.read_double();
//double z1=record.read_double();
//for (int i=0;i<num_points;++i)
// {
// double z=record.read_double();
// }
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return line;
}
geometry2d * shape_io::read_polygon()
{
using mapnik::polygon_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
std::vector<int> parts(num_parts);
geometry2d * poly = new polygon_impl;
poly->set_capacity(num_points + num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
for (int k=0;k<num_parts;k++)
{
int start=parts[k];
int end;
if (k==num_parts-1)
{
end=num_points;
}
else
{
end=parts[k+1];
}
double x=record.read_double();
double y=record.read_double();
poly->move_to(x,y);
for (int j=start+1;j<end;j++)
{
x=record.read_double();
y=record.read_double();
poly->line_to(x,y);
}
}
return poly;
}
geometry2d * shape_io::read_polygonm()
{
using mapnik::polygon_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
std::vector<int> parts(num_parts);
geometry2d * poly = new polygon_impl;
poly->set_capacity(num_points + num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
for (int k=0;k<num_parts;k++)
{
int start=parts[k];
int end;
if (k==num_parts-1)
{
end=num_points;
}
else
{
end=parts[k+1];
}
double x=record.read_double();
double y=record.read_double();
poly->move_to(x,y);
for (int j=start+1;j<end;j++)
{
x=record.read_double();
y=record.read_double();
poly->line_to(x,y);
}
}
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return poly;
}
geometry2d * shape_io::read_polygonz()
{
using mapnik::polygon_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
std::vector<int> parts(num_parts);
geometry2d * poly=new polygon_impl;
poly->set_capacity(num_points + num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
for (int k=0;k<num_parts;k++)
{
int start=parts[k];
int end;
if (k==num_parts-1)
{
end=num_points;
}
else
{
end=parts[k+1];
}
double x=record.read_double();
double y=record.read_double();
poly->move_to(x,y);
for (int j=start+1;j<end;j++)
{
x=record.read_double();
y=record.read_double();
poly->line_to(x,y);
}
}
// z-range
//double z0=record.read_double();
//double z1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double z=record.read_double();
//}
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return poly;
}
<commit_msg>+ don't read bounding box for null shapes<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: shape_io.cc 26 2005-03-29 19:18:59Z pavlenko $
#include "shape_io.hpp"
#include "shape.hpp"
using mapnik::datasource_exception;
const std::string shape_io::SHP = ".shp";
const std::string shape_io::DBF = ".dbf";
shape_io::shape_io(const std::string& shape_name)
: type_(shape_null),
shp_(shape_name + SHP),
dbf_(shape_name + DBF),
reclength_(0),
id_(0)
{
bool ok = (shp_.is_open() && dbf_.is_open());
if (!ok)
{
throw datasource_exception("cannot read shape file");
}
}
shape_io::~shape_io()
{
shp_.close();
dbf_.close();
}
void shape_io::move_to (int pos)
{
shp_.seek(pos);
id_ = shp_.read_xdr_integer();
reclength_ = shp_.read_xdr_integer();
type_ = shp_.read_ndr_integer();
if (shp_.is_eof()) {
id_ = 0;
reclength_ = 0;
type_ = shape_null;
}
if (type_!= shape_null && type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz)
{
shp_.read_envelope(cur_extent_);
}
}
int shape_io::type() const
{
return type_;
}
const box2d<double>& shape_io::current_extent() const
{
return cur_extent_;
}
shape_file& shape_io::shp()
{
return shp_;
}
shape_file& shape_io::shx()
{
return shx_;
}
dbf_file& shape_io::dbf()
{
return dbf_;
}
geometry2d * shape_io::read_polyline()
{
using mapnik::line_string_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
geometry2d * line = new line_string_impl;
line->set_capacity(num_points + num_parts);
if (num_parts == 1)
{
line->set_capacity(num_points + 1);
record.skip(4);
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int i=1;i<num_points;++i)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
else
{
std::vector<int> parts(num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
int start,end;
for (int k=0;k<num_parts;++k)
{
start=parts[k];
if (k==num_parts-1)
end=num_points;
else
end=parts[k+1];
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int j=start+1;j<end;++j)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
}
return line;
}
geometry2d * shape_io::read_polylinem()
{
using mapnik::line_string_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
geometry2d * line = new line_string_impl;
line->set_capacity(num_points + num_parts);
if (num_parts == 1)
{
record.skip(4);
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int i=1;i<num_points;++i)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
else
{
std::vector<int> parts(num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
int start,end;
for (int k=0;k<num_parts;++k)
{
start=parts[k];
if (k==num_parts-1)
end=num_points;
else
end=parts[k+1];
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int j=start+1;j<end;++j)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
}
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return line;
}
geometry2d * shape_io::read_polylinez()
{
using mapnik::line_string_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
geometry2d * line = new line_string_impl;
line->set_capacity(num_points + num_parts);
if (num_parts == 1)
{
record.skip(4);
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int i=1;i<num_points;++i)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
else
{
std::vector<int> parts(num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
int start,end;
for (int k=0;k<num_parts;++k)
{
start=parts[k];
if (k==num_parts-1)
end=num_points;
else
end=parts[k+1];
double x=record.read_double();
double y=record.read_double();
line->move_to(x,y);
for (int j=start+1;j<end;++j)
{
x=record.read_double();
y=record.read_double();
line->line_to(x,y);
}
}
}
// z-range
//double z0=record.read_double();
//double z1=record.read_double();
//for (int i=0;i<num_points;++i)
// {
// double z=record.read_double();
// }
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return line;
}
geometry2d * shape_io::read_polygon()
{
using mapnik::polygon_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
std::vector<int> parts(num_parts);
geometry2d * poly = new polygon_impl;
poly->set_capacity(num_points + num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
for (int k=0;k<num_parts;k++)
{
int start=parts[k];
int end;
if (k==num_parts-1)
{
end=num_points;
}
else
{
end=parts[k+1];
}
double x=record.read_double();
double y=record.read_double();
poly->move_to(x,y);
for (int j=start+1;j<end;j++)
{
x=record.read_double();
y=record.read_double();
poly->line_to(x,y);
}
}
return poly;
}
geometry2d * shape_io::read_polygonm()
{
using mapnik::polygon_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
std::vector<int> parts(num_parts);
geometry2d * poly = new polygon_impl;
poly->set_capacity(num_points + num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
for (int k=0;k<num_parts;k++)
{
int start=parts[k];
int end;
if (k==num_parts-1)
{
end=num_points;
}
else
{
end=parts[k+1];
}
double x=record.read_double();
double y=record.read_double();
poly->move_to(x,y);
for (int j=start+1;j<end;j++)
{
x=record.read_double();
y=record.read_double();
poly->line_to(x,y);
}
}
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return poly;
}
geometry2d * shape_io::read_polygonz()
{
using mapnik::polygon_impl;
shape_file::record_type record(reclength_*2-36);
shp_.read_record(record);
int num_parts=record.read_ndr_integer();
int num_points=record.read_ndr_integer();
std::vector<int> parts(num_parts);
geometry2d * poly=new polygon_impl;
poly->set_capacity(num_points + num_parts);
for (int i=0;i<num_parts;++i)
{
parts[i]=record.read_ndr_integer();
}
for (int k=0;k<num_parts;k++)
{
int start=parts[k];
int end;
if (k==num_parts-1)
{
end=num_points;
}
else
{
end=parts[k+1];
}
double x=record.read_double();
double y=record.read_double();
poly->move_to(x,y);
for (int j=start+1;j<end;j++)
{
x=record.read_double();
y=record.read_double();
poly->line_to(x,y);
}
}
// z-range
//double z0=record.read_double();
//double z1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double z=record.read_double();
//}
// m-range
//double m0=record.read_double();
//double m1=record.read_double();
//for (int i=0;i<num_points;++i)
//{
// double m=record.read_double();
//}
return poly;
}
<|endoftext|> |
<commit_before>#include "ancovabayesianform.h"
#include "ui_ancovabayesianform.h"
AncovaBayesianForm::AncovaBayesianForm(QWidget *parent) :
AnalysisForm("AncovaBayesianForm", parent),
ui(new Ui::AncovaBayesianForm)
{
ui->setupUi(this);
ui->listAvailableFields->setModel(&_availableVariablesModel);
_dependentListModel = new TableModelVariablesAssigned(this);
_dependentListModel->setVariableTypesSuggested(Column::ColumnTypeScale | Column::ColumnTypeOrdinal);
_dependentListModel->setSource(&_availableVariablesModel);
ui->dependent->setModel(_dependentListModel);
_fixedFactorsListModel = new TableModelVariablesAssigned(this);
_fixedFactorsListModel->setSource(&_availableVariablesModel);
_fixedFactorsListModel->setVariableTypesSuggested(Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
ui->fixedFactors->setModel(_fixedFactorsListModel);
_randomFactorsListModel = new TableModelVariablesAssigned(this);
_randomFactorsListModel->setSource(&_availableVariablesModel);
_randomFactorsListModel->setVariableTypesSuggested(Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
ui->randomFactors->setModel(_randomFactorsListModel);
_covariatesListModel = new TableModelVariablesAssigned(this);
_covariatesListModel->setSource(&_availableVariablesModel);
_covariatesListModel->setVariableTypesSuggested(Column::ColumnTypeScale);
_covariatesListModel->setVariableTypesAllowed(Column::ColumnTypeScale | Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
ui->covariates->setModel(_covariatesListModel);
ui->buttonAssignDependent->setSourceAndTarget(ui->listAvailableFields, ui->dependent);
ui->buttonAssignFixed->setSourceAndTarget(ui->listAvailableFields, ui->fixedFactors);
ui->buttonAssignRandom->setSourceAndTarget(ui->listAvailableFields, ui->randomFactors);
ui->buttonAssignRandom->setSourceAndTarget(ui->listAvailableFields, ui->covariates);
connect(_dependentListModel, SIGNAL(assignmentsChanged()), this, SLOT(dependentChanged()));
connect(_fixedFactorsListModel, SIGNAL(assignmentsChanged()), this, SLOT(factorsChanged()));
connect(_randomFactorsListModel, SIGNAL(assignmentsChanged()), this, SLOT(factorsChanged()));
_anovaModel = new TableModelAnovaModel(this);
ui->modelTerms->setModel(_anovaModel);
ui->modelTerms->hide();
}
AncovaBayesianForm::~AncovaBayesianForm()
{
delete ui;
}
/*void AncovaBayesianForm::set(Options *options, DataSet *dataSet)
{
OptionVariables *nuisanceOption = dynamic_cast<OptionVariables *>(options->get("nuisanceTerms"));
_anovaModel->setNuisanceTermsOption(nuisanceOption);
AnalysisForm::set(options, dataSet);
}*/
void AncovaBayesianForm::factorsChanged()
{
_anovaModel->setVariables(_fixedFactorsListModel->assigned());
}
void AncovaBayesianForm::dependentChanged()
{
/*const QList<ColumnInfo> &assigned = _dependentListModel->assigned();
if (assigned.length() == 0)
_anovaModel->setDependent(ColumnInfo("", 0));
else
_anovaModel->setDependent(assigned.last());*/
}
<commit_msg>Bayesian ANOVA UI: hid unused options<commit_after>#include "ancovabayesianform.h"
#include "ui_ancovabayesianform.h"
AncovaBayesianForm::AncovaBayesianForm(QWidget *parent) :
AnalysisForm("AncovaBayesianForm", parent),
ui(new Ui::AncovaBayesianForm)
{
ui->setupUi(this);
ui->listAvailableFields->setModel(&_availableVariablesModel);
_dependentListModel = new TableModelVariablesAssigned(this);
_dependentListModel->setVariableTypesSuggested(Column::ColumnTypeScale | Column::ColumnTypeOrdinal);
_dependentListModel->setSource(&_availableVariablesModel);
ui->dependent->setModel(_dependentListModel);
_fixedFactorsListModel = new TableModelVariablesAssigned(this);
_fixedFactorsListModel->setSource(&_availableVariablesModel);
_fixedFactorsListModel->setVariableTypesSuggested(Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
ui->fixedFactors->setModel(_fixedFactorsListModel);
_randomFactorsListModel = new TableModelVariablesAssigned(this);
_randomFactorsListModel->setSource(&_availableVariablesModel);
_randomFactorsListModel->setVariableTypesSuggested(Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
ui->randomFactors->setModel(_randomFactorsListModel);
_covariatesListModel = new TableModelVariablesAssigned(this);
_covariatesListModel->setSource(&_availableVariablesModel);
_covariatesListModel->setVariableTypesSuggested(Column::ColumnTypeScale);
_covariatesListModel->setVariableTypesAllowed(Column::ColumnTypeScale | Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
ui->covariates->setModel(_covariatesListModel);
ui->buttonAssignDependent->setSourceAndTarget(ui->listAvailableFields, ui->dependent);
ui->buttonAssignFixed->setSourceAndTarget(ui->listAvailableFields, ui->fixedFactors);
ui->buttonAssignRandom->setSourceAndTarget(ui->listAvailableFields, ui->randomFactors);
ui->buttonAssignRandom->setSourceAndTarget(ui->listAvailableFields, ui->covariates);
connect(_dependentListModel, SIGNAL(assignmentsChanged()), this, SLOT(dependentChanged()));
connect(_fixedFactorsListModel, SIGNAL(assignmentsChanged()), this, SLOT(factorsChanged()));
connect(_randomFactorsListModel, SIGNAL(assignmentsChanged()), this, SLOT(factorsChanged()));
_anovaModel = new TableModelAnovaModel(this);
ui->modelTerms->setModel(_anovaModel);
ui->modelTerms->hide();
#ifdef QT_NO_DEBUG
// temporary hides until the appropriate R code is implemented
ui->posteriorDistributions->hide();
ui->posteriorEstimates->hide();
#else
ui->posteriorDistributions->setStyleSheet("background-color: pink;");
ui->posteriorEstimates->setStyleSheet("background-color: pink;");
#endif
}
AncovaBayesianForm::~AncovaBayesianForm()
{
delete ui;
}
/*void AncovaBayesianForm::set(Options *options, DataSet *dataSet)
{
OptionVariables *nuisanceOption = dynamic_cast<OptionVariables *>(options->get("nuisanceTerms"));
_anovaModel->setNuisanceTermsOption(nuisanceOption);
AnalysisForm::set(options, dataSet);
}*/
void AncovaBayesianForm::factorsChanged()
{
_anovaModel->setVariables(_fixedFactorsListModel->assigned());
}
void AncovaBayesianForm::dependentChanged()
{
/*const QList<ColumnInfo> &assigned = _dependentListModel->assigned();
if (assigned.length() == 0)
_anovaModel->setDependent(ColumnInfo("", 0));
else
_anovaModel->setDependent(assigned.last());*/
}
<|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/ref_counted.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class MediaPlayerBrowserTest : public InProcessBrowserTest {
public:
MediaPlayerBrowserTest() {}
GURL GetMusicTestURL() {
return GURL("http://localhost:1337/files/plugin/sample_mp3.mp3");
}
bool IsPlayerVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost) {
return true;
}
}
}
return false;
}
bool IsPlaylistVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost &&
url.ref() == "playlist") {
return true;
}
}
}
return false;
}
};
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, Popup) {
StartHTTPServer();
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
// Check that its not currently visible
ASSERT_FALSE(IsPlayerVisible());
player->EnqueueMediaURL(GetMusicTestURL());
ASSERT_TRUE(IsPlayerVisible());
}
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, PopupPlaylist) {
StartHTTPServer();
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
player->EnqueueMediaURL(GetMusicTestURL());
EXPECT_FALSE(IsPlaylistVisible());
player->TogglePlaylistWindowVisible();
EXPECT_TRUE(IsPlaylistVisible());
}
} // namespace
<commit_msg>Fix build on ChromeOS by adding required return value checks.<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/ref_counted.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
class MediaPlayerBrowserTest : public InProcessBrowserTest {
public:
MediaPlayerBrowserTest() {}
GURL GetMusicTestURL() {
return GURL("http://localhost:1337/files/plugin/sample_mp3.mp3");
}
bool IsPlayerVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost) {
return true;
}
}
}
return false;
}
bool IsPlaylistVisible() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIMediaplayerHost &&
url.ref() == "playlist") {
return true;
}
}
}
return false;
}
};
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, Popup) {
ASSERT_TRUE(StartHTTPServer());
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
// Check that its not currently visible
ASSERT_FALSE(IsPlayerVisible());
player->EnqueueMediaURL(GetMusicTestURL());
ASSERT_TRUE(IsPlayerVisible());
}
IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, PopupPlaylist) {
ASSERT_TRUE(StartHTTPServer());
// Doing this so we have a valid profile.
ui_test_utils::NavigateToURL(browser(),
GURL("chrome://downloads"));
MediaPlayer* player = MediaPlayer::Get();
player->EnqueueMediaURL(GetMusicTestURL());
EXPECT_FALSE(IsPlaylistVisible());
player->TogglePlaylistWindowVisible();
EXPECT_TRUE(IsPlaylistVisible());
}
} // namespace
<|endoftext|> |
<commit_before>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2013-2017 Igor Mironchik
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.
*/
// UnitTest include.
#include <UnitTest/unit_test.hpp>
// Args include.
#include <Args/all.hpp>
using namespace Args;
#ifdef ARGS_WSTRING_BUILD
using CHAR = String::value_type;
#else
using CHAR = char;
#endif
TEST( ArgExceptions, TestNoValueForArg )
{
const int argc = 2;
const CHAR * argv[ argc ] = { SL( "program.exe" ),
SL( "-a" ) };
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( 'a' ), true );
try {
cmd.parse( argc, argv );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" requires value that wasn't presented." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestRequiredArgInAllOfGroup )
{
const int argc = 2;
const CHAR * argv[ argc ] = { SL( "program.exe" ),
SL( "-a" ) };
CmdLine cmd;
cmd.addAllOfGroup( SL( "group" ) )
.addArgWithFlagOnly( SL( 'a' ), true, true )
.end();
try {
cmd.parse( argc, argv );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Required argument \"-a\" is not allowed to be in "
"AllOf group \"group\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestAlreadyInCmdLine1 )
{
CmdLine cmd;
try {
auto a1 = CmdLine::ArgPtr( new Arg( Char( SL( 'a' ) ), true, true ),
details::Deleter< ArgIface >( true ) );
auto a2 = CmdLine::ArgPtr( a1.get(),
details::Deleter< ArgIface >( false ) );
cmd.addArg( std::move( a1 ) );
cmd.addArg( std::move( a2 ) );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" already in the command line parser." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestAlreadyInCmdLine2 )
{
CmdLine cmd;
try {
Arg a1( Char( SL( 'a' ) ), true, true );
cmd.addArg( &a1 );
cmd.addArg( &a1 );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" already in the command line parser." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestAddingNull )
{
CmdLine cmd;
try {
cmd.addArg( nullptr );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Attempt to add nullptr to the "
"command line as argument." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestEmptyNameOfArgAsCommand )
{
try {
CmdLine cmd;
ArgAsCommand a( SL( "" ) );
cmd.addArg( a );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "ArgAsCommand can't be with empty name." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestDissallowedNameOfArgAsCommand )
{
try {
CmdLine cmd;
ArgAsCommand a( SL( "arg with space" ) );
cmd.addArg( a );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed name \"arg with space\" for the argument." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestEmptyNameOfCommand )
{
try {
CmdLine cmd;
Command a( SL( "" ) );
cmd.addArg( a );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Command can't be with empty name." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestRedefinitionOfCommand )
{
try {
CmdLine cmd;
Command a( SL( "cmd" ) );
Command b( SL( "cmd" ) );
cmd.addArg( a );
cmd.addArg( b );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Redefinition of command with name \"cmd\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestDissallowedNameOfCommand )
{
try {
CmdLine cmd;
Command a( SL( "cmd with space" ) );
cmd.addArg( a );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed name \"cmd with space\" for the command." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgAlreadyDefined )
{
try {
const int argc = 3;
const CHAR * argv[ argc ] = { SL( "program.exe" ),
SL( "-a" ), SL( "-a" ) };
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( 'a' ) );
cmd.parse( argc, argv );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" already defined." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgRedefinition )
{
try {
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( 'a' ) )
.addArgWithFlagOnly( SL( 'a' ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Redefinition of argument witg flag \"-a\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestDissallowedFlag )
{
try {
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( '~' ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed flag \"-~\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgNameRedefinition )
{
try {
CmdLine cmd;
cmd.addArgWithNameOnly( SL( "name" ) )
.addArgWithNameOnly( SL( "name" ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Redefinition of argument with name \"--name\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgDissallowedName )
{
try {
CmdLine cmd;
cmd.addArgWithNameOnly( SL( "~~" ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed name \"--~~\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgEmptyNameAndFlag )
{
try {
CmdLine cmd;
cmd.addArgWithNameOnly( SL( "" ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Arguments with empty flag and name "
"are disallowed." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestCommandIngroup )
{
try {
AllOfGroup g( SL( "" ) );
Command c( SL( "c" ) );
g.addArg( (ArgIface&) c );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Commands not allowed in groups. "
"You are trying to add command \"c\" to group \"\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestCommandIngroup2 )
{
try {
AllOfGroup g( SL( "" ) );
AllOfGroup::ArgPtr c( new Command( SL( "c" ) ),
details::Deleter< ArgIface > ( true ) );
g.addArg( std::move( c ) );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Commands not allowed in groups. "
"You are trying to add command \"c\" to group \"\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestCommandIngroup3 )
{
try {
AllOfGroup g( SL( "" ) );
Command c( SL( "c" ) );
g.addArg( (ArgIface*) &c );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Commands not allowed in groups. "
"You are trying to add command \"c\" to group \"\"." ) )
return;
}
CHECK_CONDITION( false )
}
int main()
{
RUN_ALL_TESTS()
return 0;
}
<commit_msg>Testing.<commit_after>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2013-2017 Igor Mironchik
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.
*/
// UnitTest include.
#include <UnitTest/unit_test.hpp>
// Args include.
#include <Args/all.hpp>
using namespace Args;
#ifdef ARGS_WSTRING_BUILD
using CHAR = String::value_type;
#else
using CHAR = char;
#endif
TEST( ArgExceptions, TestNoValueForArg )
{
const int argc = 2;
const CHAR * argv[ argc ] = { SL( "program.exe" ),
SL( "-a" ) };
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( 'a' ), true );
try {
cmd.parse( argc, argv );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" requires value that wasn't presented." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestRequiredArgInAllOfGroup )
{
const int argc = 2;
const CHAR * argv[ argc ] = { SL( "program.exe" ),
SL( "-a" ) };
CmdLine cmd;
cmd.addAllOfGroup( SL( "group" ) )
.addArgWithFlagOnly( SL( 'a' ), true, true )
.end();
try {
cmd.parse( argc, argv );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Required argument \"-a\" is not allowed to be in "
"AllOf group \"group\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestAlreadyInCmdLine1 )
{
CmdLine cmd;
try {
auto a1 = CmdLine::ArgPtr( new Arg( Char( SL( 'a' ) ), true, true ),
details::Deleter< ArgIface >( true ) );
auto a2 = CmdLine::ArgPtr( a1.get(),
details::Deleter< ArgIface >( false ) );
cmd.addArg( std::move( a1 ) );
cmd.addArg( std::move( a2 ) );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" already in the command line parser." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestAlreadyInCmdLine2 )
{
CmdLine cmd;
try {
Arg a1( Char( SL( 'a' ) ), true, true );
cmd.addArg( &a1 );
cmd.addArg( &a1 );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" already in the command line parser." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestAddingNull )
{
CmdLine cmd;
try {
cmd.addArg( nullptr );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Attempt to add nullptr to the "
"command line as argument." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestEmptyNameOfArgAsCommand )
{
try {
CmdLine cmd;
ArgAsCommand a( SL( "" ) );
cmd.addArg( a );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "ArgAsCommand can't be with empty name." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestDissallowedNameOfArgAsCommand )
{
try {
CmdLine cmd;
ArgAsCommand a( SL( "arg with space" ) );
cmd.addArg( a );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed name \"arg with space\" for the argument." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestEmptyNameOfCommand )
{
try {
CmdLine cmd;
Command a( SL( "" ) );
cmd.addArg( a );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Command can't be with empty name." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestRedefinitionOfCommand )
{
try {
CmdLine cmd;
Command a( SL( "cmd" ) );
Command b( SL( "cmd" ) );
cmd.addArg( a );
cmd.addArg( b );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Redefinition of command with name \"cmd\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestDissallowedNameOfCommand )
{
try {
CmdLine cmd;
Command a( SL( "cmd with space" ) );
cmd.addArg( a );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed name \"cmd with space\" for the command." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgAlreadyDefined )
{
try {
const int argc = 3;
const CHAR * argv[ argc ] = { SL( "program.exe" ),
SL( "-a" ), SL( "-a" ) };
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( 'a' ) );
cmd.parse( argc, argv );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Argument \"-a\" already defined." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgRedefinition )
{
try {
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( 'a' ) )
.addArgWithFlagOnly( SL( 'a' ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Redefinition of argument witg flag \"-a\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestDissallowedFlag )
{
try {
CmdLine cmd;
cmd.addArgWithFlagOnly( SL( '~' ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed flag \"-~\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgNameRedefinition )
{
try {
CmdLine cmd;
cmd.addArgWithNameOnly( SL( "name" ) )
.addArgWithNameOnly( SL( "name" ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Redefinition of argument with name \"--name\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgDissallowedName )
{
try {
CmdLine cmd;
cmd.addArgWithNameOnly( SL( "~~" ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Disallowed name \"--~~\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestArgEmptyNameAndFlag )
{
try {
CmdLine cmd;
cmd.addArgWithNameOnly( SL( "" ) );
cmd.parse();
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Arguments with empty flag and name "
"are disallowed." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestCommandIngroup )
{
try {
AllOfGroup g( SL( "" ) );
Command c( SL( "c" ) );
g.addArg( (ArgIface&) c );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Commands not allowed in groups. "
"You are trying to add command \"c\" to group \"\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestCommandIngroup2 )
{
try {
AllOfGroup g( SL( "" ) );
AllOfGroup::ArgPtr c( new Command( SL( "c" ) ),
details::Deleter< ArgIface > ( true ) );
g.addArg( std::move( c ) );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Commands not allowed in groups. "
"You are trying to add command \"c\" to group \"\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestCommandIngroup3 )
{
try {
AllOfGroup g( SL( "" ) );
Command c( SL( "c" ) );
g.addArg( (ArgIface*) &c );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Commands not allowed in groups. "
"You are trying to add command \"c\" to group \"\"." ) )
return;
}
CHECK_CONDITION( false )
}
TEST( ArgExceptions, TestMisspelledSubcommand )
{
try {
const int argc = 3;
const CHAR * argv[ argc ] = { SL( "program.exe" ),
SL( "cmd" ), SL( "bac" ) };
CmdLine cmd;
cmd.addCommand( SL( "cmd" ) )
.addSubCommand( SL( "abc" ) )
.addSubCommand( SL( "cba" ) )
.end();
cmd.parse( argc, argv );
}
catch( const BaseException & x )
{
CHECK_CONDITION( x.desc() ==
SL( "Unknown argument \"bac\".\n\nProbably you mean \"abc or cba\"." ) )
return;
}
CHECK_CONDITION( false )
}
int main()
{
RUN_ALL_TESTS()
return 0;
}
<|endoftext|> |
<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#include "../precompiled.hpp"
#include "timer_driver.hpp"
#include "../core/abstract_timer.hpp"
#include "../xutilities.hpp"
namespace poseidon {
namespace {
inline
int64_t&
do_shift_time(int64_t& value, int64_t shift)
noexcept
{
// `value` must be non-negative. `shift` may be any value.
ROCKET_ASSERT(value >= 0);
value += ::rocket::clamp(shift, -value, INT64_MAX-value);
ROCKET_ASSERT(value >= 0);
return value;
}
int64_t
do_get_time(int64_t shift)
noexcept
{
// Get the time since the system was started.
::timespec ts;
::clock_gettime(CLOCK_MONOTONIC, &ts);
int64_t value = static_cast<int64_t>(ts.tv_sec) * 1'000;
value += static_cast<int64_t>(ts.tv_nsec) / 1'000'000;
value += 9876543210;
// Shift the time point using saturation arithmetic.
do_shift_time(value, shift);
return value;
}
struct PQ_Element
{
int64_t next;
rcptr<Abstract_Timer> timer;
};
struct PQ_Compare
{
constexpr
bool
operator()(const PQ_Element& lhs, const PQ_Element& rhs)
const noexcept
{ return lhs.next > rhs.next; }
constexpr
bool
operator()(const PQ_Element& lhs, int64_t rhs)
const noexcept
{ return lhs.next > rhs; }
constexpr
bool
operator()(int64_t lhs, const PQ_Element& rhs)
const noexcept
{ return lhs > rhs.next; }
}
constexpr pq_compare;
} // namespace
POSEIDON_STATIC_CLASS_DEFINE(Timer_Driver)
{
// constant data
::rocket::once_flag m_init_once;
::pthread_t m_thread;
// dynamic data
mutable mutex m_pq_mutex;
condition_variable m_pq_avail;
::std::vector<PQ_Element> m_pq;
static
void
do_init_once()
{
// Create the thread. Note it is never joined or detached.
mutex::unique_lock lock(self->m_pq_mutex);
self->m_thread = create_daemon_thread<do_thread_loop>("timer");
}
static
void
do_thread_loop(void* /*param*/)
{
rcptr<Abstract_Timer> timer;
int64_t now;
// Await an element and pop it.
mutex::unique_lock lock(self->m_pq_mutex);
for(;;) {
timer.reset();
if(self->m_pq.empty()) {
// Wait until an element becomes available.
self->m_pq_avail.wait(lock);
continue;
}
// Check the first element.
now = do_get_time(0);
int64_t delta = self->m_pq.front().next - now;
if(delta > 0) {
// Wait for it.
delta = ::rocket::min(delta, LONG_MAX);
self->m_pq_avail.wait_for(lock, static_cast<long>(delta));
continue;
}
// Pop it.
::std::pop_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
timer = ::std::move(self->m_pq.back().timer);
if(!timer.unique()) {
// Process this timer!
int64_t period = timer->m_period.load(::std::memory_order_relaxed);
if(period > 0) {
// The timer is periodic. Insert it back.
self->m_pq.back().timer = timer;
do_shift_time(self->m_pq.back().next, period);
::std::push_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
}
else {
// The timer is one-shot. Delete it.
self->m_pq.pop_back();
}
break;
}
// Delete this timer when no other reference of it exists.
POSEIDON_LOG_DEBUG("Killed orphan timer: $1", timer);
self->m_pq.pop_back();
}
lock.unlock();
// Execute the timer procedure.
// The argument is a snapshot of the monotonic clock, not its real-time value.
try {
timer->do_on_async_timer(now);
}
catch(exception& stdex) {
POSEIDON_LOG_WARN("Exception thrown from timer: $1\n"
"[timer class `$2`]",
stdex.what(), typeid(*timer).name());
}
timer->m_count.fetch_add(1, ::std::memory_order_release);
}
};
void
Timer_Driver::
start()
{
self->m_init_once.call(self->do_init_once);
}
rcptr<Abstract_Timer>
Timer_Driver::
insert(uptr<Abstract_Timer>&& utimer)
{
// Take ownership of `utimer`.
rcptr<Abstract_Timer> timer(utimer.release());
if(!timer)
POSEIDON_THROW("null timer pointer not valid");
if(!timer.unique())
POSEIDON_THROW("timer pointer must be unique");
// Get the next trigger time.
// The timer is considered to be owned uniquely, so there is no need to lock it.
int64_t next = do_get_time(timer->m_first);
// Lock priority queue for modification.
mutex::unique_lock lock(self->m_pq_mutex);
// Insert the timer.
self->m_pq.push_back({ next, timer });
::std::push_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
self->m_pq_avail.notify_one();
return timer;
}
bool
Timer_Driver::
invalidate_internal(const Abstract_Timer* ctimer)
noexcept
{
// Lock priority queue for modification.
mutex::unique_lock lock(self->m_pq_mutex);
// Don't do anything if the timer does not exist in the queue.
PQ_Element* qelem;
if(::std::none_of(self->m_pq.begin(), self->m_pq.end(),
[&](PQ_Element& r) { return (qelem = &r)->timer.get() == ctimer; }))
return false;
// Update the element in place.
qelem->next = do_get_time(ctimer->m_first.load(::std::memory_order_relaxed));
::std::make_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
self->m_pq_avail.notify_one();
return true;
}
} // namespace poseidon
<commit_msg>static/timer_driver: Reorder two clauses<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#include "../precompiled.hpp"
#include "timer_driver.hpp"
#include "../core/abstract_timer.hpp"
#include "../xutilities.hpp"
namespace poseidon {
namespace {
inline
int64_t&
do_shift_time(int64_t& value, int64_t shift)
noexcept
{
// `value` must be non-negative. `shift` may be any value.
ROCKET_ASSERT(value >= 0);
value += ::rocket::clamp(shift, -value, INT64_MAX-value);
ROCKET_ASSERT(value >= 0);
return value;
}
int64_t
do_get_time(int64_t shift)
noexcept
{
// Get the time since the system was started.
::timespec ts;
::clock_gettime(CLOCK_MONOTONIC, &ts);
int64_t value = static_cast<int64_t>(ts.tv_sec) * 1'000;
value += static_cast<int64_t>(ts.tv_nsec) / 1'000'000;
value += 9876543210;
// Shift the time point using saturation arithmetic.
do_shift_time(value, shift);
return value;
}
struct PQ_Element
{
int64_t next;
rcptr<Abstract_Timer> timer;
};
struct PQ_Compare
{
constexpr
bool
operator()(const PQ_Element& lhs, const PQ_Element& rhs)
const noexcept
{ return lhs.next > rhs.next; }
constexpr
bool
operator()(const PQ_Element& lhs, int64_t rhs)
const noexcept
{ return lhs.next > rhs; }
constexpr
bool
operator()(int64_t lhs, const PQ_Element& rhs)
const noexcept
{ return lhs > rhs.next; }
}
constexpr pq_compare;
} // namespace
POSEIDON_STATIC_CLASS_DEFINE(Timer_Driver)
{
// constant data
::rocket::once_flag m_init_once;
::pthread_t m_thread;
// dynamic data
mutable mutex m_pq_mutex;
condition_variable m_pq_avail;
::std::vector<PQ_Element> m_pq;
static
void
do_init_once()
{
// Create the thread. Note it is never joined or detached.
mutex::unique_lock lock(self->m_pq_mutex);
self->m_thread = create_daemon_thread<do_thread_loop>("timer");
}
static
void
do_thread_loop(void* /*param*/)
{
rcptr<Abstract_Timer> timer;
int64_t now;
// Await an element and pop it.
mutex::unique_lock lock(self->m_pq_mutex);
for(;;) {
timer.reset();
if(self->m_pq.empty()) {
// Wait until an element becomes available.
self->m_pq_avail.wait(lock);
continue;
}
// Check the first element.
now = do_get_time(0);
int64_t delta = self->m_pq.front().next - now;
if(delta > 0) {
// Wait for it.
delta = ::rocket::min(delta, LONG_MAX);
self->m_pq_avail.wait_for(lock, static_cast<long>(delta));
continue;
}
// Pop it.
::std::pop_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
timer = ::std::move(self->m_pq.back().timer);
if(timer.unique()) {
// Delete this timer when no other reference of it exists.
POSEIDON_LOG_DEBUG("Killed orphan timer: $1", timer);
self->m_pq.pop_back();
continue;
}
// Process this timer!
int64_t period = timer->m_period.load(::std::memory_order_relaxed);
if(period > 0) {
// The timer is periodic. Insert it back.
self->m_pq.back().timer = timer;
do_shift_time(self->m_pq.back().next, period);
::std::push_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
}
else {
// The timer is one-shot. Delete it.
self->m_pq.pop_back();
}
break;
}
lock.unlock();
// Execute the timer procedure.
// The argument is a snapshot of the monotonic clock, not its real-time value.
try {
timer->do_on_async_timer(now);
}
catch(exception& stdex) {
POSEIDON_LOG_WARN("Exception thrown from timer: $1\n"
"[timer class `$2`]",
stdex.what(), typeid(*timer).name());
}
timer->m_count.fetch_add(1, ::std::memory_order_release);
}
};
void
Timer_Driver::
start()
{
self->m_init_once.call(self->do_init_once);
}
rcptr<Abstract_Timer>
Timer_Driver::
insert(uptr<Abstract_Timer>&& utimer)
{
// Take ownership of `utimer`.
rcptr<Abstract_Timer> timer(utimer.release());
if(!timer)
POSEIDON_THROW("null timer pointer not valid");
if(!timer.unique())
POSEIDON_THROW("timer pointer must be unique");
// Get the next trigger time.
// The timer is considered to be owned uniquely, so there is no need to lock it.
int64_t next = do_get_time(timer->m_first);
// Lock priority queue for modification.
mutex::unique_lock lock(self->m_pq_mutex);
// Insert the timer.
self->m_pq.push_back({ next, timer });
::std::push_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
self->m_pq_avail.notify_one();
return timer;
}
bool
Timer_Driver::
invalidate_internal(const Abstract_Timer* ctimer)
noexcept
{
// Lock priority queue for modification.
mutex::unique_lock lock(self->m_pq_mutex);
// Don't do anything if the timer does not exist in the queue.
PQ_Element* qelem;
if(::std::none_of(self->m_pq.begin(), self->m_pq.end(),
[&](PQ_Element& r) { return (qelem = &r)->timer.get() == ctimer; }))
return false;
// Update the element in place.
qelem->next = do_get_time(ctimer->m_first.load(::std::memory_order_relaxed));
::std::make_heap(self->m_pq.begin(), self->m_pq.end(), pq_compare);
self->m_pq_avail.notify_one();
return true;
}
} // namespace poseidon
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/proxy/serialized_flash_menu.h"
#include "ipc/ipc_message.h"
#include "ppapi/c/private/ppb_flash_menu.h"
#include "ppapi/proxy/ppapi_param_traits.h"
namespace ppapi {
namespace proxy {
namespace {
// Maximum depth of submenus allowed (e.g., 1 indicates that submenus are
// allowed, but not sub-submenus).
const int kMaxMenuDepth = 2;
bool CheckMenu(int depth, const PP_Flash_Menu* menu);
void FreeMenu(const PP_Flash_Menu* menu);
void WriteMenu(IPC::Message* m, const PP_Flash_Menu* menu);
PP_Flash_Menu* ReadMenu(int depth, const IPC::Message* m, PickleIterator* iter);
bool CheckMenuItem(int depth, const PP_Flash_MenuItem* item) {
if (item->type == PP_FLASH_MENUITEM_TYPE_SUBMENU)
return CheckMenu(depth, item->submenu);
return true;
}
bool CheckMenu(int depth, const PP_Flash_Menu* menu) {
if (depth > kMaxMenuDepth || !menu)
return false;
++depth;
if (menu->count && !menu->items)
return false;
for (uint32_t i = 0; i < menu->count; ++i) {
if (!CheckMenuItem(depth, menu->items + i))
return false;
}
return true;
}
void WriteMenuItem(IPC::Message* m, const PP_Flash_MenuItem* menu_item) {
PP_Flash_MenuItem_Type type = menu_item->type;
m->WriteUInt32(type);
m->WriteString(menu_item->name ? menu_item->name : "");
m->WriteInt(menu_item->id);
IPC::ParamTraits<PP_Bool>::Write(m, menu_item->enabled);
IPC::ParamTraits<PP_Bool>::Write(m, menu_item->checked);
if (type == PP_FLASH_MENUITEM_TYPE_SUBMENU)
WriteMenu(m, menu_item->submenu);
}
void WriteMenu(IPC::Message* m, const PP_Flash_Menu* menu) {
m->WriteUInt32(menu->count);
for (uint32_t i = 0; i < menu->count; ++i)
WriteMenuItem(m, menu->items + i);
}
void FreeMenuItem(const PP_Flash_MenuItem* menu_item) {
if (menu_item->name)
delete [] menu_item->name;
if (menu_item->submenu)
FreeMenu(menu_item->submenu);
}
void FreeMenu(const PP_Flash_Menu* menu) {
if (menu->items) {
for (uint32_t i = 0; i < menu->count; ++i)
FreeMenuItem(menu->items + i);
delete [] menu->items;
}
delete menu;
}
bool ReadMenuItem(int depth,
const IPC::Message* m,
PickleIterator* iter,
PP_Flash_MenuItem* menu_item) {
uint32_t type;
if (!m->ReadUInt32(iter, &type))
return false;
if (type > PP_FLASH_MENUITEM_TYPE_SUBMENU)
return false;
menu_item->type = static_cast<PP_Flash_MenuItem_Type>(type);
std::string name;
if (!m->ReadString(iter, &name))
return false;
menu_item->name = new char[name.size() + 1];
std::copy(name.begin(), name.end(), menu_item->name);
menu_item->name[name.size()] = 0;
if (!m->ReadInt(iter, &menu_item->id))
return false;
if (!IPC::ParamTraits<PP_Bool>::Read(m, iter, &menu_item->enabled))
return false;
if (!IPC::ParamTraits<PP_Bool>::Read(m, iter, &menu_item->checked))
return false;
if (type == PP_FLASH_MENUITEM_TYPE_SUBMENU) {
menu_item->submenu = ReadMenu(depth, m, iter);
if (!menu_item->submenu)
return false;
}
return true;
}
PP_Flash_Menu* ReadMenu(int depth,
const IPC::Message* m,
PickleIterator* iter) {
if (depth > kMaxMenuDepth)
return NULL;
++depth;
PP_Flash_Menu* menu = new PP_Flash_Menu;
menu->items = NULL;
if (!m->ReadUInt32(iter, &menu->count)) {
FreeMenu(menu);
return NULL;
}
if (menu->count == 0)
return menu;
menu->items = new PP_Flash_MenuItem[menu->count];
memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count);
for (uint32_t i = 0; i < menu->count; ++i) {
if (!ReadMenuItem(depth, m, iter, menu->items + i)) {
FreeMenu(menu);
return NULL;
}
}
return menu;
}
} // anonymous namespace
SerializedFlashMenu::SerializedFlashMenu()
: pp_menu_(NULL),
own_menu_(false) {
}
SerializedFlashMenu::~SerializedFlashMenu() {
if (own_menu_)
FreeMenu(pp_menu_);
}
bool SerializedFlashMenu::SetPPMenu(const PP_Flash_Menu* menu) {
DCHECK(!pp_menu_);
if (!CheckMenu(0, menu))
return false;
pp_menu_ = menu;
own_menu_ = false;
return true;
}
void SerializedFlashMenu::WriteToMessage(IPC::Message* m) const {
WriteMenu(m, pp_menu_);
}
bool SerializedFlashMenu::ReadFromMessage(const IPC::Message* m,
PickleIterator* iter) {
DCHECK(!pp_menu_);
pp_menu_ = ReadMenu(0, m, iter);
if (!pp_menu_)
return false;
own_menu_ = true;
return true;
}
} // namespace proxy
} // namespace ppapi
<commit_msg>IPC: defend against excessive number of submenu entries in PPAPI message.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/proxy/serialized_flash_menu.h"
#include "ipc/ipc_message.h"
#include "ppapi/c/private/ppb_flash_menu.h"
#include "ppapi/proxy/ppapi_param_traits.h"
namespace ppapi {
namespace proxy {
namespace {
// Maximum depth of submenus allowed (e.g., 1 indicates that submenus are
// allowed, but not sub-submenus).
const int kMaxMenuDepth = 2;
const uint32_t kMaxMenuEntries = 1000;
bool CheckMenu(int depth, const PP_Flash_Menu* menu);
void FreeMenu(const PP_Flash_Menu* menu);
void WriteMenu(IPC::Message* m, const PP_Flash_Menu* menu);
PP_Flash_Menu* ReadMenu(int depth, const IPC::Message* m, PickleIterator* iter);
bool CheckMenuItem(int depth, const PP_Flash_MenuItem* item) {
if (item->type == PP_FLASH_MENUITEM_TYPE_SUBMENU)
return CheckMenu(depth, item->submenu);
return true;
}
bool CheckMenu(int depth, const PP_Flash_Menu* menu) {
if (depth > kMaxMenuDepth || !menu)
return false;
++depth;
if (menu->count && !menu->items)
return false;
for (uint32_t i = 0; i < menu->count; ++i) {
if (!CheckMenuItem(depth, menu->items + i))
return false;
}
return true;
}
void WriteMenuItem(IPC::Message* m, const PP_Flash_MenuItem* menu_item) {
PP_Flash_MenuItem_Type type = menu_item->type;
m->WriteUInt32(type);
m->WriteString(menu_item->name ? menu_item->name : "");
m->WriteInt(menu_item->id);
IPC::ParamTraits<PP_Bool>::Write(m, menu_item->enabled);
IPC::ParamTraits<PP_Bool>::Write(m, menu_item->checked);
if (type == PP_FLASH_MENUITEM_TYPE_SUBMENU)
WriteMenu(m, menu_item->submenu);
}
void WriteMenu(IPC::Message* m, const PP_Flash_Menu* menu) {
m->WriteUInt32(menu->count);
for (uint32_t i = 0; i < menu->count; ++i)
WriteMenuItem(m, menu->items + i);
}
void FreeMenuItem(const PP_Flash_MenuItem* menu_item) {
if (menu_item->name)
delete [] menu_item->name;
if (menu_item->submenu)
FreeMenu(menu_item->submenu);
}
void FreeMenu(const PP_Flash_Menu* menu) {
if (menu->items) {
for (uint32_t i = 0; i < menu->count; ++i)
FreeMenuItem(menu->items + i);
delete [] menu->items;
}
delete menu;
}
bool ReadMenuItem(int depth,
const IPC::Message* m,
PickleIterator* iter,
PP_Flash_MenuItem* menu_item) {
uint32_t type;
if (!m->ReadUInt32(iter, &type))
return false;
if (type > PP_FLASH_MENUITEM_TYPE_SUBMENU)
return false;
menu_item->type = static_cast<PP_Flash_MenuItem_Type>(type);
std::string name;
if (!m->ReadString(iter, &name))
return false;
menu_item->name = new char[name.size() + 1];
std::copy(name.begin(), name.end(), menu_item->name);
menu_item->name[name.size()] = 0;
if (!m->ReadInt(iter, &menu_item->id))
return false;
if (!IPC::ParamTraits<PP_Bool>::Read(m, iter, &menu_item->enabled))
return false;
if (!IPC::ParamTraits<PP_Bool>::Read(m, iter, &menu_item->checked))
return false;
if (type == PP_FLASH_MENUITEM_TYPE_SUBMENU) {
menu_item->submenu = ReadMenu(depth, m, iter);
if (!menu_item->submenu)
return false;
}
return true;
}
PP_Flash_Menu* ReadMenu(int depth,
const IPC::Message* m,
PickleIterator* iter) {
if (depth > kMaxMenuDepth)
return NULL;
++depth;
PP_Flash_Menu* menu = new PP_Flash_Menu;
menu->items = NULL;
if (!m->ReadUInt32(iter, &menu->count)) {
FreeMenu(menu);
return NULL;
}
if (menu->count == 0)
return menu;
if (menu->count > kMaxMenuEntries) {
FreeMenu(menu);
return NULL;
}
menu->items = new PP_Flash_MenuItem[menu->count];
memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count);
for (uint32_t i = 0; i < menu->count; ++i) {
if (!ReadMenuItem(depth, m, iter, menu->items + i)) {
FreeMenu(menu);
return NULL;
}
}
return menu;
}
} // anonymous namespace
SerializedFlashMenu::SerializedFlashMenu()
: pp_menu_(NULL),
own_menu_(false) {
}
SerializedFlashMenu::~SerializedFlashMenu() {
if (own_menu_)
FreeMenu(pp_menu_);
}
bool SerializedFlashMenu::SetPPMenu(const PP_Flash_Menu* menu) {
DCHECK(!pp_menu_);
if (!CheckMenu(0, menu))
return false;
pp_menu_ = menu;
own_menu_ = false;
return true;
}
void SerializedFlashMenu::WriteToMessage(IPC::Message* m) const {
WriteMenu(m, pp_menu_);
}
bool SerializedFlashMenu::ReadFromMessage(const IPC::Message* m,
PickleIterator* iter) {
DCHECK(!pp_menu_);
pp_menu_ = ReadMenu(0, m, iter);
if (!pp_menu_)
return false;
own_menu_ = true;
return true;
}
} // namespace proxy
} // namespace ppapi
<|endoftext|> |
<commit_before>/*
Copyright (C) 2019 The Falco Authors.
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 "webserver.h"
#include <catch.hpp>
TEST_CASE("webserver must accept invalid data", "[!hide][webserver][k8s_audit_handler][accept_data]")
{
// falco_engine* engine = new falco_engine();
// falco_outputs* outputs = new falco_outputs(engine);
// std::string errstr;
// std::string input("{\"kind\": 0}");
//k8s_audit_handler::accept_data(engine, outputs, input, errstr);
REQUIRE(1 == 1);
}<commit_msg>docs(tests/falco): license for webserver unit tests<commit_after>/*
Copyright (C) 2019 The Falco Authors.
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 "webserver.h"
#include <catch.hpp>
TEST_CASE("webserver must accept invalid data", "[!hide][webserver][k8s_audit_handler][accept_data]")
{
// falco_engine* engine = new falco_engine();
// falco_outputs* outputs = new falco_outputs(engine);
// std::string errstr;
// std::string input("{\"kind\": 0}");
//k8s_audit_handler::accept_data(engine, outputs, input, errstr);
REQUIRE(1 == 1);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 - 2016, Roland Bock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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 "TabSample.h"
#include <sqlpp11/mysql/mysql.h>
#include <sqlpp11/sqlpp11.h>
#include <cassert>
#include <iostream>
#include <vector>
const auto library_raii = sqlpp::mysql::scoped_library_initializer_t{};
namespace
{
const auto now = ::sqlpp::chrono::floor<::std::chrono::milliseconds>(std::chrono::system_clock::now());
const auto today = ::sqlpp::chrono::floor<::sqlpp::chrono::days>(now);
const auto yesterday = today - ::sqlpp::chrono::days{1};
template <typename L, typename R>
auto require_equal(int line, const L& l, const R& r) -> void
{
if (l != r)
{
std::cerr << line << ": ";
serialize(::sqlpp::wrap_operand_t<L>{l}, std::cerr);
std::cerr << " != ";
serialize(::sqlpp::wrap_operand_t<R>{r}, std::cerr);
std::cerr << "\n" ;
throw std::runtime_error("Unexpected result");
}
}
template <typename L, typename R>
auto require_close(int line, const L& l, const R& r) -> void
{
if (std::chrono::abs(l - r) > std::chrono::seconds{1})
{
std::cerr << line << ": abs(";
serialize(::sqlpp::wrap_operand_t<L>{l}, std::cerr);
std::cerr << " - ";
serialize(::sqlpp::wrap_operand_t<R>{r}, std::cerr);
std::cerr << ") > 1s\n" ;
throw std::runtime_error("Unexpected result");
}
}
}
namespace mysql = sqlpp::mysql;
int DateTime(int, char*[])
{
auto config = std::make_shared<mysql::connection_config>();
config->user = "root";
config->database = "sqlpp_mysql";
config->debug = true;
try
{
mysql::connection db(config);
}
catch (const std::exception& e)
{
std::cerr << "For testing, you'll need to create a database sqlpp_mysql for user root (no password)" << std::endl;
std::cerr << e.what() << std::endl;
return 1;
}
catch (...)
{
std::cerr << "Unknown exception during connect" << std::endl;
return 1;
}
try
{
mysql::connection db(config);
db.execute(R"(SET time_zone = '+00:00')"); // To force MySQL's CURRENT_TIMESTAMP into the right timezone
db.execute(R"(DROP TABLE IF EXISTS tab_date_time)");
db.execute(R"(CREATE TABLE tab_date_time (
col_day_point date,
col_time_point datetime(3),
col_date_time_point datetime DEFAULT CURRENT_TIMESTAMP
))");
const auto tab = TabDateTime{};
db(insert_into(tab).default_values());
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.is_null(), true);
require_equal(__LINE__, row.colDayPoint.value(), ::sqlpp::chrono::day_point{});
require_equal(__LINE__, row.colTimePoint.is_null(), true);
require_equal(__LINE__, row.colTimePoint.value(), ::sqlpp::chrono::microsecond_point{});
require_close(__LINE__, row.colDateTimePoint.value(), std::chrono::system_clock::now());
}
auto statement = db.prepare(select(tab.colDateTimePoint).from(tab).unconditionally());
for (const auto& row : db(statement))
{
require_equal(__LINE__, row.colDateTimePoint.is_null(), false);
require_close(__LINE__, row.colDateTimePoint.value(), std::chrono::system_clock::now());
}
db(update(tab).set(tab.colDayPoint = today, tab.colTimePoint = now).unconditionally());
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.value(), today);
require_equal(__LINE__, row.colTimePoint.value(), now);
}
db(update(tab).set(tab.colDayPoint = yesterday, tab.colTimePoint = today).unconditionally());
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.value(), yesterday);
require_equal(__LINE__, row.colTimePoint.value(), today);
}
auto x = update(tab)
.set(tab.colDayPoint = parameter(tab.colDayPoint), tab.colTimePoint = parameter(tab.colTimePoint))
.unconditionally();
auto prepared_update = db.prepare(
update(tab)
.set(tab.colDayPoint = parameter(tab.colDayPoint), tab.colTimePoint = parameter(tab.colTimePoint))
.unconditionally());
prepared_update.params.colDayPoint = today;
prepared_update.params.colTimePoint = now;
std::cout << "---- running prepared update ----" << std::endl;
db(prepared_update);
std::cout << "---- finished prepared update ----" << std::endl;
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.value(), today);
require_equal(__LINE__, row.colTimePoint.value(), now);
}
}
catch (const std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
catch (...)
{
std::cerr << "Unkown exception" << std::endl;
}
return 0;
}
<commit_msg>Fix compile error for c++11<commit_after>/*
* Copyright (c) 2013 - 2016, Roland Bock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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 "TabSample.h"
#include <sqlpp11/mysql/mysql.h>
#include <sqlpp11/sqlpp11.h>
#include <cassert>
#include <iostream>
#include <vector>
const auto library_raii = sqlpp::mysql::scoped_library_initializer_t{};
namespace
{
const auto now = ::sqlpp::chrono::floor<::std::chrono::milliseconds>(std::chrono::system_clock::now());
const auto today = ::sqlpp::chrono::floor<::sqlpp::chrono::days>(now);
const auto yesterday = today - ::sqlpp::chrono::days{1};
template <typename L, typename R>
auto require_equal(int line, const L& l, const R& r) -> void
{
if (l != r)
{
std::cerr << line << ": ";
serialize(::sqlpp::wrap_operand_t<L>{l}, std::cerr);
std::cerr << " != ";
serialize(::sqlpp::wrap_operand_t<R>{r}, std::cerr);
std::cerr << "\n" ;
throw std::runtime_error("Unexpected result");
}
}
template <typename L, typename R>
auto require_close(int line, const L& l, const R& r) -> void
{
if (date::abs(l - r) > std::chrono::seconds{1})
{
std::cerr << line << ": abs(";
serialize(::sqlpp::wrap_operand_t<L>{l}, std::cerr);
std::cerr << " - ";
serialize(::sqlpp::wrap_operand_t<R>{r}, std::cerr);
std::cerr << ") > 1s\n" ;
throw std::runtime_error("Unexpected result");
}
}
}
namespace mysql = sqlpp::mysql;
int DateTime(int, char*[])
{
auto config = std::make_shared<mysql::connection_config>();
config->user = "root";
config->database = "sqlpp_mysql";
config->debug = true;
try
{
mysql::connection db(config);
}
catch (const std::exception& e)
{
std::cerr << "For testing, you'll need to create a database sqlpp_mysql for user root (no password)" << std::endl;
std::cerr << e.what() << std::endl;
return 1;
}
catch (...)
{
std::cerr << "Unknown exception during connect" << std::endl;
return 1;
}
try
{
mysql::connection db(config);
db.execute(R"(SET time_zone = '+00:00')"); // To force MySQL's CURRENT_TIMESTAMP into the right timezone
db.execute(R"(DROP TABLE IF EXISTS tab_date_time)");
db.execute(R"(CREATE TABLE tab_date_time (
col_day_point date,
col_time_point datetime(3),
col_date_time_point datetime DEFAULT CURRENT_TIMESTAMP
))");
const auto tab = TabDateTime{};
db(insert_into(tab).default_values());
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.is_null(), true);
require_equal(__LINE__, row.colDayPoint.value(), ::sqlpp::chrono::day_point{});
require_equal(__LINE__, row.colTimePoint.is_null(), true);
require_equal(__LINE__, row.colTimePoint.value(), ::sqlpp::chrono::microsecond_point{});
require_close(__LINE__, row.colDateTimePoint.value(), std::chrono::system_clock::now());
}
auto statement = db.prepare(select(tab.colDateTimePoint).from(tab).unconditionally());
for (const auto& row : db(statement))
{
require_equal(__LINE__, row.colDateTimePoint.is_null(), false);
require_close(__LINE__, row.colDateTimePoint.value(), std::chrono::system_clock::now());
}
db(update(tab).set(tab.colDayPoint = today, tab.colTimePoint = now).unconditionally());
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.value(), today);
require_equal(__LINE__, row.colTimePoint.value(), now);
}
db(update(tab).set(tab.colDayPoint = yesterday, tab.colTimePoint = today).unconditionally());
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.value(), yesterday);
require_equal(__LINE__, row.colTimePoint.value(), today);
}
auto x = update(tab)
.set(tab.colDayPoint = parameter(tab.colDayPoint), tab.colTimePoint = parameter(tab.colTimePoint))
.unconditionally();
auto prepared_update = db.prepare(
update(tab)
.set(tab.colDayPoint = parameter(tab.colDayPoint), tab.colTimePoint = parameter(tab.colTimePoint))
.unconditionally());
prepared_update.params.colDayPoint = today;
prepared_update.params.colTimePoint = now;
std::cout << "---- running prepared update ----" << std::endl;
db(prepared_update);
std::cout << "---- finished prepared update ----" << std::endl;
for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally()))
{
require_equal(__LINE__, row.colDayPoint.value(), today);
require_equal(__LINE__, row.colTimePoint.value(), now);
}
}
catch (const std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
catch (...)
{
std::cerr << "Unkown exception" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2009 Peter Krusche, The University of Warwick *
* peter@dcs.warwick.ac.uk *
***************************************************************************/
#include "bsp_cpp/simplebsp.h"
#include <iostream>
void print_info (bsp::RunnableContext * ctx, int counter) {
using namespace std;
if (!ctx) {
bsp_abort("FUCK!");
}
if (ctx->bsp_parent() != NULL) {
cout << "Hi " <<
counter <<
"! I am sub-process number " <<
ctx->bsp_pid() << " out of " << ctx->bsp_nprocs()
<< " I live on node " << bsp_pid()
<< endl;
} else {
cout << "Hi " <<
counter <<
"! I am process number " <<
ctx->bsp_pid() << " out of " << ctx->bsp_nprocs()
<< " I live on node " << bsp_pid()
<< endl;
}
}
BSP_BEGIN();
using namespace std;
BSP_ONLY( 0 ) cout << "Hi, I am proc 0. I am special." << endl;
BSP_CONTEXT_BEGIN (
BSP_CONTEXT_VAR ( int counter )
);
using namespace std;
BSP_PARALLEL_BEGIN (
bsp_nprocs() * 4 // recursively increase number of processors
);
// this is done at node level
cout << "t:" << bsp_nthreads() << " p:" << bsp_nprocs() << endl;
BSP_SUPERSTEP_BEGIN() {
counter = 1;
print_info(bsp_context(), counter);
BSP_PARALLEL_BEGIN (
bsp_nprocs() // recursively increase number of processors
);
BSP_SUPERSTEP_BEGIN() {
counter = 1;
print_info(bsp_context(), counter);
}
BSP_SUPERSTEP_END();
BSP_SUPERSTEP_BEGIN() {
counter = 2;
print_info(bsp_context(), counter);
} BSP_SUPERSTEP_END();
BSP_PARALLEL_END ();
counter++;
} BSP_SUPERSTEP_END();
BSP_SUPERSTEP_BEGIN() {
counter++;
print_info(bsp_context(), counter);
} BSP_SUPERSTEP_END();
BSP_PARALLEL_END ();
BSP_CONTEXT_END ();
BSP_END();
<commit_msg><commit_after>/***************************************************************************
* Copyright (C) 2009 Peter Krusche, The University of Warwick *
* peter@dcs.warwick.ac.uk *
***************************************************************************/
#include "bsp_cpp/simplebsp.h"
#include <iostream>
#include <tbb/spin_mutex.h>
tbb::spin_mutex output_mutex;
void print_info (bsp::RunnableContext * ctx, int counter) {
using namespace std;
tbb::spin_mutex::scoped_lock l(output_mutex);
if (!ctx) {
bsp_abort("Can't print NULL context.");
}
if (ctx->bsp_parent() != NULL) {
cout << "Hi " <<
counter <<
"! I am sub-process number " <<
ctx->bsp_pid() << " out of " << ctx->bsp_nprocs()
<< " I live on node " << bsp_pid()
<< endl;
} else {
cout << "Hi " <<
counter <<
"! I am process number " <<
ctx->bsp_pid() << " out of " << ctx->bsp_nprocs()
<< " I live on node " << bsp_pid()
<< endl;
}
}
BSP_BEGIN();
using namespace std;
BSP_ONLY( 0 ) cout << "Hi, I am proc 0. I am special." << endl;
BSP_CONTEXT_BEGIN (
BSP_CONTEXT_VAR ( int counter )
);
using namespace std;
BSP_PARALLEL_BEGIN (
bsp_nprocs() * 4 // recursively increase number of processors
);
// this is done at node level
cout << "t:" << bsp_nthreads() << " p:" << bsp_nprocs() << endl;
BSP_SUPERSTEP_BEGIN() {
counter = 1;
print_info(bsp_context(), counter);
BSP_PARALLEL_BEGIN (
bsp_nprocs() // recursively increase number of processors
);
BSP_SUPERSTEP_BEGIN() {
counter = 1;
print_info(bsp_context(), counter);
}
BSP_SUPERSTEP_END();
BSP_SUPERSTEP_BEGIN() {
counter = 2;
print_info(bsp_context(), counter);
} BSP_SUPERSTEP_END();
BSP_PARALLEL_END ();
counter++;
} BSP_SUPERSTEP_END();
BSP_SUPERSTEP_BEGIN() {
counter++;
print_info(bsp_context(), counter);
} BSP_SUPERSTEP_END();
BSP_PARALLEL_END ();
BSP_CONTEXT_END ();
BSP_END();
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesOperator.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqNonEditableStyledItemDelegate.h>
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <pqView.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkPVDataSetAttributesInformation.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkAlgorithm.h>
#include <vtkDataArray.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkSMSourceProxy.h>
#include <QDebug>
#include <QDoubleValidator>
#include <QMainWindow>
namespace tomviz {
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: QWidget(parentObject), m_ui(new Ui::DataPropertiesPanel)
{
m_ui->setupUi(this);
m_ui->xLengthBox->setValidator(new QDoubleValidator(m_ui->xLengthBox));
m_ui->yLengthBox->setValidator(new QDoubleValidator(m_ui->yLengthBox));
m_ui->zLengthBox->setValidator(new QDoubleValidator(m_ui->zLengthBox));
QVBoxLayout* l = m_ui->verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", this);
l->insertWidget(l->indexOf(m_ui->FileName), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Original Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->OriginalDataRange), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Transformed Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->TransformedDataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Units and Size", this);
l->insertWidget(l->indexOf(m_ui->LengthWidget), separator);
m_tiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", this);
l->insertWidget(l->indexOf(m_ui->SetTiltAnglesButton), m_tiltAnglesSeparator);
clear();
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(updateAxesGridLabels()));
connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),
SLOT(updateAxesGridLabels()));
connect(m_ui->SetTiltAnglesButton, SIGNAL(clicked()), SLOT(setTiltAngles()));
connect(m_ui->unitBox, SIGNAL(editingFinished()), SLOT(updateUnits()));
connect(m_ui->xLengthBox, SIGNAL(editingFinished()), SLOT(updateXLength()));
connect(m_ui->yLengthBox, SIGNAL(editingFinished()), SLOT(updateYLength()));
connect(m_ui->zLengthBox, SIGNAL(editingFinished()), SLOT(updateZLength()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent* e)
{
updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (m_currentDataSource) {
disconnect(m_currentDataSource);
}
m_currentDataSource = dsource;
if (dsource) {
connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
scheduleUpdate();
}
namespace {
QString getDataDimensionsString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString =
QString("Dimensions: %1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
return extentString;
}
} // namespace
void DataPropertiesPanel::updateInformationWidget(
QTreeWidget* infoTreeWidget, vtkPVDataInformation* dataInfo)
{
infoTreeWidget->clear();
vtkPVDataSetAttributesInformation* pointDataInfo =
dataInfo->GetPointDataInformation();
if (pointDataInfo) {
QPixmap pointDataPixmap(":/pqWidgets/Icons/pqPointData16.png");
int numArrays = pointDataInfo->GetNumberOfArrays();
for (int i = 0; i < numArrays; i++) {
vtkPVArrayInformation* arrayInfo;
arrayInfo = pointDataInfo->GetArrayInformation(i);
// name, type, data range, data type
QTreeWidgetItem* item = new QTreeWidgetItem(infoTreeWidget);
item->setData(0, Qt::DisplayRole, arrayInfo->GetName());
QString dataType = vtkImageScalarTypeNameMacro(arrayInfo->GetDataType());
item->setData(2, Qt::DisplayRole, dataType);
int numComponents = arrayInfo->GetNumberOfComponents();
QString dataRange;
double range[2];
for (int j = 0; j < numComponents; j++) {
if (j != 0) {
dataRange.append(", ");
}
arrayInfo->GetComponentRange(j, range);
QString componentRange =
QString("[%1, %2]").arg(range[0]).arg(range[1]);
dataRange.append(componentRange);
}
item->setData(1, Qt::DisplayRole,
dataType == "string" ? tr("NA") : dataRange);
item->setData(1, Qt::ToolTipRole, dataRange);
item->setFlags(item->flags() | Qt::ItemIsEditable);
if (arrayInfo->GetIsPartial()) {
item->setForeground(0, QBrush(QColor("darkBlue")));
item->setData(0, Qt::DisplayRole,
QString("%1 (partial)").arg(arrayInfo->GetName()));
} else {
item->setForeground(0, QBrush(QColor("darkGreen")));
}
}
}
infoTreeWidget->header()->resizeSections(QHeaderView::ResizeToContents);
infoTreeWidget->setItemDelegate(new pqNonEditableStyledItemDelegate(this));
}
void DataPropertiesPanel::updateData()
{
if (!m_updateNeeded) {
return;
}
disconnect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
clear();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
m_ui->FileName->setText(dsource->filename());
m_ui->OriginalDataRange->setText(
getDataDimensionsString(dsource->originalDataSource()));
m_ui->TransformedDataRange->setText(
getDataDimensionsString(dsource->producer()));
int extent[6];
double spacing[3];
dsource->getExtent(extent);
dsource->getSpacing(spacing);
m_ui->xLengthBox->setText(
QString("%1").arg(spacing[0] * (extent[1] - extent[0])));
m_ui->yLengthBox->setText(
QString("%1").arg(spacing[1] * (extent[3] - extent[2])));
m_ui->zLengthBox->setText(
QString("%1").arg(spacing[2] * (extent[5] - extent[4])));
m_ui->unitBox->setText(m_currentDataSource->getUnits(0));
vtkSMSourceProxy* sourceProxy =
vtkSMSourceProxy::SafeDownCast(dsource->originalDataSource());
if (sourceProxy) {
updateInformationWidget(m_ui->OriginalDataTreeWidget,
sourceProxy->GetDataInformation());
}
sourceProxy = vtkSMSourceProxy::SafeDownCast(dsource->producer());
if (sourceProxy) {
updateInformationWidget(m_ui->TransformedDataTreeWidget,
sourceProxy->GetDataInformation());
}
// display tilt series data
if (dsource->type() == DataSource::TiltSeries) {
m_tiltAnglesSeparator->show();
m_ui->SetTiltAnglesButton->show();
m_ui->TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
m_ui->TiltAnglesTable->setRowCount(tiltAngles.size());
m_ui->TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i) {
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
m_ui->TiltAnglesTable->setItem(i, 0, item);
}
} else {
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->hide();
}
connect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
m_updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = m_currentDataSource;
// The table shouldn't be shown if this is not true, so this slot shouldn't be
// called
Q_ASSERT(dsource->type() == DataSource::TiltSeries);
QTableWidgetItem* item = m_ui->TiltAnglesTable->item(row, column);
auto ok = false;
auto value = item->data(Qt::DisplayRole).toDouble(&ok);
if (ok) {
auto needToAdd = false;
SetTiltAnglesOperator* op = nullptr;
if (dsource->operators().size() > 0) {
op = qobject_cast<SetTiltAnglesOperator*>(dsource->operators().last());
}
if (!op) {
op = new SetTiltAnglesOperator;
op->setParent(dsource);
needToAdd = true;
}
auto tiltAngles = op->tiltAngles();
tiltAngles[row] = value;
op->setTiltAngles(tiltAngles);
if (needToAdd) {
dsource->addOperator(op);
}
} else {
std::cerr << "Invalid tilt angle." << std::endl;
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = m_currentDataSource;
auto mainWindow = qobject_cast<QMainWindow*>(window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
m_updateNeeded = true;
if (isVisible()) {
updateData();
}
}
void DataPropertiesPanel::updateUnits()
{
if (m_currentDataSource) {
const QString& text = m_ui->unitBox->text();
m_currentDataSource->setUnits(text);
updateAxesGridLabels();
}
}
void DataPropertiesPanel::updateXLength()
{
const QString& text = m_ui->xLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse X Length string";
return;
}
updateSpacing(0, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateYLength()
{
const QString& text = m_ui->yLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Y Length string";
return;
}
updateSpacing(1, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateZLength()
{
const QString& text = m_ui->zLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Z Length string";
return;
}
updateSpacing(2, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateAxesGridLabels()
{
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
if (!view) {
return;
}
auto axesGrid = vtkSMPropertyHelper(view, "AxesGrid", true).GetAsProxy();
DataSource* ds = ActiveObjects::instance().activeDataSource();
if (!axesGrid || !ds) {
return;
}
QString xTitle = QString("X (%1)").arg(ds->getUnits(0));
QString yTitle = QString("Y (%1)").arg(ds->getUnits(1));
QString zTitle = QString("Z (%1)").arg(ds->getUnits(2));
vtkSMPropertyHelper(axesGrid, "XTitle").Set(xTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "YTitle").Set(yTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "ZTitle").Set(zTitle.toUtf8().data());
axesGrid->UpdateVTKObjects();
pqView* qtView =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (qtView) {
qtView->render();
}
}
void DataPropertiesPanel::clear()
{
m_ui->FileName->setText("");
m_ui->OriginalDataRange->setText("");
m_ui->TransformedDataRange->setText("");
if (m_colorMapWidget) {
m_ui->verticalLayout->removeWidget(m_colorMapWidget);
delete m_colorMapWidget;
}
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->clear();
m_ui->TiltAnglesTable->setRowCount(0);
m_ui->TiltAnglesTable->hide();
}
void DataPropertiesPanel::updateSpacing(int axis, double newLength)
{
if (!m_currentDataSource) {
return;
}
int extent[6];
double spacing[3];
m_currentDataSource->getExtent(extent);
m_currentDataSource->getSpacing(spacing);
spacing[axis] = newLength / (extent[2 * axis + 1] - extent[2 * axis]);
m_currentDataSource->setSpacing(spacing);
}
}
<commit_msg>Clear the data array tree widgets<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataPropertiesPanel.h"
#include "ui_DataPropertiesPanel.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "SetTiltAnglesOperator.h"
#include "SetTiltAnglesReaction.h"
#include "Utilities.h"
#include <pqNonEditableStyledItemDelegate.h>
#include <pqPropertiesPanel.h>
#include <pqProxyWidget.h>
#include <pqView.h>
#include <vtkDataSetAttributes.h>
#include <vtkPVArrayInformation.h>
#include <vtkPVDataInformation.h>
#include <vtkPVDataSetAttributesInformation.h>
#include <vtkSMPropertyHelper.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkAlgorithm.h>
#include <vtkDataArray.h>
#include <vtkDataObject.h>
#include <vtkFieldData.h>
#include <vtkSMSourceProxy.h>
#include <QDebug>
#include <QDoubleValidator>
#include <QMainWindow>
namespace tomviz {
DataPropertiesPanel::DataPropertiesPanel(QWidget* parentObject)
: QWidget(parentObject), m_ui(new Ui::DataPropertiesPanel)
{
m_ui->setupUi(this);
m_ui->xLengthBox->setValidator(new QDoubleValidator(m_ui->xLengthBox));
m_ui->yLengthBox->setValidator(new QDoubleValidator(m_ui->yLengthBox));
m_ui->zLengthBox->setValidator(new QDoubleValidator(m_ui->zLengthBox));
QVBoxLayout* l = m_ui->verticalLayout;
l->setSpacing(pqPropertiesPanel::suggestedVerticalSpacing());
// add separator labels.
QWidget* separator = pqProxyWidget::newGroupLabelWidget("Filename", this);
l->insertWidget(l->indexOf(m_ui->FileName), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Original Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->OriginalDataRange), separator);
separator =
pqProxyWidget::newGroupLabelWidget("Transformed Dimensions & Range", this);
l->insertWidget(l->indexOf(m_ui->TransformedDataRange), separator);
separator = pqProxyWidget::newGroupLabelWidget("Units and Size", this);
l->insertWidget(l->indexOf(m_ui->LengthWidget), separator);
m_tiltAnglesSeparator =
pqProxyWidget::newGroupLabelWidget("Tilt Angles", this);
l->insertWidget(l->indexOf(m_ui->SetTiltAnglesButton), m_tiltAnglesSeparator);
clear();
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(setDataSource(DataSource*)));
connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
SLOT(updateAxesGridLabels()));
connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),
SLOT(updateAxesGridLabels()));
connect(m_ui->SetTiltAnglesButton, SIGNAL(clicked()), SLOT(setTiltAngles()));
connect(m_ui->unitBox, SIGNAL(editingFinished()), SLOT(updateUnits()));
connect(m_ui->xLengthBox, SIGNAL(editingFinished()), SLOT(updateXLength()));
connect(m_ui->yLengthBox, SIGNAL(editingFinished()), SLOT(updateYLength()));
connect(m_ui->zLengthBox, SIGNAL(editingFinished()), SLOT(updateZLength()));
}
DataPropertiesPanel::~DataPropertiesPanel()
{
}
void DataPropertiesPanel::paintEvent(QPaintEvent* e)
{
updateData();
QWidget::paintEvent(e);
}
void DataPropertiesPanel::setDataSource(DataSource* dsource)
{
if (m_currentDataSource) {
disconnect(m_currentDataSource);
}
m_currentDataSource = dsource;
if (dsource) {
connect(dsource, SIGNAL(dataChanged()), SLOT(scheduleUpdate()),
Qt::UniqueConnection);
}
scheduleUpdate();
}
namespace {
QString getDataDimensionsString(vtkSMSourceProxy* proxy)
{
vtkPVDataInformation* info = proxy->GetDataInformation(0);
QString extentString =
QString("Dimensions: %1 x %2 x %3")
.arg(info->GetExtent()[1] - info->GetExtent()[0] + 1)
.arg(info->GetExtent()[3] - info->GetExtent()[2] + 1)
.arg(info->GetExtent()[5] - info->GetExtent()[4] + 1);
return extentString;
}
} // namespace
void DataPropertiesPanel::updateInformationWidget(
QTreeWidget* infoTreeWidget, vtkPVDataInformation* dataInfo)
{
infoTreeWidget->clear();
vtkPVDataSetAttributesInformation* pointDataInfo =
dataInfo->GetPointDataInformation();
if (pointDataInfo) {
QPixmap pointDataPixmap(":/pqWidgets/Icons/pqPointData16.png");
int numArrays = pointDataInfo->GetNumberOfArrays();
for (int i = 0; i < numArrays; i++) {
vtkPVArrayInformation* arrayInfo;
arrayInfo = pointDataInfo->GetArrayInformation(i);
// name, type, data range, data type
QTreeWidgetItem* item = new QTreeWidgetItem(infoTreeWidget);
item->setData(0, Qt::DisplayRole, arrayInfo->GetName());
QString dataType = vtkImageScalarTypeNameMacro(arrayInfo->GetDataType());
item->setData(2, Qt::DisplayRole, dataType);
int numComponents = arrayInfo->GetNumberOfComponents();
QString dataRange;
double range[2];
for (int j = 0; j < numComponents; j++) {
if (j != 0) {
dataRange.append(", ");
}
arrayInfo->GetComponentRange(j, range);
QString componentRange =
QString("[%1, %2]").arg(range[0]).arg(range[1]);
dataRange.append(componentRange);
}
item->setData(1, Qt::DisplayRole,
dataType == "string" ? tr("NA") : dataRange);
item->setData(1, Qt::ToolTipRole, dataRange);
item->setFlags(item->flags() | Qt::ItemIsEditable);
if (arrayInfo->GetIsPartial()) {
item->setForeground(0, QBrush(QColor("darkBlue")));
item->setData(0, Qt::DisplayRole,
QString("%1 (partial)").arg(arrayInfo->GetName()));
} else {
item->setForeground(0, QBrush(QColor("darkGreen")));
}
}
}
infoTreeWidget->header()->resizeSections(QHeaderView::ResizeToContents);
infoTreeWidget->setItemDelegate(new pqNonEditableStyledItemDelegate(this));
}
void DataPropertiesPanel::updateData()
{
if (!m_updateNeeded) {
return;
}
disconnect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)), this,
SLOT(onTiltAnglesModified(int, int)));
clear();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
m_ui->FileName->setText(dsource->filename());
m_ui->OriginalDataRange->setText(
getDataDimensionsString(dsource->originalDataSource()));
m_ui->TransformedDataRange->setText(
getDataDimensionsString(dsource->producer()));
int extent[6];
double spacing[3];
dsource->getExtent(extent);
dsource->getSpacing(spacing);
m_ui->xLengthBox->setText(
QString("%1").arg(spacing[0] * (extent[1] - extent[0])));
m_ui->yLengthBox->setText(
QString("%1").arg(spacing[1] * (extent[3] - extent[2])));
m_ui->zLengthBox->setText(
QString("%1").arg(spacing[2] * (extent[5] - extent[4])));
m_ui->unitBox->setText(m_currentDataSource->getUnits(0));
vtkSMSourceProxy* sourceProxy =
vtkSMSourceProxy::SafeDownCast(dsource->originalDataSource());
if (sourceProxy) {
updateInformationWidget(m_ui->OriginalDataTreeWidget,
sourceProxy->GetDataInformation());
}
sourceProxy = vtkSMSourceProxy::SafeDownCast(dsource->producer());
if (sourceProxy) {
updateInformationWidget(m_ui->TransformedDataTreeWidget,
sourceProxy->GetDataInformation());
}
// display tilt series data
if (dsource->type() == DataSource::TiltSeries) {
m_tiltAnglesSeparator->show();
m_ui->SetTiltAnglesButton->show();
m_ui->TiltAnglesTable->show();
QVector<double> tiltAngles = dsource->getTiltAngles();
m_ui->TiltAnglesTable->setRowCount(tiltAngles.size());
m_ui->TiltAnglesTable->setColumnCount(1);
for (int i = 0; i < tiltAngles.size(); ++i) {
QTableWidgetItem* item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, QString::number(tiltAngles[i]));
m_ui->TiltAnglesTable->setItem(i, 0, item);
}
} else {
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->hide();
}
connect(m_ui->TiltAnglesTable, SIGNAL(cellChanged(int, int)),
SLOT(onTiltAnglesModified(int, int)));
m_updateNeeded = false;
}
void DataPropertiesPanel::onTiltAnglesModified(int row, int column)
{
DataSource* dsource = m_currentDataSource;
// The table shouldn't be shown if this is not true, so this slot shouldn't be
// called
Q_ASSERT(dsource->type() == DataSource::TiltSeries);
QTableWidgetItem* item = m_ui->TiltAnglesTable->item(row, column);
auto ok = false;
auto value = item->data(Qt::DisplayRole).toDouble(&ok);
if (ok) {
auto needToAdd = false;
SetTiltAnglesOperator* op = nullptr;
if (dsource->operators().size() > 0) {
op = qobject_cast<SetTiltAnglesOperator*>(dsource->operators().last());
}
if (!op) {
op = new SetTiltAnglesOperator;
op->setParent(dsource);
needToAdd = true;
}
auto tiltAngles = op->tiltAngles();
tiltAngles[row] = value;
op->setTiltAngles(tiltAngles);
if (needToAdd) {
dsource->addOperator(op);
}
} else {
std::cerr << "Invalid tilt angle." << std::endl;
}
}
void DataPropertiesPanel::setTiltAngles()
{
DataSource* dsource = m_currentDataSource;
auto mainWindow = qobject_cast<QMainWindow*>(window());
SetTiltAnglesReaction::showSetTiltAnglesUI(mainWindow, dsource);
}
void DataPropertiesPanel::scheduleUpdate()
{
m_updateNeeded = true;
if (isVisible()) {
updateData();
}
}
void DataPropertiesPanel::updateUnits()
{
if (m_currentDataSource) {
const QString& text = m_ui->unitBox->text();
m_currentDataSource->setUnits(text);
updateAxesGridLabels();
}
}
void DataPropertiesPanel::updateXLength()
{
const QString& text = m_ui->xLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse X Length string";
return;
}
updateSpacing(0, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateYLength()
{
const QString& text = m_ui->yLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Y Length string";
return;
}
updateSpacing(1, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateZLength()
{
const QString& text = m_ui->zLengthBox->text();
auto ok = false;
double newLength = text.toDouble(&ok);
if (!ok) {
qWarning() << "Failed to parse Z Length string";
return;
}
updateSpacing(2, newLength);
updateData();
DataSource* dsource = m_currentDataSource;
if (!dsource) {
return;
}
emit dsource->dataPropertiesChanged();
}
void DataPropertiesPanel::updateAxesGridLabels()
{
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
if (!view) {
return;
}
auto axesGrid = vtkSMPropertyHelper(view, "AxesGrid", true).GetAsProxy();
DataSource* ds = ActiveObjects::instance().activeDataSource();
if (!axesGrid || !ds) {
return;
}
QString xTitle = QString("X (%1)").arg(ds->getUnits(0));
QString yTitle = QString("Y (%1)").arg(ds->getUnits(1));
QString zTitle = QString("Z (%1)").arg(ds->getUnits(2));
vtkSMPropertyHelper(axesGrid, "XTitle").Set(xTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "YTitle").Set(yTitle.toUtf8().data());
vtkSMPropertyHelper(axesGrid, "ZTitle").Set(zTitle.toUtf8().data());
axesGrid->UpdateVTKObjects();
pqView* qtView =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (qtView) {
qtView->render();
}
}
void DataPropertiesPanel::clear()
{
m_ui->FileName->setText("");
m_ui->OriginalDataRange->setText("");
m_ui->OriginalDataTreeWidget->clear();
m_ui->TransformedDataRange->setText("");
m_ui->TransformedDataTreeWidget->clear();
if (m_colorMapWidget) {
m_ui->verticalLayout->removeWidget(m_colorMapWidget);
delete m_colorMapWidget;
}
m_tiltAnglesSeparator->hide();
m_ui->SetTiltAnglesButton->hide();
m_ui->TiltAnglesTable->clear();
m_ui->TiltAnglesTable->setRowCount(0);
m_ui->TiltAnglesTable->hide();
}
void DataPropertiesPanel::updateSpacing(int axis, double newLength)
{
if (!m_currentDataSource) {
return;
}
int extent[6];
double spacing[3];
m_currentDataSource->getExtent(extent);
m_currentDataSource->getSpacing(spacing);
spacing[axis] = newLength / (extent[2 * axis + 1] - extent[2 * axis]);
m_currentDataSource->setSpacing(spacing);
}
}
<|endoftext|> |
<commit_before>//===-- Acceptor.cpp --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Acceptor.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ScopedPrinter.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Host/ConnectionFileDescriptor.h"
#include "lldb/Host/common/TCPSocket.h"
#include "Utility/UriParser.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::lldb_server;
using namespace llvm;
namespace {
struct SocketScheme {
const char *m_scheme;
const Socket::SocketProtocol m_protocol;
};
SocketScheme socket_schemes[] = {
{"tcp", Socket::ProtocolTcp},
{"udp", Socket::ProtocolUdp},
{"unix", Socket::ProtocolUnixDomain},
{"unix-abstract", Socket::ProtocolUnixAbstract},
};
bool FindProtocolByScheme(const char *scheme,
Socket::SocketProtocol &protocol) {
for (auto s : socket_schemes) {
if (!strcmp(s.m_scheme, scheme)) {
protocol = s.m_protocol;
return true;
}
}
return false;
}
const char *FindSchemeByProtocol(const Socket::SocketProtocol protocol) {
for (auto s : socket_schemes) {
if (s.m_protocol == protocol)
return s.m_scheme;
}
return nullptr;
}
}
Error Acceptor::Listen(int backlog) {
return m_listener_socket_up->Listen(StringRef(m_name), backlog);
}
Error Acceptor::Accept(const bool child_processes_inherit, Connection *&conn) {
Socket *conn_socket = nullptr;
auto error = m_listener_socket_up->Accept(
StringRef(m_name), child_processes_inherit, conn_socket);
if (error.Success())
conn = new ConnectionFileDescriptor(conn_socket);
return error;
}
Socket::SocketProtocol Acceptor::GetSocketProtocol() const {
return m_listener_socket_up->GetSocketProtocol();
}
const char *Acceptor::GetSocketScheme() const {
return FindSchemeByProtocol(GetSocketProtocol());
}
std::string Acceptor::GetLocalSocketId() const { return m_local_socket_id(); }
std::unique_ptr<Acceptor> Acceptor::Create(StringRef name,
const bool child_processes_inherit,
Error &error) {
error.Clear();
Socket::SocketProtocol socket_protocol = Socket::ProtocolUnixDomain;
int port;
StringRef scheme, host, path;
// Try to match socket name as URL - e.g., tcp://localhost:5555
if (UriParser::Parse(name.str(), scheme, host, port, path)) {
if (!FindProtocolByScheme(scheme.str().c_str(), socket_protocol))
error.SetErrorStringWithFormat("Unknown protocol scheme \"%s\"",
scheme.str().c_str());
else
name = name.drop_front(scheme.size() + strlen("://"));
} else {
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
// Try to match socket name as $host:port - e.g., localhost:5555
if (Socket::DecodeHostAndPort(name, host_str, port_str, port, nullptr))
socket_protocol = Socket::ProtocolTcp;
}
if (error.Fail())
return std::unique_ptr<Acceptor>();
std::unique_ptr<Socket> listener_socket_up =
Socket::Create(socket_protocol, child_processes_inherit, error);
LocalSocketIdFunc local_socket_id;
if (error.Success()) {
if (listener_socket_up->GetSocketProtocol() == Socket::ProtocolTcp) {
TCPSocket *tcp_socket =
static_cast<TCPSocket *>(listener_socket_up.get());
local_socket_id = [tcp_socket]() {
auto local_port = tcp_socket->GetLocalPortNumber();
return (local_port != 0) ? llvm::to_string(local_port) : "";
};
} else {
const std::string socket_name = name;
local_socket_id = [socket_name]() { return socket_name; };
}
return std::unique_ptr<Acceptor>(
new Acceptor(std::move(listener_socket_up), name, local_socket_id));
}
return std::unique_ptr<Acceptor>();
}
Acceptor::Acceptor(std::unique_ptr<Socket> &&listener_socket, StringRef name,
const LocalSocketIdFunc &local_socket_id)
: m_listener_socket_up(std::move(listener_socket)), m_name(name.str()),
m_local_socket_id(local_socket_id) {}
<commit_msg>Fix remote-linux regression due to stringRef changes<commit_after>//===-- Acceptor.cpp --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Acceptor.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ScopedPrinter.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Host/ConnectionFileDescriptor.h"
#include "lldb/Host/common/TCPSocket.h"
#include "Utility/UriParser.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::lldb_server;
using namespace llvm;
namespace {
struct SocketScheme {
const char *m_scheme;
const Socket::SocketProtocol m_protocol;
};
SocketScheme socket_schemes[] = {
{"tcp", Socket::ProtocolTcp},
{"udp", Socket::ProtocolUdp},
{"unix", Socket::ProtocolUnixDomain},
{"unix-abstract", Socket::ProtocolUnixAbstract},
};
bool FindProtocolByScheme(const char *scheme,
Socket::SocketProtocol &protocol) {
for (auto s : socket_schemes) {
if (!strcmp(s.m_scheme, scheme)) {
protocol = s.m_protocol;
return true;
}
}
return false;
}
const char *FindSchemeByProtocol(const Socket::SocketProtocol protocol) {
for (auto s : socket_schemes) {
if (s.m_protocol == protocol)
return s.m_scheme;
}
return nullptr;
}
}
Error Acceptor::Listen(int backlog) {
return m_listener_socket_up->Listen(StringRef(m_name), backlog);
}
Error Acceptor::Accept(const bool child_processes_inherit, Connection *&conn) {
Socket *conn_socket = nullptr;
auto error = m_listener_socket_up->Accept(
StringRef(m_name), child_processes_inherit, conn_socket);
if (error.Success())
conn = new ConnectionFileDescriptor(conn_socket);
return error;
}
Socket::SocketProtocol Acceptor::GetSocketProtocol() const {
return m_listener_socket_up->GetSocketProtocol();
}
const char *Acceptor::GetSocketScheme() const {
return FindSchemeByProtocol(GetSocketProtocol());
}
std::string Acceptor::GetLocalSocketId() const { return m_local_socket_id(); }
std::unique_ptr<Acceptor> Acceptor::Create(StringRef name,
const bool child_processes_inherit,
Error &error) {
error.Clear();
Socket::SocketProtocol socket_protocol = Socket::ProtocolUnixDomain;
int port;
StringRef scheme, host, path;
// Try to match socket name as URL - e.g., tcp://localhost:5555
if (UriParser::Parse(name, scheme, host, port, path)) {
if (!FindProtocolByScheme(scheme.str().c_str(), socket_protocol))
error.SetErrorStringWithFormat("Unknown protocol scheme \"%s\"",
scheme.str().c_str());
else
name = name.drop_front(scheme.size() + strlen("://"));
} else {
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
// Try to match socket name as $host:port - e.g., localhost:5555
if (Socket::DecodeHostAndPort(name, host_str, port_str, port, nullptr))
socket_protocol = Socket::ProtocolTcp;
}
if (error.Fail())
return std::unique_ptr<Acceptor>();
std::unique_ptr<Socket> listener_socket_up =
Socket::Create(socket_protocol, child_processes_inherit, error);
LocalSocketIdFunc local_socket_id;
if (error.Success()) {
if (listener_socket_up->GetSocketProtocol() == Socket::ProtocolTcp) {
TCPSocket *tcp_socket =
static_cast<TCPSocket *>(listener_socket_up.get());
local_socket_id = [tcp_socket]() {
auto local_port = tcp_socket->GetLocalPortNumber();
return (local_port != 0) ? llvm::to_string(local_port) : "";
};
} else {
const std::string socket_name = name;
local_socket_id = [socket_name]() { return socket_name; };
}
return std::unique_ptr<Acceptor>(
new Acceptor(std::move(listener_socket_up), name, local_socket_id));
}
return std::unique_ptr<Acceptor>();
}
Acceptor::Acceptor(std::unique_ptr<Socket> &&listener_socket, StringRef name,
const LocalSocketIdFunc &local_socket_id)
: m_listener_socket_up(std::move(listener_socket)), m_name(name.str()),
m_local_socket_id(local_socket_id) {}
<|endoftext|> |
<commit_before>/*
* Copyright 2017, International Business Machines
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include "ap_int.h"
#include <hls_stream.h>
#include "action_bfs.H"
typedef ap_uint<VEX_WIDTH> Q_t;
//--------------------------------------------------------------------------------------------
// WRITE DATA TO MEMORY
short write_burst_of_data_to_mem(snap_membus_t *dout_gmem, snap_membus_t *d_ddrmem,
snapu16_t memory_type, snapu64_t output_address,
snap_membus_t *buffer, snapu64_t size_in_bytes_to_transfer)
{
short rc;
switch (memory_type) {
case HOST_DRAM:
memcpy((snap_membus_t *) (dout_gmem + output_address),
buffer, size_in_bytes_to_transfer);
rc = 0;
break;
case CARD_DRAM:
memcpy((snap_membus_t *) (d_ddrmem + output_address),
buffer, size_in_bytes_to_transfer);
rc = 0;
break;
default:
rc = 1;
}
return rc;
}
// READ DATA FROM MEMORY
short read_burst_of_data_from_mem(snap_membus_t *din_gmem, snap_membus_t *d_ddrmem,
snapu16_t memory_type, snapu64_t input_address,
snap_membus_t *buffer, snapu64_t size_in_bytes_to_transfer)
{
short rc;
switch (memory_type) {
case HOST_DRAM:
memcpy(buffer, (snap_membus_t *) (din_gmem + input_address),
size_in_bytes_to_transfer);
rc = 0;
break;
case CARD_DRAM:
memcpy(buffer, (snap_membus_t *) (d_ddrmem + input_address),
size_in_bytes_to_transfer);
rc = 0;
break;
default:
rc = 1;
}
return rc;
}
//--------------------------------------------------------------------------------------------
//--- MAIN PROGRAM ---------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
void action_wrapper(snap_membus_t *din_gmem, snap_membus_t *dout_gmem,
snap_membus_t *d_ddrmem,
action_reg *Action_Register, action_RO_config_reg *Action_Config)
{
// Host Memory AXI Interface
#pragma HLS INTERFACE m_axi port=din_gmem bundle=host_mem offset=slave depth=512
#pragma HLS INTERFACE m_axi port=dout_gmem bundle=host_mem offset=slave depth=512
#pragma HLS INTERFACE s_axilite port=din_gmem bundle=ctrl_reg offset=0x030
#pragma HLS INTERFACE s_axilite port=dout_gmem bundle=ctrl_reg offset=0x040
//DDR memory Interface
#pragma HLS INTERFACE m_axi port=d_ddrmem bundle=card_mem0 offset=slave depth=512
#pragma HLS INTERFACE s_axilite port=d_ddrmem bundle=ctrl_reg offset=0x050
// Host Memory AXI Lite Master Interface
#pragma HLS DATA_PACK variable=Action_Config
#pragma HLS INTERFACE s_axilite port=Action_Config bundle=ctrl_reg offset=0x010
#pragma HLS DATA_PACK variable=Action_Register
#pragma HLS INTERFACE s_axilite port=Action_Register bundle=ctrl_reg offset=0x100
#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg
// Hardcoded numbers
Action_Config->action_type = (snapu32_t) BFS_ACTION_TYPE;
Action_Config->release_level = (snapu32_t) RELEASE_LEVEL;
// VARIABLES
short rc=0;
snapu32_t ReturnCode;
snapu64_t INPUT_ADDRESS;
snapu64_t OUTPUT_ADDRESS;
snapu64_t fetch_address;
snapu64_t commit_address;
ap_uint<1> visited[MAX_VEX_NUM];
ap_uint<VEX_WIDTH> i,j, root, current, vex_num;
ap_uint<VEX_WIDTH> vnode_cnt;
snapu32_t vnode_place;
snapu64_t edgelink_ptr;
ap_uint<VEX_WIDTH> adjvex;
snap_membus_t buf_node[1];
snap_membus_t buf_out[1];
ap_uint<4> idx;
if(Action_Register->Control.sat == 0x04)
{
//== Parameters fetched in memory ==
//==================================
// byte address received need to be aligned with port width
INPUT_ADDRESS = Action_Register->Data.input_adjtable_address;
OUTPUT_ADDRESS = Action_Register->Data.output_address;
commit_address = OUTPUT_ADDRESS;
vex_num = Action_Register->Data.input_vex_num;
ReturnCode = RET_CODE_OK;
//define a local BRAM to hold VNODE:
// MAX_VEX_NUM * VNODE_SIZE
snap_membus_t vnode_array[MAX_VEX_NUM/(BPERDW/VNODE_SIZE)];
//Initialize it with burst read
//It will improve the performance a lot.
rc = read_burst_of_data_from_mem(din_gmem, d_ddrmem, Action_Register->Data.input_type,
(INPUT_ADDRESS>>ADDR_RIGHT_SHIFT), vnode_array, vex_num*VNODE_SIZE);
// A 512*512bits only takes 15 BRAM_18K, XCKU060 has 2160 in total. Less than 1%
// But It may harm the timing when this array size increased.
L0: for (root = 0; root < vex_num; root ++)
{
#if defined(NO_SYNTH)
printf("***Handling root = %d ***\n", root);
#endif
hls::stream <Q_t> Q;
#pragma HLS stream depth=2048 variable=Q
for (i = 0; i < vex_num; i ++)
{
#pragma HLS UNROLL factor=128
visited[i] = 0;
}
buf_out[0] = 0;
vnode_cnt = 0;
vnode_place = 0;
buf_out[0](31,0) = root;
vnode_cnt ++;
vnode_place += 32;
visited[root]=1;
Q.write(root);
while (!Q.empty())
{
current = Q.read();
idx = current (1,0);
edgelink_ptr = (snapu64_t)(vnode_array[current/4](128*idx+63, 128*idx+0));
while (edgelink_ptr != 0) //judge with NULL
{
//Update fetch address
fetch_address = edgelink_ptr;
idx = edgelink_ptr(5,4);
//Read next edge
rc |= read_burst_of_data_from_mem(din_gmem, d_ddrmem, Action_Register->Data.input_type,
(fetch_address>>ADDR_RIGHT_SHIFT), buf_node, BPERDW);
edgelink_ptr = (snapu64_t)(buf_node[0](128*idx + 63, 128*idx));
adjvex = (snapu32_t)(buf_node[0](128*idx + 95, 128*idx + 64));
if(!visited[adjvex])
{
visited[adjvex] = 1;
Q.write(adjvex);
buf_out[0](vnode_place+31, vnode_place) = adjvex;
vnode_cnt ++;
vnode_place += 32;
//Commit buf_out if MEMDW is fulfilled
if(vnode_place >= MEMDW)
{
rc |= write_burst_of_data_to_mem(din_gmem, d_ddrmem, Action_Register->Data.output_type,
(commit_address>>ADDR_RIGHT_SHIFT), buf_out, BPERDW);
buf_out[0] = 0;
vnode_place = 0;
commit_address += BPERDW;
}
}
}
}
//Last node
buf_out[0](vnode_place+31, vnode_place) = 0xFF000000 + vnode_cnt;
rc |= write_burst_of_data_to_mem(din_gmem, d_ddrmem, Action_Register->Data.output_type,
(commit_address>>ADDR_RIGHT_SHIFT), buf_out, BPERDW);
buf_out[0] = 0;
vnode_place = 0;
commit_address += BPERDW;
//Update register
Action_Register->Data.status_pos = commit_address(31,0);
Action_Register->Data.status_vex = root;
}
if(rc!=0)
ReturnCode = RET_CODE_FAILURE;
//Update register
Action_Register->Data.status_pos = commit_address(31,0);
Action_Register->Data.status_vex = root;
Action_Register->Control.Retc = (snapu32_t) ReturnCode;
}
return;
}
<commit_msg>old version to be merged<commit_after>/*
* Copyright 2017, International Business Machines
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include "ap_int.h"
#include <hls_stream.h>
#include "bfs.h"
typedef ap_uint<VEX_WIDTH> Q_t;
//--------------------------------------------------------------------------------------------
// WRITE RESULTS IN MMIO REGS
void write_results_in_BFS_regs(action_output_reg *Action_Output, action_input_reg *Action_Input,
ap_uint<32>ReturnCode, ap_uint<VEX_WIDTH> current_vex, ap_uint<32> current_pos)
{
// Always check that ALL Outputs are tied to a value or HLS will generate a
// Action_Output_i and a Action_Output_o registers and address to read results
// will be shifted ...and wrong
// => easy checking in generated files : grep 0x184 hls_action_ctrl_reg_s_axi.vhd
//
Action_Output->Retc = (ap_uint<32>) ReturnCode;
Action_Output->Reserved = 0;
Action_Output->Data.action_version = RELEASE_VERSION;
// Registers unchanged
Action_Output->Data.input_adjtable_address = Action_Input->Data.input_adjtable_address;
Action_Output->Data.input_type = Action_Input->Data.input_type;
Action_Output->Data.input_flags = Action_Input->Data.input_flags;
Action_Output->Data.input_vex_num = Action_Input->Data.input_vex_num;
Action_Output->Data.output_address = Action_Input->Data.output_address;
Action_Output->Data.output_type = Action_Input->Data.output_type;
Action_Output->Data.output_flags = Action_Input->Data.output_flags;
Action_Output->Data.status_pos = current_pos;
Action_Output->Data.status_vex = current_vex;
Action_Output->Data.unused = 0;
}
//--------------------------------------------------------------------------------------------
//--- MAIN PROGRAM ---------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
void hls_action(ap_uint<MEMDW> *din_gmem, ap_uint<MEMDW> *dout_gmem,
ap_uint<MEMDW> *d_ddrmem,
action_input_reg *Action_Input, action_output_reg *Action_Output)
{
// Host Memory AXI Interface
#pragma HLS INTERFACE m_axi port=din_gmem bundle=host_mem
#pragma HLS INTERFACE m_axi port=dout_gmem bundle=host_mem
#pragma HLS INTERFACE s_axilite port=din_gmem bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite port=dout_gmem bundle=ctrl_reg
//DDR memory Interface
#pragma HLS INTERFACE m_axi port=d_ddrmem bundle=card_mem0 offset=slave
#pragma HLS INTERFACE s_axilite port=d_ddrmem bundle=ctrl_reg
// Host Memory AXI Lite Master Interface
#pragma HLS DATA_PACK variable=Action_Input
#pragma HLS INTERFACE s_axilite port=Action_Input offset=0x080 bundle=ctrl_reg
#pragma HLS DATA_PACK variable=Action_Output
#pragma HLS INTERFACE s_axilite port=Action_Output offset=0x104 bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg
// VARIABLES
short rc;
ap_uint<32> ReturnCode;
ap_uint<64> INPUT_ADDRESS;
ap_uint<64> OUTPUT_ADDRESS;
ap_uint<64> fetch_address;
ap_uint<64> commit_address;
ap_uint<1> visited[MAX_VEX_NUM];
ap_uint<VEX_WIDTH> i,j, root, current, vex_num;
ap_uint<VEX_WIDTH> vnode_cnt;
ap_uint<32> vnode_place;
ap_uint<64> edgelink_ptr;
ap_uint<VEX_WIDTH> adjvex;
ap_uint<MEMDW> buf_node[1];
ap_uint<MEMDW> buf_out[1];
ap_uint<4> idx;
//== Parameters fetched in memory ==
//==================================
// byte address received need to be aligned with port width
INPUT_ADDRESS = Action_Input->Data.input_adjtable_address;
OUTPUT_ADDRESS = Action_Input->Data.output_address;
commit_address = OUTPUT_ADDRESS;
vex_num = Action_Input->Data.input_vex_num;
ReturnCode = RET_CODE_OK;
if(Action_Input->Control.action == BFS_ACTION_TYPE) {
//define a local BRAM to hold VNODE:
// MAX_VEX_NUM * VNODE_SIZE
ap_uint<MEMDW> vnode_array[MAX_VEX_NUM/(BPERDW/VNODE_SIZE)];
//Initialize it with burst read
//It will improve the performance a lot.
rc = read_burst_of_data_from_mem(din_gmem, d_ddrmem, Action_Input->Data.input_type,
(INPUT_ADDRESS>>ADDR_RIGHT_SHIFT), vnode_array, vex_num*VNODE_SIZE);
// A 512*512bits only takes 15 BRAM_18K, XCKU060 has 2160 in total. Less than 1%
// But It may harm the timing when this array size increased.
L0: for (root = 0; root < vex_num; root ++)
{
#if defined(NO_SYNTH)
printf("***Handling root = %d ***\n", root);
#endif
hls::stream <Q_t> Q;
#pragma HLS stream depth=2048 variable=Q
for (i = 0; i < vex_num; i ++)
{
#pragma HLS UNROLL factor=128
visited[i] = 0;
}
buf_out[0] = 0;
vnode_cnt = 0;
vnode_place = 0;
buf_out[0](31,0) = root;
vnode_cnt ++;
vnode_place += 32;
visited[root]=1;
Q.write(root);
while (!Q.empty())
{
current = Q.read();
idx = current (1,0);
edgelink_ptr = (ap_uint<64>)(vnode_array[current/4](128*idx+63, 128*idx+0));
while (edgelink_ptr != 0) //judge with NULL
{
//Update fetch address
fetch_address = edgelink_ptr;
idx = edgelink_ptr(5,4);
//Read next edge
rc |= read_burst_of_data_from_mem(din_gmem, d_ddrmem, Action_Input->Data.input_type,
(fetch_address>>ADDR_RIGHT_SHIFT), buf_node, BPERDW);
edgelink_ptr = (ap_uint<64>)(buf_node[0](128*idx + 63, 128*idx));
adjvex = (ap_uint<32>)(buf_node[0](128*idx + 95, 128*idx + 64));
if(!visited[adjvex])
{
visited[adjvex] = 1;
Q.write(adjvex);
buf_out[0](vnode_place+31, vnode_place) = adjvex;
vnode_cnt ++;
vnode_place += 32;
//Commit buf_out if MEMDW is fulfilled
if(vnode_place >= MEMDW)
{
rc |= write_burst_of_data_to_mem(din_gmem, d_ddrmem, Action_Input->Data.output_type,
(commit_address>>ADDR_RIGHT_SHIFT), buf_out, BPERDW);
buf_out[0] = 0;
vnode_place = 0;
commit_address += BPERDW;
}
}
}
}
//Last node
buf_out[0](vnode_place+31, vnode_place) = 0xFF000000 + vnode_cnt;
rc |= write_burst_of_data_to_mem(din_gmem, d_ddrmem, Action_Input->Data.output_type,
(commit_address>>ADDR_RIGHT_SHIFT), buf_out, BPERDW);
buf_out[0] = 0;
vnode_place = 0;
commit_address += BPERDW;
write_results_in_BFS_regs(Action_Output, Action_Input, ReturnCode, root, commit_address(31,0) );
}
}
else // unknown action
ReturnCode = RET_CODE_FAILURE;
if(rc!=0)
ReturnCode = RET_CODE_FAILURE;
write_results_in_BFS_regs(Action_Output, Action_Input, ReturnCode, root, commit_address(31,0));
return;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EventOASISTContext.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:52:28 $
*
* 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 _XMLOFF_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif
#include <hash_map>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
class XMLTransformerOASISEventMap_Impl:
public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
NameHash_Impl, NameHash_Impl >
{
public:
XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
~XMLTransformerOASISEventMap_Impl();
};
XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
if( pInit )
{
XMLTransformerOASISEventMap_Impl::key_type aKey;
XMLTransformerOASISEventMap_Impl::data_type aData;
while( pInit->m_pOASISName )
{
aKey.m_nPrefix = pInit->m_nOASISPrefix;
aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);
OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );
aData = OUString::createFromAscii(pInit->m_pOOoName);
XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );
insert( aVal );
++pInit;
}
}
}
XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);
XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLRenameElemTransformerContext( rImp, rQName,
rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}
XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateFormEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}
void XMLEventOASISTransformerContext::FlushEventMap(
XMLTransformerOASISEventMap_Impl *p )
{
delete p;
}
OUString XMLEventOASISTransformerContext::GetEventName(
sal_uInt16 nPrefix,
const OUString& rName,
XMLTransformerOASISEventMap_Impl& rMap,
XMLTransformerOASISEventMap_Impl *pMap2)
{
XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
if( pMap2 )
{
XMLTransformerOASISEventMap_Impl::const_iterator aIter =
pMap2->find( aKey );
if( !(aIter == pMap2->end()) )
return (*aIter).second;
}
XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
if( aIter == rMap.end() )
return rName;
else
return (*aIter).second;
}
bool ParseURLAsString(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );
sal_Int32 params = rAttrValue.indexOf( '?' );
if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
{
return FALSE;
}
sal_Int32 start = SCHEME.getLength();
*pName = rAttrValue.copy( start, params - start );
OUString aToken;
OUString aLanguage;
params++;
do
{
aToken = rAttrValue.getToken( 0, '&', params );
sal_Int32 dummy = 0;
if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
{
aLanguage = aToken.getToken( 1, '=', dummy );
}
else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
{
OUString tmp = aToken.getToken( 1, '=', dummy );
if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
{
*pLocation = GetXMLToken( XML_DOCUMENT );
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
}
} while ( params >= 0 );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
return TRUE;
}
return FALSE;
}
bool ParseURL(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
return ParseURLAsString( rAttrValue, pName, pLocation );
#else
Reference< com::sun::star::lang::XMultiServiceFactory >
xSMgr = ::comphelper::getProcessServiceFactory();
Reference< com::sun::star::uri::XUriReferenceFactory >
xFactory( xSMgr->createInstance( OUString::createFromAscii(
"com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );
if ( xFactory.is() )
{
Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
xFactory->parse( rAttrValue ), UNO_QUERY );
if ( xUrl.is() )
{
OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
{
OUString aLanguage = xUrl->getParameter( aLanguageKey );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
*pName = xUrl->getName();
OUString tmp =
xUrl->getParameter( GetXMLToken( XML_LOCATION ) );
OUString doc = GetXMLToken( XML_DOCUMENT );
if ( tmp.equalsIgnoreAsciiCase( doc ) )
{
*pLocation = doc;
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
return TRUE;
}
}
}
return FALSE;
}
else
{
return ParseURLAsString( rAttrValue, pName, pLocation );
}
#endif
}
void XMLEventOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
OSL_TRACE("XMLEventOASISTransformerContext::StartElement");
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_HREF:
{
OUString aAttrValue( rAttrValue );
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->RemoveAttributeByIndex( i );
OUString aAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
}
break;
case XML_ATACTION_EVENT_NAME:
{
// Check if the event belongs to a form or control by
// cehcking the 2nd ancestor element, f.i.:
// <form:button><form:event-listeners><form:event-listener>
const XMLTransformerContext *pObjContext =
GetTransformer().GetAncestorContext( 1 );
sal_Bool bForm = pObjContext &&
pObjContext->HasNamespace(XML_NAMESPACE_FORM );
pMutableAttrList->SetValueByIndex( i,
GetTransformer().GetEventName( rAttrValue,
bForm ) );
}
break;
case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
{
OUString aAttrValue( rAttrValue );
sal_uInt16 nValPrefix =
static_cast<sal_uInt16>((*aIter).second.m_nParam1);
if( GetTransformer().RemoveNamespacePrefix(
aAttrValue, nValPrefix ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_MACRO_NAME:
{
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->SetValueByIndex( i, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
else
{
const OUString& rApp = GetXMLToken( XML_APPLICATION );
const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
OUString aAttrValue;
if( rAttrValue.getLength() > rApp.getLength()+1 &&
rAttrValue.copy(0,rApp.getLength()).
equalsIgnoreAsciiCase( rApp ) &&
':' == rAttrValue[rApp.getLength()] )
{
aLocation = rApp;
aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
}
else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
rAttrValue.copy(0,rDoc.getLength()).
equalsIgnoreAsciiCase( rDoc ) &&
':' == rAttrValue[rDoc.getLength()] )
{
aLocation= rDoc;
aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
}
if( aAttrValue.getLength() )
pMutableAttrList->SetValueByIndex( i,
aAttrValue );
if( aLocation.getLength() )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
// draw bug
aAttrQName = GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LIBRARY ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
}
}
}
break;
case XML_ATACTION_COPY:
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.34); FILE MERGED 2006/09/01 18:00:15 kaib 1.6.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EventOASISTContext.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:23:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif
#include <hash_map>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
class XMLTransformerOASISEventMap_Impl:
public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
NameHash_Impl, NameHash_Impl >
{
public:
XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
~XMLTransformerOASISEventMap_Impl();
};
XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
if( pInit )
{
XMLTransformerOASISEventMap_Impl::key_type aKey;
XMLTransformerOASISEventMap_Impl::data_type aData;
while( pInit->m_pOASISName )
{
aKey.m_nPrefix = pInit->m_nOASISPrefix;
aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);
OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );
aData = OUString::createFromAscii(pInit->m_pOOoName);
XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );
insert( aVal );
++pInit;
}
}
}
XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);
XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLRenameElemTransformerContext( rImp, rQName,
rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}
XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateFormEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}
void XMLEventOASISTransformerContext::FlushEventMap(
XMLTransformerOASISEventMap_Impl *p )
{
delete p;
}
OUString XMLEventOASISTransformerContext::GetEventName(
sal_uInt16 nPrefix,
const OUString& rName,
XMLTransformerOASISEventMap_Impl& rMap,
XMLTransformerOASISEventMap_Impl *pMap2)
{
XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
if( pMap2 )
{
XMLTransformerOASISEventMap_Impl::const_iterator aIter =
pMap2->find( aKey );
if( !(aIter == pMap2->end()) )
return (*aIter).second;
}
XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
if( aIter == rMap.end() )
return rName;
else
return (*aIter).second;
}
bool ParseURLAsString(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );
sal_Int32 params = rAttrValue.indexOf( '?' );
if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
{
return FALSE;
}
sal_Int32 start = SCHEME.getLength();
*pName = rAttrValue.copy( start, params - start );
OUString aToken;
OUString aLanguage;
params++;
do
{
aToken = rAttrValue.getToken( 0, '&', params );
sal_Int32 dummy = 0;
if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
{
aLanguage = aToken.getToken( 1, '=', dummy );
}
else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
{
OUString tmp = aToken.getToken( 1, '=', dummy );
if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
{
*pLocation = GetXMLToken( XML_DOCUMENT );
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
}
} while ( params >= 0 );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
return TRUE;
}
return FALSE;
}
bool ParseURL(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
return ParseURLAsString( rAttrValue, pName, pLocation );
#else
Reference< com::sun::star::lang::XMultiServiceFactory >
xSMgr = ::comphelper::getProcessServiceFactory();
Reference< com::sun::star::uri::XUriReferenceFactory >
xFactory( xSMgr->createInstance( OUString::createFromAscii(
"com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );
if ( xFactory.is() )
{
Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
xFactory->parse( rAttrValue ), UNO_QUERY );
if ( xUrl.is() )
{
OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
{
OUString aLanguage = xUrl->getParameter( aLanguageKey );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
*pName = xUrl->getName();
OUString tmp =
xUrl->getParameter( GetXMLToken( XML_LOCATION ) );
OUString doc = GetXMLToken( XML_DOCUMENT );
if ( tmp.equalsIgnoreAsciiCase( doc ) )
{
*pLocation = doc;
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
return TRUE;
}
}
}
return FALSE;
}
else
{
return ParseURLAsString( rAttrValue, pName, pLocation );
}
#endif
}
void XMLEventOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
OSL_TRACE("XMLEventOASISTransformerContext::StartElement");
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_HREF:
{
OUString aAttrValue( rAttrValue );
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->RemoveAttributeByIndex( i );
OUString aAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
}
break;
case XML_ATACTION_EVENT_NAME:
{
// Check if the event belongs to a form or control by
// cehcking the 2nd ancestor element, f.i.:
// <form:button><form:event-listeners><form:event-listener>
const XMLTransformerContext *pObjContext =
GetTransformer().GetAncestorContext( 1 );
sal_Bool bForm = pObjContext &&
pObjContext->HasNamespace(XML_NAMESPACE_FORM );
pMutableAttrList->SetValueByIndex( i,
GetTransformer().GetEventName( rAttrValue,
bForm ) );
}
break;
case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
{
OUString aAttrValue( rAttrValue );
sal_uInt16 nValPrefix =
static_cast<sal_uInt16>((*aIter).second.m_nParam1);
if( GetTransformer().RemoveNamespacePrefix(
aAttrValue, nValPrefix ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_MACRO_NAME:
{
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->SetValueByIndex( i, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
else
{
const OUString& rApp = GetXMLToken( XML_APPLICATION );
const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
OUString aAttrValue;
if( rAttrValue.getLength() > rApp.getLength()+1 &&
rAttrValue.copy(0,rApp.getLength()).
equalsIgnoreAsciiCase( rApp ) &&
':' == rAttrValue[rApp.getLength()] )
{
aLocation = rApp;
aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
}
else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
rAttrValue.copy(0,rDoc.getLength()).
equalsIgnoreAsciiCase( rDoc ) &&
':' == rAttrValue[rDoc.getLength()] )
{
aLocation= rDoc;
aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
}
if( aAttrValue.getLength() )
pMutableAttrList->SetValueByIndex( i,
aAttrValue );
if( aLocation.getLength() )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
// draw bug
aAttrQName = GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LIBRARY ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
}
}
}
break;
case XML_ATACTION_COPY:
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkGraphics.h"
#include "SkMath.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTArray.h"
#include "PictureRenderer.h"
#include "picture_utils.h"
static void usage(const char* argv0) {
SkDebugf("SkPicture rendering tool\n");
SkDebugf("\n"
"Usage: \n"
" %s <input>... <outputDir> \n"
" [--mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]]\n"
" [--device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
"]"
, argv0);
SkDebugf("\n\n");
SkDebugf(
" input: A list of directories and files to use as input. Files are\n"
" expected to have the .skp extension.\n\n");
SkDebugf(
" outputDir: directory to write the rendered images.\n\n");
SkDebugf(
" --mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]: Run in the corresponding mode.\n"
" Default is simple.\n");
SkDebugf(
" pipe, Render using a SkGPipe.\n");
SkDebugf(
" pow2tile minWidth height[%], Creates tiles with widths\n"
" that are all a power of two\n"
" such that they minimize the\n"
" amount of wasted tile space.\n"
" minWidth is the minimum width\n"
" of these tiles and must be a\n"
" power of two. A simple render\n"
" is done with these tiles.\n");
SkDebugf(
" simple, Render using the default rendering method.\n");
SkDebugf(
" tile width[%] height[%], Do a simple render using tiles\n"
" with the given dimensions.\n");
SkDebugf("\n");
SkDebugf(
" --device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
": Use the corresponding device. Default is bitmap.\n");
SkDebugf(
" bitmap, Render to a bitmap.\n");
#if SK_SUPPORT_GPU
SkDebugf(
" gpu, Render to the GPU.\n");
#endif
}
static void make_output_filepath(SkString* path, const SkString& dir,
const SkString& name) {
sk_tools::make_filepath(path, dir, name);
path->remove(path->size() - 3, 3);
path->append("png");
}
static void write_output(const SkString& outputDir, const SkString& inputFilename,
const sk_tools::PictureRenderer& renderer) {
SkString outputPath;
make_output_filepath(&outputPath, outputDir, inputFilename);
bool isWritten = renderer.write(outputPath);
if (!isWritten) {
SkDebugf("Could not write to file %s\n", outputPath.c_str());
}
}
static void render_picture(const SkString& inputPath, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkString inputFilename;
sk_tools::get_basename(&inputFilename, inputPath);
SkFILEStream inputStream;
inputStream.setPath(inputPath.c_str());
if (!inputStream.isValid()) {
SkDebugf("Could not open file %s\n", inputPath.c_str());
return;
}
SkPicture picture(&inputStream);
renderer.init(&picture);
renderer.render(true);
renderer.resetState();
write_output(outputDir, inputFilename, renderer);
renderer.end();
}
static void process_input(const SkString& input, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkOSFile::Iter iter(input.c_str(), "skp");
SkString inputFilename;
if (iter.next(&inputFilename)) {
do {
SkString inputPath;
sk_tools::make_filepath(&inputPath, input, inputFilename);
render_picture(inputPath, outputDir, renderer);
} while(iter.next(&inputFilename));
} else {
SkString inputPath(input);
render_picture(inputPath, outputDir, renderer);
}
}
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
sk_tools::PictureRenderer*& renderer){
const char* argv0 = argv[0];
char* const* stop = argv + argc;
sk_tools::PictureRenderer::SkDeviceTypes deviceType =
sk_tools::PictureRenderer::kBitmap_DeviceType;
for (++argv; argv < stop; ++argv) {
if (0 == strcmp(*argv, "--mode")) {
SkDELETE(renderer);
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --mode\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "pipe")) {
renderer = SkNEW(sk_tools::PipePictureRenderer);
} else if (0 == strcmp(*argv, "simple")) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
} else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) {
char* mode = *argv;
bool isPowerOf2Mode = false;
if (0 == strcmp(*argv, "pow2tile")) {
isPowerOf2Mode = true;
}
sk_tools::TiledPictureRenderer* tileRenderer =
SkNEW(sk_tools::TiledPictureRenderer);
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing width for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (isPowerOf2Mode) {
int minWidth = atoi(*argv);
if (!SkIsPow2(minWidth) || minWidth <= 0) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width"
" value that is a power of two\n", mode);
exit(-1);
}
tileRenderer->setTileMinPowerOf2Width(minWidth);
} else if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileWidthPercentage(atof(*argv));
if (!(tileRenderer->getTileWidthPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileWidth(atoi(*argv));
if (!(tileRenderer->getTileWidth() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width > 0\n", mode);
exit(-1);
}
}
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing height for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileHeightPercentage(atof(*argv));
if (!(tileRenderer->getTileHeightPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf(
"--mode %s must be given a height percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileHeight(atoi(*argv));
if (!(tileRenderer->getTileHeight() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a height > 0\n", mode);
exit(-1);
}
}
renderer = tileRenderer;
} else {
SkDebugf("%s is not a valid mode for --mode\n", *argv);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--device")) {
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --deivce\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "bitmap")) {
deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
}
#if SK_SUPPORT_GPU
else if (0 == strcmp(*argv, "gpu")) {
deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
}
#endif
else {
SkDebugf("%s is not a valid mode for --device\n", *argv);
usage(argv0);
exit(-1);
}
} else if ((0 == strcmp(*argv, "-h")) || (0 == strcmp(*argv, "--help"))) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
} else {
inputs->push_back(SkString(*argv));
}
}
if (inputs->count() < 2) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
}
if (NULL == renderer) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
}
renderer->setDeviceType(deviceType);
}
int main(int argc, char* const argv[]) {
SkGraphics::Init();
SkTArray<SkString> inputs;
sk_tools::PictureRenderer* renderer = NULL;
parse_commandline(argc, argv, &inputs, renderer);
SkString outputDir = inputs[inputs.count() - 1];
SkASSERT(renderer);
for (int i = 0; i < inputs.count() - 1; i ++) {
process_input(inputs[i], outputDir, *renderer);
}
SkDELETE(renderer);
SkGraphics::Term();
}
<commit_msg>Add per-picture logging to render_pictures<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkGraphics.h"
#include "SkMath.h"
#include "SkOSFile.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTArray.h"
#include "PictureRenderer.h"
#include "picture_utils.h"
static void usage(const char* argv0) {
SkDebugf("SkPicture rendering tool\n");
SkDebugf("\n"
"Usage: \n"
" %s <input>... <outputDir> \n"
" [--mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]]\n"
" [--device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
"]"
, argv0);
SkDebugf("\n\n");
SkDebugf(
" input: A list of directories and files to use as input. Files are\n"
" expected to have the .skp extension.\n\n");
SkDebugf(
" outputDir: directory to write the rendered images.\n\n");
SkDebugf(
" --mode pipe | pow2tile minWidth height[%] | simple\n"
" | tile width[%] height[%]: Run in the corresponding mode.\n"
" Default is simple.\n");
SkDebugf(
" pipe, Render using a SkGPipe.\n");
SkDebugf(
" pow2tile minWidth height[%], Creates tiles with widths\n"
" that are all a power of two\n"
" such that they minimize the\n"
" amount of wasted tile space.\n"
" minWidth is the minimum width\n"
" of these tiles and must be a\n"
" power of two. A simple render\n"
" is done with these tiles.\n");
SkDebugf(
" simple, Render using the default rendering method.\n");
SkDebugf(
" tile width[%] height[%], Do a simple render using tiles\n"
" with the given dimensions.\n");
SkDebugf("\n");
SkDebugf(
" --device bitmap"
#if SK_SUPPORT_GPU
" | gpu"
#endif
": Use the corresponding device. Default is bitmap.\n");
SkDebugf(
" bitmap, Render to a bitmap.\n");
#if SK_SUPPORT_GPU
SkDebugf(
" gpu, Render to the GPU.\n");
#endif
}
static void make_output_filepath(SkString* path, const SkString& dir,
const SkString& name) {
sk_tools::make_filepath(path, dir, name);
path->remove(path->size() - 3, 3);
path->append("png");
}
static void write_output(const SkString& outputDir, const SkString& inputFilename,
const sk_tools::PictureRenderer& renderer) {
SkString outputPath;
make_output_filepath(&outputPath, outputDir, inputFilename);
bool isWritten = renderer.write(outputPath);
if (!isWritten) {
SkDebugf("Could not write to file %s\n", outputPath.c_str());
}
}
static void render_picture(const SkString& inputPath, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkString inputFilename;
sk_tools::get_basename(&inputFilename, inputPath);
SkFILEStream inputStream;
inputStream.setPath(inputPath.c_str());
if (!inputStream.isValid()) {
SkDebugf("Could not open file %s\n", inputPath.c_str());
return;
}
SkPicture picture(&inputStream);
SkDebugf("drawing... [%i %i] %s\n", picture.width(), picture.height(),
inputPath.c_str());
renderer.init(&picture);
renderer.render(true);
renderer.resetState();
write_output(outputDir, inputFilename, renderer);
renderer.end();
}
static void process_input(const SkString& input, const SkString& outputDir,
sk_tools::PictureRenderer& renderer) {
SkOSFile::Iter iter(input.c_str(), "skp");
SkString inputFilename;
if (iter.next(&inputFilename)) {
do {
SkString inputPath;
sk_tools::make_filepath(&inputPath, input, inputFilename);
render_picture(inputPath, outputDir, renderer);
} while(iter.next(&inputFilename));
} else {
SkString inputPath(input);
render_picture(inputPath, outputDir, renderer);
}
}
static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs,
sk_tools::PictureRenderer*& renderer){
const char* argv0 = argv[0];
char* const* stop = argv + argc;
sk_tools::PictureRenderer::SkDeviceTypes deviceType =
sk_tools::PictureRenderer::kBitmap_DeviceType;
for (++argv; argv < stop; ++argv) {
if (0 == strcmp(*argv, "--mode")) {
SkDELETE(renderer);
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --mode\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "pipe")) {
renderer = SkNEW(sk_tools::PipePictureRenderer);
} else if (0 == strcmp(*argv, "simple")) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
} else if ((0 == strcmp(*argv, "tile")) || (0 == strcmp(*argv, "pow2tile"))) {
char* mode = *argv;
bool isPowerOf2Mode = false;
if (0 == strcmp(*argv, "pow2tile")) {
isPowerOf2Mode = true;
}
sk_tools::TiledPictureRenderer* tileRenderer =
SkNEW(sk_tools::TiledPictureRenderer);
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing width for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (isPowerOf2Mode) {
int minWidth = atoi(*argv);
if (!SkIsPow2(minWidth) || minWidth <= 0) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width"
" value that is a power of two\n", mode);
exit(-1);
}
tileRenderer->setTileMinPowerOf2Width(minWidth);
} else if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileWidthPercentage(atof(*argv));
if (!(tileRenderer->getTileWidthPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileWidth(atoi(*argv));
if (!(tileRenderer->getTileWidth() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a width > 0\n", mode);
exit(-1);
}
}
++argv;
if (argv >= stop) {
SkDELETE(tileRenderer);
SkDebugf("Missing height for --mode %s\n", mode);
usage(argv0);
exit(-1);
}
if (sk_tools::is_percentage(*argv)) {
tileRenderer->setTileHeightPercentage(atof(*argv));
if (!(tileRenderer->getTileHeightPercentage() > 0)) {
SkDELETE(tileRenderer);
SkDebugf(
"--mode %s must be given a height percentage > 0\n", mode);
exit(-1);
}
} else {
tileRenderer->setTileHeight(atoi(*argv));
if (!(tileRenderer->getTileHeight() > 0)) {
SkDELETE(tileRenderer);
SkDebugf("--mode %s must be given a height > 0\n", mode);
exit(-1);
}
}
renderer = tileRenderer;
} else {
SkDebugf("%s is not a valid mode for --mode\n", *argv);
usage(argv0);
exit(-1);
}
} else if (0 == strcmp(*argv, "--device")) {
++argv;
if (argv >= stop) {
SkDebugf("Missing mode for --deivce\n");
usage(argv0);
exit(-1);
}
if (0 == strcmp(*argv, "bitmap")) {
deviceType = sk_tools::PictureRenderer::kBitmap_DeviceType;
}
#if SK_SUPPORT_GPU
else if (0 == strcmp(*argv, "gpu")) {
deviceType = sk_tools::PictureRenderer::kGPU_DeviceType;
}
#endif
else {
SkDebugf("%s is not a valid mode for --device\n", *argv);
usage(argv0);
exit(-1);
}
} else if ((0 == strcmp(*argv, "-h")) || (0 == strcmp(*argv, "--help"))) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
} else {
inputs->push_back(SkString(*argv));
}
}
if (inputs->count() < 2) {
SkDELETE(renderer);
usage(argv0);
exit(-1);
}
if (NULL == renderer) {
renderer = SkNEW(sk_tools::SimplePictureRenderer);
}
renderer->setDeviceType(deviceType);
}
int main(int argc, char* const argv[]) {
SkGraphics::Init();
SkTArray<SkString> inputs;
sk_tools::PictureRenderer* renderer = NULL;
parse_commandline(argc, argv, &inputs, renderer);
SkString outputDir = inputs[inputs.count() - 1];
SkASSERT(renderer);
for (int i = 0; i < inputs.count() - 1; i ++) {
process_input(inputs[i], outputDir, *renderer);
}
SkDELETE(renderer);
SkGraphics::Term();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Birthstone is a programming language and interpreter language written *
* by Robb Tolliver for his Senior Project at BYU-Idaho during the Fall *
* Semester of 2010. *
* *
* Copyright (C) 2010 by Robert Tolliver *
* Robb.Tolli@gmail.com *
* *
* Birthstone is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Birthstone 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 Birthstone. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "parser.h"
using namespace std;
int main(int argc, char **argv)
{
string filename;
bool interactive = true;
if (argc > 1)
{
ifstream input(argv[1]);
if (input.good())
Parser(input).run();
else
{
cerr << "error: could not read input file. " << endl;
}
}
else // interactive mode
{
string str;
stringstream input;
Parser parser(input);
cout << "birthstone interactive shell" << endl;
do
{
cout << "bs> ";
getline(cin, str);
input.str(str);
parser.run();
} while (true/* TODO: stop when quit or exit is entered*/);
}
return 0;
}
<commit_msg>attempted to make interactive mode continue to work after the first command. This could not be tested due to the segmentation fault introduced in the last revision (r47).<commit_after>/******************************************************************************
* Birthstone is a programming language and interpreter language written *
* by Robb Tolliver for his Senior Project at BYU-Idaho during the Fall *
* Semester of 2010. *
* *
* Copyright (C) 2010 by Robert Tolliver *
* Robb.Tolli@gmail.com *
* *
* Birthstone is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Birthstone 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 Birthstone. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "parser.h"
using namespace std;
int main(int argc, char **argv)
{
string filename;
bool interactive = true;
if (argc > 1)
{
ifstream input(argv[1]);
if (input.good())
Parser(input).run();
else
{
cerr << "error: could not read input file. " << endl;
}
}
else // interactive mode
{
string str;
istringstream input;
Parser parser(input);
cout << "birthstone interactive shell" << endl;
do
{
cout << "bs> ";
getline(cin, str);
input.str(str);
input.seekg(0);
parser.run();
} while (true/* TODO: stop when quit or exit is entered*/);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "action_header.h"
#include "../server_settings.h"
#include "../ClientMain.h"
namespace
{
void access_dir_details(std::string folder, std::string& ret)
{
bool has_error = false;
getFiles(folder, &has_error);
if (has_error)
{
ret += "Cannot access " + folder + ". " + os_last_error_str() + "\n";
}
else
{
ret += "Can access " + folder + "\n";
}
}
std::string access_err_details(std::string folder)
{
std::vector<std::string> toks;
Tokenize(folder, toks, os_file_sep());
std::string ret;
std::string cdir = os_file_sep();
access_dir_details(cdir, ret);
for (size_t i = 0; i < toks.size(); ++i)
{
if (toks[i].empty()) continue;
if (cdir != os_file_sep())
{
cdir += os_file_sep();
}
cdir += toks[i];
access_dir_details(cdir, ret);
}
return ret;
}
std::string access_dir_hint(std::string folder)
{
if (folder.size() > 1 && folder[1] == ':')
{
bool has_error = false;
getFiles(folder.substr(0, 2) + os_file_sep(), &has_error);
if (has_error)
{
return "volume_not_accessible";
}
}
if ((folder.size() > 2 && folder[0] == '\\'
&& folder[1] == '\\'
&& folder[2] != '?')
|| next(folder, 0, "\\\\?\\UNC"))
{
bool has_error = false;
getFiles(folder, &has_error);
if (has_error && os_last_error() == 5
|| os_last_error() == 1326)
{
return "folder_unc_access_denied";
}
}
return std::string();
}
bool is_stop_show(IDatabase* db, std::string stop_key)
{
db_results res = db->Read("SELECT tvalue FROM misc WHERE tkey='stop_show'");
if (!res.empty())
{
std::vector<std::string> toks;
Tokenize(res[0]["tvalue"], toks, ",");
return std::find(toks.begin(), toks.end(), stop_key) != toks.end();
}
return false;
}
void add_stop_show(IDatabase* db, JSON::Object& ret, std::string dir_error_stop_show_key)
{
ret.set("dir_error_stop_show_key", dir_error_stop_show_key);
if (is_stop_show(db, dir_error_stop_show_key))
{
ret.set("dir_error_show", false);
}
}
void access_dir_checks(IDatabase* db, ServerSettings& settings, std::string backupfolder, std::string backupfolder_uncompr,
JSON::Object& ret)
{
#ifdef _WIN32
if (backupfolder.size() == 2 && backupfolder[1] == ':')
{
backupfolder += os_file_sep();
}
if (backupfolder_uncompr.size() == 2 && backupfolder_uncompr[1] == ':')
{
backupfolder_uncompr += os_file_sep();
}
#endif
if (backupfolder.empty() || !os_directory_exists(os_file_prefix(backupfolder)) || !os_directory_exists(os_file_prefix(backupfolder_uncompr)))
{
if (!backupfolder.empty())
{
ret.set("system_err", os_last_error_str());
}
ret.set("dir_error", true);
if (settings.getSettings()->backupfolder.empty())
{
ret.set("dir_error_ext", "err_name_empty");
}
else if (!os_directory_exists(os_file_prefix(settings.getSettings()->backupfolder)))
{
ret.set("dir_error_ext", "err_folder_not_found");
add_stop_show(db, ret, "dir_error_not_found");
}
else
{
add_stop_show(db, ret, "dir_error_misc");
}
#ifdef _WIN32
std::string hint = access_dir_hint(settings.getSettings()->backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
#ifndef _WIN32
ret.set("detail_err_str", access_err_details(settings.getSettings()->backupfolder));
#endif
}
else if (!os_directory_exists(os_file_prefix(backupfolder + os_file_sep() + "clients")) && !os_create_dir(os_file_prefix(backupfolder + os_file_sep() + "clients")))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir");
#ifdef _WIN32
std::string hint = access_dir_hint(backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
}
else
{
bool has_access_error = false;
std::string testfoldername = "testfolderHvfgh---dFFoeRRRf";
std::string testfolderpath = backupfolder + os_file_sep() + testfoldername;
if (os_directory_exists(os_file_prefix(testfolderpath)))
{
if (!os_remove_dir(os_file_prefix(testfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir2");
has_access_error = true;
#ifdef _WIN32
std::string hint = access_dir_hint(backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
}
}
SSettings* server_settings = settings.getSettings();
if (!has_access_error
&& !os_create_dir(os_file_prefix(testfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir3");
#ifdef _WIN32
std::string hint = access_dir_hint(backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
has_access_error = true;
}
else if (!server_settings->no_file_backups
&& os_directory_exists(os_file_prefix(backupfolder + os_file_sep() + "testfo~1")))
{
ret.set("dir_error", true);
ret.set("dir_error_ext", "dos_names_created");
add_stop_show(db, ret, "dos_names_created");
ret.set("dir_error_hint", "dos_names_created");
if (backupfolder.size() > 2
&& backupfolder[1] == ':')
{
ret.set("dir_error_volume", backupfolder.substr(0, 2));
}
else
{
ret.set("dir_error_volume", "<VOLUME>");
}
}
if (!server_settings->no_file_backups)
{
std::string linkfolderpath = testfolderpath + "_link";
os_remove_symlink_dir(os_file_prefix(linkfolderpath));
Server->deleteFile(os_file_prefix(linkfolderpath));
if (!has_access_error
&& !os_link_symbolic(os_file_prefix(testfolderpath), os_file_prefix(linkfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_symbolic_links");
ret.set("dir_error_hint", "UrBackup cannot create symbolic links on the backup storage. "
"Your backup storage must support symbolic links in order for UrBackup to work correctly. "
"The UrBackup Server must run as administrative user on Windows (If not you get error code 1314). "
"Note: As of 2016-05-07 samba (which is used by many Linux based NAS operating systems for Windows file sharing) has not "
"implemented the necessary functionality to support symbolic link creation from Windows (With this you get error code 4390).");
add_stop_show(db, ret, "dir_error_cannot_create_symbolic_links");
}
os_remove_symlink_dir(os_file_prefix(linkfolderpath));
}
#ifdef _WIN32
if (!server_settings->no_file_backups)
{
std::string test1_path = testfolderpath + os_file_sep() + "test1";
std::string test2_path = testfolderpath + os_file_sep() + "Test1";
if (!os_create_dir(test1_path)
|| !os_create_dir(test2_path))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_file_system_case_insensitive");
ret.set("dir_error_hint", "err_file_system_case_insensitive");
add_stop_show(db, ret, "err_file_system_case_insensitive");
}
os_remove_dir(test1_path);
os_remove_dir(test2_path);
std::string test3_path = testfolderpath + os_file_sep() + "CON";
std::auto_ptr<IFile> test_file(Server->openFile(test3_path, MODE_WRITE));
if (test_file.get() == NULL)
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_file_system_special_windows_files_disallowed");
ret.set("dir_error_hint", "err_file_system_special_windows_files_disallowed");
add_stop_show(db, ret, "err_file_system_special_windows_files_disallowed");
}
test_file.reset();
Server->deleteFile(test3_path);
}
#endif
if (!server_settings->no_file_backups)
{
bool use_tmpfiles = server_settings->use_tmpfiles;
std::string tmpfile_path;
if (!use_tmpfiles)
{
tmpfile_path = server_settings->backupfolder + os_file_sep() + "urbackup_tmp_files";
}
std::auto_ptr<IFile> tmp_f(ClientMain::getTemporaryFileRetry(use_tmpfiles, tmpfile_path, logid_t()));
if (tmp_f.get() == NULL)
{
ret.set("tmpdir_error", true);
ret.set("tmpdir_error_stop_show_key", "tmpdir_error");
if (is_stop_show(db, "tmpdir_error"))
{
ret.set("tmpdir_error_show", false);
}
}
else
{
std::string teststring = base64_decode("WDVPIVAlQEFQWzRcUFpYNTQoUF4pN0NDKTd9JEVJQ0FSLVNUQU5EQVJELUFOVElWSVJVUy1URVNULUZJTEUhJEgrSCo=");
tmp_f->Write(teststring);
std::string tmp_fn = tmp_f->getFilename();
tmp_f.reset();
tmp_f.reset(Server->openFile(tmp_fn, MODE_RW));
std::string readstring;
if (tmp_f.get() != NULL)
{
readstring = tmp_f->Read(static_cast<_u32>(teststring.size()));
}
tmp_f.reset();
Server->deleteFile(tmp_fn);
if (teststring != readstring)
{
ret.set("virus_error", true);
ret.set("virus_error_path", ExtractFilePath(tmp_fn));
ret.set("virus_error_stop_show_key", "virus_error");
if (is_stop_show(db, "virus_error"))
{
ret.set("virus_error_show", false);
}
}
}
}
if (!has_access_error
&& !os_remove_dir(os_file_prefix(testfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir4");
has_access_error = true;
}
}
IFile *tmp = Server->openTemporaryFile();
ScopedDeleteFile delete_tmp_file(tmp);
if (tmp == NULL)
{
ret.set("tmpdir_error", true);
ret.set("tmpdir_error_stop_show_key", "tmpdir_error");
if (is_stop_show(db, "tmpdir_error"))
{
ret.set("tmpdir_error_show", false);
}
}
}
}
ACTION_IMPL(status_check)
{
Helper helper(tid, &POST, &PARAMS);
JSON::Object ret;
std::string rights = helper.getRights("status");
SUser *session = helper.getSession();
if (session != NULL && session->id == SESSION_ID_INVALID) return;
if (session != NULL && rights == "all")
{
IDatabase *db = helper.getDatabase();
helper.releaseAll();
ServerSettings settings(db);
access_dir_checks(db, settings, settings.getSettings()->backupfolder,
settings.getSettings()->backupfolder_uncompr, ret);
}
else
{
ret.set("error", 1);
}
helper.Write(ret.stringify(false));
}<commit_msg>Run check on non-Windows<commit_after>#include "action_header.h"
#include "../server_settings.h"
#include "../ClientMain.h"
namespace
{
void access_dir_details(std::string folder, std::string& ret)
{
bool has_error = false;
getFiles(folder, &has_error);
if (has_error)
{
ret += "Cannot access " + folder + ". " + os_last_error_str() + "\n";
}
else
{
ret += "Can access " + folder + "\n";
}
}
std::string access_err_details(std::string folder)
{
std::vector<std::string> toks;
Tokenize(folder, toks, os_file_sep());
std::string ret;
std::string cdir = os_file_sep();
access_dir_details(cdir, ret);
for (size_t i = 0; i < toks.size(); ++i)
{
if (toks[i].empty()) continue;
if (cdir != os_file_sep())
{
cdir += os_file_sep();
}
cdir += toks[i];
access_dir_details(cdir, ret);
}
return ret;
}
std::string access_dir_hint(std::string folder)
{
if (folder.size() > 1 && folder[1] == ':')
{
bool has_error = false;
getFiles(folder.substr(0, 2) + os_file_sep(), &has_error);
if (has_error)
{
return "volume_not_accessible";
}
}
if ((folder.size() > 2 && folder[0] == '\\'
&& folder[1] == '\\'
&& folder[2] != '?')
|| next(folder, 0, "\\\\?\\UNC"))
{
bool has_error = false;
getFiles(folder, &has_error);
if (has_error && os_last_error() == 5
|| os_last_error() == 1326)
{
return "folder_unc_access_denied";
}
}
return std::string();
}
bool is_stop_show(IDatabase* db, std::string stop_key)
{
db_results res = db->Read("SELECT tvalue FROM misc WHERE tkey='stop_show'");
if (!res.empty())
{
std::vector<std::string> toks;
Tokenize(res[0]["tvalue"], toks, ",");
return std::find(toks.begin(), toks.end(), stop_key) != toks.end();
}
return false;
}
void add_stop_show(IDatabase* db, JSON::Object& ret, std::string dir_error_stop_show_key)
{
ret.set("dir_error_stop_show_key", dir_error_stop_show_key);
if (is_stop_show(db, dir_error_stop_show_key))
{
ret.set("dir_error_show", false);
}
}
void access_dir_checks(IDatabase* db, ServerSettings& settings, std::string backupfolder, std::string backupfolder_uncompr,
JSON::Object& ret)
{
#ifdef _WIN32
if (backupfolder.size() == 2 && backupfolder[1] == ':')
{
backupfolder += os_file_sep();
}
if (backupfolder_uncompr.size() == 2 && backupfolder_uncompr[1] == ':')
{
backupfolder_uncompr += os_file_sep();
}
#endif
if (backupfolder.empty() || !os_directory_exists(os_file_prefix(backupfolder)) || !os_directory_exists(os_file_prefix(backupfolder_uncompr)))
{
if (!backupfolder.empty())
{
ret.set("system_err", os_last_error_str());
}
ret.set("dir_error", true);
if (settings.getSettings()->backupfolder.empty())
{
ret.set("dir_error_ext", "err_name_empty");
}
else if (!os_directory_exists(os_file_prefix(settings.getSettings()->backupfolder)))
{
ret.set("dir_error_ext", "err_folder_not_found");
add_stop_show(db, ret, "dir_error_not_found");
}
else
{
add_stop_show(db, ret, "dir_error_misc");
}
#ifdef _WIN32
std::string hint = access_dir_hint(settings.getSettings()->backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
#ifndef _WIN32
ret.set("detail_err_str", access_err_details(settings.getSettings()->backupfolder));
#endif
}
else if (!os_directory_exists(os_file_prefix(backupfolder + os_file_sep() + "clients")) && !os_create_dir(os_file_prefix(backupfolder + os_file_sep() + "clients")))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir");
#ifdef _WIN32
std::string hint = access_dir_hint(backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
}
else
{
bool has_access_error = false;
std::string testfoldername = "testfolderHvfgh---dFFoeRRRf";
std::string testfolderpath = backupfolder + os_file_sep() + testfoldername;
if (os_directory_exists(os_file_prefix(testfolderpath)))
{
if (!os_remove_dir(os_file_prefix(testfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir2");
has_access_error = true;
#ifdef _WIN32
std::string hint = access_dir_hint(backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
}
}
SSettings* server_settings = settings.getSettings();
if (!has_access_error
&& !os_create_dir(os_file_prefix(testfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir3");
#ifdef _WIN32
std::string hint = access_dir_hint(backupfolder);
if (!hint.empty())
{
ret.set("dir_error_hint", hint);
}
#endif
has_access_error = true;
}
else if (!server_settings->no_file_backups
&& os_directory_exists(os_file_prefix(backupfolder + os_file_sep() + "testfo~1")))
{
ret.set("dir_error", true);
ret.set("dir_error_ext", "dos_names_created");
add_stop_show(db, ret, "dos_names_created");
ret.set("dir_error_hint", "dos_names_created");
if (backupfolder.size() > 2
&& backupfolder[1] == ':')
{
ret.set("dir_error_volume", backupfolder.substr(0, 2));
}
else
{
ret.set("dir_error_volume", "<VOLUME>");
}
}
if (!server_settings->no_file_backups)
{
std::string linkfolderpath = testfolderpath + "_link";
os_remove_symlink_dir(os_file_prefix(linkfolderpath));
Server->deleteFile(os_file_prefix(linkfolderpath));
if (!has_access_error
&& !os_link_symbolic(os_file_prefix(testfolderpath), os_file_prefix(linkfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_symbolic_links");
ret.set("dir_error_hint", "UrBackup cannot create symbolic links on the backup storage. "
"Your backup storage must support symbolic links in order for UrBackup to work correctly. "
"The UrBackup Server must run as administrative user on Windows (If not you get error code 1314). "
"Note: As of 2016-05-07 samba (which is used by many Linux based NAS operating systems for Windows file sharing) has not "
"implemented the necessary functionality to support symbolic link creation from Windows (With this you get error code 4390).");
add_stop_show(db, ret, "dir_error_cannot_create_symbolic_links");
}
os_remove_symlink_dir(os_file_prefix(linkfolderpath));
}
#ifndef _WIN32
if (!server_settings->no_file_backups)
{
std::string test1_path = testfolderpath + os_file_sep() + "test1";
std::string test2_path = testfolderpath + os_file_sep() + "Test1";
if (!os_create_dir(test1_path)
|| !os_create_dir(test2_path))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_file_system_case_insensitive");
ret.set("dir_error_hint", "err_file_system_case_insensitive");
add_stop_show(db, ret, "err_file_system_case_insensitive");
}
os_remove_dir(test1_path);
os_remove_dir(test2_path);
std::string test3_path = testfolderpath + os_file_sep() + "CON";
std::auto_ptr<IFile> test_file(Server->openFile(test3_path, MODE_WRITE));
if (test_file.get() == NULL)
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_file_system_special_windows_files_disallowed");
ret.set("dir_error_hint", "err_file_system_special_windows_files_disallowed");
add_stop_show(db, ret, "err_file_system_special_windows_files_disallowed");
}
test_file.reset();
Server->deleteFile(test3_path);
}
#endif
if (!server_settings->no_file_backups)
{
bool use_tmpfiles = server_settings->use_tmpfiles;
std::string tmpfile_path;
if (!use_tmpfiles)
{
tmpfile_path = server_settings->backupfolder + os_file_sep() + "urbackup_tmp_files";
}
std::auto_ptr<IFile> tmp_f(ClientMain::getTemporaryFileRetry(use_tmpfiles, tmpfile_path, logid_t()));
if (tmp_f.get() == NULL)
{
ret.set("tmpdir_error", true);
ret.set("tmpdir_error_stop_show_key", "tmpdir_error");
if (is_stop_show(db, "tmpdir_error"))
{
ret.set("tmpdir_error_show", false);
}
}
else
{
std::string teststring = base64_decode("WDVPIVAlQEFQWzRcUFpYNTQoUF4pN0NDKTd9JEVJQ0FSLVNUQU5EQVJELUFOVElWSVJVUy1URVNULUZJTEUhJEgrSCo=");
tmp_f->Write(teststring);
std::string tmp_fn = tmp_f->getFilename();
tmp_f.reset();
tmp_f.reset(Server->openFile(tmp_fn, MODE_RW));
std::string readstring;
if (tmp_f.get() != NULL)
{
readstring = tmp_f->Read(static_cast<_u32>(teststring.size()));
}
tmp_f.reset();
Server->deleteFile(tmp_fn);
if (teststring != readstring)
{
ret.set("virus_error", true);
ret.set("virus_error_path", ExtractFilePath(tmp_fn));
ret.set("virus_error_stop_show_key", "virus_error");
if (is_stop_show(db, "virus_error"))
{
ret.set("virus_error_show", false);
}
}
}
}
if (!has_access_error
&& !os_remove_dir(os_file_prefix(testfolderpath)))
{
ret.set("system_err", os_last_error_str());
ret.set("dir_error", true);
ret.set("dir_error_ext", "err_cannot_create_subdir");
add_stop_show(db, ret, "dir_error_cannot_create_subdir4");
has_access_error = true;
}
}
IFile *tmp = Server->openTemporaryFile();
ScopedDeleteFile delete_tmp_file(tmp);
if (tmp == NULL)
{
ret.set("tmpdir_error", true);
ret.set("tmpdir_error_stop_show_key", "tmpdir_error");
if (is_stop_show(db, "tmpdir_error"))
{
ret.set("tmpdir_error_show", false);
}
}
}
}
ACTION_IMPL(status_check)
{
Helper helper(tid, &POST, &PARAMS);
JSON::Object ret;
std::string rights = helper.getRights("status");
SUser *session = helper.getSession();
if (session != NULL && session->id == SESSION_ID_INVALID) return;
if (session != NULL && rights == "all")
{
IDatabase *db = helper.getDatabase();
helper.releaseAll();
ServerSettings settings(db);
access_dir_checks(db, settings, settings.getSettings()->backupfolder,
settings.getSettings()->backupfolder_uncompr, ret);
}
else
{
ret.set("error", 1);
}
helper.Write(ret.stringify(false));
}<|endoftext|> |
<commit_before>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#ifndef _WIN32
#ifdef INFOWARE_USE_X11
#include "infoware/system.hpp"
#include <X11/Xlib.h>
#include <cstdlib>
std::vector<iware::system::display_t> iware::system::displays() {
std::vector<iware::system::display_t> ret;
if(const auto display_name = getenv("DISPLAY"))
if(const auto display = XOpenDisplay(display_name))
for(int i = 0; i < ScreenCount(display); ++i) {
const unsigned int width = DisplayWidth(display, i);
// 25.4 millimeters per inch
ret.emplace_back(iware::system::display_t{width, DisplayHeight(display, i), static_cast<unsigned int>(25.4 * DisplayWidthMM(display, i) / width),
DefaultDepth(display, i)});
}
return {};
}
#endif
#endif
<commit_msg>Fix impl-def behaviour<commit_after>// infoware - C++ System information Library
//
// Written in 2016 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#ifndef _WIN32
#ifdef INFOWARE_USE_X11
#include "infoware/system.hpp"
#include <X11/Xlib.h>
#include <cstdlib>
std::vector<iware::system::display_t> iware::system::displays() {
std::vector<iware::system::display_t> ret;
if(const auto display_name = std::getenv("DISPLAY"))
if(const auto display = XOpenDisplay(display_name))
for(int i = 0; i < ScreenCount(display); ++i) {
const unsigned int width = DisplayWidth(display, i);
// 25.4 millimeters per inch
ret.emplace_back(iware::system::display_t{width, DisplayHeight(display, i), static_cast<unsigned int>(25.4 * DisplayWidthMM(display, i) / width),
DefaultDepth(display, i)});
}
return ret;
}
#endif
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <cstring>
#include <string>
#include "base/fiber.hh"
#include "base/logging.hh"
#include "base/types.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "sim/init.hh"
#include "systemc/core/kernel.hh"
#include "systemc/core/python.hh"
#include "systemc/core/scheduler.hh"
#include "systemc/ext/core/sc_main.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
// A weak symbol to detect if sc_main has been defined, and if so where it is.
[[gnu::weak]] int sc_main(int argc, char *argv[]);
namespace sc_core
{
namespace
{
bool scMainCalled = false;
int _argc = 0;
char **_argv = NULL;
class ScMainFiber : public Fiber
{
public:
std::string resultStr;
int resultInt;
ScMainFiber() : resultInt(1) {}
void
main()
{
if (::sc_main) {
try {
resultInt = ::sc_main(_argc, _argv);
if (resultInt)
resultStr = "sc_main returned non-zero";
else
resultStr = "sc_main finished";
// Make sure no systemc events/notifications are scheduled
// after sc_main returns.
} catch (const sc_report &r) {
// There was an exception nobody caught.
resultStr = r.what();
}
::sc_gem5::Kernel::scMainFinished(true);
::sc_gem5::scheduler.clear();
} else {
// If python tries to call sc_main but no sc_main was defined...
fatal("sc_main called but not defined.\n");
}
}
};
ScMainFiber scMainFiber;
// This wrapper adapts the python version of sc_main to the c++ version.
void
sc_main(pybind11::args args)
{
panic_if(scMainCalled, "sc_main called more than once.");
_argc = args.size();
_argv = new char *[_argc];
// Initialize all the _argvs to NULL so we can delete [] them
// unconditionally.
for (int idx = 0; idx < _argc; idx++)
_argv[idx] = NULL;
// Attempt to convert all the arguments to strings. If that fails, clean
// up after ourselves. Also don't count this as a call to sc_main since
// we never got to the c++ version of that function.
try {
for (int idx = 0; idx < _argc; idx++) {
std::string arg = args[idx].cast<std::string>();
_argv[idx] = new char[arg.length() + 1];
strcpy(_argv[idx], arg.c_str());
}
} catch (...) {
// If that didn't work for some reason (probably a conversion error)
// blow away _argv and _argc and pass on the exception.
for (int idx = 0; idx < _argc; idx++)
delete [] _argv[idx];
delete [] _argv;
_argc = 0;
throw;
}
// At this point we're going to call the c++ sc_main, so we can't try
// again later.
scMainCalled = true;
scMainFiber.run();
}
int
sc_main_result_code()
{
return scMainFiber.resultInt;
}
std::string
sc_main_result_str()
{
return scMainFiber.resultStr;
}
// Make our sc_main wrapper available in the internal _m5 python module under
// the systemc submodule.
struct InstallScMain : public ::sc_gem5::PythonInitFunc
{
void
run(pybind11::module &systemc) override
{
systemc.def("sc_main", &sc_main);
systemc.def("sc_main_result_code", &sc_main_result_code);
systemc.def("sc_main_result_str", &sc_main_result_str);
}
} installScMain;
sc_stop_mode _stop_mode = SC_STOP_FINISH_DELTA;
} // anonymous namespace
int
sc_argc()
{
return _argc;
}
const char *const *
sc_argv()
{
return _argv;
}
void
sc_start()
{
Tick now = ::sc_gem5::scheduler.getCurTick();
sc_start(sc_time::from_value(MaxTick - now), SC_EXIT_ON_STARVATION);
}
void
sc_pause()
{
if (::sc_gem5::Kernel::status() == SC_RUNNING)
::sc_gem5::scheduler.schedulePause();
}
void
sc_start(const sc_time &time, sc_starvation_policy p)
{
if (time.value() == 0) {
::sc_gem5::scheduler.oneCycle();
} else {
Tick now = ::sc_gem5::scheduler.getCurTick();
::sc_gem5::scheduler.start(now + time.value(), p == SC_RUN_TO_TIME);
}
}
void
sc_set_stop_mode(sc_stop_mode mode)
{
if (sc_is_running()) {
SC_REPORT_ERROR("attempt to set sc_stop mode "
"after start will be ignored", "");
return;
}
_stop_mode = mode;
}
sc_stop_mode
sc_get_stop_mode()
{
return _stop_mode;
}
void
sc_stop()
{
if (::sc_gem5::Kernel::status() == SC_STOPPED)
return;
if (sc_is_running()) {
bool finish_delta = (_stop_mode == SC_STOP_FINISH_DELTA);
::sc_gem5::scheduler.scheduleStop(finish_delta);
} else {
::sc_gem5::Kernel::stop();
}
}
const sc_time &
sc_time_stamp()
{
static sc_time tstamp;
Tick tick = ::sc_gem5::scheduler.getCurTick();
//XXX We're assuming the systemc time resolution is in ps.
tstamp = sc_time::from_value(tick / SimClock::Int::ps);
return tstamp;
}
sc_dt::uint64
sc_delta_count()
{
return sc_gem5::scheduler.numCycles();
}
bool
sc_is_running()
{
return sc_get_status() & (SC_RUNNING | SC_PAUSED);
}
bool
sc_pending_activity_at_current_time()
{
return ::sc_gem5::scheduler.pendingCurr();
}
bool
sc_pending_activity_at_future_time()
{
return ::sc_gem5::scheduler.pendingFuture();
}
bool
sc_pending_activity()
{
return sc_pending_activity_at_current_time() ||
sc_pending_activity_at_future_time();
}
sc_time
sc_time_to_pending_activity()
{
return sc_time::from_value(::sc_gem5::scheduler.timeToPending());
}
sc_status
sc_get_status()
{
return ::sc_gem5::kernel ? ::sc_gem5::kernel->status() : SC_ELABORATION;
}
std::ostream &
operator << (std::ostream &os, sc_status s)
{
switch (s) {
case SC_ELABORATION:
os << "SC_ELABORATION";
break;
case SC_BEFORE_END_OF_ELABORATION:
os << "SC_BEFORE_END_OF_ELABORATION";
break;
case SC_END_OF_ELABORATION:
os << "SC_END_OF_ELABORATION";
break;
case SC_START_OF_SIMULATION:
os << "SC_START_OF_SIMULATION";
break;
case SC_RUNNING:
os << "SC_RUNNING";
break;
case SC_PAUSED:
os << "SC_PAUSED";
break;
case SC_STOPPED:
os << "SC_STOPPED";
break;
case SC_END_OF_SIMULATION:
os << "SC_END_OF_SIMULATION";
break;
// Nonstandard
case SC_END_OF_INITIALIZATION:
os << "SC_END_OF_INITIALIZATION";
break;
case SC_END_OF_UPDATE:
os << "SC_END_OF_UPDATE";
break;
case SC_BEFORE_TIMESTEP:
os << "SC_BEFORE_TIMESTEP";
break;
default:
if (s & SC_STATUS_ANY) {
const char *prefix = "(";
for (sc_status m = (sc_status)0x1;
m < SC_STATUS_ANY; m = (sc_status)(m << 1)) {
if (m & s) {
os << prefix;
prefix = "|";
os << m;
}
}
os << ")";
} else {
ccprintf(os, "%#x", s);
}
}
return os;
}
} // namespace sc_core
<commit_msg>systemc: Handle sc_time_stamp before any sc_time is constructed.<commit_after>/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <cstring>
#include <string>
#include "base/fiber.hh"
#include "base/logging.hh"
#include "base/types.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "sim/init.hh"
#include "systemc/core/kernel.hh"
#include "systemc/core/python.hh"
#include "systemc/core/scheduler.hh"
#include "systemc/ext/core/sc_main.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
// A weak symbol to detect if sc_main has been defined, and if so where it is.
[[gnu::weak]] int sc_main(int argc, char *argv[]);
namespace sc_core
{
namespace
{
bool scMainCalled = false;
int _argc = 0;
char **_argv = NULL;
class ScMainFiber : public Fiber
{
public:
std::string resultStr;
int resultInt;
ScMainFiber() : resultInt(1) {}
void
main()
{
if (::sc_main) {
try {
resultInt = ::sc_main(_argc, _argv);
if (resultInt)
resultStr = "sc_main returned non-zero";
else
resultStr = "sc_main finished";
// Make sure no systemc events/notifications are scheduled
// after sc_main returns.
} catch (const sc_report &r) {
// There was an exception nobody caught.
resultStr = r.what();
}
::sc_gem5::Kernel::scMainFinished(true);
::sc_gem5::scheduler.clear();
} else {
// If python tries to call sc_main but no sc_main was defined...
fatal("sc_main called but not defined.\n");
}
}
};
ScMainFiber scMainFiber;
// This wrapper adapts the python version of sc_main to the c++ version.
void
sc_main(pybind11::args args)
{
panic_if(scMainCalled, "sc_main called more than once.");
_argc = args.size();
_argv = new char *[_argc];
// Initialize all the _argvs to NULL so we can delete [] them
// unconditionally.
for (int idx = 0; idx < _argc; idx++)
_argv[idx] = NULL;
// Attempt to convert all the arguments to strings. If that fails, clean
// up after ourselves. Also don't count this as a call to sc_main since
// we never got to the c++ version of that function.
try {
for (int idx = 0; idx < _argc; idx++) {
std::string arg = args[idx].cast<std::string>();
_argv[idx] = new char[arg.length() + 1];
strcpy(_argv[idx], arg.c_str());
}
} catch (...) {
// If that didn't work for some reason (probably a conversion error)
// blow away _argv and _argc and pass on the exception.
for (int idx = 0; idx < _argc; idx++)
delete [] _argv[idx];
delete [] _argv;
_argc = 0;
throw;
}
// At this point we're going to call the c++ sc_main, so we can't try
// again later.
scMainCalled = true;
scMainFiber.run();
}
int
sc_main_result_code()
{
return scMainFiber.resultInt;
}
std::string
sc_main_result_str()
{
return scMainFiber.resultStr;
}
// Make our sc_main wrapper available in the internal _m5 python module under
// the systemc submodule.
struct InstallScMain : public ::sc_gem5::PythonInitFunc
{
void
run(pybind11::module &systemc) override
{
systemc.def("sc_main", &sc_main);
systemc.def("sc_main_result_code", &sc_main_result_code);
systemc.def("sc_main_result_str", &sc_main_result_str);
}
} installScMain;
sc_stop_mode _stop_mode = SC_STOP_FINISH_DELTA;
} // anonymous namespace
int
sc_argc()
{
return _argc;
}
const char *const *
sc_argv()
{
return _argv;
}
void
sc_start()
{
Tick now = ::sc_gem5::scheduler.getCurTick();
sc_start(sc_time::from_value(MaxTick - now), SC_EXIT_ON_STARVATION);
}
void
sc_pause()
{
if (::sc_gem5::Kernel::status() == SC_RUNNING)
::sc_gem5::scheduler.schedulePause();
}
void
sc_start(const sc_time &time, sc_starvation_policy p)
{
if (time.value() == 0) {
::sc_gem5::scheduler.oneCycle();
} else {
Tick now = ::sc_gem5::scheduler.getCurTick();
::sc_gem5::scheduler.start(now + time.value(), p == SC_RUN_TO_TIME);
}
}
void
sc_set_stop_mode(sc_stop_mode mode)
{
if (sc_is_running()) {
SC_REPORT_ERROR("attempt to set sc_stop mode "
"after start will be ignored", "");
return;
}
_stop_mode = mode;
}
sc_stop_mode
sc_get_stop_mode()
{
return _stop_mode;
}
void
sc_stop()
{
if (::sc_gem5::Kernel::status() == SC_STOPPED)
return;
if (sc_is_running()) {
bool finish_delta = (_stop_mode == SC_STOP_FINISH_DELTA);
::sc_gem5::scheduler.scheduleStop(finish_delta);
} else {
::sc_gem5::Kernel::stop();
}
}
const sc_time &
sc_time_stamp()
{
static sc_time tstamp;
Tick tick = ::sc_gem5::scheduler.getCurTick();
//XXX We're assuming the systemc time resolution is in ps.
// If tick is zero, the time scale may not be fixed yet, and
// SimClock::Int::ps may be zero.
tstamp = sc_time::from_value(tick ? tick / SimClock::Int::ps : 0);
return tstamp;
}
sc_dt::uint64
sc_delta_count()
{
return sc_gem5::scheduler.numCycles();
}
bool
sc_is_running()
{
return sc_get_status() & (SC_RUNNING | SC_PAUSED);
}
bool
sc_pending_activity_at_current_time()
{
return ::sc_gem5::scheduler.pendingCurr();
}
bool
sc_pending_activity_at_future_time()
{
return ::sc_gem5::scheduler.pendingFuture();
}
bool
sc_pending_activity()
{
return sc_pending_activity_at_current_time() ||
sc_pending_activity_at_future_time();
}
sc_time
sc_time_to_pending_activity()
{
return sc_time::from_value(::sc_gem5::scheduler.timeToPending());
}
sc_status
sc_get_status()
{
return ::sc_gem5::kernel ? ::sc_gem5::kernel->status() : SC_ELABORATION;
}
std::ostream &
operator << (std::ostream &os, sc_status s)
{
switch (s) {
case SC_ELABORATION:
os << "SC_ELABORATION";
break;
case SC_BEFORE_END_OF_ELABORATION:
os << "SC_BEFORE_END_OF_ELABORATION";
break;
case SC_END_OF_ELABORATION:
os << "SC_END_OF_ELABORATION";
break;
case SC_START_OF_SIMULATION:
os << "SC_START_OF_SIMULATION";
break;
case SC_RUNNING:
os << "SC_RUNNING";
break;
case SC_PAUSED:
os << "SC_PAUSED";
break;
case SC_STOPPED:
os << "SC_STOPPED";
break;
case SC_END_OF_SIMULATION:
os << "SC_END_OF_SIMULATION";
break;
// Nonstandard
case SC_END_OF_INITIALIZATION:
os << "SC_END_OF_INITIALIZATION";
break;
case SC_END_OF_UPDATE:
os << "SC_END_OF_UPDATE";
break;
case SC_BEFORE_TIMESTEP:
os << "SC_BEFORE_TIMESTEP";
break;
default:
if (s & SC_STATUS_ANY) {
const char *prefix = "(";
for (sc_status m = (sc_status)0x1;
m < SC_STATUS_ANY; m = (sc_status)(m << 1)) {
if (m & s) {
os << prefix;
prefix = "|";
os << m;
}
}
os << ")";
} else {
ccprintf(os, "%#x", s);
}
}
return os;
}
} // namespace sc_core
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <vector>
#include "base/logging.hh"
#include "base/types.hh"
#include "python/pybind11/pybind.hh"
#include "systemc/core/python.hh"
#include "systemc/ext/core/sc_time.hh"
namespace sc_core
{
namespace
{
const char *TimeUnitNames[] = {
[SC_FS] = "fs",
[SC_PS] = "ps",
[SC_NS] = "ns",
[SC_US] = "us",
[SC_MS] = "ms",
[SC_SEC] = "s"
};
double TimeUnitScale[] = {
[SC_FS] = 1.0e-15,
[SC_PS] = 1.0e-12,
[SC_NS] = 1.0e-9,
[SC_US] = 1.0e-6,
[SC_MS] = 1.0e-3,
[SC_SEC] = 1.0
};
bool timeFixed = false;
bool pythonReady = false;
struct SetInfo
{
SetInfo(::sc_core::sc_time *time, double d, ::sc_core::sc_time_unit tu) :
time(time), d(d), tu(tu)
{}
::sc_core::sc_time *time;
double d;
::sc_core::sc_time_unit tu;
};
std::vector<SetInfo> toSet;
void
setWork(sc_time *time, double d, ::sc_core::sc_time_unit tu)
{
//XXX Assuming the time resolution is 1ps.
double scale = TimeUnitScale[tu] / TimeUnitScale[SC_PS];
// Accellera claims there is a linux bug, and that these next two
// lines work around them.
volatile double tmp = d * scale + 0.5;
*time = sc_time::from_value(static_cast<uint64_t>(tmp));
}
void
fixTime()
{
auto ticks = pybind11::module::import("m5.ticks");
auto fix_global_frequency = ticks.attr("fixGlobalFrequency");
fix_global_frequency();
for (auto &t: toSet)
setWork(t.time, t.d, t.tu);
toSet.clear();
}
void
set(::sc_core::sc_time *time, double d, ::sc_core::sc_time_unit tu)
{
// Only fix time once.
if (!timeFixed) {
timeFixed = true;
// If we've run, python is working and we haven't fixed time yet.
if (pythonReady)
fixTime();
}
if (pythonReady) {
// Time should be working. Set up this sc_time.
setWork(time, d, tu);
} else {
// Time isn't set up yet. Defer setting up this sc_time.
toSet.emplace_back(time, d, tu);
}
}
class TimeSetter : public ::sc_gem5::PythonReadyFunc
{
public:
TimeSetter() : ::sc_gem5::PythonReadyFunc() {}
void
run() override
{
// Record that we've run and python/pybind should be usable.
pythonReady = true;
// If time is already fixed, let python know.
if (timeFixed)
fixTime();
}
} timeSetter;
} // anonymous namespace
sc_time::sc_time() : val(0) {}
sc_time::sc_time(double d, sc_time_unit tu)
{
val = 0;
if (d != 0)
set(this, d, tu);
}
sc_time::sc_time(const sc_time &t)
{
val = t.val;
}
sc_time::sc_time(double, bool)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
sc_time::sc_time(sc_dt::uint64, bool)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
sc_time &
sc_time::operator = (const sc_time &t)
{
val = t.val;
return *this;
}
sc_dt::uint64
sc_time::value() const
{
return val;
}
double
sc_time::to_double() const
{
return static_cast<double>(val);
}
double
sc_time::to_seconds() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return 0.0;
}
const std::string
sc_time::to_string() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return "";
}
bool
sc_time::operator == (const sc_time &t) const
{
return val == t.val;
}
bool
sc_time::operator != (const sc_time &t) const
{
return val != t.val;
}
bool
sc_time::operator < (const sc_time &t) const
{
return val < t.val;
}
bool
sc_time::operator <= (const sc_time &t) const
{
return val <= t.val;
}
bool
sc_time::operator > (const sc_time &t) const
{
return val > t.val;
}
bool
sc_time::operator >= (const sc_time &t) const
{
return val >= t.val;
}
sc_time &
sc_time::operator += (const sc_time &t)
{
val += t.val;
return *this;
}
sc_time &
sc_time::operator -= (const sc_time &t)
{
val -= t.val;
return *this;
}
sc_time &
sc_time::operator *= (double d)
{
val = static_cast<int64_t>(static_cast<double>(val) * d + 0.5);
return *this;
}
sc_time &
sc_time::operator /= (double d)
{
val = static_cast<int64_t>(static_cast<double>(val) / d + 0.5);
return *this;
}
void
sc_time::print(std::ostream &os) const
{
if (val == 0) {
os << "0 s";
} else {
//XXX Assuming the time resolution is 1ps.
sc_time_unit tu = SC_PS;
uint64_t scaled = val;
while (tu < SC_SEC && (scaled % 1000) == 0) {
tu = (sc_time_unit)((int)tu + 1);
scaled /= 1000;
}
os << scaled << ' ' << TimeUnitNames[tu];
}
}
sc_time
sc_time::from_value(sc_dt::uint64 u)
{
sc_time t;
t.val = u;
return t;
}
sc_time
sc_time::from_seconds(double)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return sc_time();
}
sc_time
sc_time::from_string(const char *str)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return sc_time();
}
const sc_time
operator + (const sc_time &a, const sc_time &b)
{
return sc_time::from_value(a.value() + b.value());
}
const sc_time
operator - (const sc_time &a, const sc_time &b)
{
return sc_time::from_value(a.value() - b.value());
}
const sc_time
operator * (const sc_time &t, double d)
{
volatile double tmp = static_cast<double>(t.value()) * d + 0.5;
return sc_time::from_value(static_cast<int64_t>(tmp));
}
const sc_time
operator * (double d, const sc_time &t)
{
volatile double tmp = d * static_cast<double>(t.value()) + 0.5;
return sc_time::from_value(static_cast<int64_t>(tmp));
}
const sc_time
operator / (const sc_time &t, double d)
{
volatile double tmp = static_cast<double>(t.value()) / d + 0.5;
return sc_time::from_value(static_cast<int64_t>(tmp));
}
double
operator / (const sc_time &t1, const sc_time &t2)
{
return t1.to_double() / t2.to_double();
}
std::ostream &
operator << (std::ostream &os, const sc_time &t)
{
t.print(os);
return os;
}
const sc_time SC_ZERO_TIME;
void
sc_set_time_resolution(double, sc_time_unit)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
sc_time
sc_get_time_resolution()
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return sc_time();
}
const sc_time &
sc_max_time()
{
static const sc_time MaxScTime = sc_time::from_value(MaxTick);
return MaxScTime;
}
void
sc_set_default_time_unit(double, sc_time_unit)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
sc_time
sc_get_default_time_unit()
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return *(sc_time *)nullptr;
}
sc_time_tuple::sc_time_tuple(const sc_time &)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
bool
sc_time_tuple::has_value() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return false;
}
sc_dt::uint64
sc_time_tuple::value() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return 0;
}
const char *
sc_time_tuple::unit_symbol() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return "";
}
double
sc_time_tuple::to_double() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return 0.0;
}
std::string
sc_time_tuple::to_string() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return "";
}
} // namespace sc_core
<commit_msg>systemc: Implement a little more of sc_time.<commit_after>/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <vector>
#include "base/logging.hh"
#include "base/types.hh"
#include "python/pybind11/pybind.hh"
#include "systemc/core/python.hh"
#include "systemc/ext/core/sc_time.hh"
namespace sc_core
{
namespace
{
const char *TimeUnitNames[] = {
[SC_FS] = "fs",
[SC_PS] = "ps",
[SC_NS] = "ns",
[SC_US] = "us",
[SC_MS] = "ms",
[SC_SEC] = "s"
};
double TimeUnitScale[] = {
[SC_FS] = 1.0e-15,
[SC_PS] = 1.0e-12,
[SC_NS] = 1.0e-9,
[SC_US] = 1.0e-6,
[SC_MS] = 1.0e-3,
[SC_SEC] = 1.0
};
bool timeFixed = false;
bool pythonReady = false;
struct SetInfo
{
SetInfo(::sc_core::sc_time *time, double d, ::sc_core::sc_time_unit tu) :
time(time), d(d), tu(tu)
{}
::sc_core::sc_time *time;
double d;
::sc_core::sc_time_unit tu;
};
std::vector<SetInfo> toSet;
void
setWork(sc_time *time, double d, ::sc_core::sc_time_unit tu)
{
//XXX Assuming the time resolution is 1ps.
double scale = TimeUnitScale[tu] / TimeUnitScale[SC_PS];
// Accellera claims there is a linux bug, and that these next two
// lines work around them.
volatile double tmp = d * scale + 0.5;
*time = sc_time::from_value(static_cast<uint64_t>(tmp));
}
void
fixTime()
{
auto ticks = pybind11::module::import("m5.ticks");
auto fix_global_frequency = ticks.attr("fixGlobalFrequency");
fix_global_frequency();
for (auto &t: toSet)
setWork(t.time, t.d, t.tu);
toSet.clear();
}
void
set(::sc_core::sc_time *time, double d, ::sc_core::sc_time_unit tu)
{
// Only fix time once.
if (!timeFixed) {
timeFixed = true;
// If we've run, python is working and we haven't fixed time yet.
if (pythonReady)
fixTime();
}
if (pythonReady) {
// Time should be working. Set up this sc_time.
setWork(time, d, tu);
} else {
// Time isn't set up yet. Defer setting up this sc_time.
toSet.emplace_back(time, d, tu);
}
}
class TimeSetter : public ::sc_gem5::PythonReadyFunc
{
public:
TimeSetter() : ::sc_gem5::PythonReadyFunc() {}
void
run() override
{
// Record that we've run and python/pybind should be usable.
pythonReady = true;
// If time is already fixed, let python know.
if (timeFixed)
fixTime();
}
} timeSetter;
} // anonymous namespace
sc_time::sc_time() : val(0) {}
sc_time::sc_time(double d, sc_time_unit tu)
{
val = 0;
if (d != 0)
set(this, d, tu);
}
sc_time::sc_time(const sc_time &t)
{
val = t.val;
}
sc_time::sc_time(double d, bool scale)
{
//XXX Assuming the time resolution is 1ps, and the default unit is 1ns.
set(this, d, scale ? SC_NS : SC_PS);
}
sc_time::sc_time(sc_dt::uint64 v, bool scale)
{
//XXX Assuming the time resolution is 1ps, and the default unit is 1ns.
set(this, static_cast<double>(v), scale ? SC_NS : SC_PS);
}
sc_time &
sc_time::operator = (const sc_time &t)
{
val = t.val;
return *this;
}
sc_dt::uint64
sc_time::value() const
{
return val;
}
double
sc_time::to_double() const
{
return static_cast<double>(val);
}
double
sc_time::to_seconds() const
{
double d = to_double();
//XXX Assuming the time resolution is 1ps.
double scale = TimeUnitScale[SC_PS] / TimeUnitScale[SC_SEC];
return d * scale;
}
const std::string
sc_time::to_string() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return "";
}
bool
sc_time::operator == (const sc_time &t) const
{
return val == t.val;
}
bool
sc_time::operator != (const sc_time &t) const
{
return val != t.val;
}
bool
sc_time::operator < (const sc_time &t) const
{
return val < t.val;
}
bool
sc_time::operator <= (const sc_time &t) const
{
return val <= t.val;
}
bool
sc_time::operator > (const sc_time &t) const
{
return val > t.val;
}
bool
sc_time::operator >= (const sc_time &t) const
{
return val >= t.val;
}
sc_time &
sc_time::operator += (const sc_time &t)
{
val += t.val;
return *this;
}
sc_time &
sc_time::operator -= (const sc_time &t)
{
val -= t.val;
return *this;
}
sc_time &
sc_time::operator *= (double d)
{
val = static_cast<int64_t>(static_cast<double>(val) * d + 0.5);
return *this;
}
sc_time &
sc_time::operator /= (double d)
{
val = static_cast<int64_t>(static_cast<double>(val) / d + 0.5);
return *this;
}
void
sc_time::print(std::ostream &os) const
{
if (val == 0) {
os << "0 s";
} else {
//XXX Assuming the time resolution is 1ps.
sc_time_unit tu = SC_PS;
uint64_t scaled = val;
while (tu < SC_SEC && (scaled % 1000) == 0) {
tu = (sc_time_unit)((int)tu + 1);
scaled /= 1000;
}
os << scaled << ' ' << TimeUnitNames[tu];
}
}
sc_time
sc_time::from_value(sc_dt::uint64 u)
{
sc_time t;
t.val = u;
return t;
}
sc_time
sc_time::from_seconds(double d)
{
sc_time t;
set(&t, d, SC_SEC);
return t;
}
sc_time
sc_time::from_string(const char *str)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return sc_time();
}
const sc_time
operator + (const sc_time &a, const sc_time &b)
{
return sc_time::from_value(a.value() + b.value());
}
const sc_time
operator - (const sc_time &a, const sc_time &b)
{
return sc_time::from_value(a.value() - b.value());
}
const sc_time
operator * (const sc_time &t, double d)
{
volatile double tmp = static_cast<double>(t.value()) * d + 0.5;
return sc_time::from_value(static_cast<int64_t>(tmp));
}
const sc_time
operator * (double d, const sc_time &t)
{
volatile double tmp = d * static_cast<double>(t.value()) + 0.5;
return sc_time::from_value(static_cast<int64_t>(tmp));
}
const sc_time
operator / (const sc_time &t, double d)
{
volatile double tmp = static_cast<double>(t.value()) / d + 0.5;
return sc_time::from_value(static_cast<int64_t>(tmp));
}
double
operator / (const sc_time &t1, const sc_time &t2)
{
return t1.to_double() / t2.to_double();
}
std::ostream &
operator << (std::ostream &os, const sc_time &t)
{
t.print(os);
return os;
}
const sc_time SC_ZERO_TIME;
void
sc_set_time_resolution(double, sc_time_unit)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
sc_time
sc_get_time_resolution()
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return sc_time();
}
const sc_time &
sc_max_time()
{
static const sc_time MaxScTime = sc_time::from_value(MaxTick);
return MaxScTime;
}
void
sc_set_default_time_unit(double, sc_time_unit)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
sc_time
sc_get_default_time_unit()
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return *(sc_time *)nullptr;
}
sc_time_tuple::sc_time_tuple(const sc_time &)
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
}
bool
sc_time_tuple::has_value() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return false;
}
sc_dt::uint64
sc_time_tuple::value() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return 0;
}
const char *
sc_time_tuple::unit_symbol() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return "";
}
double
sc_time_tuple::to_double() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return 0.0;
}
std::string
sc_time_tuple::to_string() const
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return "";
}
} // namespace sc_core
<|endoftext|> |
<commit_before>#if defined(TLANG_WITH_LLVM)
// A helper for the llvm backend
#include <llvm/Transforms/Utils/Cloning.h>
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include <llvm/Linker/Linker.h>
#include <llvm/Demangle/Demangle.h>
#include "util.h"
#include "taichi_llvm_context.h"
#include "backends/llvm_jit.h"
TLANG_NAMESPACE_BEGIN
static llvm::ExitOnError exit_on_err;
TaichiLLVMContext::TaichiLLVMContext(Arch arch) : arch(arch) {
llvm::InitializeAllTargets();
llvm::remove_fatal_error_handler();
llvm::install_fatal_error_handler(
[](void *user_data, const std::string &reason, bool gen_crash_diag) {
TC_ERROR("LLVM Fatal Error: {}", reason);
},
nullptr);
if (arch == Arch::x86_64) {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
} else {
LLVMInitializeNVPTXTarget();
LLVMInitializeNVPTXTargetMC();
LLVMInitializeNVPTXTargetInfo();
LLVMInitializeNVPTXAsmPrinter();
}
ctx = std::make_unique<llvm::LLVMContext>();
TC_INFO("Creating llvm context for arch: {}", arch_name(arch));
jit = exit_on_err(TaichiLLVMJIT::create(arch));
}
TaichiLLVMContext::~TaichiLLVMContext() {
}
llvm::Type *TaichiLLVMContext::get_data_type(DataType dt) {
if (dt == DataType::i32) {
return llvm::Type::getInt32Ty(*ctx);
} else if (dt == DataType::f32) {
return llvm::Type::getFloatTy(*ctx);
} else if (dt == DataType::f64) {
return llvm::Type::getDoubleTy(*ctx);
} else {
TC_INFO(data_type_name(dt));
TC_NOT_IMPLEMENTED
}
return nullptr;
}
std::string find_existing_command(const std::vector<std::string> &commands) {
for (auto &cmd : commands) {
if (command_exist(cmd)) {
return cmd;
}
}
TC_P(commands);
TC_ERROR("No command found.");
return "";
}
// clang++-7 -S -emit-llvm tmp0001.cpp -Ofast -std=c++14 -march=native -mfma -I
// ../headers -ffp-contract=fast -Wall -D_GLIBCXX_USE_CXX11_ABI=0 -DTLANG_CPU
// -lstdc++ -o tmp0001.bc
void compile_runtime_bitcode(Arch arch) {
static std::set<int> runtime_compiled;
if (runtime_compiled.find((int)arch) == runtime_compiled.end()) {
auto clang = find_existing_command({"clang-7", "clang"});
TC_ASSERT(command_exist("llvm-as"));
TC_TRACE("Compiling runtime module bitcode...");
auto runtime_folder = get_repo_dir() + "/src/runtime/";
std::string macro = fmt::format(" -D ARCH_{} ", arch_name(arch));
int ret = std::system(
fmt::format(
"{} -S {}runtime.cpp -o {}runtime.ll -emit-llvm -std=c++17 {}",
clang, runtime_folder, runtime_folder, macro)
.c_str());
if (ret) {
TC_ERROR("Runtime compilation failed.");
}
std::system(fmt::format("llvm-as {}runtime.ll -o {}runtime_{}.bc",
runtime_folder, runtime_folder, arch_name(arch))
.c_str());
runtime_compiled.insert((int)arch);
}
}
std::unique_ptr<llvm::Module> TaichiLLVMContext::get_init_module() {
return clone_runtime_module();
}
std::unique_ptr<llvm::Module> module_from_bitcode_file(std::string bitcode_path,
llvm::LLVMContext *ctx) {
std::ifstream ifs(bitcode_path);
std::string bitcode(std::istreambuf_iterator<char>(ifs),
(std::istreambuf_iterator<char>()));
auto runtime =
parseBitcodeFile(MemoryBufferRef(bitcode, "runtime_bitcode"), *ctx);
if (!runtime) {
TC_ERROR("Runtime bitcode load failure.");
}
bool module_broken = llvm::verifyModule(*runtime.get(), &llvm::errs());
TC_ERROR_IF(module_broken, "Module broken");
return std::move(runtime.get());
}
std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_runtime_module() {
if (!runtime_module) {
compile_runtime_bitcode(arch);
runtime_module = module_from_bitcode_file(
get_repo_dir() +
fmt::format("/src/runtime/runtime_{}.bc", arch_name(arch)),
ctx.get());
if (arch == Arch::gpu) {
auto libdevice_module = module_from_bitcode_file(
"/usr/local/cuda-10.0/nvvm/libdevice/libdevice.10.bc", ctx.get());
libdevice_module->setTargetTriple("nvptx64-nvidia-cuda");
runtime_module->setTargetTriple("nvptx64-nvidia-cuda");
runtime_module->setDataLayout(libdevice_module->getDataLayout());
auto patch_intrinsic = [&](std::string name, Intrinsic::ID intrin) {
auto func = runtime_module->getFunction(name);
func->getEntryBlock().eraseFromParent();
auto bb = llvm::BasicBlock::Create(*ctx, "entry", func);
IRBuilder<> builder(*ctx);
builder.SetInsertPoint(bb);
builder.CreateRet(builder.CreateIntrinsic(intrin, {}, {}));
};
patch_intrinsic("thread_idx", Intrinsic::nvvm_read_ptx_sreg_tid_x);
patch_intrinsic("block_idx", Intrinsic::nvvm_read_ptx_sreg_ctaid_x);
// patch_intrinsic("block_barrier", Intrinsic::nvvm_barrier0);
bool failed = llvm::Linker::linkModules(*runtime_module,
std::move(libdevice_module));
// runtime_module->print(llvm::errs(), nullptr);
if (failed) {
TC_ERROR("CUDA libdevice linking failure.");
}
}
/*
for (auto &f : *runtime_module) {
TC_INFO("Loaded runtime function: {}", std::string(f.getName()));
}
*/
}
return llvm::CloneModule(*runtime_module);
}
std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_struct_module() {
TC_ASSERT(struct_module);
/*
auto runtime = clone_runtime_module();
bool failed =
llvm::Linker::linkModules(*runtime, llvm::CloneModule(*struct_module));
if (failed) {
TC_ERROR("Runtime linking failure.");
}
*/
// return llvm::CloneModule(*struct_module);
// runtime_module->print(llvm::errs(), nullptr);
return llvm::CloneModule(*struct_module);
}
void TaichiLLVMContext::set_struct_module(
const std::unique_ptr<llvm::Module> &module) {
TC_ASSERT(module);
if (llvm::verifyModule(*module, &llvm::errs())) {
module->print(llvm::errs(), nullptr);
TC_ERROR("module broken");
}
struct_module = llvm::CloneModule(*module);
}
template <typename T>
llvm::Value *TaichiLLVMContext::get_constant(DataType dt, T t) {
if (dt == DataType::f32) {
return llvm::ConstantFP::get(*ctx, llvm::APFloat((float32)t));
} else if (dt == DataType::f64) {
return llvm::ConstantFP::get(*ctx, llvm::APFloat((float64)t));
} else if (dt == DataType::i32) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, true));
} else if (dt == DataType::u32) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, false));
} else if (dt == DataType::i64) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, true));
} else if (dt == DataType::u64) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, false));
} else {
TC_NOT_IMPLEMENTED
return nullptr;
}
}
template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, int32 t);
template <typename T>
llvm::Value *TaichiLLVMContext::get_constant(T t) {
using TargetType = T;
if constexpr (std::is_same_v<TargetType, float32> ||
std::is_same_v<TargetType, float64>) {
return llvm::ConstantFP::get(*ctx, llvm::APFloat(t));
} else if (std::is_same_v<TargetType, bool>) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(1, t, false));
} else if (std::is_same_v<TargetType, int32> ||
std::is_same_v<TargetType, uint32>) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, true));
} else if (std::is_same_v<TargetType, int64> ||
std::is_same_v<TargetType, uint64>) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, true));
} else {
TC_NOT_IMPLEMENTED
return nullptr;
}
}
std::string TaichiLLVMContext::type_name(llvm::Type *type) {
std::string type_name;
llvm::raw_string_ostream rso(type_name);
type->print(rso);
return rso.str();
}
std::size_t TaichiLLVMContext::get_type_size(llvm::Type *type) {
return jit->get_type_size(type);
}
template llvm::Value *TaichiLLVMContext::get_constant(float32 t);
template llvm::Value *TaichiLLVMContext::get_constant(float64 t);
template llvm::Value *TaichiLLVMContext::get_constant(bool t);
template llvm::Value *TaichiLLVMContext::get_constant(int32 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint32 t);
template llvm::Value *TaichiLLVMContext::get_constant(int64 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint64 t);
TLANG_NAMESPACE_END
#endif
<commit_msg>block barrier intrinsic<commit_after>#if defined(TLANG_WITH_LLVM)
// A helper for the llvm backend
#include <llvm/Transforms/Utils/Cloning.h>
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include <llvm/Linker/Linker.h>
#include <llvm/Demangle/Demangle.h>
#include "util.h"
#include "taichi_llvm_context.h"
#include "backends/llvm_jit.h"
TLANG_NAMESPACE_BEGIN
static llvm::ExitOnError exit_on_err;
TaichiLLVMContext::TaichiLLVMContext(Arch arch) : arch(arch) {
llvm::InitializeAllTargets();
llvm::remove_fatal_error_handler();
llvm::install_fatal_error_handler(
[](void *user_data, const std::string &reason, bool gen_crash_diag) {
TC_ERROR("LLVM Fatal Error: {}", reason);
},
nullptr);
if (arch == Arch::x86_64) {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
} else {
LLVMInitializeNVPTXTarget();
LLVMInitializeNVPTXTargetMC();
LLVMInitializeNVPTXTargetInfo();
LLVMInitializeNVPTXAsmPrinter();
}
ctx = std::make_unique<llvm::LLVMContext>();
TC_INFO("Creating llvm context for arch: {}", arch_name(arch));
jit = exit_on_err(TaichiLLVMJIT::create(arch));
}
TaichiLLVMContext::~TaichiLLVMContext() {
}
llvm::Type *TaichiLLVMContext::get_data_type(DataType dt) {
if (dt == DataType::i32) {
return llvm::Type::getInt32Ty(*ctx);
} else if (dt == DataType::f32) {
return llvm::Type::getFloatTy(*ctx);
} else if (dt == DataType::f64) {
return llvm::Type::getDoubleTy(*ctx);
} else {
TC_INFO(data_type_name(dt));
TC_NOT_IMPLEMENTED
}
return nullptr;
}
std::string find_existing_command(const std::vector<std::string> &commands) {
for (auto &cmd : commands) {
if (command_exist(cmd)) {
return cmd;
}
}
TC_P(commands);
TC_ERROR("No command found.");
return "";
}
// clang++-7 -S -emit-llvm tmp0001.cpp -Ofast -std=c++14 -march=native -mfma -I
// ../headers -ffp-contract=fast -Wall -D_GLIBCXX_USE_CXX11_ABI=0 -DTLANG_CPU
// -lstdc++ -o tmp0001.bc
void compile_runtime_bitcode(Arch arch) {
static std::set<int> runtime_compiled;
if (runtime_compiled.find((int)arch) == runtime_compiled.end()) {
auto clang = find_existing_command({"clang-7", "clang"});
TC_ASSERT(command_exist("llvm-as"));
TC_TRACE("Compiling runtime module bitcode...");
auto runtime_folder = get_repo_dir() + "/src/runtime/";
std::string macro = fmt::format(" -D ARCH_{} ", arch_name(arch));
int ret = std::system(
fmt::format(
"{} -S {}runtime.cpp -o {}runtime.ll -emit-llvm -std=c++17 {}",
clang, runtime_folder, runtime_folder, macro)
.c_str());
if (ret) {
TC_ERROR("Runtime compilation failed.");
}
std::system(fmt::format("llvm-as {}runtime.ll -o {}runtime_{}.bc",
runtime_folder, runtime_folder, arch_name(arch))
.c_str());
runtime_compiled.insert((int)arch);
}
}
std::unique_ptr<llvm::Module> TaichiLLVMContext::get_init_module() {
return clone_runtime_module();
}
std::unique_ptr<llvm::Module> module_from_bitcode_file(std::string bitcode_path,
llvm::LLVMContext *ctx) {
std::ifstream ifs(bitcode_path);
std::string bitcode(std::istreambuf_iterator<char>(ifs),
(std::istreambuf_iterator<char>()));
auto runtime =
parseBitcodeFile(MemoryBufferRef(bitcode, "runtime_bitcode"), *ctx);
if (!runtime) {
TC_ERROR("Runtime bitcode load failure.");
}
bool module_broken = llvm::verifyModule(*runtime.get(), &llvm::errs());
TC_ERROR_IF(module_broken, "Module broken");
return std::move(runtime.get());
}
std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_runtime_module() {
if (!runtime_module) {
compile_runtime_bitcode(arch);
runtime_module = module_from_bitcode_file(
get_repo_dir() +
fmt::format("/src/runtime/runtime_{}.bc", arch_name(arch)),
ctx.get());
if (arch == Arch::gpu) {
auto libdevice_module = module_from_bitcode_file(
"/usr/local/cuda-10.0/nvvm/libdevice/libdevice.10.bc", ctx.get());
libdevice_module->setTargetTriple("nvptx64-nvidia-cuda");
runtime_module->setTargetTriple("nvptx64-nvidia-cuda");
runtime_module->setDataLayout(libdevice_module->getDataLayout());
auto patch_intrinsic = [&](std::string name, Intrinsic::ID intrin,
bool ret = true) {
auto func = runtime_module->getFunction(name);
func->getEntryBlock().eraseFromParent();
auto bb = llvm::BasicBlock::Create(*ctx, "entry", func);
IRBuilder<> builder(*ctx);
builder.SetInsertPoint(bb);
if (ret) {
builder.CreateRet(builder.CreateIntrinsic(intrin, {}, {}));
} else {
builder.CreateIntrinsic(intrin, {}, {});
builder.CreateRetVoid();
}
};
patch_intrinsic("thread_idx", Intrinsic::nvvm_read_ptx_sreg_tid_x);
patch_intrinsic("block_idx", Intrinsic::nvvm_read_ptx_sreg_ctaid_x);
patch_intrinsic("block_barrier", Intrinsic::nvvm_barrier0, false);
bool failed = llvm::Linker::linkModules(*runtime_module,
std::move(libdevice_module));
// runtime_module->print(llvm::errs(), nullptr);
if (failed) {
TC_ERROR("CUDA libdevice linking failure.");
}
}
/*
for (auto &f : *runtime_module) {
TC_INFO("Loaded runtime function: {}", std::string(f.getName()));
}
*/
}
return llvm::CloneModule(*runtime_module);
}
std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_struct_module() {
TC_ASSERT(struct_module);
/*
auto runtime = clone_runtime_module();
bool failed =
llvm::Linker::linkModules(*runtime, llvm::CloneModule(*struct_module));
if (failed) {
TC_ERROR("Runtime linking failure.");
}
*/
// return llvm::CloneModule(*struct_module);
// runtime_module->print(llvm::errs(), nullptr);
return llvm::CloneModule(*struct_module);
}
void TaichiLLVMContext::set_struct_module(
const std::unique_ptr<llvm::Module> &module) {
TC_ASSERT(module);
if (llvm::verifyModule(*module, &llvm::errs())) {
module->print(llvm::errs(), nullptr);
TC_ERROR("module broken");
}
struct_module = llvm::CloneModule(*module);
}
template <typename T>
llvm::Value *TaichiLLVMContext::get_constant(DataType dt, T t) {
if (dt == DataType::f32) {
return llvm::ConstantFP::get(*ctx, llvm::APFloat((float32)t));
} else if (dt == DataType::f64) {
return llvm::ConstantFP::get(*ctx, llvm::APFloat((float64)t));
} else if (dt == DataType::i32) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, true));
} else if (dt == DataType::u32) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, false));
} else if (dt == DataType::i64) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, true));
} else if (dt == DataType::u64) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, false));
} else {
TC_NOT_IMPLEMENTED
return nullptr;
}
}
template llvm::Value *TaichiLLVMContext::get_constant(DataType dt, int32 t);
template <typename T>
llvm::Value *TaichiLLVMContext::get_constant(T t) {
using TargetType = T;
if constexpr (std::is_same_v<TargetType, float32> ||
std::is_same_v<TargetType, float64>) {
return llvm::ConstantFP::get(*ctx, llvm::APFloat(t));
} else if (std::is_same_v<TargetType, bool>) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(1, t, false));
} else if (std::is_same_v<TargetType, int32> ||
std::is_same_v<TargetType, uint32>) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, true));
} else if (std::is_same_v<TargetType, int64> ||
std::is_same_v<TargetType, uint64>) {
return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, true));
} else {
TC_NOT_IMPLEMENTED
return nullptr;
}
}
std::string TaichiLLVMContext::type_name(llvm::Type *type) {
std::string type_name;
llvm::raw_string_ostream rso(type_name);
type->print(rso);
return rso.str();
}
std::size_t TaichiLLVMContext::get_type_size(llvm::Type *type) {
return jit->get_type_size(type);
}
template llvm::Value *TaichiLLVMContext::get_constant(float32 t);
template llvm::Value *TaichiLLVMContext::get_constant(float64 t);
template llvm::Value *TaichiLLVMContext::get_constant(bool t);
template llvm::Value *TaichiLLVMContext::get_constant(int32 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint32 t);
template llvm::Value *TaichiLLVMContext::get_constant(int64 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint64 t);
TLANG_NAMESPACE_END
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <compressor.h>
#include <test/setup_common.h>
#include <stdint.h>
#include <boost/test/unit_test.hpp>
// amounts 0.00000001 .. 0.00100000
#define NUM_MULTIPLES_UNIT 100000
// amounts 0.01 .. 100.00
#define NUM_MULTIPLES_CENT 10000
// amounts 1 .. 10000
#define NUM_MULTIPLES_1SYS 10000
// amounts 50 .. 21000000
#define NUM_MULTIPLES_50SYS 420000
BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup)
bool static TestEncode(uint64_t in) {
return in == DecompressAmount(CompressAmount(in));
}
bool static TestDecode(uint64_t in) {
return in == CompressAmount(DecompressAmount(in));
}
bool static TestPair(uint64_t dec, uint64_t enc) {
return CompressAmount(dec) == enc &&
DecompressAmount(enc) == dec;
}
BOOST_AUTO_TEST_CASE(compress_amounts)
{
BOOST_CHECK(TestPair( 0, 0x0));
BOOST_CHECK(TestPair( 1, 0x1));
BOOST_CHECK(TestPair( CENT, 0x7));
BOOST_CHECK(TestPair( COIN, 0x9));
BOOST_CHECK(TestPair( 50*COIN, 0x32));
BOOST_CHECK(TestPair(21000000*COIN, 0x1406f40));
for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++)
BOOST_CHECK(TestEncode(i));
for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++)
BOOST_CHECK(TestEncode(i * CENT));
for (uint64_t i = 1; i <= NUM_MULTIPLES_1SYS; i++)
BOOST_CHECK(TestEncode(i * COIN));
for (uint64_t i = 1; i <= NUM_MULTIPLES_50SYS; i++)
BOOST_CHECK(TestEncode(i * 50 * COIN));
for (uint64_t i = 0; i < 100000; i++)
BOOST_CHECK(TestDecode(i));
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add unit testing for the CompressScript functions<commit_after>// Copyright (c) 2012-2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <compressor.h>
#include <test/setup_common.h>
#include <script/standard.h>
#include <stdint.h>
#include <boost/test/unit_test.hpp>
// amounts 0.00000001 .. 0.00100000
#define NUM_MULTIPLES_UNIT 100000
// amounts 0.01 .. 100.00
#define NUM_MULTIPLES_CENT 10000
// amounts 1 .. 10000
#define NUM_MULTIPLES_1SYS 10000
// amounts 50 .. 21000000
#define NUM_MULTIPLES_50SYS 420000
BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup)
bool static TestEncode(uint64_t in) {
return in == DecompressAmount(CompressAmount(in));
}
bool static TestDecode(uint64_t in) {
return in == CompressAmount(DecompressAmount(in));
}
bool static TestPair(uint64_t dec, uint64_t enc) {
return CompressAmount(dec) == enc &&
DecompressAmount(enc) == dec;
}
BOOST_AUTO_TEST_CASE(compress_amounts)
{
BOOST_CHECK(TestPair( 0, 0x0));
BOOST_CHECK(TestPair( 1, 0x1));
BOOST_CHECK(TestPair( CENT, 0x7));
BOOST_CHECK(TestPair( COIN, 0x9));
BOOST_CHECK(TestPair( 50*COIN, 0x32));
BOOST_CHECK(TestPair(21000000*COIN, 0x1406f40));
for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++)
BOOST_CHECK(TestEncode(i));
for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++)
BOOST_CHECK(TestEncode(i * CENT));
for (uint64_t i = 1; i <= NUM_MULTIPLES_1SYS; i++)
BOOST_CHECK(TestEncode(i * COIN));
for (uint64_t i = 1; i <= NUM_MULTIPLES_50SYS; i++)
BOOST_CHECK(TestEncode(i * 50 * COIN));
for (uint64_t i = 0; i < 100000; i++)
BOOST_CHECK(TestDecode(i));
}
BOOST_AUTO_TEST_CASE(compress_script_to_ckey_id)
{
// case CKeyID
CKey key;
key.MakeNewKey(true);
CPubKey pubkey = key.GetPubKey();
CScript script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK_EQUAL(script.size(), 25);
std::vector<unsigned char> out;
bool done = CompressScript(script, out);
BOOST_CHECK_EQUAL(done, true);
// Check compressed script
BOOST_CHECK_EQUAL(out.size(), 21);
BOOST_CHECK_EQUAL(out[0], 0x00);
BOOST_CHECK_EQUAL(memcmp(&out[1], &script[3], 20), 0); // compare the 20 relevant chars of the CKeyId in the script
}
BOOST_AUTO_TEST_CASE(compress_script_to_cscript_id)
{
// case CScriptID
CScript script, redeemScript;
script << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL;
BOOST_CHECK_EQUAL(script.size(), 23);
std::vector<unsigned char> out;
bool done = CompressScript(script, out);
BOOST_CHECK_EQUAL(done, true);
// Check compressed script
BOOST_CHECK_EQUAL(out.size(), 21);
BOOST_CHECK_EQUAL(out[0], 0x01);
BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 20), 0); // compare the 20 relevant chars of the CScriptId in the script
}
BOOST_AUTO_TEST_CASE(compress_script_to_compressed_pubkey_id)
{
CKey key;
key.MakeNewKey(true); // case compressed PubKeyID
CScript script = CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // COMPRESSED_PUBLIC_KEY_SIZE (33)
BOOST_CHECK_EQUAL(script.size(), 35);
std::vector<unsigned char> out;
bool done = CompressScript(script, out);
BOOST_CHECK_EQUAL(done, true);
// Check compressed script
BOOST_CHECK_EQUAL(out.size(), 33);
BOOST_CHECK_EQUAL(memcmp(&out[0], &script[1], 1), 0);
BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // compare the 32 chars of the compressed CPubKey
}
BOOST_AUTO_TEST_CASE(compress_script_to_uncompressed_pubkey_id)
{
CKey key;
key.MakeNewKey(false); // case uncompressed PubKeyID
CScript script = CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // PUBLIC_KEY_SIZE (65)
BOOST_CHECK_EQUAL(script.size(), 67); // 1 char code + 65 char pubkey + OP_CHECKSIG
std::vector<unsigned char> out;
bool done = CompressScript(script, out);
BOOST_CHECK_EQUAL(done, true);
// Check compressed script
BOOST_CHECK_EQUAL(out.size(), 33);
BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // first 32 chars of CPubKey are copied into out[1:]
BOOST_CHECK_EQUAL(out[0], 0x04 | (script[65] & 0x01)); // least significant bit (lsb) of last char of pubkey is mapped into out[0]
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <fastarduino/eeprom.h>
#include <fastarduino/devices/tones.h>
#include <fastarduino/time.h>
// Board-dependent settings
static constexpr const board::Timer NTIMER = board::Timer::TIMER1;
static constexpr const board::DigitalPin OUTPUT = board::PWMPin::D9_PB1_OC1A;
using devices::audio::Tone;
using namespace eeprom;
using GENERATOR = devices::audio::ToneGenerator<NTIMER, OUTPUT>;
struct TonePlay
{
Tone tone;
uint16_t ms;
};
// Melody to be played
TonePlay music[] EEMEM =
{
// Intro
{Tone::A1, 500},
{Tone::A1, 500},
{Tone::A1, 500},
{Tone::F1, 350},
{Tone::C2, 150},
{Tone::A1, 500},
{Tone::F1, 350},
{Tone::C2, 150},
{Tone::A1, 650},
// Marker for end of melody
{Tone::USER0, 0}
};
int main()
{
sei();
GENERATOR generator;
TonePlay* play = music;
while (true)
{
TonePlay tone;
EEPROM::read(play, tone);
if (tone.tone == Tone::USER0)
break;
generator.tone(tone.tone, tone.ms);
++play;
}
}
<commit_msg>Fix tuto sample after PWM API change.<commit_after>#include <fastarduino/eeprom.h>
#include <fastarduino/devices/tones.h>
#include <fastarduino/time.h>
// Board-dependent settings
static constexpr const board::Timer NTIMER = board::Timer::TIMER1;
static constexpr const board::PWMPin OUTPUT = board::PWMPin::D9_PB1_OC1A;
using devices::audio::Tone;
using namespace eeprom;
using GENERATOR = devices::audio::ToneGenerator<NTIMER, OUTPUT>;
struct TonePlay
{
Tone tone;
uint16_t ms;
};
// Melody to be played
TonePlay music[] EEMEM =
{
// Intro
{Tone::A1, 500},
{Tone::A1, 500},
{Tone::A1, 500},
{Tone::F1, 350},
{Tone::C2, 150},
{Tone::A1, 500},
{Tone::F1, 350},
{Tone::C2, 150},
{Tone::A1, 650},
// Marker for end of melody
{Tone::USER0, 0}
};
int main()
{
sei();
GENERATOR generator;
TonePlay* play = music;
while (true)
{
TonePlay tone;
EEPROM::read(play, tone);
if (tone.tone == Tone::USER0)
break;
generator.tone(tone.tone, tone.ms);
++play;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlnumfe.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 13:34:03 $
*
* 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 _XMLOFF_XMLNUMFE_HXX
#define _XMLOFF_XMLNUMFE_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_XMLOFF_DLLAPI_H
#include "xmloff/dllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#define XML_WRITTENNUMBERSTYLES "WrittenNumberStyles"
class Color;
class LocaleDataWrapper;
class CharClass;
class SvXMLExport;
class SvXMLNamespaceMap;
class SvXMLAttributeList;
class SvNumberFormatter;
class SvNumberformat;
class SvXMLNumUsedList_Impl;
class SvXMLEmbeddedTextEntryArr;
class XMLOFF_DLLPUBLIC SvXMLNumFmtExport
{
private:
SvXMLExport& rExport;
::rtl::OUString sPrefix;
SvNumberFormatter* pFormatter;
::rtl::OUStringBuffer sTextContent;
SvXMLNumUsedList_Impl* pUsedList;
CharClass* pCharClass;
LocaleDataWrapper* pLocaleData;
SAL_DLLPRIVATE void AddCalendarAttr_Impl( const ::rtl::OUString& rCalendar );
SAL_DLLPRIVATE void AddStyleAttr_Impl( sal_Bool bLong );
SAL_DLLPRIVATE void AddTextualAttr_Impl( sal_Bool bText );
SAL_DLLPRIVATE void AddLanguageAttr_Impl( sal_Int32 nLang );
SAL_DLLPRIVATE void AddToTextElement_Impl( const ::rtl::OUString& rString );
SAL_DLLPRIVATE void FinishTextElement_Impl();
SAL_DLLPRIVATE void WriteColorElement_Impl( const Color& rColor );
SAL_DLLPRIVATE void WriteNumberElement_Impl( sal_Int32 nDecimals, sal_Int32 nInteger,
const ::rtl::OUString& rDashStr, sal_Bool bVarDecimals,
sal_Bool bGrouping, sal_Int32 nTrailingThousands,
const SvXMLEmbeddedTextEntryArr& rEmbeddedEntries );
SAL_DLLPRIVATE void WriteScientificElement_Impl( sal_Int32 nDecimals, sal_Int32 nInteger,
sal_Bool bGrouping, sal_Int32 nExp );
SAL_DLLPRIVATE void WriteFractionElement_Impl( sal_Int32 nInteger, sal_Bool bGrouping,
sal_Int32 nNumerator, sal_Int32 nDenominator );
SAL_DLLPRIVATE void WriteCurrencyElement_Impl( const ::rtl::OUString& rString,
const ::rtl::OUString& rExt );
SAL_DLLPRIVATE void WriteBooleanElement_Impl();
SAL_DLLPRIVATE void WriteTextContentElement_Impl();
SAL_DLLPRIVATE void WriteDayElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteMonthElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong, sal_Bool bText );
SAL_DLLPRIVATE void WriteYearElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteEraElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteDayOfWeekElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteWeekElement_Impl( const ::rtl::OUString& rCalendar );
SAL_DLLPRIVATE void WriteQuarterElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteHoursElement_Impl( sal_Bool bLong );
SAL_DLLPRIVATE void WriteMinutesElement_Impl( sal_Bool bLong );
SAL_DLLPRIVATE void WriteSecondsElement_Impl( sal_Bool bLong, sal_uInt16 nDecimals );
SAL_DLLPRIVATE void WriteAMPMElement_Impl();
SAL_DLLPRIVATE void WriteMapElement_Impl( sal_Int32 nOp, double fLimit,
sal_Int32 nKey, sal_Int32 nPart );
SAL_DLLPRIVATE sal_Bool WriteTextWithCurrency_Impl( const ::rtl::OUString& rString,
const ::com::sun::star::lang::Locale& rLocale );
SAL_DLLPRIVATE void ExportPart_Impl( const SvNumberformat& rFormat, sal_uInt32 nKey,
sal_uInt16 nPart, sal_Bool bDefPart );
SAL_DLLPRIVATE void ExportFormat_Impl( const SvNumberformat& rFormat, sal_uInt32 nKey );
public:
SvXMLNumFmtExport( SvXMLExport& rExport,
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XNumberFormatsSupplier >& rSupp );
SvXMLNumFmtExport( SvXMLExport& rExport,
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XNumberFormatsSupplier >& rSupp,
const rtl::OUString& rPrefix );
virtual ~SvXMLNumFmtExport();
// core API
void Export( sal_Bool bIsAutoStyle);
// mark number format as used
void SetUsed( sal_uInt32 nKey );
// get the style name that was generated for a key
::rtl::OUString GetStyleName( sal_uInt32 nKey );
void GetWasUsed(com::sun::star::uno::Sequence<sal_Int32>& rWasUsed);
void SetWasUsed(const com::sun::star::uno::Sequence<sal_Int32>& rWasUsed);
// two methods to allow the field import/export to treat system languages
// properly:
/// obtain number format with system languange for a given key
sal_uInt32 ForceSystemLanguage( sal_uInt32 nKey );
/// determine whether number format uses system language
bool IsSystemLanguage( sal_uInt32 nKey );
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.212); FILE MERGED 2008/04/01 16:09:27 thb 1.2.212.3: #i85898# Stripping all external header guards 2008/04/01 13:04:28 thb 1.2.212.2: #i85898# Stripping all external header guards 2008/03/31 16:27:58 rt 1.2.212.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlnumfe.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XMLOFF_XMLNUMFE_HXX
#define _XMLOFF_XMLNUMFE_HXX
#include "sal/config.h"
#include "xmloff/dllapi.h"
#include "sal/types.h"
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#include <com/sun/star/uno/Sequence.h>
#include <rtl/ustrbuf.hxx>
#define XML_WRITTENNUMBERSTYLES "WrittenNumberStyles"
class Color;
class LocaleDataWrapper;
class CharClass;
class SvXMLExport;
class SvXMLNamespaceMap;
class SvXMLAttributeList;
class SvNumberFormatter;
class SvNumberformat;
class SvXMLNumUsedList_Impl;
class SvXMLEmbeddedTextEntryArr;
class XMLOFF_DLLPUBLIC SvXMLNumFmtExport
{
private:
SvXMLExport& rExport;
::rtl::OUString sPrefix;
SvNumberFormatter* pFormatter;
::rtl::OUStringBuffer sTextContent;
SvXMLNumUsedList_Impl* pUsedList;
CharClass* pCharClass;
LocaleDataWrapper* pLocaleData;
SAL_DLLPRIVATE void AddCalendarAttr_Impl( const ::rtl::OUString& rCalendar );
SAL_DLLPRIVATE void AddStyleAttr_Impl( sal_Bool bLong );
SAL_DLLPRIVATE void AddTextualAttr_Impl( sal_Bool bText );
SAL_DLLPRIVATE void AddLanguageAttr_Impl( sal_Int32 nLang );
SAL_DLLPRIVATE void AddToTextElement_Impl( const ::rtl::OUString& rString );
SAL_DLLPRIVATE void FinishTextElement_Impl();
SAL_DLLPRIVATE void WriteColorElement_Impl( const Color& rColor );
SAL_DLLPRIVATE void WriteNumberElement_Impl( sal_Int32 nDecimals, sal_Int32 nInteger,
const ::rtl::OUString& rDashStr, sal_Bool bVarDecimals,
sal_Bool bGrouping, sal_Int32 nTrailingThousands,
const SvXMLEmbeddedTextEntryArr& rEmbeddedEntries );
SAL_DLLPRIVATE void WriteScientificElement_Impl( sal_Int32 nDecimals, sal_Int32 nInteger,
sal_Bool bGrouping, sal_Int32 nExp );
SAL_DLLPRIVATE void WriteFractionElement_Impl( sal_Int32 nInteger, sal_Bool bGrouping,
sal_Int32 nNumerator, sal_Int32 nDenominator );
SAL_DLLPRIVATE void WriteCurrencyElement_Impl( const ::rtl::OUString& rString,
const ::rtl::OUString& rExt );
SAL_DLLPRIVATE void WriteBooleanElement_Impl();
SAL_DLLPRIVATE void WriteTextContentElement_Impl();
SAL_DLLPRIVATE void WriteDayElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteMonthElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong, sal_Bool bText );
SAL_DLLPRIVATE void WriteYearElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteEraElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteDayOfWeekElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteWeekElement_Impl( const ::rtl::OUString& rCalendar );
SAL_DLLPRIVATE void WriteQuarterElement_Impl( const ::rtl::OUString& rCalendar, sal_Bool bLong );
SAL_DLLPRIVATE void WriteHoursElement_Impl( sal_Bool bLong );
SAL_DLLPRIVATE void WriteMinutesElement_Impl( sal_Bool bLong );
SAL_DLLPRIVATE void WriteSecondsElement_Impl( sal_Bool bLong, sal_uInt16 nDecimals );
SAL_DLLPRIVATE void WriteAMPMElement_Impl();
SAL_DLLPRIVATE void WriteMapElement_Impl( sal_Int32 nOp, double fLimit,
sal_Int32 nKey, sal_Int32 nPart );
SAL_DLLPRIVATE sal_Bool WriteTextWithCurrency_Impl( const ::rtl::OUString& rString,
const ::com::sun::star::lang::Locale& rLocale );
SAL_DLLPRIVATE void ExportPart_Impl( const SvNumberformat& rFormat, sal_uInt32 nKey,
sal_uInt16 nPart, sal_Bool bDefPart );
SAL_DLLPRIVATE void ExportFormat_Impl( const SvNumberformat& rFormat, sal_uInt32 nKey );
public:
SvXMLNumFmtExport( SvXMLExport& rExport,
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XNumberFormatsSupplier >& rSupp );
SvXMLNumFmtExport( SvXMLExport& rExport,
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XNumberFormatsSupplier >& rSupp,
const rtl::OUString& rPrefix );
virtual ~SvXMLNumFmtExport();
// core API
void Export( sal_Bool bIsAutoStyle);
// mark number format as used
void SetUsed( sal_uInt32 nKey );
// get the style name that was generated for a key
::rtl::OUString GetStyleName( sal_uInt32 nKey );
void GetWasUsed(com::sun::star::uno::Sequence<sal_Int32>& rWasUsed);
void SetWasUsed(const com::sun::star::uno::Sequence<sal_Int32>& rWasUsed);
// two methods to allow the field import/export to treat system languages
// properly:
/// obtain number format with system languange for a given key
sal_uInt32 ForceSystemLanguage( sal_uInt32 nKey );
/// determine whether number format uses system language
bool IsSystemLanguage( sal_uInt32 nKey );
};
#endif
<|endoftext|> |
<commit_before>/*
Solution to this task can be found at our blog.
You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by a zero-indexed array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.
The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.
Write a function:
int solution(vector<int> &H);
that, given a zero-indexed array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.
For example, given array H containing N = 9 integers:
H[0] = 8 H[1] = 8 H[2] = 5
H[3] = 7 H[4] = 9 H[5] = 8
H[6] = 7 H[7] = 4 H[8] = 8
the function should return 7. The figure shows one possible arrangement of seven blocks.
Assume that:
N is an integer within the range [1..100,000];
each element of array H is an integer within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Copyright 2009–2015 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
*/
// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &H) {
// write your code in C++11
vector<int> stack;
int count(0);
unsigned int i(0);
while( i<H.size() ) {
if( stack.empty() ) {
stack.push_back( H[i] );
count++;
i++;
}
else {
while( !stack.empty() && stack.back()>H[i] ) {
stack.pop_back();
}
if( stack.empty() )
continue;
else if( stack.back()==H[i] ) {
i++;
}
else if( stack.back()<H[i] ) {
stack.push_back( H[i] );
count++;
i++;
}
}
}
return count;
}
<commit_msg>Update solution.cpp<commit_after>// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &H) {
// write your code in C++11
vector<int> stack;
int count(0);
unsigned int i(0);
while( i<H.size() ) {
if( stack.empty() ) {
stack.push_back( H[i] );
count++;
i++;
}
else {
while( !stack.empty() && stack.back()>H[i] ) {
stack.pop_back();
}
if( stack.empty() )
continue;
else if( stack.back()==H[i] ) {
i++;
}
else if( stack.back()<H[i] ) {
stack.push_back( H[i] );
count++;
i++;
}
}
}
return count;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_ppe_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_ppe_utils.H
/// @brief PPE commonly used functions
///
/// *HWP HW Owner : Ashish More <ashish.more.@in.ibm.com>
/// *HWP HW Backup Owner : Brian Vanderpool <vanderp@us.ibm.com>
/// *HWP FW Owner : Sangeetha T S <sangeet2@in.ibm.com>
/// *HWP Team : PM
/// *HWP Level : 2
/// *HWP Consumed by : CMEs, GPEs, SBE, Cronus
#include <map>
#ifndef __P9_PPE_UTILS_H__
#define __P9_PPE_UTILS_H__
typedef struct
{
uint16_t number;
uint32_t value;
} PPERegValue_t;
typedef struct
{
PPERegValue_t reg;
std::string name;
} PPEReg_t;
typedef struct
{
uint16_t number;
uint64_t value;
} SCOMRegValue_t;
typedef struct
{
SCOMRegValue_t reg;
std::string name;
} SCOMReg_t;
/**
* @brief enumerates opcodes for few instructions.
*/
enum
{
OPCODE_31 = 31,
MTSPR_CONST1 = 467,
MTSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MTSPR_CONST1 << (31 - 30)),
MFSPR_CONST1 = 339,
MFSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MFSPR_CONST1 << (31 - 30)),
MFMSRD_CONST1 = 83,
MFCR_CONST1 = 19,
ANDIS_CONST = 29,
ORIS_CONST = 25,
};
/**
* @brief Offsets from base address for XIRs.
*/
const static uint64_t PPE_XIXCR = 0x0; //XCR_NONE
const static uint64_t PPE_XIRAMRA = 0x1; //XCR_SPRG0
const static uint64_t PPE_XIRAMGA = 0x2; //IR_SPRG0
const static uint64_t PPE_XIRAMDBG = 0x3; //XSR_SPRG0
const static uint64_t PPE_XIRAMEDR = 0x4; //IR_EDR
const static uint64_t PPE_XIDBGPRO = 0x5; //XSR_IAR
enum PPE_DUMP_MODE
{
NONE = 0x0,
XIRS = 0x4,
SNAPSHOT = 0x1,
HALT = 0x2,
FORCE_HALT = 0x3
};
enum VERBOSE_MODE
{
NOVERBOSE = 0x0,
VERBOSE = 0x1,
VERBOSEP = 0x2,
VERBOSE1 = 0x3,
};
enum INT_VEC_OFFSET
{
MCHK_VEC = 0x000 , // 0,
SRST_VEC = 0x040 , // 64,
DSI_VEC = 0x060 , // 96,
ISI_VEC = 0x080 , // 128,
EXT_VEC = 0x0A0 , // 160,
ALIG_VEC = 0x0C0 , // 192,
PRG_VEC = 0x0E0 , // 224,
DEC_VEC = 0x100 , // 256,
FIT_VEC = 0x120 , // 288,
WDT_VEC = 0x140 , // 320,
} ;
enum PPE_XIRS
{
XIR_XSR,
XIR_IAR,
XIR_IR,
XIR_EDR,
XIR_SPRG0,
};
//enum PPE_SPECIAL_ACCESS
//{
// MSR,
// CR,
//};
enum PPE_SPRS
{
CTR = 9,
DACR = 316,
DBCR = 308,
DEC = 22,
EDR = 61,
IVPR = 63,
ISR = 62,
LR = 8,
PIR = 286,
PVR = 287,
SPRG0 = 272,
SRR0 = 26,
SRR1 = 27,
TCR = 340,
TSR = 336,
XER = 1,
//Some unique identification no. FOR OTHER REGS(non sprn)
XSR = 4200,
IAR = 2,
IR = 3,
MSR = 42,
CR = 420,
};
// Note: EDR is available via XIR
enum PPE_GPRS
{
R0 = 0,
R1 = 1,
R2 = 2,
R3 = 3,
R4 = 4,
R5 = 5,
R6 = 6,
R7 = 7,
R8 = 8,
R9 = 9,
R10 = 10,
R13 = 13,
R28 = 28,
R29 = 29,
R30 = 30,
R31 = 31,
};
// Vector defining all spr acceess egisters
const std::map<uint16_t, std::string> v_ppe_sprs_num_name =
{
{ MSR, "MSR" },
{ CR, "CR" },
{ CTR, "CTR" },
{ LR, "LR" },
{ ISR, "ISR" },
{ SRR0, "SRR0" },
{ SRR1, "SRR1" },
{ TCR, "TCR" },
{ TSR, "TSR" },
{ DACR, "DACR" },
{ DBCR, "DBCR" },
{ DEC, "DEC" },
{ IVPR, "IVPR" },
{ PIR, "PIR" },
{ PVR, "PVR" },
{ XER, "XER" }
};
// Vector defining the GPRs
const std::map<uint16_t, std::string> v_ppe_gprs_num_name =
{
{ R0, "R0" },
{ R1, "R1" },
{ R2, "R2" },
{ R3, "R3" },
{ R4, "R4" },
{ R5, "R5" },
{ R6, "R6" },
{ R7, "R7" },
{ R8, "R8" },
{ R9, "R9" },
{ R10, "R10" },
{ R13, "R13" },
{ R28, "R28" },
{ R29, "R29" },
{ R30, "R30" },
{ R31, "R31" }
};
// Vector defining the other xsr regs
const std::map<uint16_t, std::string> v_ppe_xsr_num_name =
{
{ XSR, "XSR" },
{ IAR, "IAR" },
{ IR, "IR" },
{ EDR, "EDR" },
{ SPRG0, "SPRG0" }
};
#endif // __P9_PPE_UTILS_H__
<commit_msg>PM: PPE State tool fixes.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_ppe_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_ppe_utils.H
/// @brief PPE commonly used functions
///
/// *HWP HW Owner : Ashish More <ashish.more.@in.ibm.com>
/// *HWP HW Backup Owner : Brian Vanderpool <vanderp@us.ibm.com>
/// *HWP FW Owner : Sangeetha T S <sangeet2@in.ibm.com>
/// *HWP Team : PM
/// *HWP Level : 3
/// *HWP Consumed by : Cronus, HB, FSP
#ifndef __P9_PPE_UTILS_H__
#define __P9_PPE_UTILS_H__
#include <map>
#include <fapi2.H>
typedef struct
{
uint16_t number;
uint32_t value;
} PPERegValue_t;
typedef struct
{
uint16_t number;
uint64_t value;
} SCOMRegValue_t;
/**
* @brief enumerates opcodes for few instructions.
*/
enum
{
OPCODE_31 = 31,
MTSPR_CONST1 = 467,
MTSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MTSPR_CONST1 << (31 - 30)),
MFSPR_CONST1 = 339,
MFSPR_BASE_OPCODE = (OPCODE_31 << (31 - 5)) | (MFSPR_CONST1 << (31 - 30)),
MFMSRD_CONST1 = 83,
MFCR_CONST1 = 19,
ANDIS_CONST = 29,
ORIS_CONST = 25,
};
/**
* @brief Offsets from base address for XIRs.
*/
const static uint64_t PPE_XIXCR = 0x0; //XCR_NONE
const static uint64_t PPE_XIRAMRA = 0x1; //XCR_SPRG0
const static uint64_t PPE_XIRAMGA = 0x2; //IR_SPRG0
const static uint64_t PPE_XIRAMDBG = 0x3; //XSR_SPRG0
const static uint64_t PPE_XIRAMEDR = 0x4; //IR_EDR
const static uint64_t PPE_XIDBGPRO = 0x5; //XSR_IAR
enum PPE_DUMP_MODE
{
NONE = 0x0,
XIRS = 0x4,
SNAPSHOT = 0x1,
HALT = 0x2,
FORCE_HALT = 0x3
};
enum VERBOSE_MODE
{
NOVERBOSE = 0x0,
VERBOSE = 0x1,
VERBOSEP = 0x2,
VERBOSE1 = 0x3,
};
enum INT_VEC_OFFSET
{
MCHK_VEC = 0x000 , // 0,
SRST_VEC = 0x040 , // 64,
DSI_VEC = 0x060 , // 96,
ISI_VEC = 0x080 , // 128,
EXT_VEC = 0x0A0 , // 160,
ALIG_VEC = 0x0C0 , // 192,
PRG_VEC = 0x0E0 , // 224,
DEC_VEC = 0x100 , // 256,
FIT_VEC = 0x120 , // 288,
WDT_VEC = 0x140 , // 320,
} ;
enum PPE_XIRS
{
XIR_XSR,
XIR_IAR,
XIR_IR,
XIR_EDR,
XIR_SPRG0,
};
//enum PPE_SPECIAL_ACCESS
//{
// MSR,
// CR,
//};
enum PPE_SPRS
{
CTR = 9,
DACR = 316,
DBCR = 308,
DEC = 22,
EDR = 61,
IVPR = 63,
ISR = 62,
LR = 8,
PIR = 286,
PVR = 287,
SPRG0 = 272,
SRR0 = 26,
SRR1 = 27,
TCR = 340,
TSR = 336,
XER = 1,
//Some unique identification no. FOR OTHER REGS(non sprn)
XSR = 4200,
IAR = 2,
IR = 3,
MSR = 42,
CR = 420,
};
// Note: EDR is available via XIR
enum PPE_GPRS
{
R0 = 0,
R1 = 1,
R2 = 2,
R3 = 3,
R4 = 4,
R5 = 5,
R6 = 6,
R7 = 7,
R8 = 8,
R9 = 9,
R10 = 10,
R13 = 13,
R28 = 28,
R29 = 29,
R30 = 30,
R31 = 31,
};
#ifndef __HOSTBOOT_MODULE
typedef struct
{
SCOMRegValue_t reg;
std::string name;
} SCOMReg_t;
typedef struct
{
PPERegValue_t reg;
std::string name;
} PPEReg_t;
// Vector defining all spr acceess egisters
const std::map<uint16_t, std::string> v_ppe_sprs_num_name =
{
{ MSR, "MSR" },
{ CR, "CR" },
{ CTR, "CTR" },
{ LR, "LR" },
{ ISR, "ISR" },
{ SRR0, "SRR0" },
{ SRR1, "SRR1" },
{ TCR, "TCR" },
{ TSR, "TSR" },
{ DACR, "DACR" },
{ DBCR, "DBCR" },
{ DEC, "DEC" },
{ IVPR, "IVPR" },
{ PIR, "PIR" },
{ PVR, "PVR" },
{ XER, "XER" }
};
// Vector defining the GPRs
const std::map<uint16_t, std::string> v_ppe_gprs_num_name =
{
{ R0, "R0" },
{ R1, "R1" },
{ R2, "R2" },
{ R3, "R3" },
{ R4, "R4" },
{ R5, "R5" },
{ R6, "R6" },
{ R7, "R7" },
{ R8, "R8" },
{ R9, "R9" },
{ R10, "R10" },
{ R13, "R13" },
{ R28, "R28" },
{ R29, "R29" },
{ R30, "R30" },
{ R31, "R31" }
};
// Vector defining the other xsr regs
const std::map<uint16_t, std::string> v_ppe_xsr_num_name =
{
{ XSR, "XSR" },
{ IAR, "IAR" },
{ IR, "IR" },
{ EDR, "EDR" },
{ SPRG0, "SPRG0" }
};
#endif //__HOSTBOOT_MODULE
///--------------------------------------------------------------------------------------
/// @brief generates a PPE instruction for some formats
/// @param[in] i_Op Opcode
/// @param[in] i_Rts Source or Target Register
/// @param[in] i_RA Address Register
/// @param[in] i_d Instruction Data Field
/// @return returns 32 bit instruction representing the PPE instruction.
///--------------------------------------------------------------------------------------
uint32_t ppe_getInstruction( const uint16_t i_Op, const uint16_t i_Rts, const uint16_t i_Ra, const uint16_t i_d );
///--------------------------------------------------------------------------------------
/// @brief generates instruction for mtspr
/// @param[in] i_Rs source register number
/// @param[in] i_Spr represents spr where data is to be moved.
/// @return returns 32 bit instruction representing mtspr instruction.
///--------------------------------------------------------------------------------------
uint32_t ppe_getMtsprInstruction( const uint16_t i_Rs, const uint16_t i_Spr );
///--------------------------------------------------------------------------------------
/// @brief generates instruction for mfspr
/// @param[in] i_Rt target register number
/// @param[in] i_Spr represents spr where data is to sourced
/// @return returns 32 bit instruction representing mfspr instruction.
///--------------------------------------------------------------------------------------
uint32_t ppe_getMfsprInstruction( const uint16_t i_Rt, const uint16_t i_Spr );
///--------------------------------------------------------------------------------------
/// @brief generates instruction for mfmsr instruction.
/// @param[in] i_Rt target register number
/// @return returns 32 bit instruction representing mfmsr instruction.
/// @note moves contents of register MSR to i_Rt register.
///--------------------------------------------------------------------------------------
uint32_t ppe_getMfmsrInstruction( const uint16_t i_Rt );
///--------------------------------------------------------------------------------------
/// @brief generates instruction for mfcr instruction.
/// @param[in] i_Rt target register number
/// @return returns 32 bit instruction representing mfcr instruction.
/// @note moves contents of register CR to i_Rt register.
///--------------------------------------------------------------------------------------
uint32_t ppe_getMfcrInstruction( const uint16_t i_Rt );
///--------------------------------------------------------------------------------------
/// @brief poll for Halt state
/// @param[in] i_target fapi2 target for proc chip
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note moves contents of register MSR to i_Rt register.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_pollHaltState(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address) ;
///--------------------------------------------------------------------------------------
/// @brief halt the engine
/// @param[in] i_target fapi2 target for proc chip
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR with halt bit to halt the engine.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_halt(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief force halt the engine
/// @param[in] i_target fapi2 target for proc chip
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR with force halt to force halt the engine.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_force_halt(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief resume the halted engine
/// @param[in] i_target fapi2 target for proc chip
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR with resume bit to resume the engine.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_resume(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief update dbcr
/// @param[in] i_target fapi2 target for proc chip
/// @param[in] i_base_address base SCOM address of the PPE
/// @param[in] i_inst_op instruction opcode
/// @param[in] i_immed_16 16 bit constant
/// @param[in] i_Rs source GPR number
/// @return fapi2::ReturnCode
/// @note programs mtdbcr
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_update_dbcr(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address,
const uint64_t i_inst_op,
const uint16_t i_immed_16,
const uint16_t i_Rs );
///--------------------------------------------------------------------------------------
/// @brief update dacr
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @param[in] i_address address to be updated
/// @return fapi2::ReturnCode
/// @note programs mtdacr
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_update_dacr(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address,
const uint64_t i_address,
const uint16_t i_Rs );
///--------------------------------------------------------------------------------------
/// @brief Perform RAM "read" operation
/// @param[in] i_target Chip Target
/// @param[in] i_base_address base SCOM address of the PPE
/// @param[in] i_instruction RAM instruction to move a register
/// @param[out] o_data Returned data
/// @return fapi2::ReturnCode
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_RAMRead(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address,
const fapi2::buffer<uint64_t> i_instruction,
fapi2::buffer<uint32_t>& o_data );
///--------------------------------------------------------------------------------------
/// @brief Perform RAM "read" operation
/// @param[in] i_target Chip Target
/// @param[in] i_base_address base SCOM address of the PPE
/// @param[in] i_instruction RAM instruction to move a register
/// @return fapi2::ReturnCode
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_RAM(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address,
const uint64_t i_instruction
);
///--------------------------------------------------------------------------------------
/// @brief single step the engine
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @param[in] i_Rs
/// @param[in] i_step_count
/// @return fapi2::ReturnCode
/// @note programs XCR with single step tosingle step the engine.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_single_step(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address,
const uint16_t i_Rs,
uint64_t i_step_count );
///--------------------------------------------------------------------------------------
/// @brief clear the dbg status engine
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR to clear dbg status.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_clear_dbg(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief toggle TRH
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR to toggle trh.
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_toggle_trh(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief xcr soft reset
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR to give soft reset
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_soft_reset(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief xcr hard reset
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR to give hard reset
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_hard_reset(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief xcr resume only
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @return fapi2::ReturnCode
/// @note programs XCR to only resume
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_resume_only(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address );
///--------------------------------------------------------------------------------------
/// @brief only single step the engine
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @param[in] i_step_count
/// @return fapi2::ReturnCode
/// @note programs XCR with single step no clearing DBCR
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_ss_only(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address,
uint64_t i_step_count );
///--------------------------------------------------------------------------------------
/// @brief populate IAR register with a given address
/// @param[in] i_target target register number
/// @param[in] i_base_address base SCOM address of the PPE
/// @param[in] i_address address to be populated
/// @return fapi2::ReturnCode
/// @note programs XCR with single step no clearing DBCR
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_write_iar(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_base_address,
const uint64_t i_address );
#ifndef __HOSTBOOT_MODULE
///--------------------------------------------------------------------------------------
/// @brief finds name of SCOM registers and populates a vector
/// @param[in] i_ppe_regs_value a vector of SCOMRegValue_t
/// @param[in] i_ppe_regs_num_name a map of reg num and respective name
/// @param[in] i_scom_regs a vector of SCOMReg_t
/// @return fapi2::ReturnCode
///--------------------------------------------------------------------------------------
fapi2::ReturnCode scom_regs_populate_name(
std::vector<SCOMRegValue_t> i_ppe_regs_value,
const std::map<uint16_t, std::string> i_ppe_regs_num_name,
std::vector<SCOMReg_t>& i_scom_regs );
///--------------------------------------------------------------------------------------
/// @brief populates register names
/// @param[in] i_ppe_regs_value
/// @param[in] i_ppe_regs_num_name
/// @param[in] i_ppe_regs
/// @return fapi2::ReturnCode
///--------------------------------------------------------------------------------------
fapi2::ReturnCode ppe_regs_populate_name(
std::vector<PPERegValue_t> i_ppe_regs_value,
const std::map<uint16_t, std::string> i_ppe_regs_num_name,
std::vector<PPEReg_t>& i_ppe_regs );
#endif //__HOSTBOOT_MODULE
#endif // __P9_PPE_UTILS_H__
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tempfile.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:17:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "tempfile.hxx"
#include "comdep.hxx"
#include <rtl/ustring.hxx>
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
#ifndef _TOOLS_TIME_HXX
#include <time.hxx>
#endif
#include <debug.hxx>
#include <stdio.h>
#ifdef UNX
#define _MAX_PATH 260
#endif
using namespace osl;
namespace { struct TempNameBase_Impl : public rtl::Static< ::rtl::OUString, TempNameBase_Impl > {}; }
struct TempFile_Impl
{
String aName;
sal_Bool bIsDirectory;
};
String GetSystemTempDir_Impl()
{
char sBuf[_MAX_PATH];
const char *pDir = TempDirImpl(sBuf);
::rtl::OString aTmpA( pDir );
::rtl::OUString aTmp = ::rtl::OStringToOUString( aTmpA, osl_getThreadTextEncoding() );
rtl::OUString aRet;
FileBase::getFileURLFromSystemPath( aTmp, aRet );
String aName = aRet;
sal_Int32 i = aName.Len();
if( aName.GetChar(i-1) != '/' )
aName += '/';
return aName;
}
#define TMPNAME_SIZE ( 1 + 5 + 5 + 4 + 1 )
String ConstructTempDir_Impl( const String* pParent )
{
String aName;
if ( pParent && pParent->Len() )
{
// if parent given try to use it
rtl::OUString aTmp( *pParent );
rtl::OUString aRet;
// test for valid filename
{
::osl::DirectoryItem aItem;
sal_Int32 i = aRet.getLength();
if ( aRet[i-1] == '/' )
i--;
if ( DirectoryItem::get( ::rtl::OUString( aRet, i ), aItem ) == FileBase::E_None )
aName = aRet;
}
}
if ( !aName.Len() )
{
// if no parent or invalid parent : use system directory
::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();
if ( !rTempNameBase_Impl.getLength() )
rTempNameBase_Impl = GetSystemTempDir_Impl();
aName = rTempNameBase_Impl;
}
// Make sure that directory ends with a separator
sal_Int32 i = aName.Len();
if( i>0 && aName.GetChar(i-1) != '/' )
aName += '/';
return aName;
}
void CreateTempName_Impl( String& rName, sal_Bool bKeep, sal_Bool bDir = sal_True )
{
// add a suitable tempname
// Prefix can have 5 chars, leaving 3 for numbers. 26 ** 3 == 17576
// ER 13.07.00 why not radix 36 [0-9A-Z] ?!?
const unsigned nRadix = 26;
String aName( rName );
aName += String::CreateFromAscii( "sv" );
sal_Int32 i = aName.Len();
rName.Erase();
static unsigned long u = Time::GetSystemTicks();
for ( unsigned long nOld = u; ++u != nOld; )
{
u %= (nRadix*nRadix*nRadix);
String aTmp( aName );
aTmp += String::CreateFromInt32( (sal_Int32) (unsigned) u, nRadix );
aTmp += String::CreateFromAscii( ".tmp" );
if ( bDir )
{
FileBase::RC err = Directory::create( aTmp );
if ( err == FileBase::E_None )
{
// !bKeep: only for creating a name, not a file or directory
if ( bKeep || Directory::remove( aTmp ) == FileBase::E_None )
rName = aTmp;
break;
}
else if ( err != FileBase::E_EXIST )
{
// if f.e. name contains invalid chars stop trying to create dirs
break;
}
}
else
{
DBG_ASSERT( bKeep, "Too expensive, use directory for creating name!" );
File aFile( aTmp );
FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);
if ( err == FileBase::E_None )
{
rName = aTmp;
aFile.close();
break;
}
else if ( err != FileBase::E_EXIST )
{
// if f.e. name contains invalid chars stop trying to create files
break;
}
}
}
}
String TempFile::CreateTempName( const String* pParent )
{
// get correct directory
String aName = ConstructTempDir_Impl( pParent );
// get TempFile name with default naming scheme
CreateTempName_Impl( aName, sal_False );
// convert to file URL
rtl::OUString aTmp;
if ( aName.Len() )
aTmp = aName;
return aTmp;
}
TempFile::TempFile( const String* pParent, sal_Bool bDirectory )
: pImp( new TempFile_Impl )
, bKillingFileEnabled( sal_False )
{
pImp->bIsDirectory = bDirectory;
// get correct directory
pImp->aName = ConstructTempDir_Impl( pParent );
// get TempFile with default naming scheme
CreateTempName_Impl( pImp->aName, sal_True, bDirectory );
}
TempFile::TempFile( const String& rLeadingChars, const String* pExtension, const String* pParent, sal_Bool bDirectory )
: pImp( new TempFile_Impl )
, bKillingFileEnabled( sal_False )
{
pImp->bIsDirectory = bDirectory;
// get correct directory
String aName = ConstructTempDir_Impl( pParent );
// now use special naming scheme ( name takes leading chars and an index counting up from zero
aName += rLeadingChars;
for ( sal_Int32 i=0;; i++ )
{
String aTmp( aName );
aTmp += String::CreateFromInt32( i );
if ( pExtension )
aTmp += *pExtension;
else
aTmp += String::CreateFromAscii( ".tmp" );
if ( bDirectory )
{
FileBase::RC err = Directory::create( aTmp );
if ( err == FileBase::E_None )
{
pImp->aName = aTmp;
break;
}
else if ( err != FileBase::E_EXIST )
// if f.e. name contains invalid chars stop trying to create dirs
break;
}
else
{
File aFile( aTmp );
FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);
if ( err == FileBase::E_None )
{
pImp->aName = aTmp;
aFile.close();
break;
}
else if ( err != FileBase::E_EXIST )
// if f.e. name contains invalid chars stop trying to create dirs
break;
}
}
}
TempFile::~TempFile()
{
if ( bKillingFileEnabled )
{
if ( pImp->bIsDirectory )
{
// at the moment no recursiv algorithm present
Directory::remove( pImp->aName );
}
else
{
File::remove( pImp->aName );
}
}
delete pImp;
}
sal_Bool TempFile::IsValid() const
{
return pImp->aName.Len() != 0;
}
String TempFile::GetName() const
{
rtl::OUString aTmp;
aTmp = pImp->aName;
return aTmp;
}
String TempFile::SetTempNameBaseDirectory( const String &rBaseName )
{
String aName( rBaseName );
::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();
FileBase::RC err= Directory::create( aName );
if ( err == FileBase::E_None || err == FileBase::E_EXIST )
{
rTempNameBase_Impl = aName;
rTempNameBase_Impl += String( '/' );
TempFile aBase( NULL, sal_True );
if ( aBase.IsValid() )
rTempNameBase_Impl = aBase.pImp->aName;
}
rtl::OUString aTmp;
aTmp = rTempNameBase_Impl;
return aTmp;
}
String TempFile::GetTempNameBaseDirectory()
{
::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();
if ( !rTempNameBase_Impl.getLength() )
rTempNameBase_Impl = GetSystemTempDir_Impl();
rtl::OUString aTmp;
aTmp = rTempNameBase_Impl;
return aTmp;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.8.8); FILE MERGED 2006/02/24 14:48:54 sb 1.8.8.2: #i53898# Made code warning-free; removed dead code. 2005/10/14 11:19:33 sb 1.8.8.1: #i53898# Made code warning-free; cleanup.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tempfile.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-06-19 13:42:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "tempfile.hxx"
#include "comdep.hxx"
#include <rtl/ustring.hxx>
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
#ifndef _TOOLS_TIME_HXX
#include <time.hxx>
#endif
#include <debug.hxx>
#include <stdio.h>
#ifdef UNX
#define _MAX_PATH 260
#endif
using namespace osl;
namespace { struct TempNameBase_Impl : public rtl::Static< ::rtl::OUString, TempNameBase_Impl > {}; }
struct TempFile_Impl
{
String aName;
sal_Bool bIsDirectory;
};
String GetSystemTempDir_Impl()
{
char sBuf[_MAX_PATH];
const char *pDir = TempDirImpl(sBuf);
::rtl::OString aTmpA( pDir );
::rtl::OUString aTmp = ::rtl::OStringToOUString( aTmpA, osl_getThreadTextEncoding() );
rtl::OUString aRet;
FileBase::getFileURLFromSystemPath( aTmp, aRet );
String aName = aRet;
if( aName.GetChar(aName.Len()-1) != '/' )
aName += '/';
return aName;
}
#define TMPNAME_SIZE ( 1 + 5 + 5 + 4 + 1 )
String ConstructTempDir_Impl( const String* pParent )
{
String aName;
if ( pParent && pParent->Len() )
{
// if parent given try to use it
rtl::OUString aTmp( *pParent );
rtl::OUString aRet;
// test for valid filename
{
::osl::DirectoryItem aItem;
sal_Int32 i = aRet.getLength();
if ( aRet[i-1] == '/' )
i--;
if ( DirectoryItem::get( ::rtl::OUString( aRet, i ), aItem ) == FileBase::E_None )
aName = aRet;
}
}
if ( !aName.Len() )
{
// if no parent or invalid parent : use system directory
::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();
if ( !rTempNameBase_Impl.getLength() )
rTempNameBase_Impl = GetSystemTempDir_Impl();
aName = rTempNameBase_Impl;
}
// Make sure that directory ends with a separator
xub_StrLen i = aName.Len();
if( i>0 && aName.GetChar(i-1) != '/' )
aName += '/';
return aName;
}
void CreateTempName_Impl( String& rName, sal_Bool bKeep, sal_Bool bDir = sal_True )
{
// add a suitable tempname
// Prefix can have 5 chars, leaving 3 for numbers. 26 ** 3 == 17576
// ER 13.07.00 why not radix 36 [0-9A-Z] ?!?
const unsigned nRadix = 26;
String aName( rName );
aName += String::CreateFromAscii( "sv" );
rName.Erase();
static unsigned long u = Time::GetSystemTicks();
for ( unsigned long nOld = u; ++u != nOld; )
{
u %= (nRadix*nRadix*nRadix);
String aTmp( aName );
aTmp += String::CreateFromInt32( (sal_Int32) (unsigned) u, nRadix );
aTmp += String::CreateFromAscii( ".tmp" );
if ( bDir )
{
FileBase::RC err = Directory::create( aTmp );
if ( err == FileBase::E_None )
{
// !bKeep: only for creating a name, not a file or directory
if ( bKeep || Directory::remove( aTmp ) == FileBase::E_None )
rName = aTmp;
break;
}
else if ( err != FileBase::E_EXIST )
{
// if f.e. name contains invalid chars stop trying to create dirs
break;
}
}
else
{
DBG_ASSERT( bKeep, "Too expensive, use directory for creating name!" );
File aFile( aTmp );
FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);
if ( err == FileBase::E_None )
{
rName = aTmp;
aFile.close();
break;
}
else if ( err != FileBase::E_EXIST )
{
// if f.e. name contains invalid chars stop trying to create files
break;
}
}
}
}
String TempFile::CreateTempName( const String* pParent )
{
// get correct directory
String aName = ConstructTempDir_Impl( pParent );
// get TempFile name with default naming scheme
CreateTempName_Impl( aName, sal_False );
// convert to file URL
rtl::OUString aTmp;
if ( aName.Len() )
aTmp = aName;
return aTmp;
}
TempFile::TempFile( const String* pParent, sal_Bool bDirectory )
: pImp( new TempFile_Impl )
, bKillingFileEnabled( sal_False )
{
pImp->bIsDirectory = bDirectory;
// get correct directory
pImp->aName = ConstructTempDir_Impl( pParent );
// get TempFile with default naming scheme
CreateTempName_Impl( pImp->aName, sal_True, bDirectory );
}
TempFile::TempFile( const String& rLeadingChars, const String* pExtension, const String* pParent, sal_Bool bDirectory )
: pImp( new TempFile_Impl )
, bKillingFileEnabled( sal_False )
{
pImp->bIsDirectory = bDirectory;
// get correct directory
String aName = ConstructTempDir_Impl( pParent );
// now use special naming scheme ( name takes leading chars and an index counting up from zero
aName += rLeadingChars;
for ( sal_Int32 i=0;; i++ )
{
String aTmp( aName );
aTmp += String::CreateFromInt32( i );
if ( pExtension )
aTmp += *pExtension;
else
aTmp += String::CreateFromAscii( ".tmp" );
if ( bDirectory )
{
FileBase::RC err = Directory::create( aTmp );
if ( err == FileBase::E_None )
{
pImp->aName = aTmp;
break;
}
else if ( err != FileBase::E_EXIST )
// if f.e. name contains invalid chars stop trying to create dirs
break;
}
else
{
File aFile( aTmp );
FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);
if ( err == FileBase::E_None )
{
pImp->aName = aTmp;
aFile.close();
break;
}
else if ( err != FileBase::E_EXIST )
// if f.e. name contains invalid chars stop trying to create dirs
break;
}
}
}
TempFile::~TempFile()
{
if ( bKillingFileEnabled )
{
if ( pImp->bIsDirectory )
{
// at the moment no recursiv algorithm present
Directory::remove( pImp->aName );
}
else
{
File::remove( pImp->aName );
}
}
delete pImp;
}
sal_Bool TempFile::IsValid() const
{
return pImp->aName.Len() != 0;
}
String TempFile::GetName() const
{
rtl::OUString aTmp;
aTmp = pImp->aName;
return aTmp;
}
String TempFile::SetTempNameBaseDirectory( const String &rBaseName )
{
String aName( rBaseName );
::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();
FileBase::RC err= Directory::create( aName );
if ( err == FileBase::E_None || err == FileBase::E_EXIST )
{
rTempNameBase_Impl = aName;
rTempNameBase_Impl += String( '/' );
TempFile aBase( NULL, sal_True );
if ( aBase.IsValid() )
rTempNameBase_Impl = aBase.pImp->aName;
}
rtl::OUString aTmp;
aTmp = rTempNameBase_Impl;
return aTmp;
}
String TempFile::GetTempNameBaseDirectory()
{
::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();
if ( !rTempNameBase_Impl.getLength() )
rTempNameBase_Impl = GetSystemTempDir_Impl();
rtl::OUString aTmp;
aTmp = rTempNameBase_Impl;
return aTmp;
}
<|endoftext|> |
<commit_before>#include "variant/sdc_platform.hpp"
#include "hal.h"
// SDC1 configuration
static const SDCConfig SDC1_CONFIG {
0 // Dummy
};
SDCPlatform::SDCPlatform() {
sdcStart(&SDCD1, &SDC1_CONFIG);
palSetPadMode(GPIOB, 12, PAL_MODE_INPUT_PULLUP); // uSD-CD
palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(12)); // SDIO-D0
palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(12)); // SDIO-D1
palSetPadMode(GPIOC, 10, PAL_MODE_ALTERNATE(12)); // SDIO-D2
palSetPadMode(GPIOC, 11, PAL_MODE_ALTERNATE(12)); // SDIO-D3
palSetPadMode(GPIOC, 12, PAL_MODE_ALTERNATE(12)); // SDIO-CK
palSetPadMode(GPIOD, 2, PAL_MODE_ALTERNATE(12)); // SDIO-CMD
}
SDCDriver& SDCPlatform::getSDCDriver() {
return SDCD1;
}
<commit_msg>refs #18 Don't set SDIO pad modes.<commit_after>#include "variant/sdc_platform.hpp"
#include "hal.h"
// SDC1 configuration
static const SDCConfig SDC1_CONFIG {
0 // Dummy
};
SDCPlatform::SDCPlatform() {
sdcStart(&SDCD1, &SDC1_CONFIG);
palSetPadMode(GPIOB, 12, PAL_MODE_INPUT_PULLUP); // uSD-CD
//palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(12)); // SDIO-D0
//palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(12)); // SDIO-D1
//palSetPadMode(GPIOC, 10, PAL_MODE_ALTERNATE(12)); // SDIO-D2
//palSetPadMode(GPIOC, 11, PAL_MODE_ALTERNATE(12)); // SDIO-D3
//palSetPadMode(GPIOC, 12, PAL_MODE_ALTERNATE(12)); // SDIO-CK
//palSetPadMode(GPIOD, 2, PAL_MODE_ALTERNATE(12)); // SDIO-CMD
}
SDCDriver& SDCPlatform::getSDCDriver() {
return SDCD1;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_PROPERTIES_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_PROPERTIES_GENERATOR_GRAMMAR_HPP
#include <mapnik/value_types.hpp>
#include <mapnik/value.hpp>
#include <mapnik/feature_kv_iterator.hpp>
// boost
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/cons.hpp>
namespace mapnik { namespace json {
template <typename OutputIterator>
struct escaped_string
: karma::grammar<OutputIterator, std::string(char const*)>
{
escaped_string();
karma::rule<OutputIterator, std::string(char const*)> esc_str;
karma::symbols<char, char const*> esc_char;
};
struct extract_string
{
using result_type = std::tuple<std::string,bool>;
result_type operator() (mapnik::value const& val) const
{
bool need_quotes = val.is<value_unicode_string>();
return std::make_tuple(val.to_string(), need_quotes);
}
};
struct utf8
{
using result_type = std::string;
std::string operator() (mapnik::value_unicode_string const& ustr) const
{
std::string result;
to_utf8(ustr,result);
return result;
}
};
template <typename OutputIterator, typename KeyValueStore>
struct properties_generator_grammar : karma::grammar<OutputIterator, KeyValueStore const&()>
{
using pair_type = std::tuple<std::string, mapnik::value>;
properties_generator_grammar();
// rules
karma::rule<OutputIterator, KeyValueStore const&()> properties;
karma::rule<OutputIterator, pair_type()> pair;
karma::rule<OutputIterator, std::tuple<std::string,bool>()> value;
karma::rule<OutputIterator, mapnik::value_null()> value_null_;
karma::rule<OutputIterator, mapnik::value_unicode_string()> ustring;
escaped_string<OutputIterator> escaped_string_;
typename karma::int_generator<mapnik::value_integer,10, false> int__;
boost::phoenix::function<extract_string> extract_string_;
boost::phoenix::function<utf8> utf8_;
std::string quote_;
};
}}
#endif //MAPNIK_JSON_PROPERTIES_GENERATOR_GRAMMAR_HPP
<commit_msg>remove unused utf8 phoenix function<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_PROPERTIES_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_PROPERTIES_GENERATOR_GRAMMAR_HPP
#include <mapnik/value_types.hpp>
#include <mapnik/value.hpp>
#include <mapnik/feature_kv_iterator.hpp>
// boost
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/cons.hpp>
namespace mapnik { namespace json {
template <typename OutputIterator>
struct escaped_string
: karma::grammar<OutputIterator, std::string(char const*)>
{
escaped_string();
karma::rule<OutputIterator, std::string(char const*)> esc_str;
karma::symbols<char, char const*> esc_char;
};
struct extract_string
{
using result_type = std::tuple<std::string,bool>;
result_type operator() (mapnik::value const& val) const
{
bool need_quotes = val.is<value_unicode_string>();
return std::make_tuple(val.to_string(), need_quotes);
}
};
template <typename OutputIterator, typename KeyValueStore>
struct properties_generator_grammar : karma::grammar<OutputIterator, KeyValueStore const&()>
{
using pair_type = std::tuple<std::string, mapnik::value>;
properties_generator_grammar();
// rules
karma::rule<OutputIterator, KeyValueStore const&()> properties;
karma::rule<OutputIterator, pair_type()> pair;
karma::rule<OutputIterator, std::tuple<std::string,bool>()> value;
karma::rule<OutputIterator, mapnik::value_null()> value_null_;
karma::rule<OutputIterator, mapnik::value_unicode_string()> ustring;
escaped_string<OutputIterator> escaped_string_;
typename karma::int_generator<mapnik::value_integer,10, false> int__;
boost::phoenix::function<extract_string> extract_string_;
std::string quote_;
};
}}
#endif //MAPNIK_JSON_PROPERTIES_GENERATOR_GRAMMAR_HPP
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
LOG_SETUP("optimized_test");
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/optimized.h>
using namespace vespalib;
class Test : public vespalib::TestApp
{
private:
template<typename T>
void testMsbIdx();
template<typename T>
void testLsbIdx();
public:
int Main();
};
template<typename T>
void Test::testMsbIdx()
{
EXPECT_EQUAL(Optimized::msbIdx(T(0)), 0);
EXPECT_EQUAL(Optimized::msbIdx(T(1)), 0);
EXPECT_EQUAL(Optimized::msbIdx(T(-1)), int(sizeof(T)*8 - 1));
T v(static_cast<T>(-1));
for (size_t i(0); i < sizeof(T); i++) {
for (size_t j(0); j < 8; j++) {
EXPECT_EQUAL(Optimized::msbIdx(v), int(sizeof(T)*8 - (i*8+j) - 1));
v = v >> 1;
}
}
}
template<typename T>
void Test::testLsbIdx()
{
EXPECT_EQUAL(Optimized::lsbIdx(T(0)), 0);
EXPECT_EQUAL(Optimized::lsbIdx(T(1)), 0);
EXPECT_EQUAL(Optimized::lsbIdx(T(T(1)<<(sizeof(T)*8 - 1))), int(sizeof(T)*8 - 1));
EXPECT_EQUAL(Optimized::lsbIdx(T(-1)), 0);
T v(static_cast<T>(-1));
for (size_t i(0); i < sizeof(T); i++) {
for (size_t j(0); j < 8; j++) {
EXPECT_EQUAL(Optimized::lsbIdx(v), int(i*8+j));
v = v << 1;
}
}
}
int Test::Main()
{
TEST_INIT("optimized_test");
testMsbIdx<uint32_t>();
testMsbIdx<uint64_t>();
TEST_FLUSH();
testLsbIdx<uint32_t>();
testLsbIdx<uint64_t>();
TEST_FLUSH();
EXPECT_EQUAL(Optimized::popCount(0u), 0);
EXPECT_EQUAL(Optimized::popCount(1u), 1);
EXPECT_EQUAL(Optimized::popCount(uint32_t(-1)), 32);
EXPECT_EQUAL(Optimized::popCount(0ul), 0);
EXPECT_EQUAL(Optimized::popCount(1ul), 1);
EXPECT_EQUAL(Optimized::popCount(uint64_t(-1l)), 64);
TEST_FLUSH();
TEST_DONE();
}
TEST_APPHOOK(Test)
<commit_msg>Remove unused includes<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/optimized.h>
using namespace vespalib;
class Test : public vespalib::TestApp
{
private:
template<typename T>
void testMsbIdx();
template<typename T>
void testLsbIdx();
public:
int Main();
};
template<typename T>
void Test::testMsbIdx()
{
EXPECT_EQUAL(Optimized::msbIdx(T(0)), 0);
EXPECT_EQUAL(Optimized::msbIdx(T(1)), 0);
EXPECT_EQUAL(Optimized::msbIdx(T(-1)), int(sizeof(T)*8 - 1));
T v(static_cast<T>(-1));
for (size_t i(0); i < sizeof(T); i++) {
for (size_t j(0); j < 8; j++) {
EXPECT_EQUAL(Optimized::msbIdx(v), int(sizeof(T)*8 - (i*8+j) - 1));
v = v >> 1;
}
}
}
template<typename T>
void Test::testLsbIdx()
{
EXPECT_EQUAL(Optimized::lsbIdx(T(0)), 0);
EXPECT_EQUAL(Optimized::lsbIdx(T(1)), 0);
EXPECT_EQUAL(Optimized::lsbIdx(T(T(1)<<(sizeof(T)*8 - 1))), int(sizeof(T)*8 - 1));
EXPECT_EQUAL(Optimized::lsbIdx(T(-1)), 0);
T v(static_cast<T>(-1));
for (size_t i(0); i < sizeof(T); i++) {
for (size_t j(0); j < 8; j++) {
EXPECT_EQUAL(Optimized::lsbIdx(v), int(i*8+j));
v = v << 1;
}
}
}
int Test::Main()
{
TEST_INIT("optimized_test");
testMsbIdx<uint32_t>();
testMsbIdx<uint64_t>();
TEST_FLUSH();
testLsbIdx<uint32_t>();
testLsbIdx<uint64_t>();
TEST_FLUSH();
EXPECT_EQUAL(Optimized::popCount(0u), 0);
EXPECT_EQUAL(Optimized::popCount(1u), 1);
EXPECT_EQUAL(Optimized::popCount(uint32_t(-1)), 32);
EXPECT_EQUAL(Optimized::popCount(0ul), 0);
EXPECT_EQUAL(Optimized::popCount(1ul), 1);
EXPECT_EQUAL(Optimized::popCount(uint64_t(-1l)), 64);
TEST_FLUSH();
TEST_DONE();
}
TEST_APPHOOK(Test)
<|endoftext|> |
<commit_before>#include "viewer/primitives/simple_geometry_primitives.hh"
#include <GL/glew.h>
#include "viewer/colors/material.hh"
#include "viewer/gl_aliases.hh"
#include "geometry/perp.hh"
namespace viewer {
using Vec3 = Eigen::Vector3d;
using Vec4 = Eigen::Vector4d;
void draw_axes(const Axes &axes) {
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTransform(axes.world_from_axes);
glScaled(axes.scale, axes.scale, axes.scale);
if (axes.dotted) {
glEnable(GL_LINE_STIPPLE);
glLineStipple(1.0, 0x00FF);
}
glLineWidth(axes.line_width);
glBegin(GL_LINES);
glColor4d(1.0, 0.0, 0.0, 0.9);
glVertex(Vec3::UnitX().eval());
glVertex(Vec3::Zero().eval());
glColor4d(0.0, 1.0, 0.0, 0.9);
glVertex(Vec3::UnitY().eval());
glVertex(Vec3::Zero().eval());
glColor4d(0.0, 0.0, 1.0, 0.9);
glVertex(Vec3::UnitZ().eval());
glVertex(Vec3::Zero().eval());
glEnd();
glPopMatrix();
glPopAttrib();
if (axes.dotted) {
glDisable(GL_LINE_STIPPLE);
}
}
void draw_lines(const std::vector<Line> &lines) {
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
for (const auto &line : lines) {
glLineWidth(line.width);
glColor(line.color);
glBegin(GL_LINES);
glVertex(line.start);
glVertex(line.end);
glEnd();
}
glPopAttrib();
}
void draw_polygon(const Polygon &polygon) {
const int n_points = static_cast<int>(polygon.points.size());
const Eigen::Vector3d offset(0.0, 0.0, polygon.height);
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
glLineWidth(polygon.width);
// Draw the height of the poly
/*
glBegin(GL_QUADS);
glColor(polygon.color);
for (int k = 0; k < n_points; ++k) {
const auto &start = polygon.points[k];
const auto &end = polygon.points[(k + 1) % n_points];
glVertex(start);
glVertex(end);
glVertex(Vec3(end + offset));
glVertex(Vec3(start + offset));
}
glEnd();
*/
/*
if (polygon.outline) {
glLineWidth(0.8);
glBegin(GL_LINE_LOOP);
glColor(Vec4(Vec4::Ones()));
for (int k = 0; k < n_points; ++k) {
const auto &start = polygon.points[k];
const auto &end = polygon.points[(k + 1) % n_points];
glVertex(start);
glVertex(end);
glVertex(Vec3(end + offset));
glVertex(Vec3(start + offset));
}
glEnd();
}
*/
glColor(polygon.color);
glBegin(GL_TRIANGLE_FAN);
for (int k = 0; k < n_points; ++k) {
const auto &point = polygon.points[k];
glVertex(point);
}
glEnd();
if (polygon.outline) {
glLineWidth(3.0);
glColor(Vec4(Vec4::Ones()));
glBegin(GL_LINE_LOOP);
for (int k = 0; k < n_points; ++k) {
const auto &point = polygon.points[k];
glVertex(point);
}
glEnd();
}
glPopAttrib();
}
void draw_points(const Points &points) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glColor(points.color);
glPointSize(points.size);
glBegin(GL_POINTS);
for (const auto &pt : points.points) {
glVertex(pt);
}
glEnd();
glPopAttrib();
}
void draw_colored_points(const ColoredPoints &points) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glPointSize(points.size);
glBegin(GL_POINTS);
for (std::size_t k = 0; k < points.points.size(); ++k) {
glColor(points.colors[k]);
glVertex(points.points[k]);
}
glEnd();
glPopAttrib();
}
void draw_points2d(const Points2d &points) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glColor(points.color);
glPointSize(points.size);
glBegin(GL_POINTS);
for (const auto &pt : points.points) {
glVertex3d(pt.x(), pt.y(), points.z_offset);
}
glEnd();
glPopAttrib();
}
void draw_circle(const Vec3 ¢er,
const Vec3 &normal,
const double radius,
const Vec4 &color) {
constexpr double CIRCLE_RES = 0.05;
const Vec3 x_u = geometry::perp(normal);
const Vec3 y_u = -x_u.cross(normal);
Eigen::Matrix3d world_from_circle_frame;
world_from_circle_frame.col(0) = x_u;
world_from_circle_frame.col(1) = y_u;
world_from_circle_frame.col(2) = normal;
glColor(color);
glBegin(GL_LINE_LOOP);
for (double t = 0.0; t < (2.0 * M_PI); t += CIRCLE_RES) {
const Vec3 pt_circle_frm(radius * std::sin(t), radius * std::cos(t), 0.0);
const Vec3 pt_world_frm = (world_from_circle_frame * pt_circle_frm) + center;
glVertex(pt_world_frm);
}
glEnd();
}
void draw_sphere(const Sphere &sphere) {
glLineWidth(sphere.line_width);
draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitX(), sphere.radius,
sphere.color);
draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitY(), sphere.radius,
sphere.color);
draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitZ(), sphere.radius,
sphere.color);
}
void draw_ellipsoid(const Ellipsoid &ellipsoid) {
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Deform the universe by the ellipse's cholesky factor
const Eigen::Matrix3d L = ellipsoid.ellipse.cholesky_factor;
glTranslate(ellipsoid.ellipse.p0);
glApply(L);
draw_sphere({jcc::Vec3::Zero(), 1.0, ellipsoid.color, ellipsoid.line_width});
glPopMatrix();
glPopAttrib();
}
void draw_plane_grid(const Plane &plane) {
const Vec3 &n = plane.plane.u_normal;
const Vec3 x_dir = geometry::perp(n);
const Vec3 y_dir = x_dir.cross(n).normalized();
const int n_lines = 10;
const double displacement = n_lines * plane.line_spacing;
const Vec3 offset = plane.plane.u_normal * plane.plane.distance_from_origin;
const Vec3 y_offset = y_dir * (n_lines * plane.line_spacing);
const Vec3 x_offset = x_dir * (n_lines * plane.line_spacing);
glPushAttrib(GL_CURRENT_BIT);
glColor(plane.color);
glBegin(GL_LINES);
{
for (double x = -displacement; x <= displacement; x += plane.line_spacing) {
const Vec3 v = (x * x_dir) + offset;
// Lines retreating off to infinity by homogeneousness
// turns out, it doesn't look that good.
/*
glVertex4d(v.x(), v.y(), v.z(), 0.0);
glVertex4d(y_dir.x(), y_dir.y(), y_dir.z(), 0.0);
glVertex4d(v.x(), v.y(), v.z(), 1.0);
*/
glVertex(Vec3(v + y_offset));
glVertex(Vec3(v - y_offset));
}
for (double y = -displacement; y <= displacement; y += plane.line_spacing) {
const Vec3 v = (y * y_dir) + offset;
glVertex(Vec3(v + x_offset));
glVertex(Vec3(v - x_offset));
}
}
glEnd();
glPopAttrib();
}
void draw_point(const Point &point) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glPointSize(point.size);
glColor(point.color);
glBegin(GL_POINTS);
glVertex(point.point);
glEnd();
glPopAttrib();
}
void draw_trimesh(const TriMesh &trimesh) {
glPushAttrib(GL_CURRENT_BIT);
glPushMatrix();
glTransform(trimesh.world_from_mesh);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
if (trimesh.outline) {
glPushAttrib(GL_LINE_BIT);
glLineWidth(trimesh.outline_width);
glBegin(GL_LINES);
for (const auto &tri : trimesh.mesh.triangles) {
glVertex(tri.vertices[0]);
glVertex(tri.vertices[1]);
glVertex(tri.vertices[2]);
}
glEnd();
glPopAttrib();
}
// glEnable(GL_LIGHTING);
const auto material = colors::get_plastic(trimesh.color);
colors::gl_material(material);
glColor(trimesh.color);
if (trimesh.filled) {
glBegin(GL_TRIANGLES);
for (const auto &tri : trimesh.mesh.triangles) {
glVertex(tri.vertices[0]);
glVertex(tri.vertices[1]);
glVertex(tri.vertices[2]);
}
glEnd();
}
// glDisable(GL_LIGHTING);
glPopMatrix();
glPopAttrib();
// draw the display list
}
} // namespace viewer
<commit_msg>Visualize axes in plane vis<commit_after>#include "viewer/primitives/simple_geometry_primitives.hh"
#include <GL/glew.h>
#include "viewer/colors/material.hh"
#include "viewer/gl_aliases.hh"
#include "geometry/perp.hh"
namespace viewer {
using Vec3 = Eigen::Vector3d;
using Vec4 = Eigen::Vector4d;
void draw_axes(const Axes &axes) {
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTransform(axes.world_from_axes);
glScaled(axes.scale, axes.scale, axes.scale);
if (axes.dotted) {
glEnable(GL_LINE_STIPPLE);
glLineStipple(1.0, 0x00FF);
}
glLineWidth(axes.line_width);
glBegin(GL_LINES);
glColor4d(1.0, 0.0, 0.0, 0.9);
glVertex(Vec3::UnitX().eval());
glVertex(Vec3::Zero().eval());
glColor4d(0.0, 1.0, 0.0, 0.9);
glVertex(Vec3::UnitY().eval());
glVertex(Vec3::Zero().eval());
glColor4d(0.0, 0.0, 1.0, 0.9);
glVertex(Vec3::UnitZ().eval());
glVertex(Vec3::Zero().eval());
glEnd();
glPopMatrix();
glPopAttrib();
if (axes.dotted) {
glDisable(GL_LINE_STIPPLE);
}
}
void draw_lines(const std::vector<Line> &lines) {
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
for (const auto &line : lines) {
glLineWidth(line.width);
glColor(line.color);
glBegin(GL_LINES);
glVertex(line.start);
glVertex(line.end);
glEnd();
}
glPopAttrib();
}
void draw_polygon(const Polygon &polygon) {
const int n_points = static_cast<int>(polygon.points.size());
const Eigen::Vector3d offset(0.0, 0.0, polygon.height);
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
glLineWidth(polygon.width);
// Draw the height of the poly
/*
glBegin(GL_QUADS);
glColor(polygon.color);
for (int k = 0; k < n_points; ++k) {
const auto &start = polygon.points[k];
const auto &end = polygon.points[(k + 1) % n_points];
glVertex(start);
glVertex(end);
glVertex(Vec3(end + offset));
glVertex(Vec3(start + offset));
}
glEnd();
*/
/*
if (polygon.outline) {
glLineWidth(0.8);
glBegin(GL_LINE_LOOP);
glColor(Vec4(Vec4::Ones()));
for (int k = 0; k < n_points; ++k) {
const auto &start = polygon.points[k];
const auto &end = polygon.points[(k + 1) % n_points];
glVertex(start);
glVertex(end);
glVertex(Vec3(end + offset));
glVertex(Vec3(start + offset));
}
glEnd();
}
*/
glColor(polygon.color);
glBegin(GL_TRIANGLE_FAN);
for (int k = 0; k < n_points; ++k) {
const auto &point = polygon.points[k];
glVertex(point);
}
glEnd();
if (polygon.outline) {
glLineWidth(3.0);
glColor(Vec4(Vec4::Ones()));
glBegin(GL_LINE_LOOP);
for (int k = 0; k < n_points; ++k) {
const auto &point = polygon.points[k];
glVertex(point);
}
glEnd();
}
glPopAttrib();
}
void draw_points(const Points &points) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glColor(points.color);
glPointSize(points.size);
glBegin(GL_POINTS);
for (const auto &pt : points.points) {
glVertex(pt);
}
glEnd();
glPopAttrib();
}
void draw_colored_points(const ColoredPoints &points) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glPointSize(points.size);
glBegin(GL_POINTS);
for (std::size_t k = 0; k < points.points.size(); ++k) {
glColor(points.colors[k]);
glVertex(points.points[k]);
}
glEnd();
glPopAttrib();
}
void draw_points2d(const Points2d &points) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glColor(points.color);
glPointSize(points.size);
glBegin(GL_POINTS);
for (const auto &pt : points.points) {
glVertex3d(pt.x(), pt.y(), points.z_offset);
}
glEnd();
glPopAttrib();
}
void draw_circle(const Vec3 ¢er,
const Vec3 &normal,
const double radius,
const Vec4 &color) {
constexpr double CIRCLE_RES = 0.05;
const Vec3 x_u = geometry::perp(normal);
const Vec3 y_u = -x_u.cross(normal);
Eigen::Matrix3d world_from_circle_frame;
world_from_circle_frame.col(0) = x_u;
world_from_circle_frame.col(1) = y_u;
world_from_circle_frame.col(2) = normal;
glColor(color);
glBegin(GL_LINE_LOOP);
for (double t = 0.0; t < (2.0 * M_PI); t += CIRCLE_RES) {
const Vec3 pt_circle_frm(radius * std::sin(t), radius * std::cos(t), 0.0);
const Vec3 pt_world_frm = (world_from_circle_frame * pt_circle_frm) + center;
glVertex(pt_world_frm);
}
glEnd();
}
void draw_sphere(const Sphere &sphere) {
glLineWidth(sphere.line_width);
draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitX(), sphere.radius,
sphere.color);
draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitY(), sphere.radius,
sphere.color);
draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitZ(), sphere.radius,
sphere.color);
}
void draw_ellipsoid(const Ellipsoid &ellipsoid) {
glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Deform the universe by the ellipse's cholesky factor
const Eigen::Matrix3d L = ellipsoid.ellipse.cholesky_factor;
glTranslate(ellipsoid.ellipse.p0);
glApply(L);
draw_sphere({jcc::Vec3::Zero(), 1.0, ellipsoid.color, ellipsoid.line_width});
glPopMatrix();
glPopAttrib();
}
void draw_plane_grid(const Plane &plane) {
const Vec3 &n = plane.plane.u_normal;
const Vec3 x_dir = geometry::perp(n);
const Vec3 y_dir = x_dir.cross(n).normalized();
const int n_lines = 100;
const double displacement = n_lines * plane.line_spacing;
const Vec3 offset = plane.plane.u_normal * plane.plane.distance_from_origin;
const Vec3 y_offset = y_dir * (n_lines * plane.line_spacing);
const Vec3 x_offset = x_dir * (n_lines * plane.line_spacing);
glPushAttrib(GL_CURRENT_BIT);
glLineWidth(1.0);
glColor(plane.color);
glBegin(GL_LINES);
{
for (double x = -displacement; x < -plane.line_spacing; x += plane.line_spacing) {
const Vec3 v_x = (x * x_dir) + offset;
const Vec3 v_y = (x * y_dir) + offset;
glVertex(Vec3(v_x + y_offset));
glVertex(Vec3(v_x - y_offset));
glVertex(Vec3(v_y + x_offset));
glVertex(Vec3(v_y - x_offset));
}
for (double x = plane.line_spacing; x <= displacement; x += plane.line_spacing) {
const Vec3 v_x = (x * x_dir) + offset;
const Vec3 v_y = (x * y_dir) + offset;
glVertex(Vec3(v_x + y_offset));
glVertex(Vec3(v_x - y_offset));
glVertex(Vec3(v_y + x_offset));
glVertex(Vec3(v_y - x_offset));
}
}
glEnd();
glLineWidth(8.0);
glBegin(GL_LINES);
{
glColor(Vec4(1.0, 0.0, 0.0, 0.8));
glVertex(Vec3(x_offset));
glVertex(Vec3(-x_offset));
glColor(Vec4(0.0, 1.0, 0.0, 0.8));
glVertex(Vec3(y_offset));
glVertex(Vec3(-y_offset));
}
glEnd();
glPopAttrib();
}
void draw_point(const Point &point) {
glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);
glPointSize(point.size);
glColor(point.color);
glBegin(GL_POINTS);
glVertex(point.point);
glEnd();
glPopAttrib();
}
void draw_trimesh(const TriMesh &trimesh) {
glPushAttrib(GL_CURRENT_BIT);
glPushMatrix();
glTransform(trimesh.world_from_mesh);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
if (trimesh.outline) {
glPushAttrib(GL_LINE_BIT);
glLineWidth(trimesh.outline_width);
glBegin(GL_LINES);
for (const auto &tri : trimesh.mesh.triangles) {
glVertex(tri.vertices[0]);
glVertex(tri.vertices[1]);
glVertex(tri.vertices[2]);
}
glEnd();
glPopAttrib();
}
// glEnable(GL_LIGHTING);
const auto material = colors::get_plastic(trimesh.color);
colors::gl_material(material);
glColor(trimesh.color);
if (trimesh.filled) {
glBegin(GL_TRIANGLES);
for (const auto &tri : trimesh.mesh.triangles) {
glVertex(tri.vertices[0]);
glVertex(tri.vertices[1]);
glVertex(tri.vertices[2]);
}
glEnd();
}
// glDisable(GL_LIGHTING);
glPopMatrix();
glPopAttrib();
// draw the display list
}
} // namespace viewer
<|endoftext|> |
<commit_before>//_____________________________________________________________________
/**
*
*
* @param d Detector
* @param r Ring
* @param vz Z--coordinate of interaction point
* @param nDead On returm the number of dead strips
* @param deadScript Output stream for dead strips
*
* @return
*
* @ingroup pwglf_forward_scripts_corr
*/
TH2D* MakeOneRing(UShort_t d,
Char_t r,
Double_t vz,
Int_t& nDead,
std::ostream* deadScript)
{
AliFMDGeometry* geom = AliFMDGeometry::Instance();
AliFMDParameters* pars = AliFMDParameters::Instance();
Float_t konst = pars->GetDACPerMIP();
UShort_t nS = (r == 'I' || r == 'i' ? 20 : 40);
UShort_t nT = (r == 'I' || r == 'i' ? 512 : 256);
// Make our two histograms
TH2D* hAll = new TH2D("all","All",200,-4,6,nS,0,2*TMath::Pi());
hAll->SetXTitle("#eta");
hAll->SetYTitle("#phi");
hAll->Sumw2();
hAll->SetDirectory(0);
TH2D* hOK = static_cast<TH2D*>(hAll->Clone());
hOK->SetDirectory(0);
if (deadScript)
*deadScript << "\n // === FMD" << d << r << " === " << std::endl;
// Loop over all sectors and strips in this ring
Int_t nOK = 0;
Int_t nAll = 0;
Int_t nPhi = hAll->GetNbinsY();
for (UShort_t s = 0; s < nS; s++) {
for (UShort_t t = 0; t < nT; t++) {
// Get eta,phi by quering the geometry (first for (x,y,z), then
// correcting for the vertex position, and then calculating
// (eta, phi))
Double_t x, y, z;
geom->Detector2XYZ(d, r, s, t, x, y, z);
z -= vz;
Double_t q, eta, phi, theta;
AliFMDGeometry::XYZ2REtaPhiTheta(x, y, z, q, eta, phi, theta);
if (phi < 0) phi += 2*TMath::Pi();
TString reason;
// Check if this is a dead channel or not
Bool_t isDead = pars->IsDead(d, r, s, t);
if (isDead) {
if (deadScript)
Warning("", "FMD%d%c[%2d,%3d] is dead because OCDB says so");
reason = "OCDB";
}
// Pedestal, noise, gain
Double_t ped = pars->GetPedestal (d, r, s, t);
Double_t noise = pars->GetPedestalWidth(d, r, s, t);
Double_t gain = pars->GetPulseGain (d, r, s, t);
if (ped < 10) {
if (!isDead && deadScript) {
reason = "Low pedestal";
Warning("", "FMD%d%c[%2d,%3d] is dead because pedestal %f < 10",
d, r, s, t, ped);
}
isDead = true;
}
Float_t corr = 0;
if (noise > .5 && gain > .5) corr = noise / (gain * konst);
if (corr > 0.05 || corr <= 0) {
if (!isDead && deadScript) {
reason = "high noise/low gain";
Warning("", "FMD%d%c[%2d,%3d] is dead because %f/(%f*%f)=%f > 0.05 or negative",
d, r, s, t, noise, gain, konst, corr);
}
isDead = true;
}
// Special check for FMD2i - upper part of sectors 16/17 have
// have anomalous gains and/or noise - common sources are
// power regulartors for bias currents and the like
Int_t VA = t/128;
if(d==2 && r=='I' && VA>1 && (s==16 || s==17)) {
if (!isDead && deadScript) {
reason = "I say so";
Warning("", "FMD%d%c[%2d,%3d] is dead because I say so", d, r, s, t);
}
isDead =true;
}
// Find the eta bin number and corresponding overflow bin
Int_t etaBin = hAll->GetXaxis()->FindBin(eta);
Int_t ovrBin = hAll->GetBin(etaBin, nPhi+1);
// Increment all histogram
hAll->Fill(eta, phi);
hAll->AddBinContent(ovrBin);
nAll++;
// If not dead, increment OK histogram
if (!isDead) {
hOK->Fill(eta, phi);
hOK->AddBinContent(ovrBin);
nOK++;
}
else {
nDead++;
if (deadScript)
*deadScript << " filter->AddDead(" << d << ",'" << r << "',"
<< std::setw(2) << s << ','
<< std::setw(3) << t << "); // "
<< reason << std::endl;
}
}
}
// Divide out the efficiency.
// Note, that the overflow bins along eta now contains the ratio
// nOK/nAll Strips for a given eta bin.
hOK->Divide(hOK,hAll,1,1,"B");
// Invert overflow bin
for (Int_t etaBin = 1; etaBin <= hOK->GetNbinsX(); etaBin++) {
Double_t ovr = hOK->GetBinContent(etaBin, nPhi+1);
Double_t novr = (ovr < 1e-12 ? 0 : 1./ovr);
hOK->SetBinContent(etaBin, nPhi+1, novr);
#if 0
if (ovr > 0 && ovr != 1)
Info("", "Setting overflow bin (%3d,%3d) to 1/%f=%f", etaBin, nPhi+1,
ovr, hOK->GetBinContent(etaBin, nPhi+1));
#endif
}
// Clean up
delete hAll;
Printf("=== FMD%d%c at vz=%+5.1f - %d/%d=%3d%% OK (w/overflow)",
d, r, vz, nOK, nAll, (100*nOK)/nAll);
// Return result
return hOK;
}
//_____________________________________________________________________
/**
*
*
* @param runNo Run number
* @param nVtxBins Number of @f$IP_{z}@f$ bins
* @param vtxLow Least @f$IP_{z}@f$
* @param vtxHigh Largest @f$IP_{z}@f$
*
* @ingroup pwglf_forward_scripts_corr
*/
void ExtractAcceptance(Int_t runNo=121526,
Int_t nVtxBins=10,
Float_t vtxLow=-10,
Float_t vtxHigh=10)
{
const char* fwd = "$ALICE_PHYSICS/PWGLF/FORWARD/analysis2";
gSystem->AddIncludePath(Form("-I%s", fwd));
gROOT->Macro(Form("%s/scripts/LoadLibs.C", fwd));
// gSystem->Load("libANALYSIS");
// gSystem->Load("libANALYSISalice");
// gSystem->Load("libPWGLFforward2");
// Float_t delta = (vtxHigh - vtxLow) / (Float_t)nVtxBins;
Bool_t gridOnline = kTRUE;
if(!(TGrid::Connect("alien://",0,0,"t")))
gridOnline = kFALSE;
// --- Figure out the year --------------------------------------
UShort_t year = 0;
if (runNo <= 99999) year = 2009;
else if (runNo <= 139667) year = 2010;
else if (runNo <= 170718) year = 2011;
else if (runNo <= 194306) year = 2012;
else if (runNo <= 197709) year = 2013;
else if (runNo <= 208364) year = 2014;
else year = 2015;
if (year <= 0) {
Warning("", "Couldn't deduce the year from the run number");
// return;
}
// --- Initialisations ------------------------------------------
//Set up CDB manager
Printf("=== Setting up OCDB");
AliCDBManager* cdb = AliCDBManager::Instance();
if(gridOnline) {
cdb->SetDefaultStorageFromRun(runNo);
// cdb->SetDefaultStorage(Form("alien://Folder=/alice/data/%4d/OCDB", year));
}
else
cdb->SetDefaultStorage("local://$(ALICE_PHYSICS)/OCDB");
cdb->SetRun(runNo);
// Get the geometry
Printf("=== Loading geometry");
AliGeomManager::LoadGeometry();
// Get an initialize parameters
Printf("=== Intialising parameters");
AliFMDParameters* pars = AliFMDParameters::Instance();
pars->Init();
// Get an initialise geometry
Printf("=== Initialising geomtry");
AliFMDGeometry* geom = AliFMDGeometry::Instance();
geom->Init();
geom->InitTransformations();
// --- Get the general run parameters ------------------------------
AliCDBEntry* grpE = cdb->Get("GRP/GRP/Data");
if (!grpE) {
AliWarningF("No GRP entry found for run %d", runNo);
return;
}
AliGRPObject* grp = static_cast<AliGRPObject*>(grpE->GetObject());
if (!grp) {
AliWarningF("No GRP object found for run %d", runNo);
return;
}
Float_t beamE = grp->GetBeamEnergy();
TString beamT = grp->GetBeamType();
# if 0
// This isn't really needed as the acceptance map is indifferent to
// the field settings.
Float_t l3cur = grp->GetL3Current(AliGRPObject::kMean);
Char_t l3pol = grp->GetL3Polarity();
Bool_t l3lhc = grp->IsPolarityConventionLHC();
Bool_t l3uni = grp->IsUniformBMap();
AliMagF* fldM =
AliMagF::CreateFieldMap(TMath::Abs(l3cur) * (l3pol ? -1:1), 0,
(l3lhc ? 0 : 1), l3uni, beamE, beamT.Data());
Float_t l3fld = fldM->SolenoidField();
#endif
UShort_t sys = AliForwardUtil::ParseCollisionSystem(beamT);
UShort_t sNN = AliForwardUtil::ParseCenterOfMassEnergy(sys, 2 * beamE);
Short_t fld = 0; // AliForwardUtil::ParseMagneticField(l3fld);
Printf("=== Run=%d, year=%d, sys=%d, sNN=%d, fld=%d",
runNo, year, sys, sNN, fld);
// --- Output object -----------------------------------------------
// Make our correction object
AliFMDCorrAcceptance* corr = new AliFMDCorrAcceptance();
corr->SetVertexAxis(nVtxBins, vtxLow, vtxHigh);
// --- Output script -----------------------------------------------
std::ofstream deadScript("deadstrips.C");
deadScript << "// Automatically generaeted by ExtractAcceptance.C\n"
<< "// Add additional dead strips to sharing filter\n"
<< "// Information taken from OCDB entry for\n"
<< "//\n"
<< "// run = " << runNo << "\n"
<< "// year = " << year << "\n"
<< "// system = " << sys << "\n"
<< "// sqrt{sNN} = " << sNN << "GeV\n"
<< "// L3 field = " << fld << "kG\n"
<< "void deadstrips(AliFMDESDFixer* filter)\n"
<< "{" << std::endl;
// --- Loop over verticies and rings -------------------------------
Int_t nDead = 0;
Bool_t gotDead = false;
Float_t dV = (vtxHigh - vtxLow) / nVtxBins;
Printf("=== Looping over vertices: %d bins from %+6.2f to %+6.2f "
"in steps of %+6.2f",
nVtxBins, vtxLow, vtxHigh, dV);
for (Double_t v = vtxLow+dV/2; v < vtxHigh; v += dV) {
for(UShort_t d = 1; d <= 3;d++) {
UShort_t nR = (d == 1 ? 1 : 2);
for (UShort_t q = 0; q < nR; q++) {
Char_t r = (q == 0 ? 'I' : 'O');
// Delegate to other function
Int_t nLocal = 0;
TH2D* ratio = MakeOneRing(d, r, v, nLocal,
!gotDead ? &deadScript : 0);
nDead += nLocal;
if (!ratio) {
Warning("ExtractAcceptance", "Didn't get correction from "
"FMD%d%c @ vz=%+6.2fcm", d, r, v);
continue;
}
// Printf("v=%+6.2f FMD%d%c, got %d dead strips", v, d, r, nLocal);
// Set the correction
corr->SetCorrection(d, r, v, ratio);
}
}
gotDead = true;
}
corr->SetHasOverflow();
corr->Print();
// corr->ls();
deadScript << "}\n"
<< "// EOF" << std::endl;
deadScript.close();
// Write to a file
Printf("=== Writing to disk");
AliForwardCorrectionManager& cm = AliForwardCorrectionManager::Instance();
if (!cm.Store(corr, runNo, sys, sNN, fld, false, false,
"fmd_corrections.root")) {
Error("", "Failed to store acceptance correction in local file");
return;
}
std::ofstream f("Upload.C");
f << "// Generated by ExtractELoss.C\n"
<< "TString MakeDest(const TString& dest, const TString& fname)\n"
<< "{\n"
<< " TString tmp(dest);\n"
<< " if (!tmp.IsNull()) {\n"
<< " if (!tmp.EndsWith(\"/\")) tmp.Append(\"/\");\n"
<< " tmp.Append(fname);\n"
<< " }\n"
<< " return tmp;\n"
<< "}\n\n"
<< "void Upload(const TString& dest=\"\")\n"
<< "{\n"
<< " gROOT->Macro(\"" << fwd << "/scripts/LoadLibs.C\");\n"
<< " \n"
<< " const char* fmdFile = \"fmd_corrections.root\";\n"
<< " TString fdest = MakeDest(dest, fmdFile);\n"
<< " \n"
<< " AliForwardCorrectionManager::Instance().Append(fmdFile, fdest);\n"
<< "}\n"
<< "// EOF\n"
<< std::endl;
f.close();
Info("ExtracAcceptance",
"Run generated Upload.C(DEST) script to copy files in place");
}
//
// EOF
//
<commit_msg>Do not flag FMD2i automatically<commit_after>//_____________________________________________________________________
/**
*
*
* @param d Detector
* @param r Ring
* @param vz Z--coordinate of interaction point
* @param nDead On returm the number of dead strips
* @param deadScript Output stream for dead strips
*
* @return
*
* @ingroup pwglf_forward_scripts_corr
*/
TH2D* MakeOneRing(UShort_t d,
Char_t r,
Double_t vz,
Int_t& nDead,
std::ostream* deadScript)
{
AliFMDGeometry* geom = AliFMDGeometry::Instance();
AliFMDParameters* pars = AliFMDParameters::Instance();
Float_t konst = pars->GetDACPerMIP();
UShort_t nS = (r == 'I' || r == 'i' ? 20 : 40);
UShort_t nT = (r == 'I' || r == 'i' ? 512 : 256);
// Make our two histograms
TH2D* hAll = new TH2D("all","All",200,-4,6,nS,0,2*TMath::Pi());
hAll->SetXTitle("#eta");
hAll->SetYTitle("#phi");
hAll->Sumw2();
hAll->SetDirectory(0);
TH2D* hOK = static_cast<TH2D*>(hAll->Clone());
hOK->SetDirectory(0);
if (deadScript)
*deadScript << "\n // === FMD" << d << r << " === " << std::endl;
// Loop over all sectors and strips in this ring
Int_t nOK = 0;
Int_t nAll = 0;
Int_t nPhi = hAll->GetNbinsY();
for (UShort_t s = 0; s < nS; s++) {
for (UShort_t t = 0; t < nT; t++) {
// Get eta,phi by quering the geometry (first for (x,y,z), then
// correcting for the vertex position, and then calculating
// (eta, phi))
Double_t x, y, z;
geom->Detector2XYZ(d, r, s, t, x, y, z);
z -= vz;
Double_t q, eta, phi, theta;
AliFMDGeometry::XYZ2REtaPhiTheta(x, y, z, q, eta, phi, theta);
if (phi < 0) phi += 2*TMath::Pi();
TString reason;
// Check if this is a dead channel or not
Bool_t isDead = pars->IsDead(d, r, s, t);
if (isDead) {
if (deadScript)
Warning("", "FMD%d%c[%2d,%3d] is dead because OCDB says so");
reason = "OCDB";
}
// Pedestal, noise, gain
Double_t ped = pars->GetPedestal (d, r, s, t);
Double_t noise = pars->GetPedestalWidth(d, r, s, t);
Double_t gain = pars->GetPulseGain (d, r, s, t);
if (ped < 10) {
if (!isDead && deadScript) {
reason = "Low pedestal";
Warning("", "FMD%d%c[%2d,%3d] is dead because pedestal %f < 10",
d, r, s, t, ped);
}
isDead = true;
}
Float_t corr = 0;
if (noise > .5 && gain > .5) corr = noise / (gain * konst);
if (corr > 0.05 || corr <= 0) {
if (!isDead && deadScript) {
reason = "high noise/low gain";
Warning("", "FMD%d%c[%2d,%3d] is dead because %f/(%f*%f)=%f > 0.05 or negative",
d, r, s, t, noise, gain, konst, corr);
}
isDead = true;
}
// Special check for FMD2i - upper part of sectors 16/17 have
// have anomalous gains and/or noise - common sources are
// power regulartors for bias currents and the like
#if 0
Int_t VA = t/128;
if(d==2 && r=='I' && VA>1 && (s==16 || s==17)) {
if (!isDead && deadScript) {
reason = "I say so";
Warning("", "FMD%d%c[%2d,%3d] is dead because I say so", d, r, s, t);
}
isDead =true;
}
#endif
// Find the eta bin number and corresponding overflow bin
Int_t etaBin = hAll->GetXaxis()->FindBin(eta);
Int_t ovrBin = hAll->GetBin(etaBin, nPhi+1);
// Increment all histogram
hAll->Fill(eta, phi);
hAll->AddBinContent(ovrBin);
nAll++;
// If not dead, increment OK histogram
if (!isDead) {
hOK->Fill(eta, phi);
hOK->AddBinContent(ovrBin);
nOK++;
}
else {
nDead++;
if (deadScript)
*deadScript << " filter->AddDead(" << d << ",'" << r << "',"
<< std::setw(2) << s << ','
<< std::setw(3) << t << "); // "
<< reason << std::endl;
}
}
}
// Divide out the efficiency.
// Note, that the overflow bins along eta now contains the ratio
// nOK/nAll Strips for a given eta bin.
hOK->Divide(hOK,hAll,1,1,"B");
// Invert overflow bin
for (Int_t etaBin = 1; etaBin <= hOK->GetNbinsX(); etaBin++) {
Double_t ovr = hOK->GetBinContent(etaBin, nPhi+1);
Double_t novr = (ovr < 1e-12 ? 0 : 1./ovr);
hOK->SetBinContent(etaBin, nPhi+1, novr);
#if 0
if (ovr > 0 && ovr != 1)
Info("", "Setting overflow bin (%3d,%3d) to 1/%f=%f", etaBin, nPhi+1,
ovr, hOK->GetBinContent(etaBin, nPhi+1));
#endif
}
// Clean up
delete hAll;
Printf("=== FMD%d%c at vz=%+5.1f - %d/%d=%3d%% OK (w/overflow)",
d, r, vz, nOK, nAll, (100*nOK)/nAll);
// Return result
return hOK;
}
//_____________________________________________________________________
/**
*
*
* @param runNo Run number
* @param nVtxBins Number of @f$IP_{z}@f$ bins
* @param vtxLow Least @f$IP_{z}@f$
* @param vtxHigh Largest @f$IP_{z}@f$
*
* @ingroup pwglf_forward_scripts_corr
*/
void ExtractAcceptance(Int_t runNo=121526,
Int_t nVtxBins=10,
Float_t vtxLow=-10,
Float_t vtxHigh=10)
{
const char* fwd = "$ALICE_PHYSICS/PWGLF/FORWARD/analysis2";
gSystem->AddIncludePath(Form("-I%s", fwd));
gROOT->Macro(Form("%s/scripts/LoadLibs.C", fwd));
// gSystem->Load("libANALYSIS");
// gSystem->Load("libANALYSISalice");
// gSystem->Load("libPWGLFforward2");
// Float_t delta = (vtxHigh - vtxLow) / (Float_t)nVtxBins;
Bool_t gridOnline = kTRUE;
if(!(TGrid::Connect("alien://",0,0,"t")))
gridOnline = kFALSE;
// --- Figure out the year --------------------------------------
UShort_t year = 0;
if (runNo <= 99999) year = 2009;
else if (runNo <= 139667) year = 2010;
else if (runNo <= 170718) year = 2011;
else if (runNo <= 194306) year = 2012;
else if (runNo <= 197709) year = 2013;
else if (runNo <= 208364) year = 2014;
else year = 2015;
if (year <= 0) {
Warning("", "Couldn't deduce the year from the run number");
// return;
}
// --- Initialisations ------------------------------------------
//Set up CDB manager
Printf("=== Setting up OCDB");
AliCDBManager* cdb = AliCDBManager::Instance();
if(gridOnline) {
cdb->SetDefaultStorageFromRun(runNo);
// cdb->SetDefaultStorage(Form("alien://Folder=/alice/data/%4d/OCDB", year));
}
else
cdb->SetDefaultStorage("local://$(ALICE_PHYSICS)/OCDB");
cdb->SetRun(runNo);
// Get the geometry
Printf("=== Loading geometry");
AliGeomManager::LoadGeometry();
// Get an initialize parameters
Printf("=== Intialising parameters");
AliFMDParameters* pars = AliFMDParameters::Instance();
pars->Init();
// Get an initialise geometry
Printf("=== Initialising geomtry");
AliFMDGeometry* geom = AliFMDGeometry::Instance();
geom->Init();
geom->InitTransformations();
// --- Get the general run parameters ------------------------------
AliCDBEntry* grpE = cdb->Get("GRP/GRP/Data");
if (!grpE) {
AliWarningF("No GRP entry found for run %d", runNo);
return;
}
AliGRPObject* grp = static_cast<AliGRPObject*>(grpE->GetObject());
if (!grp) {
AliWarningF("No GRP object found for run %d", runNo);
return;
}
Float_t beamE = grp->GetBeamEnergy();
TString beamT = grp->GetBeamType();
# if 0
// This isn't really needed as the acceptance map is indifferent to
// the field settings.
Float_t l3cur = grp->GetL3Current(AliGRPObject::kMean);
Char_t l3pol = grp->GetL3Polarity();
Bool_t l3lhc = grp->IsPolarityConventionLHC();
Bool_t l3uni = grp->IsUniformBMap();
AliMagF* fldM =
AliMagF::CreateFieldMap(TMath::Abs(l3cur) * (l3pol ? -1:1), 0,
(l3lhc ? 0 : 1), l3uni, beamE, beamT.Data());
Float_t l3fld = fldM->SolenoidField();
#endif
UShort_t sys = AliForwardUtil::ParseCollisionSystem(beamT);
UShort_t sNN = AliForwardUtil::ParseCenterOfMassEnergy(sys, 2 * beamE);
Short_t fld = 0; // AliForwardUtil::ParseMagneticField(l3fld);
Printf("=== Run=%d, year=%d, sys=%d, sNN=%d, fld=%d",
runNo, year, sys, sNN, fld);
// --- Output object -----------------------------------------------
// Make our correction object
AliFMDCorrAcceptance* corr = new AliFMDCorrAcceptance();
corr->SetVertexAxis(nVtxBins, vtxLow, vtxHigh);
// --- Output script -----------------------------------------------
std::ofstream deadScript("deadstrips.C");
deadScript << "// Automatically generaeted by ExtractAcceptance.C\n"
<< "// Add additional dead strips to sharing filter\n"
<< "// Information taken from OCDB entry for\n"
<< "//\n"
<< "// run = " << runNo << "\n"
<< "// year = " << year << "\n"
<< "// system = " << sys << "\n"
<< "// sqrt{sNN} = " << sNN << "GeV\n"
<< "// L3 field = " << fld << "kG\n"
<< "void deadstrips(AliFMDESDFixer* filter)\n"
<< "{" << std::endl;
// --- Loop over verticies and rings -------------------------------
Int_t nDead = 0;
Bool_t gotDead = false;
Float_t dV = (vtxHigh - vtxLow) / nVtxBins;
Printf("=== Looping over vertices: %d bins from %+6.2f to %+6.2f "
"in steps of %+6.2f",
nVtxBins, vtxLow, vtxHigh, dV);
for (Double_t v = vtxLow+dV/2; v < vtxHigh; v += dV) {
for(UShort_t d = 1; d <= 3;d++) {
UShort_t nR = (d == 1 ? 1 : 2);
for (UShort_t q = 0; q < nR; q++) {
Char_t r = (q == 0 ? 'I' : 'O');
// Delegate to other function
Int_t nLocal = 0;
TH2D* ratio = MakeOneRing(d, r, v, nLocal,
!gotDead ? &deadScript : 0);
nDead += nLocal;
if (!ratio) {
Warning("ExtractAcceptance", "Didn't get correction from "
"FMD%d%c @ vz=%+6.2fcm", d, r, v);
continue;
}
// Printf("v=%+6.2f FMD%d%c, got %d dead strips", v, d, r, nLocal);
// Set the correction
corr->SetCorrection(d, r, v, ratio);
}
}
gotDead = true;
}
corr->SetHasOverflow();
corr->Print();
// corr->ls();
deadScript << "}\n"
<< "// EOF" << std::endl;
deadScript.close();
// Write to a file
Printf("=== Writing to disk");
AliForwardCorrectionManager& cm = AliForwardCorrectionManager::Instance();
if (!cm.Store(corr, runNo, sys, sNN, fld, false, false,
"fmd_corrections.root")) {
Error("", "Failed to store acceptance correction in local file");
return;
}
std::ofstream f("Upload.C");
f << "// Generated by ExtractELoss.C\n"
<< "TString MakeDest(const TString& dest, const TString& fname)\n"
<< "{\n"
<< " TString tmp(dest);\n"
<< " if (!tmp.IsNull()) {\n"
<< " if (!tmp.EndsWith(\"/\")) tmp.Append(\"/\");\n"
<< " tmp.Append(fname);\n"
<< " }\n"
<< " return tmp;\n"
<< "}\n\n"
<< "void Upload(const TString& dest=\"\")\n"
<< "{\n"
<< " gROOT->Macro(\"" << fwd << "/scripts/LoadLibs.C\");\n"
<< " \n"
<< " const char* fmdFile = \"fmd_corrections.root\";\n"
<< " TString fdest = MakeDest(dest, fmdFile);\n"
<< " \n"
<< " AliForwardCorrectionManager::Instance().Append(fmdFile, fdest);\n"
<< "}\n"
<< "// EOF\n"
<< std::endl;
f.close();
Info("ExtracAcceptance",
"Run generated Upload.C(DEST) script to copy files in place");
}
//
// EOF
//
<|endoftext|> |
<commit_before>#ifndef _DEDEFS_HPP
#define _DEDEFS_HPP
/*-------------------------------------------------------------------------
* drawElements C++ Base Library
* -----------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Basic definitions.
*//*--------------------------------------------------------------------*/
#include "deDefs.h"
#if !defined(__cplusplus)
# error "C++ is required"
#endif
namespace de
{
//! Compute absolute value of x.
template<typename T> inline T abs (T x) { return x < T(0) ? -x : x; }
//! Get minimum of x and y.
template<typename T> inline T min (T x, T y) { return x <= y ? x : y; }
//! Get maximum of x and y.
template<typename T> inline T max (T x, T y) { return x >= y ? x : y; }
//! Clamp x in range a <= x <= b.
template<typename T> inline T clamp (T x, T a, T b) { DE_ASSERT(a <= b); return x < a ? a : (x > b ? b : x); }
//! Test if x is in bounds a <= x < b.
template<typename T> inline bool inBounds (T x, T a, T b) { return a <= x && x < b; }
//! Test if x is in range a <= x <= b.
template<typename T> inline bool inRange (T x, T a, T b) { return a <= x && x <= b; }
//! Helper for DE_CHECK() macros.
void throwRuntimeError (const char* message, const char* expr, const char* file, int line);
//! Default deleter.
template<typename T> struct DefaultDeleter
{
inline DefaultDeleter (void) {}
template<typename U> inline DefaultDeleter (const DefaultDeleter<U>&) {}
template<typename U> inline DefaultDeleter<T>& operator= (const DefaultDeleter<U>&) { return *this; }
inline void operator() (T* ptr) const { delete ptr; }
};
//! A deleter for arrays
template<typename T> struct ArrayDeleter
{
inline ArrayDeleter (void) {}
template<typename U> inline ArrayDeleter (const ArrayDeleter<U>&) {}
template<typename U> inline ArrayDeleter<T>& operator= (const ArrayDeleter<U>&) { return *this; }
inline void operator() (T* ptr) const { delete[] ptr; }
};
} // de
/*--------------------------------------------------------------------*//*!
* \brief Throw runtime error if condition is not met.
* \param X Condition to check.
*
* This macro throws std::runtime_error if condition X is not met.
*//*--------------------------------------------------------------------*/
#define DE_CHECK_RUNTIME_ERR(X) do { if ((!deGetFalse() && (X)) ? DE_FALSE : DE_TRUE) ::de::throwRuntimeError(DE_NULL, #X, __FILE__, __LINE__); } while(deGetFalse())
/*--------------------------------------------------------------------*//*!
* \brief Throw runtime error if condition is not met.
* \param X Condition to check.
* \param MSG Additional message to include in the exception.
*
* This macro throws std::runtime_error with message MSG if condition X is
* not met.
*//*--------------------------------------------------------------------*/
#define DE_CHECK_RUNTIME_ERR_MSG(X, MSG) do { if ((!deGetFalse() && (X)) ? DE_FALSE : DE_TRUE) ::de::throwRuntimeError(MSG, #X, __FILE__, __LINE__); } while(deGetFalse())
//! Get array start pointer.
#define DE_ARRAY_BEGIN(ARR) (&(ARR)[0])
//! Get array end pointer.
#define DE_ARRAY_END(ARR) (DE_ARRAY_BEGIN(ARR) + DE_LENGTH_OF_ARRAY(ARR))
//! Empty C++ compilation unit silencing.
#if (DE_COMPILER == DE_COMPILER_MSC)
# define DE_EMPTY_CPP_FILE namespace { deUint8 unused; }
#else
# define DE_EMPTY_CPP_FILE
#endif
// Warn if type is constructed, but left unused
//
// Used in types with non-trivial ctor/dtor but with ctor-dtor pair causing no (observable)
// side-effects.
//
// \todo add attribute for GCC
#if (DE_COMPILER == DE_COMPILER_CLANG) && defined(__has_attribute)
# if __has_attribute(warn_unused)
# define DE_WARN_UNUSED_TYPE __attribute__((warn_unused))
# else
# define DE_WARN_UNUSED_TYPE
# endif
#else
# define DE_WARN_UNUSED_TYPE
#endif
#endif // _DEDEFS_HPP
<commit_msg>Add de::alignOf<T>() to deDefs.hpp<commit_after>#ifndef _DEDEFS_HPP
#define _DEDEFS_HPP
/*-------------------------------------------------------------------------
* drawElements C++ Base Library
* -----------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Basic definitions.
*//*--------------------------------------------------------------------*/
#include "deDefs.h"
#if !defined(__cplusplus)
# error "C++ is required"
#endif
namespace de
{
//! Compute absolute value of x.
template<typename T> inline T abs (T x) { return x < T(0) ? -x : x; }
//! Get minimum of x and y.
template<typename T> inline T min (T x, T y) { return x <= y ? x : y; }
//! Get maximum of x and y.
template<typename T> inline T max (T x, T y) { return x >= y ? x : y; }
//! Clamp x in range a <= x <= b.
template<typename T> inline T clamp (T x, T a, T b) { DE_ASSERT(a <= b); return x < a ? a : (x > b ? b : x); }
//! Test if x is in bounds a <= x < b.
template<typename T> inline bool inBounds (T x, T a, T b) { return a <= x && x < b; }
//! Test if x is in range a <= x <= b.
template<typename T> inline bool inRange (T x, T a, T b) { return a <= x && x <= b; }
//! Helper for DE_CHECK() macros.
void throwRuntimeError (const char* message, const char* expr, const char* file, int line);
//! Default deleter.
template<typename T> struct DefaultDeleter
{
inline DefaultDeleter (void) {}
template<typename U> inline DefaultDeleter (const DefaultDeleter<U>&) {}
template<typename U> inline DefaultDeleter<T>& operator= (const DefaultDeleter<U>&) { return *this; }
inline void operator() (T* ptr) const { delete ptr; }
};
//! A deleter for arrays
template<typename T> struct ArrayDeleter
{
inline ArrayDeleter (void) {}
template<typename U> inline ArrayDeleter (const ArrayDeleter<U>&) {}
template<typename U> inline ArrayDeleter<T>& operator= (const ArrayDeleter<U>&) { return *this; }
inline void operator() (T* ptr) const { delete[] ptr; }
};
//! Get required memory alignment for type
template<typename T>
size_t alignOf (void)
{
struct PaddingCheck { deUint8 b; T t; };
return (size_t)DE_OFFSET_OF(PaddingCheck, t);
}
} // de
/*--------------------------------------------------------------------*//*!
* \brief Throw runtime error if condition is not met.
* \param X Condition to check.
*
* This macro throws std::runtime_error if condition X is not met.
*//*--------------------------------------------------------------------*/
#define DE_CHECK_RUNTIME_ERR(X) do { if ((!deGetFalse() && (X)) ? DE_FALSE : DE_TRUE) ::de::throwRuntimeError(DE_NULL, #X, __FILE__, __LINE__); } while(deGetFalse())
/*--------------------------------------------------------------------*//*!
* \brief Throw runtime error if condition is not met.
* \param X Condition to check.
* \param MSG Additional message to include in the exception.
*
* This macro throws std::runtime_error with message MSG if condition X is
* not met.
*//*--------------------------------------------------------------------*/
#define DE_CHECK_RUNTIME_ERR_MSG(X, MSG) do { if ((!deGetFalse() && (X)) ? DE_FALSE : DE_TRUE) ::de::throwRuntimeError(MSG, #X, __FILE__, __LINE__); } while(deGetFalse())
//! Get array start pointer.
#define DE_ARRAY_BEGIN(ARR) (&(ARR)[0])
//! Get array end pointer.
#define DE_ARRAY_END(ARR) (DE_ARRAY_BEGIN(ARR) + DE_LENGTH_OF_ARRAY(ARR))
//! Empty C++ compilation unit silencing.
#if (DE_COMPILER == DE_COMPILER_MSC)
# define DE_EMPTY_CPP_FILE namespace { deUint8 unused; }
#else
# define DE_EMPTY_CPP_FILE
#endif
// Warn if type is constructed, but left unused
//
// Used in types with non-trivial ctor/dtor but with ctor-dtor pair causing no (observable)
// side-effects.
//
// \todo add attribute for GCC
#if (DE_COMPILER == DE_COMPILER_CLANG) && defined(__has_attribute)
# if __has_attribute(warn_unused)
# define DE_WARN_UNUSED_TYPE __attribute__((warn_unused))
# else
# define DE_WARN_UNUSED_TYPE
# endif
#else
# define DE_WARN_UNUSED_TYPE
#endif
#endif // _DEDEFS_HPP
<|endoftext|> |
<commit_before>#pragma once
#ifndef INPUTCOMMON_H_UTH
#define INPUTCOMMON_H_UTH
//Windows
#include <UtH/Platform/Common/InputBase.hpp>
#include <pmath/Vector2.hpp>
namespace uth
{
enum InputEvent
{
NONE = 0,
STATIONARY,
CLICK,
TAP = CLICK,
DRAG,
ZOOM_IN,
ZOOM_OUT
};
class CommonInput : public InputBase
{
private:
InputEvent m_event;
pmath::Vec2 m_position;
public:
const InputEvent& Event() const;
const pmath::Vec2 Position() const;
void Update();
// Use with uthInput.Common == Event
bool operator == (const InputEvent& Event) const;
bool operator != (const InputEvent& Event) const;
};
}
#endif<commit_msg>Added RELEASE event for input for windows too.<commit_after>#pragma once
#ifndef INPUTCOMMON_H_UTH
#define INPUTCOMMON_H_UTH
//Windows
#include <UtH/Platform/Common/InputBase.hpp>
#include <pmath/Vector2.hpp>
namespace uth
{
enum InputEvent
{
NONE = 0,
STATIONARY,
CLICK,
TAP = CLICK,
DRAG,
ZOOM_IN,
ZOOM_OUT,
RELEASE = CLICK
};
class CommonInput : public InputBase
{
private:
InputEvent m_event;
pmath::Vec2 m_position;
public:
const InputEvent& Event() const;
const pmath::Vec2 Position() const;
void Update();
// Use with uthInput.Common == Event
bool operator == (const InputEvent& Event) const;
bool operator != (const InputEvent& Event) const;
};
}
#endif<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin 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/>.
*/
#ifndef LIBBITCOIN_CHANNEL_HPP
#define LIBBITCOIN_CHANNEL_HPP
#include <cstdint>
#include <memory>
#include <bitcoin/bitcoin/constants.hpp>
#include <bitcoin/bitcoin/define.hpp>
#include <bitcoin/bitcoin/network/channel_proxy.hpp>
#include <bitcoin/bitcoin/satoshi_serialize.hpp>
#include <bitcoin/bitcoin/utility/logger.hpp>
#include <bitcoin/bitcoin/utility/serializer.hpp>
namespace libbitcoin {
namespace network {
class channel;
// TODO: move channel_ptr into channel as public type (interface break).
typedef std::shared_ptr<channel> channel_ptr;
class BC_API channel
{
public:
// TODO: move into channel_proxy (interface break).
typedef std::shared_ptr<channel_proxy> channel_proxy_ptr;
channel(channel_proxy_ptr proxy);
~channel();
void stop();
bool stopped() const;
template <typename Message>
void send(const Message& packet, channel_proxy::send_handler handle_send)
{
const auto proxy = weak_proxy_.lock();
if (!proxy)
handle_send(error::service_stopped);
else
proxy->send(packet, handle_send);
}
void send_raw(const header_type& packet_header,
const data_chunk& payload, channel_proxy::send_handler handle_send);
void subscribe_version(
channel_proxy::receive_version_handler handle_receive);
void subscribe_verack(
channel_proxy::receive_verack_handler handle_receive);
void subscribe_address(
channel_proxy::receive_address_handler handle_receive);
void subscribe_get_address(
channel_proxy::receive_get_address_handler handle_receive);
void subscribe_inventory(
channel_proxy::receive_inventory_handler handle_receive);
void subscribe_get_data(
channel_proxy::receive_get_data_handler handle_receive);
void subscribe_get_blocks(
channel_proxy::receive_get_blocks_handler handle_receive);
void subscribe_transaction(
channel_proxy::receive_transaction_handler handle_receive);
void subscribe_block(
channel_proxy::receive_block_handler handle_receive);
void subscribe_raw(
channel_proxy::receive_raw_handler handle_receive);
void subscribe_stop(
channel_proxy::stop_handler handle_stop);
private:
std::weak_ptr<channel_proxy> weak_proxy_;
};
} // namespace network
} // namespace libbitcoin
#endif
<commit_msg>Remove unnecessary include.<commit_after>/**
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin 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/>.
*/
#ifndef LIBBITCOIN_CHANNEL_HPP
#define LIBBITCOIN_CHANNEL_HPP
#include <cstdint>
#include <memory>
#include <bitcoin/bitcoin/constants.hpp>
#include <bitcoin/bitcoin/define.hpp>
#include <bitcoin/bitcoin/network/channel_proxy.hpp>
#include <bitcoin/bitcoin/utility/logger.hpp>
#include <bitcoin/bitcoin/utility/serializer.hpp>
namespace libbitcoin {
namespace network {
class channel;
// TODO: move channel_ptr into channel as public type (interface break).
typedef std::shared_ptr<channel> channel_ptr;
class BC_API channel
{
public:
// TODO: move into channel_proxy (interface break).
typedef std::shared_ptr<channel_proxy> channel_proxy_ptr;
channel(channel_proxy_ptr proxy);
~channel();
void stop();
bool stopped() const;
template <typename Message>
void send(const Message& packet, channel_proxy::send_handler handle_send)
{
const auto proxy = weak_proxy_.lock();
if (!proxy)
handle_send(error::service_stopped);
else
proxy->send(packet, handle_send);
}
void send_raw(const header_type& packet_header,
const data_chunk& payload, channel_proxy::send_handler handle_send);
void subscribe_version(
channel_proxy::receive_version_handler handle_receive);
void subscribe_verack(
channel_proxy::receive_verack_handler handle_receive);
void subscribe_address(
channel_proxy::receive_address_handler handle_receive);
void subscribe_get_address(
channel_proxy::receive_get_address_handler handle_receive);
void subscribe_inventory(
channel_proxy::receive_inventory_handler handle_receive);
void subscribe_get_data(
channel_proxy::receive_get_data_handler handle_receive);
void subscribe_get_blocks(
channel_proxy::receive_get_blocks_handler handle_receive);
void subscribe_transaction(
channel_proxy::receive_transaction_handler handle_receive);
void subscribe_block(
channel_proxy::receive_block_handler handle_receive);
void subscribe_raw(
channel_proxy::receive_raw_handler handle_receive);
void subscribe_stop(
channel_proxy::stop_handler handle_stop);
private:
std::weak_ptr<channel_proxy> weak_proxy_;
};
} // namespace network
} // namespace libbitcoin
#endif
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2012-2014.
// 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
/// Forward declares monomorphic datasets interfaces
// ***************************************************************************
#ifndef BOOST_TEST_DATA_MONOMORPHIC_FWD_HPP_102212GER
#define BOOST_TEST_DATA_MONOMORPHIC_FWD_HPP_102212GER
// Boost.Test
#include <boost/test/data/config.hpp>
#include <boost/test/data/size.hpp>
#include <boost/test/utils/is_forward_iterable.hpp>
// Boost
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/add_const.hpp>
#else
#include <boost/utility/declval.hpp>
#endif
#include <boost/type_traits/remove_const.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/type_traits/decay.hpp>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
namespace data {
namespace monomorphic {
#if !defined(BOOST_TEST_DOXYGEN_DOC__)
template<typename T>
struct traits;
template<typename T>
class dataset;
template<typename T>
class singleton;
template<typename C>
class collection;
template<typename T>
class array;
#endif
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
# define BOOST_TEST_ENABLE_IF std::enable_if
#else
# define BOOST_TEST_ENABLE_IF boost::enable_if_c
#endif
// ************************************************************************** //
// ************** monomorphic::is_dataset ************** //
// ************************************************************************** //
//! Helper metafunction indicating if the specified type is a dataset.
template<typename DS>
struct is_dataset : mpl::false_ {};
//! A reference to a dataset is a dataset
template<typename DS>
struct is_dataset<DS&> : is_dataset<DS> {};
//! A const dataset is a dataset
template<typename DS>
struct is_dataset<DS const> : is_dataset<DS> {};
//____________________________________________________________________________//
} // namespace monomorphic
// ************************************************************************** //
// ************** data::make ************** //
// ************************************************************************** //
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
//! @brief Creates a dataset from a value, a collection or an array
//!
//! This function has several overloads:
//! @code
//! // returns ds if ds is already a dataset
//! template <typename DS> DS make(DS&& ds);
//!
//! // creates a singleton dataset, for non forward iterable and non dataset type T
//! // (a C string is not considered as a sequence).
//! template <typename T> monomorphic::singleton<T> make(T&& v);
//! monomorphic::singleton<char*> make( char* str );
//! monomorphic::singleton<char const*> make( char const* str );
//!
//! // creates a collection dataset, for forward iterable and non dataset type C
//! template <typename C> monomorphic::collection<C> make(C && c);
//!
//! // creates an array dataset
//! template<typename T, std::size_t size> monomorphic::array<T> make( T (&a)[size] );
//! @endcode
template<typename DS>
inline typename BOOST_TEST_ENABLE_IF<monomorphic::is_dataset<DS>::value,DS>::type
make(DS&& ds)
{
return std::forward<DS>( ds );
}
// warning: doxygen is apparently unable to handle @overload from different files, so if the overloads
// below are not declared with @overload in THIS file, they do not appear in the documentation.
// fwrd declaration for singletons
//! @overload boost::unit_test::data::make()
template<typename T>
inline typename BOOST_TEST_ENABLE_IF<!is_forward_iterable<T>::value &&
!monomorphic::is_dataset<T>::value &&
!boost::is_array< typename boost::remove_reference<T>::type >::value,
monomorphic::singleton<T> >::type
make( T&& v );
//! @overload boost::unit_test::data::make()
template<typename C>
inline typename BOOST_TEST_ENABLE_IF<is_forward_iterable<C>::value,
monomorphic::collection<C> >::type
make( C&& c );
#else // !BOOST_NO_CXX11_RVALUE_REFERENCES
//! @overload boost::unit_test:data::make()
template<typename DS>
inline typename BOOST_TEST_ENABLE_IF<monomorphic::is_dataset<DS>::value,DS const&>::type
make(DS const& ds)
{
return ds;
}
// fwrd declaration for singletons
#if !(defined(BOOST_MSVC) && (BOOST_MSVC < 1600))
//! @overload boost::unit_test::data::make()
template<typename T>
inline typename BOOST_TEST_ENABLE_IF<!is_forward_iterable<T>::value &&
!monomorphic::is_dataset<T>::value &&
!boost::is_array< typename boost::remove_reference<T>::type >::value,
monomorphic::singleton<T> >::type
make( T const& v );
#endif
// fwrd declaration for collections
//! @overload boost::unit_test::data::make()
template<typename C>
inline typename BOOST_TEST_ENABLE_IF<is_forward_iterable<C>::value,
monomorphic::collection<C> >::type
make( C const& c );
//____________________________________________________________________________//
#endif // !BOOST_NO_CXX11_RVALUE_REFERENCES
// fwrd declarations
//! @overload boost::unit_test::data::make()
template<typename T, std::size_t size>
inline monomorphic::array< typename boost::remove_const<T>::type >
make( T (&a)[size] );
// apparently some compilers (eg clang-3.4 on linux) have trouble understanding
// the previous line for T being const
//! @overload boost::unit_test::data::make()
template<typename T, std::size_t size>
inline monomorphic::array< typename boost::remove_const<T>::type >
make( T const (&)[size] );
template<typename T, std::size_t size>
inline monomorphic::array< typename boost::remove_const<T>::type >
make( T a[size] );
//! @overload boost::unit_test::data::make()
inline monomorphic::singleton<char*>
make( char* str );
//! @overload boost::unit_test::data::make()
inline monomorphic::singleton<char const*>
make( char const* str );
//____________________________________________________________________________//
namespace result_of {
#ifndef BOOST_NO_CXX11_DECLTYPE
//! Result of the make call.
template<typename DS>
struct make
{
typedef decltype(data::make(boost::declval<DS>())) type;
};
#else
// explicit specialisation, cumbersome
template <typename DS, typename Enable = void>
struct make;
template <typename DS>
struct make<
DS const&,
typename BOOST_TEST_ENABLE_IF<monomorphic::is_dataset<DS>::value>::type
>
{
typedef DS const& type;
};
template <typename T>
struct make<
T,
typename BOOST_TEST_ENABLE_IF< (!is_forward_iterable<T>::value &&
!monomorphic::is_dataset<T>::value &&
!boost::is_array< typename boost::remove_reference<T>::type >::value)
>::type
>
{
typedef monomorphic::singleton<T> type;
};
template <typename C>
struct make<
C,
typename BOOST_TEST_ENABLE_IF< is_forward_iterable<C>::value>::type
>
{
typedef monomorphic::collection<C> type;
};
#if 1
template <typename T, std::size_t size>
struct make<T [size]>
{
typedef monomorphic::array<typename boost::remove_const<T>::type> type;
};
#endif
template <typename T, std::size_t size>
struct make<T (&)[size]>
{
typedef monomorphic::array<typename boost::remove_const<T>::type> type;
};
template <typename T, std::size_t size>
struct make<T const (&)[size]>
{
typedef monomorphic::array<typename boost::remove_const<T>::type> type;
};
template <>
struct make<char*>
{
typedef monomorphic::singleton<char*> type;
};
template <>
struct make<char const*>
{
typedef monomorphic::singleton<char const*> type;
};
#endif // BOOST_NO_CXX11_DECLTYPE
} // namespace result_of
//____________________________________________________________________________//
} // namespace data
} // namespace unit_test
} // namespace boost
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_DATA_MONOMORPHIC_FWD_HPP_102212GER
<commit_msg>Update fwd.hpp<commit_after>// (C) Copyright Gennadiy Rozental 2012-2014.
// 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
/// Forward declares monomorphic datasets interfaces
// ***************************************************************************
#ifndef BOOST_TEST_DATA_MONOMORPHIC_FWD_HPP_102212GER
#define BOOST_TEST_DATA_MONOMORPHIC_FWD_HPP_102212GER
// Boost.Test
#include <boost/test/data/config.hpp>
#include <boost/test/data/size.hpp>
#include <boost/test/utils/is_forward_iterable.hpp>
// Boost
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/add_const.hpp>
#else
#include <boost/utility/declval.hpp>
#endif
#include <boost/type_traits/remove_const.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/type_traits/decay.hpp>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
namespace data {
namespace monomorphic {
#if !defined(BOOST_TEST_DOXYGEN_DOC__)
template<typename T>
struct traits;
template<typename T>
class dataset;
template<typename T>
class singleton;
template<typename C>
class collection;
template<typename T>
class array;
#endif
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
# define BOOST_TEST_ENABLE_IF std::enable_if
#else
# define BOOST_TEST_ENABLE_IF boost::enable_if_c
#endif
// ************************************************************************** //
// ************** monomorphic::is_dataset ************** //
// ************************************************************************** //
//! Helper metafunction indicating if the specified type is a dataset.
template<typename D_S>
struct is_dataset : mpl::false_ {};
//! A reference to a dataset is a dataset
template<typename D_S>
struct is_dataset<D_S&> : is_dataset<D_S> {};
//! A const dataset is a dataset
template<typename D_S>
struct is_dataset<D_S const> : is_dataset<D_S> {};
//____________________________________________________________________________//
} // namespace monomorphic
// ************************************************************************** //
// ************** data::make ************** //
// ************************************************************************** //
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
//! @brief Creates a dataset from a value, a collection or an array
//!
//! This function has several overloads:
//! @code
//! // returns ds if ds is already a dataset
//! template <typename D_S> D_S make(D_S&& ds);
//!
//! // creates a singleton dataset, for non forward iterable and non dataset type T
//! // (a C string is not considered as a sequence).
//! template <typename T> monomorphic::singleton<T> make(T&& v);
//! monomorphic::singleton<char*> make( char* str );
//! monomorphic::singleton<char const*> make( char const* str );
//!
//! // creates a collection dataset, for forward iterable and non dataset type C
//! template <typename C> monomorphic::collection<C> make(C && c);
//!
//! // creates an array dataset
//! template<typename T, std::size_t size> monomorphic::array<T> make( T (&a)[size] );
//! @endcode
template<typename D_S>
inline typename BOOST_TEST_ENABLE_IF<monomorphic::is_dataset<D_S>::value,D_S>::type
make(D_S&& ds)
{
return std::forward<D_S>( ds );
}
// warning: doxygen is apparently unable to handle @overload from different files, so if the overloads
// below are not declared with @overload in THIS file, they do not appear in the documentation.
// fwrd declaration for singletons
//! @overload boost::unit_test::data::make()
template<typename T>
inline typename BOOST_TEST_ENABLE_IF<!is_forward_iterable<T>::value &&
!monomorphic::is_dataset<T>::value &&
!boost::is_array< typename boost::remove_reference<T>::type >::value,
monomorphic::singleton<T> >::type
make( T&& v );
//! @overload boost::unit_test::data::make()
template<typename C>
inline typename BOOST_TEST_ENABLE_IF<is_forward_iterable<C>::value,
monomorphic::collection<C> >::type
make( C&& c );
#else // !BOOST_NO_CXX11_RVALUE_REFERENCES
//! @overload boost::unit_test:data::make()
template<typename D_S>
inline typename BOOST_TEST_ENABLE_IF<monomorphic::is_dataset<D_S>::value,D_S const&>::type
make(D_S const& ds)
{
return ds;
}
// fwrd declaration for singletons
#if !(defined(BOOST_MSVC) && (BOOST_MSVC < 1600))
//! @overload boost::unit_test::data::make()
template<typename T>
inline typename BOOST_TEST_ENABLE_IF<!is_forward_iterable<T>::value &&
!monomorphic::is_dataset<T>::value &&
!boost::is_array< typename boost::remove_reference<T>::type >::value,
monomorphic::singleton<T> >::type
make( T const& v );
#endif
// fwrd declaration for collections
//! @overload boost::unit_test::data::make()
template<typename C>
inline typename BOOST_TEST_ENABLE_IF<is_forward_iterable<C>::value,
monomorphic::collection<C> >::type
make( C const& c );
//____________________________________________________________________________//
#endif // !BOOST_NO_CXX11_RVALUE_REFERENCES
// fwrd declarations
//! @overload boost::unit_test::data::make()
template<typename T, std::size_t size>
inline monomorphic::array< typename boost::remove_const<T>::type >
make( T (&a)[size] );
// apparently some compilers (eg clang-3.4 on linux) have trouble understanding
// the previous line for T being const
//! @overload boost::unit_test::data::make()
template<typename T, std::size_t size>
inline monomorphic::array< typename boost::remove_const<T>::type >
make( T const (&)[size] );
template<typename T, std::size_t size>
inline monomorphic::array< typename boost::remove_const<T>::type >
make( T a[size] );
//! @overload boost::unit_test::data::make()
inline monomorphic::singleton<char*>
make( char* str );
//! @overload boost::unit_test::data::make()
inline monomorphic::singleton<char const*>
make( char const* str );
//____________________________________________________________________________//
namespace result_of {
#ifndef BOOST_NO_CXX11_DECLTYPE
//! Result of the make call.
template<typename D_S>
struct make
{
typedef decltype(data::make(boost::declval<D_S>())) type;
};
#else
// explicit specialisation, cumbersome
template <typename D_S, typename Enable = void>
struct make;
template <typename D_S>
struct make<
D_S const&,
typename BOOST_TEST_ENABLE_IF<monomorphic::is_dataset<D_S>::value>::type
>
{
typedef D_S const& type;
};
template <typename T>
struct make<
T,
typename BOOST_TEST_ENABLE_IF< (!is_forward_iterable<T>::value &&
!monomorphic::is_dataset<T>::value &&
!boost::is_array< typename boost::remove_reference<T>::type >::value)
>::type
>
{
typedef monomorphic::singleton<T> type;
};
template <typename C>
struct make<
C,
typename BOOST_TEST_ENABLE_IF< is_forward_iterable<C>::value>::type
>
{
typedef monomorphic::collection<C> type;
};
#if 1
template <typename T, std::size_t size>
struct make<T [size]>
{
typedef monomorphic::array<typename boost::remove_const<T>::type> type;
};
#endif
template <typename T, std::size_t size>
struct make<T (&)[size]>
{
typedef monomorphic::array<typename boost::remove_const<T>::type> type;
};
template <typename T, std::size_t size>
struct make<T const (&)[size]>
{
typedef monomorphic::array<typename boost::remove_const<T>::type> type;
};
template <>
struct make<char*>
{
typedef monomorphic::singleton<char*> type;
};
template <>
struct make<char const*>
{
typedef monomorphic::singleton<char const*> type;
};
#endif // BOOST_NO_CXX11_DECLTYPE
} // namespace result_of
//____________________________________________________________________________//
} // namespace data
} // namespace unit_test
} // namespace boost
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_DATA_MONOMORPHIC_FWD_HPP_102212GER
<|endoftext|> |
<commit_before>#include "brents_fun.h"
#include <iomanip>
//The code is from: http://rosettacode.org/wiki/Roots_of_a_function#C.2B.2B
unsigned int brents_fun(std::function<double (double)> f, double& sol, double lower, double upper, double tol, unsigned int max_iter)
{
double a = lower;
double b = upper;
double fa = f(a); // calculated now to save function calls
double fb = f(b); // calculated now to save function calls
double fs = 0; // initialize
if (!(fa * fb < 0))
{
// throws exception if root isn't bracketed
//std::cout << "Signs of f(lower_bound) and f(upper_bound) must be opposites" << std::endl;
return 0;
}
if (std::abs(fa) < std::abs(b)) // if magnitude of f(lower_bound) is less than magnitude of f(upper_bound)
{
std::swap(a,b);
std::swap(fa,fb);
}
double c = a; // c now equals the largest magnitude of the lower and upper bounds
double fc = fa; // precompute function evalutation for point c by assigning it the same value as fa
bool mflag = true; // boolean flag used to evaluate if statement later on
double s = 0; // Our Root that will be returned
double d = 0; // Only used if mflag is unset (mflag == false)
for (unsigned int iter = 1; iter < max_iter; ++iter)
{
// stop if converged on root or error is less than tolerance
if (std::abs(b-a) < tol)
{
//std::cout<<std::setprecision(16)<< "After " << iter << " iterations the root is: " << s << std::endl;
sol=b;
return iter;
} // end if
if (fa != fc && fb != fc)
{
// use inverse quadratic interopolation
s = ( a * fb * fc / ((fa - fb) * (fa - fc)) )
+ ( b * fa * fc / ((fb - fa) * (fb - fc)) )
+ ( c * fa * fb / ((fc - fa) * (fc - fb)) );
}
else
{
// secant method
s = b - fb * (b - a) / (fb - fa);
}
// checks to see whether we can use the faster converging quadratic && secant methods
// or if we need to use bisection
if ( ( (s < (3 * a + b) * 0.25) || (s > b) ) ||
( mflag && (std::abs(s-b) >= (std::abs(b-c) * 0.5)) ) ||
( !mflag && (std::abs(s-b) >= (std::abs(c-d) * 0.5)) ) ||
( mflag && (std::abs(b-c) < tol) ) ||
( !mflag && (std::abs(c-d) < tol)) )
{
// bisection method
s = (a+b)*0.5;
mflag = true;
}
else
{
mflag = false;
}
fs = f(s); // calculate fs
d = c; // first time d is being used (wasnt used on first iteration because mflag was set)
c = b; // set c equal to upper bound
fc = fb; // set f(c) = f(b)
if ( fa * fs < 0) // fa and fs have opposite signs
{
b = s;
fb = fs; // set f(b) = f(s)
}
else
{
a = s;
fa = fs; // set f(a) = f(s)
}
if (std::abs(fa) < std::abs(fb)) // if magnitude of fa is less than magnitude of fb
{
std::swap(a,b); // swap a and b
std::swap(fa,fb); // make sure f(a) and f(b) are correct after swap
}
} // end for
//std::cout<< "The solution does not converge or iterations are not sufficient" << std::endl;
return max_iter;
} // end brents_fun
<commit_msg>fix the bug's bug.<commit_after>#include "brents_fun.h"
#include <iomanip>
//The code is from: http://rosettacode.org/wiki/Roots_of_a_function#C.2B.2B
unsigned int brents_fun(std::function<double (double)> f, double& sol, double lower, double upper, double tol, unsigned int max_iter)
{
double a = lower;
double b = upper;
double fa = f(a); // calculated now to save function calls
double fb = f(b); // calculated now to save function calls
double fs = 0; // initialize
if (!(fa * fb < 0))
{
// throws exception if root isn't bracketed
//std::cout << "Signs of f(lower_bound) and f(upper_bound) must be opposites" << std::endl;
return 0;
}
if (std::abs(fa) < std::abs(b)) // if magnitude of f(lower_bound) is less than magnitude of f(upper_bound)
{
std::swap(a,b);
std::swap(fa,fb);
}
double c = a; // c now equals the largest magnitude of the lower and upper bounds
double fc = fa; // precompute function evalutation for point c by assigning it the same value as fa
bool mflag = true; // boolean flag used to evaluate if statement later on
double s = b; // Our Root that will be returned
double d = 0; // Only used if mflag is unset (mflag == false)
for (unsigned int iter = 1; iter < max_iter; ++iter)
{
// stop if converged on root or error is less than tolerance
if (std::abs(b-a) < tol || fb==0)
{
//std::cout<<std::setprecision(16)<< "After " << iter << " iterations the root is: " << s << std::endl;
sol=s;
return iter;
} // end if
if (fa != fc && fb != fc)
{
// use inverse quadratic interopolation
s = ( a * fb * fc / ((fa - fb) * (fa - fc)) )
+ ( b * fa * fc / ((fb - fa) * (fb - fc)) )
+ ( c * fa * fb / ((fc - fa) * (fc - fb)) );
}
else
{
// secant method
s = b - fb * (b - a) / (fb - fa);
}
// checks to see whether we can use the faster converging quadratic && secant methods
// or if we need to use bisection
if ( ( (s < (3 * a + b) * 0.25) || (s > b) ) ||
( mflag && (std::abs(s-b) >= (std::abs(b-c) * 0.5)) ) ||
( !mflag && (std::abs(s-b) >= (std::abs(c-d) * 0.5)) ) ||
( mflag && (std::abs(b-c) < tol) ) ||
( !mflag && (std::abs(c-d) < tol)) )
{
// bisection method
s = (a+b)*0.5;
mflag = true;
}
else
{
mflag = false;
}
fs = f(s); // calculate fs
d = c; // first time d is being used (wasnt used on first iteration because mflag was set)
c = b; // set c equal to upper bound
fc = fb; // set f(c) = f(b)
if ( fa * fs < 0) // fa and fs have opposite signs
{
b = s;
fb = fs; // set f(b) = f(s)
}
else
{
a = s;
fa = fs; // set f(a) = f(s)
}
if (std::abs(fa) < std::abs(fb)) // if magnitude of fa is less than magnitude of fb
{
std::swap(a,b); // swap a and b
std::swap(fa,fb); // make sure f(a) and f(b) are correct after swap
}
} // end for
//std::cout<< "The solution does not converge or iterations are not sufficient" << std::endl;
return max_iter;
} // end brents_fun
<|endoftext|> |
<commit_before>/**
* \file
* \brief SortedIntrusiveForwardList template class header
*
* \author Copyright (C) 2015-2017 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/.
*/
#ifndef ESTD_SORTEDINTRUSIVEFORWARDLIST_HPP_
#define ESTD_SORTEDINTRUSIVEFORWARDLIST_HPP_
#include "estd/IntrusiveForwardList.hpp"
#include <algorithm>
namespace estd
{
/**
* \brief SortedIntrusiveForwardList class is an IntrusiveForwardList with sorted elements
*
* This class tries to provide an interface similar to std::forward_list.
*
* \note The elements are sorted as long as the user does not modify the contents.
*
* \tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in
* ascending order
* \tparam T is the type that has the IntrusiveForwardListNode variable
* \tparam NodePointer is a pointer-to-member to IntrusiveForwardListNode variable in \a T
* \tparam U is the type that will be stored on the list; it can be different from \a T, but must be implicitly
* convertible to \a T (so usually a type derived from \a T); default - \a T; using different type than \a T can be used
* to break circular dependencies, because \a T must be fully defined to instantiate this class, but it is enough to
* forward declare \a U - it only needs to be fully defined to use member functions
*/
template<typename Compare, typename T, IntrusiveForwardListNode T::* NodePointer, typename U = T>
class SortedIntrusiveForwardList
{
public:
/// unsorted intrusive forward list used internally
using UnsortedIntrusiveForwardList = IntrusiveForwardList<T, NodePointer, U>;
/// const iterator of elements on the list
using const_iterator = typename UnsortedIntrusiveForwardList::const_iterator;
/// const pointer to value linked in the list
using const_pointer = typename UnsortedIntrusiveForwardList::const_pointer;
/// const reference to value linked in the list
using const_reference = typename UnsortedIntrusiveForwardList::const_reference;
/// iterator of elements on the list
using iterator = typename UnsortedIntrusiveForwardList::iterator;
/// pointer to value linked in the list
using pointer = typename UnsortedIntrusiveForwardList::pointer;
/// reference to value linked in the list
using reference = typename UnsortedIntrusiveForwardList::reference;
/// value linked in the list
using value_type = typename UnsortedIntrusiveForwardList::value_type;
/**
* \brief SortedIntrusiveForwardList's constructor
*
* \param [in] compare is a reference to Compare object used to copy-construct internal comparison functor
*/
constexpr explicit SortedIntrusiveForwardList(const Compare& compare = Compare{}) :
implementation_{compare}
{
}
/**
* \return iterator of "one before the first" element on the list
*/
iterator before_begin()
{
return implementation_.intrusiveForwardList.before_begin();
}
/**
* \return const iterator of "one before the first" element on the list
*/
const_iterator before_begin() const
{
return implementation_.intrusiveForwardList.before_begin();
}
/**
* \return iterator of first element on the list
*/
iterator begin()
{
return implementation_.intrusiveForwardList.begin();
}
/**
* \return const iterator of first element on the list
*/
const_iterator begin() const
{
return implementation_.intrusiveForwardList.begin();
}
/**
* \return const iterator of "one before the first" element on the list
*/
const_iterator cbefore_begin() const
{
return implementation_.intrusiveForwardList.cbefore_begin();
}
/**
* \return const iterator of first element on the list
*/
const_iterator cbegin() const
{
return implementation_.intrusiveForwardList.cbegin();
}
/**
* \return const iterator of "one past the last" element on the list
*/
const_iterator cend() const
{
return implementation_.intrusiveForwardList.cend();
}
/**
* \brief Unlinks all elements from the list.
*/
void clear()
{
implementation_.intrusiveForwardList.clear();
}
/**
* \return true is the list is empty, false otherwise
*/
bool empty() const
{
return implementation_.intrusiveForwardList.empty();
}
/**
* \return iterator of "one past the last" element on the list
*/
iterator end()
{
return implementation_.intrusiveForwardList.end();
}
/**
* \return const iterator of "one past the last" element on the list
*/
const_iterator end() const
{
return implementation_.intrusiveForwardList.end();
}
/**
* \return reference to first element on the list
*/
reference front()
{
return implementation_.intrusiveForwardList.front();
}
/**
* \return const reference to first element on the list
*/
const_reference front() const
{
return implementation_.intrusiveForwardList.front();
}
/**
* \brief Links the element in the list, keeping it sorted.
*
* \param [in] newElement is a reference to the element that will be linked in the list
*
* \return iterator of \a newElement
*/
iterator insert(reference newElement)
{
return UnsortedIntrusiveForwardList::insert_after(implementation_.findInsertPositionBefore(newElement),
newElement);
}
/**
* \brief Unlinks the first element from the list.
*/
void pop_front()
{
implementation_.intrusiveForwardList.pop_front();
}
/**
* \brief Transfers the element from another list to this one, keeping it sorted.
*
* \param [in] beforeSplicedElement is an iterator of the element preceding the one which will be spliced from
* another list to this one
*/
void splice_after(const iterator beforeSplicedElement)
{
const auto splicedElement = std::next(beforeSplicedElement);
UnsortedIntrusiveForwardList::splice_after(implementation_.findInsertPositionBefore(*splicedElement),
beforeSplicedElement);
}
/**
* \brief Swaps contents with another list.
*
* \param [in] other is a reference to SortedIntrusiveForwardList with which contents of this list will be swapped
*/
void swap(SortedIntrusiveForwardList& other)
{
implementation_.swap(other.implementation_);
}
/**
* \brief Unlinks the element following \a position from the list.
*
* \note No instance of the list is needed for this operation.
*
* \param [in] position is an iterator preceding the element which will be unlinked from the list
*
* \return iterator of the element that was following the element which was unlinked
*/
static iterator erase_after(const iterator position)
{
return UnsortedIntrusiveForwardList::erase_after(position);
}
SortedIntrusiveForwardList(const SortedIntrusiveForwardList&) = delete;
SortedIntrusiveForwardList(SortedIntrusiveForwardList&&) = default;
const SortedIntrusiveForwardList& operator=(const SortedIntrusiveForwardList&) = delete;
SortedIntrusiveForwardList& operator=(SortedIntrusiveForwardList&&) = delete;
private:
/// Implementation struct is used primarily for "Empty Base Optimization" with \a Compare type
struct Implementation : public Compare
{
/**
* \brief Implementation's constructor
*
* \param [in] comparee is a reference to Compare object used to copy-construct internal comparison functor
*/
constexpr Implementation(const Compare& comparee) :
Compare{comparee},
intrusiveForwardList{}
{
}
/**
* \brief Finds insert position "before" the position that satisfies sorting criteria.
*
* \param [in] newElement is a const reference to new element that is going to be inserted/spliced
*
* \return iterator for which Compare's function call operator of next value and \a newElement returns true.
*/
iterator findInsertPositionBefore(const_reference newElement)
{
auto it = intrusiveForwardList.before_begin();
auto next = intrusiveForwardList.begin();
const auto end = intrusiveForwardList.end();
while (next != end && this->Compare::operator()(*next, newElement) == false)
{
it = next;
++next;
}
return it;
}
/**
* \brief Swaps contents with another instance.
*
* \param [in] other is a reference to Implementation with which contents of this instance will be swapped
*/
void swap(Implementation& other)
{
intrusiveForwardList.swap(other.intrusiveForwardList);
using std::swap;
swap(static_cast<Compare&>(*this), static_cast<Compare&>(other));
}
Implementation(const Implementation&) = delete;
Implementation(Implementation&&) = default;
const Implementation& operator=(const Implementation&) = delete;
Implementation& operator=(Implementation&&) = delete;
/// internal unsorted IntrusiveForwardList
UnsortedIntrusiveForwardList intrusiveForwardList;
};
/// internal Implementation object - unsorted IntrusiveForwardList and Compare instance
Implementation implementation_;
};
/**
* \brief Swaps contents of two lists.
*
* \tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in
* ascending order
* \tparam T is the type that has the IntrusiveForwardListNode variable
* \tparam NodePointer is a pointer-to-member to IntrusiveForwardListNode variable in \a T
* \tparam U is the type that will be stored on the list; it can be different from \a T, but must be implicitly
* convertible to \a T (so usually a type derived from \a T); default - \a T;
*
* \param [in] left is a reference to SortedIntrusiveForwardList with which contents of \a right will be swapped
* \param [in] right is a reference to SortedIntrusiveForwardList with which contents of \a left will be swapped
*/
template<typename Compare, typename T, IntrusiveForwardListNode T::* NodePointer, typename U = T>
inline void swap(SortedIntrusiveForwardList<Compare, T, NodePointer, U>& left,
SortedIntrusiveForwardList<Compare, T, NodePointer, U>& right)
{
left.swap(right);
}
} // namespace estd
#endif // ESTD_SORTEDINTRUSIVEFORWARDLIST_HPP_
<commit_msg>Make SortedIntrusiveForwardList::Implementation's constructor explicit<commit_after>/**
* \file
* \brief SortedIntrusiveForwardList template class header
*
* \author Copyright (C) 2015-2017 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/.
*/
#ifndef ESTD_SORTEDINTRUSIVEFORWARDLIST_HPP_
#define ESTD_SORTEDINTRUSIVEFORWARDLIST_HPP_
#include "estd/IntrusiveForwardList.hpp"
#include <algorithm>
namespace estd
{
/**
* \brief SortedIntrusiveForwardList class is an IntrusiveForwardList with sorted elements
*
* This class tries to provide an interface similar to std::forward_list.
*
* \note The elements are sorted as long as the user does not modify the contents.
*
* \tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in
* ascending order
* \tparam T is the type that has the IntrusiveForwardListNode variable
* \tparam NodePointer is a pointer-to-member to IntrusiveForwardListNode variable in \a T
* \tparam U is the type that will be stored on the list; it can be different from \a T, but must be implicitly
* convertible to \a T (so usually a type derived from \a T); default - \a T; using different type than \a T can be used
* to break circular dependencies, because \a T must be fully defined to instantiate this class, but it is enough to
* forward declare \a U - it only needs to be fully defined to use member functions
*/
template<typename Compare, typename T, IntrusiveForwardListNode T::* NodePointer, typename U = T>
class SortedIntrusiveForwardList
{
public:
/// unsorted intrusive forward list used internally
using UnsortedIntrusiveForwardList = IntrusiveForwardList<T, NodePointer, U>;
/// const iterator of elements on the list
using const_iterator = typename UnsortedIntrusiveForwardList::const_iterator;
/// const pointer to value linked in the list
using const_pointer = typename UnsortedIntrusiveForwardList::const_pointer;
/// const reference to value linked in the list
using const_reference = typename UnsortedIntrusiveForwardList::const_reference;
/// iterator of elements on the list
using iterator = typename UnsortedIntrusiveForwardList::iterator;
/// pointer to value linked in the list
using pointer = typename UnsortedIntrusiveForwardList::pointer;
/// reference to value linked in the list
using reference = typename UnsortedIntrusiveForwardList::reference;
/// value linked in the list
using value_type = typename UnsortedIntrusiveForwardList::value_type;
/**
* \brief SortedIntrusiveForwardList's constructor
*
* \param [in] compare is a reference to Compare object used to copy-construct internal comparison functor
*/
constexpr explicit SortedIntrusiveForwardList(const Compare& compare = Compare{}) :
implementation_{compare}
{
}
/**
* \return iterator of "one before the first" element on the list
*/
iterator before_begin()
{
return implementation_.intrusiveForwardList.before_begin();
}
/**
* \return const iterator of "one before the first" element on the list
*/
const_iterator before_begin() const
{
return implementation_.intrusiveForwardList.before_begin();
}
/**
* \return iterator of first element on the list
*/
iterator begin()
{
return implementation_.intrusiveForwardList.begin();
}
/**
* \return const iterator of first element on the list
*/
const_iterator begin() const
{
return implementation_.intrusiveForwardList.begin();
}
/**
* \return const iterator of "one before the first" element on the list
*/
const_iterator cbefore_begin() const
{
return implementation_.intrusiveForwardList.cbefore_begin();
}
/**
* \return const iterator of first element on the list
*/
const_iterator cbegin() const
{
return implementation_.intrusiveForwardList.cbegin();
}
/**
* \return const iterator of "one past the last" element on the list
*/
const_iterator cend() const
{
return implementation_.intrusiveForwardList.cend();
}
/**
* \brief Unlinks all elements from the list.
*/
void clear()
{
implementation_.intrusiveForwardList.clear();
}
/**
* \return true is the list is empty, false otherwise
*/
bool empty() const
{
return implementation_.intrusiveForwardList.empty();
}
/**
* \return iterator of "one past the last" element on the list
*/
iterator end()
{
return implementation_.intrusiveForwardList.end();
}
/**
* \return const iterator of "one past the last" element on the list
*/
const_iterator end() const
{
return implementation_.intrusiveForwardList.end();
}
/**
* \return reference to first element on the list
*/
reference front()
{
return implementation_.intrusiveForwardList.front();
}
/**
* \return const reference to first element on the list
*/
const_reference front() const
{
return implementation_.intrusiveForwardList.front();
}
/**
* \brief Links the element in the list, keeping it sorted.
*
* \param [in] newElement is a reference to the element that will be linked in the list
*
* \return iterator of \a newElement
*/
iterator insert(reference newElement)
{
return UnsortedIntrusiveForwardList::insert_after(implementation_.findInsertPositionBefore(newElement),
newElement);
}
/**
* \brief Unlinks the first element from the list.
*/
void pop_front()
{
implementation_.intrusiveForwardList.pop_front();
}
/**
* \brief Transfers the element from another list to this one, keeping it sorted.
*
* \param [in] beforeSplicedElement is an iterator of the element preceding the one which will be spliced from
* another list to this one
*/
void splice_after(const iterator beforeSplicedElement)
{
const auto splicedElement = std::next(beforeSplicedElement);
UnsortedIntrusiveForwardList::splice_after(implementation_.findInsertPositionBefore(*splicedElement),
beforeSplicedElement);
}
/**
* \brief Swaps contents with another list.
*
* \param [in] other is a reference to SortedIntrusiveForwardList with which contents of this list will be swapped
*/
void swap(SortedIntrusiveForwardList& other)
{
implementation_.swap(other.implementation_);
}
/**
* \brief Unlinks the element following \a position from the list.
*
* \note No instance of the list is needed for this operation.
*
* \param [in] position is an iterator preceding the element which will be unlinked from the list
*
* \return iterator of the element that was following the element which was unlinked
*/
static iterator erase_after(const iterator position)
{
return UnsortedIntrusiveForwardList::erase_after(position);
}
SortedIntrusiveForwardList(const SortedIntrusiveForwardList&) = delete;
SortedIntrusiveForwardList(SortedIntrusiveForwardList&&) = default;
const SortedIntrusiveForwardList& operator=(const SortedIntrusiveForwardList&) = delete;
SortedIntrusiveForwardList& operator=(SortedIntrusiveForwardList&&) = delete;
private:
/// Implementation struct is used primarily for "Empty Base Optimization" with \a Compare type
struct Implementation : public Compare
{
/**
* \brief Implementation's constructor
*
* \param [in] comparee is a reference to Compare object used to copy-construct internal comparison functor
*/
constexpr explicit Implementation(const Compare& comparee) :
Compare{comparee},
intrusiveForwardList{}
{
}
/**
* \brief Finds insert position "before" the position that satisfies sorting criteria.
*
* \param [in] newElement is a const reference to new element that is going to be inserted/spliced
*
* \return iterator for which Compare's function call operator of next value and \a newElement returns true.
*/
iterator findInsertPositionBefore(const_reference newElement)
{
auto it = intrusiveForwardList.before_begin();
auto next = intrusiveForwardList.begin();
const auto end = intrusiveForwardList.end();
while (next != end && this->Compare::operator()(*next, newElement) == false)
{
it = next;
++next;
}
return it;
}
/**
* \brief Swaps contents with another instance.
*
* \param [in] other is a reference to Implementation with which contents of this instance will be swapped
*/
void swap(Implementation& other)
{
intrusiveForwardList.swap(other.intrusiveForwardList);
using std::swap;
swap(static_cast<Compare&>(*this), static_cast<Compare&>(other));
}
Implementation(const Implementation&) = delete;
Implementation(Implementation&&) = default;
const Implementation& operator=(const Implementation&) = delete;
Implementation& operator=(Implementation&&) = delete;
/// internal unsorted IntrusiveForwardList
UnsortedIntrusiveForwardList intrusiveForwardList;
};
/// internal Implementation object - unsorted IntrusiveForwardList and Compare instance
Implementation implementation_;
};
/**
* \brief Swaps contents of two lists.
*
* \tparam Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in
* ascending order
* \tparam T is the type that has the IntrusiveForwardListNode variable
* \tparam NodePointer is a pointer-to-member to IntrusiveForwardListNode variable in \a T
* \tparam U is the type that will be stored on the list; it can be different from \a T, but must be implicitly
* convertible to \a T (so usually a type derived from \a T); default - \a T;
*
* \param [in] left is a reference to SortedIntrusiveForwardList with which contents of \a right will be swapped
* \param [in] right is a reference to SortedIntrusiveForwardList with which contents of \a left will be swapped
*/
template<typename Compare, typename T, IntrusiveForwardListNode T::* NodePointer, typename U = T>
inline void swap(SortedIntrusiveForwardList<Compare, T, NodePointer, U>& left,
SortedIntrusiveForwardList<Compare, T, NodePointer, U>& right)
{
left.swap(right);
}
} // namespace estd
#endif // ESTD_SORTEDINTRUSIVEFORWARDLIST_HPP_
<|endoftext|> |
<commit_before>#include <pcl/common/common.h>
#include <pcl/search/kdtree.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv/cv.h>
#include <eigen3/Eigen/Core>
#include <image_geometry/pinhole_camera_model.h>
#include <sensor_msgs/PointCloud2.h>
#include <common/small_helpers.hpp>
#ifndef PCL_DEPTH_FILTER_H_
#define PCL_DEPTH_FILTER_H_
inline void
extract_depth_discontinuity(
const image_geometry::PinholeCameraModel &camera_model,
pcl::PointCloud<pcl::PointXYZI> &in,
cv_bridge::CvImage& image_pcl,
int point_size = 1
)
{
pcl::search::KdTree<pcl::PointXYZI>::Ptr tree_n( new pcl::search::KdTree<pcl::PointXYZI>() );
tree_n->setInputCloud(in.makeShared());
tree_n->setEpsilon(0.5);
unsigned int hits = 0;
unsigned int hits_image = 0;
BOOST_FOREACH (const pcl::PointXYZI& pt, in.points){
// look up 3D position
// printf ("\t(%f, %f, %f)\n", pt.x, pt.y, pt.z);
// project to 2D Image
cv::Point2d point_image;
if( pt.z > 1) { // min distance from camera 1m
point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z));
if( between<int>(0, point_image.x, image_pcl.image.cols)
&& between<int>(0, point_image.y, image_pcl.image.rows)
)
{
hits_image++;
std::vector<int> k_indices;
std::vector<float> square_distance;
int neighbors = 0;
//Position in image is known
neighbors = tree_n->nearestKSearch(pt, 2, k_indices, square_distance);
// look for neighbors where at least 1 is closer (Distance to origin) than the other
float distance_selected = sqrt(/*(pt.x* pt.x)+(pt.y* pt.y)+*/(pt.z* pt.z));
float intensity_max = pt.intensity ;
if (neighbors > 0) {
int nearest_neighbor = 0;
for(int i = 0; i < neighbors; i++){
if( intensity_max < in.points.at(k_indices.at(i)).intensity ) intensity_max = in.points.at(k_indices.at(i)).intensity;
float current_distance = //(in->points.at(k_indices.at(i)).x* in->points.at(k_indices.at(i)).x)
// +(in->points.at(k_indices.at(i)).y* in->points.at(k_indices.at(i)).y)
+(in.points.at(k_indices.at(i)).z* in.points.at(k_indices.at(i)).z);
current_distance = sqrt(current_distance);
float range = 0.15;
if( (pt.z - range) < in.points.at(k_indices.at(i)).z
&& in.points.at(k_indices.at(i)).z > (pt.z + range)
)
{
//same area.. dont do anything
cv::circle(image_pcl.image, point_image, point_size, cv::Scalar(intensity_max), -1);
hits++;
break;
}
else{
}
// 1. Is one of the neighbors closer than selected?
// if( sqrt((distance_selected - current_distance)*(distance_selected - current_distance)) > 0.3 ){
// // YES
// cv::circle(image_pcl.image, point_image, point_size, cv::Scalar(intensity_max), -1);
// //out->push_back(pt);
// hits++;
// break;
// }
}
}
}
}
}
printf("Hits: %u Hit_image: %u cloud: %lu", hits, hits_image, in.size());
}
inline void
filter_depth_discontinuity(
pcl::PointCloud<pcl::PointXYZI> &in,
pcl::PointCloud<pcl::PointXYZI> &out,
int neighbohrs_to_search = 2,
float epsilon = 0.5
)
{
pcl::search::KdTree<pcl::PointXYZI>::Ptr tree_n( new pcl::search::KdTree<pcl::PointXYZI>() );
tree_n->setInputCloud(in.makeShared());
tree_n->setEpsilon(epsilon);
BOOST_FOREACH (const pcl::PointXYZI& pt, in.points){
std::vector<int> k_indices;
std::vector<float> square_distance;
int found_neighbors = 0;
//Position in image is known
found_neighbors = tree_n->nearestKSearch(pt, neighbohrs_to_search, k_indices, square_distance);
// look for neighbors where at least 1 is closer (Distance to origin) than the other
if (found_neighbors > 0) {
int nearest_neighbor = 0;
float distance = in.points.at(k_indices.at(0)).z;
for(int i = 1; i < found_neighbors; i++){
float current_distance = in.points.at(k_indices.at(i)).z;
// 1. Is one of the neighbors closer than selected?
if(distance > current_distance){
// YES
out.push_back(pt);
break;
}
}
}
}
}
inline void filter_depth_edges(
pcl::PointCloud<pcl::PointXY> &in_xy,
pcl::PointCloud<pcl::PointXYZI> &in_point,
pcl::PointCloud<pcl::PointXYZI> &out_filtred,
cv_bridge::CvImage& image_pcl,
int neighbohrs_to_search = 2,
int point_size = 1
)
{
assert( in_xy.points.size() == in_point.points.size());
pcl::search::KdTree<pcl::PointXY>::Ptr tree_n( new pcl::search::KdTree<pcl::PointXY>() );
tree_n->setInputCloud(in_xy.makeShared());
tree_n->setEpsilon(0.5);
unsigned int hits = 0;
unsigned int i_p = 0;
float cloud_intensity_min = 9999;
float cloud_intensity_max = 0;
BOOST_FOREACH (const pcl::PointXY& pt, in_xy.points){
pcl::PointXYZI* pt_ori = &in_point.points.at(i_p);
++i_p;
std::vector<int> k_indices;
std::vector<float> square_distance;
int found_neighbors = 0;
//Position in image is known
found_neighbors = tree_n->nearestKSearch(pt, neighbohrs_to_search, k_indices, square_distance);
//found_neighbors = tree_n->radiusSearch(pt, 2, k_indices, square_distance);
// look for neighbors where at least 1 is closer (Distance to origin) than the other
float pt_depth = pt_ori->z;
//float distance_selected = point_distance(*pt_ori);
float intensity_max = pt_ori->intensity;
if(intensity_max < cloud_intensity_min) cloud_intensity_min = intensity_max;
if(intensity_max > cloud_intensity_max) cloud_intensity_max = intensity_max;
int valid = 0;
if (found_neighbors > 0) {
int nearest_neighbor = 0;
for(int i = 0; i < found_neighbors; i++){
float intensity = in_point.points.at(k_indices.at(i)).intensity;
if(intensity > intensity_max) intensity_max = intensity;
//float current_distance = point_distance(in_point->points.at(k_indices.at(i)));
float current_distance = in_point.points.at(k_indices.at(i)).z;
// 1. Is one of the neighbors closer than selected?
if( pt_depth - current_distance > 0.5){
++valid;
}
if( !inRange<float>(intensity, 30.0, pt_ori->intensity)){
++valid;
}
}
}
if(valid > 0){
cv::circle(image_pcl.image, cv::Point2f(pt.x, pt.y), point_size, cv::Scalar(intensity_max), -1);
out_filtred.push_back(*pt_ori);
hits++;
}
}
printf("depth cloud: %lu, hits: %u imin: %f imax: %f", in_xy.size(), hits, cloud_intensity_min, cloud_intensity_max);
}
#endif
<commit_msg>added check for neighbohrs = 0<commit_after>#include <pcl/common/common.h>
#include <pcl/search/kdtree.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv/cv.h>
#include <eigen3/Eigen/Core>
#include <image_geometry/pinhole_camera_model.h>
#include <sensor_msgs/PointCloud2.h>
#include <common/small_helpers.hpp>
#ifndef PCL_DEPTH_FILTER_H_
#define PCL_DEPTH_FILTER_H_
inline void
extract_depth_discontinuity(
const image_geometry::PinholeCameraModel &camera_model,
pcl::PointCloud<pcl::PointXYZI> &in,
cv_bridge::CvImage& image_pcl,
int point_size = 1
)
{
pcl::search::KdTree<pcl::PointXYZI>::Ptr tree_n( new pcl::search::KdTree<pcl::PointXYZI>() );
tree_n->setInputCloud(in.makeShared());
tree_n->setEpsilon(0.5);
unsigned int hits = 0;
unsigned int hits_image = 0;
BOOST_FOREACH (const pcl::PointXYZI& pt, in.points){
// look up 3D position
// printf ("\t(%f, %f, %f)\n", pt.x, pt.y, pt.z);
// project to 2D Image
cv::Point2d point_image;
if( pt.z > 1) { // min distance from camera 1m
point_image = camera_model.project3dToPixel(cv::Point3d(pt.x, pt.y, pt.z));
if( between<int>(0, point_image.x, image_pcl.image.cols)
&& between<int>(0, point_image.y, image_pcl.image.rows)
)
{
hits_image++;
std::vector<int> k_indices;
std::vector<float> square_distance;
int neighbors = 0;
//Position in image is known
neighbors = tree_n->nearestKSearch(pt, 2, k_indices, square_distance);
// look for neighbors where at least 1 is closer (Distance to origin) than the other
float distance_selected = sqrt(/*(pt.x* pt.x)+(pt.y* pt.y)+*/(pt.z* pt.z));
float intensity_max = pt.intensity ;
if (neighbors > 0) {
int nearest_neighbor = 0;
for(int i = 0; i < neighbors; i++){
if( intensity_max < in.points.at(k_indices.at(i)).intensity ) intensity_max = in.points.at(k_indices.at(i)).intensity;
float current_distance = //(in->points.at(k_indices.at(i)).x* in->points.at(k_indices.at(i)).x)
// +(in->points.at(k_indices.at(i)).y* in->points.at(k_indices.at(i)).y)
+(in.points.at(k_indices.at(i)).z* in.points.at(k_indices.at(i)).z);
current_distance = sqrt(current_distance);
float range = 0.15;
if( (pt.z - range) < in.points.at(k_indices.at(i)).z
&& in.points.at(k_indices.at(i)).z > (pt.z + range)
)
{
//same area.. dont do anything
cv::circle(image_pcl.image, point_image, point_size, cv::Scalar(intensity_max), -1);
hits++;
break;
}
else{
}
// 1. Is one of the neighbors closer than selected?
// if( sqrt((distance_selected - current_distance)*(distance_selected - current_distance)) > 0.3 ){
// // YES
// cv::circle(image_pcl.image, point_image, point_size, cv::Scalar(intensity_max), -1);
// //out->push_back(pt);
// hits++;
// break;
// }
}
}
}
}
}
printf("Hits: %u Hit_image: %u cloud: %lu", hits, hits_image, in.size());
}
inline void
filter_depth_discontinuity(
pcl::PointCloud<pcl::PointXYZI> &in,
pcl::PointCloud<pcl::PointXYZI> &out,
int neighbohrs_to_search = 2,
float epsilon = 0.5
)
{
pcl::search::KdTree<pcl::PointXYZI>::Ptr tree_n( new pcl::search::KdTree<pcl::PointXYZI>() );
tree_n->setInputCloud(in.makeShared());
tree_n->setEpsilon(epsilon);
if(neighbohrs_to_search < 1)
{
neighbohrs_to_search = 1;
}
BOOST_FOREACH (const pcl::PointXYZI& pt, in.points){
std::vector<int> k_indices;
std::vector<float> square_distance;
int found_neighbors = 0;
//Position in image is known
found_neighbors = tree_n->nearestKSearch(pt, neighbohrs_to_search, k_indices, square_distance);
// look for neighbors where at least 1 is closer (Distance to origin) than the other
if (found_neighbors > 0) {
int nearest_neighbor = 0;
float distance = in.points.at(k_indices.at(0)).z;
for(int i = 1; i < found_neighbors; i++){
float current_distance = in.points.at(k_indices.at(i)).z;
// 1. Is one of the neighbors closer than selected?
if(distance > current_distance){
// YES
out.push_back(pt);
break;
}
}
}
}
}
inline void filter_depth_edges(
pcl::PointCloud<pcl::PointXY> &in_xy,
pcl::PointCloud<pcl::PointXYZI> &in_point,
pcl::PointCloud<pcl::PointXYZI> &out_filtred,
cv_bridge::CvImage& image_pcl,
int neighbohrs_to_search = 2,
int point_size = 1
)
{
assert( in_xy.points.size() == in_point.points.size());
pcl::search::KdTree<pcl::PointXY>::Ptr tree_n( new pcl::search::KdTree<pcl::PointXY>() );
tree_n->setInputCloud(in_xy.makeShared());
tree_n->setEpsilon(0.5);
unsigned int hits = 0;
unsigned int i_p = 0;
float cloud_intensity_min = 9999;
float cloud_intensity_max = 0;
BOOST_FOREACH (const pcl::PointXY& pt, in_xy.points){
pcl::PointXYZI* pt_ori = &in_point.points.at(i_p);
++i_p;
std::vector<int> k_indices;
std::vector<float> square_distance;
int found_neighbors = 0;
//Position in image is known
found_neighbors = tree_n->nearestKSearch(pt, neighbohrs_to_search, k_indices, square_distance);
//found_neighbors = tree_n->radiusSearch(pt, 2, k_indices, square_distance);
// look for neighbors where at least 1 is closer (Distance to origin) than the other
float pt_depth = pt_ori->z;
//float distance_selected = point_distance(*pt_ori);
float intensity_max = pt_ori->intensity;
if(intensity_max < cloud_intensity_min) cloud_intensity_min = intensity_max;
if(intensity_max > cloud_intensity_max) cloud_intensity_max = intensity_max;
int valid = 0;
if (found_neighbors > 0) {
int nearest_neighbor = 0;
for(int i = 0; i < found_neighbors; i++){
float intensity = in_point.points.at(k_indices.at(i)).intensity;
if(intensity > intensity_max) intensity_max = intensity;
//float current_distance = point_distance(in_point->points.at(k_indices.at(i)));
float current_distance = in_point.points.at(k_indices.at(i)).z;
// 1. Is one of the neighbors closer than selected?
if( pt_depth - current_distance > 0.5){
++valid;
}
if( !inRange<float>(intensity, 30.0, pt_ori->intensity)){
++valid;
}
}
}
if(valid > 0){
cv::circle(image_pcl.image, cv::Point2f(pt.x, pt.y), point_size, cv::Scalar(intensity_max), -1);
out_filtred.push_back(*pt_ori);
hits++;
}
}
printf("depth cloud: %lu, hits: %u imin: %f imax: %f", in_xy.size(), hits, cloud_intensity_min, cloud_intensity_max);
}
#endif
<|endoftext|> |
<commit_before>//============================================================================
// include/vsmc/opencl/internal/cl_wrapper.hpp
//----------------------------------------------------------------------------
//
// vSMC: Scalable Monte Carlo
//
// This file is distributed under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================
#ifndef VSMC_OPENCL_INTERNAL_CL_WRAPPER_HPP
#define VSMC_OPENCL_INTERNAL_CL_WRAPPER_HPP
#if defined(VSMC_GCC)
#if VSMC_GCC_VERSION >= 40600
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#elif defined(VSMC_MSVC)
#pragma warning(push)
#pragma warning(disable:4996)
#endif
#include <cl.hpp>
#ifndef __CL_ENABLE_EXCEPTIONS
#error __CL_ENABLE_EXCEPTIONS not defined before #include<cl.hpp>
#endif
#if defined(VSMC_GCC)
#if VSMC_GCC_VERSION >= 40600
#pragma GCC diagnostic pop
#endif
#elif defined(VSM_MSVC)
#pragma warning(pop)
#endif
#if defined(CL_VERSION_2_0)
#define VSMC_OPENCL_VERSION 200
#elif defined(CL_VERSION_1_2)
#define VSMC_OPENCL_VERSION 120
#elif defined(CL_VERSION_1_1)
#define VSMC_OPENCL_VERSION 110
#else
#define VSMC_OPENCL_VERSION 100
#endif
#endif // VSMC_OPENCL_INTERNAL_CL_WRAPPER_HPP
<commit_msg>cl_wrapper include config.hpp first<commit_after>//============================================================================
// include/vsmc/opencl/internal/cl_wrapper.hpp
//----------------------------------------------------------------------------
//
// vSMC: Scalable Monte Carlo
//
// This file is distributed under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================
#ifndef VSMC_OPENCL_INTERNAL_CL_WRAPPER_HPP
#define VSMC_OPENCL_INTERNAL_CL_WRAPPER_HPP
#include <vsmc/internal/config.hpp>
#if defined(VSMC_GCC)
#if VSMC_GCC_VERSION >= 40600
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#elif defined(VSMC_MSVC)
#pragma warning(push)
#pragma warning(disable:4996)
#endif
#include <cl.hpp>
#ifndef __CL_ENABLE_EXCEPTIONS
#error __CL_ENABLE_EXCEPTIONS not defined before #include<cl.hpp>
#endif
#if defined(VSMC_GCC)
#if VSMC_GCC_VERSION >= 40600
#pragma GCC diagnostic pop
#endif
#elif defined(VSM_MSVC)
#pragma warning(pop)
#endif
#if defined(CL_VERSION_2_0)
#define VSMC_OPENCL_VERSION 200
#elif defined(CL_VERSION_1_2)
#define VSMC_OPENCL_VERSION 120
#elif defined(CL_VERSION_1_1)
#define VSMC_OPENCL_VERSION 110
#else
#define VSMC_OPENCL_VERSION 100
#endif
#endif // VSMC_OPENCL_INTERNAL_CL_WRAPPER_HPP
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2007 Christoph Cullmann <cullmann@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kategrepthread.h"
#include "kategrepthread.moc"
#include <kdebug.h>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
KateGrepThread::KateGrepThread(QWidget *parent, const QString &dir,
bool recursive, const QStringList &fileWildcards,
const QList<QRegExp> &searchPattern)
: QThread (parent), m_cancel (false)
, m_recursive (recursive), m_fileWildcards (fileWildcards)
, m_searchPattern (searchPattern)
{
m_workQueue << dir;
}
KateGrepThread::~KateGrepThread ()
{}
void KateGrepThread::run ()
{
// do the real work
while (!m_cancel && !m_workQueue.isEmpty())
{
QDir currentDir (m_workQueue.takeFirst());
// if not readable, skip it
if (!currentDir.isReadable ())
continue;
// append all dirs to the workqueue
QFileInfoList currentSubDirs = currentDir.entryInfoList (QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot | QDir::Readable);
// append them to the workqueue, if readable
for (int i = 0; i < currentSubDirs.size(); ++i)
m_workQueue << currentSubDirs.at(i).absoluteFilePath ();
// work with all files in this dir..., use wildcards for them...
QFileInfoList currentFiles = currentDir.entryInfoList (m_fileWildcards, QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot | QDir::Readable);
// iterate over all files
for (int i = 0; !m_cancel && i < currentFiles.size(); ++i)
grepInFile (currentFiles.at(i).absoluteFilePath (), currentFiles.at(i).fileName());
}
}
void KateGrepThread::grepInFile (const QString &fileName, const QString &baseName)
{
QFile file (fileName);
// can't read file, return
if (!file.open(QFile::ReadOnly))
return;
// try to extract data
QTextStream stream (&file);
QStringList lines;
int lineNumber = 0;
while (!m_cancel && !stream.atEnd ())
{
// enough lines gathered, try to match them...
if (lines.size() == m_searchPattern.size())
{
int firstColumn = -1;
for (int i = 0; i < m_searchPattern.size(); ++i)
{
int column = m_searchPattern.at(i).indexIn (lines.at(i));
if (column == -1)
{
firstColumn = -1; // reset firstColumn
break;
}
else if (i == 0) // remember first column
firstColumn = column;
}
// found match...
if (firstColumn != -1)
{
kDebug () << "found match: " << fileName << " : " << lineNumber;
emit foundMatch (fileName, lineNumber, firstColumn, baseName, lines.at (0));
}
// remove first line...
lines.pop_front ();
++lineNumber;
}
lines.append (stream.readLine());
}
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>only do recursive search if wanted BUG: 157521<commit_after>/* This file is part of the KDE project
Copyright (C) 2007 Christoph Cullmann <cullmann@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kategrepthread.h"
#include "kategrepthread.moc"
#include <kdebug.h>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
KateGrepThread::KateGrepThread(QWidget *parent, const QString &dir,
bool recursive, const QStringList &fileWildcards,
const QList<QRegExp> &searchPattern)
: QThread (parent), m_cancel (false)
, m_recursive (recursive), m_fileWildcards (fileWildcards)
, m_searchPattern (searchPattern)
{
m_workQueue << dir;
}
KateGrepThread::~KateGrepThread ()
{}
void KateGrepThread::run ()
{
// do the real work
while (!m_cancel && !m_workQueue.isEmpty())
{
QDir currentDir (m_workQueue.takeFirst());
// if not readable, skip it
if (!currentDir.isReadable ())
continue;
// only add subdirs to worklist if we should do recursive search
if (m_recursive)
{
// append all dirs to the workqueue
QFileInfoList currentSubDirs = currentDir.entryInfoList (QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot | QDir::Readable);
// append them to the workqueue, if readable
for (int i = 0; i < currentSubDirs.size(); ++i)
m_workQueue << currentSubDirs.at(i).absoluteFilePath ();
}
// work with all files in this dir..., use wildcards for them...
QFileInfoList currentFiles = currentDir.entryInfoList (m_fileWildcards, QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot | QDir::Readable);
// iterate over all files
for (int i = 0; !m_cancel && i < currentFiles.size(); ++i)
grepInFile (currentFiles.at(i).absoluteFilePath (), currentFiles.at(i).fileName());
}
}
void KateGrepThread::grepInFile (const QString &fileName, const QString &baseName)
{
QFile file (fileName);
// can't read file, return
if (!file.open(QFile::ReadOnly))
return;
// try to extract data
QTextStream stream (&file);
QStringList lines;
int lineNumber = 0;
while (!m_cancel && !stream.atEnd ())
{
// enough lines gathered, try to match them...
if (lines.size() == m_searchPattern.size())
{
int firstColumn = -1;
for (int i = 0; i < m_searchPattern.size(); ++i)
{
int column = m_searchPattern.at(i).indexIn (lines.at(i));
if (column == -1)
{
firstColumn = -1; // reset firstColumn
break;
}
else if (i == 0) // remember first column
firstColumn = column;
}
// found match...
if (firstColumn != -1)
{
kDebug () << "found match: " << fileName << " : " << lineNumber;
emit foundMatch (fileName, lineNumber, firstColumn, baseName, lines.at (0));
}
// remove first line...
lines.pop_front ();
++lineNumber;
}
lines.append (stream.readLine());
}
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>//
// file : xQGanttBarViewPort_Events.C
// date : 11 nov 2000
// changed : 27 dec 2000
// author : jh
//
#include "xQGanttBarViewPort.h"
#include "xQGanttBarView.h"
#include <math.h>
KGanttItem* xQGanttBarViewPort::_currentItem = NULL;
int _currentMButton = 0;
bool _Mousemoved = FALSE;
bool _selectItem = false;
int _timediff;
bool _changeEnd = false, _changeStart = false;
int oldw = -1, oldx = -1;
QDateTime _tmpStartDateTime, _tmpEndDateTime;
void
xQGanttBarViewPort::mousePressEvent(QMouseEvent* e)
{
// set _currentItem to pushed mousebutton
_currentMButton = e->button();
_Mousemoved = false;
_startPoint->setX( e->x() );
_startPoint->setY( e->y() );
_endPoint->setX( e->x() );
_endPoint->setY( e->y() );
_itemInfo->hide();
_itemTextEdit->hide();
// right mousebutton & control -> popup menu
if(e->button() == RightButton && e->state() == ControlButton ) {
_menu->popup(e->globalPos());
return;
}
/*
* get clicked item and position
*/
_currentItem = NULL;
Position pos = check(&_currentItem, e->x(), e->y());
if(!_currentItem) {
unselectAll();
return;
}
/*
* edit text
*/
if(e->button() == MidButton && _mode == Select) {
xQTaskPosition* tp = _gItemList.find(_currentItem);
QPainter p(this);
QRect rect = p.boundingRect(tp->_textPosX,
tp->_textPosY, 200,
tp->_screenH, AlignLeft, _currentItem->getText() );
_itemTextEdit->setText(_currentItem->getText());
_itemTextEdit->move(tp->_textPosX, tp->_screenY + _margin + 1);
_itemTextEdit->setFixedWidth(rect.width()+40);
_itemTextEdit->setFixedHeight(tp->_screenH - 2 * _margin - 2);
_itemTextEdit->setFocus();
// if item is not editable, _itemTextEdit should be not editable
// as well
_itemTextEdit->setReadOnly(!_currentItem->isEditable());
_itemTextEdit->show();
}
/*
* open/close item, move start, end, item
*/
if(e->button() == LeftButton && _mode == Select) {
_timediff = 0;
switch(pos) {
case Handle:
_currentItem->open( !_currentItem->isOpen() );
break;
case Center:
_changeEnd = true;
_changeStart = true;
if(e->state() == ShiftButton) {
QString tmp; tmp.sprintf("%s\n", _currentItem->getText().latin1() );
tmp += _currentItem->getStart().toString();
tmp += " - ";
tmp += _currentItem->getEnd().toString();
_itemInfo->setText( tmp );
_itemInfo->adjustSize();
_itemInfo->move(e->x() + 25, _gItemList.find(_currentItem)->_screenY - 50 );
_itemInfo->show();
}
else
_selectItem = true;
break;
case East:
_changeEnd = true;
_changeStart = false;
break;
case West:
_changeStart = true;
_changeEnd = false;
break;
default :
break;
}
} // if(e->button() == LeftButton && _mode == Select)
}
void
xQGanttBarViewPort::mouseReleaseEvent(QMouseEvent* e)
{
switch(_mode) {
case Select: {
if(_Mousemoved == true) {
_itemInfo->hide();
if(_changeStart == true || _changeEnd == true) {
if(_changeStart == true) {
_currentItem->setStart( _tmpStartDateTime );
}
if(_changeEnd == true) {
_currentItem->setEnd( _tmpEndDateTime );
}
oldx = -1; oldw = -1;
recalc();
QWidget::update();
}
}
else {
if(_currentItem && _selectItem) {
if(e->state() & ControlButton) {
_currentItem->select( !_currentItem->isSelected() );
}
else {
bool state = _currentItem->isSelected();
unselectAll();
_currentItem->select( !state );
}
QWidget::update();
_selectItem = false;
}
}
_changeEnd = false;
_changeStart = false;
}
break;
case Zoom:
if(!_Mousemoved) {
if(e->button() == LeftButton)
zoom(1.4, e->x(), e->y() );
if(e->button() == RightButton)
zoom(0.7, e->x(), e->y() );
if(e->button() == MidButton)
zoomAll();
}
else {
if(_currentMButton == LeftButton) {
QPainter p(this);
QPen pen(DashLine);
pen.setColor(red);
p.setRasterOp(XorROP);
p.setPen( pen );
p.drawRect(_startPoint->x(),
_startPoint->y(),
_endPoint->x()-_startPoint->x(),
_endPoint->y() - _startPoint->y());
double x1 = _startPoint->x();
double y1 = _startPoint->y();
double x2 = _endPoint->x();
double y2 = _endPoint->y();
double sys_width = fabs(x2 - x1);
double mass = (_parent->visibleWidth()/ sys_width);
zoom(mass, (int) (x1+(x2-x1)/2), (int) (y1+(y2-y1)/2) );
}
}
break;
default:
break;
}
_Mousemoved = false;
_currentMButton = 0;
}
void
xQGanttBarViewPort::mouseMoveEvent(QMouseEvent* e)
{
if(fabs(_startPoint->x() - e->x()) < 2 &&
fabs(_startPoint->y() - e->y()) < 2 )
return;
static QPen _dashPen(QColor(255,0,0),DashLine);
static QPen _solidPen(QColor(200,200,200));
_Mousemoved = true;
switch(_mode) {
case Select: {
if(_currentMButton == LeftButton && _currentItem) {
QPainter p(this);
p.setRasterOp(XorROP);
// QPen pen(DashLine);
// pen.setColor(red);
p.setPen( _dashPen );
QString stmp;
stmp.sprintf("%s\n", _currentItem->getText().latin1() );
int pixeldiff = e->x() - _startPoint->x();
_timediff = (int) ((double) pixeldiff / _scaleX + 0.5 );
xQTaskPosition* tpos = _gItemList[_currentItem];
int x = tpos->_screenX; int w = tpos->_screenW;
if(_changeStart && _changeEnd) {
double tmp = (double) _timediff/(double) _snapgrid;
_timediff = ((int) (tmp + sgn(tmp) * 0.5)) * _snapgrid;
stmp += _currentItem->getStart().addSecs(_timediff*60).toString();
stmp += " - ";
stmp += _currentItem->getEnd().addSecs(_timediff*60).toString();
x += (int) (_timediff * _scaleX);
_tmpStartDateTime = _currentItem->getStart().addSecs(_timediff*60);
_tmpEndDateTime = _currentItem->getEnd().addSecs(_timediff*60);
}
else {
if(_changeStart) {
QDateTime movedStart( _currentItem->getStart().addSecs(_timediff*60) );
_tmpStartDateTime.setDate( movedStart.date() );
_tmpStartDateTime.setTime(QTime(0,0,0,0));
double diff = _tmpStartDateTime.secsTo(movedStart)/60;
double tmp = diff/(double) _snapgrid;
_timediff = ((int) (tmp + sgn(tmp) * 0.5)) * _snapgrid;
_tmpStartDateTime = _tmpStartDateTime.addSecs(_timediff*60);
_timediff = _currentItem->getStart().secsTo(_tmpStartDateTime)/60;
stmp += _tmpStartDateTime.toString().latin1();
stmp += " - ";
stmp += _currentItem->getEnd().toString();
x += (int) (_timediff * _scaleX);
w -= (int) (_timediff * _scaleX);
}
if(_changeEnd) {
QDateTime movedEnd( _currentItem->getEnd().addSecs(_timediff*60) );
_tmpEndDateTime.setDate( movedEnd.date() );
_tmpEndDateTime.setTime(QTime(0,0,0,0));
double diff = _tmpEndDateTime.secsTo(movedEnd)/60;
double tmp = diff/(double) _snapgrid;
_timediff = ((int) (tmp + sgn(tmp) * 0.5)) * _snapgrid;
_tmpEndDateTime = _tmpEndDateTime.addSecs(_timediff*60);
_timediff = _currentItem->getEnd().secsTo(_tmpEndDateTime)/60;
stmp += _currentItem->getStart().toString();
stmp += " - ";
stmp += _tmpEndDateTime.toString().latin1();
w += (int) (_timediff * _scaleX);
}
}
_itemInfo->setText( stmp );
_itemInfo->adjustSize();
_itemInfo->move(e->x() + 25, _gItemList.find(_currentItem)->_screenY - 50);
_itemInfo->show();
if(oldx > 0) {
p.fillRect(oldx, _gItemList.find(_currentItem)->_screenY,
oldw, _gItemList.find(_currentItem)->_screenH,
QBrush(QColor(50,50,50), Dense4Pattern));
p.drawRect(oldx, _gItemList.find(_currentItem)->_screenY,
oldw, _gItemList.find(_currentItem)->_screenH);
p.setPen(_solidPen);
if(_changeStart)
p.drawLine(oldx, 0, oldx, height());
if(oldw > 2)
if(_changeEnd)
p.drawLine(oldx + oldw, 0, oldx + oldw, height());
}
p.setPen(_dashPen);
p.fillRect(x, _gItemList.find(_currentItem)->_screenY,
w, _gItemList.find(_currentItem)->_screenH,
QBrush(QColor(50,50,50), Dense4Pattern) );
p.drawRect(x, _gItemList.find(_currentItem)->_screenY,
w, _gItemList.find(_currentItem)->_screenH);
p.setPen(_solidPen);
if(_changeStart)
p.drawLine(x, 0, x, height());
if(w>2)
if(_changeEnd)
p.drawLine(x + w, 0, x + w, height());
oldx = x; oldw = w;
}
else {
static Position _pos = Outside;
KGanttItem* item = NULL;
Position pos = check(&item, e->x(), e->y());
if(_pos != pos) {
_pos = pos;
if(pos == West || pos == East) {
setCursor( splitHCursor );
break;
}
if(pos == North || pos == South) {
setCursor( splitVCursor );
break;
}
if(pos == Center) {
setCursor( upArrowCursor);
break;
}
if(pos == Handle) {
setCursor(pointingHandCursor);
break;
}
setCursor(arrowCursor);
}
}
}
break;
case Zoom: {
if(_currentMButton == LeftButton) {
static QString strpos;
strpos = "";
int s = worldX(_startPoint->x());
QDateTime d1 = _toplevelitem->getStart().addSecs(s*60);
s = worldX(e->x());
QDateTime d2 = _toplevelitem->getStart().addSecs(s*60);
strpos += d1.date().toString();
strpos += " - ";
strpos += d2.date().toString();
emit message(strpos);
QPainter p(this);
QPen pen(DashLine);
pen.setColor(red);
p.setRasterOp(XorROP);
p.setPen( pen );
p.drawRect(_startPoint->x(),
_startPoint->y(),
_endPoint->x()-_startPoint->x(),
_endPoint->y() - _startPoint->y());
QBrush _selectedbrush( QColor(50,50,50), Dense4Pattern );
p.fillRect( _startPoint->x(), _startPoint->y(),
_endPoint->x()-_startPoint->x(), _endPoint->y() - _startPoint->y(),
_selectedbrush );
_endPoint->setX( e->x() );
_endPoint->setY( e->y() );
p.drawRect(_startPoint->x(), _startPoint->y(),
_endPoint->x()-_startPoint->x(), _endPoint->y() - _startPoint->y());
p.fillRect( _startPoint->x(), _startPoint->y(),
_endPoint->x()-_startPoint->x(), _endPoint->y() - _startPoint->y(),
_selectedbrush );
}
}
break;
case Move: {
emit scroll(_startPoint->x() - e->x(), _startPoint->y() - e->y() );
}
break;
default :
break;
}
}
void
xQGanttBarViewPort::keyPressEvent(QKeyEvent* e)
{
printf("xQGanttBarViewPort::keyPressEvent() key = %d \n", e->key() );
int dx = 15;
if(e->state() == ControlButton)
dx *= 10;
switch(e->key()) {
case Key_Left:
emit scroll(-dx,0);
break;
case Key_Right:
emit scroll(dx,0);
break;
case Key_Up:
emit scroll(0,-dx);
break;
case Key_Down:
emit scroll(0, dx);
break;
case 43: // +
zoom(1.4);
break;
case 45: // -
zoom(0.7);
break;
case 4103: // del
deleteSelectedItems();
break;
case 4102: // einfg
insertIntoSelectedItem();
break;
case 4119: // bild v
emit scroll(0, dx*15);
break;
case 4118: // bild ^
emit scroll(0,-dx*15);
break;
}
}
void
xQGanttBarViewPort::paintEvent(QPaintEvent * e)
/////////////////////////////////////////////////
{
update(e->rect().left(), e->rect().top(),
e->rect().right(), e->rect().bottom() );
}
<commit_msg>IRIX compile fix.<commit_after>//
// file : xQGanttBarViewPort_Events.C
// date : 11 nov 2000
// changed : 27 dec 2000
// author : jh
//
#include "xQGanttBarViewPort.h"
#include "xQGanttBarView.h"
#include <math.h>
KGanttItem* xQGanttBarViewPort::_currentItem = NULL;
int _currentMButton = 0;
bool _Mousemoved = FALSE;
bool _selectItem = false;
int _timediff;
bool _changeEnd = false, _changeStart = false;
int oldw = -1, oldx = -1;
QDateTime _tmpStartDateTime, _tmpEndDateTime;
void
xQGanttBarViewPort::mousePressEvent(QMouseEvent* e)
{
// set _currentItem to pushed mousebutton
_currentMButton = e->button();
_Mousemoved = false;
_startPoint->setX( e->x() );
_startPoint->setY( e->y() );
_endPoint->setX( e->x() );
_endPoint->setY( e->y() );
_itemInfo->hide();
_itemTextEdit->hide();
// right mousebutton & control -> popup menu
if(e->button() == RightButton && e->state() == ControlButton ) {
_menu->popup(e->globalPos());
return;
}
/*
* get clicked item and position
*/
_currentItem = NULL;
Position pos = check(&_currentItem, e->x(), e->y());
if(!_currentItem) {
unselectAll();
return;
}
/*
* edit text
*/
if(e->button() == MidButton && _mode == Select) {
xQTaskPosition* tp = _gItemList.find(_currentItem);
QPainter p(this);
QRect rect = p.boundingRect(tp->_textPosX,
tp->_textPosY, 200,
tp->_screenH, AlignLeft, _currentItem->getText() );
_itemTextEdit->setText(_currentItem->getText());
_itemTextEdit->move(tp->_textPosX, tp->_screenY + _margin + 1);
_itemTextEdit->setFixedWidth(rect.width()+40);
_itemTextEdit->setFixedHeight(tp->_screenH - 2 * _margin - 2);
_itemTextEdit->setFocus();
// if item is not editable, _itemTextEdit should be not editable
// as well
_itemTextEdit->setReadOnly(!_currentItem->isEditable());
_itemTextEdit->show();
}
/*
* open/close item, move start, end, item
*/
if(e->button() == LeftButton && _mode == Select) {
_timediff = 0;
switch(pos) {
case Handle:
_currentItem->open( !_currentItem->isOpen() );
break;
case Center:
_changeEnd = true;
_changeStart = true;
if(e->state() == ShiftButton) {
QString tmp; tmp.sprintf("%s\n", _currentItem->getText().latin1() );
tmp += _currentItem->getStart().toString();
tmp += " - ";
tmp += _currentItem->getEnd().toString();
_itemInfo->setText( tmp );
_itemInfo->adjustSize();
_itemInfo->move(e->x() + 25, _gItemList.find(_currentItem)->_screenY - 50 );
_itemInfo->show();
}
else
_selectItem = true;
break;
case East:
_changeEnd = true;
_changeStart = false;
break;
case West:
_changeStart = true;
_changeEnd = false;
break;
default :
break;
}
} // if(e->button() == LeftButton && _mode == Select)
}
void
xQGanttBarViewPort::mouseReleaseEvent(QMouseEvent* e)
{
switch(_mode) {
case Select: {
if(_Mousemoved == true) {
_itemInfo->hide();
if(_changeStart == true || _changeEnd == true) {
if(_changeStart == true) {
_currentItem->setStart( _tmpStartDateTime );
}
if(_changeEnd == true) {
_currentItem->setEnd( _tmpEndDateTime );
}
oldx = -1; oldw = -1;
recalc();
QWidget::update();
}
}
else {
if(_currentItem && _selectItem) {
if(e->state() & ControlButton) {
_currentItem->select( !_currentItem->isSelected() );
}
else {
bool state = _currentItem->isSelected();
unselectAll();
_currentItem->select( !state );
}
QWidget::update();
_selectItem = false;
}
}
_changeEnd = false;
_changeStart = false;
}
break;
case Zoom:
if(!_Mousemoved) {
if(e->button() == LeftButton)
zoom(1.4, e->x(), e->y() );
if(e->button() == RightButton)
zoom(0.7, e->x(), e->y() );
if(e->button() == MidButton)
zoomAll();
}
else {
if(_currentMButton == LeftButton) {
QPainter p(this);
QPen pen(DashLine);
pen.setColor(red);
p.setRasterOp(XorROP);
p.setPen( pen );
p.drawRect(_startPoint->x(),
_startPoint->y(),
_endPoint->x()-_startPoint->x(),
_endPoint->y() - _startPoint->y());
double x1 = _startPoint->x();
double y1 = _startPoint->y();
double x2 = _endPoint->x();
double y2 = _endPoint->y();
double sys_width = fabs(x2 - x1);
double mass = (_parent->visibleWidth()/ sys_width);
zoom(mass, (int) (x1+(x2-x1)/2), (int) (y1+(y2-y1)/2) );
}
}
break;
default:
break;
}
_Mousemoved = false;
_currentMButton = 0;
}
void
xQGanttBarViewPort::mouseMoveEvent(QMouseEvent* e)
{
if(fabs((float)(_startPoint->x() - e->x())) < 2 &&
fabs((float)(_startPoint->y() - e->y())) < 2 )
return;
static QPen _dashPen(QColor(255,0,0),DashLine);
static QPen _solidPen(QColor(200,200,200));
_Mousemoved = true;
switch(_mode) {
case Select: {
if(_currentMButton == LeftButton && _currentItem) {
QPainter p(this);
p.setRasterOp(XorROP);
// QPen pen(DashLine);
// pen.setColor(red);
p.setPen( _dashPen );
QString stmp;
stmp.sprintf("%s\n", _currentItem->getText().latin1() );
int pixeldiff = e->x() - _startPoint->x();
_timediff = (int) ((double) pixeldiff / _scaleX + 0.5 );
xQTaskPosition* tpos = _gItemList[_currentItem];
int x = tpos->_screenX; int w = tpos->_screenW;
if(_changeStart && _changeEnd) {
double tmp = (double) _timediff/(double) _snapgrid;
_timediff = ((int) (tmp + sgn(tmp) * 0.5)) * _snapgrid;
stmp += _currentItem->getStart().addSecs(_timediff*60).toString();
stmp += " - ";
stmp += _currentItem->getEnd().addSecs(_timediff*60).toString();
x += (int) (_timediff * _scaleX);
_tmpStartDateTime = _currentItem->getStart().addSecs(_timediff*60);
_tmpEndDateTime = _currentItem->getEnd().addSecs(_timediff*60);
}
else {
if(_changeStart) {
QDateTime movedStart( _currentItem->getStart().addSecs(_timediff*60) );
_tmpStartDateTime.setDate( movedStart.date() );
_tmpStartDateTime.setTime(QTime(0,0,0,0));
double diff = _tmpStartDateTime.secsTo(movedStart)/60;
double tmp = diff/(double) _snapgrid;
_timediff = ((int) (tmp + sgn(tmp) * 0.5)) * _snapgrid;
_tmpStartDateTime = _tmpStartDateTime.addSecs(_timediff*60);
_timediff = _currentItem->getStart().secsTo(_tmpStartDateTime)/60;
stmp += _tmpStartDateTime.toString().latin1();
stmp += " - ";
stmp += _currentItem->getEnd().toString();
x += (int) (_timediff * _scaleX);
w -= (int) (_timediff * _scaleX);
}
if(_changeEnd) {
QDateTime movedEnd( _currentItem->getEnd().addSecs(_timediff*60) );
_tmpEndDateTime.setDate( movedEnd.date() );
_tmpEndDateTime.setTime(QTime(0,0,0,0));
double diff = _tmpEndDateTime.secsTo(movedEnd)/60;
double tmp = diff/(double) _snapgrid;
_timediff = ((int) (tmp + sgn(tmp) * 0.5)) * _snapgrid;
_tmpEndDateTime = _tmpEndDateTime.addSecs(_timediff*60);
_timediff = _currentItem->getEnd().secsTo(_tmpEndDateTime)/60;
stmp += _currentItem->getStart().toString();
stmp += " - ";
stmp += _tmpEndDateTime.toString().latin1();
w += (int) (_timediff * _scaleX);
}
}
_itemInfo->setText( stmp );
_itemInfo->adjustSize();
_itemInfo->move(e->x() + 25, _gItemList.find(_currentItem)->_screenY - 50);
_itemInfo->show();
if(oldx > 0) {
p.fillRect(oldx, _gItemList.find(_currentItem)->_screenY,
oldw, _gItemList.find(_currentItem)->_screenH,
QBrush(QColor(50,50,50), Dense4Pattern));
p.drawRect(oldx, _gItemList.find(_currentItem)->_screenY,
oldw, _gItemList.find(_currentItem)->_screenH);
p.setPen(_solidPen);
if(_changeStart)
p.drawLine(oldx, 0, oldx, height());
if(oldw > 2)
if(_changeEnd)
p.drawLine(oldx + oldw, 0, oldx + oldw, height());
}
p.setPen(_dashPen);
p.fillRect(x, _gItemList.find(_currentItem)->_screenY,
w, _gItemList.find(_currentItem)->_screenH,
QBrush(QColor(50,50,50), Dense4Pattern) );
p.drawRect(x, _gItemList.find(_currentItem)->_screenY,
w, _gItemList.find(_currentItem)->_screenH);
p.setPen(_solidPen);
if(_changeStart)
p.drawLine(x, 0, x, height());
if(w>2)
if(_changeEnd)
p.drawLine(x + w, 0, x + w, height());
oldx = x; oldw = w;
}
else {
static Position _pos = Outside;
KGanttItem* item = NULL;
Position pos = check(&item, e->x(), e->y());
if(_pos != pos) {
_pos = pos;
if(pos == West || pos == East) {
setCursor( splitHCursor );
break;
}
if(pos == North || pos == South) {
setCursor( splitVCursor );
break;
}
if(pos == Center) {
setCursor( upArrowCursor);
break;
}
if(pos == Handle) {
setCursor(pointingHandCursor);
break;
}
setCursor(arrowCursor);
}
}
}
break;
case Zoom: {
if(_currentMButton == LeftButton) {
static QString strpos;
strpos = "";
int s = worldX(_startPoint->x());
QDateTime d1 = _toplevelitem->getStart().addSecs(s*60);
s = worldX(e->x());
QDateTime d2 = _toplevelitem->getStart().addSecs(s*60);
strpos += d1.date().toString();
strpos += " - ";
strpos += d2.date().toString();
emit message(strpos);
QPainter p(this);
QPen pen(DashLine);
pen.setColor(red);
p.setRasterOp(XorROP);
p.setPen( pen );
p.drawRect(_startPoint->x(),
_startPoint->y(),
_endPoint->x()-_startPoint->x(),
_endPoint->y() - _startPoint->y());
QBrush _selectedbrush( QColor(50,50,50), Dense4Pattern );
p.fillRect( _startPoint->x(), _startPoint->y(),
_endPoint->x()-_startPoint->x(), _endPoint->y() - _startPoint->y(),
_selectedbrush );
_endPoint->setX( e->x() );
_endPoint->setY( e->y() );
p.drawRect(_startPoint->x(), _startPoint->y(),
_endPoint->x()-_startPoint->x(), _endPoint->y() - _startPoint->y());
p.fillRect( _startPoint->x(), _startPoint->y(),
_endPoint->x()-_startPoint->x(), _endPoint->y() - _startPoint->y(),
_selectedbrush );
}
}
break;
case Move: {
emit scroll(_startPoint->x() - e->x(), _startPoint->y() - e->y() );
}
break;
default :
break;
}
}
void
xQGanttBarViewPort::keyPressEvent(QKeyEvent* e)
{
printf("xQGanttBarViewPort::keyPressEvent() key = %d \n", e->key() );
int dx = 15;
if(e->state() == ControlButton)
dx *= 10;
switch(e->key()) {
case Key_Left:
emit scroll(-dx,0);
break;
case Key_Right:
emit scroll(dx,0);
break;
case Key_Up:
emit scroll(0,-dx);
break;
case Key_Down:
emit scroll(0, dx);
break;
case 43: // +
zoom(1.4);
break;
case 45: // -
zoom(0.7);
break;
case 4103: // del
deleteSelectedItems();
break;
case 4102: // einfg
insertIntoSelectedItem();
break;
case 4119: // bild v
emit scroll(0, dx*15);
break;
case 4118: // bild ^
emit scroll(0,-dx*15);
break;
}
}
void
xQGanttBarViewPort::paintEvent(QPaintEvent * e)
/////////////////////////////////////////////////
{
update(e->rect().left(), e->rect().top(),
e->rect().right(), e->rect().bottom() );
}
<|endoftext|> |
<commit_before>/*
* Copyright 2018-present Facebook, 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 <folly/experimental/JemallocHugePageAllocator.h>
#include <folly/portability/String.h>
#include <glog/logging.h>
#include <sstream>
#if defined(MADV_HUGEPAGE) && defined(FOLLY_USE_JEMALLOC) && !FOLLY_SANITIZE
#include <jemalloc/jemalloc.h>
#if (JEMALLOC_VERSION_MAJOR >= 5)
#define FOLLY_JEMALLOC_HUGE_PAGE_ALLOCATOR_SUPPORTED 1
bool folly::JemallocHugePageAllocator::hugePagesSupported{true};
#endif
#endif // MADV_HUGEPAGE && defined(FOLLY_USE_JEMALLOC) && !FOLLY_SANITIZE
#ifndef FOLLY_JEMALLOC_HUGE_PAGE_ALLOCATOR_SUPPORTED
// Some mocks when jemalloc.h is not included or version too old
// or when the system does not support the MADV_HUGEPAGE madvise flag
#undef MALLOCX_ARENA
#undef MALLOCX_TCACHE_NONE
#undef MADV_HUGEPAGE
#define MALLOCX_ARENA(x) 0
#define MALLOCX_TCACHE_NONE 0
#define MADV_HUGEPAGE 0
#if !defined(JEMALLOC_VERSION_MAJOR) || (JEMALLOC_VERSION_MAJOR < 5)
typedef struct extent_hooks_s extent_hooks_t;
typedef void*(extent_alloc_t)(
extent_hooks_t*,
void*,
size_t,
size_t,
bool*,
bool*,
unsigned);
struct extent_hooks_s {
extent_alloc_t* alloc;
};
#endif // JEMALLOC_VERSION_MAJOR
bool folly::JemallocHugePageAllocator::hugePagesSupported{false};
#endif // FOLLY_JEMALLOC_HUGE_PAGE_ALLOCATOR_SUPPORTED
namespace folly {
namespace {
static void print_error(int err, const char* msg) {
int cur_errno = std::exchange(errno, err);
PLOG(ERROR) << msg;
errno = cur_errno;
}
class HugePageArena {
public:
int init(int nr_pages, const JemallocHugePageAllocator::Options& options);
void* reserve(size_t size, size_t alignment);
bool addressInArena(void* address) {
uintptr_t addr = reinterpret_cast<uintptr_t>(address);
return addr >= start_ && addr < end_;
}
size_t freeSpace() {
return end_ - freePtr_;
}
unsigned arenaIndex() {
return arenaIndex_;
}
private:
static void* allocHook(
extent_hooks_t* extent,
void* new_addr,
size_t size,
size_t alignment,
bool* zero,
bool* commit,
unsigned arena_ind);
uintptr_t start_{0};
uintptr_t end_{0};
uintptr_t freePtr_{0};
extent_alloc_t* originalAlloc_{nullptr};
extent_hooks_t extentHooks_;
unsigned arenaIndex_{0};
};
constexpr size_t kHugePageSize = 2 * 1024 * 1024;
// Singleton arena instance
static HugePageArena arena;
template <typename T, typename U>
static inline T align_up(T val, U alignment) {
DCHECK((alignment & (alignment - 1)) == 0);
return (val + alignment - 1) & ~(alignment - 1);
}
// mmap enough memory to hold the aligned huge pages, then use madvise
// to get huge pages. Note that this is only a hint and is not guaranteed
// to be honoured. Check /proc/<pid>/smaps to verify!
static uintptr_t map_pages(size_t nr_pages) {
// Initial mmapped area is large enough to contain the aligned huge pages
size_t alloc_size = nr_pages * kHugePageSize;
void* p = mmap(
nullptr,
alloc_size + kHugePageSize,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if (p == MAP_FAILED) {
return 0;
}
// Aligned start address
uintptr_t first_page = align_up((uintptr_t)p, kHugePageSize);
// Unmap left-over 4k pages
munmap(p, first_page - (uintptr_t)p);
munmap(
(void*)(first_page + alloc_size),
kHugePageSize - (first_page - (uintptr_t)p));
// Tell the kernel to please give us huge pages for this range
madvise((void*)first_page, kHugePageSize * nr_pages, MADV_HUGEPAGE);
LOG(INFO) << nr_pages << " huge pages at " << (void*)first_page;
return first_page;
}
void* HugePageArena::allocHook(
extent_hooks_t* extent,
void* new_addr,
size_t size,
size_t alignment,
bool* zero,
bool* commit,
unsigned arena_ind) {
DCHECK((size & (size - 1)) == 0);
void* res = nullptr;
if (new_addr == nullptr) {
res = arena.reserve(size, alignment);
}
if (res == nullptr) {
LOG_IF(WARNING, new_addr != nullptr) << "Explicit address not supported";
res = arena.originalAlloc_(
extent, new_addr, size, alignment, zero, commit, arena_ind);
} else {
if (*zero) {
bzero(res, size);
}
*commit = true;
}
VLOG(0) << "Extent request of size " << size << " alignment " << alignment
<< " = " << res << " (" << arena.freeSpace() << " bytes free)";
return res;
}
int HugePageArena::init(
int nr_pages,
const JemallocHugePageAllocator::Options& options) {
DCHECK(start_ == 0);
DCHECK(usingJEMalloc());
size_t len = sizeof(arenaIndex_);
if (auto ret = mallctl("arenas.create", &arenaIndex_, &len, nullptr, 0)) {
print_error(ret, "Unable to create arena");
return 0;
}
// Set grow retained limit to stop jemalloc from
// forever increasing the requested size after failed allocations.
// Normally jemalloc asks for maps of increasing size in order to avoid
// hitting the limit of allowed mmaps per process.
// Since this arena is backed by a single mmap and is using huge pages,
// this is not a concern here.
// TODO: Support growth of the huge page arena.
size_t mib[3];
size_t miblen = sizeof(mib) / sizeof(size_t);
std::ostringstream rtl_key;
rtl_key << "arena." << arenaIndex_ << ".retain_grow_limit";
if (auto ret = mallctlnametomib(rtl_key.str().c_str(), mib, &miblen)) {
print_error(ret, "Unable to read growth limit");
return 0;
}
size_t grow_retained_limit = kHugePageSize;
mib[1] = arenaIndex_;
if (auto ret = mallctlbymib(
mib,
miblen,
nullptr,
nullptr,
&grow_retained_limit,
sizeof(grow_retained_limit))) {
print_error(ret, "Unable to set growth limit");
return 0;
}
std::ostringstream hooks_key;
hooks_key << "arena." << arenaIndex_ << ".extent_hooks";
extent_hooks_t* hooks;
len = sizeof(hooks);
// Read the existing hooks
if (auto ret = mallctl(hooks_key.str().c_str(), &hooks, &len, nullptr, 0)) {
print_error(ret, "Unable to get the hooks");
return 0;
}
originalAlloc_ = hooks->alloc;
// Set the custom hook
extentHooks_ = *hooks;
extentHooks_.alloc = &allocHook;
extent_hooks_t* new_hooks = &extentHooks_;
if (auto ret = mallctl(
hooks_key.str().c_str(),
nullptr,
nullptr,
&new_hooks,
sizeof(new_hooks))) {
print_error(ret, "Unable to set the hooks");
return 0;
}
if (options.noDecay) {
// Set decay time to 0, which will cause jemalloc to free memory
// back to kernel immediately.
ssize_t decay_ms = 0;
std::ostringstream dirty_decay_key;
dirty_decay_key << "arena." << arenaIndex_ << ".dirty_decay_ms";
if (auto ret = mallctl(
dirty_decay_key.str().c_str(),
nullptr,
nullptr,
&decay_ms,
sizeof(decay_ms))) {
print_error(ret, "Unable to set decay time");
return 0;
}
}
start_ = freePtr_ = map_pages(nr_pages);
if (start_ == 0) {
return false;
}
end_ = start_ + (nr_pages * kHugePageSize);
return MALLOCX_ARENA(arenaIndex_) | MALLOCX_TCACHE_NONE;
}
void* HugePageArena::reserve(size_t size, size_t alignment) {
VLOG(1) << "Reserve: " << size << " alignemnt " << alignment;
uintptr_t res = align_up(freePtr_, alignment);
uintptr_t newFreePtr = res + size;
if (newFreePtr > end_) {
LOG(WARNING) << "Request of size " << size << " denied: " << freeSpace()
<< " bytes available - not backed by huge pages";
return nullptr;
}
freePtr_ = newFreePtr;
return reinterpret_cast<void*>(res);
}
} // namespace
int JemallocHugePageAllocator::flags_{0};
bool JemallocHugePageAllocator::init(int nr_pages, const Options& options) {
if (!usingJEMalloc()) {
LOG(ERROR) << "Not linked with jemalloc?";
hugePagesSupported = false;
}
if (hugePagesSupported) {
if (flags_ == 0) {
flags_ = arena.init(nr_pages, options);
} else {
LOG(WARNING) << "Already initialized";
}
} else {
LOG(WARNING) << "Huge Page Allocator not supported";
}
return flags_ != 0;
}
size_t JemallocHugePageAllocator::freeSpace() {
return arena.freeSpace();
}
bool JemallocHugePageAllocator::addressInArena(void* address) {
return arena.addressInArena(address);
}
unsigned arenaIndex() {
return arena.arenaIndex();
}
} // namespace folly
<commit_msg>Avoid allocation from the hugepage allocator alloc_hook.<commit_after>/*
* Copyright 2018-present Facebook, 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 <folly/experimental/JemallocHugePageAllocator.h>
#include <folly/portability/String.h>
#include <glog/logging.h>
#include <sstream>
#if defined(MADV_HUGEPAGE) && defined(FOLLY_USE_JEMALLOC) && !FOLLY_SANITIZE
#include <jemalloc/jemalloc.h>
#if (JEMALLOC_VERSION_MAJOR >= 5)
#define FOLLY_JEMALLOC_HUGE_PAGE_ALLOCATOR_SUPPORTED 1
bool folly::JemallocHugePageAllocator::hugePagesSupported{true};
#endif
#endif // MADV_HUGEPAGE && defined(FOLLY_USE_JEMALLOC) && !FOLLY_SANITIZE
#ifndef FOLLY_JEMALLOC_HUGE_PAGE_ALLOCATOR_SUPPORTED
// Some mocks when jemalloc.h is not included or version too old
// or when the system does not support the MADV_HUGEPAGE madvise flag
#undef MALLOCX_ARENA
#undef MALLOCX_TCACHE_NONE
#undef MADV_HUGEPAGE
#define MALLOCX_ARENA(x) 0
#define MALLOCX_TCACHE_NONE 0
#define MADV_HUGEPAGE 0
#if !defined(JEMALLOC_VERSION_MAJOR) || (JEMALLOC_VERSION_MAJOR < 5)
typedef struct extent_hooks_s extent_hooks_t;
typedef void*(extent_alloc_t)(
extent_hooks_t*,
void*,
size_t,
size_t,
bool*,
bool*,
unsigned);
struct extent_hooks_s {
extent_alloc_t* alloc;
};
#endif // JEMALLOC_VERSION_MAJOR
bool folly::JemallocHugePageAllocator::hugePagesSupported{false};
#endif // FOLLY_JEMALLOC_HUGE_PAGE_ALLOCATOR_SUPPORTED
namespace folly {
namespace {
static void print_error(int err, const char* msg) {
int cur_errno = std::exchange(errno, err);
PLOG(ERROR) << msg;
errno = cur_errno;
}
class HugePageArena {
public:
int init(int nr_pages, const JemallocHugePageAllocator::Options& options);
void* reserve(size_t size, size_t alignment);
bool addressInArena(void* address) {
uintptr_t addr = reinterpret_cast<uintptr_t>(address);
return addr >= start_ && addr < end_;
}
size_t freeSpace() {
return end_ - freePtr_;
}
unsigned arenaIndex() {
return arenaIndex_;
}
private:
static void* allocHook(
extent_hooks_t* extent,
void* new_addr,
size_t size,
size_t alignment,
bool* zero,
bool* commit,
unsigned arena_ind);
uintptr_t start_{0};
uintptr_t end_{0};
uintptr_t freePtr_{0};
extent_alloc_t* originalAlloc_{nullptr};
extent_hooks_t extentHooks_;
unsigned arenaIndex_{0};
};
constexpr size_t kHugePageSize = 2 * 1024 * 1024;
// Singleton arena instance
static HugePageArena arena;
template <typename T, typename U>
static inline T align_up(T val, U alignment) {
DCHECK((alignment & (alignment - 1)) == 0);
return (val + alignment - 1) & ~(alignment - 1);
}
// mmap enough memory to hold the aligned huge pages, then use madvise
// to get huge pages. Note that this is only a hint and is not guaranteed
// to be honoured. Check /proc/<pid>/smaps to verify!
static uintptr_t map_pages(size_t nr_pages) {
// Initial mmapped area is large enough to contain the aligned huge pages
size_t alloc_size = nr_pages * kHugePageSize;
void* p = mmap(
nullptr,
alloc_size + kHugePageSize,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if (p == MAP_FAILED) {
return 0;
}
// Aligned start address
uintptr_t first_page = align_up((uintptr_t)p, kHugePageSize);
// Unmap left-over 4k pages
munmap(p, first_page - (uintptr_t)p);
munmap(
(void*)(first_page + alloc_size),
kHugePageSize - (first_page - (uintptr_t)p));
// Tell the kernel to please give us huge pages for this range
madvise((void*)first_page, kHugePageSize * nr_pages, MADV_HUGEPAGE);
LOG(INFO) << nr_pages << " huge pages at " << (void*)first_page;
return first_page;
}
// WARNING WARNING WARNING
// This function is the hook invoked on malloc path for the hugepage allocator.
// This means it should not, itself, call malloc. If any of the following
// happens within this function, it *WILL* cause a DEADLOCK (from the circular
// dependency):
// - any dynamic memory allocation (i.e. calls to malloc)
// - any operations that may lead to dynamic operations, such as logging (e.g.
// LOG, VLOG, LOG_IF) and DCHECK.
// WARNING WARNING WARNING
void* HugePageArena::allocHook(
extent_hooks_t* extent,
void* new_addr,
size_t size,
size_t alignment,
bool* zero,
bool* commit,
unsigned arena_ind) {
assert((size & (size - 1)) == 0);
void* res = nullptr;
if (new_addr == nullptr) {
res = arena.reserve(size, alignment);
}
if (res == nullptr) {
res = arena.originalAlloc_(
extent, new_addr, size, alignment, zero, commit, arena_ind);
} else {
if (*zero) {
bzero(res, size);
}
*commit = true;
}
return res;
}
int HugePageArena::init(
int nr_pages,
const JemallocHugePageAllocator::Options& options) {
DCHECK(start_ == 0);
DCHECK(usingJEMalloc());
size_t len = sizeof(arenaIndex_);
if (auto ret = mallctl("arenas.create", &arenaIndex_, &len, nullptr, 0)) {
print_error(ret, "Unable to create arena");
return 0;
}
// Set grow retained limit to stop jemalloc from
// forever increasing the requested size after failed allocations.
// Normally jemalloc asks for maps of increasing size in order to avoid
// hitting the limit of allowed mmaps per process.
// Since this arena is backed by a single mmap and is using huge pages,
// this is not a concern here.
// TODO: Support growth of the huge page arena.
size_t mib[3];
size_t miblen = sizeof(mib) / sizeof(size_t);
std::ostringstream rtl_key;
rtl_key << "arena." << arenaIndex_ << ".retain_grow_limit";
if (auto ret = mallctlnametomib(rtl_key.str().c_str(), mib, &miblen)) {
print_error(ret, "Unable to read growth limit");
return 0;
}
size_t grow_retained_limit = kHugePageSize;
mib[1] = arenaIndex_;
if (auto ret = mallctlbymib(
mib,
miblen,
nullptr,
nullptr,
&grow_retained_limit,
sizeof(grow_retained_limit))) {
print_error(ret, "Unable to set growth limit");
return 0;
}
std::ostringstream hooks_key;
hooks_key << "arena." << arenaIndex_ << ".extent_hooks";
extent_hooks_t* hooks;
len = sizeof(hooks);
// Read the existing hooks
if (auto ret = mallctl(hooks_key.str().c_str(), &hooks, &len, nullptr, 0)) {
print_error(ret, "Unable to get the hooks");
return 0;
}
originalAlloc_ = hooks->alloc;
// Set the custom hook
extentHooks_ = *hooks;
extentHooks_.alloc = &allocHook;
extent_hooks_t* new_hooks = &extentHooks_;
if (auto ret = mallctl(
hooks_key.str().c_str(),
nullptr,
nullptr,
&new_hooks,
sizeof(new_hooks))) {
print_error(ret, "Unable to set the hooks");
return 0;
}
if (options.noDecay) {
// Set decay time to 0, which will cause jemalloc to free memory
// back to kernel immediately.
ssize_t decay_ms = 0;
std::ostringstream dirty_decay_key;
dirty_decay_key << "arena." << arenaIndex_ << ".dirty_decay_ms";
if (auto ret = mallctl(
dirty_decay_key.str().c_str(),
nullptr,
nullptr,
&decay_ms,
sizeof(decay_ms))) {
print_error(ret, "Unable to set decay time");
return 0;
}
}
start_ = freePtr_ = map_pages(nr_pages);
if (start_ == 0) {
return false;
}
end_ = start_ + (nr_pages * kHugePageSize);
return MALLOCX_ARENA(arenaIndex_) | MALLOCX_TCACHE_NONE;
}
// Warning: Check the comments in HugePageArena::allocHook before making any
// change to this function.
void* HugePageArena::reserve(size_t size, size_t alignment) {
uintptr_t res = align_up(freePtr_, alignment);
uintptr_t newFreePtr = res + size;
if (newFreePtr > end_) {
return nullptr;
}
freePtr_ = newFreePtr;
return reinterpret_cast<void*>(res);
}
} // namespace
int JemallocHugePageAllocator::flags_{0};
bool JemallocHugePageAllocator::init(int nr_pages, const Options& options) {
if (!usingJEMalloc()) {
LOG(ERROR) << "Not linked with jemalloc?";
hugePagesSupported = false;
}
if (hugePagesSupported) {
if (flags_ == 0) {
flags_ = arena.init(nr_pages, options);
} else {
LOG(WARNING) << "Already initialized";
}
} else {
LOG(WARNING) << "Huge Page Allocator not supported";
}
return flags_ != 0;
}
size_t JemallocHugePageAllocator::freeSpace() {
return arena.freeSpace();
}
bool JemallocHugePageAllocator::addressInArena(void* address) {
return arena.addressInArena(address);
}
unsigned arenaIndex() {
return arena.arenaIndex();
}
} // namespace folly
<|endoftext|> |
<commit_before><commit_msg>Resolves: tdf#90256 repair invalid docking positions<commit_after><|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLFloat.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/NumberFormatException.hpp>
#include <xercesc/util/Janitor.hpp>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <float.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ctor/dtor
// ---------------------------------------------------------------------------
XMLFloat::XMLFloat(const XMLCh* const strValue,
MemoryManager* const manager)
:XMLAbstractDoubleFloat(manager)
{
init(strValue);
}
XMLFloat::~XMLFloat()
{
}
void XMLFloat::checkBoundary(char* const strValue)
{
convert(strValue);
if (fDataConverted == false)
{
/**
* float related checking
*/
if (fValue < (-1) * FLT_MAX)
{
fType = NegINF;
fDataConverted = true;
fDataOverflowed = true;
}
else if (fValue > (-1)*FLT_MIN && fValue < 0)
{
fDataConverted = true;
fValue = 0;
}
else if (fValue > 0 && fValue < FLT_MIN )
{
fDataConverted = true;
fValue = 0;
}
else if (fValue > FLT_MAX)
{
fType = PosINF;
fDataConverted = true;
fDataOverflowed = true;
}
}
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(XMLFloat)
XMLFloat::XMLFloat(MemoryManager* const manager)
:XMLAbstractDoubleFloat(manager)
{
}
void XMLFloat::serialize(XSerializeEngine& serEng)
{
XMLAbstractDoubleFloat::serialize(serEng);
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Instead of using the FLT_MIN and FLT_MAX macros, use the XMLSchema definition of minimum and maximum value for a xs:float (XERCESC-1833)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLFloat.hpp>
#include <math.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ctor/dtor
// ---------------------------------------------------------------------------
XMLFloat::XMLFloat(const XMLCh* const strValue,
MemoryManager* const manager)
:XMLAbstractDoubleFloat(manager)
{
init(strValue);
}
XMLFloat::~XMLFloat()
{
}
void XMLFloat::checkBoundary(char* const strValue)
{
convert(strValue);
if (fDataConverted == false)
{
/**
* float related checking
*/
// 3.2.4 The basic value space of float consists of the values m 2^e, where
// m is an integer whose absolute value is less than 2^24,
// and e is an integer between -149 and 104, inclusive
static const double fltMin = pow(2.0,-149);
static const double fltMax = pow(2.0,24) * pow(2.0,104);
if (fValue < (-1) * fltMax)
{
fType = NegINF;
fDataConverted = true;
fDataOverflowed = true;
}
else if (fValue > (-1)*fltMin && fValue < 0)
{
fDataConverted = true;
fValue = 0;
}
else if (fValue > 0 && fValue < fltMin )
{
fDataConverted = true;
fValue = 0;
}
else if (fValue > fltMax)
{
fType = PosINF;
fDataConverted = true;
fDataOverflowed = true;
}
}
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(XMLFloat)
XMLFloat::XMLFloat(MemoryManager* const manager)
:XMLAbstractDoubleFloat(manager)
{
}
void XMLFloat::serialize(XSerializeEngine& serEng)
{
XMLAbstractDoubleFloat::serialize(serEng);
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>#include <QSettings>
#include "QGCSettingsWidget.h"
#include "MainWindow.h"
#include "ui_QGCSettingsWidget.h"
#include "LinkManager.h"
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "GAudioOutput.h"
//, Qt::WindowFlags flags
QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :
QDialog(parent, flags),
mainWindow((MainWindow*)parent),
ui(new Ui::QGCSettingsWidget)
{
ui->setupUi(this);
// Center the window on the screen.
QRect position = frameGeometry();
position.moveCenter(QApplication::desktop()->availableGeometry().center());
move(position.topLeft());
// Add all protocols
QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();
foreach (ProtocolInterface* protocol, protocols) {
MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
if (mavlink) {
MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);
ui->tabWidget->addTab(msettings, "MAVLink");
}
}
this->window()->setWindowTitle(tr("QGroundControl Settings"));
// Settings reset
connect(ui->resetSettingsButton, SIGNAL(clicked()), this, SLOT(resetSettings()));
// Audio preferences
ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());
connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));
connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));
// Reconnect
ui->reconnectCheckBox->setChecked(mainWindow->autoReconnectEnabled());
connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableAutoReconnect(bool)));
// Low power mode
ui->lowPowerCheckBox->setChecked(mainWindow->lowPowerModeEnabled());
connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableLowPowerMode(bool)));
// Dock widget title bars
ui->titleBarCheckBox->setChecked(mainWindow->dockWidgetTitleBarsEnabled());
connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),mainWindow,SLOT(enableDockWidgetTitleBars(bool)));
// Custom mode
ui->customModeComboBox->addItem(tr("Default: Generic MAVLink and serial links"), MainWindow::CUSTOM_MODE_NONE);
ui->customModeComboBox->addItem(tr("Wifi: Generic MAVLink, wifi or serial links"), MainWindow::CUSTOM_MODE_WIFI);
ui->customModeComboBox->addItem(tr("PX4: Optimized for PX4 Autopilot Users"), MainWindow::CUSTOM_MODE_PX4);
ui->customModeComboBox->addItem(tr("APM: Optimized for ArduPilot Users"), MainWindow::CUSTOM_MODE_APM);
ui->customModeComboBox->setCurrentIndex(ui->customModeComboBox->findData(mainWindow->getCustomMode()));
connect(ui->customModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectCustomMode(int)));
// Intialize the style UI to the proper values obtained from the MainWindow.
MainWindow::QGC_MAINWINDOW_STYLE style = mainWindow->getStyle();
ui->styleChooser->setCurrentIndex(style);
if (style == MainWindow::QGC_MAINWINDOW_STYLE_DARK)
{
ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());
}
else
{
ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());
}
// And then connect all the signals for the UI for changing styles.
connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(styleChanged(int)));
connect(ui->styleCustomButton, SIGNAL(clicked()), this, SLOT(selectStylesheet()));
connect(ui->styleDefaultButton, SIGNAL(clicked()), this, SLOT(setDefaultStyle()));
connect(ui->styleSheetFile, SIGNAL(editingFinished()), this, SLOT(lineEditFinished()));
// Close / destroy
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(deleteLater()));
}
QGCSettingsWidget::~QGCSettingsWidget()
{
delete ui;
}
void QGCSettingsWidget::selectStylesheet()
{
// Let user select style sheet. The root directory for the file picker is the user's home directory if they haven't loaded a custom style.
// Otherwise it defaults to the directory of that custom file.
QString findDir;
QString oldStylesheet(ui->styleSheetFile->text());
QFile styleSheet(oldStylesheet);
if (styleSheet.exists() && oldStylesheet[0] != ':')
{
findDir = styleSheet.fileName();
}
else
{
findDir = QDir::homePath();
}
// Prompt the user to select a new style sheet. Do nothing if they cancel.
QString newStyleFileName = QFileDialog::getOpenFileName(this, tr("Specify stylesheet"), findDir, tr("CSS Stylesheet (*.css);;"));
if (newStyleFileName.isNull()) {
return;
}
// Load the new style sheet if a valid one was selected, notifying the user
// of an error if necessary.
QFile newStyleFile(newStyleFileName);
if (!newStyleFile.exists() || !updateStyle(newStyleFileName))
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Information);
msgBox.setText(tr("QGroundControl did not load a new style"));
msgBox.setInformativeText(tr("Stylesheet file %1 was not readable").arg(newStyleFileName));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
}
// And update the UI as needed.
else
{
ui->styleSheetFile->setText(newStyleFileName);
}
}
bool QGCSettingsWidget::updateStyle(QString style)
{
switch (ui->styleChooser->currentIndex())
{
case 0:
return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, style);
case 1:
return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, style);
default:
return false;
}
}
void QGCSettingsWidget::lineEditFinished()
{
QString newStyleFileName(ui->styleSheetFile->text());
QFile newStyleFile(newStyleFileName);
if (!newStyleFile.exists() || !updateStyle(newStyleFileName))
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Information);
msgBox.setText(tr("QGroundControl did not load a new style"));
msgBox.setInformativeText(tr("Stylesheet file %1 was not readable").arg(newStyleFileName));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
}
}
void QGCSettingsWidget::styleChanged(int index)
{
if (index == 1)
{
ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, mainWindow->getLightStyleSheet());
}
else
{
ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, mainWindow->getDarkStyleSheet());
}
}
void QGCSettingsWidget::setDefaultStyle()
{
if (ui->styleChooser->currentIndex() == 1)
{
ui->styleSheetFile->setText(MainWindow::defaultLightStyle);
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, MainWindow::defaultLightStyle);
}
else
{
ui->styleSheetFile->setText(MainWindow::defaultDarkStyle);
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, MainWindow::defaultDarkStyle);
}
}
void QGCSettingsWidget::selectCustomMode(int mode)
{
MainWindow::instance()->setCustomMode(static_cast<enum MainWindow::CUSTOM_MODE>(ui->customModeComboBox->itemData(mode).toInt()));
MainWindow::instance()->showInfoMessage(tr("Please restart QGroundControl"), tr("The optimization selection was changed. The application needs to be closed and restarted to put all optimizations into effect."));
}
void QGCSettingsWidget::resetSettings()
{
QSettings settings;
settings.sync();
settings.clear();
// Write current application version
settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION);
settings.sync();
}
<commit_msg>Added missing includes to QGCSettingsWidget.<commit_after>#include <QSettings>
#include <QDesktopWidget>
#include "QGCSettingsWidget.h"
#include "MainWindow.h"
#include "ui_QGCSettingsWidget.h"
#include "LinkManager.h"
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "GAudioOutput.h"
//, Qt::WindowFlags flags
QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :
QDialog(parent, flags),
mainWindow((MainWindow*)parent),
ui(new Ui::QGCSettingsWidget)
{
ui->setupUi(this);
// Center the window on the screen.
QRect position = frameGeometry();
position.moveCenter(QApplication::desktop()->availableGeometry().center());
move(position.topLeft());
// Add all protocols
QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();
foreach (ProtocolInterface* protocol, protocols) {
MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
if (mavlink) {
MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);
ui->tabWidget->addTab(msettings, "MAVLink");
}
}
this->window()->setWindowTitle(tr("QGroundControl Settings"));
// Settings reset
connect(ui->resetSettingsButton, SIGNAL(clicked()), this, SLOT(resetSettings()));
// Audio preferences
ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());
connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));
connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));
// Reconnect
ui->reconnectCheckBox->setChecked(mainWindow->autoReconnectEnabled());
connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableAutoReconnect(bool)));
// Low power mode
ui->lowPowerCheckBox->setChecked(mainWindow->lowPowerModeEnabled());
connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableLowPowerMode(bool)));
// Dock widget title bars
ui->titleBarCheckBox->setChecked(mainWindow->dockWidgetTitleBarsEnabled());
connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),mainWindow,SLOT(enableDockWidgetTitleBars(bool)));
// Custom mode
ui->customModeComboBox->addItem(tr("Default: Generic MAVLink and serial links"), MainWindow::CUSTOM_MODE_NONE);
ui->customModeComboBox->addItem(tr("Wifi: Generic MAVLink, wifi or serial links"), MainWindow::CUSTOM_MODE_WIFI);
ui->customModeComboBox->addItem(tr("PX4: Optimized for PX4 Autopilot Users"), MainWindow::CUSTOM_MODE_PX4);
ui->customModeComboBox->addItem(tr("APM: Optimized for ArduPilot Users"), MainWindow::CUSTOM_MODE_APM);
ui->customModeComboBox->setCurrentIndex(ui->customModeComboBox->findData(mainWindow->getCustomMode()));
connect(ui->customModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectCustomMode(int)));
// Intialize the style UI to the proper values obtained from the MainWindow.
MainWindow::QGC_MAINWINDOW_STYLE style = mainWindow->getStyle();
ui->styleChooser->setCurrentIndex(style);
if (style == MainWindow::QGC_MAINWINDOW_STYLE_DARK)
{
ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());
}
else
{
ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());
}
// And then connect all the signals for the UI for changing styles.
connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(styleChanged(int)));
connect(ui->styleCustomButton, SIGNAL(clicked()), this, SLOT(selectStylesheet()));
connect(ui->styleDefaultButton, SIGNAL(clicked()), this, SLOT(setDefaultStyle()));
connect(ui->styleSheetFile, SIGNAL(editingFinished()), this, SLOT(lineEditFinished()));
// Close / destroy
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(deleteLater()));
}
QGCSettingsWidget::~QGCSettingsWidget()
{
delete ui;
}
void QGCSettingsWidget::selectStylesheet()
{
// Let user select style sheet. The root directory for the file picker is the user's home directory if they haven't loaded a custom style.
// Otherwise it defaults to the directory of that custom file.
QString findDir;
QString oldStylesheet(ui->styleSheetFile->text());
QFile styleSheet(oldStylesheet);
if (styleSheet.exists() && oldStylesheet[0] != ':')
{
findDir = styleSheet.fileName();
}
else
{
findDir = QDir::homePath();
}
// Prompt the user to select a new style sheet. Do nothing if they cancel.
QString newStyleFileName = QFileDialog::getOpenFileName(this, tr("Specify stylesheet"), findDir, tr("CSS Stylesheet (*.css);;"));
if (newStyleFileName.isNull()) {
return;
}
// Load the new style sheet if a valid one was selected, notifying the user
// of an error if necessary.
QFile newStyleFile(newStyleFileName);
if (!newStyleFile.exists() || !updateStyle(newStyleFileName))
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Information);
msgBox.setText(tr("QGroundControl did not load a new style"));
msgBox.setInformativeText(tr("Stylesheet file %1 was not readable").arg(newStyleFileName));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
}
// And update the UI as needed.
else
{
ui->styleSheetFile->setText(newStyleFileName);
}
}
bool QGCSettingsWidget::updateStyle(QString style)
{
switch (ui->styleChooser->currentIndex())
{
case 0:
return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, style);
case 1:
return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, style);
default:
return false;
}
}
void QGCSettingsWidget::lineEditFinished()
{
QString newStyleFileName(ui->styleSheetFile->text());
QFile newStyleFile(newStyleFileName);
if (!newStyleFile.exists() || !updateStyle(newStyleFileName))
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Information);
msgBox.setText(tr("QGroundControl did not load a new style"));
msgBox.setInformativeText(tr("Stylesheet file %1 was not readable").arg(newStyleFileName));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
}
}
void QGCSettingsWidget::styleChanged(int index)
{
if (index == 1)
{
ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, mainWindow->getLightStyleSheet());
}
else
{
ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, mainWindow->getDarkStyleSheet());
}
}
void QGCSettingsWidget::setDefaultStyle()
{
if (ui->styleChooser->currentIndex() == 1)
{
ui->styleSheetFile->setText(MainWindow::defaultLightStyle);
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, MainWindow::defaultLightStyle);
}
else
{
ui->styleSheetFile->setText(MainWindow::defaultDarkStyle);
mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, MainWindow::defaultDarkStyle);
}
}
void QGCSettingsWidget::selectCustomMode(int mode)
{
MainWindow::instance()->setCustomMode(static_cast<enum MainWindow::CUSTOM_MODE>(ui->customModeComboBox->itemData(mode).toInt()));
MainWindow::instance()->showInfoMessage(tr("Please restart QGroundControl"), tr("The optimization selection was changed. The application needs to be closed and restarted to put all optimizations into effect."));
}
void QGCSettingsWidget::resetSettings()
{
QSettings settings;
settings.sync();
settings.clear();
// Write current application version
settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION);
settings.sync();
}
<|endoftext|> |
<commit_before>//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include <ossim/util/ossimRemapTool.h>
#include <ossim/init/ossimInit.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimException.h>
#include <ossim/imaging/ossimBandMergeSource.h>
#include <ossim/imaging/ossimHistogramRemapper.h>
#include <ossim/base/ossimMultiResLevelHistogram.h>
#include <ossim/base/ossimMultiBandHistogram.h>
#include <ossim/imaging/ossimImageHistogramSource.h>
#include <iostream>
#include <ossim/imaging/ossimHistogramWriter.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
using namespace std;
const char* ossimRemapTool::DESCRIPTION =
"Performs remap to 8-bit including optional histogram stretch and saves the corresponding external geometry file.";
static const std::string HISTO_STRETCH_KW = "histo_stretch";
ossimRemapTool::ossimRemapTool()
: m_doHistoStretch(true),
m_entry(0)
{
}
ossimRemapTool::~ossimRemapTool()
{
}
void ossimRemapTool::setUsage(ossimArgumentParser& ap)
{
// Add options.
ossimApplicationUsage* au = ap.getApplicationUsage();
ossimString usageString = ap.getApplicationName();
usageString += " remap [options] <input-image> ";
au->setCommandLineUsage(usageString);
// Set the command line options:
au->setDescription(DESCRIPTION);
// Base class has its own:
ossimTool::setUsage(ap);
au->addCommandLineOption("-e, --entry", "<entry> For multi image handlers which entry do you wish to extract. For list of entries use: \"ossim-info -i <your_image>\" ");
au->addCommandLineOption("-n, --no-histo", "Optionally bypass histogram-stretch. ");
au->addCommandLineOption("-o, --output", "Output filename (defaults to <input-image>-remap.<ext>).");
}
bool ossimRemapTool::initialize(ossimArgumentParser& ap)
{
if (!ossimTool::initialize(ap))
return false;
if (m_helpRequested)
return true;
ossimString ts1;
ossimArgumentParser::ossimParameter sp1 (ts1);
if ( ap.read("-e", sp1) || ap.read("--entry", sp1) )
m_entry = ts1.toUInt32();
if ( ap.read("--no-histo") || ap.read("-n"))
m_doHistoStretch = false;
if(ap.read("--output", sp1) || ap.read("-o", sp1))
m_productFilename = ts1;
if ( ap.argc() >= 2 )
{
// Input file is last arg:
m_inputFilename = ap[ap.argc()-1];
cout<<m_inputFilename<<endl;
}
else
{
ossimNotify(ossimNotifyLevel_FATAL)<<"ossimRemapTool::initialize() Input filename must be "
"provided!"<<endl;
ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_FATAL));
return false;
}
if (m_productFilename.empty())
{
m_productFilename = m_inputFilename.fileNoExtension() + "-remap";
m_productFilename.setExtension(m_inputFilename.ext());
}
try
{
initProcessingChain();
}
catch (ossimException& xe)
{
ossimNotify(ossimNotifyLevel_FATAL)<<xe.what()<<endl;
return false;
}
return true;
}
void ossimRemapTool::initProcessingChain()
{
ostringstream errMsg ("ossimRemapTool::initProcessingChain() ERROR: ");
ossimRefPtr<ossimImageHandler> handler =
ossimImageHandlerRegistry::instance()->open(m_inputFilename);
if (!handler)
{
errMsg<<"Could not open input image file at <"<<m_inputFilename<<">.";
throw ossimException(errMsg.str());
}
if (m_entry)
handler->setCurrentEntry(m_entry);
m_procChain->add(handler.get());
m_geom = handler->getImageGeometry();
// Add histogram remapper if requested:
if (m_doHistoStretch)
{
ossimRefPtr<ossimMultiResLevelHistogram> histogram = handler->getImageHistogram();
if (!histogram)
{
// Need to create a histogram:
ossimRefPtr<ossimImageHistogramSource> histoSource = new ossimImageHistogramSource;
ossimRefPtr<ossimHistogramWriter> writer = new ossimHistogramWriter;
histoSource->connectMyInputTo(0, handler.get());
histoSource->enableSource();
writer->connectMyInputTo(0, histoSource.get());
ossimFilename histoFile;
handler->getFilenameWithThisExt("his", histoFile);
writer->setFilename(histoFile);
writer->addListener(&theStdOutProgress);
writer->execute();
histogram = handler->getImageHistogram();
if (!histogram)
{
errMsg<<"Could not create histogram from <"<<histoFile<<">.";
throw ossimException(errMsg.str());
}
ossimRefPtr<ossimHistogramRemapper> histogramRemapper = new ossimHistogramRemapper();
histogramRemapper->setEnableFlag(true);
histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX );
histogramRemapper->setHistogram(histogram);
m_procChain->add(histogramRemapper.get());
}
}
// Add scalar remapper:
ossimRefPtr<ossimScalarRemapper> scalarRemapper = new ossimScalarRemapper();
scalarRemapper->setOutputScalarType(OSSIM_UINT8);
m_procChain->add(scalarRemapper.get());
}
bool ossimRemapTool::execute()
{
m_geom->getBoundingRect(m_aoiViewRect);
// Parent class has service to create writer:
ossimRefPtr<ossimImageFileWriter>writer = newWriter();
m_writer->connectMyInputTo(0, m_procChain.get());
// Add a listener to get percent complete.
m_writer->addListener(&theStdOutProgress);
// Write the file and external geometry:
;
if(!m_writer->execute())
return false;
if (!m_writer->writeExternalGeometryFile())
return false;
ossimNotify(ossimNotifyLevel_INFO)<<"Wrote product image to <"<<m_productFilename<<">"<<endl;
return true;
}
<commit_msg>Working version<commit_after>//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include <ossim/util/ossimRemapTool.h>
#include <ossim/init/ossimInit.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimException.h>
#include <ossim/imaging/ossimBandMergeSource.h>
#include <ossim/imaging/ossimHistogramRemapper.h>
#include <ossim/base/ossimMultiResLevelHistogram.h>
#include <ossim/base/ossimMultiBandHistogram.h>
#include <ossim/imaging/ossimImageHistogramSource.h>
#include <iostream>
#include <ossim/imaging/ossimHistogramWriter.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
using namespace std;
const char* ossimRemapTool::DESCRIPTION =
"Performs remap to 8-bit including optional histogram stretch and saves the corresponding external geometry file.";
ossimRemapTool::ossimRemapTool()
: m_doHistoStretch(true),
m_entry(0)
{
theStdOutProgress.setFlushStreamFlag(true);
}
ossimRemapTool::~ossimRemapTool()
{
}
void ossimRemapTool::setUsage(ossimArgumentParser& ap)
{
// Add options.
ossimApplicationUsage* au = ap.getApplicationUsage();
ossimString usageString = ap.getApplicationName();
usageString += " remap [options] <input-image> [<remap-out-image>]";
au->setCommandLineUsage(usageString);
// Set the command line options:
au->setDescription(DESCRIPTION);
// Base class has its own:
ossimTool::setUsage(ap);
au->addCommandLineOption("-e, --entry", "<entry> For multi image handlers which entry do you wish to extract. For list of entries use: \"ossim-info -i <your_image>\" ");
au->addCommandLineOption("-n, --no-histo", "Optionally bypass histogram-stretch. ");
}
bool ossimRemapTool::initialize(ossimArgumentParser& ap)
{
if (!ossimTool::initialize(ap))
return false;
if (m_helpRequested)
return true;
ossimString ts1;
ossimArgumentParser::ossimParameter sp1 (ts1);
if ( ap.read("-e", sp1) || ap.read("--entry", sp1) )
m_entry = ts1.toUInt32();
if ( ap.read("--no-histo") || ap.read("-n"))
m_doHistoStretch = false;
// Determine input filename:
if ( ap.argc() > 1 )
m_inputFilename = ap[1];
if (!m_inputFilename.isReadable())
{
ossimNotify(ossimNotifyLevel_FATAL)<<"ossimRemapTool::initialize() Input filename <"
<<m_inputFilename<<"> was not specified or is not "
<<"readable. Try again.\n"<<endl;
return false;
}
// Establish output filename:
if ( ap.argc() > 2 )
{
m_productFilename = ap[2];
cout<<m_inputFilename<<endl;
}
if (m_productFilename.empty())
{
m_productFilename = m_inputFilename.fileNoExtension() + "-remap";
m_productFilename.setExtension(m_inputFilename.ext());
}
try
{
initProcessingChain();
}
catch (ossimException& xe)
{
ossimNotify(ossimNotifyLevel_FATAL)<<xe.what()<<endl;
return false;
}
return true;
}
void ossimRemapTool::initProcessingChain()
{
ostringstream errMsg ("ossimRemapTool::initProcessingChain() ERROR: ");
ossimRefPtr<ossimImageHandler> handler =
ossimImageHandlerRegistry::instance()->open(m_inputFilename);
if (!handler)
{
errMsg<<"Could not open input image file at <"<<m_inputFilename<<">.";
throw ossimException(errMsg.str());
}
if (m_entry)
handler->setCurrentEntry(m_entry);
m_procChain->add(handler.get());
m_geom = handler->getImageGeometry();
// Add histogram remapper if requested:
if (m_doHistoStretch)
{
ossimRefPtr<ossimMultiResLevelHistogram> histogram = handler->getImageHistogram();
if (!histogram)
{
// Need to create a histogram:
ossimRefPtr<ossimImageHistogramSource> histoSource = new ossimImageHistogramSource;
ossimRefPtr<ossimHistogramWriter> writer = new ossimHistogramWriter;
histoSource->connectMyInputTo(0, handler.get());
histoSource->enableSource();
writer->connectMyInputTo(0, histoSource.get());
ossimFilename histoFile;
histoFile = handler->getFilenameWithThisExtension(ossimString("his"));
writer->setFilename(histoFile);
writer->addListener(&theStdOutProgress);
writer->execute();
histogram = handler->getImageHistogram();
if (!histogram)
{
errMsg<<"Could not create histogram from <"<<histoFile<<">.";
throw ossimException(errMsg.str());
}
}
// Ready the histogram object in the processing chain:
ossimRefPtr<ossimHistogramRemapper> histogramRemapper = new ossimHistogramRemapper();
histogramRemapper->setEnableFlag(true);
histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX );
histogramRemapper->setHistogram(histogram);
m_procChain->add(histogramRemapper.get());
}
// Add scalar remapper:
ossimRefPtr<ossimScalarRemapper> scalarRemapper = new ossimScalarRemapper();
scalarRemapper->setOutputScalarType(OSSIM_UINT8);
m_procChain->add(scalarRemapper.get());
m_procChain->initialize();
}
bool ossimRemapTool::execute()
{
m_geom->getBoundingRect(m_aoiViewRect);
// Parent class has service to create writer:
m_writer = newWriter();
m_writer->connectMyInputTo(0, m_procChain.get());
// Add a listener to get percent complete.
m_writer->addListener(&theStdOutProgress);
// Write the file and external geometry:
if(!m_writer->execute())
return false;
if (!m_writer->writeExternalGeometryFile())
return false;
ossimNotify(ossimNotifyLevel_INFO)<<"Wrote product image to <"<<m_productFilename<<">"<<endl;
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "..\StdAfx.h"
#include "..\BatchEncoder.h"
#include "Utilities.h"
#include "UnicodeUtf8.h"
#include "Utf8String.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
void DoTheShutdown()
{
if (::IsWindowsXPOrGreater())
{
HANDLE m_hToken;
if (::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &m_hToken))
{
LUID m_Luid;
if (::LookupPrivilegeValue(NULL, _T("SeShutdownPrivilege"), &m_Luid))
{
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = m_Luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
::AdjustTokenPrivileges(m_hToken, FALSE, &tp, 0, NULL, NULL);
}
::CloseHandle(m_hToken);
}
}
::ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF | EWX_FORCEIFHUNG, 0);
::PostQuitMessage(0);
}
void LaunchAndWait(LPCTSTR file, LPCTSTR params, BOOL bWait)
{
SHELLEXECUTEINFO sei;
::ZeroMemory(&sei, sizeof(SHELLEXECUTEINFO));
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
// sei.lpVerb is uninitialised, so that default action will be taken
sei.nShow = SW_SHOWNORMAL;
sei.lpFile = file;
sei.lpParameters = params;
// check the return value
::ShellExecuteEx(&sei);
// wait till the child terminates
if (bWait == TRUE)
::WaitForSingleObject(sei.hProcess, INFINITE);
::CloseHandle(sei.hProcess);
}
void SetComboBoxHeight(HWND hDlg, int nComboBoxID)
{
// limit the size default to: 8 to 30, system default is 30
const int nSizeLimit = 15;
HWND hComboxBox = ::GetDlgItem(hDlg, nComboBoxID);
// NOTE: on WinXP standard method does not work
// but we are using CB_SETMINVISIBLE message
// version >= 5.1 (Windows XP or later windows)
if (::IsWindowsXPOrGreater())
{
// well we using right now 5.0 NT define, but we need this for XP
#if !defined(CBM_FIRST) | !defined(CB_SETMINVISIBLE)
#define CBM_FIRST 0x1700
#define CB_SETMINVISIBLE (CBM_FIRST + 1)
#endif
::SendMessage(hComboxBox, CB_SETMINVISIBLE, (WPARAM)nSizeLimit, 0);
return;
}
int nCount = (int) ::SendDlgItemMessage(hDlg, nComboBoxID, CB_GETCOUNT, 0, 0);
int nHeight = (int) ::SendDlgItemMessage(hDlg, nComboBoxID, CB_GETITEMHEIGHT, 0, 0);
RECT rcCB;
int nCY = 0;
::GetWindowRect(hComboxBox, &rcCB);
if (nCount > nSizeLimit)
nCY = nHeight * nSizeLimit;
else
nCY = 2 * nHeight * nCount;
::SetWindowPos(hComboxBox,
NULL,
0,
0,
rcCB.right - rcCB.left,
nCY,
SWP_NOZORDER | SWP_NOMOVE | SWP_SHOWWINDOW);
}
static UINT MyGetFileName(LPCTSTR lpszPathName, LPTSTR lpszTitle, UINT nMax)
{
LPTSTR lpszTemp = ::PathFindFileName(lpszPathName);
if (lpszTitle == NULL)
return lstrlen(lpszTemp) + 1;
lstrcpyn(lpszTitle, lpszTemp, nMax);
return(0);
}
CString GetFileName(CString szFilePath)
{
CString strResult;
MyGetFileName(szFilePath, strResult.GetBuffer(_MAX_FNAME), _MAX_FNAME);
strResult.ReleaseBuffer();
return strResult;
}
CString GetExeFilePath()
{
TCHAR szExeFilePath[MAX_PATH + 1] = _T("");
DWORD dwRet = ::GetModuleFileName(::GetModuleHandle(NULL), szExeFilePath, MAX_PATH);
if (dwRet > 0)
{
CString szTempBuff1;
CString szTempBuff2;
szTempBuff1.Format(_T("%s"), szExeFilePath);
szTempBuff2 = ::GetFileName(szTempBuff1);
szTempBuff1.TrimRight(szTempBuff2);
return szTempBuff1;
}
return NULL;
}
void UpdatePath()
{
::SetCurrentDirectory(::GetExeFilePath());
}
CString GetConfigString(const char *pszUtf8)
{
CString szBuff;
if (pszUtf8 == NULL)
{
szBuff = _T("");
return szBuff;
}
if (strlen(pszUtf8) == 0)
{
szBuff = _T("");
return szBuff;
}
#ifdef _UNICODE
// UTF-8 to UNICODE
wchar_t *pszUnicode;
pszUnicode = MakeUnicodeString((unsigned char *)pszUtf8);
szBuff = pszUnicode;
free(pszUnicode);
#else
// UTF-8 to ANSI
char *pszAnsi;
Utf8Decode(pszUtf8, &pszAnsi);
szBuff = pszAnsi;
free(pszAnsi);
#endif
return szBuff;
}
int stoi(CString szData)
{
return _tstoi(szData);
}
BOOL MakeFullPath(CString szPath)
{
if (szPath[szPath.GetLength() - 1] != '\\')
szPath = szPath + _T("\\");
CString szTmpDir = szPath.Left(2);
_tchdir(szTmpDir);
int nStart = 3;
int nEnd = 0;
while (TRUE)
{
nEnd = szPath.Find('\\', nStart);
if (nEnd == -1)
return TRUE;
CString szNextDir = szPath.Mid(nStart, nEnd - nStart);
CString szCurDir = szTmpDir + _T("\\") + szNextDir;
if (_tchdir(szCurDir) != 0)
{
_tchdir(szTmpDir);
if (_tmkdir(szNextDir) != 0)
return FALSE;
}
szTmpDir += _T("\\") + szNextDir;
nStart = nEnd + 1;
}
return FALSE;
}
CString FormatTime(double fTime, int nFormat)
{
CString szTime = _T("");
DWORD dwTime[5] = { 0, 0, 0, 0, 0 }; // DD HH MM SS MS
dwTime[0] = (DWORD)fTime / (24 * 60 * 60); // DD -> [days]
dwTime[1] = ((DWORD)fTime - (dwTime[0] * (24 * 60 * 60))) / (60 * 60); // HH -> [h]
dwTime[2] = ((DWORD)fTime - ((dwTime[0] * (24 * 60 * 60)) + (dwTime[1] * (60 * 60)))) / 60; // MM -> [m]
dwTime[3] = ((DWORD)fTime - ((dwTime[0] * (24 * 60 * 60)) + (dwTime[1] * (60 * 60)) + (dwTime[2] * 60))); // SS -> [s]
dwTime[4] = (DWORD)(((double)fTime - (DWORD)fTime) * (double) 1000.1); // MS -> [ms]
if (nFormat == 0)
{
// display simple time
szTime.Format(_T("%0.3f"), fTime);
}
else if (nFormat == 1)
{
// exclude only days if not used
if (dwTime[0] != 0)
{
szTime.Format(_T("(%02ld:%02ld:%02ld:%02ld.%03ld"),
dwTime[0], dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
else
{
szTime.Format(_T("%02ld:%02ld:%02ld.%03ld"),
dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
}
else if (nFormat == 2)
{
// exclude unused values from time display
if (dwTime[0] != 0)
{
szTime.Format(_T("(%02ld:%02ld:%02ld:%02ld.%03ld"),
dwTime[0], dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
else if ((dwTime[0] == 0) && (dwTime[1] != 0))
{
szTime.Format(_T("%02ld:%02ld:%02ld.%03ld"),
dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
else if ((dwTime[0] == 0) && (dwTime[1] == 0) && (dwTime[2] != 0))
{
szTime.Format(_T("%02ld:%02ld.%03ld"),
dwTime[2], dwTime[3], dwTime[4]);
}
else if ((dwTime[0] == 0) && (dwTime[1] == 0) && (dwTime[2] == 0) && (dwTime[3] != 0))
{
szTime.Format(_T("%02ld.%03ld"),
dwTime[3], dwTime[4]);
}
else
{
szTime.Format(_T("%03ld"),
dwTime[4]);
}
}
else if (nFormat == 3)
{
// exclude days if not used and doąt show milliseconds
if (dwTime[0] != 0)
{
szTime.Format(_T("(%02ld:%02ld:%02ld:%02ld"),
dwTime[0], dwTime[1], dwTime[2], dwTime[3]);
}
else
{
szTime.Format(_T("%02ld:%02ld:%02ld"),
dwTime[1], dwTime[2], dwTime[3]);
}
}
return szTime;
}
void GetFullPathName(CString &szFilePath)
{
TCHAR szFullPath[MAX_PATH + 2] = _T("");
LPTSTR pszFilePos = NULL;
::GetFullPathName(szFilePath, MAX_PATH + 1, szFullPath, &pszFilePos);
szFilePath = szFullPath;
}
<commit_msg>Update Utilities.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\BatchEncoder.h"
#include "Utilities.h"
#include "UnicodeUtf8.h"
#include "Utf8String.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
void DoTheShutdown()
{
if (::IsWindowsXPOrGreater())
{
HANDLE m_hToken;
if (::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &m_hToken))
{
LUID m_Luid;
if (::LookupPrivilegeValue(NULL, _T("SeShutdownPrivilege"), &m_Luid))
{
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = m_Luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
::AdjustTokenPrivileges(m_hToken, FALSE, &tp, 0, NULL, NULL);
}
::CloseHandle(m_hToken);
}
}
::ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF | EWX_FORCEIFHUNG, 0);
::PostQuitMessage(0);
}
void LaunchAndWait(LPCTSTR file, LPCTSTR params, BOOL bWait)
{
SHELLEXECUTEINFO sei;
::ZeroMemory(&sei, sizeof(SHELLEXECUTEINFO));
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
// sei.lpVerb is uninitialised, so that default action will be taken
sei.nShow = SW_SHOWNORMAL;
sei.lpFile = file;
sei.lpParameters = params;
// check the return value
::ShellExecuteEx(&sei);
// wait till the child terminates
if (bWait == TRUE)
::WaitForSingleObject(sei.hProcess, INFINITE);
::CloseHandle(sei.hProcess);
}
void SetComboBoxHeight(HWND hDlg, int nComboBoxID)
{
// limit the size default to: 8 to 30, system default is 30
const int nSizeLimit = 15;
HWND hComboxBox = ::GetDlgItem(hDlg, nComboBoxID);
// NOTE: on WinXP standard method does not work
// but we are using CB_SETMINVISIBLE message
// version >= 5.1 (Windows XP or later windows)
if (::IsWindowsXPOrGreater())
{
// well we using right now 5.0 NT define, but we need this for XP
#if !defined(CBM_FIRST) | !defined(CB_SETMINVISIBLE)
#define CBM_FIRST 0x1700
#define CB_SETMINVISIBLE (CBM_FIRST + 1)
#endif
::SendMessage(hComboxBox, CB_SETMINVISIBLE, (WPARAM)nSizeLimit, 0);
return;
}
int nCount = (int) ::SendDlgItemMessage(hDlg, nComboBoxID, CB_GETCOUNT, 0, 0);
int nHeight = (int) ::SendDlgItemMessage(hDlg, nComboBoxID, CB_GETITEMHEIGHT, 0, 0);
RECT rcCB;
int nCY = 0;
::GetWindowRect(hComboxBox, &rcCB);
if (nCount > nSizeLimit)
nCY = nHeight * nSizeLimit;
else
nCY = 2 * nHeight * nCount;
::SetWindowPos(hComboxBox,
NULL,
0,
0,
rcCB.right - rcCB.left,
nCY,
SWP_NOZORDER | SWP_NOMOVE | SWP_SHOWWINDOW);
}
static UINT MyGetFileName(LPCTSTR lpszPathName, LPTSTR lpszTitle, UINT nMax)
{
LPTSTR lpszTemp = ::PathFindFileName(lpszPathName);
if (lpszTitle == NULL)
return lstrlen(lpszTemp) + 1;
lstrcpyn(lpszTitle, lpszTemp, nMax);
return(0);
}
CString GetFileName(CString szFilePath)
{
CString strResult;
MyGetFileName(szFilePath, strResult.GetBuffer(_MAX_FNAME), _MAX_FNAME);
strResult.ReleaseBuffer();
return strResult;
}
CString GetExeFilePath()
{
TCHAR szExeFilePath[MAX_PATH + 1] = _T("");
DWORD dwRet = ::GetModuleFileName(::GetModuleHandle(NULL), szExeFilePath, MAX_PATH);
if (dwRet > 0)
{
CString szTempBuff1;
CString szTempBuff2;
szTempBuff1.Format(_T("%s"), szExeFilePath);
szTempBuff2 = ::GetFileName(szTempBuff1);
szTempBuff1.TrimRight(szTempBuff2);
return szTempBuff1;
}
return NULL;
}
void UpdatePath()
{
::SetCurrentDirectory(::GetExeFilePath());
}
CString GetConfigString(const char *pszUtf8)
{
CString szBuff;
if (pszUtf8 == NULL)
{
szBuff = _T("");
return szBuff;
}
if (strlen(pszUtf8) == 0)
{
szBuff = _T("");
return szBuff;
}
#ifdef _UNICODE
// UTF-8 to UNICODE
wchar_t *pszUnicode;
pszUnicode = MakeUnicodeString((unsigned char *)pszUtf8);
szBuff = pszUnicode;
free(pszUnicode);
#else
// UTF-8 to ANSI
char *pszAnsi;
Utf8Decode(pszUtf8, &pszAnsi);
szBuff = pszAnsi;
free(pszAnsi);
#endif
return szBuff;
}
int stoi(CString szData)
{
return _tstoi(szData);
}
BOOL MakeFullPath(CString szPath)
{
if (szPath[szPath.GetLength() - 1] != '\\')
szPath = szPath + _T("\\");
CString szTmpDir = szPath.Left(2);
_tchdir(szTmpDir);
int nStart = 3;
int nEnd = 0;
while (TRUE)
{
nEnd = szPath.Find('\\', nStart);
if (nEnd == -1)
return TRUE;
CString szNextDir = szPath.Mid(nStart, nEnd - nStart);
CString szCurDir = szTmpDir + _T("\\") + szNextDir;
if (_tchdir(szCurDir) != 0)
{
_tchdir(szTmpDir);
if (_tmkdir(szNextDir) != 0)
return FALSE;
}
szTmpDir += _T("\\") + szNextDir;
nStart = nEnd + 1;
}
return FALSE;
}
CString FormatTime(double fTime, int nFormat)
{
CString szTime = _T("");
DWORD dwTime[5] = { 0, 0, 0, 0, 0 }; // DD HH MM SS MS
dwTime[0] = (DWORD)fTime / (24 * 60 * 60); // DD -> [days]
dwTime[1] = ((DWORD)fTime - (dwTime[0] * (24 * 60 * 60))) / (60 * 60); // HH -> [h]
dwTime[2] = ((DWORD)fTime - ((dwTime[0] * (24 * 60 * 60)) + (dwTime[1] * (60 * 60)))) / 60; // MM -> [m]
dwTime[3] = ((DWORD)fTime - ((dwTime[0] * (24 * 60 * 60)) + (dwTime[1] * (60 * 60)) + (dwTime[2] * 60))); // SS -> [s]
dwTime[4] = (DWORD)(((double)fTime - (DWORD)fTime) * (double) 1000.1); // MS -> [ms]
if (nFormat == 0)
{
// display simple time
szTime.Format(_T("%0.3f"), fTime);
}
else if (nFormat == 1)
{
// exclude only days if not used
if (dwTime[0] != 0)
{
szTime.Format(_T("(%02ld:%02ld:%02ld:%02ld.%03ld"),
dwTime[0], dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
else
{
szTime.Format(_T("%02ld:%02ld:%02ld.%03ld"),
dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
}
else if (nFormat == 2)
{
// exclude unused values from time display
if (dwTime[0] != 0)
{
szTime.Format(_T("(%02ld:%02ld:%02ld:%02ld.%03ld"),
dwTime[0], dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
else if ((dwTime[0] == 0) && (dwTime[1] != 0))
{
szTime.Format(_T("%02ld:%02ld:%02ld.%03ld"),
dwTime[1], dwTime[2], dwTime[3], dwTime[4]);
}
else if ((dwTime[0] == 0) && (dwTime[1] == 0) && (dwTime[2] != 0))
{
szTime.Format(_T("%02ld:%02ld.%03ld"),
dwTime[2], dwTime[3], dwTime[4]);
}
else if ((dwTime[0] == 0) && (dwTime[1] == 0) && (dwTime[2] == 0) && (dwTime[3] != 0))
{
szTime.Format(_T("%02ld.%03ld"),
dwTime[3], dwTime[4]);
}
else
{
szTime.Format(_T("%03ld"),
dwTime[4]);
}
}
else if (nFormat == 3)
{
// exclude days if not used and doąt show milliseconds
if (dwTime[0] != 0)
{
szTime.Format(_T("(%02ld:%02ld:%02ld:%02ld"),
dwTime[0], dwTime[1], dwTime[2], dwTime[3]);
}
else
{
szTime.Format(_T("%02ld:%02ld:%02ld"),
dwTime[1], dwTime[2], dwTime[3]);
}
}
return szTime;
}
void GetFullPathName(CString &szFilePath)
{
TCHAR szFullPath[MAX_PATH + 2] = _T("");
LPTSTR pszFilePos = NULL;
::GetFullPathName(szFilePath, MAX_PATH + 1, szFullPath, &pszFilePos);
szFilePath = szFullPath;
}
<|endoftext|> |
<commit_before>#include <QtPlugin>
#include <QApplication>
#include <QFontDatabase>
#include "fish_annotator/video_annotator/mainwindow.h"
#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
Q_IMPORT_PLUGIN(QICOPlugin)
#endif
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
#if __unix__
QFontDatabase::addApplicationFont(":/fonts/DejaVuSansCondensed.ttf");
#endif
fish_annotator::video_annotator::MainWindow* w =
new fish_annotator::video_annotator::MainWindow();
w->setAttribute(Qt::WA_DeleteOnClose, true);
w->show();
return a.exec();
}
<commit_msg>Import svg plugin in video annotator<commit_after>#include <QtPlugin>
#include <QApplication>
#include <QFontDatabase>
#include "fish_annotator/video_annotator/mainwindow.h"
#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
Q_IMPORT_PLUGIN(QICOPlugin)
Q_IMPORT_PLUGIN(QSvgPlugin)
#endif
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
#if __unix__
QFontDatabase::addApplicationFont(":/fonts/DejaVuSansCondensed.ttf");
#endif
fish_annotator::video_annotator::MainWindow* w =
new fish_annotator::video_annotator::MainWindow();
w->setAttribute(Qt::WA_DeleteOnClose, true);
w->show();
return a.exec();
}
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/main_window.h"
#include "xenia/base/clock.h"
#include "xenia/base/logging.h"
#include "xenia/base/threading.h"
#include "xenia/gpu/graphics_system.h"
#include "xenia/emulator.h"
#include "xenia/profiling.h"
namespace xe {
namespace ui {
const std::wstring kBaseTitle = L"xenia";
MainWindow::MainWindow(Emulator* emulator)
: PlatformWindow(kBaseTitle),
emulator_(emulator),
main_menu_(MenuItem::Type::kNormal) {}
MainWindow::~MainWindow() = default;
void MainWindow::Start() {
xe::threading::Fence fence;
loop_.Post([&]() {
xe::threading::set_name("Win32 Loop");
xe::Profiler::ThreadEnter("Win32 Loop");
if (!Initialize()) {
XEFATAL("Failed to initialize main window");
exit(1);
}
fence.Signal();
});
fence.Wait();
}
bool MainWindow::Initialize() {
if (!PlatformWindow::Initialize()) {
return false;
}
Resize(1280, 720);
UpdateTitle();
on_key_down.AddListener([this](KeyEvent& e) {
bool handled = true;
switch (e.key_code()) {
case 0x73: { // VK_F4
emulator()->graphics_system()->RequestFrameTrace();
break;
}
case 0x74: { // VK_F5
emulator()->graphics_system()->ClearCaches();
break;
}
case 0x6D: { // numpad minus
Clock::set_guest_time_scalar(Clock::guest_time_scalar() / 2.0);
UpdateTitle();
break;
}
case 0x6B: { // numpad plus
Clock::set_guest_time_scalar(Clock::guest_time_scalar() * 2.0);
UpdateTitle();
break;
}
case 0x0D: { // numpad enter
Clock::set_guest_time_scalar(1.0);
UpdateTitle();
break;
}
default: {
handled = false;
break;
}
}
e.set_handled(handled);
});
// Main menu
// FIXME: This code is really messy.
auto file = std::make_unique<PlatformMenu>(MenuItem::Type::kPopup, L"&File");
file->AddChild(std::make_unique<PlatformMenu>(
MenuItem::Type::kString, Commands::IDC_FILE_OPEN, L"&Open"));
main_menu_.AddChild(std::move(file));
auto debug =
std::make_unique<PlatformMenu>(MenuItem::Type::kPopup, L"&Debug");
SetMenu(&main_menu_);
return true;
}
void MainWindow::UpdateTitle() {
std::wstring title(kBaseTitle);
if (Clock::guest_time_scalar() != 1.0) {
title += L" (@";
title += xe::to_wstring(std::to_string(Clock::guest_time_scalar()));
title += L"x)";
}
set_title(title);
}
void MainWindow::OnClose() {
loop_.Quit();
// TODO(benvanik): proper exit.
XELOGI("User-initiated death!");
exit(1);
}
void MainWindow::OnCommand(int id) {}
X_STATUS MainWindow::LaunchPath(std::wstring path) {
X_STATUS result;
// Launch based on file type.
// This is a silly guess based on file extension.
// NOTE: this blocks!
auto file_system_type = emulator_->file_system()->InferType(path);
switch (file_system_type) {
case kernel::fs::FileSystemType::STFS_TITLE:
result = emulator_->LaunchSTFSTitle(path);
break;
case kernel::fs::FileSystemType::XEX_FILE:
result = emulator_->LaunchXexFile(path);
break;
case kernel::fs::FileSystemType::DISC_IMAGE:
result = emulator_->LaunchDiscImage(path);
break;
}
return result;
}
} // namespace ui
} // namespace xe
<commit_msg>Resize main window after attaching the menu<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/main_window.h"
#include "xenia/base/clock.h"
#include "xenia/base/logging.h"
#include "xenia/base/threading.h"
#include "xenia/gpu/graphics_system.h"
#include "xenia/emulator.h"
#include "xenia/profiling.h"
namespace xe {
namespace ui {
const std::wstring kBaseTitle = L"xenia";
MainWindow::MainWindow(Emulator* emulator)
: PlatformWindow(kBaseTitle),
emulator_(emulator),
main_menu_(MenuItem::Type::kNormal) {}
MainWindow::~MainWindow() = default;
void MainWindow::Start() {
xe::threading::Fence fence;
loop_.Post([&]() {
xe::threading::set_name("Win32 Loop");
xe::Profiler::ThreadEnter("Win32 Loop");
if (!Initialize()) {
XEFATAL("Failed to initialize main window");
exit(1);
}
fence.Signal();
});
fence.Wait();
}
bool MainWindow::Initialize() {
if (!PlatformWindow::Initialize()) {
return false;
}
UpdateTitle();
on_key_down.AddListener([this](KeyEvent& e) {
bool handled = true;
switch (e.key_code()) {
case 0x73: { // VK_F4
emulator()->graphics_system()->RequestFrameTrace();
break;
}
case 0x74: { // VK_F5
emulator()->graphics_system()->ClearCaches();
break;
}
case 0x6D: { // numpad minus
Clock::set_guest_time_scalar(Clock::guest_time_scalar() / 2.0);
UpdateTitle();
break;
}
case 0x6B: { // numpad plus
Clock::set_guest_time_scalar(Clock::guest_time_scalar() * 2.0);
UpdateTitle();
break;
}
case 0x0D: { // numpad enter
Clock::set_guest_time_scalar(1.0);
UpdateTitle();
break;
}
default: {
handled = false;
break;
}
}
e.set_handled(handled);
});
// Main menu
// FIXME: This code is really messy.
auto file = std::make_unique<PlatformMenu>(MenuItem::Type::kPopup, L"&File");
file->AddChild(std::make_unique<PlatformMenu>(
MenuItem::Type::kString, Commands::IDC_FILE_OPEN, L"&Open"));
main_menu_.AddChild(std::move(file));
SetMenu(&main_menu_);
Resize(1280, 720);
return true;
}
void MainWindow::UpdateTitle() {
std::wstring title(kBaseTitle);
if (Clock::guest_time_scalar() != 1.0) {
title += L" (@";
title += xe::to_wstring(std::to_string(Clock::guest_time_scalar()));
title += L"x)";
}
set_title(title);
}
void MainWindow::OnClose() {
loop_.Quit();
// TODO(benvanik): proper exit.
XELOGI("User-initiated death!");
exit(1);
}
void MainWindow::OnCommand(int id) {}
X_STATUS MainWindow::LaunchPath(std::wstring path) {
X_STATUS result;
// Launch based on file type.
// This is a silly guess based on file extension.
// NOTE: this blocks!
auto file_system_type = emulator_->file_system()->InferType(path);
switch (file_system_type) {
case kernel::fs::FileSystemType::STFS_TITLE:
result = emulator_->LaunchSTFSTitle(path);
break;
case kernel::fs::FileSystemType::XEX_FILE:
result = emulator_->LaunchXexFile(path);
break;
case kernel::fs::FileSystemType::DISC_IMAGE:
result = emulator_->LaunchDiscImage(path);
break;
}
return result;
}
} // namespace ui
} // namespace xe
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012-2014 The SSDB 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 "resp.h"
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <util/strings.h>
int Response::size() const{
return (int)resp.size();
}
void Response::push_back(const std::string &s){
resp.push_back(s);
}
void Response::emplace_back(std::string &&s){
resp.emplace_back(s);
}
void Response::add(int s){
add((int64_t)s);
}
void Response::add(int64_t s){
char buf[22] = {0};
sprintf(buf, "%" PRId64 "", s);
resp.emplace_back(buf);
}
void Response::add(uint64_t s){
char buf[22] = {0};
sprintf(buf, "%" PRIu64 "", s);
resp.emplace_back(buf);
}
void Response::add(double s){
// char buf[30];
// snprintf(buf, sizeof(buf), "%f", s);
//
std::ostringstream strs;
strs << std::setprecision(64) << s;
std::string str = strs.str();
// std::string str = std::to_string(s);
resp.push_back(str);
}
void Response::add(long double s){
resp.push_back(str(s));
}
void Response::add(const std::string &s){
resp.push_back(s);
}
void Response::reply_ok() {
resp.push_back("ok");
}
void Response::reply_errror(const std::string &errmsg) {
resp.push_back("error");
resp.push_back(errmsg);
}
void Response::reply_status(int status){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
}
}
void Response::reply_bool(int status){
if(status == -1){
resp.push_back("error");
}else if(status == 0){
resp.push_back("ok");
resp.push_back("0");
}else{
resp.push_back("ok");
resp.push_back("1");
}
}
void Response::reply_int(int status, uint64_t val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_int(int status, int val){
return reply_int(status, static_cast<int64_t >(val));
}
void Response::reply_int(int status, int64_t val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_long_double(int status, long double val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_double(int status, double val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_get(int status, const std::string *val){
if(status < 0){
resp.push_back("error");
}else if(status == 0){
resp.push_back("not_found");
}else{
resp.push_back("ok");
if(val){
resp.push_back(*val);
}
return;
}
}
void Response::reply_scan_ready() {
resp.clear();
resp.push_back("ok");
resp.push_back("0");
}
void Response::reply_list_ready() {
resp.push_back("ok");
}
void Response::reply_not_found() {
resp.push_back("not_found");
}
<commit_msg>[Performance]move<commit_after>/*
Copyright (c) 2012-2014 The SSDB 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 "resp.h"
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <util/strings.h>
int Response::size() const{
return (int)resp.size();
}
void Response::push_back(const std::string &s){
resp.push_back(s);
}
void Response::emplace_back(std::string &&s){
resp.emplace_back(s);
}
void Response::add(int s){
add((int64_t)s);
}
void Response::add(int64_t s){
char buf[22] = {0};
sprintf(buf, "%" PRId64 "", s);
resp.emplace_back(buf);
}
void Response::add(uint64_t s){
char buf[22] = {0};
sprintf(buf, "%" PRIu64 "", s);
resp.emplace_back(buf);
}
void Response::add(double s){
// char buf[30];
// snprintf(buf, sizeof(buf), "%f", s);
//
std::ostringstream strs;
strs << std::setprecision(64) << s;
std::string str = strs.str();
// std::string str = std::to_string(s);
resp.push_back(str);
}
void Response::add(long double s){
resp.push_back(str(s));
}
void Response::add(const std::string &s){
resp.push_back(s);
}
void Response::reply_ok() {
resp.push_back("ok");
}
void Response::reply_errror(const std::string &errmsg) {
resp.push_back("error");
resp.push_back(errmsg);
}
void Response::reply_status(int status){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
}
}
void Response::reply_bool(int status){
if(status == -1){
resp.push_back("error");
}else if(status == 0){
resp.push_back("ok");
resp.push_back("0");
}else{
resp.push_back("ok");
resp.push_back("1");
}
}
void Response::reply_int(int status, uint64_t val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_int(int status, int val){
return reply_int(status, static_cast<int64_t >(val));
}
void Response::reply_int(int status, int64_t val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_long_double(int status, long double val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_double(int status, double val){
if(status == -1){
resp.push_back("error");
}else{
resp.push_back("ok");
this->add(val);
}
}
void Response::reply_get(int status, const std::string *val){
if(status < 0){
resp.push_back("error");
}else if(status == 0){
resp.push_back("not_found");
}else{
resp.push_back("ok");
if(val){
resp.emplace_back(*val);
}
return;
}
}
void Response::reply_scan_ready() {
resp.clear();
resp.push_back("ok");
resp.push_back("0");
}
void Response::reply_list_ready() {
resp.push_back("ok");
}
void Response::reply_not_found() {
resp.push_back("not_found");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: UnoNamespaceMap.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:14:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_UNONAMESPACEMAP_HXX_
#define _SVX_UNONAMESPACEMAP_HXX_
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
class SfxItemPool;
namespace svx {
SVX_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL NamespaceMap_createInstance( sal_uInt16* pWhichIds, SfxItemPool* pPool );
/** deprecated */
SVX_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL NamespaceMap_createInstance( sal_uInt16* pWhichIds, SfxItemPool* pPool1, SfxItemPool* pPool2 );
}
#endif // _SVX_UNONAMESPACEMAP_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.1256); FILE MERGED 2008/04/01 12:46:17 thb 1.4.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:17:53 rt 1.4.1256.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: UnoNamespaceMap.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVX_UNONAMESPACEMAP_HXX_
#define _SVX_UNONAMESPACEMAP_HXX_
#include <com/sun/star/uno/XInterface.hpp>
#include "svx/svxdllapi.h"
class SfxItemPool;
namespace svx {
SVX_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL NamespaceMap_createInstance( sal_uInt16* pWhichIds, SfxItemPool* pPool );
/** deprecated */
SVX_DLLPUBLIC com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL NamespaceMap_createInstance( sal_uInt16* pWhichIds, SfxItemPool* pPool1, SfxItemPool* pPool2 );
}
#endif // _SVX_UNONAMESPACEMAP_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fmservs.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2004-03-19 12:20:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif
#ifndef _FM_STATIC_HXX_
#include "fmstatic.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
namespace svxform
{
// -----------------------
// service names for compatibility
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_EDIT,"stardiv.one.form.component.Edit"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TEXTFIELD,"stardiv.one.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_LISTBOX,"stardiv.one.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMBOBOX,"stardiv.one.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_RADIOBUTTON,"stardiv.one.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GROUPBOX,"stardiv.one.form.component.GroupBox"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FIXEDTEXT,"stardiv.one.form.component.FixedText"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMMANDBUTTON,"stardiv.one.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CHECKBOX,"stardiv.one.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRID,"stardiv.one.form.component.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRIDCONTROL,"stardiv.one.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGEBUTTON,"stardiv.one.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FILECONTROL,"stardiv.one.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TIMEFIELD,"stardiv.one.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_DATEFIELD,"stardiv.one.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_NUMERICFIELD,"stardiv.one.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CURRENCYFIELD,"stardiv.one.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_PATTERNFIELD,"stardiv.one.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDEN,"stardiv.one.form.component.Hidden");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDENCONTROL,"stardiv.one.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGECONTROL,"stardiv.one.form.component.ImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FORMATTEDFIELD,"stardiv.one.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRID,"stardiv.one.form.control.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRIDCONTROL,"stardiv.one.form.control.GridControl");
// -----------------------
// new (sun) service names
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORM,"com.sun.star.form.component.Form");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TEXTFIELD,"com.sun.star.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_LISTBOX,"com.sun.star.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMBOBOX,"com.sun.star.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_RADIOBUTTON,"com.sun.star.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GROUPBOX,"com.sun.star.form.component.GroupBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FIXEDTEXT,"com.sun.star.form.component.FixedText");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMMANDBUTTON,"com.sun.star.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CHECKBOX,"com.sun.star.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GRIDCONTROL,"com.sun.star.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGEBUTTON,"com.sun.star.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FILECONTROL,"com.sun.star.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TIMEFIELD,"com.sun.star.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_DATEFIELD,"com.sun.star.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_NUMERICFIELD,"com.sun.star.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CURRENCYFIELD,"com.sun.star.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_PATTERNFIELD,"com.sun.star.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_HIDDENCONTROL,"com.sun.star.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGECONTROL,"com.sun.star.form.component.DatabaseImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORMATTEDFIELD,"com.sun.star.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SCROLLBAR, "com.sun.star.form.component.ScrollBar" );
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SPINBUTTON, "com.sun.star.form.component.SpinButton" );
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_CONTROL_GRIDCONTROL,"com.sun.star.form.control.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_NUMBER_FORMATTER,"com.sun.star.util.NumberFormatter");
IMPLEMENT_CONSTASCII_USTRING(FM_FORM_CONTROLLER,"com.sun.star.form.FormController");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_CONNECTION,"com.sun.star.sdb.Connection");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_INTERACTION_HANDLER,"com.sun.star.sdb.InteractionHandler");
} // namespace svxform
#define DECL_SERVICE(ImplName) \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ImplName##_NewInstance_Impl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &) throw( ::com::sun::star::uno::Exception );
#define REGISTER_SERVICE(ImplName, ServiceName) \
sString = (ServiceName); \
xSingleFactory = ::cppu::createSingleFactory(xServiceFactory, \
::rtl::OUString(), ImplName##_NewInstance_Impl, \
::com::sun::star::uno::Sequence< ::rtl::OUString>(&sString, 1)); \
if (xSingleFactory.is()) \
xSet->insert(::com::sun::star::uno::makeAny(xSingleFactory));
// declration of the service creation methods
// ------------------------------------------------------------------------
DECL_SERVICE(FmXGridControl);
DECL_SERVICE(FmXFormController);
namespace svxform
{
// ------------------------------------------------------------------------
void ImplSmartRegisterUnoServices()
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory(::comphelper::getProcessServiceFactory(), ::com::sun::star::uno::UNO_QUERY);
::com::sun::star::uno::Reference< ::com::sun::star::container::XSet > xSet(xServiceFactory, ::com::sun::star::uno::UNO_QUERY);
if (!xSet.is())
return;
::com::sun::star::uno::Sequence< ::rtl::OUString> aServices;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > xSingleFactory;
::rtl::OUString sString;
REGISTER_SERVICE(FmXFormController, FM_FORM_CONTROLLER);
// DBGridControl
// ------------------------------------------------------------------------
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRID); // compatibility
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRIDCONTROL);
REGISTER_SERVICE(FmXGridControl, FM_SUN_CONTROL_GRIDCONTROL);
};
} // namespace svxform
<commit_msg>INTEGRATION: CWS frmcontrols02 (1.10.18); FILE MERGED 2004/01/22 10:34:13 fs 1.10.18.1: #i24411# +FRM_SUN_COMPONENT_NAVIGATIONBAR<commit_after>/*************************************************************************
*
* $RCSfile: fmservs.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2004-04-13 10:58:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif
#ifndef _FM_STATIC_HXX_
#include "fmstatic.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
namespace svxform
{
// -----------------------
// service names for compatibility
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_EDIT,"stardiv.one.form.component.Edit"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TEXTFIELD,"stardiv.one.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_LISTBOX,"stardiv.one.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMBOBOX,"stardiv.one.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_RADIOBUTTON,"stardiv.one.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GROUPBOX,"stardiv.one.form.component.GroupBox"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FIXEDTEXT,"stardiv.one.form.component.FixedText"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_COMMANDBUTTON,"stardiv.one.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CHECKBOX,"stardiv.one.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRID,"stardiv.one.form.component.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_GRIDCONTROL,"stardiv.one.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGEBUTTON,"stardiv.one.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FILECONTROL,"stardiv.one.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_TIMEFIELD,"stardiv.one.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_DATEFIELD,"stardiv.one.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_NUMERICFIELD,"stardiv.one.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_CURRENCYFIELD,"stardiv.one.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_PATTERNFIELD,"stardiv.one.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDEN,"stardiv.one.form.component.Hidden");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_HIDDENCONTROL,"stardiv.one.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_IMAGECONTROL,"stardiv.one.form.component.ImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_COMPONENT_FORMATTEDFIELD,"stardiv.one.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRID,"stardiv.one.form.control.Grid"); // compatibility
IMPLEMENT_CONSTASCII_USTRING(FM_CONTROL_GRIDCONTROL,"stardiv.one.form.control.GridControl");
// -----------------------
// new (sun) service names
// -----------------------
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORM,"com.sun.star.form.component.Form");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TEXTFIELD,"com.sun.star.form.component.TextField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_LISTBOX,"com.sun.star.form.component.ListBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMBOBOX,"com.sun.star.form.component.ComboBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_RADIOBUTTON,"com.sun.star.form.component.RadioButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GROUPBOX,"com.sun.star.form.component.GroupBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FIXEDTEXT,"com.sun.star.form.component.FixedText");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_COMMANDBUTTON,"com.sun.star.form.component.CommandButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CHECKBOX,"com.sun.star.form.component.CheckBox");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_GRIDCONTROL,"com.sun.star.form.component.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGEBUTTON,"com.sun.star.form.component.ImageButton");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FILECONTROL,"com.sun.star.form.component.FileControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_TIMEFIELD,"com.sun.star.form.component.TimeField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_DATEFIELD,"com.sun.star.form.component.DateField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_NUMERICFIELD,"com.sun.star.form.component.NumericField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_CURRENCYFIELD,"com.sun.star.form.component.CurrencyField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_PATTERNFIELD,"com.sun.star.form.component.PatternField");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_HIDDENCONTROL,"com.sun.star.form.component.HiddenControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_IMAGECONTROL,"com.sun.star.form.component.DatabaseImageControl");
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_COMPONENT_FORMATTEDFIELD,"com.sun.star.form.component.FormattedField");
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SCROLLBAR, "com.sun.star.form.component.ScrollBar" );
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_SPINBUTTON, "com.sun.star.form.component.SpinButton" );
IMPLEMENT_CONSTASCII_USTRING( FM_SUN_COMPONENT_NAVIGATIONBAR,"com.sun.star.form.component.NavigationToolBar" );
IMPLEMENT_CONSTASCII_USTRING(FM_SUN_CONTROL_GRIDCONTROL,"com.sun.star.form.control.GridControl");
IMPLEMENT_CONSTASCII_USTRING(FM_NUMBER_FORMATTER,"com.sun.star.util.NumberFormatter");
IMPLEMENT_CONSTASCII_USTRING(FM_FORM_CONTROLLER,"com.sun.star.form.FormController");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_CONNECTION,"com.sun.star.sdb.Connection");
IMPLEMENT_CONSTASCII_USTRING(SRV_SDB_INTERACTION_HANDLER,"com.sun.star.sdb.InteractionHandler");
} // namespace svxform
#define DECL_SERVICE(ImplName) \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ImplName##_NewInstance_Impl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &) throw( ::com::sun::star::uno::Exception );
#define REGISTER_SERVICE(ImplName, ServiceName) \
sString = (ServiceName); \
xSingleFactory = ::cppu::createSingleFactory(xServiceFactory, \
::rtl::OUString(), ImplName##_NewInstance_Impl, \
::com::sun::star::uno::Sequence< ::rtl::OUString>(&sString, 1)); \
if (xSingleFactory.is()) \
xSet->insert(::com::sun::star::uno::makeAny(xSingleFactory));
// declration of the service creation methods
// ------------------------------------------------------------------------
DECL_SERVICE(FmXGridControl);
DECL_SERVICE(FmXFormController);
namespace svxform
{
// ------------------------------------------------------------------------
void ImplSmartRegisterUnoServices()
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory(::comphelper::getProcessServiceFactory(), ::com::sun::star::uno::UNO_QUERY);
::com::sun::star::uno::Reference< ::com::sun::star::container::XSet > xSet(xServiceFactory, ::com::sun::star::uno::UNO_QUERY);
if (!xSet.is())
return;
::com::sun::star::uno::Sequence< ::rtl::OUString> aServices;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > xSingleFactory;
::rtl::OUString sString;
REGISTER_SERVICE(FmXFormController, FM_FORM_CONTROLLER);
// DBGridControl
// ------------------------------------------------------------------------
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRID); // compatibility
REGISTER_SERVICE(FmXGridControl, FM_CONTROL_GRIDCONTROL);
REGISTER_SERVICE(FmXGridControl, FM_SUN_CONTROL_GRIDCONTROL);
};
} // namespace svxform
<|endoftext|> |
<commit_before>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*}}}*/
/* $Id$ */
// INCLUDES/*{{{*/
#include <Exception/Errno.hxx>
#include <Exception/Type.hxx>
/*}}}*/
Exception::Type Exception::errnoToType(int p_errno)
{
// TODO
return General;
}
// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<commit_msg>Wrote Exception::errnoToType().<commit_after>// LICENSE/*{{{*/
/*
sxc - Simple Xmpp Client
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*}}}*/
// INCLUDES/*{{{*/
#include <errno.h>
#include <Exception/Errno.hxx>
#include <Exception/Type.hxx>
/*}}}*/
namespace Exception
{
Type errnoToType(int p_errno)
{
Type result = General;
switch (p_errno) {
case EACCES:
result = AccessDenied;
break;
case EEXIST:
result = FileExists;
break;
case ENOENT:
result = FileMissing;
break;
case ELOOP:
case ENOTDIR:
result = BadPath;
break;
case ENAMETOOLONG:
result = BadFile;
break;
case ENOSPC:
case EROFS:
result = WriteFailed;
break;
// The following ones should not be needed but may be passed as
// parameter and could be handled in future versions:
// case EBADF:
// case EFAULT:
// case ENOMEM:
}
return result;
}
}
// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<|endoftext|> |
<commit_before>//
// Created by Zal on 11/19/16.
//
#include <assert.h>
#include "BinaryMatrix.h"
void BinaryMatrix::BinaryMatrix(int w, int h) {
this->width = w;
this->height = h;
baseSize = sizeof(char);
int n = w*h;
dataLength = (n % baseSize == 0)? n/baseSize : n/baseSize +1;
this->data = new char[dataLength];
}
void BinaryMatrix::~BinaryMatrix() {
delete[] data;
}
void BinaryMatrix::T() {
this->transposed = !this->transposed;
}
BinaryMatrix BinaryMatrix::binMultiply(const BinaryMatrix& other) {
BinaryMatrix res(this->width, this->height);
for(int i = 0; i < this->dataLength; ++i) {
res.data[i] = !(this->data[i] ^ other.data[i]);
}
return res;
}
BinaryMatrix BinaryMatrix::tBinMultiply(const BinaryMatrix& other) {
}
double BinaryMatrix::doubleMultiply(const double& other) {
}
BinaryMatrix BinaryMatrix::operator*(const BinaryMatrix& other ) {
assert(this->width == other.width);
assert(this->height == other.height)
if(this->transposed != other.transposed) {
return this->tBinMultiply(other);
}
else {
return this->binMultiply(other);
}
}
<commit_msg>DataLength should be set in constructor<commit_after>//
// Created by Zal on 11/19/16.
//
#include <assert.h>
#include "BinaryMatrix.h"
void BinaryMatrix::BinaryMatrix(int w, int h) {
this->width = w;
this->height = h;
baseSize = sizeof(char);
int n = w*h;
this->dataLength = (n % baseSize == 0)? n/baseSize : n/baseSize +1;
this->data = new char[dataLength];
}
void BinaryMatrix::~BinaryMatrix() {
delete[] data;
}
void BinaryMatrix::T() {
this->transposed = !this->transposed;
}
BinaryMatrix BinaryMatrix::binMultiply(const BinaryMatrix& other) {
BinaryMatrix res(this->width, this->height);
for(int i = 0; i < this->dataLength; ++i) {
res.data[i] = !(this->data[i] ^ other.data[i]);
}
return res;
}
BinaryMatrix BinaryMatrix::tBinMultiply(const BinaryMatrix& other) {
}
double BinaryMatrix::doubleMultiply(const double& other) {
}
BinaryMatrix BinaryMatrix::operator*(const BinaryMatrix& other ) {
assert(this->width == other.width);
assert(this->height == other.height)
if(this->transposed != other.transposed) {
return this->tBinMultiply(other);
}
else {
return this->binMultiply(other);
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <chrono>
#include <chrono>
#include <type_traits>
#include <cassert>
int main()
{
#if _LIBCPP_STD_VER > 11
using namespace std::literals::chrono_literals;
// Make sure the types are right
static_assert ( std::is_same<decltype( 3h ), std::chrono::hours>::value, "" );
static_assert ( std::is_same<decltype( 3min ), std::chrono::minutes>::value, "" );
static_assert ( std::is_same<decltype( 3s ), std::chrono::seconds>::value, "" );
static_assert ( std::is_same<decltype( 3ms ), std::chrono::milliseconds>::value, "" );
static_assert ( std::is_same<decltype( 3us ), std::chrono::microseconds>::value, "" );
static_assert ( std::is_same<decltype( 3ns ), std::chrono::nanoseconds>::value, "" );
std::chrono::hours h = 4h;
assert ( h == std::chrono::hours(4));
auto h2 = 4.0h;
assert ( h == h2 );
std::chrono::minutes min = 36min;
assert ( min == std::chrono::minutes(36));
auto min2 = 36.0min;
assert ( min == min2 );
std::chrono::seconds s = 24s;
assert ( s == std::chrono::seconds(24));
auto s2 = 24.0s;
assert ( s == s2 );
std::chrono::milliseconds ms = 247ms;
assert ( ms == std::chrono::milliseconds(247));
auto ms2 = 247.0ms;
assert ( ms == ms2 );
std::chrono::microseconds us = 867us;
assert ( us == std::chrono::microseconds(867));
auto us2 = 867.0us;
assert ( us == us2 );
std::chrono::nanoseconds ns = 645ns;
assert ( ns == std::chrono::nanoseconds(645));
auto ns2 = 645.ns;
assert ( ns == ns2 );
#endif
}
<commit_msg>Rename time.duration.literals step 2<commit_after><|endoftext|> |
<commit_before>
#include "SchedulingManagerFactory.h"
#include "TimeWarpEventSetFactory.h"
#include "TimeWarpSimulationManager.h"
#include "SimulationConfiguration.h"
#include "SchedulingManager.h"
#include "DefaultSchedulingManager.h"
#include "TimeWarpMultiSetSchedulingManager.h"
#include <WarpedDebug.h>
/*
#if USE_TIMEWARP
#include "threadedtimewarp/ThreadedTimeWarpSimulationManager.h"
#include "threadedtimewarp/ThreadedSchedulingManager.h"
#endif
*/
#include "ThreadedTimeWarpSimulationManager.h"
#include "ThreadedTimeWarpMultiSetSchedulingManager.h"
using std::cerr;
using std::endl;
SchedulingManagerFactory::SchedulingManagerFactory(){}
SchedulingManagerFactory::~SchedulingManagerFactory(){
// myScheduler will be deleted by the end user - the
// TimeWarpSimulationManager
}
Configurable *
SchedulingManagerFactory::allocate( SimulationConfiguration &configuration,
Configurable *parent ) const {
SchedulingManager *retval = 0;
std::string simulationType = configuration.get_string({"Simulation"}, "Sequential");
if(configuration.schedulerTypeIs( "MULTISET" )){
TimeWarpSimulationManager *mySimulationManager = dynamic_cast<TimeWarpSimulationManager *>( parent );
ASSERT(mySimulationManager!=0);
retval = new TimeWarpMultiSetSchedulingManager( mySimulationManager );
debug::debugout << " a TimeWarpMultiSetSchedulingManager." << endl;
}
else {
dynamic_cast<TimeWarpSimulationManager *>(parent)->shutdown( "Unknown SCHEDULER choice \"" +
configuration.getSchedulerType() + "\"" );
}
#if USE_TIMEWARP
if (simulationType == "ThreadedTimeWarp") {
if (configuration.schedulerTypeIs("MULTISET")) {
ThreadedTimeWarpSimulationManager *mySimulationManager =
dynamic_cast<ThreadedTimeWarpSimulationManager *> (parent);
ASSERT(mySimulationManager!=0);
retval = new ThreadedTimeWarpMultiSetSchedulingManager(mySimulationManager);
debug::debugout << " a Threaded TimeWarpMultiSetSchedulingManager." << endl;
} else {
dynamic_cast<TimeWarpSimulationManager *> (parent)->shutdown(
"Unknown SCHEDULER choice \""
+ configuration.getSchedulerType() + "\"");
}
}
#endif
return retval;
}
const SchedulingManagerFactory *
SchedulingManagerFactory::instance(){
static SchedulingManagerFactory *singleton = new SchedulingManagerFactory();
return singleton;
}
<commit_msg>Removed schedulerTypeIs<commit_after>
#include "SchedulingManagerFactory.h"
#include "TimeWarpEventSetFactory.h"
#include "TimeWarpSimulationManager.h"
#include "SimulationConfiguration.h"
#include "SchedulingManager.h"
#include "DefaultSchedulingManager.h"
#include "TimeWarpMultiSetSchedulingManager.h"
#include <WarpedDebug.h>
/*
#if USE_TIMEWARP
#include "threadedtimewarp/ThreadedTimeWarpSimulationManager.h"
#include "threadedtimewarp/ThreadedSchedulingManager.h"
#endif
*/
#include "ThreadedTimeWarpSimulationManager.h"
#include "ThreadedTimeWarpMultiSetSchedulingManager.h"
using std::cerr;
using std::endl;
SchedulingManagerFactory::SchedulingManagerFactory(){}
SchedulingManagerFactory::~SchedulingManagerFactory(){
// myScheduler will be deleted by the end user - the
// TimeWarpSimulationManager
}
Configurable *
SchedulingManagerFactory::allocate( SimulationConfiguration &configuration,
Configurable *parent ) const {
SchedulingManager *retval = 0;
std::string simulationType = configuration.get_string({"Simulation"}, "Sequential");
std::string schedulerType = configuration.get_string({"TimeWarp", "Scheduler", "Type"},
"Default");
if(schedulerType == "MultiSet"){
TimeWarpSimulationManager *mySimulationManager = dynamic_cast<TimeWarpSimulationManager *>( parent );
ASSERT(mySimulationManager!=0);
retval = new TimeWarpMultiSetSchedulingManager( mySimulationManager );
debug::debugout << " a TimeWarpMultiSetSchedulingManager." << endl;
} else {
dynamic_cast<TimeWarpSimulationManager *>(parent)->shutdown( "Unknown SCHEDULER choice \"" +
configuration.getSchedulerType() + "\"" );
}
#if USE_TIMEWARP
if (simulationType == "ThreadedTimeWarp") {
if (schedulerType == "MultiSet") {
ThreadedTimeWarpSimulationManager *mySimulationManager =
dynamic_cast<ThreadedTimeWarpSimulationManager *> (parent);
ASSERT(mySimulationManager!=0);
retval = new ThreadedTimeWarpMultiSetSchedulingManager(mySimulationManager);
debug::debugout << " a Threaded TimeWarpMultiSetSchedulingManager." << endl;
} else {
dynamic_cast<TimeWarpSimulationManager *> (parent)->shutdown(
"Unknown SCHEDULER choice \""
+ configuration.getSchedulerType() + "\"");
}
}
#endif
return retval;
}
const SchedulingManagerFactory *
SchedulingManagerFactory::instance(){
static SchedulingManagerFactory *singleton = new SchedulingManagerFactory();
return singleton;
}
<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kmailchanges.h"
#include "kolabconfig.h"
#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
static const char* s_folderContentsType[] = {
I18N_NOOP( "Calendar" ),
I18N_NOOP( "Contacts" ),
I18N_NOOP( "Notes" ),
I18N_NOOP( "Tasks" ),
I18N_NOOP( "Journal" ) };
class CreateImapAccount : public KConfigPropagator::Change
{
protected:
CreateImapAccount( const QString& title )
: KConfigPropagator::Change( title )
{
}
void constructUserDomainAndEmail()
{
mDefaultDomain = KolabConfig::self()->server();
mUser = KolabConfig::self()->user();
int pos = mUser.find( "@" );
// with kolab the userid _is_ the full email
if ( pos > 0 ) {
// The user typed in a full email address. Assume it's correct
mEmail = mUser;
const QString h = mUser.mid( pos+1 );
if ( !h.isEmpty() )
// The user did type in a domain on the email address. Use that
mDefaultDomain = h;
}
else
// Construct the email address. And use it for the username also
mUser = mEmail = mUser+"@"+KolabConfig::self()->server();
}
// This sucks as this is a 1:1 copy from KMAccount::encryptStr()
static QString encryptStr(const QString& aStr)
{
QString result;
for (uint i = 0; i < aStr.length(); i++)
result += (aStr[i].unicode() < 0x20) ? aStr[i] :
QChar(0x1001F - aStr[i].unicode());
return result;
}
QString mUser;
QString mEmail;
QString mDefaultDomain;
};
class CreateDisconnectedImapAccount : public CreateImapAccount
{
public:
CreateDisconnectedImapAccount()
: CreateImapAccount( i18n("Create Disconnected IMAP Account for KMail") )
{
}
void apply()
{
constructUserDomainAndEmail();
KConfig c( "kmailrc" );
c.setGroup( "General" );
c.writeEntry( "Default domain", mDefaultDomain );
uint accCnt = c.readNumEntry( "accounts", 0 );
c.writeEntry( "accounts", accCnt+1 );
uint transCnt = c.readNumEntry( "transports", 0 );
c.writeEntry( "transports", transCnt+1 );
c.setGroup( QString("Account %1").arg(accCnt+1) );
int uid = kapp->random();
c.writeEntry( "Folder", uid );
c.writeEntry( "Id", uid );
c.writeEntry( "Type", "cachedimap");
c.writeEntry( "auth", "*");
c.writeEntry( "Name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "login",mUser );
if ( KolabConfig::self()->savePassword() ) {
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "store-passwd", true );
}
c.writeEntry( "port", "993" );
c.writeEntry( "use-ssl", true );
c.writeEntry( "sieve-support", "true" );
c.setGroup( QString("Folder-%1").arg( uid ) );
c.writeEntry( "isOpen", true );
c.setGroup( QString("Transport %1").arg(transCnt+1) );
c.writeEntry( "name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "type", "smtp" );
c.writeEntry( "port", "465" );
c.writeEntry( "encryption", "SSL" );
c.writeEntry( "auth", true );
c.writeEntry( "authtype", "PLAIN" );
c.writeEntry( "user", mEmail );
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "storepass", "true" );
// Write email in "default kcontrol settings", used by IdentityManager
// if it has to create a default identity.
KEMailSettings es;
es.setSetting( KEMailSettings::RealName, KolabConfig::self()->realName() );
es.setSetting( KEMailSettings::EmailAddress, mEmail );
KPIM::IdentityManager identityManager;
if ( !identityManager.allEmails().contains( mEmail ) ) {
// Not sure how to name the identity. First one is "Default", next one "Kolab", but then...
// let's use the server name after that.
QString accountName = i18n( "Kolab" );
const QStringList identities = identityManager.identities();
if ( identities.find( accountName ) != identities.end() ) {
accountName = KolabConfig::self()->server();
int i = 2;
// And if there's already one, number them
while ( identities.find( accountName ) != identities.end() ) {
accountName = KolabConfig::self()->server() + " " + QString::number( i++ );
}
}
KPIM::Identity& identity = identityManager.newFromScratch( accountName );
identity.setFullName( KolabConfig::self()->realName() );
identity.setEmailAddr( mEmail );
identityManager.commit();
}
// This needs to be done here, since it reference just just generated id
c.setGroup( "IMAP Resource" );
c.writeEntry("TheIMAPResourceAccount", uid);
c.writeEntry("TheIMAPResourceFolderParent", QString(".%1.directory/INBOX").arg( uid ));
}
};
class CreateOnlineImapAccount : public CreateImapAccount
{
public:
CreateOnlineImapAccount()
: CreateImapAccount( i18n("Create Online IMAP Account for KMail") )
{
}
void apply()
{
constructUserDomainAndEmail();
KConfig c( "kmailrc" );
c.setGroup( "General" );
uint accCnt = c.readNumEntry( "accounts", 0 );
c.writeEntry( "accounts", accCnt+1 );
c.setGroup( QString("Account %1").arg(accCnt+1) );
int uid = kapp->random();
c.writeEntry( "Folder", uid );
c.writeEntry( "Id", uid );
c.writeEntry( "Type", "imap");
c.writeEntry( "auth", "*");
c.writeEntry( "Name", "Kolab Server Mail" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "login", mUser );
if ( KolabConfig::self()->savePassword() ) {
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "store-passwd", true );
}
c.writeEntry( "port", "993" );
c.writeEntry( "use-ssl", true );
c.writeEntry( "sieve-support", "true" );
// locally unsubscribe the default folders
c.writeEntry( "locally-subscribed-folders", true );
QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/")
.arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) )
.arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) )
.arg( i18n(s_folderContentsType[4]) );
c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders );
c.setGroup( QString("Folder-%1").arg( uid ) );
c.writeEntry( "isOpen", true );
}
};
void createKMailChanges( KConfigPropagator::Change::List& changes )
{
KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoAccept";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoDeclConflict";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyMangleFromToHeaders";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyBodyInvites";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceEnabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceStorageFormat";
c->value = "XML";
changes.append( c );
if ( KolabConfig::self()->useOnlineForNonGroupware() ) {
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "ShowOnlyGroupwareFoldersForGroupwareAccount";
c->value = "true";
changes.append( c );
changes.append( new CreateOnlineImapAccount );
}
changes.append( new CreateDisconnectedImapAccount );
}
<commit_msg>Enable local subscription for dimap accounts with "only show groupware folders" enabled by default.<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kmailchanges.h"
#include "kolabconfig.h"
#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
static const char* s_folderContentsType[] = {
I18N_NOOP( "Calendar" ),
I18N_NOOP( "Contacts" ),
I18N_NOOP( "Notes" ),
I18N_NOOP( "Tasks" ),
I18N_NOOP( "Journal" ) };
class CreateImapAccount : public KConfigPropagator::Change
{
protected:
CreateImapAccount( const QString& title )
: KConfigPropagator::Change( title )
{
}
void constructUserDomainAndEmail()
{
mDefaultDomain = KolabConfig::self()->server();
mUser = KolabConfig::self()->user();
int pos = mUser.find( "@" );
// with kolab the userid _is_ the full email
if ( pos > 0 ) {
// The user typed in a full email address. Assume it's correct
mEmail = mUser;
const QString h = mUser.mid( pos+1 );
if ( !h.isEmpty() )
// The user did type in a domain on the email address. Use that
mDefaultDomain = h;
}
else
// Construct the email address. And use it for the username also
mUser = mEmail = mUser+"@"+KolabConfig::self()->server();
}
// This sucks as this is a 1:1 copy from KMAccount::encryptStr()
static QString encryptStr(const QString& aStr)
{
QString result;
for (uint i = 0; i < aStr.length(); i++)
result += (aStr[i].unicode() < 0x20) ? aStr[i] :
QChar(0x1001F - aStr[i].unicode());
return result;
}
QString mUser;
QString mEmail;
QString mDefaultDomain;
};
class CreateDisconnectedImapAccount : public CreateImapAccount
{
public:
CreateDisconnectedImapAccount()
: CreateImapAccount( i18n("Create Disconnected IMAP Account for KMail") )
{
}
void apply()
{
constructUserDomainAndEmail();
KConfig c( "kmailrc" );
c.setGroup( "General" );
c.writeEntry( "Default domain", mDefaultDomain );
uint accCnt = c.readNumEntry( "accounts", 0 );
c.writeEntry( "accounts", accCnt+1 );
uint transCnt = c.readNumEntry( "transports", 0 );
c.writeEntry( "transports", transCnt+1 );
c.setGroup( QString("Account %1").arg(accCnt+1) );
int uid = kapp->random();
c.writeEntry( "Folder", uid );
c.writeEntry( "Id", uid );
c.writeEntry( "Type", "cachedimap");
c.writeEntry( "auth", "*");
c.writeEntry( "Name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
// in case the user wants to get rid of some groupware folders
if ( KolabConfig::self()->useOnlineForNonGroupware() ) {
c.writeEntry( "locally-subscribed-folders", true );
}
c.writeEntry( "login",mUser );
if ( KolabConfig::self()->savePassword() ) {
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "store-passwd", true );
}
c.writeEntry( "port", "993" );
c.writeEntry( "use-ssl", true );
c.writeEntry( "sieve-support", "true" );
c.setGroup( QString("Folder-%1").arg( uid ) );
c.writeEntry( "isOpen", true );
c.setGroup( QString("Transport %1").arg(transCnt+1) );
c.writeEntry( "name", "Kolab Server" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "type", "smtp" );
c.writeEntry( "port", "465" );
c.writeEntry( "encryption", "SSL" );
c.writeEntry( "auth", true );
c.writeEntry( "authtype", "PLAIN" );
c.writeEntry( "user", mEmail );
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "storepass", "true" );
// Write email in "default kcontrol settings", used by IdentityManager
// if it has to create a default identity.
KEMailSettings es;
es.setSetting( KEMailSettings::RealName, KolabConfig::self()->realName() );
es.setSetting( KEMailSettings::EmailAddress, mEmail );
KPIM::IdentityManager identityManager;
if ( !identityManager.allEmails().contains( mEmail ) ) {
// Not sure how to name the identity. First one is "Default", next one "Kolab", but then...
// let's use the server name after that.
QString accountName = i18n( "Kolab" );
const QStringList identities = identityManager.identities();
if ( identities.find( accountName ) != identities.end() ) {
accountName = KolabConfig::self()->server();
int i = 2;
// And if there's already one, number them
while ( identities.find( accountName ) != identities.end() ) {
accountName = KolabConfig::self()->server() + " " + QString::number( i++ );
}
}
KPIM::Identity& identity = identityManager.newFromScratch( accountName );
identity.setFullName( KolabConfig::self()->realName() );
identity.setEmailAddr( mEmail );
identityManager.commit();
}
// This needs to be done here, since it reference just just generated id
c.setGroup( "IMAP Resource" );
c.writeEntry("TheIMAPResourceAccount", uid);
c.writeEntry("TheIMAPResourceFolderParent", QString(".%1.directory/INBOX").arg( uid ));
}
};
class CreateOnlineImapAccount : public CreateImapAccount
{
public:
CreateOnlineImapAccount()
: CreateImapAccount( i18n("Create Online IMAP Account for KMail") )
{
}
void apply()
{
constructUserDomainAndEmail();
KConfig c( "kmailrc" );
c.setGroup( "General" );
uint accCnt = c.readNumEntry( "accounts", 0 );
c.writeEntry( "accounts", accCnt+1 );
c.setGroup( QString("Account %1").arg(accCnt+1) );
int uid = kapp->random();
c.writeEntry( "Folder", uid );
c.writeEntry( "Id", uid );
c.writeEntry( "Type", "imap");
c.writeEntry( "auth", "*");
c.writeEntry( "Name", "Kolab Server Mail" );
c.writeEntry( "host", KolabConfig::self()->server() );
c.writeEntry( "login", mUser );
if ( KolabConfig::self()->savePassword() ) {
c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
c.writeEntry( "store-passwd", true );
}
c.writeEntry( "port", "993" );
c.writeEntry( "use-ssl", true );
c.writeEntry( "sieve-support", "true" );
// locally unsubscribe the default folders
c.writeEntry( "locally-subscribed-folders", true );
QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/")
.arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) )
.arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) )
.arg( i18n(s_folderContentsType[4]) );
c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders );
c.setGroup( QString("Folder-%1").arg( uid ) );
c.writeEntry( "isOpen", true );
}
};
void createKMailChanges( KConfigPropagator::Change::List& changes )
{
KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoAccept";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "AutoDeclConflict";
c->value = "false";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyMangleFromToHeaders";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "Groupware";
c->name = "LegacyBodyInvites";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "Enabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceEnabled";
c->value = "true";
changes.append( c );
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "TheIMAPResourceStorageFormat";
c->value = "XML";
changes.append( c );
if ( KolabConfig::self()->useOnlineForNonGroupware() ) {
c = new KConfigPropagator::ChangeConfig;
c->file = "kmailrc";
c->group = "IMAP Resource";
c->name = "ShowOnlyGroupwareFoldersForGroupwareAccount";
c->value = "true";
changes.append( c );
changes.append( new CreateOnlineImapAccount );
}
changes.append( new CreateDisconnectedImapAccount );
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __rtkCudaSARTConeBeamReconstructionFilter_cxx
#define __rtkCudaSARTConeBeamReconstructionFilter_cxx
#include "rtkJosephForwardProjectionImageFilter.h"
#include "rtkJosephBackProjectionImageFilter.h"
#include "rtkCudaForwardProjectionImageFilter.h"
#include "rtkCudaBackProjectionImageFilter.h"
#include "rtkCudaSARTConeBeamReconstructionFilter.h"
#include "itkImageFileWriter.h"
namespace rtk
{
CudaSARTConeBeamReconstructionFilter
::CudaSARTConeBeamReconstructionFilter():
m_ExplicitGPUMemoryManagementFlag(false)
{
// Create each filter which are specific for cuda
m_ForwardProjectionFilter = ForwardProjectionFilterType::New();
BackProjectionFilterType::Pointer p = BackProjectionFilterType::New();
this->SetBackProjectionFilter(p.GetPointer());
//Permanent internal connections
m_ForwardProjectionFilter->SetInput( 0, m_ZeroMultiplyFilter->GetOutput() );
m_SubtractFilter->SetInput(1, m_ForwardProjectionFilter->GetOutput() );
}
void
CudaSARTConeBeamReconstructionFilter
::GenerateData()
{
// Init GPU memory
if(!m_ExplicitGPUMemoryManagementFlag);
this->InitDevice();
// Run reconstruction
this->Superclass::GenerateData();
// Transfer result to CPU image
if(!m_ExplicitGPUMemoryManagementFlag);
this->CleanUpDevice();
}
void
CudaSARTConeBeamReconstructionFilter
::InitDevice()
{
//Nothing to do, memory control internally managed
}
void
CudaSARTConeBeamReconstructionFilter
::CleanUpDevice()
{
//Nothing to do, memory control internally managed
}
} // end namespace rtk
#endif // __rtkCudaSARTConeBeamReconstructionFilter_cxx
<commit_msg>Remove erroneous semi-colons<commit_after>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __rtkCudaSARTConeBeamReconstructionFilter_cxx
#define __rtkCudaSARTConeBeamReconstructionFilter_cxx
#include "rtkJosephForwardProjectionImageFilter.h"
#include "rtkJosephBackProjectionImageFilter.h"
#include "rtkCudaForwardProjectionImageFilter.h"
#include "rtkCudaBackProjectionImageFilter.h"
#include "rtkCudaSARTConeBeamReconstructionFilter.h"
#include "itkImageFileWriter.h"
namespace rtk
{
CudaSARTConeBeamReconstructionFilter
::CudaSARTConeBeamReconstructionFilter():
m_ExplicitGPUMemoryManagementFlag(false)
{
// Create each filter which are specific for cuda
m_ForwardProjectionFilter = ForwardProjectionFilterType::New();
BackProjectionFilterType::Pointer p = BackProjectionFilterType::New();
this->SetBackProjectionFilter(p.GetPointer());
//Permanent internal connections
m_ForwardProjectionFilter->SetInput( 0, m_ZeroMultiplyFilter->GetOutput() );
m_SubtractFilter->SetInput(1, m_ForwardProjectionFilter->GetOutput() );
}
void
CudaSARTConeBeamReconstructionFilter
::GenerateData()
{
// Init GPU memory
if(!m_ExplicitGPUMemoryManagementFlag)
this->InitDevice();
// Run reconstruction
this->Superclass::GenerateData();
// Transfer result to CPU image
if(!m_ExplicitGPUMemoryManagementFlag)
this->CleanUpDevice();
}
void
CudaSARTConeBeamReconstructionFilter
::InitDevice()
{
//Nothing to do, memory control internally managed
}
void
CudaSARTConeBeamReconstructionFilter
::CleanUpDevice()
{
//Nothing to do, memory control internally managed
}
} // end namespace rtk
#endif // __rtkCudaSARTConeBeamReconstructionFilter_cxx
<|endoftext|> |
<commit_before>/*
kopeteaddrbookexport.cpp - Kopete Online Status
Logic for exporting data acquired from messaging systems to the
KDE address book
Copyright (c) 2004 by Will Stephenson <lists@stevello.free-online.co.uk>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kabc/phonenumber.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <kdialogbase.h>
#include <kiconloader.h>
#include <klistbox.h>
#include <klocale.h>
#include "kopeteaccount.h"
#include "kopeteglobal.h"
#include "kopetemetacontact.h"
#include "kopetecontact.h"
#include "kopeteaddrbookexport.h"
#include "kopeteaddrbookexportui.h"
KopeteAddressBookExport::KopeteAddressBookExport( QWidget *parent, Kopete::MetaContact *mc ) : QObject( parent )
{
// instantiate dialog and populate widgets
mParent = parent;
mAddressBook = KABC::StdAddressBook::self();
mMetaContact = mc;
}
KopeteAddressBookExport::~KopeteAddressBookExport()
{
}
void KopeteAddressBookExport::initLabels()
{
if ( !mAddressee.isEmpty() )
{
mUI->mLblFirstName->setText( mAddressee.givenNameLabel() );
mUI->mLblLastName->setText( mAddressee.familyNameLabel() );
mUI->mLblEmail->setText( mAddressee.emailLabel() );
mUI->mLblUrl->setText( mAddressee.urlLabel() );
mUI->mLblHomePhone->setText( mAddressee.homePhoneLabel() );
mUI->mLblWorkPhone->setText( mAddressee.businessPhoneLabel() );
mUI->mLblMobilePhone->setText( mAddressee.mobilePhoneLabel() );
}
}
void KopeteAddressBookExport::fetchKABCData()
{
if ( !mAddressee.isEmpty() )
{
mAddrBookIcon = SmallIcon( "kaddressbook" );
// given name
QString given = mAddressee.givenName();
if ( !given.isEmpty() )
mUI->mFirstName->insertItem( mAddrBookIcon, given );
else
mUI->mFirstName->insertItem( mAddrBookIcon, i18n("<Not Set>") );
// family name
QString family = mAddressee.familyName();
if ( !family.isEmpty() )
mUI->mLastName->insertItem( mAddrBookIcon, family );
else
mUI->mLastName->insertItem( mAddrBookIcon, i18n("<Not Set>") );
// url
QString url = mAddressee.url().url();
if ( !url.isEmpty() )
mUI->mUrl->insertItem( mAddrBookIcon, url );
else
mUI->mUrl->insertItem( mAddrBookIcon, i18n("<Not Set>") );
// emails
QStringList emails = mAddressee.emails();
numEmails = emails.count();
for ( QStringList::Iterator it = emails.begin(); it != emails.end(); ++it )
mUI->mEmails->insertItem( mAddrBookIcon, *it );
if ( numEmails == 0 )
{
mUI->mEmails->insertItem( mAddrBookIcon, i18n("<Not Set>") );
numEmails = 1;
}
// phone numbers
fetchPhoneNumbers( mUI->mHomePhones, KABC::PhoneNumber::Home, numHomePhones );
fetchPhoneNumbers( mUI->mWorkPhones, KABC::PhoneNumber::Work, numWorkPhones );
fetchPhoneNumbers( mUI->mMobilePhones, KABC::PhoneNumber::Cell, numMobilePhones );
}
}
void KopeteAddressBookExport::fetchPhoneNumbers( KListBox * listBox, int type, uint& counter )
{
KABC::PhoneNumber::List phones = mAddressee.phoneNumbers( type );
counter = phones.count();
KABC::PhoneNumber::List::Iterator it;
for ( it = phones.begin(); it != phones.end(); ++it )
listBox->insertItem( mAddrBookIcon, (*it).number() );
if ( counter == 0 )
{
listBox->insertItem( mAddrBookIcon, i18n("<Not Set>") );
counter = 1;
}
}
void KopeteAddressBookExport::fetchIMData()
{
QPtrList<Kopete::Contact> contacts = mMetaContact->contacts();
QPtrListIterator<Kopete::Contact> cit( contacts );
for( ; cit.current(); ++cit )
{
// for each contact, get the property content
Kopete::Contact* c = cit.current();
QPixmap contactIcon = c->account()->accountIcon( 16 );
// given name
populateIM( c, contactIcon, mUI->mFirstName, Kopete::Global::Properties::self()->firstName() );
// family name
populateIM( c, contactIcon, mUI->mLastName, Kopete::Global::Properties::self()->lastName() );
// url
// TODO: make URL/homepage a global template, currently only in IRC channel contact
// emails
populateIM( c, contactIcon, mUI->mEmails, Kopete::Global::Properties::self()->emailAddress() );
// home phone
populateIM( c, contactIcon, mUI->mHomePhones, Kopete::Global::Properties::self()->privatePhone() );
// work phone
populateIM( c, contactIcon, mUI->mWorkPhones, Kopete::Global::Properties::self()->workPhone() );
// mobile phone
populateIM( c, contactIcon, mUI->mMobilePhones, Kopete::Global::Properties::self()->privateMobilePhone() );
}
}
void KopeteAddressBookExport::populateIM( const Kopete::Contact *contact, const QPixmap &icon, QComboBox *combo, const Kopete::ContactPropertyTmpl &property )
{
Kopete::ContactProperty prop = contact->property( property );
if ( !prop.isNull() )
{
combo->insertItem( icon, prop.value().toString() );
}
}
void KopeteAddressBookExport::populateIM( const Kopete::Contact *contact, const QPixmap &icon, KListBox *listBox, const Kopete::ContactPropertyTmpl &property )
{
Kopete::ContactProperty prop = contact->property( property );
if ( !prop.isNull() )
{
listBox->insertItem( icon, prop.value().toString() );
}
}
int KopeteAddressBookExport::showDialog()
{
mAddressee = mAddressBook->findByUid( mMetaContact->metaContactId() );
if ( !mAddressee.isEmpty() )
{
numEmails = 0;
numHomePhones = 0;
numWorkPhones = 0;
numMobilePhones = 0;
mDialog = new KDialogBase( mParent, "addressbookexportdialog", true, i18n("Export to Address Book"), KDialogBase::Ok|KDialogBase::Cancel );
mUI = new AddressBookExportUI( mDialog );
mDialog->setMainWidget( mUI );
mDialog->setButtonOK( KGuiItem( ( "Export" ),
QString::null, i18n( "Set address book fields using the selected data from Kopete" ) ) );
initLabels();
// fetch existing data from kabc
fetchKABCData();
// fetch data from contacts
fetchIMData();
return mDialog->exec();
}
else
return QDialog::Rejected;
}
void KopeteAddressBookExport::exportData()
{
// write the data from the widget to KABC
// update the Addressee
// first name
bool dirty = false;
if ( newValue( mUI->mFirstName ) )
{
dirty = true;
mAddressee.setGivenName( mUI->mFirstName->currentText() );
}
// last name
if ( newValue( mUI->mLastName ) )
{
dirty = true;
mAddressee.setFamilyName( mUI->mLastName->currentText() );
}
// url
if ( newValue( mUI->mUrl ) )
{
dirty = true;
mAddressee.setUrl( KURL( mUI->mUrl->currentText() ) );
}
QStringList newVals;
// email
newVals = newValues( mUI->mEmails, numEmails );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertEmail( *it );
}
// home phone
newVals = newValues( mUI->mHomePhones, numHomePhones );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertPhoneNumber( KABC::PhoneNumber( *it, KABC::PhoneNumber::Home ) );
}
// work phone
newVals = newValues( mUI->mWorkPhones, numWorkPhones );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertPhoneNumber( KABC::PhoneNumber( *it, KABC::PhoneNumber::Work ) );
}
// mobile
newVals = newValues( mUI->mMobilePhones, numMobilePhones );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertPhoneNumber( KABC::PhoneNumber( *it, KABC::PhoneNumber::Cell ) );
}
if ( dirty )
{
// write the changed addressbook
mAddressBook->insertAddressee( mAddressee );
KABC::Ticket *ticket = mAddressBook->requestSaveTicket();
if ( !ticket )
kdWarning( 14000 ) << k_funcinfo << "WARNING: Resource is locked by other application!" << endl;
else
{
if ( !mAddressBook->save( ticket ) )
{
kdWarning( 14000 ) << k_funcinfo << "ERROR: Saving failed!" << endl;
mAddressBook->releaseSaveTicket( ticket );
}
}
kdDebug( 14000 ) << k_funcinfo << "Finished writing KABC" << endl;
}
}
bool KopeteAddressBookExport::newValue( QComboBox *combo )
{
// all data in position 0 is from KABC, so if position 0 is selected,
// or if the selection is the same as the data at 0, return false
return !( combo->currentItem() == 0 ||
( combo->text( combo->currentItem() ) == combo->text( 0 ) ) );
}
QStringList KopeteAddressBookExport::newValues( KListBox *listBox, uint counter )
{
QStringList newValues;
// need to iterate all items except those from KABC and check if selected and not same as the first
// counter is the number of KABC items, and hence the index of the first non KABC item
for ( uint i = counter; i < listBox->count(); ++i )
{
if ( listBox->isSelected( i ) )
{
// check whether it matches any KABC item
bool duplicate = false;
for ( uint j = 0; j < counter; ++j )
{
if ( listBox->text( i ) == listBox->text( j ) )
duplicate = true;
}
if ( !duplicate )
newValues.append( listBox->text( i ) );
}
}
return newValues;
}
<commit_msg>missing i18n<commit_after>/*
kopeteaddrbookexport.cpp - Kopete Online Status
Logic for exporting data acquired from messaging systems to the
KDE address book
Copyright (c) 2004 by Will Stephenson <lists@stevello.free-online.co.uk>
Kopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kabc/phonenumber.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <kdialogbase.h>
#include <kiconloader.h>
#include <klistbox.h>
#include <klocale.h>
#include "kopeteaccount.h"
#include "kopeteglobal.h"
#include "kopetemetacontact.h"
#include "kopetecontact.h"
#include "kopeteaddrbookexport.h"
#include "kopeteaddrbookexportui.h"
KopeteAddressBookExport::KopeteAddressBookExport( QWidget *parent, Kopete::MetaContact *mc ) : QObject( parent )
{
// instantiate dialog and populate widgets
mParent = parent;
mAddressBook = KABC::StdAddressBook::self();
mMetaContact = mc;
}
KopeteAddressBookExport::~KopeteAddressBookExport()
{
}
void KopeteAddressBookExport::initLabels()
{
if ( !mAddressee.isEmpty() )
{
mUI->mLblFirstName->setText( mAddressee.givenNameLabel() );
mUI->mLblLastName->setText( mAddressee.familyNameLabel() );
mUI->mLblEmail->setText( mAddressee.emailLabel() );
mUI->mLblUrl->setText( mAddressee.urlLabel() );
mUI->mLblHomePhone->setText( mAddressee.homePhoneLabel() );
mUI->mLblWorkPhone->setText( mAddressee.businessPhoneLabel() );
mUI->mLblMobilePhone->setText( mAddressee.mobilePhoneLabel() );
}
}
void KopeteAddressBookExport::fetchKABCData()
{
if ( !mAddressee.isEmpty() )
{
mAddrBookIcon = SmallIcon( "kaddressbook" );
// given name
QString given = mAddressee.givenName();
if ( !given.isEmpty() )
mUI->mFirstName->insertItem( mAddrBookIcon, given );
else
mUI->mFirstName->insertItem( mAddrBookIcon, i18n("<Not Set>") );
// family name
QString family = mAddressee.familyName();
if ( !family.isEmpty() )
mUI->mLastName->insertItem( mAddrBookIcon, family );
else
mUI->mLastName->insertItem( mAddrBookIcon, i18n("<Not Set>") );
// url
QString url = mAddressee.url().url();
if ( !url.isEmpty() )
mUI->mUrl->insertItem( mAddrBookIcon, url );
else
mUI->mUrl->insertItem( mAddrBookIcon, i18n("<Not Set>") );
// emails
QStringList emails = mAddressee.emails();
numEmails = emails.count();
for ( QStringList::Iterator it = emails.begin(); it != emails.end(); ++it )
mUI->mEmails->insertItem( mAddrBookIcon, *it );
if ( numEmails == 0 )
{
mUI->mEmails->insertItem( mAddrBookIcon, i18n("<Not Set>") );
numEmails = 1;
}
// phone numbers
fetchPhoneNumbers( mUI->mHomePhones, KABC::PhoneNumber::Home, numHomePhones );
fetchPhoneNumbers( mUI->mWorkPhones, KABC::PhoneNumber::Work, numWorkPhones );
fetchPhoneNumbers( mUI->mMobilePhones, KABC::PhoneNumber::Cell, numMobilePhones );
}
}
void KopeteAddressBookExport::fetchPhoneNumbers( KListBox * listBox, int type, uint& counter )
{
KABC::PhoneNumber::List phones = mAddressee.phoneNumbers( type );
counter = phones.count();
KABC::PhoneNumber::List::Iterator it;
for ( it = phones.begin(); it != phones.end(); ++it )
listBox->insertItem( mAddrBookIcon, (*it).number() );
if ( counter == 0 )
{
listBox->insertItem( mAddrBookIcon, i18n("<Not Set>") );
counter = 1;
}
}
void KopeteAddressBookExport::fetchIMData()
{
QPtrList<Kopete::Contact> contacts = mMetaContact->contacts();
QPtrListIterator<Kopete::Contact> cit( contacts );
for( ; cit.current(); ++cit )
{
// for each contact, get the property content
Kopete::Contact* c = cit.current();
QPixmap contactIcon = c->account()->accountIcon( 16 );
// given name
populateIM( c, contactIcon, mUI->mFirstName, Kopete::Global::Properties::self()->firstName() );
// family name
populateIM( c, contactIcon, mUI->mLastName, Kopete::Global::Properties::self()->lastName() );
// url
// TODO: make URL/homepage a global template, currently only in IRC channel contact
// emails
populateIM( c, contactIcon, mUI->mEmails, Kopete::Global::Properties::self()->emailAddress() );
// home phone
populateIM( c, contactIcon, mUI->mHomePhones, Kopete::Global::Properties::self()->privatePhone() );
// work phone
populateIM( c, contactIcon, mUI->mWorkPhones, Kopete::Global::Properties::self()->workPhone() );
// mobile phone
populateIM( c, contactIcon, mUI->mMobilePhones, Kopete::Global::Properties::self()->privateMobilePhone() );
}
}
void KopeteAddressBookExport::populateIM( const Kopete::Contact *contact, const QPixmap &icon, QComboBox *combo, const Kopete::ContactPropertyTmpl &property )
{
Kopete::ContactProperty prop = contact->property( property );
if ( !prop.isNull() )
{
combo->insertItem( icon, prop.value().toString() );
}
}
void KopeteAddressBookExport::populateIM( const Kopete::Contact *contact, const QPixmap &icon, KListBox *listBox, const Kopete::ContactPropertyTmpl &property )
{
Kopete::ContactProperty prop = contact->property( property );
if ( !prop.isNull() )
{
listBox->insertItem( icon, prop.value().toString() );
}
}
int KopeteAddressBookExport::showDialog()
{
mAddressee = mAddressBook->findByUid( mMetaContact->metaContactId() );
if ( !mAddressee.isEmpty() )
{
numEmails = 0;
numHomePhones = 0;
numWorkPhones = 0;
numMobilePhones = 0;
mDialog = new KDialogBase( mParent, "addressbookexportdialog", true, i18n("Export to Address Book"), KDialogBase::Ok|KDialogBase::Cancel );
mUI = new AddressBookExportUI( mDialog );
mDialog->setMainWidget( mUI );
mDialog->setButtonOK( KGuiItem( i18n( "Export" ),
QString::null, i18n( "Set address book fields using the selected data from Kopete" ) ) );
initLabels();
// fetch existing data from kabc
fetchKABCData();
// fetch data from contacts
fetchIMData();
return mDialog->exec();
}
else
return QDialog::Rejected;
}
void KopeteAddressBookExport::exportData()
{
// write the data from the widget to KABC
// update the Addressee
// first name
bool dirty = false;
if ( newValue( mUI->mFirstName ) )
{
dirty = true;
mAddressee.setGivenName( mUI->mFirstName->currentText() );
}
// last name
if ( newValue( mUI->mLastName ) )
{
dirty = true;
mAddressee.setFamilyName( mUI->mLastName->currentText() );
}
// url
if ( newValue( mUI->mUrl ) )
{
dirty = true;
mAddressee.setUrl( KURL( mUI->mUrl->currentText() ) );
}
QStringList newVals;
// email
newVals = newValues( mUI->mEmails, numEmails );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertEmail( *it );
}
// home phone
newVals = newValues( mUI->mHomePhones, numHomePhones );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertPhoneNumber( KABC::PhoneNumber( *it, KABC::PhoneNumber::Home ) );
}
// work phone
newVals = newValues( mUI->mWorkPhones, numWorkPhones );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertPhoneNumber( KABC::PhoneNumber( *it, KABC::PhoneNumber::Work ) );
}
// mobile
newVals = newValues( mUI->mMobilePhones, numMobilePhones );
for ( QStringList::Iterator it = newVals.begin(); it != newVals.end(); ++it )
{
dirty = true;
mAddressee.insertPhoneNumber( KABC::PhoneNumber( *it, KABC::PhoneNumber::Cell ) );
}
if ( dirty )
{
// write the changed addressbook
mAddressBook->insertAddressee( mAddressee );
KABC::Ticket *ticket = mAddressBook->requestSaveTicket();
if ( !ticket )
kdWarning( 14000 ) << k_funcinfo << "WARNING: Resource is locked by other application!" << endl;
else
{
if ( !mAddressBook->save( ticket ) )
{
kdWarning( 14000 ) << k_funcinfo << "ERROR: Saving failed!" << endl;
mAddressBook->releaseSaveTicket( ticket );
}
}
kdDebug( 14000 ) << k_funcinfo << "Finished writing KABC" << endl;
}
}
bool KopeteAddressBookExport::newValue( QComboBox *combo )
{
// all data in position 0 is from KABC, so if position 0 is selected,
// or if the selection is the same as the data at 0, return false
return !( combo->currentItem() == 0 ||
( combo->text( combo->currentItem() ) == combo->text( 0 ) ) );
}
QStringList KopeteAddressBookExport::newValues( KListBox *listBox, uint counter )
{
QStringList newValues;
// need to iterate all items except those from KABC and check if selected and not same as the first
// counter is the number of KABC items, and hence the index of the first non KABC item
for ( uint i = counter; i < listBox->count(); ++i )
{
if ( listBox->isSelected( i ) )
{
// check whether it matches any KABC item
bool duplicate = false;
for ( uint j = 0; j < counter; ++j )
{
if ( listBox->text( i ) == listBox->text( j ) )
duplicate = true;
}
if ( !duplicate )
newValues.append( listBox->text( i ) );
}
}
return newValues;
}
<|endoftext|> |
<commit_before>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kmailconnection.h"
#include "resourcekolabbase.h"
#include <kdebug.h>
#include <kurl.h>
#include <kdbusservicestarter.h>
#include <kmail/groupware_types.h>
#include <klocale.h>
#include <QDBusAbstractInterface>
#include <QMap>
#include <unistd.h>
using namespace Kolab;
KMailConnection::KMailConnection( ResourceKolabBase* resource )
: mResource( resource )
, mKmailGroupwareInterface( 0 )
{
QObject::connect(QDBusConnection::sessionBus().interface(),
SIGNAL(serviceOwnerChanged(QString,QString,QString)),
this, SLOT(dbusServiceOwnerChanged(QString,QString,QString)));
KMail::registerGroupwareTypes();
}
KMailConnection::~KMailConnection()
{
disconnectFromKMail();
}
bool KMailConnection::waitForGroupwareObject() const
{
const int waitTime = 1000 * 10; // 10 milliseconds step
const int timeout = 1000 * 1000 * 60; // 60 seconds total timeout
int waited = 0;
forever {
if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.kmail.groupware" ) ) {
return true;
}
usleep( waitTime );
waited += waitTime;
if ( waited > timeout ) {
kDebug(5650) << "Timeout while waiting for the groupware interface.";
return false;
}
}
};
bool KMailConnection::connectToKMail()
{
if ( !mKmailGroupwareInterface ) {
QString error;
QString dbusService;
int result = KDBusServiceStarter::self()->
findServiceFor( "DBUS/ResourceBackend/IMAP", QString(),
&error, &dbusService );
if ( result != 0 ) {
kError(5650) <<"Couldn't connect to the IMAP resource backend";
// TODO: You might want to show "error" (if not empty) here,
// using e.g. KMessageBox
return false;
}
kDebug(5650) << "Connected to the KMail DBus interface.";
if ( !waitForGroupwareObject() ) {
kError(5650) << "Can't connect to the groupware object on the KMail interface!";
return false;
}
mKmailGroupwareInterface = new OrgKdeKmailGroupwareInterface( dbusService, KMAIL_DBUS_GROUPWARE_PATH,
QDBusConnection::sessionBus() );
mOldServiceName = mKmailGroupwareInterface->service();
connect( mKmailGroupwareInterface, SIGNAL(incidenceAdded(QString,QString,uint,int,QString)),
SLOT(fromKMailAddIncidence(QString,QString,uint,int,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(incidenceDeleted(QString,QString,QString)),
SLOT(fromKMailDelIncidence(QString,QString,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(signalRefresh(QString,QString)),
SLOT( fromKMailRefresh(QString,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(subresourceAdded(QString,QString,QString,bool,bool)),
SLOT(fromKMailAddSubresource( QString, QString, QString, bool, bool )) );
connect( mKmailGroupwareInterface, SIGNAL(subresourceDeleted(QString,QString)),
SLOT(fromKMailDelSubresource(QString,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(asyncLoadResult(QMap<quint32,QString>,QString,QString)),
SLOT( fromKMailAsyncLoadResult(QMap<quint32,QString>,QString,QString)) );
}
return ( mKmailGroupwareInterface != 0 );
}
void KMailConnection::disconnectFromKMail()
{
delete mKmailGroupwareInterface;
mKmailGroupwareInterface = 0;
}
bool KMailConnection::fromKMailAddIncidence( const QString& type,
const QString& folder,
uint sernum,
int format,
const QString& data )
{
if ( format != KMail::StorageXML
&& format != KMail::StorageIcalVcard )
return false;
// kDebug(5650) <<"KMailConnection::fromKMailAddIncidence(" << type <<","
// << folder << "). iCal:\n" << ical;
return mResource->fromKMailAddIncidence( type, folder, sernum, format, data );
}
void KMailConnection::fromKMailDelIncidence( const QString& type,
const QString& folder,
const QString& xml )
{
kDebug(5650) <<"KMailConnection::fromKMailDelIncidence(" << type <<","
<< folder << ", " << xml << " )";
mResource->fromKMailDelIncidence( type, folder, xml );
}
void KMailConnection::fromKMailRefresh( const QString& type, const QString& folder )
{
// kDebug(5650) <<"KMailConnection::fromKMailRefresh(" << type <<","
// << folder << " )";
mResource->fromKMailRefresh( type, folder );
}
void KMailConnection::fromKMailAddSubresource( const QString& type,
const QString& resource,
const QString& label,
bool writable,
bool alarmRelevant )
{
// kDebug(5650) <<"KMailConnection::fromKMailAddSubresource(" << type <<","
// << resource << " )";
mResource->fromKMailAddSubresource( type, resource, label,
writable, alarmRelevant );
}
void KMailConnection::fromKMailDelSubresource( const QString& type,
const QString& resource )
{
// kDebug(5650) <<"KMailConnection::fromKMailDelSubresource(" << type <<","
// << resource << " )";
mResource->fromKMailDelSubresource( type, resource );
}
void KMailConnection::fromKMailAsyncLoadResult( const QMap<quint32, QString>& map,
const QString& type,
const QString& folder )
{
mResource->fromKMailAsyncLoadResult( map, type, folder );
}
bool KMailConnection::kmailSubresources( QList<KMail::SubResource>& lst,
const QString& contentsType )
{
if ( !connectToKMail() )
return false;
return checkReply<QList<KMail::SubResource>, QList<KMail::SubResource> >( mKmailGroupwareInterface->subresourcesKolab( contentsType ), lst );
}
bool KMailConnection::kmailIncidencesCount( int& count,
const QString& mimetype,
const QString& resource )
{
if ( !connectToKMail() )
return false;
return checkReply<int, int>( mKmailGroupwareInterface->incidencesKolabCount( mimetype, resource ), count );
}
bool KMailConnection::kmailIncidences( KMail::SernumDataPair::List& lst,
const QString& mimetype,
const QString& resource,
int startIndex,
int nbMessages )
{
if ( !connectToKMail() )
return false;
return checkReply<QList<KMail::SernumDataPair>, QList<KMail::SernumDataPair> >(
mKmailGroupwareInterface->incidencesKolab( mimetype, resource, startIndex, nbMessages ), lst );
}
bool KMailConnection::kmailGetAttachment( KUrl& url,
const QString& resource,
quint32 sernum,
const QString& filename )
{
if ( !connectToKMail() )
return false;
return checkReply<QString, KUrl>( mKmailGroupwareInterface->getAttachment( resource, sernum, filename ), url );
}
bool KMailConnection::kmailAttachmentMimetype( QString & mimeType,
const QString & resource,
quint32 sernum,
const QString & filename )
{
if ( !connectToKMail() )
return false;
return checkReply<QString, QString>( mKmailGroupwareInterface->attachmentMimetype( resource, sernum, filename ), mimeType );
}
bool KMailConnection::kmailListAttachments(QStringList &list,
const QString & resource, quint32 sernum)
{
if ( !connectToKMail() )
return false;
return checkReply<QStringList, QStringList>( mKmailGroupwareInterface->listAttachments( resource, sernum ), list );
}
bool KMailConnection::kmailDeleteIncidence( const QString& resource,
quint32 sernum )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->deleteIncidenceKolab( resource, sernum ) );
}
bool KMailConnection::kmailUpdate( const QString& resource,
quint32& sernum,
const QString& subject,
const QString& plainTextBody,
const KMail::CustomHeader::List& customHeaders,
const QStringList& attachmentURLs,
const QStringList& attachmentMimetypes,
const QStringList& attachmentNames,
const QStringList& deletedAttachments )
{
if ( !connectToKMail() )
return false;
return checkReply<quint32,quint32>( mKmailGroupwareInterface->update(
resource,
sernum,
subject,
plainTextBody,
customHeaders,
attachmentURLs,
attachmentMimetypes,
attachmentNames,
deletedAttachments ), sernum );
}
bool KMailConnection::kmailAddSubresource( const QString& resource,
const QString& parent,
const QString& contentsType )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->addSubresource( resource, parent, contentsType ) );
}
bool KMailConnection::kmailRemoveSubresource( const QString& resource )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->removeSubresource( resource ) );
}
bool KMailConnection::kmailStorageFormat( KMail::StorageFormat& type,
const QString& folder )
{
if ( !connectToKMail() )
return false;
QDBusReply<int> reply = mKmailGroupwareInterface->storageFormat( folder );
if ( reply.isValid() )
type = static_cast<KMail::StorageFormat>( reply.value() );
return mKmailGroupwareInterface->lastError().type() == QDBusError::NoError;
}
bool KMailConnection::kmailTriggerSync( const QString &contentsType )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->triggerSync( contentsType ) );
}
void KMailConnection::dbusServiceOwnerChanged( const QString &service, const QString &oldOwner,
const QString &newOwner )
{
Q_UNUSED( newOwner );
// The owner of the D-Bus service we're interested in changed, so either connect or disconnect.
if ( mOldServiceName == service && !service.isEmpty() ) {
if ( mKmailGroupwareInterface )
{
// Delete the stub so that the next time we need to talk to kmail,
// we'll know that we need to start a new one.
disconnectFromKMail();
}
else {
const bool kmailJustStarted = oldOwner.isEmpty();
if ( kmailJustStarted ) { // Vampire protection
if ( !connectToKMail() ) {
kWarning(5650) << "Could not connect to KMail, even though the D-Bus service just became available!";
}
}
}
}
}
#include "kmailconnection.moc"
<commit_msg>Build with pendantic<commit_after>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "kmailconnection.h"
#include "resourcekolabbase.h"
#include <kdebug.h>
#include <kurl.h>
#include <kdbusservicestarter.h>
#include <kmail/groupware_types.h>
#include <klocale.h>
#include <QDBusAbstractInterface>
#include <QMap>
#include <unistd.h>
using namespace Kolab;
KMailConnection::KMailConnection( ResourceKolabBase* resource )
: mResource( resource )
, mKmailGroupwareInterface( 0 )
{
QObject::connect(QDBusConnection::sessionBus().interface(),
SIGNAL(serviceOwnerChanged(QString,QString,QString)),
this, SLOT(dbusServiceOwnerChanged(QString,QString,QString)));
KMail::registerGroupwareTypes();
}
KMailConnection::~KMailConnection()
{
disconnectFromKMail();
}
bool KMailConnection::waitForGroupwareObject() const
{
const int waitTime = 1000 * 10; // 10 milliseconds step
const int timeout = 1000 * 1000 * 60; // 60 seconds total timeout
int waited = 0;
forever {
if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.kmail.groupware" ) ) {
return true;
}
usleep( waitTime );
waited += waitTime;
if ( waited > timeout ) {
kDebug(5650) << "Timeout while waiting for the groupware interface.";
return false;
}
}
}
bool KMailConnection::connectToKMail()
{
if ( !mKmailGroupwareInterface ) {
QString error;
QString dbusService;
int result = KDBusServiceStarter::self()->
findServiceFor( "DBUS/ResourceBackend/IMAP", QString(),
&error, &dbusService );
if ( result != 0 ) {
kError(5650) <<"Couldn't connect to the IMAP resource backend";
// TODO: You might want to show "error" (if not empty) here,
// using e.g. KMessageBox
return false;
}
kDebug(5650) << "Connected to the KMail DBus interface.";
if ( !waitForGroupwareObject() ) {
kError(5650) << "Can't connect to the groupware object on the KMail interface!";
return false;
}
mKmailGroupwareInterface = new OrgKdeKmailGroupwareInterface( dbusService, KMAIL_DBUS_GROUPWARE_PATH,
QDBusConnection::sessionBus() );
mOldServiceName = mKmailGroupwareInterface->service();
connect( mKmailGroupwareInterface, SIGNAL(incidenceAdded(QString,QString,uint,int,QString)),
SLOT(fromKMailAddIncidence(QString,QString,uint,int,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(incidenceDeleted(QString,QString,QString)),
SLOT(fromKMailDelIncidence(QString,QString,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(signalRefresh(QString,QString)),
SLOT( fromKMailRefresh(QString,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(subresourceAdded(QString,QString,QString,bool,bool)),
SLOT(fromKMailAddSubresource( QString, QString, QString, bool, bool )) );
connect( mKmailGroupwareInterface, SIGNAL(subresourceDeleted(QString,QString)),
SLOT(fromKMailDelSubresource(QString,QString)) );
connect( mKmailGroupwareInterface, SIGNAL(asyncLoadResult(QMap<quint32,QString>,QString,QString)),
SLOT( fromKMailAsyncLoadResult(QMap<quint32,QString>,QString,QString)) );
}
return ( mKmailGroupwareInterface != 0 );
}
void KMailConnection::disconnectFromKMail()
{
delete mKmailGroupwareInterface;
mKmailGroupwareInterface = 0;
}
bool KMailConnection::fromKMailAddIncidence( const QString& type,
const QString& folder,
uint sernum,
int format,
const QString& data )
{
if ( format != KMail::StorageXML
&& format != KMail::StorageIcalVcard )
return false;
// kDebug(5650) <<"KMailConnection::fromKMailAddIncidence(" << type <<","
// << folder << "). iCal:\n" << ical;
return mResource->fromKMailAddIncidence( type, folder, sernum, format, data );
}
void KMailConnection::fromKMailDelIncidence( const QString& type,
const QString& folder,
const QString& xml )
{
kDebug(5650) <<"KMailConnection::fromKMailDelIncidence(" << type <<","
<< folder << ", " << xml << " )";
mResource->fromKMailDelIncidence( type, folder, xml );
}
void KMailConnection::fromKMailRefresh( const QString& type, const QString& folder )
{
// kDebug(5650) <<"KMailConnection::fromKMailRefresh(" << type <<","
// << folder << " )";
mResource->fromKMailRefresh( type, folder );
}
void KMailConnection::fromKMailAddSubresource( const QString& type,
const QString& resource,
const QString& label,
bool writable,
bool alarmRelevant )
{
// kDebug(5650) <<"KMailConnection::fromKMailAddSubresource(" << type <<","
// << resource << " )";
mResource->fromKMailAddSubresource( type, resource, label,
writable, alarmRelevant );
}
void KMailConnection::fromKMailDelSubresource( const QString& type,
const QString& resource )
{
// kDebug(5650) <<"KMailConnection::fromKMailDelSubresource(" << type <<","
// << resource << " )";
mResource->fromKMailDelSubresource( type, resource );
}
void KMailConnection::fromKMailAsyncLoadResult( const QMap<quint32, QString>& map,
const QString& type,
const QString& folder )
{
mResource->fromKMailAsyncLoadResult( map, type, folder );
}
bool KMailConnection::kmailSubresources( QList<KMail::SubResource>& lst,
const QString& contentsType )
{
if ( !connectToKMail() )
return false;
return checkReply<QList<KMail::SubResource>, QList<KMail::SubResource> >( mKmailGroupwareInterface->subresourcesKolab( contentsType ), lst );
}
bool KMailConnection::kmailIncidencesCount( int& count,
const QString& mimetype,
const QString& resource )
{
if ( !connectToKMail() )
return false;
return checkReply<int, int>( mKmailGroupwareInterface->incidencesKolabCount( mimetype, resource ), count );
}
bool KMailConnection::kmailIncidences( KMail::SernumDataPair::List& lst,
const QString& mimetype,
const QString& resource,
int startIndex,
int nbMessages )
{
if ( !connectToKMail() )
return false;
return checkReply<QList<KMail::SernumDataPair>, QList<KMail::SernumDataPair> >(
mKmailGroupwareInterface->incidencesKolab( mimetype, resource, startIndex, nbMessages ), lst );
}
bool KMailConnection::kmailGetAttachment( KUrl& url,
const QString& resource,
quint32 sernum,
const QString& filename )
{
if ( !connectToKMail() )
return false;
return checkReply<QString, KUrl>( mKmailGroupwareInterface->getAttachment( resource, sernum, filename ), url );
}
bool KMailConnection::kmailAttachmentMimetype( QString & mimeType,
const QString & resource,
quint32 sernum,
const QString & filename )
{
if ( !connectToKMail() )
return false;
return checkReply<QString, QString>( mKmailGroupwareInterface->attachmentMimetype( resource, sernum, filename ), mimeType );
}
bool KMailConnection::kmailListAttachments(QStringList &list,
const QString & resource, quint32 sernum)
{
if ( !connectToKMail() )
return false;
return checkReply<QStringList, QStringList>( mKmailGroupwareInterface->listAttachments( resource, sernum ), list );
}
bool KMailConnection::kmailDeleteIncidence( const QString& resource,
quint32 sernum )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->deleteIncidenceKolab( resource, sernum ) );
}
bool KMailConnection::kmailUpdate( const QString& resource,
quint32& sernum,
const QString& subject,
const QString& plainTextBody,
const KMail::CustomHeader::List& customHeaders,
const QStringList& attachmentURLs,
const QStringList& attachmentMimetypes,
const QStringList& attachmentNames,
const QStringList& deletedAttachments )
{
if ( !connectToKMail() )
return false;
return checkReply<quint32,quint32>( mKmailGroupwareInterface->update(
resource,
sernum,
subject,
plainTextBody,
customHeaders,
attachmentURLs,
attachmentMimetypes,
attachmentNames,
deletedAttachments ), sernum );
}
bool KMailConnection::kmailAddSubresource( const QString& resource,
const QString& parent,
const QString& contentsType )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->addSubresource( resource, parent, contentsType ) );
}
bool KMailConnection::kmailRemoveSubresource( const QString& resource )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->removeSubresource( resource ) );
}
bool KMailConnection::kmailStorageFormat( KMail::StorageFormat& type,
const QString& folder )
{
if ( !connectToKMail() )
return false;
QDBusReply<int> reply = mKmailGroupwareInterface->storageFormat( folder );
if ( reply.isValid() )
type = static_cast<KMail::StorageFormat>( reply.value() );
return mKmailGroupwareInterface->lastError().type() == QDBusError::NoError;
}
bool KMailConnection::kmailTriggerSync( const QString &contentsType )
{
if ( !connectToKMail() )
return false;
return checkReply( mKmailGroupwareInterface->triggerSync( contentsType ) );
}
void KMailConnection::dbusServiceOwnerChanged( const QString &service, const QString &oldOwner,
const QString &newOwner )
{
Q_UNUSED( newOwner );
// The owner of the D-Bus service we're interested in changed, so either connect or disconnect.
if ( mOldServiceName == service && !service.isEmpty() ) {
if ( mKmailGroupwareInterface )
{
// Delete the stub so that the next time we need to talk to kmail,
// we'll know that we need to start a new one.
disconnectFromKMail();
}
else {
const bool kmailJustStarted = oldOwner.isEmpty();
if ( kmailJustStarted ) { // Vampire protection
if ( !connectToKMail() ) {
kWarning(5650) << "Could not connect to KMail, even though the D-Bus service just became available!";
}
}
}
}
}
#include "kmailconnection.moc"
<|endoftext|> |
<commit_before>#include "nodetests.h"
#include "yaml-cpp/yaml.h"
namespace {
struct TEST {
TEST(): ok(false) {}
TEST(bool ok_): ok(ok_) {}
TEST(const char *error_): ok(false), error(error_) {}
bool ok;
std::string error;
};
}
#define YAML_ASSERT(cond) do { if(!(cond)) return " Assert failed: " #cond; } while(false)
namespace Test
{
namespace Node
{
TEST SimpleScalar()
{
YAML::Node node = YAML::Node("Hello, World!");
YAML_ASSERT(node.Type() == YAML::NodeType::Scalar);
YAML_ASSERT(node.as<std::string>() == "Hello, World!");
return true;
}
TEST IntScalar()
{
YAML::Node node = YAML::Node(15);
YAML_ASSERT(node.Type() == YAML::NodeType::Scalar);
YAML_ASSERT(node.as<int>() == 15);
return true;
}
TEST SimpleAppendSequence()
{
YAML::Node node;
node.append(10);
node.append("foo");
node.append("monkey");
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
YAML_ASSERT(node.size() == 3);
YAML_ASSERT(node[0].as<int>() == 10);
YAML_ASSERT(node[1].as<std::string>() == "foo");
YAML_ASSERT(node[2].as<std::string>() == "monkey");
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
return true;
}
TEST SimpleAssignSequence()
{
YAML::Node node;
node[0] = 10;
node[1] = "foo";
node[2] = "monkey";
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
YAML_ASSERT(node.size() == 3);
YAML_ASSERT(node[0].as<int>() == 10);
YAML_ASSERT(node[1].as<std::string>() == "foo");
YAML_ASSERT(node[2].as<std::string>() == "monkey");
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
return true;
}
TEST SimpleMap()
{
YAML::Node node;
node["key"] = "value";
YAML_ASSERT(node.Type() == YAML::NodeType::Map);
YAML_ASSERT(node["key"].as<std::string>() == "value");
YAML_ASSERT(node.size() == 1);
return true;
}
TEST MapWithUndefinedValues()
{
YAML::Node node;
node["key"] = "value";
node["undefined"];
YAML_ASSERT(node.Type() == YAML::NodeType::Map);
YAML_ASSERT(node["key"].as<std::string>() == "value");
YAML_ASSERT(node.size() == 1);
node["undefined"] = "monkey";
YAML_ASSERT(node["undefined"].as<std::string>() == "monkey");
YAML_ASSERT(node.size() == 2);
return true;
}
TEST MapIteratorWithUndefinedValues()
{
YAML::Node node;
node["key"] = "value";
node["undefined"];
std::size_t count = 0;
for(YAML::const_iterator it=node.begin();it!=node.end();++it)
count++;
YAML_ASSERT(count == 1);
return true;
}
TEST SimpleSubkeys()
{
YAML::Node node;
node["device"]["udid"] = "12345";
node["device"]["name"] = "iPhone";
node["device"]["os"] = "4.0";
node["username"] = "monkey";
YAML_ASSERT(node["device"]["udid"].as<std::string>() == "12345");
YAML_ASSERT(node["device"]["name"].as<std::string>() == "iPhone");
YAML_ASSERT(node["device"]["os"].as<std::string>() == "4.0");
YAML_ASSERT(node["username"].as<std::string>() == "monkey");
return true;
}
TEST StdVector()
{
std::vector<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
YAML_ASSERT(node["primes"].as<std::vector<int> >() == primes);
return true;
}
TEST StdList()
{
std::list<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
YAML_ASSERT(node["primes"].as<std::list<int> >() == primes);
return true;
}
TEST StdMap()
{
std::map<int, int> squares;
squares[0] = 0;
squares[1] = 1;
squares[2] = 4;
squares[3] = 9;
squares[4] = 16;
YAML::Node node;
node["squares"] = squares;
YAML_ASSERT((node["squares"].as<std::map<int, int> >() == squares));
return true;
}
}
void RunNodeTest(TEST (*test)(), const std::string& name, int& passed, int& total) {
TEST ret;
try {
ret = test();
} catch(...) {
ret.ok = false;
}
if(ret.ok) {
passed++;
} else {
std::cout << "Node test failed: " << name << "\n";
if(ret.error != "")
std::cout << ret.error << "\n";
}
total++;
}
bool RunNodeTests()
{
int passed = 0;
int total = 0;
RunNodeTest(&Node::SimpleScalar, "simple scalar", passed, total);
RunNodeTest(&Node::IntScalar, "int scalar", passed, total);
RunNodeTest(&Node::SimpleAppendSequence, "simple append sequence", passed, total);
RunNodeTest(&Node::SimpleAssignSequence, "simple assign sequence", passed, total);
RunNodeTest(&Node::SimpleMap, "simple map", passed, total);
RunNodeTest(&Node::MapWithUndefinedValues, "map with undefined values", passed, total);
RunNodeTest(&Node::MapIteratorWithUndefinedValues, "map iterator with undefined values", passed, total);
RunNodeTest(&Node::SimpleSubkeys, "simple subkey", passed, total);
RunNodeTest(&Node::StdVector, "std::vector", passed, total);
RunNodeTest(&Node::StdList, "std::list", passed, total);
RunNodeTest(&Node::StdMap, "std::map", passed, total);
std::cout << "Node tests: " << passed << "/" << total << " passed\n";
return passed == total;
}
}
<commit_msg>Added two alias tests<commit_after>#include "nodetests.h"
#include "yaml-cpp/yaml.h"
namespace {
struct TEST {
TEST(): ok(false) {}
TEST(bool ok_): ok(ok_) {}
TEST(const char *error_): ok(false), error(error_) {}
bool ok;
std::string error;
};
}
#define YAML_ASSERT(cond) do { if(!(cond)) return " Assert failed: " #cond; } while(false)
namespace Test
{
namespace Node
{
TEST SimpleScalar()
{
YAML::Node node = YAML::Node("Hello, World!");
YAML_ASSERT(node.Type() == YAML::NodeType::Scalar);
YAML_ASSERT(node.as<std::string>() == "Hello, World!");
return true;
}
TEST IntScalar()
{
YAML::Node node = YAML::Node(15);
YAML_ASSERT(node.Type() == YAML::NodeType::Scalar);
YAML_ASSERT(node.as<int>() == 15);
return true;
}
TEST SimpleAppendSequence()
{
YAML::Node node;
node.append(10);
node.append("foo");
node.append("monkey");
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
YAML_ASSERT(node.size() == 3);
YAML_ASSERT(node[0].as<int>() == 10);
YAML_ASSERT(node[1].as<std::string>() == "foo");
YAML_ASSERT(node[2].as<std::string>() == "monkey");
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
return true;
}
TEST SimpleAssignSequence()
{
YAML::Node node;
node[0] = 10;
node[1] = "foo";
node[2] = "monkey";
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
YAML_ASSERT(node.size() == 3);
YAML_ASSERT(node[0].as<int>() == 10);
YAML_ASSERT(node[1].as<std::string>() == "foo");
YAML_ASSERT(node[2].as<std::string>() == "monkey");
YAML_ASSERT(node.Type() == YAML::NodeType::Sequence);
return true;
}
TEST SimpleMap()
{
YAML::Node node;
node["key"] = "value";
YAML_ASSERT(node.Type() == YAML::NodeType::Map);
YAML_ASSERT(node["key"].as<std::string>() == "value");
YAML_ASSERT(node.size() == 1);
return true;
}
TEST MapWithUndefinedValues()
{
YAML::Node node;
node["key"] = "value";
node["undefined"];
YAML_ASSERT(node.Type() == YAML::NodeType::Map);
YAML_ASSERT(node["key"].as<std::string>() == "value");
YAML_ASSERT(node.size() == 1);
node["undefined"] = "monkey";
YAML_ASSERT(node["undefined"].as<std::string>() == "monkey");
YAML_ASSERT(node.size() == 2);
return true;
}
TEST MapIteratorWithUndefinedValues()
{
YAML::Node node;
node["key"] = "value";
node["undefined"];
std::size_t count = 0;
for(YAML::const_iterator it=node.begin();it!=node.end();++it)
count++;
YAML_ASSERT(count == 1);
return true;
}
TEST SimpleSubkeys()
{
YAML::Node node;
node["device"]["udid"] = "12345";
node["device"]["name"] = "iPhone";
node["device"]["os"] = "4.0";
node["username"] = "monkey";
YAML_ASSERT(node["device"]["udid"].as<std::string>() == "12345");
YAML_ASSERT(node["device"]["name"].as<std::string>() == "iPhone");
YAML_ASSERT(node["device"]["os"].as<std::string>() == "4.0");
YAML_ASSERT(node["username"].as<std::string>() == "monkey");
return true;
}
TEST StdVector()
{
std::vector<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
YAML_ASSERT(node["primes"].as<std::vector<int> >() == primes);
return true;
}
TEST StdList()
{
std::list<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
YAML_ASSERT(node["primes"].as<std::list<int> >() == primes);
return true;
}
TEST StdMap()
{
std::map<int, int> squares;
squares[0] = 0;
squares[1] = 1;
squares[2] = 4;
squares[3] = 9;
squares[4] = 16;
YAML::Node node;
node["squares"] = squares;
YAML_ASSERT((node["squares"].as<std::map<int, int> >() == squares));
return true;
}
TEST SimpleAlias()
{
YAML::Node node;
node["foo"] = "value";
node["bar"] = node["foo"];
YAML_ASSERT(node["foo"].as<std::string>() == "value");
YAML_ASSERT(node["bar"].as<std::string>() == "value");
YAML_ASSERT(node["foo"] == node["bar"]);
YAML_ASSERT(node.size() == 2);
return true;
}
TEST AliasAsKey()
{
YAML::Node node;
node["foo"] = "value";
YAML::Node value = node["foo"];
node[value] = "foo";
YAML_ASSERT(node["foo"].as<std::string>() == "value");
YAML_ASSERT(node[value].as<std::string>() == "foo");
YAML_ASSERT(node["value"].as<std::string>() == "foo");
YAML_ASSERT(node.size() == 2);
return true;
}
}
void RunNodeTest(TEST (*test)(), const std::string& name, int& passed, int& total) {
TEST ret;
try {
ret = test();
} catch(...) {
ret.ok = false;
}
if(ret.ok) {
passed++;
} else {
std::cout << "Node test failed: " << name << "\n";
if(ret.error != "")
std::cout << ret.error << "\n";
}
total++;
}
bool RunNodeTests()
{
int passed = 0;
int total = 0;
RunNodeTest(&Node::SimpleScalar, "simple scalar", passed, total);
RunNodeTest(&Node::IntScalar, "int scalar", passed, total);
RunNodeTest(&Node::SimpleAppendSequence, "simple append sequence", passed, total);
RunNodeTest(&Node::SimpleAssignSequence, "simple assign sequence", passed, total);
RunNodeTest(&Node::SimpleMap, "simple map", passed, total);
RunNodeTest(&Node::MapWithUndefinedValues, "map with undefined values", passed, total);
RunNodeTest(&Node::MapIteratorWithUndefinedValues, "map iterator with undefined values", passed, total);
RunNodeTest(&Node::SimpleSubkeys, "simple subkey", passed, total);
RunNodeTest(&Node::StdVector, "std::vector", passed, total);
RunNodeTest(&Node::StdList, "std::list", passed, total);
RunNodeTest(&Node::StdMap, "std::map", passed, total);
RunNodeTest(&Node::SimpleAlias, "simple alias", passed, total);
RunNodeTest(&Node::AliasAsKey, "alias as key", passed, total);
std::cout << "Node tests: " << passed << "/" << total << " passed\n";
return passed == total;
}
}
<|endoftext|> |
<commit_before>// Copyright 2010 Google
// 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.
//
// Costas Array Problem
//
// Finds an NxN matrix of 0s and 1s, with only one 1 per row,
// and one 1 per column, such that all displacement vectors
// between each pair of 1s are distinct.
//
// This example contains two separate implementations. CostasHard()
// uses hard constraints, whereas CostasSoft() uses a minimizer to
// minimize the number of duplicates.
#include <time.h>
#include "base/callback.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "constraint_solver/constraint_solveri.h"
#include "base/random.h"
DEFINE_int32(minsize, 0, "Minimum degree of Costas matrix.");
DEFINE_int32(maxsize, 0, "Maximum degree of Costas matrix.");
DEFINE_int32(freevar, 5, "Number of free variables.");
DEFINE_int32(freeorderedvar, 4, "Number of variables in ordered subset.");
DEFINE_int32(sublimit, 20, "Number of attempts per subtree.");
DEFINE_int32(timelimit, 120000, "Time limit for local search.");
DEFINE_bool(soft_constraints, false, "Use soft constraints.");
DEFINE_string(export_profile, "", "filename to save the profile overview");
namespace operations_research {
// Checks that all pairwise distances are unique and returns all violators
void CheckConstraintViolators(const vector<int64>& vars,
vector<int>* const violators) {
int dim = vars.size();
// Check that all indices are unique
for (int i = 0; i < dim; ++i) {
for (int k = i + 1; k < dim; ++k) {
if (vars[i] == vars[k]) {
violators->push_back(i);
violators->push_back(k);
}
}
}
// Check that all differences are unique for each level
for (int level = 1; level < dim; ++level) {
for (int i = 0; i < dim - level; ++i) {
const int difference = vars[i + level] - vars[i];
for (int k = i + 1; k < dim - level; ++k) {
if (difference == vars[k + level] - vars[k]) {
violators->push_back(k + level);
violators->push_back(k);
violators->push_back(i + level);
violators->push_back(i);
}
}
}
}
}
// Check that all pairwise differences are unique
bool CheckCostas(const vector<int64>& vars) {
vector<int> violators;
CheckConstraintViolators(vars, &violators);
return violators.empty();
}
// Cycles all possible permutations
class OrderedLNS: public BaseLNS {
public:
OrderedLNS(const vector<IntVar*>& vars, int free_elements) :
BaseLNS(vars.data(), vars.size()),
free_elements_(free_elements) {
index_ = 0;
// Start of with the first free_elements_ as a permutations, eg. 0,1,2,3,...
for (int i = 0; i < free_elements; ++i) {
index_ += i * pow(vars.size(), free_elements-i-1);
}
}
virtual bool NextFragment(vector<int>* const fragment) {
int dim = Size();
set<int> fragment_set;
do {
int work_index = index_;
fragment->clear();
fragment_set.clear();
for (int i = 0; i < free_elements_; ++i) {
int current_index = work_index % dim;
work_index = work_index / dim;
pair<set<int>::iterator, bool> ret = fragment_set.insert(current_index);
// Check if element has been used before
if (ret.second) {
fragment->push_back(current_index);
} else {
break;
}
}
// Go to next possible permutation
++index_;
// Try again if a duplicate index is used
} while (fragment_set.size() < free_elements_);
return true;
}
private:
int index_;
const int free_elements_;
};
// RandomLNS is used for the local search and frees the
// number of elements specified in 'free_elements' randomly.
class RandomLNS: public BaseLNS {
public:
RandomLNS(const vector<IntVar*>& vars, int free_elements) :
BaseLNS(vars.data(), vars.size()),
free_elements_(free_elements),
rand_(ACMRandom::HostnamePidTimeSeed()) {
}
virtual bool NextFragment(vector<int>* const fragment) {
vector<int> weighted_elements;
vector<int64> values;
// Create weighted vector for randomizer. Add one of each possible elements
// to the weighted vector and then add more elements depending on the
// number of conflicts
for (int i = 0; i < Size(); ++i) {
values.push_back(Value(i));
// Insert each variable at least once.
weighted_elements.push_back(i);
}
CheckConstraintViolators(values, &weighted_elements);
int size = weighted_elements.size();
// Randomly insert elements in vector until no more options remain
while (fragment->size() < min(free_elements_, size)) {
const int index = weighted_elements[rand_.Next() % size];
fragment->push_back(index);
// Remove all elements with this index from weighted_elements
for (vector<int>::iterator pos = weighted_elements.begin();
pos != weighted_elements.end(); ) {
if (*pos == index) {
// Try to erase as many elements as possible at the same time
vector<int>::iterator end = pos;
while ((end + 1) != weighted_elements.end() && *(end + 1) == *pos) {
++end;
}
pos = weighted_elements.erase(pos, end);
} else {
++pos;
}
}
size = weighted_elements.size();
}
return true;
}
private:
const int free_elements_;
ACMRandom rand_;
};
class Evaluator {
public:
explicit Evaluator(const vector<IntVar*>& vars) : vars_(vars) {}
// Prefer the value with the smallest domain
int64 VarEvaluator(int64 index) {
return vars_[index]->Size();
}
// Penalize for each time the value appears in a different domain,
// as values have to be unique
int64 ValueEvaluator(int64 id, int64 value) {
int appearance = 0;
for (int i = 0; i < vars_.size(); ++i) {
if (i != id && vars_[i]->Contains(value)) {
++appearance;
}
}
return appearance;
}
private:
vector<IntVar*> vars_;
};
// Computes a Costas Array using soft constraints.
// Instead of enforcing that all distance vectors are unique, we
// minimize the number of duplicate distance vectors.
void CostasSoft(const int dim) {
Solver solver("Costas");
// For the matrix and for the count of occurrences of each possible distance
// for each stage
const int num_elements = dim + (2 * dim + 1) * (dim);
// create the variables
vector<IntVar*> vars;
solver.MakeIntVarArray(num_elements, -dim, dim, "var_", &vars);
// the costas matrix
vector<IntVar*> matrix(dim);
// number of occurrences per stage
vector<IntVar*> occurences;
// All possible values of the distance vector
// used to count the occurrence of all these values
vector<int64> possible_values(2 * dim + 1);
for (int64 i = -dim; i <= dim; ++i) {
possible_values[i + dim] = i;
}
int index = 0;
// Initialize the matrix that contains the coordinates of all '1' per row
for (; index < dim; ++index) {
matrix[index] = vars[index];
vars[index]->SetMin(1);
}
// First constraint for the elements in the Costas Matrix. We want
// them to be unique.
vector<IntVar*> matrix_count;
solver.MakeIntVarArray(2 * dim + 1, 0, dim, "matrix_count_", &matrix_count);
solver.AddConstraint(solver.MakeDistribute(matrix, possible_values,
matrix_count));
// Here we only consider the elements from 1 to dim.
for (int64 j = dim + 1; j <= 2 * dim; ++j) {
// Penalize if an element occurs more than once.
vars[index]
= solver.MakeSemiContinuousExpr(solver.MakeSum(matrix_count[j], -1),
0, 1)->Var();
occurences.push_back(vars[index++]);
}
// Count the number of duplicates for each stage
for (int i = 1; i < dim; ++i) {
vector<IntVar*> subset(dim - i);
// Initialize each stage
for (int j = 0; j < dim - i; ++j) {
IntVar* const diff = solver.MakeDifference(vars[j + i], vars[j])->Var();
subset[j] = diff;
}
// Count the number of occurrences for all possible values
vector<IntVar*> domain_count;
solver.MakeIntVarArray(2 * dim + 1, 0, dim, "domain_count_", &domain_count);
solver.AddConstraint(solver.MakeDistribute(subset,
possible_values,
domain_count));
// Penalize occurrences of more than one
for (int64 j = 0; j <= 2 * dim; ++j) {
vars[index] =
solver.MakeSemiContinuousExpr(solver.MakeSum(domain_count[j], -1),
0, dim - i)->Var();
occurences.push_back(vars[index++]);
}
}
// We would like to minimize the penalties that we just computed
IntVar* const objective_var = solver.MakeSum(occurences)->Var();
OptimizeVar* const total_duplicates = solver.MakeMinimize(objective_var, 1);
SearchMonitor* const log = solver.MakeSearchLog(1000, objective_var);
// Out of all solutions, we just want to store the last one.
SolutionCollector* const collector = solver.MakeLastSolutionCollector();
collector->Add(vars);
// The first solution that the local optimization is based on
Evaluator evaluator(matrix);
DecisionBuilder* const first_solution =
solver.MakePhase(matrix,
NewPermanentCallback(&evaluator,
&Evaluator::VarEvaluator),
NewPermanentCallback(&evaluator,
&Evaluator::ValueEvaluator));
SearchLimit* const search_time_limit =
solver.MakeLimit(FLAGS_timelimit, kint64max, kint64max, kint64max);
// Locally optimize solutions for LNS
SearchLimit* const fail_limit = solver.MakeLimit(kint64max, kint64max,
FLAGS_sublimit, kint64max);
DecisionBuilder* const subdecision_builder =
solver.MakeSolveOnce(first_solution, fail_limit);
vector<LocalSearchOperator*> localSearchOperators;
// Apply RandomLNS to free FLAGS_freevar variables at each stage
localSearchOperators.push_back(
solver.RevAlloc(new OrderedLNS(matrix, FLAGS_freevar)));
// Go through all possible permutations one by one
localSearchOperators.push_back(
solver.RevAlloc(new OrderedLNS(matrix, FLAGS_freeorderedvar)));
LocalSearchPhaseParameters* const ls_params =
solver.MakeLocalSearchPhaseParameters(
solver.ConcatenateOperators(localSearchOperators),
subdecision_builder);
DecisionBuilder* const second_phase =
solver.MakeLocalSearchPhase(matrix.data(),
matrix.size(),
first_solution,
ls_params);
// Try to find a solution
solver.Solve(second_phase,
collector,
log,
total_duplicates,
search_time_limit);
vector<int64> costas_matrix;
string output;
for (int n = 0; n < dim; ++n) {
const int64 v = collector->Value(0, vars[n]);
costas_matrix.push_back(v);
StringAppendF(&output, "%3lld", v);
}
if (!CheckCostas(costas_matrix)) {
LG << "No Costas Matrix found, closest solution displayed.";
}
LG << output;
}
// Computes a Costas Array.
void CostasHard(const int dim) {
SolverParameters parameters;
if (!FLAGS_export_profile.empty()) {
parameters.profile_level = SolverParameters::NORMAL_PROFILING;
}
Solver solver("costas", parameters);
// we need space for the matrix and for each pair
const int num_elements = dim + dim * (dim - 1) / 2;
// create the variables
vector<IntVar*> vars;
solver.MakeIntVarArray(num_elements, -dim, dim, "var", &vars);
vector<IntVar*> matrix(dim);
// Initialize the matrix that contains the coordinates of all '1' per row
for (int m = 0; m < dim; ++m) {
matrix[m] = vars[m];
vars[m]->SetMin(1);
}
solver.AddConstraint(solver.MakeAllDifferent(matrix, false));
int index = dim;
// Check that the pairwise difference is unique
for (int i = 1; i < dim; ++i) {
vector<IntVar*> subset(dim - i);
for (int j = 0; j < dim - i; ++j) {
IntVar* const diff = solver.MakeDifference(vars[j + i], vars[j])->Var();
vars[index++] = diff;
subset[j] = diff;
}
solver.AddConstraint(solver.MakeAllDifferent(subset, false));
}
DecisionBuilder* const db = solver.MakePhase(vars,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
solver.NewSearch(db);
if (solver.NextSolution()) {
vector<int64> costas_matrix;
string output;
for (int n = 0; n < dim; ++n) {
const int64 v = vars[n]->Value();
costas_matrix.push_back(v);
StringAppendF(&output, "%3lld", v);
}
LG << output << " (" << solver.wall_time() << "ms)";
CHECK(CheckCostas(costas_matrix)) <<
": Solution is not a valid Costas Matrix.";
} else {
LG << "No solution found.";
}
if (!FLAGS_export_profile.empty()) {
solver.ExportProfilingOverview(FLAGS_export_profile);
}
}
} // namespace operations_research
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
int min = 1;
int max = 10;
if (FLAGS_minsize != 0) {
min = FLAGS_minsize;
if (FLAGS_maxsize != 0) {
max = FLAGS_maxsize;
} else {
max = min;
}
}
for (int i = min; i <= max; ++i) {
LG << "Computing Costas Array for dim = " << i;
if (FLAGS_soft_constraints) {
operations_research::CostasSoft(i);
} else {
operations_research::CostasHard(i);
}
}
return 0;
}
<commit_msg>fix costas array on windows<commit_after>// Copyright 2010 Google
// 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.
//
// Costas Array Problem
//
// Finds an NxN matrix of 0s and 1s, with only one 1 per row,
// and one 1 per column, such that all displacement vectors
// between each pair of 1s are distinct.
//
// This example contains two separate implementations. CostasHard()
// uses hard constraints, whereas CostasSoft() uses a minimizer to
// minimize the number of duplicates.
#include <time.h>
#include "base/callback.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "constraint_solver/constraint_solveri.h"
#include "base/random.h"
DEFINE_int32(minsize, 0, "Minimum degree of Costas matrix.");
DEFINE_int32(maxsize, 0, "Maximum degree of Costas matrix.");
DEFINE_int32(freevar, 5, "Number of free variables.");
DEFINE_int32(freeorderedvar, 4, "Number of variables in ordered subset.");
DEFINE_int32(sublimit, 20, "Number of attempts per subtree.");
DEFINE_int32(timelimit, 120000, "Time limit for local search.");
DEFINE_bool(soft_constraints, false, "Use soft constraints.");
DEFINE_string(export_profile, "", "filename to save the profile overview");
namespace operations_research {
// Checks that all pairwise distances are unique and returns all violators
void CheckConstraintViolators(const vector<int64>& vars,
vector<int>* const violators) {
int dim = vars.size();
// Check that all indices are unique
for (int i = 0; i < dim; ++i) {
for (int k = i + 1; k < dim; ++k) {
if (vars[i] == vars[k]) {
violators->push_back(i);
violators->push_back(k);
}
}
}
// Check that all differences are unique for each level
for (int level = 1; level < dim; ++level) {
for (int i = 0; i < dim - level; ++i) {
const int difference = vars[i + level] - vars[i];
for (int k = i + 1; k < dim - level; ++k) {
if (difference == vars[k + level] - vars[k]) {
violators->push_back(k + level);
violators->push_back(k);
violators->push_back(i + level);
violators->push_back(i);
}
}
}
}
}
// Check that all pairwise differences are unique
bool CheckCostas(const vector<int64>& vars) {
vector<int> violators;
CheckConstraintViolators(vars, &violators);
return violators.empty();
}
// Cycles all possible permutations
class OrderedLNS: public BaseLNS {
public:
OrderedLNS(const vector<IntVar*>& vars, int free_elements) :
BaseLNS(vars.data(), vars.size()),
free_elements_(free_elements) {
index_ = 0;
// Start of with the first free_elements_ as a permutations, eg. 0,1,2,3,...
for (int i = 0; i < free_elements; ++i) {
index_ += i * pow(static_cast<double>(vars.size()),
free_elements - i - 1);
}
}
virtual bool NextFragment(vector<int>* const fragment) {
int dim = Size();
set<int> fragment_set;
do {
int work_index = index_;
fragment->clear();
fragment_set.clear();
for (int i = 0; i < free_elements_; ++i) {
int current_index = work_index % dim;
work_index = work_index / dim;
pair<set<int>::iterator, bool> ret = fragment_set.insert(current_index);
// Check if element has been used before
if (ret.second) {
fragment->push_back(current_index);
} else {
break;
}
}
// Go to next possible permutation
++index_;
// Try again if a duplicate index is used
} while (fragment_set.size() < free_elements_);
return true;
}
private:
int index_;
const int free_elements_;
};
// RandomLNS is used for the local search and frees the
// number of elements specified in 'free_elements' randomly.
class RandomLNS: public BaseLNS {
public:
RandomLNS(const vector<IntVar*>& vars, int free_elements) :
BaseLNS(vars.data(), vars.size()),
free_elements_(free_elements),
rand_(ACMRandom::HostnamePidTimeSeed()) {
}
virtual bool NextFragment(vector<int>* const fragment) {
vector<int> weighted_elements;
vector<int64> values;
// Create weighted vector for randomizer. Add one of each possible elements
// to the weighted vector and then add more elements depending on the
// number of conflicts
for (int i = 0; i < Size(); ++i) {
values.push_back(Value(i));
// Insert each variable at least once.
weighted_elements.push_back(i);
}
CheckConstraintViolators(values, &weighted_elements);
int size = weighted_elements.size();
// Randomly insert elements in vector until no more options remain
while (fragment->size() < min(free_elements_, size)) {
const int index = weighted_elements[rand_.Next() % size];
fragment->push_back(index);
// Remove all elements with this index from weighted_elements
for (vector<int>::iterator pos = weighted_elements.begin();
pos != weighted_elements.end(); ) {
if (*pos == index) {
// Try to erase as many elements as possible at the same time
vector<int>::iterator end = pos;
while ((end + 1) != weighted_elements.end() && *(end + 1) == *pos) {
++end;
}
pos = weighted_elements.erase(pos, end);
} else {
++pos;
}
}
size = weighted_elements.size();
}
return true;
}
private:
const int free_elements_;
ACMRandom rand_;
};
class Evaluator {
public:
explicit Evaluator(const vector<IntVar*>& vars) : vars_(vars) {}
// Prefer the value with the smallest domain
int64 VarEvaluator(int64 index) {
return vars_[index]->Size();
}
// Penalize for each time the value appears in a different domain,
// as values have to be unique
int64 ValueEvaluator(int64 id, int64 value) {
int appearance = 0;
for (int i = 0; i < vars_.size(); ++i) {
if (i != id && vars_[i]->Contains(value)) {
++appearance;
}
}
return appearance;
}
private:
vector<IntVar*> vars_;
};
// Computes a Costas Array using soft constraints.
// Instead of enforcing that all distance vectors are unique, we
// minimize the number of duplicate distance vectors.
void CostasSoft(const int dim) {
Solver solver("Costas");
// For the matrix and for the count of occurrences of each possible distance
// for each stage
const int num_elements = dim + (2 * dim + 1) * (dim);
// create the variables
vector<IntVar*> vars;
solver.MakeIntVarArray(num_elements, -dim, dim, "var_", &vars);
// the costas matrix
vector<IntVar*> matrix(dim);
// number of occurrences per stage
vector<IntVar*> occurences;
// All possible values of the distance vector
// used to count the occurrence of all these values
vector<int64> possible_values(2 * dim + 1);
for (int64 i = -dim; i <= dim; ++i) {
possible_values[i + dim] = i;
}
int index = 0;
// Initialize the matrix that contains the coordinates of all '1' per row
for (; index < dim; ++index) {
matrix[index] = vars[index];
vars[index]->SetMin(1);
}
// First constraint for the elements in the Costas Matrix. We want
// them to be unique.
vector<IntVar*> matrix_count;
solver.MakeIntVarArray(2 * dim + 1, 0, dim, "matrix_count_", &matrix_count);
solver.AddConstraint(solver.MakeDistribute(matrix, possible_values,
matrix_count));
// Here we only consider the elements from 1 to dim.
for (int64 j = dim + 1; j <= 2 * dim; ++j) {
// Penalize if an element occurs more than once.
vars[index]
= solver.MakeSemiContinuousExpr(solver.MakeSum(matrix_count[j], -1),
0, 1)->Var();
occurences.push_back(vars[index++]);
}
// Count the number of duplicates for each stage
for (int i = 1; i < dim; ++i) {
vector<IntVar*> subset(dim - i);
// Initialize each stage
for (int j = 0; j < dim - i; ++j) {
IntVar* const diff = solver.MakeDifference(vars[j + i], vars[j])->Var();
subset[j] = diff;
}
// Count the number of occurrences for all possible values
vector<IntVar*> domain_count;
solver.MakeIntVarArray(2 * dim + 1, 0, dim, "domain_count_", &domain_count);
solver.AddConstraint(solver.MakeDistribute(subset,
possible_values,
domain_count));
// Penalize occurrences of more than one
for (int64 j = 0; j <= 2 * dim; ++j) {
vars[index] =
solver.MakeSemiContinuousExpr(solver.MakeSum(domain_count[j], -1),
0, dim - i)->Var();
occurences.push_back(vars[index++]);
}
}
// We would like to minimize the penalties that we just computed
IntVar* const objective_var = solver.MakeSum(occurences)->Var();
OptimizeVar* const total_duplicates = solver.MakeMinimize(objective_var, 1);
SearchMonitor* const log = solver.MakeSearchLog(1000, objective_var);
// Out of all solutions, we just want to store the last one.
SolutionCollector* const collector = solver.MakeLastSolutionCollector();
collector->Add(vars);
// The first solution that the local optimization is based on
Evaluator evaluator(matrix);
DecisionBuilder* const first_solution =
solver.MakePhase(matrix,
NewPermanentCallback(&evaluator,
&Evaluator::VarEvaluator),
NewPermanentCallback(&evaluator,
&Evaluator::ValueEvaluator));
SearchLimit* const search_time_limit =
solver.MakeLimit(FLAGS_timelimit, kint64max, kint64max, kint64max);
// Locally optimize solutions for LNS
SearchLimit* const fail_limit = solver.MakeLimit(kint64max, kint64max,
FLAGS_sublimit, kint64max);
DecisionBuilder* const subdecision_builder =
solver.MakeSolveOnce(first_solution, fail_limit);
vector<LocalSearchOperator*> localSearchOperators;
// Apply RandomLNS to free FLAGS_freevar variables at each stage
localSearchOperators.push_back(
solver.RevAlloc(new OrderedLNS(matrix, FLAGS_freevar)));
// Go through all possible permutations one by one
localSearchOperators.push_back(
solver.RevAlloc(new OrderedLNS(matrix, FLAGS_freeorderedvar)));
LocalSearchPhaseParameters* const ls_params =
solver.MakeLocalSearchPhaseParameters(
solver.ConcatenateOperators(localSearchOperators),
subdecision_builder);
DecisionBuilder* const second_phase =
solver.MakeLocalSearchPhase(matrix.data(),
matrix.size(),
first_solution,
ls_params);
// Try to find a solution
solver.Solve(second_phase,
collector,
log,
total_duplicates,
search_time_limit);
vector<int64> costas_matrix;
string output;
for (int n = 0; n < dim; ++n) {
const int64 v = collector->Value(0, vars[n]);
costas_matrix.push_back(v);
StringAppendF(&output, "%3lld", v);
}
if (!CheckCostas(costas_matrix)) {
LG << "No Costas Matrix found, closest solution displayed.";
}
LG << output;
}
// Computes a Costas Array.
void CostasHard(const int dim) {
SolverParameters parameters;
if (!FLAGS_export_profile.empty()) {
parameters.profile_level = SolverParameters::NORMAL_PROFILING;
}
Solver solver("costas", parameters);
// we need space for the matrix and for each pair
const int num_elements = dim + dim * (dim - 1) / 2;
// create the variables
vector<IntVar*> vars;
solver.MakeIntVarArray(num_elements, -dim, dim, "var", &vars);
vector<IntVar*> matrix(dim);
// Initialize the matrix that contains the coordinates of all '1' per row
for (int m = 0; m < dim; ++m) {
matrix[m] = vars[m];
vars[m]->SetMin(1);
}
solver.AddConstraint(solver.MakeAllDifferent(matrix, false));
int index = dim;
// Check that the pairwise difference is unique
for (int i = 1; i < dim; ++i) {
vector<IntVar*> subset(dim - i);
for (int j = 0; j < dim - i; ++j) {
IntVar* const diff = solver.MakeDifference(vars[j + i], vars[j])->Var();
vars[index++] = diff;
subset[j] = diff;
}
solver.AddConstraint(solver.MakeAllDifferent(subset, false));
}
DecisionBuilder* const db = solver.MakePhase(vars,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
solver.NewSearch(db);
if (solver.NextSolution()) {
vector<int64> costas_matrix;
string output;
for (int n = 0; n < dim; ++n) {
const int64 v = vars[n]->Value();
costas_matrix.push_back(v);
StringAppendF(&output, "%3lld", v);
}
LG << output << " (" << solver.wall_time() << "ms)";
CHECK(CheckCostas(costas_matrix)) <<
": Solution is not a valid Costas Matrix.";
} else {
LG << "No solution found.";
}
if (!FLAGS_export_profile.empty()) {
solver.ExportProfilingOverview(FLAGS_export_profile);
}
}
} // namespace operations_research
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
int min = 1;
int max = 10;
if (FLAGS_minsize != 0) {
min = FLAGS_minsize;
if (FLAGS_maxsize != 0) {
max = FLAGS_maxsize;
} else {
max = min;
}
}
for (int i = min; i <= max; ++i) {
LG << "Computing Costas Array for dim = " << i;
if (FLAGS_soft_constraints) {
operations_research::CostasSoft(i);
} else {
operations_research::CostasHard(i);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include "../http_server.h"
using namespace mevent;
class HelloWorld {
public:
void Index(Connection *conn) {
conn->Resp()->SetHeader("Content-Type", "text/html");
conn->Resp()->WriteString("hello world!");
}
};
int main() {
HelloWorld hello;
HTTPServer *server = new HTTPServer();
server->SetHandler("/", std::bind(&::HelloWorld::Index, &hello, std::placeholders::_1));
server->SetWorkerThreads(4);
server->SetIdleTimeout(60);
server->SetMaxWorkerConnections(8192);
server->ListenAndServe("0.0.0.0", 80);
return 0;
}
<commit_msg>modify<commit_after>#include <stdio.h>
#include "../http_server.h"
using namespace mevent;
class HelloWorld {
public:
void Index(Connection *conn) {
conn->Resp()->SetHeader("Content-Type", "text/html");
conn->Resp()->WriteString("hello");
conn->Resp()->WriteString(" world!");
}
};
int main() {
HelloWorld hello;
HTTPServer *server = new HTTPServer();
server->SetHandler("/", std::bind(&::HelloWorld::Index, &hello, std::placeholders::_1));
server->SetWorkerThreads(4);
server->SetIdleTimeout(60);
server->SetMaxWorkerConnections(8192);
server->ListenAndServe("0.0.0.0", 80);
return 0;
}
<|endoftext|> |
<commit_before>#include <sstream>
#include <string>
#include <gtest/gtest.h>
#include "phpcxx/module.h"
#include "phpcxx/fcall.h"
#include "phpcxx/phpexception.h"
#include "phpcxx/parameters.h"
#include "phpcxx/function.h"
#include "testsapi.h"
#include "globals.h"
namespace {
class MyModule : public phpcxx::Module {
public:
using phpcxx::Module::Module;
protected:
virtual std::vector<phpcxx::Function> functions() override
{
return {
phpcxx::createFunction<&MyModule::test_simple_exception>("test_simple_exception"),
phpcxx::createFunction<&MyModule::test_nested_exception>("test_nested_exception")
};
}
static phpcxx::Value test_simple_exception()
{
bool exception_caught = false;
try {
phpcxx::call("throw_exception");
EXPECT_FALSE(1);
}
catch (const phpcxx::PhpException& e) {
exception_caught = true;
EXPECT_EQ("LogicException", e.className());
EXPECT_EQ(nullptr, e.previous());
EXPECT_EQ("Exception message", e.message());
EXPECT_EQ(123, e.code());
EXPECT_NE(phpcxx::string::npos, e.file().find("eval'd code"));
EXPECT_EQ(4, e.line());
EXPECT_STREQ(e.what(), e.message().c_str());
}
catch (const std::exception& e) {
EXPECT_FALSE(2);
}
EXPECT_EQ(nullptr, EG(exception));
return exception_caught;
}
static phpcxx::Value test_nested_exception()
{
bool exception_caught = false;
try {
phpcxx::call("throw_nested_exception");
EXPECT_FALSE(1);
}
catch (const phpcxx::PhpException& e) {
exception_caught = true;
EXPECT_EQ("Exception", e.className());
EXPECT_EQ("Top-level", e.message());
EXPECT_EQ(456, e.code());
EXPECT_NE(phpcxx::string::npos, e.file().find("eval'd code"));
EXPECT_EQ(8, e.line());
EXPECT_STREQ(e.what(), e.message().c_str());
EXPECT_NE(nullptr, e.previous());
const phpcxx::PhpException* p = e.previous();
if (p != nullptr) {
EXPECT_EQ("LogicException", p->className());
EXPECT_EQ(nullptr, p->previous());
EXPECT_EQ("Nested", p->message());
EXPECT_EQ(123, p->code());
EXPECT_NE(phpcxx::string::npos, p->file().find("eval'd code"));
EXPECT_EQ(5, p->line());
EXPECT_STREQ(p->what(), p->message().c_str());
}
phpcxx::Array trace;
trace = e.trace();
EXPECT_EQ(2, trace.size());
EXPECT_EQ(phpcxx::Type::Array, trace[0].type());
EXPECT_EQ(phpcxx::Type::Array, trace[1].type());
EXPECT_EQ("throw_nested_exception", trace[0]["function"].toString());
EXPECT_EQ("test_nested_exception", trace[1]["function"].toString());
try {
throw;
}
catch (phpcxx::PhpException& e) {
EXPECT_EQ("Exception", e.className());
EXPECT_EQ("Top-level", e.message());
EXPECT_EQ(456, e.code());
EXPECT_NE(phpcxx::string::npos, e.file().find("eval'd code"));
EXPECT_EQ(8, e.line());
EXPECT_STREQ(e.what(), e.message().c_str());
EXPECT_NE(nullptr, e.previous());
const phpcxx::PhpException* p = e.previous();
if (p != nullptr) {
EXPECT_EQ("LogicException", p->className());
EXPECT_EQ(nullptr, p->previous());
EXPECT_EQ("Nested", p->message());
EXPECT_EQ(123, p->code());
EXPECT_NE(phpcxx::string::npos, p->file().find("eval'd code"));
EXPECT_EQ(5, p->line());
EXPECT_STREQ(p->what(), p->message().c_str());
}
phpcxx::Array trace;
trace = e.trace();
EXPECT_EQ(2, trace.size());
EXPECT_EQ(phpcxx::Type::Array, trace[0].type());
EXPECT_EQ(phpcxx::Type::Array, trace[1].type());
EXPECT_EQ("throw_nested_exception", trace[0]["function"].toString());
EXPECT_EQ("test_nested_exception", trace[1]["function"].toString());
phpcxx::PhpException x(std::move(e));
EXPECT_EQ("Exception", x.className());
EXPECT_EQ("Top-level", x.message());
EXPECT_EQ(456, x.code());
EXPECT_NE(phpcxx::string::npos, x.file().find("eval'd code"));
EXPECT_EQ(8, x.line());
}
}
catch (const std::exception& e) {
EXPECT_FALSE(2);
}
EXPECT_EQ(nullptr, EG(exception));
return exception_caught;
}
};
}
TEST(PhpException, TestSimpleException)
{
MyModule module("PhpException", "0.0");
std::stringstream out;
std::stringstream err;
{
TestSAPI sapi(out, err);
sapi.addModule(module);
sapi.initialize();
sapi.run([&err] {
runPhpCode(R"___(
function throw_exception()
{
throw new LogicException("Exception message", 123);
}
)___"
);
phpcxx::Value res = phpcxx::call("test_simple_exception");
EXPECT_EQ(phpcxx::Type::True, res.type());
err << "SUCCESS" << std::flush;
});
}
std::string o = out.str(); out.str("");
std::string e = err.str(); err.str("");
EXPECT_EQ("", o);
EXPECT_EQ("SUCCESS", e);
}
TEST(PhpException, TestNestedException)
{
MyModule module("PhpException", "0.0");
std::stringstream out;
std::stringstream err;
{
TestSAPI sapi(out, err);
sapi.addModule(module);
sapi.initialize();
sapi.run([&err] {
runPhpCode(R"___(
function throw_nested_exception()
{
try {
throw new LogicException("Nested", 123);
}
catch (Exception $e) {
throw new Exception("Top-level", 456, $e);
}
}
)___"
);
phpcxx::Value res = phpcxx::call("test_nested_exception");
EXPECT_EQ(phpcxx::Type::True, res.type());
err << "SUCCESS" << std::flush;
});
}
std::string o = out.str(); out.str("");
std::string e = err.str(); err.str("");
EXPECT_EQ("", o);
EXPECT_EQ("SUCCESS", e);
}
TEST(PhpException, TestInvalidArguments)
{
MyModule module("PhpException", "0.0");
std::stringstream out;
std::stringstream err;
{
TestSAPI sapi(out, err);
sapi.addModule(module);
sapi.initialize();
sapi.run([&err] {
ASSERT_EQ(nullptr, EG(exception));
ASSERT_THROW(phpcxx::PhpException(), std::logic_error);
err << "SUCCESS" << std::flush;
});
}
std::string o = out.str(); out.str("");
std::string e = err.str(); err.str("");
EXPECT_EQ("", o);
EXPECT_EQ("SUCCESS", e);
}
<commit_msg>More assertions<commit_after>#include <sstream>
#include <string>
#include <gtest/gtest.h>
#include "phpcxx/module.h"
#include "phpcxx/fcall.h"
#include "phpcxx/phpexception.h"
#include "phpcxx/parameters.h"
#include "phpcxx/function.h"
#include "testsapi.h"
#include "globals.h"
namespace {
class MyModule : public phpcxx::Module {
public:
using phpcxx::Module::Module;
protected:
virtual std::vector<phpcxx::Function> functions() override
{
return {
phpcxx::createFunction<&MyModule::test_simple_exception>("test_simple_exception"),
phpcxx::createFunction<&MyModule::test_nested_exception>("test_nested_exception")
};
}
static phpcxx::Value test_simple_exception()
{
bool exception_caught = false;
try {
phpcxx::call("throw_exception");
EXPECT_FALSE(1);
}
catch (const phpcxx::PhpException& e) {
exception_caught = true;
EXPECT_EQ("LogicException", e.className());
EXPECT_EQ(nullptr, e.previous());
EXPECT_EQ("Exception message", e.message());
EXPECT_EQ(123, e.code());
EXPECT_NE(phpcxx::string::npos, e.file().find("eval'd code"));
EXPECT_EQ(4, e.line());
EXPECT_STREQ(e.what(), e.message().c_str());
}
catch (const std::exception& e) {
EXPECT_FALSE(2);
}
EXPECT_EQ(nullptr, EG(exception));
return exception_caught;
}
static phpcxx::Value test_nested_exception()
{
bool exception_caught = false;
try {
phpcxx::call("throw_nested_exception");
EXPECT_FALSE(1);
}
catch (const phpcxx::PhpException& e) {
exception_caught = true;
EXPECT_EQ("Exception", e.className());
EXPECT_EQ("Top-level", e.message());
EXPECT_EQ(456, e.code());
EXPECT_NE(phpcxx::string::npos, e.file().find("eval'd code"));
EXPECT_EQ(8, e.line());
EXPECT_STREQ(e.what(), e.message().c_str());
EXPECT_NE(nullptr, e.previous());
const phpcxx::PhpException* p = e.previous();
if (p != nullptr) {
EXPECT_EQ("LogicException", p->className());
EXPECT_EQ(nullptr, p->previous());
EXPECT_EQ("Nested", p->message());
EXPECT_EQ(123, p->code());
EXPECT_NE(phpcxx::string::npos, p->file().find("eval'd code"));
EXPECT_EQ(5, p->line());
EXPECT_STREQ(p->what(), p->message().c_str());
}
phpcxx::Array trace;
trace = e.trace();
EXPECT_EQ(2, trace.size());
EXPECT_EQ(phpcxx::Type::Array, trace[0].type());
EXPECT_EQ(phpcxx::Type::Array, trace[1].type());
EXPECT_EQ("throw_nested_exception", trace[0]["function"].toString());
EXPECT_EQ("test_nested_exception", trace[1]["function"].toString());
try {
throw;
}
catch (phpcxx::PhpException& f) {
EXPECT_TRUE(EG(exception) != nullptr);
EXPECT_EQ("Exception", f.className());
EXPECT_EQ("Top-level", f.message());
EXPECT_EQ(456, f.code());
EXPECT_NE(phpcxx::string::npos, f.file().find("eval'd code"));
EXPECT_EQ(8, f.line());
EXPECT_STREQ(f.what(), f.message().c_str());
EXPECT_NE(nullptr, f.previous());
const phpcxx::PhpException* p = f.previous();
if (p != nullptr) {
EXPECT_EQ("LogicException", p->className());
EXPECT_EQ(nullptr, p->previous());
EXPECT_EQ("Nested", p->message());
EXPECT_EQ(123, p->code());
EXPECT_NE(phpcxx::string::npos, p->file().find("eval'd code"));
EXPECT_EQ(5, p->line());
EXPECT_STREQ(p->what(), p->message().c_str());
}
phpcxx::Array trace;
trace = f.trace();
EXPECT_EQ(2, trace.size());
EXPECT_EQ(phpcxx::Type::Array, trace[0].type());
EXPECT_EQ(phpcxx::Type::Array, trace[1].type());
EXPECT_EQ("throw_nested_exception", trace[0]["function"].toString());
EXPECT_EQ("test_nested_exception", trace[1]["function"].toString());
}
// `throw;` rethrew the original object,
// the destructor of the exception was NOT called
EXPECT_FALSE(EG(exception) == nullptr);
// Test move constructor
try {
throw;
}
catch (phpcxx::PhpException& z) { // catch by non-const reference so that we can move
phpcxx::PhpException x(std::move(z));
EXPECT_EQ("Exception", x.className());
EXPECT_EQ("Top-level", x.message());
EXPECT_EQ(456, x.code());
EXPECT_NE(phpcxx::string::npos, x.file().find("eval'd code"));
EXPECT_EQ(8, x.line());
}
}
catch (const std::exception& e) {
EXPECT_FALSE(2);
}
EXPECT_EQ(nullptr, EG(exception));
return exception_caught;
}
};
}
TEST(PhpException, TestSimpleException)
{
MyModule module("PhpException", "0.0");
std::stringstream out;
std::stringstream err;
{
TestSAPI sapi(out, err);
sapi.addModule(module);
sapi.initialize();
sapi.run([&err] {
runPhpCode(R"___(
function throw_exception()
{
throw new LogicException("Exception message", 123);
}
)___"
);
phpcxx::Value res = phpcxx::call("test_simple_exception");
EXPECT_EQ(phpcxx::Type::True, res.type());
err << "SUCCESS" << std::flush;
});
}
std::string o = out.str(); out.str("");
std::string e = err.str(); err.str("");
EXPECT_EQ("", o);
EXPECT_EQ("SUCCESS", e);
}
TEST(PhpException, TestNestedException)
{
MyModule module("PhpException", "0.0");
std::stringstream out;
std::stringstream err;
{
TestSAPI sapi(out, err);
sapi.addModule(module);
sapi.initialize();
sapi.run([&err] {
runPhpCode(R"___(
function throw_nested_exception()
{
try {
throw new LogicException("Nested", 123);
}
catch (Exception $e) {
throw new Exception("Top-level", 456, $e);
}
}
)___"
);
phpcxx::Value res = phpcxx::call("test_nested_exception");
EXPECT_EQ(phpcxx::Type::True, res.type());
err << "SUCCESS" << std::flush;
});
}
std::string o = out.str(); out.str("");
std::string e = err.str(); err.str("");
EXPECT_EQ("", o);
EXPECT_EQ("SUCCESS", e);
}
TEST(PhpException, TestInvalidArguments)
{
MyModule module("PhpException", "0.0");
std::stringstream out;
std::stringstream err;
{
TestSAPI sapi(out, err);
sapi.addModule(module);
sapi.initialize();
sapi.run([&err] {
ASSERT_EQ(nullptr, EG(exception));
ASSERT_THROW(phpcxx::PhpException(), std::logic_error);
err << "SUCCESS" << std::flush;
});
}
std::string o = out.str(); out.str("");
std::string e = err.str(); err.str("");
EXPECT_EQ("", o);
EXPECT_EQ("SUCCESS", e);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DResultSet.cxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:23:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _COM_SUN_STAR_SDBCX_COMPAREBOOKMARK_HPP_
#include <com/sun/star/sdbcx/CompareBookmark.hpp>
#endif
#ifndef _CONNECTIVITY_DBASE_DRESULTSET_HXX_
#include "dbase/DResultSet.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CONNECTIVITY_DBASE_INDEX_HXX_
#include "dbase/DIndex.hxx"
#endif
#ifndef _CONNECTIVITY_DBASE_INDEXITER_HXX_
#include "dbase/DIndexIter.hxx"
#endif
#ifndef CONNECTIVITY_DBASE_DCODE_HXX
#include "dbase/DCode.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity::dbase;
using namespace connectivity::file;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
// using namespace com::sun::star::container;
// using namespace com::sun::star::util;
//------------------------------------------------------------------------------
ODbaseResultSet::ODbaseResultSet( OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator)
: file::OResultSet(pStmt,_aSQLIterator)
,m_bBookmarkable(sal_True)
{
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE), PROPERTY_ID_ISBOOKMARKABLE, PropertyAttribute::READONLY,&m_bBookmarkable, ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODbaseResultSet::getImplementationName( ) throw ( RuntimeException)
{
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.dbase.ResultSet");
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL ODbaseResultSet::getSupportedServiceNames( ) throw( RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(2);
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.ResultSet");
aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ResultSet");
return aSupported;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::supportsService( const ::rtl::OUString& _rServiceName ) throw( RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
// -------------------------------------------------------------------------
Any SAL_CALL ODbaseResultSet::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODbaseResultSet_BASE::queryInterface(rType);
return aRet.hasValue() ? aRet : OResultSet::queryInterface(rType);
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL ODbaseResultSet::getTypes( ) throw( RuntimeException)
{
return ::comphelper::concatSequences(OResultSet::getTypes(),ODbaseResultSet_BASE::getTypes());
}
// -------------------------------------------------------------------------
// XRowLocate
Any SAL_CALL ODbaseResultSet::getBookmark( ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
OSL_ENSURE((m_bShowDeleted || !m_aRow->isDeleted()),"getBookmark called for deleted row");
return makeAny((sal_Int32)(*m_aRow)[0]->getValue());
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::moveToBookmark( const Any& bookmark ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;
return m_pTable ? Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_True) : sal_False;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::moveRelativeToBookmark( const Any& bookmark, sal_Int32 rows ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
if(!m_pTable)
return sal_False;
Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_False);
return relative(rows);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL ODbaseResultSet::compareBookmarks( const Any& lhs, const Any& rhs ) throw( SQLException, RuntimeException)
{
sal_Int32 nFirst(0),nSecond(0),nResult(0);
if ( !( lhs >>= nFirst ) || !( rhs >>= nSecond ) )
::dbtools::throwSQLException( "XRowLocate::compareBookmarks: Invalid bookmark value", "HY111", *this );
// have a look at CompareBookmark
// we can't use the names there because we already have defines with the same name from the parser
if(nFirst < nSecond)
nResult = -1;
else if(nFirst > nSecond)
nResult = 1;
else
nResult = 0;
return nResult;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::hasOrderedBookmarks( ) throw( SQLException, RuntimeException)
{
return sal_True;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL ODbaseResultSet::hashBookmark( const Any& bookmark ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
return comphelper::getINT32(bookmark);
}
// -------------------------------------------------------------------------
// XDeleteRows
Sequence< sal_Int32 > SAL_CALL ODbaseResultSet::deleteRows( const Sequence< Any >& /*rows*/ ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
::dbtools::throwFeatureNotImplementedException( "XDeleteRows::deleteRows", *this );
return Sequence< sal_Int32 >();
}
// -------------------------------------------------------------------------
sal_Bool ODbaseResultSet::fillIndexValues(const Reference< XColumnsSupplier> &_xIndex)
{
Reference<XUnoTunnel> xTunnel(_xIndex,UNO_QUERY);
if(xTunnel.is())
{
dbase::ODbaseIndex* pIndex = reinterpret_cast< dbase::ODbaseIndex* >( xTunnel->getSomething(dbase::ODbaseIndex::getUnoTunnelImplementationId()) );
if(pIndex)
{
dbase::OIndexIterator* pIter = pIndex->createIterator(NULL,NULL);
if (pIter)
{
sal_uInt32 nRec = pIter->First();
while (nRec != SQL_COLUMN_NOTFOUND)
{
if (m_aOrderbyAscending[0])
m_pFileSet->push_back(nRec);
else
m_pFileSet->insert(m_pFileSet->begin(),nRec);
nRec = pIter->Next();
}
m_pFileSet->setFrozen();
// if(!bDistinct)
// SetRowCount(pFileSet->count());
delete pIter;
return sal_True;
}
delete pIter;
}
}
return sal_False;
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & ODbaseResultSet::getInfoHelper()
{
return *ODbaseResultSet_BASE3::getArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ODbaseResultSet::createArrayHelper() const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODbaseResultSet::acquire() throw()
{
ODbaseResultSet_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODbaseResultSet::release() throw()
{
ODbaseResultSet_BASE2::release();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL ODbaseResultSet::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
OSQLAnalyzer* ODbaseResultSet::createAnalyzer()
{
return new OFILEAnalyzer();
}
// -----------------------------------------------------------------------------
sal_Int32 ODbaseResultSet::getCurrentFilePos() const
{
return m_pTable->getFilePos();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.24.216); FILE MERGED 2008/04/01 15:08:40 thb 1.24.216.3: #i85898# Stripping all external header guards 2008/04/01 10:52:53 thb 1.24.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:29 rt 1.24.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DResultSet.cxx,v $
* $Revision: 1.25 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include <com/sun/star/sdbcx/CompareBookmark.hpp>
#include "dbase/DResultSet.hxx"
#include <com/sun/star/lang/DisposedException.hpp>
#include <comphelper/sequence.hxx>
#include "dbase/DIndex.hxx"
#include "dbase/DIndexIter.hxx"
#include "dbase/DCode.hxx"
#include <comphelper/types.hxx>
#include <connectivity/dbexception.hxx>
using namespace ::comphelper;
using namespace connectivity::dbase;
using namespace connectivity::file;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
// using namespace com::sun::star::container;
// using namespace com::sun::star::util;
//------------------------------------------------------------------------------
ODbaseResultSet::ODbaseResultSet( OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator)
: file::OResultSet(pStmt,_aSQLIterator)
,m_bBookmarkable(sal_True)
{
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE), PROPERTY_ID_ISBOOKMARKABLE, PropertyAttribute::READONLY,&m_bBookmarkable, ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODbaseResultSet::getImplementationName( ) throw ( RuntimeException)
{
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.dbase.ResultSet");
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL ODbaseResultSet::getSupportedServiceNames( ) throw( RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(2);
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.ResultSet");
aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ResultSet");
return aSupported;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::supportsService( const ::rtl::OUString& _rServiceName ) throw( RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
// -------------------------------------------------------------------------
Any SAL_CALL ODbaseResultSet::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODbaseResultSet_BASE::queryInterface(rType);
return aRet.hasValue() ? aRet : OResultSet::queryInterface(rType);
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL ODbaseResultSet::getTypes( ) throw( RuntimeException)
{
return ::comphelper::concatSequences(OResultSet::getTypes(),ODbaseResultSet_BASE::getTypes());
}
// -------------------------------------------------------------------------
// XRowLocate
Any SAL_CALL ODbaseResultSet::getBookmark( ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
OSL_ENSURE((m_bShowDeleted || !m_aRow->isDeleted()),"getBookmark called for deleted row");
return makeAny((sal_Int32)(*m_aRow)[0]->getValue());
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::moveToBookmark( const Any& bookmark ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;
return m_pTable ? Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_True) : sal_False;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::moveRelativeToBookmark( const Any& bookmark, sal_Int32 rows ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
if(!m_pTable)
return sal_False;
Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_False);
return relative(rows);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL ODbaseResultSet::compareBookmarks( const Any& lhs, const Any& rhs ) throw( SQLException, RuntimeException)
{
sal_Int32 nFirst(0),nSecond(0),nResult(0);
if ( !( lhs >>= nFirst ) || !( rhs >>= nSecond ) )
::dbtools::throwSQLException( "XRowLocate::compareBookmarks: Invalid bookmark value", "HY111", *this );
// have a look at CompareBookmark
// we can't use the names there because we already have defines with the same name from the parser
if(nFirst < nSecond)
nResult = -1;
else if(nFirst > nSecond)
nResult = 1;
else
nResult = 0;
return nResult;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL ODbaseResultSet::hasOrderedBookmarks( ) throw( SQLException, RuntimeException)
{
return sal_True;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL ODbaseResultSet::hashBookmark( const Any& bookmark ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
return comphelper::getINT32(bookmark);
}
// -------------------------------------------------------------------------
// XDeleteRows
Sequence< sal_Int32 > SAL_CALL ODbaseResultSet::deleteRows( const Sequence< Any >& /*rows*/ ) throw( SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OResultSet_BASE::rBHelper.bDisposed);
::dbtools::throwFeatureNotImplementedException( "XDeleteRows::deleteRows", *this );
return Sequence< sal_Int32 >();
}
// -------------------------------------------------------------------------
sal_Bool ODbaseResultSet::fillIndexValues(const Reference< XColumnsSupplier> &_xIndex)
{
Reference<XUnoTunnel> xTunnel(_xIndex,UNO_QUERY);
if(xTunnel.is())
{
dbase::ODbaseIndex* pIndex = reinterpret_cast< dbase::ODbaseIndex* >( xTunnel->getSomething(dbase::ODbaseIndex::getUnoTunnelImplementationId()) );
if(pIndex)
{
dbase::OIndexIterator* pIter = pIndex->createIterator(NULL,NULL);
if (pIter)
{
sal_uInt32 nRec = pIter->First();
while (nRec != SQL_COLUMN_NOTFOUND)
{
if (m_aOrderbyAscending[0])
m_pFileSet->push_back(nRec);
else
m_pFileSet->insert(m_pFileSet->begin(),nRec);
nRec = pIter->Next();
}
m_pFileSet->setFrozen();
// if(!bDistinct)
// SetRowCount(pFileSet->count());
delete pIter;
return sal_True;
}
delete pIter;
}
}
return sal_False;
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & ODbaseResultSet::getInfoHelper()
{
return *ODbaseResultSet_BASE3::getArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ODbaseResultSet::createArrayHelper() const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
void SAL_CALL ODbaseResultSet::acquire() throw()
{
ODbaseResultSet_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL ODbaseResultSet::release() throw()
{
ODbaseResultSet_BASE2::release();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL ODbaseResultSet::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
OSQLAnalyzer* ODbaseResultSet::createAnalyzer()
{
return new OFILEAnalyzer();
}
// -----------------------------------------------------------------------------
sal_Int32 ODbaseResultSet::getCurrentFilePos() const
{
return m_pTable->getFilePos();
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
#include <functional>
#include <type_traits>
namespace iter {
//Forward declarations of Accumulator and accumulate
template <typename Container, typename AccumulateFunc>
class Accumulator;
template <typename Container, typename AccumulateFunc>
Accumulator<Container, AccumulateFunc> accumulate(
Container&&, AccumulateFunc);
template <typename T, typename AccumulateFunc>
Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate(
std::initializer_list<T>, AccumulateFunc);
template <typename Container, typename AccumulateFunc>
class Accumulator {
private:
Container container;
AccumulateFunc accumulate_func;
friend Accumulator accumulate<Container, AccumulateFunc>(
Container&&, AccumulateFunc);
template <typename T, typename AF>
friend Accumulator<std::initializer_list<T>, AF> accumulate(
std::initializer_list<T>, AF);
// AccumVal must be default constructible
using AccumVal =
typename std::remove_reference<
typename std::result_of<AccumulateFunc(
iterator_deref<Container>,
iterator_deref<Container>)>::type>::type;
static_assert(
std::is_default_constructible<AccumVal>::value,
"Cannot accumulate a non-default constructible type");
Accumulator(Container container, AccumulateFunc accumulate_func)
: container(std::forward<Container>(container)),
accumulate_func(accumulate_func)
{ }
public:
class Iterator
: public std::iterator<std::forward_iterator_tag, AccumVal>
{
private:
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
AccumulateFunc accumulate_func;
AccumVal acc_val;
public:
Iterator (iterator_type<Container> iter,
iterator_type<Container> end,
AccumulateFunc accumulate_func)
: sub_iter{iter},
sub_end{end},
accumulate_func(accumulate_func),
// only get first value if not an end iterator
acc_val(!(iter != end) ? AccumVal{} : *iter)
{ }
const AccumVal& operator*() const {
return this->acc_val;
}
Iterator& operator++() {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
this->acc_val = accumulate_func(
this->acc_val, *this->sub_iter);
}
return *this;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->accumulate_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->accumulate_func};
}
};
// Helper function to instantiate an Accumulator
template <typename Container, typename AccumulateFunc>
Accumulator<Container, AccumulateFunc> accumulate(
Container&& container,
AccumulateFunc accumulate_func)
{
return {std::forward<Container>(container), accumulate_func};
}
template <typename Container>
auto accumulate(Container&& container) ->
decltype(accumulate(std::forward<Container>(container),
std::plus<typename std::remove_reference<
iterator_deref<Container>>::type>{}))
{
return accumulate(std::forward<Container>(container),
std::plus<typename std::remove_reference<
iterator_deref<Container>>::type>{});
}
template <typename T, typename AccumulateFunc>
Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate(
std::initializer_list<T> il,
AccumulateFunc accumulate_func)
{
return {std::move(il), accumulate_func};
}
template <typename T>
auto accumulate(std::initializer_list<T> il) ->
decltype(accumulate(std::move(il), std::plus<T>{}))
{
return accumulate(std::move(il), std::plus<T>{});
}
}
#endif //ifndef ITER_ACCUMULATE_H_
<commit_msg>accumulate iterators are input not forward<commit_after>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
#include <functional>
#include <type_traits>
namespace iter {
//Forward declarations of Accumulator and accumulate
template <typename Container, typename AccumulateFunc>
class Accumulator;
template <typename Container, typename AccumulateFunc>
Accumulator<Container, AccumulateFunc> accumulate(
Container&&, AccumulateFunc);
template <typename T, typename AccumulateFunc>
Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate(
std::initializer_list<T>, AccumulateFunc);
template <typename Container, typename AccumulateFunc>
class Accumulator {
private:
Container container;
AccumulateFunc accumulate_func;
friend Accumulator accumulate<Container, AccumulateFunc>(
Container&&, AccumulateFunc);
template <typename T, typename AF>
friend Accumulator<std::initializer_list<T>, AF> accumulate(
std::initializer_list<T>, AF);
// AccumVal must be default constructible
using AccumVal =
typename std::remove_reference<
typename std::result_of<AccumulateFunc(
iterator_deref<Container>,
iterator_deref<Container>)>::type>::type;
static_assert(
std::is_default_constructible<AccumVal>::value,
"Cannot accumulate a non-default constructible type");
Accumulator(Container container, AccumulateFunc accumulate_func)
: container(std::forward<Container>(container)),
accumulate_func(accumulate_func)
{ }
public:
class Iterator
: public std::iterator<std::input_iterator_tag, AccumVal>
{
private:
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
AccumulateFunc accumulate_func;
AccumVal acc_val;
public:
Iterator (iterator_type<Container> iter,
iterator_type<Container> end,
AccumulateFunc accumulate_func)
: sub_iter{iter},
sub_end{end},
accumulate_func(accumulate_func),
// only get first value if not an end iterator
acc_val(!(iter != end) ? AccumVal{} : *iter)
{ }
const AccumVal& operator*() const {
return this->acc_val;
}
Iterator& operator++() {
++this->sub_iter;
if (this->sub_iter != this->sub_end) {
this->acc_val = accumulate_func(
this->acc_val, *this->sub_iter);
}
return *this;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->accumulate_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->accumulate_func};
}
};
// Helper function to instantiate an Accumulator
template <typename Container, typename AccumulateFunc>
Accumulator<Container, AccumulateFunc> accumulate(
Container&& container,
AccumulateFunc accumulate_func)
{
return {std::forward<Container>(container), accumulate_func};
}
template <typename Container>
auto accumulate(Container&& container) ->
decltype(accumulate(std::forward<Container>(container),
std::plus<typename std::remove_reference<
iterator_deref<Container>>::type>{}))
{
return accumulate(std::forward<Container>(container),
std::plus<typename std::remove_reference<
iterator_deref<Container>>::type>{});
}
template <typename T, typename AccumulateFunc>
Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate(
std::initializer_list<T> il,
AccumulateFunc accumulate_func)
{
return {std::move(il), accumulate_func};
}
template <typename T>
auto accumulate(std::initializer_list<T> il) ->
decltype(accumulate(std::move(il), std::plus<T>{}))
{
return accumulate(std::move(il), std::plus<T>{});
}
}
#endif //ifndef ITER_ACCUMULATE_H_
<|endoftext|> |
<commit_before>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "internal/iterator_wrapper.hpp"
#include "internal/iterbase.hpp"
#include <functional>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
namespace iter {
namespace impl {
template <typename Container, typename AccumulateFunc>
class Accumulator;
using AccumulateFn = IterToolFnOptionalBindSecond<Accumulator, std::plus<>>;
}
constexpr impl::AccumulateFn accumulate{};
}
template <typename Container, typename AccumulateFunc>
class iter::impl::Accumulator {
private:
Container container_;
AccumulateFunc accumulate_func_;
friend AccumulateFn;
using AccumVal = std::remove_reference_t<std::result_of_t<AccumulateFunc(
iterator_deref<Container>, iterator_deref<Container>)>>;
Accumulator(Container&& container, AccumulateFunc accumulate_func)
: container_(std::forward<Container>(container)),
accumulate_func_(accumulate_func) {}
public:
Accumulator(Accumulator&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> {
private:
IteratorWrapper<Container> sub_iter_;
IteratorWrapper<Container> sub_end_;
AccumulateFunc* accumulate_func_;
std::unique_ptr<AccumVal> acc_val_;
public:
Iterator(IteratorWrapper<Container>&& sub_iter,
IteratorWrapper<Container>&& sub_end, AccumulateFunc& accumulate_fun)
: sub_iter_{std::move(sub_iter)},
sub_end_{std::move(sub_end)},
accumulate_func_(&accumulate_fun),
// only get first value if not an end iterator
acc_val_{
!(sub_iter_ != sub_end_) ? nullptr : new AccumVal(*sub_iter_)} {}
Iterator(const Iterator& other)
: sub_iter_{other.sub_iter_},
sub_end_{other.sub_end_},
accumulate_func_{other.accumulate_func_},
acc_val_{other.acc_val_ ? new AccumVal(*other.acc_val_) : nullptr} {}
Iterator& operator=(const Iterator& other) {
if (this == &other) {
return *this;
}
sub_iter_ = other.sub_iter_;
sub_end_ = other.sub_end_;
accumulate_func_ = other.accumulate_func_;
acc_val_.reset(other.acc_val_ ? new AccumVal(*other.acc_val_) : nullptr);
return *this;
}
Iterator(Iterator&&) = default;
Iterator& operator=(Iterator&&) = default;
const AccumVal& operator*() const {
return *acc_val_;
}
const AccumVal* operator->() const {
return acc_val_.get();
}
Iterator& operator++() {
++sub_iter_;
if (sub_iter_ != sub_end_) {
*acc_val_ = (*accumulate_func_)(*acc_val_, *sub_iter_);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return sub_iter_ != other.sub_iter_;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {get_begin(container_), get_end(container_), accumulate_func_};
}
Iterator end() {
return {get_end(container_), get_end(container_), accumulate_func_};
}
};
#endif
<commit_msg>Adds support for const iteration to accumulate<commit_after>#ifndef ITER_ACCUMULATE_H_
#define ITER_ACCUMULATE_H_
#include "internal/iterator_wrapper.hpp"
#include "internal/iterbase.hpp"
#include <functional>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
namespace iter {
namespace impl {
template <typename Container, typename AccumulateFunc>
class Accumulator;
using AccumulateFn = IterToolFnOptionalBindSecond<Accumulator, std::plus<>>;
}
constexpr impl::AccumulateFn accumulate{};
}
template <typename Container, typename AccumulateFunc>
class iter::impl::Accumulator {
private:
Container container_;
mutable AccumulateFunc accumulate_func_;
friend AccumulateFn;
using AccumVal = std::remove_reference_t<std::result_of_t<AccumulateFunc(
iterator_deref<Container>, iterator_deref<Container>)>>;
Accumulator(Container&& container, AccumulateFunc accumulate_func)
: container_(std::forward<Container>(container)),
accumulate_func_(accumulate_func) {}
public:
Accumulator(Accumulator&&) = default;
template <typename ContainerT>
class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> {
private:
template <typename>
friend class Iterator;
IteratorWrapper<ContainerT> sub_iter_;
IteratorWrapper<ContainerT> sub_end_;
AccumulateFunc* accumulate_func_;
std::unique_ptr<AccumVal> acc_val_;
public:
Iterator(IteratorWrapper<ContainerT>&& sub_iter,
IteratorWrapper<ContainerT>&& sub_end, AccumulateFunc& accumulate_fun)
: sub_iter_{std::move(sub_iter)},
sub_end_{std::move(sub_end)},
accumulate_func_(&accumulate_fun),
// only get first value if not an end iterator
acc_val_{
!(sub_iter_ != sub_end_) ? nullptr : new AccumVal(*sub_iter_)} {}
Iterator(const Iterator& other)
: sub_iter_{other.sub_iter_},
sub_end_{other.sub_end_},
accumulate_func_{other.accumulate_func_},
acc_val_{other.acc_val_ ? new AccumVal(*other.acc_val_) : nullptr} {}
Iterator& operator=(const Iterator& other) {
if (this == &other) {
return *this;
}
sub_iter_ = other.sub_iter_;
sub_end_ = other.sub_end_;
accumulate_func_ = other.accumulate_func_;
acc_val_.reset(other.acc_val_ ? new AccumVal(*other.acc_val_) : nullptr);
return *this;
}
Iterator(Iterator&&) = default;
Iterator& operator=(Iterator&&) = default;
const AccumVal& operator*() const {
return *acc_val_;
}
const AccumVal* operator->() const {
return acc_val_.get();
}
Iterator& operator++() {
++sub_iter_;
if (sub_iter_ != sub_end_) {
*acc_val_ = (*accumulate_func_)(*acc_val_, *sub_iter_);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
template <typename T>
bool operator!=(const Iterator<T>& other) const {
return sub_iter_ != other.sub_iter_;
}
template <typename T>
bool operator==(const Iterator<T>& other) const {
return !(*this != other);
}
};
Iterator<Container> begin() {
return {get_begin(container_), get_end(container_), accumulate_func_};
}
Iterator<Container> end() {
return {get_end(container_), get_end(container_), accumulate_func_};
}
Iterator<AsConst<Container>> begin() const {
return {get_begin(as_const(container_)), get_end(as_const(container_)),
accumulate_func_};
}
Iterator<AsConst<Container>> end() const {
return {get_end(as_const(container_)), get_end(as_const(container_)),
accumulate_func_};
}
};
#endif
<|endoftext|> |
<commit_before>#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/mesh_refinement.h>
#include <libmesh/remote_elem.h>
#include <libmesh/replicated_mesh.h>
#include <libmesh/auto_ptr.h> // libmesh_make_unique
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
class BoundaryMeshTest : public CppUnit::TestCase {
/**
* The goal of this test is to ensure that a 2D mesh generates
* boundary meshes correctly.
*/
public:
CPPUNIT_TEST_SUITE( BoundaryMeshTest );
#if LIBMESH_DIM > 1
CPPUNIT_TEST( testMesh );
#endif
CPPUNIT_TEST_SUITE_END();
protected:
std::unique_ptr<Mesh> _mesh;
std::unique_ptr<Mesh> _all_boundary_mesh;
std::unique_ptr<Mesh> _left_boundary_mesh;
std::unique_ptr<Mesh> _internal_boundary_mesh;
void build_mesh()
{
_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
_all_boundary_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
_left_boundary_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
_internal_boundary_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
MeshTools::Generation::build_square(*_mesh, 3, 5,
0.2, 0.8, 0.2, 0.7, QUAD9);
// We'll need to skip most repartitioning with DistributedMesh for
// now; otherwise the boundary meshes' interior parents might get
// shuffled off to different processors.
if (!_mesh->is_serial())
{
_mesh->skip_noncritical_partitioning(true);
_left_boundary_mesh->skip_noncritical_partitioning(true);
_all_boundary_mesh->skip_noncritical_partitioning(true);
_internal_boundary_mesh->skip_noncritical_partitioning(true);
}
// Set subdomain ids for specific elements. This allows us to later
// build an internal sideset with respect to a given
// subdomain. The element subdomains look like:
// ___________________
// | 2 | 2 | 2 |
// |_____|_____|_____|
// | 2 | 2 | 2 |
// |_____|_____|_____|
// | 2 | 2 | 2 |
// |_____|_____|_____|
// | 1 | 1 | 2 |
// |_____|_____|_____|
// | 1 | 1 | 2 |
// |_____|_____|_____|
//
// and we will create an internal sideset along the border between
// subdomains 1 and 2.
for (auto & elem : _mesh->active_element_ptr_range())
{
const Point c = elem->centroid();
if (c(0) < 0.6 && c(1) < 0.4)
elem->subdomain_id() = 1;
else
elem->subdomain_id() = 2;
}
// Get the border of the square
_mesh->get_boundary_info().sync(*_all_boundary_mesh);
std::set<boundary_id_type> left_id, right_id;
left_id.insert(3);
right_id.insert(1);
// Add the right side of the square to the square; this should
// make it a mixed dimension mesh
_mesh->get_boundary_info().add_elements(right_id, *_mesh);
_mesh->prepare_for_use();
// Add the left side of the square to its own boundary mesh.
_mesh->get_boundary_info().sync(left_id, *_left_boundary_mesh);
// We create an internal sideset ID that does not conflict with
// sidesets 0-3 that get created by build_square().
boundary_id_type bid = 5;
// To test the "relative to" feature, we add the same sides to the
// same sideset twice, from elements in subdomain 2 the second
// time. These should not show up in the BoundaryMesh, i.e. there
// should not be overlapped elems in the BoundaryMesh.
BoundaryInfo & bi = _mesh->get_boundary_info();
for (auto & elem : _mesh->active_element_ptr_range())
{
const Point c = elem->centroid();
if (c(0) < 0.6 && c(1) < 0.4)
{
if (c(0) > 0.4)
bi.add_side(elem, 1, bid);
if (c(1) > 0.3)
bi.add_side(elem, 2, bid);
}
else
{
if (c(0) < 0.75 && c(1) < 0.4)
bi.add_side(elem, 3, bid);
if (c(0) < 0.6 && c(1) < 0.5)
bi.add_side(elem, 0, bid);
}
}
// Create a BoundaryMesh from the internal sideset relative to subdomain 1.
{
std::set<boundary_id_type> requested_boundary_ids;
requested_boundary_ids.insert(bid);
std::set<subdomain_id_type> subdomains_relative_to;
subdomains_relative_to.insert(1);
_mesh->get_boundary_info().sync(requested_boundary_ids,
*_internal_boundary_mesh,
subdomains_relative_to);
}
}
public:
void setUp()
{
#if LIBMESH_DIM > 1
this->build_mesh();
#endif
}
void testMesh()
{
// There'd better be 3*5 + 5 elements in the interior plus right
// boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(20),
_mesh->n_elem());
// There'd better be only 7*11 nodes in the interior
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(77),
_mesh->n_nodes());
// There'd better be only 2*(3+5) elements on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(16),
_all_boundary_mesh->n_elem());
// There'd better be only 2*2*(3+5) nodes on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(32),
_all_boundary_mesh->n_nodes());
// There'd better be only 5 elements on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(5),
_left_boundary_mesh->n_elem());
// There'd better be only 2*5+1 nodes on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(11),
_left_boundary_mesh->n_nodes());
// There are only four elements in the internal sideset mesh.
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(4),
_internal_boundary_mesh->n_elem());
// There are 2*n_elem + 1 nodes in the internal sideset mesh.
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(9),
_internal_boundary_mesh->n_nodes());
this->sanityCheck();
}
void sanityCheck()
{
// Sanity check all the elements
for (const auto & elem : _mesh->active_element_ptr_range())
{
const Elem * pip = elem->dim() < 2 ? elem->interior_parent() : nullptr;
// On a DistributedMesh we might not be able to see the
// interior_parent of a non-local element
if (pip == remote_elem)
{
CPPUNIT_ASSERT(elem->processor_id() != TestCommWorld->rank());
continue;
}
// All the edges should have interior parents; none of the
// quads should.
if (pip)
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
CPPUNIT_ASSERT_EQUAL(pip->type(), QUAD9);
CPPUNIT_ASSERT_EQUAL(pip->level(), elem->level());
// We only added right edges
LIBMESH_ASSERT_FP_EQUAL(0.8, elem->centroid()(0),
TOLERANCE*TOLERANCE);
}
else
{
CPPUNIT_ASSERT_EQUAL(elem->type(), QUAD9);
}
}
for (const auto & elem : _left_boundary_mesh->active_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
const Elem * pip = elem->interior_parent();
// On a DistributedMesh we might not be able to see the
// interior_parent of a non-local element
if (pip == remote_elem)
{
CPPUNIT_ASSERT(elem->processor_id() != TestCommWorld->rank());
continue;
}
// All the edges should have interior parents
CPPUNIT_ASSERT(pip);
CPPUNIT_ASSERT_EQUAL(pip->type(), QUAD9);
CPPUNIT_ASSERT_EQUAL(pip->level(), elem->level());
// We only added left edges
LIBMESH_ASSERT_FP_EQUAL(0.2, elem->centroid()(0),
TOLERANCE*TOLERANCE);
}
for (const auto & elem : _left_boundary_mesh->active_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
const Elem * pip = elem->interior_parent();
// On a DistributedMesh we might not be able to see the
// interior_parent of a non-local element
if (pip == remote_elem)
{
CPPUNIT_ASSERT(elem->processor_id() != TestCommWorld->rank());
continue;
}
// All the edges should have interior parents
CPPUNIT_ASSERT(pip);
CPPUNIT_ASSERT_EQUAL(pip->type(), QUAD9);
CPPUNIT_ASSERT_EQUAL(pip->level(), elem->level());
}
// Sanity check for the internal sideset mesh.
for (const auto & elem : _internal_boundary_mesh->active_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
// All of the elements in the internal sideset mesh should
// have the same subdomain id as the parent Elems (i.e. 1)
// they came from.
CPPUNIT_ASSERT_EQUAL(static_cast<subdomain_id_type>(1),
elem->subdomain_id());
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( BoundaryMeshTest );
#ifdef LIBMESH_ENABLE_AMR
class BoundaryRefinedMeshTest : public BoundaryMeshTest {
/**
* The goal of this test is the same as the previous, but now we do a
* uniform refinement and make sure the result mesh is consistent. i.e.
* the new node shared between the 1D elements is the same as the node
* shared on the underlying quads, and so on.
*/
public:
CPPUNIT_TEST_SUITE( BoundaryRefinedMeshTest );
#if LIBMESH_DIM > 1
CPPUNIT_TEST( testMesh );
#endif
CPPUNIT_TEST_SUITE_END();
// Yes, this is necessary. Somewhere in those macros is a protected/private
public:
void setUp()
{
#if LIBMESH_DIM > 1
this->build_mesh();
// Need to refine interior mesh before separate boundary meshes,
// if we want to get interior_parent links right.
MeshRefinement(*_mesh).uniformly_refine(1);
MeshRefinement(*_left_boundary_mesh).uniformly_refine(1);
MeshRefinement(*_all_boundary_mesh).uniformly_refine(1);
#endif
}
void testMesh()
{
// There'd better be 3*5*4 + 5*2 active elements in the interior
// plus right boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(70),
_mesh->n_active_elem());
// Plus the original 20 now-inactive elements
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(90),
_mesh->n_elem());
// There'd better be only 13*21 nodes in the interior
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(273),
_mesh->n_nodes());
// There'd better be only 2*2*(3+5) active elements on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(32),
_all_boundary_mesh->n_active_elem());
// Plus the original 16 now-inactive elements
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(48),
_all_boundary_mesh->n_elem());
// There'd better be only 2*2*2*(3+5) nodes on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(64),
_all_boundary_mesh->n_nodes());
// There'd better be only 2*5 active elements on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(10),
_left_boundary_mesh->n_active_elem());
// Plus the original 5 now-inactive elements
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(15),
_left_boundary_mesh->n_elem());
// There'd better be only 2*2*5+1 nodes on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(21),
_left_boundary_mesh->n_nodes());
this->sanityCheck();
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( BoundaryRefinedMeshTest );
#endif
<commit_msg>Add unit test of parent side ids.<commit_after>#include <libmesh/mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/mesh_refinement.h>
#include <libmesh/remote_elem.h>
#include <libmesh/replicated_mesh.h>
#include <libmesh/auto_ptr.h> // libmesh_make_unique
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
class BoundaryMeshTest : public CppUnit::TestCase {
/**
* The goal of this test is to ensure that a 2D mesh generates
* boundary meshes correctly.
*/
public:
CPPUNIT_TEST_SUITE( BoundaryMeshTest );
#if LIBMESH_DIM > 1
CPPUNIT_TEST( testMesh );
#endif
CPPUNIT_TEST_SUITE_END();
protected:
std::unique_ptr<Mesh> _mesh;
std::unique_ptr<Mesh> _all_boundary_mesh;
std::unique_ptr<Mesh> _left_boundary_mesh;
std::unique_ptr<Mesh> _internal_boundary_mesh;
void build_mesh()
{
_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
_all_boundary_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
_left_boundary_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
_internal_boundary_mesh = libmesh_make_unique<Mesh>(*TestCommWorld);
MeshTools::Generation::build_square(*_mesh, 3, 5,
0.2, 0.8, 0.2, 0.7, QUAD9);
// We'll need to skip most repartitioning with DistributedMesh for
// now; otherwise the boundary meshes' interior parents might get
// shuffled off to different processors.
if (!_mesh->is_serial())
{
_mesh->skip_noncritical_partitioning(true);
_left_boundary_mesh->skip_noncritical_partitioning(true);
_all_boundary_mesh->skip_noncritical_partitioning(true);
_internal_boundary_mesh->skip_noncritical_partitioning(true);
}
// Set subdomain ids for specific elements. This allows us to later
// build an internal sideset with respect to a given
// subdomain. The element subdomains look like:
// ___________________
// | 2 | 2 | 2 |
// |_____|_____|_____|
// | 2 | 2 | 2 |
// |_____|_____|_____|
// | 2 | 2 | 2 |
// |_____|_____|_____|
// | 1 | 1 | 2 |
// |_____|_____|_____|
// | 1 | 1 | 2 |
// |_____|_____|_____|
//
// and we will create an internal sideset along the border between
// subdomains 1 and 2.
for (auto & elem : _mesh->active_element_ptr_range())
{
const Point c = elem->centroid();
if (c(0) < 0.6 && c(1) < 0.4)
elem->subdomain_id() = 1;
else
elem->subdomain_id() = 2;
}
// Get the border of the square
_mesh->get_boundary_info().sync(*_all_boundary_mesh);
// Check that the interior_parent side indices that we set on the
// BoundaryMesh as extra integers agree with the side returned
// by which_side_am_i().
unsigned int parent_side_index_tag =
_all_boundary_mesh->get_elem_integer_index("parent_side_index");
for (const auto & belem : _all_boundary_mesh->element_ptr_range())
{
dof_id_type parent_side_index =
belem->get_extra_integer(parent_side_index_tag);
CPPUNIT_ASSERT_EQUAL
(static_cast<dof_id_type>(belem->interior_parent()->which_side_am_i(belem)),
parent_side_index);
}
std::set<boundary_id_type> left_id, right_id;
left_id.insert(3);
right_id.insert(1);
// Add the right side of the square to the square; this should
// make it a mixed dimension mesh
_mesh->get_boundary_info().add_elements(right_id, *_mesh);
_mesh->prepare_for_use();
// Add the left side of the square to its own boundary mesh.
_mesh->get_boundary_info().sync(left_id, *_left_boundary_mesh);
// We create an internal sideset ID that does not conflict with
// sidesets 0-3 that get created by build_square().
boundary_id_type bid = 5;
// To test the "relative to" feature, we add the same sides to the
// same sideset twice, from elements in subdomain 2 the second
// time. These should not show up in the BoundaryMesh, i.e. there
// should not be overlapped elems in the BoundaryMesh.
BoundaryInfo & bi = _mesh->get_boundary_info();
for (auto & elem : _mesh->active_element_ptr_range())
{
const Point c = elem->centroid();
if (c(0) < 0.6 && c(1) < 0.4)
{
if (c(0) > 0.4)
bi.add_side(elem, 1, bid);
if (c(1) > 0.3)
bi.add_side(elem, 2, bid);
}
else
{
if (c(0) < 0.75 && c(1) < 0.4)
bi.add_side(elem, 3, bid);
if (c(0) < 0.6 && c(1) < 0.5)
bi.add_side(elem, 0, bid);
}
}
// Create a BoundaryMesh from the internal sideset relative to subdomain 1.
{
std::set<boundary_id_type> requested_boundary_ids;
requested_boundary_ids.insert(bid);
std::set<subdomain_id_type> subdomains_relative_to;
subdomains_relative_to.insert(1);
_mesh->get_boundary_info().sync(requested_boundary_ids,
*_internal_boundary_mesh,
subdomains_relative_to);
}
}
public:
void setUp()
{
#if LIBMESH_DIM > 1
this->build_mesh();
#endif
}
void testMesh()
{
// There'd better be 3*5 + 5 elements in the interior plus right
// boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(20),
_mesh->n_elem());
// There'd better be only 7*11 nodes in the interior
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(77),
_mesh->n_nodes());
// There'd better be only 2*(3+5) elements on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(16),
_all_boundary_mesh->n_elem());
// There'd better be only 2*2*(3+5) nodes on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(32),
_all_boundary_mesh->n_nodes());
// There'd better be only 5 elements on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(5),
_left_boundary_mesh->n_elem());
// There'd better be only 2*5+1 nodes on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(11),
_left_boundary_mesh->n_nodes());
// There are only four elements in the internal sideset mesh.
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(4),
_internal_boundary_mesh->n_elem());
// There are 2*n_elem + 1 nodes in the internal sideset mesh.
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(9),
_internal_boundary_mesh->n_nodes());
this->sanityCheck();
}
void sanityCheck()
{
// Sanity check all the elements
for (const auto & elem : _mesh->active_element_ptr_range())
{
const Elem * pip = elem->dim() < 2 ? elem->interior_parent() : nullptr;
// On a DistributedMesh we might not be able to see the
// interior_parent of a non-local element
if (pip == remote_elem)
{
CPPUNIT_ASSERT(elem->processor_id() != TestCommWorld->rank());
continue;
}
// All the edges should have interior parents; none of the
// quads should.
if (pip)
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
CPPUNIT_ASSERT_EQUAL(pip->type(), QUAD9);
CPPUNIT_ASSERT_EQUAL(pip->level(), elem->level());
// We only added right edges
LIBMESH_ASSERT_FP_EQUAL(0.8, elem->centroid()(0),
TOLERANCE*TOLERANCE);
}
else
{
CPPUNIT_ASSERT_EQUAL(elem->type(), QUAD9);
}
}
for (const auto & elem : _left_boundary_mesh->active_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
const Elem * pip = elem->interior_parent();
// On a DistributedMesh we might not be able to see the
// interior_parent of a non-local element
if (pip == remote_elem)
{
CPPUNIT_ASSERT(elem->processor_id() != TestCommWorld->rank());
continue;
}
// All the edges should have interior parents
CPPUNIT_ASSERT(pip);
CPPUNIT_ASSERT_EQUAL(pip->type(), QUAD9);
CPPUNIT_ASSERT_EQUAL(pip->level(), elem->level());
// We only added left edges
LIBMESH_ASSERT_FP_EQUAL(0.2, elem->centroid()(0),
TOLERANCE*TOLERANCE);
}
for (const auto & elem : _left_boundary_mesh->active_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
const Elem * pip = elem->interior_parent();
// On a DistributedMesh we might not be able to see the
// interior_parent of a non-local element
if (pip == remote_elem)
{
CPPUNIT_ASSERT(elem->processor_id() != TestCommWorld->rank());
continue;
}
// All the edges should have interior parents
CPPUNIT_ASSERT(pip);
CPPUNIT_ASSERT_EQUAL(pip->type(), QUAD9);
CPPUNIT_ASSERT_EQUAL(pip->level(), elem->level());
}
// Sanity check for the internal sideset mesh.
for (const auto & elem : _internal_boundary_mesh->active_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), EDGE3);
// All of the elements in the internal sideset mesh should
// have the same subdomain id as the parent Elems (i.e. 1)
// they came from.
CPPUNIT_ASSERT_EQUAL(static_cast<subdomain_id_type>(1),
elem->subdomain_id());
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( BoundaryMeshTest );
#ifdef LIBMESH_ENABLE_AMR
class BoundaryRefinedMeshTest : public BoundaryMeshTest {
/**
* The goal of this test is the same as the previous, but now we do a
* uniform refinement and make sure the result mesh is consistent. i.e.
* the new node shared between the 1D elements is the same as the node
* shared on the underlying quads, and so on.
*/
public:
CPPUNIT_TEST_SUITE( BoundaryRefinedMeshTest );
#if LIBMESH_DIM > 1
CPPUNIT_TEST( testMesh );
#endif
CPPUNIT_TEST_SUITE_END();
// Yes, this is necessary. Somewhere in those macros is a protected/private
public:
void setUp()
{
#if LIBMESH_DIM > 1
this->build_mesh();
// Need to refine interior mesh before separate boundary meshes,
// if we want to get interior_parent links right.
MeshRefinement(*_mesh).uniformly_refine(1);
MeshRefinement(*_left_boundary_mesh).uniformly_refine(1);
MeshRefinement(*_all_boundary_mesh).uniformly_refine(1);
#endif
}
void testMesh()
{
// There'd better be 3*5*4 + 5*2 active elements in the interior
// plus right boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(70),
_mesh->n_active_elem());
// Plus the original 20 now-inactive elements
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(90),
_mesh->n_elem());
// There'd better be only 13*21 nodes in the interior
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(273),
_mesh->n_nodes());
// There'd better be only 2*2*(3+5) active elements on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(32),
_all_boundary_mesh->n_active_elem());
// Plus the original 16 now-inactive elements
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(48),
_all_boundary_mesh->n_elem());
// There'd better be only 2*2*2*(3+5) nodes on the full boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(64),
_all_boundary_mesh->n_nodes());
// There'd better be only 2*5 active elements on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(10),
_left_boundary_mesh->n_active_elem());
// Plus the original 5 now-inactive elements
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(15),
_left_boundary_mesh->n_elem());
// There'd better be only 2*2*5+1 nodes on the left boundary
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(21),
_left_boundary_mesh->n_nodes());
this->sanityCheck();
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( BoundaryRefinedMeshTest );
#endif
<|endoftext|> |
<commit_before>#include "config/Base.hh"
#include "containers/PointCloud.hh"
#include "tests/Base.hh"
#include <iostream>
#include <string>
#include <vector>
using namespace aleph;
template <class T> void testFormats()
{
ALEPH_TEST_BEGIN( "Point cloud formats" );
using PointCloud = PointCloud<T>;
std::vector<PointCloud> pointClouds;
pointClouds.reserve( 4 );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_colon_separated.txt" ) ) );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_comma_separated.txt" ) ) );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_space_separated.txt" ) ) );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_tab_separated.txt" ) ) );
for( auto&& pc : pointClouds )
{
ALEPH_ASSERT_THROW( pc.size() == 150 );
ALEPH_ASSERT_THROW( pc.dimension() == 4 );
ALEPH_ASSERT_THROW( pc.empty() == false );
}
for( auto&& pc1 : pointClouds )
for( auto&& pc2 : pointClouds )
ALEPH_ASSERT_THROW( pc1 == pc2 );
ALEPH_TEST_END;
}
template <class T> void testAccess()
{
ALEPH_TEST_BEGIN( "Point cloud access" );
auto pc
= load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_comma_separated.txt" ) );
{
std::vector<T> actual;
std::vector<T> expected = { static_cast<T>( 5.9 ),
static_cast<T>( 3.0 ),
static_cast<T>( 5.1 ),
static_cast<T>( 1.8 ) };
pc.get( 149, std::back_inserter( actual ) );
ALEPH_ASSERT_THROW( actual == expected );
}
{
std::vector<T> p = { T(1), T(2), T(3), T(4) };
std::vector<T> q;
pc.set( 149, p.begin(), p.end() );
pc.get( 149, std::back_inserter( q ) );
ALEPH_ASSERT_THROW( p == q );
}
{
std::vector<T> p1 = { T(1), T(2), T(3), T(4) };
std::vector<T> p2;
std::vector<T> q1 = { T(5), T(6), T(7), T(8) };
std::vector<T> q2;
pc.set( 148, {1,2,3,4} );
pc.set( 149, {5,6,7,8} );
pc.get( 148, std::back_inserter( p2 ) );
pc.get( 149, std::back_inserter( q2 ) );
ALEPH_ASSERT_THROW( p1 == p2 );
ALEPH_ASSERT_THROW( q1 == q2 );
}
{
std::vector<T> p;
ALEPH_EXPECT_EXCEPTION(
pc.get( 151, std::back_inserter( p ) ),
std::runtime_error
);
}
ALEPH_TEST_END;
}
int main()
{
testFormats<float> ();
testFormats<double>();
testAccess<float> ();
testAccess<double> ();
}
<commit_msg>Testing `set()` method for point clouds<commit_after>#include "config/Base.hh"
#include "containers/PointCloud.hh"
#include "tests/Base.hh"
#include <iostream>
#include <string>
#include <vector>
using namespace aleph;
template <class T> void testFormats()
{
ALEPH_TEST_BEGIN( "Point cloud formats" );
using PointCloud = PointCloud<T>;
std::vector<PointCloud> pointClouds;
pointClouds.reserve( 4 );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_colon_separated.txt" ) ) );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_comma_separated.txt" ) ) );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_space_separated.txt" ) ) );
pointClouds.emplace_back( load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_tab_separated.txt" ) ) );
for( auto&& pc : pointClouds )
{
ALEPH_ASSERT_THROW( pc.size() == 150 );
ALEPH_ASSERT_THROW( pc.dimension() == 4 );
ALEPH_ASSERT_THROW( pc.empty() == false );
}
for( auto&& pc1 : pointClouds )
for( auto&& pc2 : pointClouds )
ALEPH_ASSERT_THROW( pc1 == pc2 );
ALEPH_TEST_END;
}
template <class T> void testAccess()
{
ALEPH_TEST_BEGIN( "Point cloud access" );
auto pc
= load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_comma_separated.txt" ) );
{
std::vector<T> actual;
std::vector<T> expected = { static_cast<T>( 5.9 ),
static_cast<T>( 3.0 ),
static_cast<T>( 5.1 ),
static_cast<T>( 1.8 ) };
pc.get( 149, std::back_inserter( actual ) );
ALEPH_ASSERT_THROW( actual == expected );
}
{
std::vector<T> p = { T(1), T(2), T(3), T(4) };
std::vector<T> q;
pc.set( 149, p.begin(), p.end() );
pc.get( 149, std::back_inserter( q ) );
ALEPH_ASSERT_THROW( p == q );
}
{
std::vector<T> p1 = { T(1), T(2), T(3), T(4) };
std::vector<T> p2;
std::vector<T> q1 = { T(5), T(6), T(7), T(8) };
std::vector<T> q2;
pc.set( 148, {1,2,3,4} );
pc.set( 149, {5,6,7,8} );
pc.get( 148, std::back_inserter( p2 ) );
pc.get( 149, std::back_inserter( q2 ) );
ALEPH_ASSERT_THROW( p1 == p2 );
ALEPH_ASSERT_THROW( q1 == q2 );
}
{
std::vector<T> p;
ALEPH_EXPECT_EXCEPTION(
pc.get( 151, std::back_inserter( p ) ),
std::runtime_error
);
}
{
std::vector<T> p;
ALEPH_EXPECT_EXCEPTION(
pc.set( 151, {1,2,3} ),
std::runtime_error
);
}
ALEPH_TEST_END;
}
int main()
{
testFormats<float> ();
testFormats<double>();
testAccess<float> ();
testAccess<double> ();
}
<|endoftext|> |
<commit_before>
#include <cmath>
#include <functional>
#include <iostream>
#include <random>
#include <vector>
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <spii/google_test_compatibility.h>
#include <spii/auto_diff_term.h>
#include <spii/solver.h>
using namespace spii;
void info_log_function(const std::string& str)
{
INFO(str);
}
// "An analysis of the behavior of a glass of genetic adaptive systems."
// K.A. De Jong. Ph.D. thesis, University of Michigan, 1975.
struct GeneralizedRosenbrockTerm
{
template<typename R>
R operator()(const R* const x1, const R* const x2) const
{
R d0 = (*x1) * (*x1) - (*x2);
R d1 = 1 - (*x1);
return 100 * d0*d0 + d1*d1;
}
};
// An easier variant.
struct EasyRosenbrockTerm
{
template<typename R>
R operator()(const R* const x1, const R* const x2) const
{
R d0 = (*x1) * (*x1) - (*x2);
R d1 = 1 - (*x1);
return d0*d0 + d1*d1;
}
};
template<typename Functor, size_t n, bool lbfgs>
void test_rosenbrock()
{
Function f;
std::vector<double> x(n);
for (size_t i = 0; i < n; ++i) {
f.add_variable(&x[i], 1);
}
// Initial values.
for (size_t i = 0; i < n; ++i) {
if (i % 2 == 0) {
x[i] = -1.2;
}
else {
x[i] = 1.0;
}
}
// Add all diagonal terms.
for (size_t i = 0; i < n - 1; ++i) {
f.add_term(new AutoDiffTerm<Functor, 1, 1>
(new Functor()), &x[i], &x[i+1]);
}
Solver solver;
solver.maximum_iterations = 10000;
solver.log_function = info_log_function;
SolverResults results;
if (lbfgs) {
solver.solve_lbfgs(f, &results);
}
else {
solver.solve_newton(f, &results);
}
INFO(results);
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
EXPECT_LT( std::fabs(f.evaluate()), 1e-9);
for (size_t i = 0; i < n - 1; ++i) {
ASSERT_LT( std::fabs(x[i] - 1.0), 1e-9);
}
}
TEST(Newton, EasyRosenbrock1000)
{
test_rosenbrock<EasyRosenbrockTerm, 1000, false>();
}
TEST(Newton, EasyRosenbrock10000)
{
test_rosenbrock<EasyRosenbrockTerm, 10000, false>();
}
TEST(LBFGS, EasyRosenbrock1000)
{
test_rosenbrock<EasyRosenbrockTerm, 1000, true>();
}
TEST(LBFGS, EasyRosenbrock10000)
{
test_rosenbrock<EasyRosenbrockTerm, 10000, true>();
}
struct LennardJones
{
template<typename R>
R operator()(const R* const p1, const R* const p2) const
{
R dx = p1[0] - p2[0];
R dy = p1[1] - p2[1];
R dz = p1[2] - p2[2];
R r2 = dx*dx + dy*dy + dz*dz;
R r6 = r2*r2*r2;
R r12 = r6*r6;
return 1.0 / r12 - 1.0 / r6;
}
};
template<bool lbfgs, int n>
void test_Lennard_Jones()
{
std::mt19937 prng(0);
std::normal_distribution<double> normal;
auto randn = std::bind(normal, prng);
Function potential;
std::vector<Eigen::Vector3d> points(n*n*n);
for (int x = 0; x < n; ++x) {
for (int y = 0; y < n; ++y) {
for (int z = 0; z < n; ++z) {
points[x + y*n + z*n*n][0] = x + 0.05 * randn();
points[x + y*n + z*n*n][1] = y + 0.05 * randn();
points[x + y*n + z*n*n][2] = z + 0.05 * randn();
potential.add_variable(&points[x + y*n + z*n*n][0], 3);
}
}
}
// Add all pairwise terms
for (int i = 0; i < n*n*n; ++i) {
for (int j = i + 1; j < n*n*n; ++j) {
potential.add_term(
new AutoDiffTerm<LennardJones, 3, 3>(
new LennardJones),
&points[i][0],
&points[j][0]);
}
}
Solver solver;
solver.maximum_iterations = 1000;
solver.function_improvement_tolerance = 1e-6;
solver.log_function = info_log_function;
// All points interact with all points, so the Hessian
// will be dense.
solver.sparsity_mode = Solver::DENSE;
SolverResults results;
if (lbfgs) {
solver.solve_lbfgs(potential, &results);
}
else {
solver.solve_newton(potential, &results);
}
INFO(results);
std::stringstream sout;
potential.print_timing_information(sout);
INFO(sout.str());
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}
TEST(Newton, LennardJones)
{
test_Lennard_Jones<false, 5>();
}
TEST(LBFGS, LennardJones)
{
test_Lennard_Jones<true, 5>();
}
struct Trid1
{
template<typename R>
R operator()(const R* const x) const
{
R d = *x - 1.0;
return d*d;
}
};
struct Trid2
{
template<typename R>
R operator()(const R* const x1, const R* const x2) const
{
return - (*x1) * (*x2);
}
};
template<size_t n, bool lbfgs>
void test_trid()
{
Function f;
std::vector<double> x(n, 1.0);
for (size_t i = 0; i < n; ++i) {
f.add_variable(&x[i], 1);
}
for (size_t i = 0; i < n; ++i) {
f.add_term( new AutoDiffTerm<Trid1, 1>(
new Trid1),
&x[i]);
}
for (size_t i = 1; i < n; ++i) {
f.add_term( new AutoDiffTerm<Trid2, 1, 1>(
new Trid2),
&x[i],
&x[i-1]);
}
Solver solver;
solver.maximum_iterations = 100;
//solver.argument_improvement_tolerance = 1e-16;
//solver.gradient_tolerance = 1e-16;
solver.log_function = info_log_function;
SolverResults results;
if (lbfgs) {
solver.maximum_iterations = 1000;
solver.solve_lbfgs(f, &results);
}
else {
solver.solve_newton(f, &results);
}
INFO(results);
double fval = f.evaluate();
// Global optimum is
//
// x[i] = (i + 1) * (n - i)
//
// Therefore, it is hard to calulate the optimal function
// value for large n.
//
double tol = 1e-8;
if (n >= 10000) {
tol = 1e-6;
}
if (n >= 100000) {
tol = 1e-4;
}
double nn = n;
EXPECT_LT(std::fabs(fval + (nn * (nn+4) * (nn-1)) / 6.0) / std::abs(fval), tol);
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
if (n <= 10) {
for (size_t i = 0; i < n; ++i) {
INFO("x[" << i << "] = " << x[i]);
}
}
}
TEST(Newton, Trid10)
{
test_trid<10, false>();
}
TEST(Newton, Trid1000)
{
test_trid<1000, false>();
}
TEST(Newton, Trid10000)
{
test_trid<10000, false>();
}
struct LogBarrier01
{
template<typename R>
R operator()(const R* const x) const
{
return -log(x[0]) - log(1.0 - x[0]);
}
};
struct QuadraticFunction1
{
QuadraticFunction1(double b)
{
this->b = b;
}
template<typename R>
R operator()(const R* const x) const
{
R d = x[0] - b;
return d * d;
}
double b;
};
TEST(Newton, Barrier)
{
std::mt19937 prng(0);
std::normal_distribution<double> normal;
auto randn = std::bind(normal, prng);
const int n = 10000;
Function f;
std::vector<double> x(n, 0.5);
for (size_t i = 0; i < n; ++i) {
f.add_variable(&x[i], 1);
f.add_term( new AutoDiffTerm<QuadraticFunction1, 1>(
new QuadraticFunction1(0.5 + randn())),
&x[i]);
f.add_term( new AutoDiffTerm<LogBarrier01, 1>(
new LogBarrier01),
&x[i]);
}
Solver solver;
solver.maximum_iterations = 100;
solver.log_function = info_log_function;
SolverResults results;
solver.solve_newton(f, &results);
INFO(results);
std::stringstream sout;
f.print_timing_information(sout);
INFO(sout.str());
CHECK(solver.maximum_iterations == 1010);
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}
<commit_msg>Accidentally checked in a failing test.<commit_after>
#include <cmath>
#include <functional>
#include <iostream>
#include <random>
#include <vector>
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <spii/google_test_compatibility.h>
#include <spii/auto_diff_term.h>
#include <spii/solver.h>
using namespace spii;
void info_log_function(const std::string& str)
{
INFO(str);
}
// "An analysis of the behavior of a glass of genetic adaptive systems."
// K.A. De Jong. Ph.D. thesis, University of Michigan, 1975.
struct GeneralizedRosenbrockTerm
{
template<typename R>
R operator()(const R* const x1, const R* const x2) const
{
R d0 = (*x1) * (*x1) - (*x2);
R d1 = 1 - (*x1);
return 100 * d0*d0 + d1*d1;
}
};
// An easier variant.
struct EasyRosenbrockTerm
{
template<typename R>
R operator()(const R* const x1, const R* const x2) const
{
R d0 = (*x1) * (*x1) - (*x2);
R d1 = 1 - (*x1);
return d0*d0 + d1*d1;
}
};
template<typename Functor, size_t n, bool lbfgs>
void test_rosenbrock()
{
Function f;
std::vector<double> x(n);
for (size_t i = 0; i < n; ++i) {
f.add_variable(&x[i], 1);
}
// Initial values.
for (size_t i = 0; i < n; ++i) {
if (i % 2 == 0) {
x[i] = -1.2;
}
else {
x[i] = 1.0;
}
}
// Add all diagonal terms.
for (size_t i = 0; i < n - 1; ++i) {
f.add_term(new AutoDiffTerm<Functor, 1, 1>
(new Functor()), &x[i], &x[i+1]);
}
Solver solver;
solver.maximum_iterations = 10000;
solver.log_function = info_log_function;
SolverResults results;
if (lbfgs) {
solver.solve_lbfgs(f, &results);
}
else {
solver.solve_newton(f, &results);
}
INFO(results);
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
EXPECT_LT( std::fabs(f.evaluate()), 1e-9);
for (size_t i = 0; i < n - 1; ++i) {
ASSERT_LT( std::fabs(x[i] - 1.0), 1e-9);
}
}
TEST(Newton, EasyRosenbrock1000)
{
test_rosenbrock<EasyRosenbrockTerm, 1000, false>();
}
TEST(Newton, EasyRosenbrock10000)
{
test_rosenbrock<EasyRosenbrockTerm, 10000, false>();
}
TEST(LBFGS, EasyRosenbrock1000)
{
test_rosenbrock<EasyRosenbrockTerm, 1000, true>();
}
TEST(LBFGS, EasyRosenbrock10000)
{
test_rosenbrock<EasyRosenbrockTerm, 10000, true>();
}
struct LennardJones
{
template<typename R>
R operator()(const R* const p1, const R* const p2) const
{
R dx = p1[0] - p2[0];
R dy = p1[1] - p2[1];
R dz = p1[2] - p2[2];
R r2 = dx*dx + dy*dy + dz*dz;
R r6 = r2*r2*r2;
R r12 = r6*r6;
return 1.0 / r12 - 1.0 / r6;
}
};
template<bool lbfgs, int n>
void test_Lennard_Jones()
{
std::mt19937 prng(0);
std::normal_distribution<double> normal;
auto randn = std::bind(normal, prng);
Function potential;
std::vector<Eigen::Vector3d> points(n*n*n);
for (int x = 0; x < n; ++x) {
for (int y = 0; y < n; ++y) {
for (int z = 0; z < n; ++z) {
points[x + y*n + z*n*n][0] = x + 0.05 * randn();
points[x + y*n + z*n*n][1] = y + 0.05 * randn();
points[x + y*n + z*n*n][2] = z + 0.05 * randn();
potential.add_variable(&points[x + y*n + z*n*n][0], 3);
}
}
}
// Add all pairwise terms
for (int i = 0; i < n*n*n; ++i) {
for (int j = i + 1; j < n*n*n; ++j) {
potential.add_term(
new AutoDiffTerm<LennardJones, 3, 3>(
new LennardJones),
&points[i][0],
&points[j][0]);
}
}
Solver solver;
solver.maximum_iterations = 1000;
solver.function_improvement_tolerance = 1e-6;
solver.log_function = info_log_function;
// All points interact with all points, so the Hessian
// will be dense.
solver.sparsity_mode = Solver::DENSE;
SolverResults results;
if (lbfgs) {
solver.solve_lbfgs(potential, &results);
}
else {
solver.solve_newton(potential, &results);
}
INFO(results);
std::stringstream sout;
potential.print_timing_information(sout);
INFO(sout.str());
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}
TEST(Newton, LennardJones)
{
test_Lennard_Jones<false, 5>();
}
TEST(LBFGS, LennardJones)
{
test_Lennard_Jones<true, 5>();
}
struct Trid1
{
template<typename R>
R operator()(const R* const x) const
{
R d = *x - 1.0;
return d*d;
}
};
struct Trid2
{
template<typename R>
R operator()(const R* const x1, const R* const x2) const
{
return - (*x1) * (*x2);
}
};
template<size_t n, bool lbfgs>
void test_trid()
{
Function f;
std::vector<double> x(n, 1.0);
for (size_t i = 0; i < n; ++i) {
f.add_variable(&x[i], 1);
}
for (size_t i = 0; i < n; ++i) {
f.add_term( new AutoDiffTerm<Trid1, 1>(
new Trid1),
&x[i]);
}
for (size_t i = 1; i < n; ++i) {
f.add_term( new AutoDiffTerm<Trid2, 1, 1>(
new Trid2),
&x[i],
&x[i-1]);
}
Solver solver;
solver.maximum_iterations = 100;
//solver.argument_improvement_tolerance = 1e-16;
//solver.gradient_tolerance = 1e-16;
solver.log_function = info_log_function;
SolverResults results;
if (lbfgs) {
solver.maximum_iterations = 1000;
solver.solve_lbfgs(f, &results);
}
else {
solver.solve_newton(f, &results);
}
INFO(results);
double fval = f.evaluate();
// Global optimum is
//
// x[i] = (i + 1) * (n - i)
//
// Therefore, it is hard to calulate the optimal function
// value for large n.
//
double tol = 1e-8;
if (n >= 10000) {
tol = 1e-6;
}
if (n >= 100000) {
tol = 1e-4;
}
double nn = n;
EXPECT_LT(std::fabs(fval + (nn * (nn+4) * (nn-1)) / 6.0) / std::abs(fval), tol);
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
if (n <= 10) {
for (size_t i = 0; i < n; ++i) {
INFO("x[" << i << "] = " << x[i]);
}
}
}
TEST(Newton, Trid10)
{
test_trid<10, false>();
}
TEST(Newton, Trid1000)
{
test_trid<1000, false>();
}
TEST(Newton, Trid10000)
{
test_trid<10000, false>();
}
struct LogBarrier01
{
template<typename R>
R operator()(const R* const x) const
{
return -log(x[0]) - log(1.0 - x[0]);
}
};
struct QuadraticFunction1
{
QuadraticFunction1(double b)
{
this->b = b;
}
template<typename R>
R operator()(const R* const x) const
{
R d = x[0] - b;
return d * d;
}
double b;
};
TEST(Newton, Barrier)
{
std::mt19937 prng(0);
std::normal_distribution<double> normal;
auto randn = std::bind(normal, prng);
const int n = 10000;
Function f;
std::vector<double> x(n, 0.5);
for (size_t i = 0; i < n; ++i) {
f.add_variable(&x[i], 1);
f.add_term( new AutoDiffTerm<QuadraticFunction1, 1>(
new QuadraticFunction1(0.5 + randn())),
&x[i]);
f.add_term( new AutoDiffTerm<LogBarrier01, 1>(
new LogBarrier01),
&x[i]);
}
Solver solver;
solver.maximum_iterations = 100;
solver.log_function = info_log_function;
SolverResults results;
solver.solve_newton(f, &results);
INFO(results);
std::stringstream sout;
f.print_timing_information(sout);
INFO(sout.str());
EXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||
results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||
results.exit_condition == SolverResults::GRADIENT_TOLERANCE);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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 <comphelper/threadpool.hxx>
#include <rtl/instance.hxx>
#include <boost/shared_ptr.hpp>
#include <thread>
#include <algorithm>
namespace comphelper {
class ThreadPool::ThreadWorker : public salhelper::Thread
{
ThreadPool *mpPool;
osl::Condition maNewWork;
bool mbWorking;
public:
ThreadWorker( ThreadPool *pPool ) :
salhelper::Thread("thread-pool"),
mpPool( pPool ),
mbWorking( false )
{
}
virtual void execute() SAL_OVERRIDE
{
ThreadTask *pTask;
while ( ( pTask = waitForWork() ) )
{
pTask->doWork();
delete pTask;
}
}
ThreadTask *waitForWork()
{
ThreadTask *pRet = NULL;
osl::ResettableMutexGuard aGuard( mpPool->maGuard );
pRet = mpPool->popWork();
while( !pRet )
{
if (mbWorking)
mpPool->stopWork();
mbWorking = false;
maNewWork.reset();
if( mpPool->mbTerminate )
break;
aGuard.clear(); // unlock
maNewWork.wait();
aGuard.reset(); // lock
pRet = mpPool->popWork();
}
if (pRet)
{
if (!mbWorking)
mpPool->startWork();
mbWorking = true;
}
return pRet;
}
// Why a condition per worker thread - you may ask.
//
// Unfortunately the Windows synchronisation API that we wrap
// is horribly inadequate cf.
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
// The existing osl::Condition API should only ever be used
// between one producer and one consumer thread to avoid the
// lost wakeup problem.
void signalNewWork()
{
maNewWork.set();
}
};
ThreadPool::ThreadPool( sal_Int32 nWorkers ) :
mnThreadsWorking( 0 ),
mbTerminate( false )
{
for( sal_Int32 i = 0; i < nWorkers; i++ )
maWorkers.push_back( new ThreadWorker( this ) );
maTasksComplete.reset();
osl::MutexGuard aGuard( maGuard );
for( size_t i = 0; i < maWorkers.size(); i++ )
maWorkers[ i ]->launch();
}
ThreadPool::~ThreadPool()
{
waitAndCleanupWorkers();
}
struct ThreadPoolStatic : public rtl::StaticWithInit< boost::shared_ptr< ThreadPool >,
ThreadPoolStatic >
{
boost::shared_ptr< ThreadPool > operator () () {
sal_Int32 nThreads = std::max( std::thread::hardware_concurrency(), 1U );
return boost::shared_ptr< ThreadPool >( new ThreadPool( nThreads ) );
};
};
ThreadPool& ThreadPool::getSharedOptimalPool()
{
return *ThreadPoolStatic::get().get();
}
void ThreadPool::waitAndCleanupWorkers()
{
waitUntilEmpty();
osl::ResettableMutexGuard aGuard( maGuard );
mbTerminate = true;
while( !maWorkers.empty() )
{
rtl::Reference< ThreadWorker > xWorker = maWorkers.back();
maWorkers.pop_back();
assert(std::find(maWorkers.begin(), maWorkers.end(), xWorker)
== maWorkers.end());
xWorker->signalNewWork();
aGuard.clear();
{ // unlocked
xWorker->join();
xWorker.clear();
}
aGuard.reset();
}
}
void ThreadPool::pushTask( ThreadTask *pTask )
{
osl::MutexGuard aGuard( maGuard );
maTasks.insert( maTasks.begin(), pTask );
// horrible beyond belief:
for( size_t i = 0; i < maWorkers.size(); i++ )
maWorkers[ i ]->signalNewWork();
maTasksComplete.reset();
}
ThreadTask *ThreadPool::popWork()
{
if( !maTasks.empty() )
{
ThreadTask *pTask = maTasks.back();
maTasks.pop_back();
return pTask;
}
else
return NULL;
}
void ThreadPool::startWork()
{
mnThreadsWorking++;
}
void ThreadPool::stopWork()
{
assert( mnThreadsWorking > 0 );
if ( --mnThreadsWorking == 0 )
maTasksComplete.set();
}
void ThreadPool::waitUntilEmpty()
{
osl::ResettableMutexGuard aGuard( maGuard );
if( maWorkers.empty() )
{ // no threads at all -> execute the work in-line
ThreadTask *pTask;
while ( ( pTask = popWork() ) )
{
pTask->doWork();
delete pTask;
}
}
else
{
aGuard.clear();
maTasksComplete.wait();
aGuard.reset();
}
assert( maTasks.empty() );
}
} // namespace comphelper
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>thread-pool: Initialize empty pools to start complete.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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 <comphelper/threadpool.hxx>
#include <rtl/instance.hxx>
#include <boost/shared_ptr.hpp>
#include <thread>
#include <algorithm>
namespace comphelper {
class ThreadPool::ThreadWorker : public salhelper::Thread
{
ThreadPool *mpPool;
osl::Condition maNewWork;
bool mbWorking;
public:
ThreadWorker( ThreadPool *pPool ) :
salhelper::Thread("thread-pool"),
mpPool( pPool ),
mbWorking( false )
{
}
virtual void execute() SAL_OVERRIDE
{
ThreadTask *pTask;
while ( ( pTask = waitForWork() ) )
{
pTask->doWork();
delete pTask;
}
}
ThreadTask *waitForWork()
{
ThreadTask *pRet = NULL;
osl::ResettableMutexGuard aGuard( mpPool->maGuard );
pRet = mpPool->popWork();
while( !pRet )
{
if (mbWorking)
mpPool->stopWork();
mbWorking = false;
maNewWork.reset();
if( mpPool->mbTerminate )
break;
aGuard.clear(); // unlock
maNewWork.wait();
aGuard.reset(); // lock
pRet = mpPool->popWork();
}
if (pRet)
{
if (!mbWorking)
mpPool->startWork();
mbWorking = true;
}
return pRet;
}
// Why a condition per worker thread - you may ask.
//
// Unfortunately the Windows synchronisation API that we wrap
// is horribly inadequate cf.
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
// The existing osl::Condition API should only ever be used
// between one producer and one consumer thread to avoid the
// lost wakeup problem.
void signalNewWork()
{
maNewWork.set();
}
};
ThreadPool::ThreadPool( sal_Int32 nWorkers ) :
mnThreadsWorking( 0 ),
mbTerminate( false )
{
for( sal_Int32 i = 0; i < nWorkers; i++ )
maWorkers.push_back( new ThreadWorker( this ) );
maTasksComplete.set();
osl::MutexGuard aGuard( maGuard );
for( size_t i = 0; i < maWorkers.size(); i++ )
maWorkers[ i ]->launch();
}
ThreadPool::~ThreadPool()
{
waitAndCleanupWorkers();
}
struct ThreadPoolStatic : public rtl::StaticWithInit< boost::shared_ptr< ThreadPool >,
ThreadPoolStatic >
{
boost::shared_ptr< ThreadPool > operator () () {
sal_Int32 nThreads = std::max( std::thread::hardware_concurrency(), 1U );
return boost::shared_ptr< ThreadPool >( new ThreadPool( nThreads ) );
};
};
ThreadPool& ThreadPool::getSharedOptimalPool()
{
return *ThreadPoolStatic::get().get();
}
void ThreadPool::waitAndCleanupWorkers()
{
waitUntilEmpty();
osl::ResettableMutexGuard aGuard( maGuard );
mbTerminate = true;
while( !maWorkers.empty() )
{
rtl::Reference< ThreadWorker > xWorker = maWorkers.back();
maWorkers.pop_back();
assert(std::find(maWorkers.begin(), maWorkers.end(), xWorker)
== maWorkers.end());
xWorker->signalNewWork();
aGuard.clear();
{ // unlocked
xWorker->join();
xWorker.clear();
}
aGuard.reset();
}
}
void ThreadPool::pushTask( ThreadTask *pTask )
{
osl::MutexGuard aGuard( maGuard );
maTasks.insert( maTasks.begin(), pTask );
// horrible beyond belief:
for( size_t i = 0; i < maWorkers.size(); i++ )
maWorkers[ i ]->signalNewWork();
maTasksComplete.reset();
}
ThreadTask *ThreadPool::popWork()
{
if( !maTasks.empty() )
{
ThreadTask *pTask = maTasks.back();
maTasks.pop_back();
return pTask;
}
else
return NULL;
}
void ThreadPool::startWork()
{
mnThreadsWorking++;
}
void ThreadPool::stopWork()
{
assert( mnThreadsWorking > 0 );
if ( --mnThreadsWorking == 0 )
maTasksComplete.set();
}
void ThreadPool::waitUntilEmpty()
{
osl::ResettableMutexGuard aGuard( maGuard );
if( maWorkers.empty() )
{ // no threads at all -> execute the work in-line
ThreadTask *pTask;
while ( ( pTask = popWork() ) )
{
pTask->doWork();
delete pTask;
}
}
else
{
aGuard.clear();
maTasksComplete.wait();
aGuard.reset();
}
assert( maTasks.empty() );
}
} // namespace comphelper
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <localsession.hxx>
#include <treecache.hxx>
#include <options.hxx>
#include <rtl/ustring.hxx>
#include "treeload.hxx"
// -----------------------------------------------------------------------------
namespace configmgr
{
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
#define ASCII(x) ::rtl::OUString::createFromAscii(x)
// -----------------------------------------------------------------------------
// ------------------------- requestSubtree without API -------------------------
// -----------------------------------------------------------------------------
OTreeLoad::OTreeLoad(uno::Reference<lang::XMultiServiceFactory> const& _xServiceProvider,
rtl::OUString const& _sSourceDirectory, rtl::OUString const& _sUpdateDirectory) throw (uno::Exception)
:m_xServiceProvider(_xServiceProvider)
{
// Create a TypeConverter
uno::Reference<script::XTypeConverter> xConverter;
xConverter = xConverter.query(m_xServiceProvider->createInstance(ASCII( "com.sun.star.script.Converter" )) );
m_xDefaultOptions = new OOptions(xConverter);
m_xDefaultOptions->setNoCache(true);
// create it .. and connect
std::auto_ptr<LocalSession> pLocal( new LocalSession(m_xServiceProvider) );
sal_Bool bOpen = pLocal->open(_sSourceDirectory, _sUpdateDirectory);
IConfigSession* pConfigSession = pLocal.release();
m_pTreeMgr = new TreeManager(pConfigSession, m_xDefaultOptions);
}
// -----------------------------------------------------------------------------
ISubtree* OTreeLoad::requestSubtree( OUString const& aSubtreePath) throw (uno::Exception)
{
return m_pTreeMgr->requestSubtree(aSubtreePath, m_xDefaultOptions, /* MinLevel */ -1);
}
// -----------------------------------------------------------------------------
void OTreeLoad::releaseSubtree( OUString const& aSubtreePath) throw (uno::Exception)
{
m_pTreeMgr->releaseSubtree(aSubtreePath, m_xDefaultOptions);
}
// -----------------------------------------------------------------------------
} // namespace
<commit_msg>INTEGRATION: CWS pchfix02 (1.1.312); FILE MERGED 2006/09/01 17:20:58 kaib 1.1.312.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: treeload.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2006-09-16 15:41:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <localsession.hxx>
#include <treecache.hxx>
#include <options.hxx>
#include <rtl/ustring.hxx>
#include "treeload.hxx"
// -----------------------------------------------------------------------------
namespace configmgr
{
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
#define ASCII(x) ::rtl::OUString::createFromAscii(x)
// -----------------------------------------------------------------------------
// ------------------------- requestSubtree without API -------------------------
// -----------------------------------------------------------------------------
OTreeLoad::OTreeLoad(uno::Reference<lang::XMultiServiceFactory> const& _xServiceProvider,
rtl::OUString const& _sSourceDirectory, rtl::OUString const& _sUpdateDirectory) throw (uno::Exception)
:m_xServiceProvider(_xServiceProvider)
{
// Create a TypeConverter
uno::Reference<script::XTypeConverter> xConverter;
xConverter = xConverter.query(m_xServiceProvider->createInstance(ASCII( "com.sun.star.script.Converter" )) );
m_xDefaultOptions = new OOptions(xConverter);
m_xDefaultOptions->setNoCache(true);
// create it .. and connect
std::auto_ptr<LocalSession> pLocal( new LocalSession(m_xServiceProvider) );
sal_Bool bOpen = pLocal->open(_sSourceDirectory, _sUpdateDirectory);
IConfigSession* pConfigSession = pLocal.release();
m_pTreeMgr = new TreeManager(pConfigSession, m_xDefaultOptions);
}
// -----------------------------------------------------------------------------
ISubtree* OTreeLoad::requestSubtree( OUString const& aSubtreePath) throw (uno::Exception)
{
return m_pTreeMgr->requestSubtree(aSubtreePath, m_xDefaultOptions, /* MinLevel */ -1);
}
// -----------------------------------------------------------------------------
void OTreeLoad::releaseSubtree( OUString const& aSubtreePath) throw (uno::Exception)
{
m_pTreeMgr->releaseSubtree(aSubtreePath, m_xDefaultOptions);
}
// -----------------------------------------------------------------------------
} // namespace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: PColumn.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2004-10-22 08:45:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/PColumn.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace dbtools;
using namespace connectivity::parse;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// -------------------------------------------------------------------------
OParseColumn::OParseColumn(const Reference<XPropertySet>& _xColumn,sal_Bool _bCase)
: connectivity::sdbcx::OColumn( getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)))
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)))
, sal_False
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))
, _bCase
)
, m_bFunction(sal_False)
, m_bDbasePrecisionChanged(sal_False)
, m_bAggregateFunction(sal_False)
{
construct();
}
// -------------------------------------------------------------------------
OParseColumn::OParseColumn( const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase
) : connectivity::sdbcx::OColumn(_Name,
_TypeName,
_DefaultValue,
_IsNullable,
_Precision,
_Scale,
_Type,
_IsAutoIncrement,
sal_False,
_IsCurrency,
_bCase)
, m_bFunction(sal_False)
, m_bDbasePrecisionChanged(sal_False)
, m_bAggregateFunction(sal_False)
{
construct();
}
// -------------------------------------------------------------------------
OParseColumn::~OParseColumn()
{
}
// -------------------------------------------------------------------------
void OParseColumn::construct()
{
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FUNCTION), PROPERTY_ID_FUNCTION, 0,&m_bFunction, ::getCppuType(reinterpret_cast< sal_Bool*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_AGGREGATEFUNCTION), PROPERTY_ID_AGGREGATEFUNCTION, 0,&m_bAggregateFunction, ::getCppuType(reinterpret_cast< sal_Bool*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TABLENAME), PROPERTY_ID_TABLENAME, nAttrib,&m_aTableName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME), PROPERTY_ID_REALNAME, 0,&m_aRealName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DBASEPRECISIONCHANGED), PROPERTY_ID_DBASEPRECISIONCHANGED, nAttrib,&m_bDbasePrecisionChanged, ::getCppuType(reinterpret_cast<sal_Bool*>(NULL)));
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OParseColumn::createArrayHelper( sal_Int32 _nId) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & SAL_CALL OParseColumn::getInfoHelper()
{
return *OParseColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
OOrderColumn::OOrderColumn( const Reference<XPropertySet>& _xColumn
,sal_Bool _bCase
,sal_Bool _bAscending)
: connectivity::sdbcx::OColumn( getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)))
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)))
, sal_False
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))
, _bCase
)
, m_bAscending(_bAscending)
{
construct();
}
// -------------------------------------------------------------------------
OOrderColumn::OOrderColumn( const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase
,sal_Bool _bAscending
) : connectivity::sdbcx::OColumn(_Name,
_TypeName,
_DefaultValue,
_IsNullable,
_Precision,
_Scale,
_Type,
_IsAutoIncrement,
sal_False,
_IsCurrency,
_bCase)
, m_bAscending(_bAscending)
{
construct();
}
// -------------------------------------------------------------------------
OOrderColumn::~OOrderColumn()
{
}
// -------------------------------------------------------------------------
void OOrderColumn::construct()
{
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING),PROPERTY_ID_ISASCENDING,0,&m_bAscending, ::getCppuType(reinterpret_cast< sal_Bool*>(NULL)));
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OOrderColumn::createArrayHelper( sal_Int32 _nId) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & SAL_CALL OOrderColumn::getInfoHelper()
{
return *OOrderColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OOrderColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if ( m_bOrder )
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdb.OrderColumn");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdb.GroupColumn");
return aSupported;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.112); FILE MERGED 2005/09/05 17:25:49 rt 1.10.112.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PColumn.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:39:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/PColumn.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace dbtools;
using namespace connectivity::parse;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// -------------------------------------------------------------------------
OParseColumn::OParseColumn(const Reference<XPropertySet>& _xColumn,sal_Bool _bCase)
: connectivity::sdbcx::OColumn( getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)))
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)))
, sal_False
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))
, _bCase
)
, m_bFunction(sal_False)
, m_bDbasePrecisionChanged(sal_False)
, m_bAggregateFunction(sal_False)
{
construct();
}
// -------------------------------------------------------------------------
OParseColumn::OParseColumn( const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase
) : connectivity::sdbcx::OColumn(_Name,
_TypeName,
_DefaultValue,
_IsNullable,
_Precision,
_Scale,
_Type,
_IsAutoIncrement,
sal_False,
_IsCurrency,
_bCase)
, m_bFunction(sal_False)
, m_bDbasePrecisionChanged(sal_False)
, m_bAggregateFunction(sal_False)
{
construct();
}
// -------------------------------------------------------------------------
OParseColumn::~OParseColumn()
{
}
// -------------------------------------------------------------------------
void OParseColumn::construct()
{
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FUNCTION), PROPERTY_ID_FUNCTION, 0,&m_bFunction, ::getCppuType(reinterpret_cast< sal_Bool*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_AGGREGATEFUNCTION), PROPERTY_ID_AGGREGATEFUNCTION, 0,&m_bAggregateFunction, ::getCppuType(reinterpret_cast< sal_Bool*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TABLENAME), PROPERTY_ID_TABLENAME, nAttrib,&m_aTableName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME), PROPERTY_ID_REALNAME, 0,&m_aRealName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DBASEPRECISIONCHANGED), PROPERTY_ID_DBASEPRECISIONCHANGED, nAttrib,&m_bDbasePrecisionChanged, ::getCppuType(reinterpret_cast<sal_Bool*>(NULL)));
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OParseColumn::createArrayHelper( sal_Int32 _nId) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & SAL_CALL OParseColumn::getInfoHelper()
{
return *OParseColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
OOrderColumn::OOrderColumn( const Reference<XPropertySet>& _xColumn
,sal_Bool _bCase
,sal_Bool _bAscending)
: connectivity::sdbcx::OColumn( getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)))
, getString(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)))
, getINT32(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)))
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)))
, sal_False
, getBOOL(_xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))
, _bCase
)
, m_bAscending(_bAscending)
{
construct();
}
// -------------------------------------------------------------------------
OOrderColumn::OOrderColumn( const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsCurrency,
sal_Bool _bCase
,sal_Bool _bAscending
) : connectivity::sdbcx::OColumn(_Name,
_TypeName,
_DefaultValue,
_IsNullable,
_Precision,
_Scale,
_Type,
_IsAutoIncrement,
sal_False,
_IsCurrency,
_bCase)
, m_bAscending(_bAscending)
{
construct();
}
// -------------------------------------------------------------------------
OOrderColumn::~OOrderColumn()
{
}
// -------------------------------------------------------------------------
void OOrderColumn::construct()
{
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING),PROPERTY_ID_ISASCENDING,0,&m_bAscending, ::getCppuType(reinterpret_cast< sal_Bool*>(NULL)));
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OOrderColumn::createArrayHelper( sal_Int32 _nId) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & SAL_CALL OOrderColumn::getInfoHelper()
{
return *OOrderColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OOrderColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if ( m_bOrder )
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdb.OrderColumn");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdb.GroupColumn");
return aSupported;
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/app_list/views/search_result_list_view.h"
#include <algorithm>
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/app_list_view_delegate.h"
#include "ui/app_list/search_result.h"
#include "ui/app_list/views/search_result_list_view_delegate.h"
#include "ui/app_list/views/search_result_view.h"
#include "ui/events/event.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/views/background.h"
#include "ui/views/layout/box_layout.h"
namespace {
const int kMaxResults = 6;
const int kExperimentAppListMaxResults = 3;
const int kTimeoutIndicatorHeight = 2;
const int kTimeoutFramerate = 60;
const SkColor kTimeoutIndicatorColor = SkColorSetRGB(30, 144, 255);
} // namespace
namespace app_list {
SearchResultListView::SearchResultListView(
SearchResultListViewDelegate* delegate,
AppListViewDelegate* view_delegate)
: delegate_(delegate),
view_delegate_(view_delegate),
results_container_(new views::View),
auto_launch_indicator_(new views::View) {
results_container_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0));
int max_results = kMaxResults;
if (app_list::switches::IsExperimentalAppListEnabled())
max_results = kExperimentAppListMaxResults;
for (int i = 0; i < max_results; ++i)
results_container_->AddChildView(new SearchResultView(this));
AddChildView(results_container_);
auto_launch_indicator_->set_background(
views::Background::CreateSolidBackground(kTimeoutIndicatorColor));
auto_launch_indicator_->SetVisible(false);
AddChildView(auto_launch_indicator_);
}
SearchResultListView::~SearchResultListView() {
}
bool SearchResultListView::IsResultViewSelected(
const SearchResultView* result_view) const {
if (selected_index() < 0)
return false;
return static_cast<const SearchResultView*>(
results_container_->child_at(selected_index())) == result_view;
}
void SearchResultListView::UpdateAutoLaunchState() {
SetAutoLaunchTimeout(view_delegate_->GetAutoLaunchTimeout());
}
bool SearchResultListView::OnKeyPressed(const ui::KeyEvent& event) {
if (selected_index() >= 0 &&
results_container_->child_at(selected_index())->OnKeyPressed(event)) {
return true;
}
int selection_index = -1;
switch (event.key_code()) {
case ui::VKEY_TAB:
if (event.IsShiftDown())
selection_index = selected_index() - 1;
else
selection_index = selected_index() + 1;
break;
case ui::VKEY_UP:
selection_index = selected_index() - 1;
break;
case ui::VKEY_DOWN:
selection_index = selected_index() + 1;
break;
default:
break;
}
if (IsValidSelectionIndex(selection_index)) {
SetSelectedIndex(selection_index);
if (auto_launch_animation_)
CancelAutoLaunchTimeout();
return true;
}
return false;
}
void SearchResultListView::SetAutoLaunchTimeout(
const base::TimeDelta& timeout) {
if (timeout > base::TimeDelta()) {
auto_launch_indicator_->SetVisible(true);
auto_launch_indicator_->SetBounds(0, 0, 0, kTimeoutIndicatorHeight);
auto_launch_animation_.reset(new gfx::LinearAnimation(
timeout.InMilliseconds(), kTimeoutFramerate, this));
auto_launch_animation_->Start();
} else {
auto_launch_indicator_->SetVisible(false);
auto_launch_animation_.reset();
}
}
void SearchResultListView::CancelAutoLaunchTimeout() {
SetAutoLaunchTimeout(base::TimeDelta());
view_delegate_->AutoLaunchCanceled();
}
SearchResultView* SearchResultListView::GetResultViewAt(int index) {
DCHECK(index >= 0 && index < results_container_->child_count());
return static_cast<SearchResultView*>(results_container_->child_at(index));
}
void SearchResultListView::ListItemsRemoved(size_t start, size_t count) {
size_t last = std::min(
start + count, static_cast<size_t>(results_container_->child_count()));
for (size_t i = start; i < last; ++i)
GetResultViewAt(i)->ClearResultNoRepaint();
SearchResultContainerView::ListItemsRemoved(start, count);
}
void SearchResultListView::OnContainerSelected(bool from_bottom) {
if (num_results() == 0)
return;
SetSelectedIndex(from_bottom ? num_results() - 1 : 0);
}
int SearchResultListView::Update() {
std::vector<SearchResult*> display_results =
AppListModel::FilterSearchResultsByDisplayType(
results(),
SearchResult::DISPLAY_LIST,
results_container_->child_count());
for (size_t i = 0; i < static_cast<size_t>(results_container_->child_count());
++i) {
SearchResultView* result_view = GetResultViewAt(i);
if (i < display_results.size()) {
result_view->SetResult(display_results[i]);
result_view->SetVisible(true);
} else {
result_view->SetResult(NULL);
result_view->SetVisible(false);
}
}
UpdateAutoLaunchState();
return display_results.size();
}
void SearchResultListView::UpdateSelectedIndex(int old_selected,
int new_selected) {
if (old_selected >= 0) {
SearchResultView* selected_view = GetResultViewAt(old_selected);
selected_view->ClearSelectedAction();
selected_view->SchedulePaint();
}
if (new_selected >= 0) {
SearchResultView* selected_view = GetResultViewAt(new_selected);
selected_view->ClearSelectedAction();
selected_view->SchedulePaint();
selected_view->NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
}
}
void SearchResultListView::ForceAutoLaunchForTest() {
if (auto_launch_animation_)
AnimationEnded(auto_launch_animation_.get());
}
void SearchResultListView::Layout() {
results_container_->SetBoundsRect(GetLocalBounds());
}
gfx::Size SearchResultListView::GetPreferredSize() const {
return results_container_->GetPreferredSize();
}
int SearchResultListView::GetHeightForWidth(int w) const {
return results_container_->GetHeightForWidth(w);
}
void SearchResultListView::VisibilityChanged(views::View* starting_from,
bool is_visible) {
if (is_visible)
UpdateAutoLaunchState();
else
CancelAutoLaunchTimeout();
}
void SearchResultListView::AnimationEnded(const gfx::Animation* animation) {
DCHECK_EQ(auto_launch_animation_.get(), animation);
view_delegate_->OpenSearchResult(results()->GetItemAt(0), true, ui::EF_NONE);
// The auto-launch has to be canceled explicitly. Think that one of searcher
// is extremely slow. Sometimes the events would happen in the following
// order:
// 1. The search results arrive, auto-launch is dispatched
// 2. Timed out and auto-launch the first search result
// 3. Then another searcher adds search results more
// At the step 3, we shouldn't dispatch the auto-launch again.
CancelAutoLaunchTimeout();
}
void SearchResultListView::AnimationProgressed(
const gfx::Animation* animation) {
DCHECK_EQ(auto_launch_animation_.get(), animation);
int indicator_width = auto_launch_animation_->CurrentValueBetween(0, width());
auto_launch_indicator_->SetBounds(
0, 0, indicator_width, kTimeoutIndicatorHeight);
}
void SearchResultListView::SearchResultActivated(SearchResultView* view,
int event_flags) {
if (view_delegate_ && view->result())
view_delegate_->OpenSearchResult(view->result(), false, event_flags);
}
void SearchResultListView::SearchResultActionActivated(SearchResultView* view,
size_t action_index,
int event_flags) {
if (view_delegate_ && view->result()) {
view_delegate_->InvokeSearchResultAction(
view->result(), action_index, event_flags);
}
}
void SearchResultListView::OnSearchResultInstalled(SearchResultView* view) {
if (delegate_ && view->result())
delegate_->OnResultInstalled(view->result());
}
void SearchResultListView::OnSearchResultUninstalled(SearchResultView* view) {
if (delegate_ && view->result())
delegate_->OnResultUninstalled(view->result());
}
} // namespace app_list
<commit_msg>Allow 6 list results in the experimental app list.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/app_list/views/search_result_list_view.h"
#include <algorithm>
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/app_list_view_delegate.h"
#include "ui/app_list/search_result.h"
#include "ui/app_list/views/search_result_list_view_delegate.h"
#include "ui/app_list/views/search_result_view.h"
#include "ui/events/event.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/views/background.h"
#include "ui/views/layout/box_layout.h"
namespace {
const int kMaxResults = 6;
const int kTimeoutIndicatorHeight = 2;
const int kTimeoutFramerate = 60;
const SkColor kTimeoutIndicatorColor = SkColorSetRGB(30, 144, 255);
} // namespace
namespace app_list {
SearchResultListView::SearchResultListView(
SearchResultListViewDelegate* delegate,
AppListViewDelegate* view_delegate)
: delegate_(delegate),
view_delegate_(view_delegate),
results_container_(new views::View),
auto_launch_indicator_(new views::View) {
results_container_->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0));
for (int i = 0; i < kMaxResults; ++i)
results_container_->AddChildView(new SearchResultView(this));
AddChildView(results_container_);
auto_launch_indicator_->set_background(
views::Background::CreateSolidBackground(kTimeoutIndicatorColor));
auto_launch_indicator_->SetVisible(false);
AddChildView(auto_launch_indicator_);
}
SearchResultListView::~SearchResultListView() {
}
bool SearchResultListView::IsResultViewSelected(
const SearchResultView* result_view) const {
if (selected_index() < 0)
return false;
return static_cast<const SearchResultView*>(
results_container_->child_at(selected_index())) == result_view;
}
void SearchResultListView::UpdateAutoLaunchState() {
SetAutoLaunchTimeout(view_delegate_->GetAutoLaunchTimeout());
}
bool SearchResultListView::OnKeyPressed(const ui::KeyEvent& event) {
if (selected_index() >= 0 &&
results_container_->child_at(selected_index())->OnKeyPressed(event)) {
return true;
}
int selection_index = -1;
switch (event.key_code()) {
case ui::VKEY_TAB:
if (event.IsShiftDown())
selection_index = selected_index() - 1;
else
selection_index = selected_index() + 1;
break;
case ui::VKEY_UP:
selection_index = selected_index() - 1;
break;
case ui::VKEY_DOWN:
selection_index = selected_index() + 1;
break;
default:
break;
}
if (IsValidSelectionIndex(selection_index)) {
SetSelectedIndex(selection_index);
if (auto_launch_animation_)
CancelAutoLaunchTimeout();
return true;
}
return false;
}
void SearchResultListView::SetAutoLaunchTimeout(
const base::TimeDelta& timeout) {
if (timeout > base::TimeDelta()) {
auto_launch_indicator_->SetVisible(true);
auto_launch_indicator_->SetBounds(0, 0, 0, kTimeoutIndicatorHeight);
auto_launch_animation_.reset(new gfx::LinearAnimation(
timeout.InMilliseconds(), kTimeoutFramerate, this));
auto_launch_animation_->Start();
} else {
auto_launch_indicator_->SetVisible(false);
auto_launch_animation_.reset();
}
}
void SearchResultListView::CancelAutoLaunchTimeout() {
SetAutoLaunchTimeout(base::TimeDelta());
view_delegate_->AutoLaunchCanceled();
}
SearchResultView* SearchResultListView::GetResultViewAt(int index) {
DCHECK(index >= 0 && index < results_container_->child_count());
return static_cast<SearchResultView*>(results_container_->child_at(index));
}
void SearchResultListView::ListItemsRemoved(size_t start, size_t count) {
size_t last = std::min(
start + count, static_cast<size_t>(results_container_->child_count()));
for (size_t i = start; i < last; ++i)
GetResultViewAt(i)->ClearResultNoRepaint();
SearchResultContainerView::ListItemsRemoved(start, count);
}
void SearchResultListView::OnContainerSelected(bool from_bottom) {
if (num_results() == 0)
return;
SetSelectedIndex(from_bottom ? num_results() - 1 : 0);
}
int SearchResultListView::Update() {
std::vector<SearchResult*> display_results =
AppListModel::FilterSearchResultsByDisplayType(
results(),
SearchResult::DISPLAY_LIST,
results_container_->child_count());
for (size_t i = 0; i < static_cast<size_t>(results_container_->child_count());
++i) {
SearchResultView* result_view = GetResultViewAt(i);
if (i < display_results.size()) {
result_view->SetResult(display_results[i]);
result_view->SetVisible(true);
} else {
result_view->SetResult(NULL);
result_view->SetVisible(false);
}
}
UpdateAutoLaunchState();
return display_results.size();
}
void SearchResultListView::UpdateSelectedIndex(int old_selected,
int new_selected) {
if (old_selected >= 0) {
SearchResultView* selected_view = GetResultViewAt(old_selected);
selected_view->ClearSelectedAction();
selected_view->SchedulePaint();
}
if (new_selected >= 0) {
SearchResultView* selected_view = GetResultViewAt(new_selected);
selected_view->ClearSelectedAction();
selected_view->SchedulePaint();
selected_view->NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
}
}
void SearchResultListView::ForceAutoLaunchForTest() {
if (auto_launch_animation_)
AnimationEnded(auto_launch_animation_.get());
}
void SearchResultListView::Layout() {
results_container_->SetBoundsRect(GetLocalBounds());
}
gfx::Size SearchResultListView::GetPreferredSize() const {
return results_container_->GetPreferredSize();
}
int SearchResultListView::GetHeightForWidth(int w) const {
return results_container_->GetHeightForWidth(w);
}
void SearchResultListView::VisibilityChanged(views::View* starting_from,
bool is_visible) {
if (is_visible)
UpdateAutoLaunchState();
else
CancelAutoLaunchTimeout();
}
void SearchResultListView::AnimationEnded(const gfx::Animation* animation) {
DCHECK_EQ(auto_launch_animation_.get(), animation);
view_delegate_->OpenSearchResult(results()->GetItemAt(0), true, ui::EF_NONE);
// The auto-launch has to be canceled explicitly. Think that one of searcher
// is extremely slow. Sometimes the events would happen in the following
// order:
// 1. The search results arrive, auto-launch is dispatched
// 2. Timed out and auto-launch the first search result
// 3. Then another searcher adds search results more
// At the step 3, we shouldn't dispatch the auto-launch again.
CancelAutoLaunchTimeout();
}
void SearchResultListView::AnimationProgressed(
const gfx::Animation* animation) {
DCHECK_EQ(auto_launch_animation_.get(), animation);
int indicator_width = auto_launch_animation_->CurrentValueBetween(0, width());
auto_launch_indicator_->SetBounds(
0, 0, indicator_width, kTimeoutIndicatorHeight);
}
void SearchResultListView::SearchResultActivated(SearchResultView* view,
int event_flags) {
if (view_delegate_ && view->result())
view_delegate_->OpenSearchResult(view->result(), false, event_flags);
}
void SearchResultListView::SearchResultActionActivated(SearchResultView* view,
size_t action_index,
int event_flags) {
if (view_delegate_ && view->result()) {
view_delegate_->InvokeSearchResultAction(
view->result(), action_index, event_flags);
}
}
void SearchResultListView::OnSearchResultInstalled(SearchResultView* view) {
if (delegate_ && view->result())
delegate_->OnResultInstalled(view->result());
}
void SearchResultListView::OnSearchResultUninstalled(SearchResultView* view) {
if (delegate_ && view->result())
delegate_->OnResultUninstalled(view->result());
}
} // namespace app_list
<|endoftext|> |
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvbonjourregistrar.h"
#ifdef HAVE_BONJOUR
#include "../vvdebugmsg.h"
#include "../vvsocket.h"
#include <iostream>
#include <sstream>
vvBonjourRegistrar::vvBonjourRegistrar()
: _serviceRef(NULL)
{
}
vvBonjourRegistrar::~vvBonjourRegistrar()
{
if(_serviceRef)
unregisterService();
}
DNSServiceErrorType vvBonjourRegistrar::registerService(const vvBonjourEntry& entry, const ushort port)
{
vvDebugMsg::msg(3, "vvBonjourRegistrar::registerService() Enter");
DNSServiceErrorType error;
error = DNSServiceRegister(&_serviceRef,
0, // no flags
0, // all network interfaces
entry.getServiceName().c_str(),
entry.getRegisteredType().c_str(),
entry.getReplyDomain().c_str(),
NULL, // use default host name
htons(port), // port number
0, // length of TXT record
NULL, // no TXT record
RegisterCallBack, // call back function
this); // no context
if (error == kDNSServiceErr_NoError)
{
_eventLoop = new vvBonjourEventLoop(_serviceRef);
_eventLoop->run(true, -1.0);
while(!_eventLoop->_noMoreFlags)
{
sleep(1);
//waiting...
}
}
else
{
vvDebugMsg::msg(2, "vvBonjourRegistrar::registerService(): DNSServiceResolve failed with error code ", error);
}
return error;
}
void vvBonjourRegistrar::unregisterService()
{
if(!_serviceRef)
{
vvDebugMsg::msg(2, "vvBonjourRegistrar::unregisterService() no service registered");
return;
}
DNSServiceRefDeallocate(_serviceRef);
_serviceRef = NULL;
if(_eventLoop)
{
delete _eventLoop;
_eventLoop = NULL;
}
}
void vvBonjourRegistrar::RegisterCallBack(DNSServiceRef service,
DNSServiceFlags flags,
DNSServiceErrorType errorCode,
const char * name,
const char * type,
const char * domain,
void * context)
{
vvDebugMsg::msg(3, "vvBonjourRegistrar::RegisterCallBack() Enter");
(void)service;
(void)flags;
vvBonjourRegistrar* instance = reinterpret_cast<vvBonjourRegistrar*>(context);
if (errorCode != kDNSServiceErr_NoError)
{
instance->_registeredService = vvBonjourEntry(name, type, domain);
vvDebugMsg::msg(3, "vvBonjourRegistrar::RegisterCallBack() error");
}
else
{
if(vvDebugMsg::getDebugLevel() >= 0)
{
std::ostringstream errmsg;
errmsg << "vvBonjourRegistrar::RegisterCallBack() Entry registered: " << name << "." << type << domain;
vvDebugMsg::msg(0, errmsg.str().c_str());
}
}
if (!(flags & kDNSServiceFlagsMoreComing))
{
// registering done
instance->_eventLoop->_noMoreFlags = true;
}
}
#endif
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<commit_msg>bugfix bonjourregistrar<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "vvbonjourregistrar.h"
#ifdef HAVE_BONJOUR
#include "../vvdebugmsg.h"
#include "../vvsocket.h"
#include <iostream>
#include <sstream>
vvBonjourRegistrar::vvBonjourRegistrar()
: _serviceRef(NULL)
{
}
vvBonjourRegistrar::~vvBonjourRegistrar()
{
if(_serviceRef)
unregisterService();
}
DNSServiceErrorType vvBonjourRegistrar::registerService(const vvBonjourEntry& entry, const ushort port)
{
vvDebugMsg::msg(3, "vvBonjourRegistrar::registerService() Enter");
DNSServiceErrorType error;
error = DNSServiceRegister(&_serviceRef,
0, // no flags
0, // all network interfaces
entry.getServiceName().c_str(),
entry.getRegisteredType().c_str(),
entry.getReplyDomain().c_str(),
NULL, // use default host name
htons(port), // port number
0, // length of TXT record
NULL, // no TXT record
RegisterCallBack, // call back function
this); // no context
if (error == kDNSServiceErr_NoError)
{
_eventLoop = new vvBonjourEventLoop(_serviceRef);
_eventLoop->run(true, -1.0);
while(!_eventLoop->_noMoreFlags)
{
sleep(1);
//waiting...
}
}
else
{
vvDebugMsg::msg(2, "vvBonjourRegistrar::registerService(): DNSServiceResolve failed with error code ", error);
}
return error;
}
void vvBonjourRegistrar::unregisterService()
{
if(!_serviceRef)
{
vvDebugMsg::msg(2, "vvBonjourRegistrar::unregisterService() no service registered");
return;
}
if(_eventLoop)
{
_eventLoop->stop();
delete _eventLoop;
_eventLoop = NULL;
}
DNSServiceRefDeallocate(_serviceRef);
_serviceRef = NULL;
}
void vvBonjourRegistrar::RegisterCallBack(DNSServiceRef service,
DNSServiceFlags flags,
DNSServiceErrorType errorCode,
const char * name,
const char * type,
const char * domain,
void * context)
{
vvDebugMsg::msg(3, "vvBonjourRegistrar::RegisterCallBack() Enter");
(void)service;
(void)flags;
vvBonjourRegistrar* instance = reinterpret_cast<vvBonjourRegistrar*>(context);
if (errorCode != kDNSServiceErr_NoError)
{
instance->_registeredService = vvBonjourEntry(name, type, domain);
vvDebugMsg::msg(3, "vvBonjourRegistrar::RegisterCallBack() error");
}
else
{
if(vvDebugMsg::getDebugLevel() >= 0)
{
std::ostringstream errmsg;
errmsg << "vvBonjourRegistrar::RegisterCallBack() Entry registered: " << name << "." << type << domain;
vvDebugMsg::msg(0, errmsg.str().c_str());
}
}
if (!(flags & kDNSServiceFlagsMoreComing))
{
// registering done
instance->_eventLoop->_noMoreFlags = true;
instance->_eventLoop->stop();
}
}
#endif
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "log.h"
#include <string>
#include <ctime>
#include <cstring>
#include <uv.h>
namespace game
{
Scoped_Log_Init::Scoped_Log_Init() noexcept
{
init_log();
}
Scoped_Log_Init::~Scoped_Log_Init() noexcept
{
uninit_log();
}
uv_loop_t* loop_ = nullptr;
Log_Severity level_ = Log_Severity::Info;
void init_log() noexcept
{
loop_ = new uv_loop_t;
uv_loop_init(loop_);
}
void uninit_log() noexcept
{
uv_loop_close(loop_);
delete loop_;
}
void flush_log() noexcept
{
uv_run(loop_, UV_RUN_NOWAIT);
}
void flush_log_full() noexcept
{
uv_run(loop_, UV_RUN_DEFAULT);
}
std::string format_time(const std::string& format)
{
// Stringify current time.
std::string time;
time.resize(25);
std::time_t t = std::time(NULL);
std::size_t count = std::strftime(&time[0], time.size(),
format.c_str(), std::localtime(&t));
if(count == 0)
{
time = "badtime";
}
time.resize(count);
return time;
}
struct write_req_t
{
uv_fs_t req;
uv_buf_t buf;
};
void after_log(uv_fs_t* fs_req)
{
write_req_t* req = (write_req_t*) fs_req;
// Uninitialize actual uv request.
uv_fs_req_cleanup(&req->req);
// Deallocate buffer.
delete[] req->buf.base;
// Deallocate request subclass.
delete req;
}
void set_log_level(Log_Severity level) noexcept
{
level_ = level;
}
void log(std::string severity, std::string msg) noexcept
{
// Create the final message.
std::string time = format_time("%F|%T");
std::string final_msg = "(" + time + "): " + severity + ": " + msg + "\n";
// Copy to a buffer libuv can use.
char* msg_data = new char[final_msg.size()];
std::memcpy(msg_data, final_msg.data(), final_msg.size());
// Make the request.
write_req_t* req = new write_req_t;
req->buf = uv_buf_init(msg_data, final_msg.size());
uv_fs_write(loop_, &req->req, 1, &req->buf, 1, -1, after_log);
}
void log(Log_Severity severity, std::string msg) noexcept
{
// This could be implemented differently, for instance with a
// enum-to-string function + calling the log(string,string) function
// directly.
switch(severity)
{
case Log_Severity::Error:
log_e(msg);
break;
case Log_Severity::Warning:
log_w(msg);
break;
case Log_Severity::Info:
log_i(msg);
break;
case Log_Severity::Debug:
log_d(msg);
}
}
void log_e(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Error))
log("error", msg);
}
void log_w(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Warning))
log("warning", msg);
}
void log_i(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Info))
log("info", msg);
}
void log_d(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Debug))
log("debug", msg);
}
}
<commit_msg>The logging uv_loop is now thread-local.<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "log.h"
#include <string>
#include <ctime>
#include <cstring>
#include <uv.h>
namespace game
{
Scoped_Log_Init::Scoped_Log_Init() noexcept
{
init_log();
}
Scoped_Log_Init::~Scoped_Log_Init() noexcept
{
uninit_log();
}
thread_local uv_loop_t* loop_ = nullptr;
Log_Severity level_ = Log_Severity::Info;
void init_log() noexcept
{
if(loop_) return;
loop_ = new uv_loop_t;
uv_loop_init(loop_);
}
void uninit_log() noexcept
{
if(!loop_) return;
uv_loop_close(loop_);
delete loop_;
}
void flush_log() noexcept
{
uv_run(loop_, UV_RUN_NOWAIT);
}
void flush_log_full() noexcept
{
uv_run(loop_, UV_RUN_DEFAULT);
}
std::string format_time(const std::string& format)
{
// Stringify current time.
std::string time;
time.resize(25);
std::time_t t = std::time(NULL);
std::size_t count = std::strftime(&time[0], time.size(),
format.c_str(), std::localtime(&t));
if(count == 0)
{
time = "badtime";
}
time.resize(count);
return time;
}
struct write_req_t
{
uv_fs_t req;
uv_buf_t buf;
};
void after_log(uv_fs_t* fs_req)
{
write_req_t* req = (write_req_t*) fs_req;
// Uninitialize actual uv request.
uv_fs_req_cleanup(&req->req);
// Deallocate buffer.
delete[] req->buf.base;
// Deallocate request subclass.
delete req;
}
void set_log_level(Log_Severity level) noexcept
{
level_ = level;
}
void log(std::string severity, std::string msg) noexcept
{
// Create the final message.
std::string time = format_time("%F|%T");
std::string final_msg = "(" + time + "): " + severity + ": " + msg + "\n";
// Copy to a buffer libuv can use.
char* msg_data = new char[final_msg.size()];
std::memcpy(msg_data, final_msg.data(), final_msg.size());
// Make the request.
write_req_t* req = new write_req_t;
req->buf = uv_buf_init(msg_data, final_msg.size());
uv_fs_write(loop_, &req->req, 1, &req->buf, 1, -1, after_log);
}
void log(Log_Severity severity, std::string msg) noexcept
{
// This could be implemented differently, for instance with a
// enum-to-string function + calling the log(string,string) function
// directly.
switch(severity)
{
case Log_Severity::Error:
log_e(msg);
break;
case Log_Severity::Warning:
log_w(msg);
break;
case Log_Severity::Info:
log_i(msg);
break;
case Log_Severity::Debug:
log_d(msg);
}
}
void log_e(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Error))
log("error", msg);
}
void log_w(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Warning))
log("warning", msg);
}
void log_i(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Info))
log("info", msg);
}
void log_d(std::string msg) noexcept
{
if(static_cast<int>(level_) <= static_cast<int>(Log_Severity::Debug))
log("debug", msg);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "WebExportWidget.h"
#include <pqActiveObjects.h>
#include <pqSettings.h>
#include <QButtonGroup>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QFileDialog>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QMap>
#include <QPushButton>
#include <QSpinBox>
#include <QString>
#include <QToolButton>
#include <QVBoxLayout>
#include <QVariant>
namespace tomviz {
WebExportWidget::WebExportWidget(QWidget* p) : QDialog(p)
{
QVBoxLayout* v = new QVBoxLayout(this);
this->setMinimumWidth(500);
this->setMinimumHeight(400);
this->setWindowTitle("Web export data");
// Output type
QLabel* outputTypelabel = new QLabel("Output type:");
QHBoxLayout* typeGroup = new QHBoxLayout;
this->m_exportType = new QComboBox;
this->m_exportType->addItem("Images: Current scene");
this->m_exportType->addItem("Images: Volume exploration");
this->m_exportType->addItem("Images: Contour exploration");
this->m_exportType->addItem("Geometry: Current scene contour(s)");
this->m_exportType->addItem("Geometry: Contour exploration");
this->m_exportType->addItem("Geometry: Volume");
// this->exportType->addItem("Composite surfaces"); // specularColor segfault
this->m_exportType->setCurrentIndex(0);
typeGroup->addWidget(outputTypelabel);
typeGroup->addWidget(this->m_exportType, 1);
v->addLayout(typeGroup);
// Image size
QLabel* imageSizeGroupLabel = new QLabel("View size:");
QLabel* imageWidthLabel = new QLabel("Width");
this->m_imageWidth = new QSpinBox();
this->m_imageWidth->setRange(50, 2048);
this->m_imageWidth->setSingleStep(1);
this->m_imageWidth->setValue(500);
this->m_imageWidth->setMinimumWidth(100);
QLabel* imageHeightLabel = new QLabel("Height");
this->m_imageHeight = new QSpinBox();
this->m_imageHeight->setRange(50, 2048);
this->m_imageHeight->setSingleStep(1);
this->m_imageHeight->setValue(500);
this->m_imageHeight->setMinimumWidth(100);
QHBoxLayout* imageSizeGroupLayout = new QHBoxLayout;
imageSizeGroupLayout->addWidget(imageSizeGroupLabel);
imageSizeGroupLayout->addStretch();
imageSizeGroupLayout->addWidget(imageWidthLabel);
imageSizeGroupLayout->addWidget(m_imageWidth);
imageSizeGroupLayout->addSpacing(30);
imageSizeGroupLayout->addWidget(imageHeightLabel);
imageSizeGroupLayout->addWidget(m_imageHeight);
this->m_imageSizeGroup = new QWidget();
this->m_imageSizeGroup->setLayout(imageSizeGroupLayout);
v->addWidget(this->m_imageSizeGroup);
// Camera settings
QLabel* cameraGrouplabel = new QLabel("Camera tilts:");
QLabel* phiLabel = new QLabel("Phi");
this->m_nbPhi = new QSpinBox();
this->m_nbPhi->setRange(4, 72);
this->m_nbPhi->setSingleStep(4);
this->m_nbPhi->setValue(36);
this->m_nbPhi->setMinimumWidth(100);
QLabel* thetaLabel = new QLabel("Theta");
this->m_nbTheta = new QSpinBox();
this->m_nbTheta->setRange(1, 20);
this->m_nbTheta->setSingleStep(1);
this->m_nbTheta->setValue(5);
this->m_nbTheta->setMinimumWidth(100);
QHBoxLayout* cameraGroupLayout = new QHBoxLayout;
cameraGroupLayout->addWidget(cameraGrouplabel);
cameraGroupLayout->addStretch();
cameraGroupLayout->addWidget(phiLabel);
cameraGroupLayout->addWidget(m_nbPhi);
cameraGroupLayout->addSpacing(30);
cameraGroupLayout->addWidget(thetaLabel);
cameraGroupLayout->addWidget(m_nbTheta);
this->m_cameraGroup = new QWidget();
this->m_cameraGroup->setLayout(cameraGroupLayout);
v->addWidget(this->m_cameraGroup);
// Volume exploration
QLabel* opacityLabel = new QLabel("Max opacity");
this->m_maxOpacity = new QSpinBox();
this->m_maxOpacity->setRange(10, 100);
this->m_maxOpacity->setSingleStep(10);
this->m_maxOpacity->setValue(50);
this->m_maxOpacity->setMinimumWidth(100);
QLabel* spanLabel = new QLabel("Tent width");
this->m_spanValue = new QSpinBox();
this->m_spanValue->setRange(1, 200);
this->m_spanValue->setSingleStep(1);
this->m_spanValue->setValue(10);
this->m_spanValue->setMinimumWidth(100);
QHBoxLayout* volumeExplorationGroupLayout = new QHBoxLayout;
volumeExplorationGroupLayout->addWidget(opacityLabel);
volumeExplorationGroupLayout->addWidget(m_maxOpacity);
cameraGroupLayout->addStretch();
volumeExplorationGroupLayout->addWidget(spanLabel);
volumeExplorationGroupLayout->addWidget(m_spanValue);
this->m_volumeExplorationGroup = new QWidget();
this->m_volumeExplorationGroup->setLayout(volumeExplorationGroupLayout);
v->addWidget(this->m_volumeExplorationGroup);
// Multi-value exploration
QLabel* multiValueLabel = new QLabel("Values:");
this->m_multiValue = new QLineEdit("25, 50, 75, 100, 125, 150, 175, 200, 225");
QHBoxLayout* multiValueGroupLayout = new QHBoxLayout;
multiValueGroupLayout->addWidget(multiValueLabel);
multiValueGroupLayout->addWidget(this->m_multiValue);
this->m_valuesGroup = new QWidget();
this->m_valuesGroup->setLayout(multiValueGroupLayout);
v->addWidget(this->m_valuesGroup);
// Volume down sampling
QLabel* scaleLabel = new QLabel("Sampling stride");
this->m_scale = new QSpinBox();
this->m_scale->setRange(1, 5);
this->m_scale->setSingleStep(1);
this->m_scale->setValue(1);
this->m_scale->setMinimumWidth(100);
QHBoxLayout* scaleGroupLayout = new QHBoxLayout;
scaleGroupLayout->addWidget(scaleLabel);
scaleGroupLayout->addWidget(this->m_scale);
this->m_volumeResampleGroup = new QWidget();
this->m_volumeResampleGroup->setLayout(scaleGroupLayout);
v->addWidget(this->m_volumeResampleGroup);
v->addStretch();
// Action buttons
QHBoxLayout* actionGroup = new QHBoxLayout;
this->m_keepData = new QCheckBox("Generate data for viewer");
this->m_exportButton = new QPushButton("Export");
this->m_cancelButton = new QPushButton("Cancel");
actionGroup->addWidget(this->m_keepData);
actionGroup->addStretch();
actionGroup->addWidget(this->m_exportButton);
actionGroup->addSpacing(20);
actionGroup->addWidget(this->m_cancelButton);
v->addLayout(actionGroup);
// UI binding
this->connect(this->m_exportButton, SIGNAL(pressed()), this, SLOT(onExport()));
this->connect(this->m_cancelButton, SIGNAL(pressed()), this, SLOT(onCancel()));
this->connect(this->m_exportType, SIGNAL(currentIndexChanged(int)), this,
SLOT(onTypeChange(int)));
// Initialize visibility
this->onTypeChange(0);
this->restoreSettings();
connect(this, &QDialog::finished, this,
&WebExportWidget::writeWidgetSettings);
}
void WebExportWidget::onTypeChange(int index)
{
pqView* view = pqActiveObjects::instance().activeView();
QSize size = view->getSize();
this->m_imageWidth->setMaximum(size.width());
this->m_imageHeight->setMaximum(size.height());
this->m_imageSizeGroup->setVisible(index < 3);
this->m_cameraGroup->setVisible(index < 3);
this->m_volumeExplorationGroup->setVisible(index == 1);
this->m_valuesGroup->setVisible(index == 1 || index == 2 || index == 4);
this->m_volumeResampleGroup->setVisible(index == 5);
}
void WebExportWidget::onExport()
{
this->accept();
}
void WebExportWidget::onCancel()
{
this->reject();
}
QMap<QString, QVariant> WebExportWidget::getKeywordArguments()
{
this->m_kwargs["executionPath"] =
QVariant(QCoreApplication::applicationDirPath());
this->m_kwargs["exportType"] = QVariant(this->m_exportType->currentIndex());
this->m_kwargs["imageWidth"] = QVariant(this->m_imageWidth->value());
this->m_kwargs["imageHeight"] = QVariant(this->m_imageHeight->value());
this->m_kwargs["nbPhi"] = QVariant(this->m_nbPhi->value());
this->m_kwargs["nbTheta"] = QVariant(this->m_nbTheta->value());
this->m_kwargs["keepData"] = QVariant(this->m_keepData->checkState());
this->m_kwargs["maxOpacity"] = QVariant(this->m_maxOpacity->value());
this->m_kwargs["tentWidth"] = QVariant(this->m_spanValue->value());
this->m_kwargs["volumeScale"] = QVariant(this->m_scale->value());
this->m_kwargs["multiValue"] = QVariant(this->m_multiValue->text());
return this->m_kwargs;
}
QMap<QString, QVariant> WebExportWidget::readSettings()
{
QMap<QString, QVariant> settingsMap;
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("web");
foreach (QString key, settings->childKeys()) {
settingsMap[key] = settings->value(key);
}
settings->endGroup();
return settingsMap;
}
void WebExportWidget::writeSettings(const QMap<QString, QVariant>& settingsMap)
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("web");
for (QMap<QString, QVariant>::const_iterator iter = settingsMap.begin();
iter != settingsMap.end(); ++iter) {
settings->setValue(iter.key(), iter.value());
}
settings->endGroup();
}
void WebExportWidget::writeWidgetSettings()
{
QVariantMap settingsMap;
settingsMap["phi"] = this->m_nbPhi->value();
settingsMap["theta"] = this->m_nbTheta->value();
settingsMap["imageWidth"] = this->m_imageWidth->value();
settingsMap["imageHeight"] = this->m_imageHeight->value();
settingsMap["generateDataViewer"] = this->m_keepData->isChecked();
settingsMap["exportType"] = this->m_exportType->currentIndex();
settingsMap["maxOpacity"] = this->m_maxOpacity->value();
settingsMap["tentWidth"] = this->m_spanValue->value();
settingsMap["volumeScale"] = this->m_scale->value();
settingsMap["multiValue"] = this->m_multiValue->text();
this->writeSettings(settingsMap);
}
void WebExportWidget::restoreSettings()
{
QVariantMap settingsMap = this->readSettings();
if (settingsMap.contains("phi")) {
this->m_nbPhi->setValue(settingsMap.value("phi").toInt());
}
if (settingsMap.contains("theta")) {
this->m_nbTheta->setValue(settingsMap.value("theta").toInt());
}
if (settingsMap.contains("imageWidth")) {
this->m_imageWidth->setValue(settingsMap.value("imageWidth").toInt());
}
if (settingsMap.contains("imageHeight")) {
this->m_imageHeight->setValue(settingsMap.value("imageHeight").toInt());
}
if (settingsMap.contains("generateDataViewer")) {
this->m_keepData->setChecked(
settingsMap.value("generateDataViewer").toBool());
}
if (settingsMap.contains("exportType")) {
this->m_exportType->setCurrentIndex(
settingsMap.value("exportType").toInt());
}
if (settingsMap.contains("maxOpacity")) {
this->m_maxOpacity->setValue(settingsMap.value("maxOpacity").toInt());
}
if (settingsMap.contains("tentWidth")) {
this->m_spanValue->setValue(settingsMap.value("tentWidth").toInt());
}
if (settingsMap.contains("volumeScale")) {
this->m_scale->setValue(settingsMap.value("volumeScale").toInt());
}
if (settingsMap.contains("multiValue")) {
this->m_multiValue->setText(settingsMap.value("multiValue").toString());
}
}
}
<commit_msg>Fix clang-format issues<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "WebExportWidget.h"
#include <pqActiveObjects.h>
#include <pqSettings.h>
#include <QButtonGroup>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QFileDialog>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QMap>
#include <QPushButton>
#include <QSpinBox>
#include <QString>
#include <QToolButton>
#include <QVBoxLayout>
#include <QVariant>
namespace tomviz {
WebExportWidget::WebExportWidget(QWidget* p) : QDialog(p)
{
QVBoxLayout* v = new QVBoxLayout(this);
this->setMinimumWidth(500);
this->setMinimumHeight(400);
this->setWindowTitle("Web export data");
// Output type
QLabel* outputTypelabel = new QLabel("Output type:");
QHBoxLayout* typeGroup = new QHBoxLayout;
this->m_exportType = new QComboBox;
this->m_exportType->addItem("Images: Current scene");
this->m_exportType->addItem("Images: Volume exploration");
this->m_exportType->addItem("Images: Contour exploration");
this->m_exportType->addItem("Geometry: Current scene contour(s)");
this->m_exportType->addItem("Geometry: Contour exploration");
this->m_exportType->addItem("Geometry: Volume");
// this->exportType->addItem("Composite surfaces"); // specularColor segfault
this->m_exportType->setCurrentIndex(0);
typeGroup->addWidget(outputTypelabel);
typeGroup->addWidget(this->m_exportType, 1);
v->addLayout(typeGroup);
// Image size
QLabel* imageSizeGroupLabel = new QLabel("View size:");
QLabel* imageWidthLabel = new QLabel("Width");
this->m_imageWidth = new QSpinBox();
this->m_imageWidth->setRange(50, 2048);
this->m_imageWidth->setSingleStep(1);
this->m_imageWidth->setValue(500);
this->m_imageWidth->setMinimumWidth(100);
QLabel* imageHeightLabel = new QLabel("Height");
this->m_imageHeight = new QSpinBox();
this->m_imageHeight->setRange(50, 2048);
this->m_imageHeight->setSingleStep(1);
this->m_imageHeight->setValue(500);
this->m_imageHeight->setMinimumWidth(100);
QHBoxLayout* imageSizeGroupLayout = new QHBoxLayout;
imageSizeGroupLayout->addWidget(imageSizeGroupLabel);
imageSizeGroupLayout->addStretch();
imageSizeGroupLayout->addWidget(imageWidthLabel);
imageSizeGroupLayout->addWidget(m_imageWidth);
imageSizeGroupLayout->addSpacing(30);
imageSizeGroupLayout->addWidget(imageHeightLabel);
imageSizeGroupLayout->addWidget(m_imageHeight);
this->m_imageSizeGroup = new QWidget();
this->m_imageSizeGroup->setLayout(imageSizeGroupLayout);
v->addWidget(this->m_imageSizeGroup);
// Camera settings
QLabel* cameraGrouplabel = new QLabel("Camera tilts:");
QLabel* phiLabel = new QLabel("Phi");
this->m_nbPhi = new QSpinBox();
this->m_nbPhi->setRange(4, 72);
this->m_nbPhi->setSingleStep(4);
this->m_nbPhi->setValue(36);
this->m_nbPhi->setMinimumWidth(100);
QLabel* thetaLabel = new QLabel("Theta");
this->m_nbTheta = new QSpinBox();
this->m_nbTheta->setRange(1, 20);
this->m_nbTheta->setSingleStep(1);
this->m_nbTheta->setValue(5);
this->m_nbTheta->setMinimumWidth(100);
QHBoxLayout* cameraGroupLayout = new QHBoxLayout;
cameraGroupLayout->addWidget(cameraGrouplabel);
cameraGroupLayout->addStretch();
cameraGroupLayout->addWidget(phiLabel);
cameraGroupLayout->addWidget(m_nbPhi);
cameraGroupLayout->addSpacing(30);
cameraGroupLayout->addWidget(thetaLabel);
cameraGroupLayout->addWidget(m_nbTheta);
this->m_cameraGroup = new QWidget();
this->m_cameraGroup->setLayout(cameraGroupLayout);
v->addWidget(this->m_cameraGroup);
// Volume exploration
QLabel* opacityLabel = new QLabel("Max opacity");
this->m_maxOpacity = new QSpinBox();
this->m_maxOpacity->setRange(10, 100);
this->m_maxOpacity->setSingleStep(10);
this->m_maxOpacity->setValue(50);
this->m_maxOpacity->setMinimumWidth(100);
QLabel* spanLabel = new QLabel("Tent width");
this->m_spanValue = new QSpinBox();
this->m_spanValue->setRange(1, 200);
this->m_spanValue->setSingleStep(1);
this->m_spanValue->setValue(10);
this->m_spanValue->setMinimumWidth(100);
QHBoxLayout* volumeExplorationGroupLayout = new QHBoxLayout;
volumeExplorationGroupLayout->addWidget(opacityLabel);
volumeExplorationGroupLayout->addWidget(m_maxOpacity);
cameraGroupLayout->addStretch();
volumeExplorationGroupLayout->addWidget(spanLabel);
volumeExplorationGroupLayout->addWidget(m_spanValue);
this->m_volumeExplorationGroup = new QWidget();
this->m_volumeExplorationGroup->setLayout(volumeExplorationGroupLayout);
v->addWidget(this->m_volumeExplorationGroup);
// Multi-value exploration
QLabel* multiValueLabel = new QLabel("Values:");
this->m_multiValue =
new QLineEdit("25, 50, 75, 100, 125, 150, 175, 200, 225");
QHBoxLayout* multiValueGroupLayout = new QHBoxLayout;
multiValueGroupLayout->addWidget(multiValueLabel);
multiValueGroupLayout->addWidget(this->m_multiValue);
this->m_valuesGroup = new QWidget();
this->m_valuesGroup->setLayout(multiValueGroupLayout);
v->addWidget(this->m_valuesGroup);
// Volume down sampling
QLabel* scaleLabel = new QLabel("Sampling stride");
this->m_scale = new QSpinBox();
this->m_scale->setRange(1, 5);
this->m_scale->setSingleStep(1);
this->m_scale->setValue(1);
this->m_scale->setMinimumWidth(100);
QHBoxLayout* scaleGroupLayout = new QHBoxLayout;
scaleGroupLayout->addWidget(scaleLabel);
scaleGroupLayout->addWidget(this->m_scale);
this->m_volumeResampleGroup = new QWidget();
this->m_volumeResampleGroup->setLayout(scaleGroupLayout);
v->addWidget(this->m_volumeResampleGroup);
v->addStretch();
// Action buttons
QHBoxLayout* actionGroup = new QHBoxLayout;
this->m_keepData = new QCheckBox("Generate data for viewer");
this->m_exportButton = new QPushButton("Export");
this->m_cancelButton = new QPushButton("Cancel");
actionGroup->addWidget(this->m_keepData);
actionGroup->addStretch();
actionGroup->addWidget(this->m_exportButton);
actionGroup->addSpacing(20);
actionGroup->addWidget(this->m_cancelButton);
v->addLayout(actionGroup);
// UI binding
this->connect(this->m_exportButton, SIGNAL(pressed()), this,
SLOT(onExport()));
this->connect(this->m_cancelButton, SIGNAL(pressed()), this,
SLOT(onCancel()));
this->connect(this->m_exportType, SIGNAL(currentIndexChanged(int)), this,
SLOT(onTypeChange(int)));
// Initialize visibility
this->onTypeChange(0);
this->restoreSettings();
connect(this, &QDialog::finished, this,
&WebExportWidget::writeWidgetSettings);
}
void WebExportWidget::onTypeChange(int index)
{
pqView* view = pqActiveObjects::instance().activeView();
QSize size = view->getSize();
this->m_imageWidth->setMaximum(size.width());
this->m_imageHeight->setMaximum(size.height());
this->m_imageSizeGroup->setVisible(index < 3);
this->m_cameraGroup->setVisible(index < 3);
this->m_volumeExplorationGroup->setVisible(index == 1);
this->m_valuesGroup->setVisible(index == 1 || index == 2 || index == 4);
this->m_volumeResampleGroup->setVisible(index == 5);
}
void WebExportWidget::onExport()
{
this->accept();
}
void WebExportWidget::onCancel()
{
this->reject();
}
QMap<QString, QVariant> WebExportWidget::getKeywordArguments()
{
this->m_kwargs["executionPath"] =
QVariant(QCoreApplication::applicationDirPath());
this->m_kwargs["exportType"] = QVariant(this->m_exportType->currentIndex());
this->m_kwargs["imageWidth"] = QVariant(this->m_imageWidth->value());
this->m_kwargs["imageHeight"] = QVariant(this->m_imageHeight->value());
this->m_kwargs["nbPhi"] = QVariant(this->m_nbPhi->value());
this->m_kwargs["nbTheta"] = QVariant(this->m_nbTheta->value());
this->m_kwargs["keepData"] = QVariant(this->m_keepData->checkState());
this->m_kwargs["maxOpacity"] = QVariant(this->m_maxOpacity->value());
this->m_kwargs["tentWidth"] = QVariant(this->m_spanValue->value());
this->m_kwargs["volumeScale"] = QVariant(this->m_scale->value());
this->m_kwargs["multiValue"] = QVariant(this->m_multiValue->text());
return this->m_kwargs;
}
QMap<QString, QVariant> WebExportWidget::readSettings()
{
QMap<QString, QVariant> settingsMap;
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("web");
foreach (QString key, settings->childKeys()) {
settingsMap[key] = settings->value(key);
}
settings->endGroup();
return settingsMap;
}
void WebExportWidget::writeSettings(const QMap<QString, QVariant>& settingsMap)
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("web");
for (QMap<QString, QVariant>::const_iterator iter = settingsMap.begin();
iter != settingsMap.end(); ++iter) {
settings->setValue(iter.key(), iter.value());
}
settings->endGroup();
}
void WebExportWidget::writeWidgetSettings()
{
QVariantMap settingsMap;
settingsMap["phi"] = this->m_nbPhi->value();
settingsMap["theta"] = this->m_nbTheta->value();
settingsMap["imageWidth"] = this->m_imageWidth->value();
settingsMap["imageHeight"] = this->m_imageHeight->value();
settingsMap["generateDataViewer"] = this->m_keepData->isChecked();
settingsMap["exportType"] = this->m_exportType->currentIndex();
settingsMap["maxOpacity"] = this->m_maxOpacity->value();
settingsMap["tentWidth"] = this->m_spanValue->value();
settingsMap["volumeScale"] = this->m_scale->value();
settingsMap["multiValue"] = this->m_multiValue->text();
this->writeSettings(settingsMap);
}
void WebExportWidget::restoreSettings()
{
QVariantMap settingsMap = this->readSettings();
if (settingsMap.contains("phi")) {
this->m_nbPhi->setValue(settingsMap.value("phi").toInt());
}
if (settingsMap.contains("theta")) {
this->m_nbTheta->setValue(settingsMap.value("theta").toInt());
}
if (settingsMap.contains("imageWidth")) {
this->m_imageWidth->setValue(settingsMap.value("imageWidth").toInt());
}
if (settingsMap.contains("imageHeight")) {
this->m_imageHeight->setValue(settingsMap.value("imageHeight").toInt());
}
if (settingsMap.contains("generateDataViewer")) {
this->m_keepData->setChecked(
settingsMap.value("generateDataViewer").toBool());
}
if (settingsMap.contains("exportType")) {
this->m_exportType->setCurrentIndex(
settingsMap.value("exportType").toInt());
}
if (settingsMap.contains("maxOpacity")) {
this->m_maxOpacity->setValue(settingsMap.value("maxOpacity").toInt());
}
if (settingsMap.contains("tentWidth")) {
this->m_spanValue->setValue(settingsMap.value("tentWidth").toInt());
}
if (settingsMap.contains("volumeScale")) {
this->m_scale->setValue(settingsMap.value("volumeScale").toInt());
}
if (settingsMap.contains("multiValue")) {
this->m_multiValue->setText(settingsMap.value("multiValue").toString());
}
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.